No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

623 líneas
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. Emb_MarkDeleteChunks docId, curRev
  130. End If
  131. 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 & ", ?, ?)", _
  132. Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
  133. For i = 0 To Chunk_Count - 1
  134. chunkId = Api_NewId()
  135. 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)) & ", ?)", _
  136. Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts)
  137. DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
  138. Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
  139. Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo
  140. Next
  141. If revNo > 1 Then
  142. DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
  143. End If
  144. DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
  145. resp = IngestJson(jobId, docId, revNo, Chunk_Count, False)
  146. Api_IdempotencyStore idemKey, reqHash, 201, resp
  147. If Err.Number <> 0 Then
  148. k = Err.Number : Api_NoteDbError
  149. Err.Clear
  150. DAL().RollbackTransaction
  151. MarkJobFailed jobId, "internal_error", Api_LastDbError
  152. Api_DbFailed k, ""
  153. Exit Sub
  154. End If
  155. DAL().CommitTransaction
  156. If Err.Number <> 0 Then
  157. k = Err.Number : Api_NoteDbError
  158. Api_DbFailed k, ""
  159. Exit Sub
  160. End If
  161. On Error GoTo 0
  162. Emb_AfterWrite Api_TenantId, 64
  163. Api_Audit "document.ingest", "document", docId, "ok"
  164. Response.AddHeader "Location", "/api/v1/documents/" & docId
  165. Api_Send 201, resp
  166. End Sub
  167. '---------------------------------------------------------------
  168. ' GET /api/v1/jobs/:id
  169. '---------------------------------------------------------------
  170. Public Sub Job(id)
  171. Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, allowed, nsId
  172. If Not Api_Authenticate() Then Exit Sub
  173. If Not Api_IsId(id) Then
  174. Api_NotFound
  175. Exit Sub
  176. End If
  177. 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))
  178. If rs.EOF Then
  179. rs.Close
  180. Api_NotFound
  181. Exit Sub
  182. End If
  183. jType = "" & rs(0)
  184. state = "" & rs(1)
  185. attempts = CLng(rs(2))
  186. resultRef = rs(3)
  187. errCode = rs(4)
  188. errMsg = rs(5)
  189. createdBy = "" & rs(6)
  190. createdAt = "" & rs(7)
  191. updatedAt = "" & rs(8)
  192. rs.Close
  193. ' The submitter always sees the job; others need read access to the document it produced
  194. allowed = (createdBy = Api_PrincipalId)
  195. If Not allowed And Not IsNull(resultRef) Then
  196. nsId = DocNamespace("" & resultRef)
  197. If Len(nsId) > 0 Then allowed = Api_CanAccessNamespace(nsId, "read")
  198. End If
  199. If Not allowed Then
  200. Api_NotFound
  201. Exit Sub
  202. End If
  203. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _
  204. ",""attempts"":" & attempts & ",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _
  205. ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}"
  206. End Sub
  207. '---------------------------------------------------------------
  208. ' GET /api/v1/documents/:id (?include_content=true)
  209. '---------------------------------------------------------------
  210. Public Sub Document(id)
  211. Dim rs, nsId, json, includeContent, curRev, sourceUri, fmt, title, createdAt, updatedAt, hash, chars, chunks, text
  212. If Not Api_Authenticate() Then Exit Sub
  213. If Not Api_IsId(id) Then
  214. Api_NotFound
  215. Exit Sub
  216. End If
  217. 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 " & _
  218. "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))
  219. If rs.EOF Then
  220. rs.Close
  221. Api_NotFound
  222. Exit Sub
  223. End If
  224. nsId = "" & rs(0)
  225. sourceUri = rs(1)
  226. fmt = "" & rs(2)
  227. title = "" & rs(3)
  228. curRev = CLng(rs(4))
  229. createdAt = "" & rs(5)
  230. updatedAt = "" & rs(6)
  231. hash = "" & rs(7)
  232. chars = CLng(rs(8))
  233. chunks = CLng(rs(9))
  234. text = "" & rs(10)
  235. rs.Close
  236. If Not Api_CanAccessNamespace(nsId, "read") Then
  237. Api_NotFound
  238. Exit Sub
  239. End If
  240. includeContent = (LCase(Trim("" & Request.QueryString("include_content"))) = "true")
  241. json = "{""id"":" & JsonLite_Quote(id) & ",""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _
  242. ",""source_uri"":" & JStr(sourceUri) & ",""format"":" & JsonLite_Quote(fmt) & ",""current_revision"":" & curRev & _
  243. ",""content_hash"":" & JsonLite_Quote(hash) & ",""char_count"":" & chars & ",""chunk_count"":" & chunks & _
  244. ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & ",""content_trust"":""untrusted_reference"""
  245. If includeContent Then json = json & ",""content"":" & JsonLite_Quote(text)
  246. Api_Send 200, "{""data"":" & json & "}}"
  247. End Sub
  248. '---------------------------------------------------------------
  249. ' GET /api/v1/chunks/:id
  250. '---------------------------------------------------------------
  251. Public Sub Chunk(id)
  252. Dim rs, nsId, json
  253. If Not Api_Authenticate() Then Exit Sub
  254. If Not Api_IsId(id) Then
  255. Api_NotFound
  256. Exit Sub
  257. End If
  258. Set rs = DAL().Query(ChunkSelect() & " WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId))
  259. If rs.EOF Then
  260. rs.Close
  261. Api_NotFound
  262. Exit Sub
  263. End If
  264. nsId = "" & rs(8)
  265. json = ChunkJson(rs, False, 0)
  266. rs.Close
  267. If Not Api_CanAccessNamespace(nsId, "read") Then
  268. Api_NotFound
  269. Exit Sub
  270. End If
  271. Api_Send 200, "{""data"":" & json & "}"
  272. End Sub
  273. '---------------------------------------------------------------
  274. ' POST /api/v1/search
  275. '---------------------------------------------------------------
  276. Public Sub Search()
  277. Dim body, input, query, fts, maxResults, detail, allowed, nsList, ids(), scores(), n, rs, sql, out, count, i, j, idList, rowJson()
  278. Dim requested, arr, ok, wanted, warn, ranker, warnJson, revs(), qid, spec, t0
  279. t0 = Timer
  280. If Not Api_Authenticate() Then Exit Sub
  281. body = Api_ReadBody()
  282. If IsEmpty(body) Then Exit Sub
  283. Set input = JsonLite_Parse(body)
  284. m_errs = ""
  285. query = ReqString(input, "query", 1000)
  286. maxResults = 10
  287. If input.Exists("max_results") Then
  288. If VarType(input.Item("max_results")) = vbDouble Then
  289. maxResults = CLng(input.Item("max_results"))
  290. If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50."
  291. Else
  292. AddErr "max_results must be a number."
  293. End If
  294. End If
  295. detail = OptString(input, "detail_level", 20)
  296. If IsNull(detail) Then detail = "full"
  297. detail = LCase(detail)
  298. If detail <> "full" And detail <> "snippet" Then AddErr "detail_level must be full or snippet."
  299. requested = IdListField(input, "namespace_ids")
  300. If Len(m_errs) > 0 Then
  301. Api_Invalid Split(m_errs, Chr(30))
  302. Exit Sub
  303. End If
  304. fts = Search_FtsQuery(query)
  305. If Len(fts) = 0 Then
  306. Api_Invalid Array("query must contain at least one word.")
  307. Exit Sub
  308. End If
  309. allowed = Api_AllowedNamespaceIds("read")
  310. If Len(allowed) > 0 And Len(requested) > 0 Then allowed = Intersect(allowed, requested)
  311. qid = Tel_NewQueryId()
  312. spec = ""
  313. If Len(allowed) = 0 Then
  314. Tel_Record qid, "search", "lexical", query, spec, t0
  315. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}"
  316. Exit Sub
  317. End If
  318. ' Step 1: ranked candidate chunk ids (lexical, fused with semantic when configured; tenant filtered);
  319. ' step 2: join canonical rows, apply the namespace and current-revision filters.
  320. Set ranker = New Ranker_Class
  321. ranker.Run "chunk", fts, query, Api_TenantId, allowed
  322. n = ranker.Count
  323. warnJson = ""
  324. If Len(ranker.Warning) > 0 Then
  325. warnJson = JsonLite_Quote(ranker.Warning)
  326. End If
  327. If n = 0 Then
  328. Tel_Record qid, "search", ranker.Strategy, query, spec, t0
  329. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}"
  330. Exit Sub
  331. End If
  332. ReDim ids(n - 1)
  333. ReDim scores(n - 1)
  334. For i = 0 To n - 1
  335. ids(i) = ranker.IdAt(i)
  336. scores(i) = -ranker.ScoreAt(i) ' ChunkJson negates again
  337. Next
  338. idList = ""
  339. For i = 0 To n - 1
  340. If Api_IsId(ids(i)) Then
  341. If Len(idList) > 0 Then idList = idList & ","
  342. idList = idList & "'" & ids(i) & "'"
  343. End If
  344. Next
  345. sql = ChunkSelect() & " WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") AND c.document_revision = d.current_revision"
  346. Set rs = DAL().Query(sql, Api_TenantId)
  347. ReDim rowJson(n - 1)
  348. ReDim revs(n - 1)
  349. Do While Not rs.EOF
  350. For j = 0 To n - 1
  351. If ids(j) = "" & rs(0) Then
  352. rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j))
  353. revs(j) = CLng(rs(2))
  354. Exit For
  355. End If
  356. Next
  357. rs.MoveNext
  358. Loop
  359. rs.Close
  360. out = ""
  361. count = 0
  362. For j = 0 To n - 1
  363. If Len("" & rowJson(j)) > 0 Then
  364. If count >= maxResults Then Exit For
  365. If count > 0 Then out = out & ","
  366. out = out & rowJson(j)
  367. count = count + 1
  368. Tel_AddResult spec, "chunk", ids(j), revs(j), -CDbl(scores(j))
  369. End If
  370. Next
  371. Tel_Record qid, "search", ranker.Strategy, query, spec, t0
  372. Api_Audit "document.search", "search", "", "ok"
  373. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}"
  374. End Sub
  375. '===============================================================
  376. ' Helpers
  377. '===============================================================
  378. ' Column order relied on by ChunkJson:
  379. ' 0 chunk id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, 8 namespace id,
  380. ' 9 doc title, 10 source uri, 11 current revision, 12 token estimate
  381. Private Function ChunkSelect()
  382. 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, " & _
  383. "d.title, d.source_uri, d.current_revision, c.token_estimate FROM chunks c JOIN documents d ON d.id = c.document_id"
  384. End Function
  385. ' score: bm25 value for search hits (0 elsewhere). bm25 is negative, lower = better, so the exposed score is its negation.
  386. Private Function ChunkJson(rs, snippet, score)
  387. Dim txt, s
  388. txt = "" & rs(4)
  389. If snippet And Len(txt) > 240 Then txt = Left(txt, 240) & "..."
  390. s = "{""chunk_id"":" & JsonLite_Quote("" & rs(0)) & ",""document_id"":" & JsonLite_Quote("" & rs(1)) & ",""document_title"":" & JsonLite_Quote("" & rs(9)) & _
  391. ",""source_uri"":" & JStr(rs(10)) & ",""document_revision"":" & CLng(rs(2)) & ",""is_current_revision"":" & LCase(CStr(CLng(rs(2)) = CLng(rs(11)))) & _
  392. ",""ordinal"":" & CLng(rs(3)) & ",""heading_path"":" & JStr(rs(5)) & ",""locator"":{""start"":" & CLng(rs(6)) & ",""end"":" & CLng(rs(7)) & "}" & _
  393. ",""token_estimate"":" & CLng(rs(12)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(8))
  394. If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(-CDbl(score))
  395. s = s & ",""content"":" & JsonLite_Quote(txt) & ",""content_trust"":""untrusted_reference""}"
  396. ChunkJson = s
  397. End Function
  398. Private Function IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
  399. IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
  400. ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
  401. End Function
  402. Private Sub MarkJobFailed(jobId, code, message)
  403. On Error Resume Next
  404. If LCase(GetAppSetting("Environment")) <> "development" Then message = ""
  405. DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId)
  406. Err.Clear
  407. On Error GoTo 0
  408. End Sub
  409. Private Function DocNamespace(docId)
  410. Dim rs
  411. DocNamespace = ""
  412. If Not Api_IsId(docId) Then Exit Function
  413. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(docId, Api_TenantId))
  414. If Not rs.EOF Then DocNamespace = "" & rs(0)
  415. rs.Close
  416. End Function
  417. Private Function TokenEstimate(text)
  418. TokenEstimate = Int(Len(text) / 4) + 1
  419. End Function
  420. Private Function HeadingOrNull(h)
  421. If Len("" & h) = 0 Then
  422. HeadingOrNull = Null
  423. Else
  424. HeadingOrNull = "" & h
  425. End If
  426. End Function
  427. Private Function JStr(v)
  428. If IsNull(v) Then
  429. JStr = "null"
  430. Else
  431. JStr = JsonLite_Quote("" & v)
  432. End If
  433. End Function
  434. ' Comma-separated quoted ids from an optional JSON array of id strings ("" when absent). Bad entries are reported.
  435. Private Function IdListField(input, name)
  436. Dim arr, i, out
  437. IdListField = ""
  438. If Not input.HasRaw(name) Then
  439. If input.Exists(name) Then
  440. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  441. End If
  442. Exit Function
  443. End If
  444. arr = JsonLite_ParseStringArray(input.Raw(name))
  445. If IsNull(arr) Then
  446. AddErr name & " must be an array of ids."
  447. Exit Function
  448. End If
  449. out = ""
  450. For i = 0 To UBound(arr)
  451. If Not Api_IsId(arr(i)) Then
  452. AddErr name & " must contain valid ids."
  453. Exit Function
  454. End If
  455. If Len(out) > 0 Then out = out & ","
  456. out = out & "'" & arr(i) & "'"
  457. Next
  458. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  459. IdListField = out
  460. End Function
  461. ' Keeps the ids of `allowed` that also appear in `requested` (both are "'id','id'" lists of validated ids)
  462. Private Function Intersect(allowed, requested)
  463. Dim a, i, out
  464. a = Split(allowed, ",")
  465. out = ""
  466. For i = 0 To UBound(a)
  467. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  468. If Len(out) > 0 Then out = out & ","
  469. out = out & a(i)
  470. End If
  471. Next
  472. Intersect = out
  473. End Function
  474. Private Sub AddErr(msg)
  475. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  476. m_errs = m_errs & msg
  477. End Sub
  478. Private Function ReqString(input, name, maxLen)
  479. Dim v
  480. ReqString = ""
  481. If Not input.Exists(name) Then
  482. AddErr name & " is required."
  483. Exit Function
  484. End If
  485. v = input.Item(name)
  486. If IsNull(v) Then
  487. AddErr name & " is required."
  488. Exit Function
  489. End If
  490. If VarType(v) <> vbString Then
  491. AddErr name & " must be a string."
  492. Exit Function
  493. End If
  494. v = Trim(v)
  495. If Len(v) = 0 Then
  496. AddErr name & " must not be empty."
  497. Exit Function
  498. End If
  499. If Len(v) > maxLen Then
  500. AddErr name & " must be at most " & maxLen & " characters."
  501. Exit Function
  502. End If
  503. ReqString = v
  504. End Function
  505. ' Like ReqString but the text is kept exactly as sent (no trimming): offsets must match the stored text
  506. Private Function ReqText(input, name, maxLen)
  507. Dim v
  508. ReqText = ""
  509. If Not input.Exists(name) Then
  510. AddErr name & " is required."
  511. Exit Function
  512. End If
  513. v = input.Item(name)
  514. If IsNull(v) Then
  515. AddErr name & " is required."
  516. Exit Function
  517. End If
  518. If VarType(v) <> vbString Then
  519. AddErr name & " must be a string."
  520. Exit Function
  521. End If
  522. If Len(Trim(v)) = 0 Then
  523. AddErr name & " must not be empty."
  524. Exit Function
  525. End If
  526. If Len(v) > maxLen Then
  527. AddErr name & " must be at most " & maxLen & " characters."
  528. Exit Function
  529. End If
  530. ReqText = v
  531. End Function
  532. Private Function OptString(input, name, maxLen)
  533. Dim v
  534. OptString = Null
  535. If Not input.Exists(name) Then Exit Function
  536. v = input.Item(name)
  537. If IsNull(v) Then Exit Function
  538. If VarType(v) <> vbString Then
  539. AddErr name & " must be a string."
  540. Exit Function
  541. End If
  542. If Len(v) > maxLen Then
  543. AddErr name & " must be at most " & maxLen & " characters."
  544. Exit Function
  545. End If
  546. OptString = v
  547. End Function
  548. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  549. Public Sub Invoke(actionName, args)
  550. Select Case LCase(actionName)
  551. Case "ingest" : Ingest
  552. Case "job" : Job args(0)
  553. Case "document" : Document args(0)
  554. Case "chunk" : Chunk args(0)
  555. Case "search" : Search
  556. Case Else
  557. Err.Raise 438, "ApiDocumentsController_Class", "Action '" & actionName & "' not found"
  558. End Select
  559. End Sub
  560. End Class
  561. Dim ApiDocumentsController_Class__Singleton
  562. Function ApiDocumentsController()
  563. If IsEmpty(ApiDocumentsController_Class__Singleton) Then
  564. Set ApiDocumentsController_Class__Singleton = New ApiDocumentsController_Class
  565. End If
  566. Set ApiDocumentsController = ApiDocumentsController_Class__Singleton
  567. End Function
  568. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  569. Sub ApiDocumentsController_Invoke(actionName, args)
  570. ApiDocumentsController().Invoke actionName, args
  571. End Sub
  572. %>

Powered by TurnKey Linux.