Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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

Powered by TurnKey Linux.