<% ' ApiDocumentsController: reference documents, chunks and lexical search (spec FR-006, FR-007, FR-009, FR-011, FR-016). ' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (chunker, FTS). ' ' POST /api/v1/ingestion/jobs Ingest {"namespace_id","title","content","format":"markdown|text","source_uri"} ' POST /api/v1/ingestion/jobs Ingest ... "async": true -> 202 with the queued job (the worker processes it) ' GET /api/v1/jobs/:id Job job state, attempts, errors ' POST /api/v1/jobs/:id/retry Retry requeue a failed job (write permission; 202) ' GET /api/v1/documents/:id Document metadata (?include_content=true adds the text) ' GET /api/v1/chunks/:id Chunk one passage with its source locator ' POST /api/v1/search Search {"query","namespace_ids":[],"max_results","detail_level":"full|snippet"} ' ' Ingestion is a durable job (core/lib.Jobs.asp): the job and its input are stored first, then processed inside the ' request (201/200) or, with "async": true, by the worker (202). An interrupted or failed job is retried by the ' worker with bounded attempts. The same source_uri in a ' namespace is one document; re-ingesting changed text creates a new revision and only the current revision is ' searchable. Identical text is a no-op, so retries never publish duplicate chunks. The service never fetches the ' source_uri: it is only stored as an identifier (no SSRF surface). ' Permissions on the namespace: write (Ingest), read (everything else). Retrieved text is untrusted reference ' data; responses say so with "content_trust". Class ApiDocumentsController_Class Private m_errs Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Documents API" End Property '--------------------------------------------------------------- ' POST /api/v1/ingestion/jobs '--------------------------------------------------------------- Public Sub Ingest() Dim body, input, idemKey, reqHash, nsId, title, content, fmt, sourceUri, norm, hash Dim jobId, k, resp, isAsync, payload If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) idemKey = Api_Header("Idempotency-Key") If Len(idemKey) > 200 Then Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." Exit Sub End If reqHash = Api_Sha256(body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub m_errs = "" nsId = ReqString(input, "namespace_id", 64) title = ReqString(input, "title", 200) content = ReqText(input, "content", 262144) fmt = OptString(input, "format", 20) sourceUri = OptString(input, "source_uri", 500) If IsNull(fmt) Then fmt = "markdown" fmt = LCase(fmt) If fmt <> "markdown" And fmt <> "text" Then AddErr "format must be markdown or text." If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "document.ingest", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If isAsync = False If input.Exists("async") Then If VarType(input.Item("async")) = vbBoolean Then isAsync = input.Item("async") Else Api_Invalid Array("async must be true or false.") Exit Sub End If End If ' The job and its input are stored first (durable acknowledgement, spec FR-016); see core/lib.Jobs.asp. payload = Job_Payload(nsId, title, fmt, sourceUri, content) On Error Resume Next If isAsync Then DAL().BeginTransaction jobId = Job_Create(Api_TenantId, Api_PrincipalId, nsId, payload, False) resp = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""queued""},""status_url"":" & JsonLite_Quote("/api/v1/jobs/" & jobId) & "}" Api_IdempotencyStore idemKey, reqHash, 202, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "document.ingest", "job", jobId, "queued" Response.AddHeader "Location", "/api/v1/jobs/" & jobId Api_Send 202, resp Exit Sub End If jobId = Job_Create(Api_TenantId, Api_PrincipalId, nsId, payload, True) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 If Not Job_RunIngest(jobId, idemKey, reqHash) Then Api_Audit "document.ingest", "job", jobId, "failed" If Job_ErrCode = "internal_error" Then Response.AddHeader "Location", "/api/v1/jobs/" & jobId Api_Error 500, "internal_error", "Ingestion failed; the input is kept and job " & jobId & " is retried automatically (GET /api/v1/jobs/" & jobId & ")." Else Api_Error 409, Job_ErrCode, Job_ErrMessage End If Exit Sub End If Emb_AfterWrite Api_TenantId, 64 If Job_HttpStatus = 200 Then Api_Audit "document.ingest", "document", Job_DocId, "unchanged" Else Api_Audit "document.ingest", "document", Job_DocId, "ok" Response.AddHeader "Location", "/api/v1/documents/" & Job_DocId End If Api_Send Job_HttpStatus, Job_Resp End Sub '--------------------------------------------------------------- ' GET /api/v1/jobs/:id '--------------------------------------------------------------- Public Sub Job(id) Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs, retryable If Not Api_Authenticate() Then Exit Sub If Not LoadJob(id, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs) Then Api_NotFound Exit Sub End If If Not JobVisible(createdBy, resultRef, inputNs) Then Api_NotFound Exit Sub End If retryable = False If state = "failed" Then If "" & errCode = "internal_error" Then retryable = (attempts < JOB_MAX_ATTEMPTS) End If End If Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _ ",""attempts"":" & attempts & ",""max_attempts"":" & JOB_MAX_ATTEMPTS & ",""auto_retry"":" & LCase(CStr(retryable)) & _ ",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _ ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/jobs/:id/retry (failed jobs only; write permission on the job's namespace) '--------------------------------------------------------------- Public Sub Retry(id) Dim jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs, r, k If Not Api_Authenticate() Then Exit Sub If Not LoadJob(id, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs) Then Api_NotFound Exit Sub End If If Not Api_CanAccessNamespace(inputNs, "write") Then Api_Audit "job.retry", "job", id, "denied" Api_NotFound Exit Sub End If If state <> "failed" Then Api_Error 409, "job_not_retryable", "Only failed jobs can be retried; this job is " & state & "." Exit Sub End If On Error Resume Next Set r = DAL().Exec("UPDATE jobs SET state = 'queued', attempt_count = 0, error_code = NULL, error_message = NULL, updated_at = ? " & _ "WHERE id = ? AND tenant_id = ? AND state = 'failed' AND payload IS NOT NULL", Array(Api_Now(), id, Api_TenantId)) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 If r.RowsAffected <> 1 Then Api_Error 409, "job_not_retryable", "The job's input is no longer stored; submit the document again." Exit Sub End If Api_Audit "job.retry", "job", id, "queued" Response.AddHeader "Location", "/api/v1/jobs/" & id Api_Send 202, "{""job"":{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":""queued""},""status_url"":" & JsonLite_Quote("/api/v1/jobs/" & id) & "}" End Sub ' Reads a job of the caller's tenant; False when it does not exist. Private Function LoadJob(id, ByRef jType, ByRef state, ByRef attempts, ByRef resultRef, ByRef errCode, ByRef errMsg, ByRef createdBy, ByRef createdAt, ByRef updatedAt, ByRef inputNs) Dim rs LoadJob = False If Not Api_IsId(id) Then Exit Function 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)) If rs.EOF Then rs.Close Exit Function End If jType = "" & rs(0) state = "" & rs(1) attempts = CLng(rs(2)) resultRef = rs(3) errCode = rs(4) errMsg = rs(5) createdBy = "" & rs(6) createdAt = "" & rs(7) updatedAt = "" & rs(8) inputNs = "" & rs(9) rs.Close LoadJob = True End Function ' The submitter always sees the job; others need read access to the document it produced or to its namespace. Private Function JobVisible(createdBy, resultRef, inputNs) Dim nsId JobVisible = (createdBy = Api_PrincipalId) If JobVisible Then Exit Function If Not IsNull(resultRef) Then nsId = DocNamespace("" & resultRef) If Len(nsId) > 0 Then JobVisible = Api_CanAccessNamespace(nsId, "read") Exit Function End If End If If Len(inputNs) > 0 Then JobVisible = Api_CanAccessNamespace(inputNs, "read") End If End Function '--------------------------------------------------------------- ' GET /api/v1/documents/:id (?include_content=true) '--------------------------------------------------------------- Public Sub Document(id) Dim rs, nsId, json, includeContent, curRev, sourceUri, fmt, title, createdAt, updatedAt, hash, chars, chunks, text If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If 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 " & _ "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)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) sourceUri = rs(1) fmt = "" & rs(2) title = "" & rs(3) curRev = CLng(rs(4)) createdAt = "" & rs(5) updatedAt = "" & rs(6) hash = "" & rs(7) chars = CLng(rs(8)) chunks = CLng(rs(9)) text = "" & rs(10) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If includeContent = (LCase(Trim("" & Request.QueryString("include_content"))) = "true") json = "{""id"":" & JsonLite_Quote(id) & ",""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _ ",""source_uri"":" & JStr(sourceUri) & ",""format"":" & JsonLite_Quote(fmt) & ",""current_revision"":" & curRev & _ ",""content_hash"":" & JsonLite_Quote(hash) & ",""char_count"":" & chars & ",""chunk_count"":" & chunks & _ ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & ",""content_trust"":""untrusted_reference""" If includeContent Then json = json & ",""content"":" & JsonLite_Quote(text) Api_Send 200, "{""data"":" & json & "}}" End Sub '--------------------------------------------------------------- ' GET /api/v1/chunks/:id '--------------------------------------------------------------- Public Sub Chunk(id) Dim rs, nsId, json If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query(ChunkSelect() & " WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(8) json = ChunkJson(rs, False, 0) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If Api_Send 200, "{""data"":" & json & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/search '--------------------------------------------------------------- Public Sub Search() Dim body, input, query, fts, maxResults, detail, allowed, nsList, ids(), scores(), n, rs, sql, out, count, i, j, idList, rowJson() Dim requested, arr, ok, wanted, warn, ranker, warnJson, revs(), qid, spec, t0 t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" query = ReqString(input, "query", 1000) maxResults = 10 If input.Exists("max_results") Then If VarType(input.Item("max_results")) = vbDouble Then maxResults = CLng(input.Item("max_results")) If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50." Else AddErr "max_results must be a number." End If End If detail = OptString(input, "detail_level", 20) If IsNull(detail) Then detail = "full" detail = LCase(detail) If detail <> "full" And detail <> "snippet" Then AddErr "detail_level must be full or snippet." requested = IdListField(input, "namespace_ids") If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If fts = Search_FtsQuery(query) If Len(fts) = 0 Then Api_Invalid Array("query must contain at least one word.") Exit Sub End If allowed = Api_AllowedNamespaceIds("read") If Len(allowed) > 0 And Len(requested) > 0 Then allowed = Intersect(allowed, requested) qid = Tel_NewQueryId() spec = "" If Len(allowed) = 0 Then Tel_Record qid, "search", "lexical", query, spec, t0 Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}" Exit Sub End If ' Step 1: ranked candidate chunk ids (lexical, fused with semantic when configured; tenant filtered); ' step 2: join canonical rows, apply the namespace and current-revision filters. Set ranker = New Ranker_Class ranker.Run "chunk", fts, query, Api_TenantId, allowed n = ranker.Count warnJson = "" If Len(ranker.Warning) > 0 Then warnJson = JsonLite_Quote(ranker.Warning) End If If n = 0 Then Tel_Record qid, "search", ranker.Strategy, query, spec, t0 Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}" Exit Sub End If ReDim ids(n - 1) ReDim scores(n - 1) For i = 0 To n - 1 ids(i) = ranker.IdAt(i) scores(i) = -ranker.ScoreAt(i) ' ChunkJson negates again Next idList = "" For i = 0 To n - 1 If Api_IsId(ids(i)) Then If Len(idList) > 0 Then idList = idList & "," idList = idList & "'" & ids(i) & "'" End If Next sql = ChunkSelect() & " WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") AND c.document_revision = d.current_revision" Set rs = DAL().Query(sql, Api_TenantId) ReDim rowJson(n - 1) ReDim revs(n - 1) Do While Not rs.EOF For j = 0 To n - 1 If ids(j) = "" & rs(0) Then rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j)) If Len(ranker.FeedbackAt(j)) > 0 Then rowJson(j) = Left(rowJson(j), Len(rowJson(j)) - 1) & ",""feedback"":" & ranker.FeedbackAt(j) & "}" End If revs(j) = CLng(rs(2)) Exit For End If Next rs.MoveNext Loop rs.Close out = "" count = 0 For j = 0 To n - 1 If Len("" & rowJson(j)) > 0 Then If count >= maxResults Then Exit For If count > 0 Then out = out & "," out = out & rowJson(j) count = count + 1 Tel_AddResult spec, "chunk", ids(j), revs(j), -CDbl(scores(j)) End If Next If ranker.Demoted > 0 Then If Len(warnJson) > 0 Then warnJson = warnJson & "," End If warnJson = warnJson & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback") End If Tel_Record qid, "search", ranker.Strategy, query, spec, t0 Api_Audit "document.search", "search", "", "ok" Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}" End Sub '=============================================================== ' Helpers '=============================================================== ' Column order relied on by ChunkJson: ' 0 chunk id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, 8 namespace id, ' 9 doc title, 10 source uri, 11 current revision, 12 token estimate Private Function ChunkSelect() 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, " & _ "d.title, d.source_uri, d.current_revision, c.token_estimate FROM chunks c JOIN documents d ON d.id = c.document_id" End Function ' score: bm25 value for search hits (0 elsewhere). bm25 is negative, lower = better, so the exposed score is its negation. Private Function ChunkJson(rs, snippet, score) Dim txt, s txt = "" & rs(4) If snippet And Len(txt) > 240 Then txt = Left(txt, 240) & "..." s = "{""chunk_id"":" & JsonLite_Quote("" & rs(0)) & ",""document_id"":" & JsonLite_Quote("" & rs(1)) & ",""document_title"":" & JsonLite_Quote("" & rs(9)) & _ ",""source_uri"":" & JStr(rs(10)) & ",""document_revision"":" & CLng(rs(2)) & ",""is_current_revision"":" & LCase(CStr(CLng(rs(2)) = CLng(rs(11)))) & _ ",""ordinal"":" & CLng(rs(3)) & ",""heading_path"":" & JStr(rs(5)) & ",""locator"":{""start"":" & CLng(rs(6)) & ",""end"":" & CLng(rs(7)) & "}" & _ ",""token_estimate"":" & CLng(rs(12)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(8)) If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(-CDbl(score)) s = s & ",""content"":" & JsonLite_Quote(txt) & ",""content_trust"":""untrusted_reference""}" ChunkJson = s End Function Private Function DocNamespace(docId) Dim rs DocNamespace = "" If Not Api_IsId(docId) Then Exit Function Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(docId, Api_TenantId)) If Not rs.EOF Then DocNamespace = "" & rs(0) rs.Close End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function ' Comma-separated quoted ids from an optional JSON array of id strings ("" when absent). Bad entries are reported. Private Function IdListField(input, name) Dim arr, i, out IdListField = "" If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids." End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw(name)) If IsNull(arr) Then AddErr name & " must be an array of ids." Exit Function End If out = "" For i = 0 To UBound(arr) If Not Api_IsId(arr(i)) Then AddErr name & " must contain valid ids." Exit Function End If If Len(out) > 0 Then out = out & "," out = out & "'" & arr(i) & "'" Next If Len(out) = 0 Then AddErr name & " must not be empty when given." IdListField = out End Function ' Keeps the ids of `allowed` that also appear in `requested` (both are "'id','id'" lists of validated ids) Private Function Intersect(allowed, requested) Dim a, i, out a = Split(allowed, ",") out = "" For i = 0 To UBound(a) If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then If Len(out) > 0 Then out = out & "," out = out & a(i) End If Next Intersect = out End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function ' Like ReqString but the text is kept exactly as sent (no trimming): offsets must match the stored text Private Function ReqText(input, name, maxLen) Dim v ReqText = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(Trim(v)) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqText = v End Function Private Function OptString(input, name, maxLen) Dim v OptString = Null If Not input.Exists(name) Then Exit Function v = input.Item(name) If IsNull(v) Then Exit Function If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptString = v End Function ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "ingest" : Ingest Case "job" : Job args(0) Case "retry" : Retry args(0) Case "document" : Document args(0) Case "chunk" : Chunk args(0) Case "search" : Search Case Else Err.Raise 438, "ApiDocumentsController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiDocumentsController_Class__Singleton Function ApiDocumentsController() If IsEmpty(ApiDocumentsController_Class__Singleton) Then Set ApiDocumentsController_Class__Singleton = New ApiDocumentsController_Class End If Set ApiDocumentsController = ApiDocumentsController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiDocumentsController_Invoke(actionName, args) ApiDocumentsController().Invoke actionName, args End Sub %>