Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

614 linhas
26KB

  1. <%
  2. ' ApiDocumentsController: reference documents, chunks and lexical search (spec FR-006, FR-007, FR-009, FR-011, FR-016).
  3. ' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (chunker, FTS).
  4. '
  5. ' POST /api/v1/ingestion/jobs Ingest {"namespace_id","title","content","format":"markdown|text","source_uri"}
  6. ' GET /api/v1/jobs/:id Job job state
  7. ' GET /api/v1/documents/:id Document metadata (?include_content=true adds the text)
  8. ' GET /api/v1/chunks/:id Chunk one passage with its source locator
  9. ' POST /api/v1/search Search {"query","namespace_ids":[],"max_results","detail_level":"full|snippet"}
  10. '
  11. ' Ingestion is processed inside the request (no worker yet) but is recorded as a job. The same source_uri in a
  12. ' namespace is one document; re-ingesting changed text creates a new revision and only the current revision is
  13. ' searchable. Identical text is a no-op, so retries never publish duplicate chunks. The service never fetches the
  14. ' source_uri: it is only stored as an identifier (no SSRF surface).
  15. ' Permissions on the namespace: write (Ingest), read (everything else). Retrieved text is untrusted reference
  16. ' data; responses say so with "content_trust".
  17. Class ApiDocumentsController_Class
  18. Private m_errs
  19. Public Property Get useLayout()
  20. useLayout = False
  21. End Property
  22. Public Property Let useLayout(v)
  23. End Property
  24. Public Property Get Title()
  25. Title = "Documents API"
  26. End Property
  27. '---------------------------------------------------------------
  28. ' POST /api/v1/ingestion/jobs
  29. '---------------------------------------------------------------
  30. Public Sub Ingest()
  31. Dim body, input, idemKey, reqHash, nsId, title, content, fmt, sourceUri, norm, hash
  32. Dim rs, docId, curRev, revNo, jobId, ts, unchanged, k, resp, i, chunkId, isMd, statusCode, chunkTotal
  33. If Not Api_Authenticate() Then Exit Sub
  34. body = Api_ReadBody()
  35. If IsEmpty(body) Then Exit Sub
  36. Set input = JsonLite_Parse(body)
  37. idemKey = Api_Header("Idempotency-Key")
  38. If Len(idemKey) > 200 Then
  39. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  40. Exit Sub
  41. End If
  42. reqHash = Api_Sha256(body)
  43. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  44. m_errs = ""
  45. nsId = ReqString(input, "namespace_id", 64)
  46. title = ReqString(input, "title", 200)
  47. content = ReqText(input, "content", 262144)
  48. fmt = OptString(input, "format", 20)
  49. sourceUri = OptString(input, "source_uri", 500)
  50. If IsNull(fmt) Then fmt = "markdown"
  51. fmt = LCase(fmt)
  52. If fmt <> "markdown" And fmt <> "text" Then AddErr "format must be markdown or text."
  53. If Len(m_errs) > 0 Then
  54. Api_Invalid Split(m_errs, Chr(30))
  55. Exit Sub
  56. End If
  57. If Not Api_CanAccessNamespace(nsId, "write") Then
  58. Api_Audit "document.ingest", "namespace", nsId, "denied"
  59. Api_Error 404, "namespace_not_found", "Namespace not found."
  60. Exit Sub
  61. End If
  62. isMd = (fmt = "markdown")
  63. norm = Chunk_Normalize(content)
  64. hash = Api_Sha256(norm)
  65. ' Find an existing document: by source_uri when given, otherwise by identical title and text
  66. docId = ""
  67. curRev = 0
  68. If Not IsNull(sourceUri) Then
  69. Set rs = DAL().Query("SELECT id, current_revision FROM documents WHERE tenant_id = ? AND namespace_id = ? AND source_uri = ?", Array(Api_TenantId, nsId, sourceUri))
  70. Else
  71. Set rs = DAL().Query("SELECT d.id, d.current_revision FROM documents d JOIN document_revisions r ON r.document_id = d.id AND r.revision = d.current_revision " & _
  72. "WHERE d.tenant_id = ? AND d.namespace_id = ? AND d.source_uri IS NULL AND d.title = ? AND r.content_hash = ?", Array(Api_TenantId, nsId, title, hash))
  73. End If
  74. If Not rs.EOF Then
  75. docId = "" & rs(0)
  76. curRev = CLng(rs(1))
  77. End If
  78. rs.Close
  79. unchanged = False
  80. If Len(docId) > 0 Then
  81. Set rs = DAL().Query("SELECT content_hash, chunk_count FROM document_revisions WHERE document_id = ? AND revision = ?", Array(docId, curRev))
  82. If Not rs.EOF Then
  83. If "" & rs(0) = hash Then
  84. unchanged = True
  85. chunkTotal = CLng(rs(1))
  86. End If
  87. End If
  88. rs.Close
  89. End If
  90. jobId = Api_NewId()
  91. ts = Api_Now()
  92. On Error Resume Next
  93. DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at) VALUES (?, ?, 'ingest', 'running', 1, ?, ?, ?, ?)", _
  94. Array(jobId, Api_TenantId, nsId, Api_PrincipalId, ts, ts)
  95. If Err.Number <> 0 Then
  96. k = Err.Number : Api_NoteDbError
  97. Api_DbFailed k, ""
  98. Exit Sub
  99. End If
  100. On Error GoTo 0
  101. If unchanged Then
  102. DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, Api_Now(), jobId)
  103. resp = IngestJson(jobId, docId, curRev, chunkTotal, True)
  104. On Error Resume Next
  105. Api_IdempotencyStore idemKey, reqHash, 200, resp
  106. On Error GoTo 0
  107. Api_Audit "document.ingest", "document", docId, "unchanged"
  108. Api_Send 200, resp
  109. Exit Sub
  110. End If
  111. ' Chunk first (pure computation), then write everything in one transaction
  112. Chunk_Run content, isMd
  113. If Len(docId) = 0 Then
  114. docId = Api_NewId()
  115. revNo = 1
  116. Else
  117. revNo = curRev + 1
  118. End If
  119. On Error Resume Next
  120. DAL().BeginTransaction
  121. If revNo = 1 Then
  122. DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  123. Array(docId, Api_TenantId, nsId, fmt, title, Api_PrincipalId, ts, ts)
  124. If Not IsNull(sourceUri) Then
  125. DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(sourceUri, docId)
  126. End If
  127. Else
  128. DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev)
  129. End If
  130. DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _
  131. Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
  132. For i = 0 To Chunk_Count - 1
  133. chunkId = Api_NewId()
  134. DAL().Execute "INSERT INTO chunks (id, document_id, document_revision, ordinal, content, heading_path, start_offset, end_offset, token_estimate, created_at) VALUES (?, ?, " & revNo & ", " & i & ", ?, ?, " & Chunk_Start(i) & ", " & Chunk_End(i) & ", " & TokenEstimate(Chunk_Text(i)) & ", ?)", _
  135. Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts)
  136. DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
  137. Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
  138. Next
  139. If revNo > 1 Then
  140. DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
  141. End If
  142. DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
  143. resp = IngestJson(jobId, docId, revNo, Chunk_Count, False)
  144. Api_IdempotencyStore idemKey, reqHash, 201, resp
  145. If Err.Number <> 0 Then
  146. k = Err.Number : Api_NoteDbError
  147. Err.Clear
  148. DAL().RollbackTransaction
  149. MarkJobFailed jobId, "internal_error", Api_LastDbError
  150. Api_DbFailed k, ""
  151. Exit Sub
  152. End If
  153. DAL().CommitTransaction
  154. If Err.Number <> 0 Then
  155. k = Err.Number : Api_NoteDbError
  156. Api_DbFailed k, ""
  157. Exit Sub
  158. End If
  159. On Error GoTo 0
  160. Api_Audit "document.ingest", "document", docId, "ok"
  161. Response.AddHeader "Location", "/api/v1/documents/" & docId
  162. Api_Send 201, resp
  163. End Sub
  164. '---------------------------------------------------------------
  165. ' GET /api/v1/jobs/:id
  166. '---------------------------------------------------------------
  167. Public Sub Job(id)
  168. Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, allowed, nsId
  169. If Not Api_Authenticate() Then Exit Sub
  170. If Not Api_IsId(id) Then
  171. Api_NotFound
  172. Exit Sub
  173. End If
  174. Set rs = DAL().Query("SELECT type, state, attempt_count, result_ref, error_code, error_message, created_by, created_at, updated_at FROM jobs WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  175. If rs.EOF Then
  176. rs.Close
  177. Api_NotFound
  178. Exit Sub
  179. End If
  180. jType = "" & rs(0)
  181. state = "" & rs(1)
  182. attempts = CLng(rs(2))
  183. resultRef = rs(3)
  184. errCode = rs(4)
  185. errMsg = rs(5)
  186. createdBy = "" & rs(6)
  187. createdAt = "" & rs(7)
  188. updatedAt = "" & rs(8)
  189. rs.Close
  190. ' The submitter always sees the job; others need read access to the document it produced
  191. allowed = (createdBy = Api_PrincipalId)
  192. If Not allowed And Not IsNull(resultRef) Then
  193. nsId = DocNamespace("" & resultRef)
  194. If Len(nsId) > 0 Then allowed = Api_CanAccessNamespace(nsId, "read")
  195. End If
  196. If Not allowed Then
  197. Api_NotFound
  198. Exit Sub
  199. End If
  200. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _
  201. ",""attempts"":" & attempts & ",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _
  202. ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}"
  203. End Sub
  204. '---------------------------------------------------------------
  205. ' GET /api/v1/documents/:id (?include_content=true)
  206. '---------------------------------------------------------------
  207. Public Sub Document(id)
  208. Dim rs, nsId, json, includeContent, curRev, sourceUri, fmt, title, createdAt, updatedAt, hash, chars, chunks, text
  209. If Not Api_Authenticate() Then Exit Sub
  210. If Not Api_IsId(id) Then
  211. Api_NotFound
  212. Exit Sub
  213. End If
  214. Set rs = DAL().Query("SELECT d.namespace_id, d.source_uri, d.format, d.title, d.current_revision, d.created_at, d.updated_at, r.content_hash, r.char_count, r.chunk_count, r.content " & _
  215. "FROM documents d JOIN document_revisions r ON r.document_id = d.id AND r.revision = d.current_revision WHERE d.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId))
  216. If rs.EOF Then
  217. rs.Close
  218. Api_NotFound
  219. Exit Sub
  220. End If
  221. nsId = "" & rs(0)
  222. sourceUri = rs(1)
  223. fmt = "" & rs(2)
  224. title = "" & rs(3)
  225. curRev = CLng(rs(4))
  226. createdAt = "" & rs(5)
  227. updatedAt = "" & rs(6)
  228. hash = "" & rs(7)
  229. chars = CLng(rs(8))
  230. chunks = CLng(rs(9))
  231. text = "" & rs(10)
  232. rs.Close
  233. If Not Api_CanAccessNamespace(nsId, "read") Then
  234. Api_NotFound
  235. Exit Sub
  236. End If
  237. includeContent = (LCase(Trim("" & Request.QueryString("include_content"))) = "true")
  238. json = "{""id"":" & JsonLite_Quote(id) & ",""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _
  239. ",""source_uri"":" & JStr(sourceUri) & ",""format"":" & JsonLite_Quote(fmt) & ",""current_revision"":" & curRev & _
  240. ",""content_hash"":" & JsonLite_Quote(hash) & ",""char_count"":" & chars & ",""chunk_count"":" & chunks & _
  241. ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & ",""content_trust"":""untrusted_reference"""
  242. If includeContent Then json = json & ",""content"":" & JsonLite_Quote(text)
  243. Api_Send 200, "{""data"":" & json & "}}"
  244. End Sub
  245. '---------------------------------------------------------------
  246. ' GET /api/v1/chunks/:id
  247. '---------------------------------------------------------------
  248. Public Sub Chunk(id)
  249. Dim rs, nsId, json
  250. If Not Api_Authenticate() Then Exit Sub
  251. If Not Api_IsId(id) Then
  252. Api_NotFound
  253. Exit Sub
  254. End If
  255. Set rs = DAL().Query(ChunkSelect() & " WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId))
  256. If rs.EOF Then
  257. rs.Close
  258. Api_NotFound
  259. Exit Sub
  260. End If
  261. nsId = "" & rs(8)
  262. json = ChunkJson(rs, False, 0)
  263. rs.Close
  264. If Not Api_CanAccessNamespace(nsId, "read") Then
  265. Api_NotFound
  266. Exit Sub
  267. End If
  268. Api_Send 200, "{""data"":" & json & "}"
  269. End Sub
  270. '---------------------------------------------------------------
  271. ' POST /api/v1/search
  272. '---------------------------------------------------------------
  273. Public Sub Search()
  274. Dim body, input, query, fts, maxResults, detail, allowed, nsList, ids(), scores(), n, rs, sql, out, count, i, j, idList, rowJson()
  275. Dim requested, arr, ok, wanted, warn
  276. If Not Api_Authenticate() Then Exit Sub
  277. body = Api_ReadBody()
  278. If IsEmpty(body) Then Exit Sub
  279. Set input = JsonLite_Parse(body)
  280. m_errs = ""
  281. query = ReqString(input, "query", 1000)
  282. maxResults = 10
  283. If input.Exists("max_results") Then
  284. If VarType(input.Item("max_results")) = vbDouble Then
  285. maxResults = CLng(input.Item("max_results"))
  286. If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50."
  287. Else
  288. AddErr "max_results must be a number."
  289. End If
  290. End If
  291. detail = OptString(input, "detail_level", 20)
  292. If IsNull(detail) Then detail = "full"
  293. detail = LCase(detail)
  294. If detail <> "full" And detail <> "snippet" Then AddErr "detail_level must be full or snippet."
  295. requested = IdListField(input, "namespace_ids")
  296. If Len(m_errs) > 0 Then
  297. Api_Invalid Split(m_errs, Chr(30))
  298. Exit Sub
  299. End If
  300. fts = Search_FtsQuery(query)
  301. If Len(fts) = 0 Then
  302. Api_Invalid Array("query must contain at least one word.")
  303. Exit Sub
  304. End If
  305. allowed = Api_AllowedNamespaceIds("read")
  306. If Len(allowed) > 0 And Len(requested) > 0 Then allowed = Intersect(allowed, requested)
  307. If Len(allowed) = 0 Then
  308. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}"
  309. Exit Sub
  310. End If
  311. ' Step 1: ranked candidate chunk ids from the index (tenant filtered); step 2: join canonical rows, apply
  312. ' the namespace and current-revision filters. The first result set is closed before the second query.
  313. Set rs = DAL().Query("SELECT chunk_id, bm25(chunks_fts) FROM chunks_fts WHERE chunks_fts MATCH ? AND tenant_id = ? ORDER BY bm25(chunks_fts) LIMIT 300", Array(fts, Api_TenantId))
  314. n = 0
  315. ReDim ids(63)
  316. ReDim scores(63)
  317. Do While Not rs.EOF
  318. If n > UBound(ids) Then
  319. ReDim Preserve ids(n * 2)
  320. ReDim Preserve scores(n * 2)
  321. End If
  322. ids(n) = "" & rs(0)
  323. scores(n) = rs(1)
  324. n = n + 1
  325. rs.MoveNext
  326. Loop
  327. rs.Close
  328. If n = 0 Then
  329. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}"
  330. Exit Sub
  331. End If
  332. idList = ""
  333. For i = 0 To n - 1
  334. If Api_IsId(ids(i)) Then
  335. If Len(idList) > 0 Then idList = idList & ","
  336. idList = idList & "'" & ids(i) & "'"
  337. End If
  338. Next
  339. sql = ChunkSelect() & " WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") AND c.document_revision = d.current_revision"
  340. Set rs = DAL().Query(sql, Api_TenantId)
  341. ReDim rowJson(n - 1)
  342. Do While Not rs.EOF
  343. For j = 0 To n - 1
  344. If ids(j) = "" & rs(0) Then
  345. rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j))
  346. Exit For
  347. End If
  348. Next
  349. rs.MoveNext
  350. Loop
  351. rs.Close
  352. out = ""
  353. count = 0
  354. For j = 0 To n - 1
  355. If Len("" & rowJson(j)) > 0 Then
  356. If count >= maxResults Then Exit For
  357. If count > 0 Then out = out & ","
  358. out = out & rowJson(j)
  359. count = count + 1
  360. End If
  361. Next
  362. Api_Audit "document.search", "search", "", "ok"
  363. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[]}"
  364. End Sub
  365. '===============================================================
  366. ' Helpers
  367. '===============================================================
  368. ' Column order relied on by ChunkJson:
  369. ' 0 chunk id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, 8 namespace id,
  370. ' 9 doc title, 10 source uri, 11 current revision, 12 token estimate
  371. Private Function ChunkSelect()
  372. ChunkSelect = "SELECT c.id, c.document_id, c.document_revision, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, d.namespace_id, " & _
  373. "d.title, d.source_uri, d.current_revision, c.token_estimate FROM chunks c JOIN documents d ON d.id = c.document_id"
  374. End Function
  375. ' score: bm25 value for search hits (0 elsewhere). bm25 is negative, lower = better, so the exposed score is its negation.
  376. Private Function ChunkJson(rs, snippet, score)
  377. Dim txt, s
  378. txt = "" & rs(4)
  379. If snippet And Len(txt) > 240 Then txt = Left(txt, 240) & "..."
  380. s = "{""chunk_id"":" & JsonLite_Quote("" & rs(0)) & ",""document_id"":" & JsonLite_Quote("" & rs(1)) & ",""document_title"":" & JsonLite_Quote("" & rs(9)) & _
  381. ",""source_uri"":" & JStr(rs(10)) & ",""document_revision"":" & CLng(rs(2)) & ",""is_current_revision"":" & LCase(CStr(CLng(rs(2)) = CLng(rs(11)))) & _
  382. ",""ordinal"":" & CLng(rs(3)) & ",""heading_path"":" & JStr(rs(5)) & ",""locator"":{""start"":" & CLng(rs(6)) & ",""end"":" & CLng(rs(7)) & "}" & _
  383. ",""token_estimate"":" & CLng(rs(12)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(8))
  384. If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(-CDbl(score))
  385. s = s & ",""content"":" & JsonLite_Quote(txt) & ",""content_trust"":""untrusted_reference""}"
  386. ChunkJson = s
  387. End Function
  388. Private Function IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
  389. IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
  390. ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
  391. End Function
  392. Private Sub MarkJobFailed(jobId, code, message)
  393. On Error Resume Next
  394. If LCase(GetAppSetting("Environment")) <> "development" Then message = ""
  395. DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId)
  396. Err.Clear
  397. On Error GoTo 0
  398. End Sub
  399. Private Function DocNamespace(docId)
  400. Dim rs
  401. DocNamespace = ""
  402. If Not Api_IsId(docId) Then Exit Function
  403. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(docId, Api_TenantId))
  404. If Not rs.EOF Then DocNamespace = "" & rs(0)
  405. rs.Close
  406. End Function
  407. Private Function TokenEstimate(text)
  408. TokenEstimate = Int(Len(text) / 4) + 1
  409. End Function
  410. Private Function HeadingOrNull(h)
  411. If Len("" & h) = 0 Then
  412. HeadingOrNull = Null
  413. Else
  414. HeadingOrNull = "" & h
  415. End If
  416. End Function
  417. Private Function JStr(v)
  418. If IsNull(v) Then
  419. JStr = "null"
  420. Else
  421. JStr = JsonLite_Quote("" & v)
  422. End If
  423. End Function
  424. ' Comma-separated quoted ids from an optional JSON array of id strings ("" when absent). Bad entries are reported.
  425. Private Function IdListField(input, name)
  426. Dim arr, i, out
  427. IdListField = ""
  428. If Not input.HasRaw(name) Then
  429. If input.Exists(name) Then
  430. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  431. End If
  432. Exit Function
  433. End If
  434. arr = JsonLite_ParseStringArray(input.Raw(name))
  435. If IsNull(arr) Then
  436. AddErr name & " must be an array of ids."
  437. Exit Function
  438. End If
  439. out = ""
  440. For i = 0 To UBound(arr)
  441. If Not Api_IsId(arr(i)) Then
  442. AddErr name & " must contain valid ids."
  443. Exit Function
  444. End If
  445. If Len(out) > 0 Then out = out & ","
  446. out = out & "'" & arr(i) & "'"
  447. Next
  448. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  449. IdListField = out
  450. End Function
  451. ' Keeps the ids of `allowed` that also appear in `requested` (both are "'id','id'" lists of validated ids)
  452. Private Function Intersect(allowed, requested)
  453. Dim a, i, out
  454. a = Split(allowed, ",")
  455. out = ""
  456. For i = 0 To UBound(a)
  457. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  458. If Len(out) > 0 Then out = out & ","
  459. out = out & a(i)
  460. End If
  461. Next
  462. Intersect = out
  463. End Function
  464. Private Sub AddErr(msg)
  465. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  466. m_errs = m_errs & msg
  467. End Sub
  468. Private Function ReqString(input, name, maxLen)
  469. Dim v
  470. ReqString = ""
  471. If Not input.Exists(name) Then
  472. AddErr name & " is required."
  473. Exit Function
  474. End If
  475. v = input.Item(name)
  476. If IsNull(v) Then
  477. AddErr name & " is required."
  478. Exit Function
  479. End If
  480. If VarType(v) <> vbString Then
  481. AddErr name & " must be a string."
  482. Exit Function
  483. End If
  484. v = Trim(v)
  485. If Len(v) = 0 Then
  486. AddErr name & " must not be empty."
  487. Exit Function
  488. End If
  489. If Len(v) > maxLen Then
  490. AddErr name & " must be at most " & maxLen & " characters."
  491. Exit Function
  492. End If
  493. ReqString = v
  494. End Function
  495. ' Like ReqString but the text is kept exactly as sent (no trimming): offsets must match the stored text
  496. Private Function ReqText(input, name, maxLen)
  497. Dim v
  498. ReqText = ""
  499. If Not input.Exists(name) Then
  500. AddErr name & " is required."
  501. Exit Function
  502. End If
  503. v = input.Item(name)
  504. If IsNull(v) Then
  505. AddErr name & " is required."
  506. Exit Function
  507. End If
  508. If VarType(v) <> vbString Then
  509. AddErr name & " must be a string."
  510. Exit Function
  511. End If
  512. If Len(Trim(v)) = 0 Then
  513. AddErr name & " must not be empty."
  514. Exit Function
  515. End If
  516. If Len(v) > maxLen Then
  517. AddErr name & " must be at most " & maxLen & " characters."
  518. Exit Function
  519. End If
  520. ReqText = v
  521. End Function
  522. Private Function OptString(input, name, maxLen)
  523. Dim v
  524. OptString = Null
  525. If Not input.Exists(name) Then Exit Function
  526. v = input.Item(name)
  527. If IsNull(v) Then Exit Function
  528. If VarType(v) <> vbString Then
  529. AddErr name & " must be a string."
  530. Exit Function
  531. End If
  532. If Len(v) > maxLen Then
  533. AddErr name & " must be at most " & maxLen & " characters."
  534. Exit Function
  535. End If
  536. OptString = v
  537. End Function
  538. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  539. Public Sub Invoke(actionName, args)
  540. Select Case LCase(actionName)
  541. Case "ingest" : Ingest
  542. Case "job" : Job args(0)
  543. Case "document" : Document args(0)
  544. Case "chunk" : Chunk args(0)
  545. Case "search" : Search
  546. Case Else
  547. Err.Raise 438, "ApiDocumentsController_Class", "Action '" & actionName & "' not found"
  548. End Select
  549. End Sub
  550. End Class
  551. Dim ApiDocumentsController_Class__Singleton
  552. Function ApiDocumentsController()
  553. If IsEmpty(ApiDocumentsController_Class__Singleton) Then
  554. Set ApiDocumentsController_Class__Singleton = New ApiDocumentsController_Class
  555. End If
  556. Set ApiDocumentsController = ApiDocumentsController_Class__Singleton
  557. End Function
  558. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  559. Sub ApiDocumentsController_Invoke(actionName, args)
  560. ApiDocumentsController().Invoke actionName, args
  561. End Sub
  562. %>

Powered by TurnKey Linux.