您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

632 行
27KB

  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. If Len(ranker.FeedbackAt(j)) > 0 Then
  354. rowJson(j) = Left(rowJson(j), Len(rowJson(j)) - 1) & ",""feedback"":" & ranker.FeedbackAt(j) & "}"
  355. End If
  356. revs(j) = CLng(rs(2))
  357. Exit For
  358. End If
  359. Next
  360. rs.MoveNext
  361. Loop
  362. rs.Close
  363. out = ""
  364. count = 0
  365. For j = 0 To n - 1
  366. If Len("" & rowJson(j)) > 0 Then
  367. If count >= maxResults Then Exit For
  368. If count > 0 Then out = out & ","
  369. out = out & rowJson(j)
  370. count = count + 1
  371. Tel_AddResult spec, "chunk", ids(j), revs(j), -CDbl(scores(j))
  372. End If
  373. Next
  374. If ranker.Demoted > 0 Then
  375. If Len(warnJson) > 0 Then
  376. warnJson = warnJson & ","
  377. End If
  378. warnJson = warnJson & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback")
  379. End If
  380. Tel_Record qid, "search", ranker.Strategy, query, spec, t0
  381. Api_Audit "document.search", "search", "", "ok"
  382. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}"
  383. End Sub
  384. '===============================================================
  385. ' Helpers
  386. '===============================================================
  387. ' Column order relied on by ChunkJson:
  388. ' 0 chunk id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, 8 namespace id,
  389. ' 9 doc title, 10 source uri, 11 current revision, 12 token estimate
  390. Private Function ChunkSelect()
  391. 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, " & _
  392. "d.title, d.source_uri, d.current_revision, c.token_estimate FROM chunks c JOIN documents d ON d.id = c.document_id"
  393. End Function
  394. ' score: bm25 value for search hits (0 elsewhere). bm25 is negative, lower = better, so the exposed score is its negation.
  395. Private Function ChunkJson(rs, snippet, score)
  396. Dim txt, s
  397. txt = "" & rs(4)
  398. If snippet And Len(txt) > 240 Then txt = Left(txt, 240) & "..."
  399. s = "{""chunk_id"":" & JsonLite_Quote("" & rs(0)) & ",""document_id"":" & JsonLite_Quote("" & rs(1)) & ",""document_title"":" & JsonLite_Quote("" & rs(9)) & _
  400. ",""source_uri"":" & JStr(rs(10)) & ",""document_revision"":" & CLng(rs(2)) & ",""is_current_revision"":" & LCase(CStr(CLng(rs(2)) = CLng(rs(11)))) & _
  401. ",""ordinal"":" & CLng(rs(3)) & ",""heading_path"":" & JStr(rs(5)) & ",""locator"":{""start"":" & CLng(rs(6)) & ",""end"":" & CLng(rs(7)) & "}" & _
  402. ",""token_estimate"":" & CLng(rs(12)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(8))
  403. If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(-CDbl(score))
  404. s = s & ",""content"":" & JsonLite_Quote(txt) & ",""content_trust"":""untrusted_reference""}"
  405. ChunkJson = s
  406. End Function
  407. Private Function IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
  408. IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
  409. ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
  410. End Function
  411. Private Sub MarkJobFailed(jobId, code, message)
  412. On Error Resume Next
  413. If LCase(GetAppSetting("Environment")) <> "development" Then message = ""
  414. DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId)
  415. Err.Clear
  416. On Error GoTo 0
  417. End Sub
  418. Private Function DocNamespace(docId)
  419. Dim rs
  420. DocNamespace = ""
  421. If Not Api_IsId(docId) Then Exit Function
  422. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(docId, Api_TenantId))
  423. If Not rs.EOF Then DocNamespace = "" & rs(0)
  424. rs.Close
  425. End Function
  426. Private Function TokenEstimate(text)
  427. TokenEstimate = Int(Len(text) / 4) + 1
  428. End Function
  429. Private Function HeadingOrNull(h)
  430. If Len("" & h) = 0 Then
  431. HeadingOrNull = Null
  432. Else
  433. HeadingOrNull = "" & h
  434. End If
  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 "document" : Document args(0)
  563. Case "chunk" : Chunk args(0)
  564. Case "search" : Search
  565. Case Else
  566. Err.Raise 438, "ApiDocumentsController_Class", "Action '" & actionName & "' not found"
  567. End Select
  568. End Sub
  569. End Class
  570. Dim ApiDocumentsController_Class__Singleton
  571. Function ApiDocumentsController()
  572. If IsEmpty(ApiDocumentsController_Class__Singleton) Then
  573. Set ApiDocumentsController_Class__Singleton = New ApiDocumentsController_Class
  574. End If
  575. Set ApiDocumentsController = ApiDocumentsController_Class__Singleton
  576. End Function
  577. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  578. Sub ApiDocumentsController_Invoke(actionName, args)
  579. ApiDocumentsController().Invoke actionName, args
  580. End Sub
  581. %>

Powered by TurnKey Linux.