Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

614 строки
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
  279. If Not Api_Authenticate() Then Exit Sub
  280. body = Api_ReadBody()
  281. If IsEmpty(body) Then Exit Sub
  282. Set input = JsonLite_Parse(body)
  283. m_errs = ""
  284. query = ReqString(input, "query", 1000)
  285. maxResults = 10
  286. If input.Exists("max_results") Then
  287. If VarType(input.Item("max_results")) = vbDouble Then
  288. maxResults = CLng(input.Item("max_results"))
  289. If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50."
  290. Else
  291. AddErr "max_results must be a number."
  292. End If
  293. End If
  294. detail = OptString(input, "detail_level", 20)
  295. If IsNull(detail) Then detail = "full"
  296. detail = LCase(detail)
  297. If detail <> "full" And detail <> "snippet" Then AddErr "detail_level must be full or snippet."
  298. requested = IdListField(input, "namespace_ids")
  299. If Len(m_errs) > 0 Then
  300. Api_Invalid Split(m_errs, Chr(30))
  301. Exit Sub
  302. End If
  303. fts = Search_FtsQuery(query)
  304. If Len(fts) = 0 Then
  305. Api_Invalid Array("query must contain at least one word.")
  306. Exit Sub
  307. End If
  308. allowed = Api_AllowedNamespaceIds("read")
  309. If Len(allowed) > 0 And Len(requested) > 0 Then allowed = Intersect(allowed, requested)
  310. If Len(allowed) = 0 Then
  311. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}"
  312. Exit Sub
  313. End If
  314. ' Step 1: ranked candidate chunk ids (lexical, fused with semantic when configured; tenant filtered);
  315. ' step 2: join canonical rows, apply the namespace and current-revision filters.
  316. Set ranker = New Ranker_Class
  317. ranker.Run "chunk", fts, query, Api_TenantId, allowed
  318. n = ranker.Count
  319. warnJson = ""
  320. If Len(ranker.Warning) > 0 Then
  321. warnJson = JsonLite_Quote(ranker.Warning)
  322. End If
  323. If n = 0 Then
  324. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}"
  325. Exit Sub
  326. End If
  327. ReDim ids(n - 1)
  328. ReDim scores(n - 1)
  329. For i = 0 To n - 1
  330. ids(i) = ranker.IdAt(i)
  331. scores(i) = -ranker.ScoreAt(i) ' ChunkJson negates again
  332. Next
  333. idList = ""
  334. For i = 0 To n - 1
  335. If Api_IsId(ids(i)) Then
  336. If Len(idList) > 0 Then idList = idList & ","
  337. idList = idList & "'" & ids(i) & "'"
  338. End If
  339. Next
  340. sql = ChunkSelect() & " WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") AND c.document_revision = d.current_revision"
  341. Set rs = DAL().Query(sql, Api_TenantId)
  342. ReDim rowJson(n - 1)
  343. Do While Not rs.EOF
  344. For j = 0 To n - 1
  345. If ids(j) = "" & rs(0) Then
  346. rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j))
  347. Exit For
  348. End If
  349. Next
  350. rs.MoveNext
  351. Loop
  352. rs.Close
  353. out = ""
  354. count = 0
  355. For j = 0 To n - 1
  356. If Len("" & rowJson(j)) > 0 Then
  357. If count >= maxResults Then Exit For
  358. If count > 0 Then out = out & ","
  359. out = out & rowJson(j)
  360. count = count + 1
  361. End If
  362. Next
  363. Api_Audit "document.search", "search", "", "ok"
  364. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}"
  365. End Sub
  366. '===============================================================
  367. ' Helpers
  368. '===============================================================
  369. ' Column order relied on by ChunkJson:
  370. ' 0 chunk id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, 8 namespace id,
  371. ' 9 doc title, 10 source uri, 11 current revision, 12 token estimate
  372. Private Function ChunkSelect()
  373. 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, " & _
  374. "d.title, d.source_uri, d.current_revision, c.token_estimate FROM chunks c JOIN documents d ON d.id = c.document_id"
  375. End Function
  376. ' score: bm25 value for search hits (0 elsewhere). bm25 is negative, lower = better, so the exposed score is its negation.
  377. Private Function ChunkJson(rs, snippet, score)
  378. Dim txt, s
  379. txt = "" & rs(4)
  380. If snippet And Len(txt) > 240 Then txt = Left(txt, 240) & "..."
  381. s = "{""chunk_id"":" & JsonLite_Quote("" & rs(0)) & ",""document_id"":" & JsonLite_Quote("" & rs(1)) & ",""document_title"":" & JsonLite_Quote("" & rs(9)) & _
  382. ",""source_uri"":" & JStr(rs(10)) & ",""document_revision"":" & CLng(rs(2)) & ",""is_current_revision"":" & LCase(CStr(CLng(rs(2)) = CLng(rs(11)))) & _
  383. ",""ordinal"":" & CLng(rs(3)) & ",""heading_path"":" & JStr(rs(5)) & ",""locator"":{""start"":" & CLng(rs(6)) & ",""end"":" & CLng(rs(7)) & "}" & _
  384. ",""token_estimate"":" & CLng(rs(12)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(8))
  385. If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(-CDbl(score))
  386. s = s & ",""content"":" & JsonLite_Quote(txt) & ",""content_trust"":""untrusted_reference""}"
  387. ChunkJson = s
  388. End Function
  389. Private Function IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
  390. IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
  391. ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
  392. End Function
  393. Private Sub MarkJobFailed(jobId, code, message)
  394. On Error Resume Next
  395. If LCase(GetAppSetting("Environment")) <> "development" Then message = ""
  396. DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId)
  397. Err.Clear
  398. On Error GoTo 0
  399. End Sub
  400. Private Function DocNamespace(docId)
  401. Dim rs
  402. DocNamespace = ""
  403. If Not Api_IsId(docId) Then Exit Function
  404. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(docId, Api_TenantId))
  405. If Not rs.EOF Then DocNamespace = "" & rs(0)
  406. rs.Close
  407. End Function
  408. Private Function TokenEstimate(text)
  409. TokenEstimate = Int(Len(text) / 4) + 1
  410. End Function
  411. Private Function HeadingOrNull(h)
  412. If Len("" & h) = 0 Then
  413. HeadingOrNull = Null
  414. Else
  415. HeadingOrNull = "" & h
  416. End If
  417. End Function
  418. Private Function JStr(v)
  419. If IsNull(v) Then
  420. JStr = "null"
  421. Else
  422. JStr = JsonLite_Quote("" & v)
  423. End If
  424. End Function
  425. ' Comma-separated quoted ids from an optional JSON array of id strings ("" when absent). Bad entries are reported.
  426. Private Function IdListField(input, name)
  427. Dim arr, i, out
  428. IdListField = ""
  429. If Not input.HasRaw(name) Then
  430. If input.Exists(name) Then
  431. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  432. End If
  433. Exit Function
  434. End If
  435. arr = JsonLite_ParseStringArray(input.Raw(name))
  436. If IsNull(arr) Then
  437. AddErr name & " must be an array of ids."
  438. Exit Function
  439. End If
  440. out = ""
  441. For i = 0 To UBound(arr)
  442. If Not Api_IsId(arr(i)) Then
  443. AddErr name & " must contain valid ids."
  444. Exit Function
  445. End If
  446. If Len(out) > 0 Then out = out & ","
  447. out = out & "'" & arr(i) & "'"
  448. Next
  449. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  450. IdListField = out
  451. End Function
  452. ' Keeps the ids of `allowed` that also appear in `requested` (both are "'id','id'" lists of validated ids)
  453. Private Function Intersect(allowed, requested)
  454. Dim a, i, out
  455. a = Split(allowed, ",")
  456. out = ""
  457. For i = 0 To UBound(a)
  458. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  459. If Len(out) > 0 Then out = out & ","
  460. out = out & a(i)
  461. End If
  462. Next
  463. Intersect = out
  464. End Function
  465. Private Sub AddErr(msg)
  466. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  467. m_errs = m_errs & msg
  468. End Sub
  469. Private Function ReqString(input, name, maxLen)
  470. Dim v
  471. ReqString = ""
  472. If Not input.Exists(name) Then
  473. AddErr name & " is required."
  474. Exit Function
  475. End If
  476. v = input.Item(name)
  477. If IsNull(v) Then
  478. AddErr name & " is required."
  479. Exit Function
  480. End If
  481. If VarType(v) <> vbString Then
  482. AddErr name & " must be a string."
  483. Exit Function
  484. End If
  485. v = Trim(v)
  486. If Len(v) = 0 Then
  487. AddErr name & " must not be empty."
  488. Exit Function
  489. End If
  490. If Len(v) > maxLen Then
  491. AddErr name & " must be at most " & maxLen & " characters."
  492. Exit Function
  493. End If
  494. ReqString = v
  495. End Function
  496. ' Like ReqString but the text is kept exactly as sent (no trimming): offsets must match the stored text
  497. Private Function ReqText(input, name, maxLen)
  498. Dim v
  499. ReqText = ""
  500. If Not input.Exists(name) Then
  501. AddErr name & " is required."
  502. Exit Function
  503. End If
  504. v = input.Item(name)
  505. If IsNull(v) Then
  506. AddErr name & " is required."
  507. Exit Function
  508. End If
  509. If VarType(v) <> vbString Then
  510. AddErr name & " must be a string."
  511. Exit Function
  512. End If
  513. If Len(Trim(v)) = 0 Then
  514. AddErr name & " must not be empty."
  515. Exit Function
  516. End If
  517. If Len(v) > maxLen Then
  518. AddErr name & " must be at most " & maxLen & " characters."
  519. Exit Function
  520. End If
  521. ReqText = v
  522. End Function
  523. Private Function OptString(input, name, maxLen)
  524. Dim v
  525. OptString = Null
  526. If Not input.Exists(name) Then Exit Function
  527. v = input.Item(name)
  528. If IsNull(v) Then Exit Function
  529. If VarType(v) <> vbString Then
  530. AddErr name & " must be a string."
  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. OptString = v
  538. End Function
  539. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  540. Public Sub Invoke(actionName, args)
  541. Select Case LCase(actionName)
  542. Case "ingest" : Ingest
  543. Case "job" : Job args(0)
  544. Case "document" : Document args(0)
  545. Case "chunk" : Chunk args(0)
  546. Case "search" : Search
  547. Case Else
  548. Err.Raise 438, "ApiDocumentsController_Class", "Action '" & actionName & "' not found"
  549. End Select
  550. End Sub
  551. End Class
  552. Dim ApiDocumentsController_Class__Singleton
  553. Function ApiDocumentsController()
  554. If IsEmpty(ApiDocumentsController_Class__Singleton) Then
  555. Set ApiDocumentsController_Class__Singleton = New ApiDocumentsController_Class
  556. End If
  557. Set ApiDocumentsController = ApiDocumentsController_Class__Singleton
  558. End Function
  559. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  560. Sub ApiDocumentsController_Invoke(actionName, args)
  561. ApiDocumentsController().Invoke actionName, args
  562. End Sub
  563. %>

Powered by TurnKey Linux.