<% ' 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"} ' GET /api/v1/jobs/:id Job job state ' 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 processed inside the request (no worker yet) but is recorded as a job. 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 rs, docId, curRev, revNo, jobId, ts, unchanged, k, resp, i, chunkId, isMd, statusCode, chunkTotal 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 isMd = (fmt = "markdown") norm = Chunk_Normalize(content) hash = Api_Sha256(norm) ' Find an existing document: by source_uri when given, otherwise by identical title and text docId = "" curRev = 0 If Not IsNull(sourceUri) Then Set rs = DAL().Query("SELECT id, current_revision FROM documents WHERE tenant_id = ? AND namespace_id = ? AND source_uri = ?", Array(Api_TenantId, nsId, sourceUri)) Else 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 " & _ "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)) End If If Not rs.EOF Then docId = "" & rs(0) curRev = CLng(rs(1)) End If rs.Close unchanged = False If Len(docId) > 0 Then Set rs = DAL().Query("SELECT content_hash, chunk_count FROM document_revisions WHERE document_id = ? AND revision = ?", Array(docId, curRev)) If Not rs.EOF Then If "" & rs(0) = hash Then unchanged = True chunkTotal = CLng(rs(1)) End If End If rs.Close End If jobId = Api_NewId() ts = Api_Now() On Error Resume Next DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at) VALUES (?, ?, 'ingest', 'running', 1, ?, ?, ?, ?)", _ Array(jobId, Api_TenantId, nsId, Api_PrincipalId, ts, ts) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 If unchanged Then DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, Api_Now(), jobId) resp = IngestJson(jobId, docId, curRev, chunkTotal, True) On Error Resume Next Api_IdempotencyStore idemKey, reqHash, 200, resp On Error GoTo 0 Api_Audit "document.ingest", "document", docId, "unchanged" Api_Send 200, resp Exit Sub End If ' Chunk first (pure computation), then write everything in one transaction Chunk_Run content, isMd If Len(docId) = 0 Then docId = Api_NewId() revNo = 1 Else revNo = curRev + 1 End If On Error Resume Next DAL().BeginTransaction If revNo = 1 Then DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ Array(docId, Api_TenantId, nsId, fmt, title, Api_PrincipalId, ts, ts) If Not IsNull(sourceUri) Then DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(sourceUri, docId) End If Else DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev) Emb_MarkDeleteChunks docId, curRev End If 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 & ", ?, ?)", _ Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts) For i = 0 To Chunk_Count - 1 chunkId = Api_NewId() 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)) & ", ?)", _ Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts) DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _ Array(Chunk_Text(i), chunkId, Api_TenantId, nsId) Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo Next If revNo > 1 Then DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId) End If DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, ts, jobId) resp = IngestJson(jobId, docId, revNo, Chunk_Count, False) Api_IdempotencyStore idemKey, reqHash, 201, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear DAL().RollbackTransaction MarkJobFailed jobId, "internal_error", Api_LastDbError 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 Emb_AfterWrite Api_TenantId, 64 Api_Audit "document.ingest", "document", docId, "ok" Response.AddHeader "Location", "/api/v1/documents/" & docId Api_Send 201, resp End Sub '--------------------------------------------------------------- ' GET /api/v1/jobs/:id '--------------------------------------------------------------- Public Sub Job(id) Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, allowed, nsId If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If 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)) If rs.EOF Then rs.Close Api_NotFound Exit Sub 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) rs.Close ' The submitter always sees the job; others need read access to the document it produced allowed = (createdBy = Api_PrincipalId) If Not allowed And Not IsNull(resultRef) Then nsId = DocNamespace("" & resultRef) If Len(nsId) > 0 Then allowed = Api_CanAccessNamespace(nsId, "read") End If If Not allowed Then Api_NotFound Exit Sub End If Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _ ",""attempts"":" & attempts & ",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _ ",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}" End Sub '--------------------------------------------------------------- ' 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 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) If Len(allowed) = 0 Then Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""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 Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""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) 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)) 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 End If Next Api_Audit "document.search", "search", "", "ok" Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""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 IngestJson(jobId, docId, revNo, chunkTotal, unchanged) IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _ ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}" End Function Private Sub MarkJobFailed(jobId, code, message) On Error Resume Next If LCase(GetAppSetting("Environment")) <> "development" Then message = "" DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId) Err.Clear On Error GoTo 0 End Sub 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 TokenEstimate(text) TokenEstimate = Int(Len(text) / 4) + 1 End Function Private Function HeadingOrNull(h) If Len("" & h) = 0 Then HeadingOrNull = Null Else HeadingOrNull = "" & h End If 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 "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 %>