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.

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

Powered by TurnKey Linux.