|
- <%
- '=======================================================================================================================
- ' Durable ingestion jobs (spec FR-016, NFR-002, AC-12, section 11).
- '
- ' A job row stores the normalized input (payload) until it succeeds, so nothing acknowledged is lost:
- ' queued accepted, not processed yet (POST /ingestion/jobs with "async": true, or POST /jobs/:id/retry)
- ' running claimed by a request or the worker; a claim older than JOB_LEASE_MINUTES is treated as interrupted
- ' succeeded the document revision is published (payload cleared)
- ' failed error_code internal_error is retried by the worker up to JOB_MAX_ATTEMPTS attempts; other codes
- ' (invalid_payload, namespace_not_found, forbidden) need a fix and POST /jobs/:id/retry
- '
- ' Claiming is a conditional UPDATE (RowsAffected = 1), so a request and the worker never process the same job at
- ' once. Publishing the revision and marking the job succeeded happen in one transaction, and identical text is a
- ' no-op ("unchanged"), so a retried or resumed job never publishes duplicate chunks.
- ' The worker (scripts/embed.asp, action worker or jobs) calls Job_ProcessDue; it re-checks the submitter's write
- ' permission at processing time, with Api_TenantId/Api_PrincipalId set to the job's tenant and submitter.
- '=======================================================================================================================
- Const JOB_MAX_ATTEMPTS = 3
- Const JOB_LEASE_MINUTES = 5
-
- ' Results of the last Job_RunIngest
- Dim Job_Resp, Job_DocId, Job_HttpStatus, Job_ErrCode, Job_ErrMessage
-
- Function Job_JStr(v)
- If IsNull(v) Or IsEmpty(v) Then
- Job_JStr = "null"
- Else
- Job_JStr = JsonLite_Quote("" & v)
- End If
- End Function
-
- Function Job_Payload(nsId, title, fmt, sourceUri, content)
- Job_Payload = "{""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _
- ",""format"":" & JsonLite_Quote(fmt) & ",""source_uri"":" & Job_JStr(sourceUri) & ",""content"":" & JsonLite_Quote(content) & "}"
- End Function
-
- ' Inserts the job (raises on a database error). running = True claims it for the current request (attempt 1).
- Function Job_Create(tenantId, principalId, nsId, payload, running)
- Dim id, ts, st, att
- id = Api_NewId()
- ts = Api_Now()
- If running Then
- st = "running"
- att = 1
- Else
- st = "queued"
- att = 0
- End If
- DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at, payload) " & _
- "VALUES (?, ?, 'ingest', '" & st & "', " & att & ", ?, ?, ?, ?, ?)", Array(id, tenantId, nsId, principalId, ts, ts, payload)
- Job_Create = id
- End Function
-
- Function Job_StaleBefore()
- Dim d
- d = DateAdd("n", -JOB_LEASE_MINUTES, Now())
- Job_StaleBefore = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
- Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
- End Function
-
- ' Claims a due job for processing: queued, an interrupted claim, or a retryable failure with attempts left.
- Function Job_Claim(jobId)
- Dim r
- Set r = DAL().Exec("UPDATE jobs SET state = 'running', attempt_count = attempt_count + 1, updated_at = ? WHERE id = ? AND payload IS NOT NULL AND (" & _
- "state = 'queued' OR (state = 'running' AND updated_at < ?) OR (state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & "))", _
- Array(Api_Now(), jobId, Job_StaleBefore()))
- Job_Claim = (r.RowsAffected = 1)
- End Function
-
- Sub Job_MarkFailed(jobId, code, message)
- Dim msg
- msg = "" & message
- If LCase("" & GetAppSetting("Environment")) <> "development" And code = "internal_error" Then
- msg = "" ' driver text can name internals; kept only in development
- End If
- On Error Resume Next
- DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", _
- Array(code, Left(msg, 500), Api_Now(), jobId)
- Err.Clear
- On Error GoTo 0
- End Sub
-
- Function Job_IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
- Job_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
-
- ' Processes a claimed ingest job. Api_TenantId/Api_PrincipalId must be the job's tenant and submitter. idemKey/reqHash
- ' (request path only) store the idempotent response inside the publishing transaction. Returns True on success
- ' (Job_Resp, Job_DocId, Job_HttpStatus 201 or 200 for unchanged); otherwise the job is failed with Job_ErrCode.
- Function Job_RunIngest(jobId, idemKey, reqHash)
- Dim rs, payload, input, nsId, title, fmt, sourceUri, content, norm, hash, docId, curRev, unchanged, chunkTotal
- Dim revNo, ts, i, chunkId, isMd, k
-
- Job_RunIngest = False
- Job_Resp = ""
- Job_DocId = ""
- Job_HttpStatus = 0
- Job_ErrCode = ""
- Job_ErrMessage = ""
-
- Set rs = DAL().Query("SELECT payload FROM jobs WHERE id = ? AND tenant_id = ?", Array(jobId, Api_TenantId))
- payload = Null
- If Not rs.EOF Then
- payload = rs(0)
- End If
- rs.Close
- If IsNull(payload) Then
- Job_Fail jobId, "invalid_payload", "The job has no stored input."
- Exit Function
- End If
-
- Set input = JsonLite_Parse("" & payload)
- If input Is Nothing Then
- Job_Fail jobId, "invalid_payload", "The stored input is not valid JSON."
- Exit Function
- End If
- If Not (input.Exists("namespace_id") And input.Exists("title") And input.Exists("format") And input.Exists("content")) Then
- Job_Fail jobId, "invalid_payload", "The stored input is incomplete."
- Exit Function
- End If
- nsId = "" & input.Item("namespace_id")
- title = "" & input.Item("title")
- fmt = "" & input.Item("format")
- content = "" & input.Item("content")
- sourceUri = Null
- If input.Exists("source_uri") Then
- If Not IsNull(input.Item("source_uri")) Then
- sourceUri = "" & input.Item("source_uri")
- End If
- End If
-
- ' Permission is checked again at processing time (a grant may have been removed since the job was accepted).
- If Not Api_CanAccessNamespace(nsId, "write") Then
- If IsNull(Api_NamespacePath(nsId)) Then
- Job_Fail jobId, "namespace_not_found", "The namespace no longer exists."
- Else
- Job_Fail jobId, "forbidden", "The submitter no longer has write permission on the namespace."
- End If
- Exit Function
- 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
-
- ts = Api_Now()
- If unchanged Then
- Job_Resp = Job_IngestJson(jobId, docId, curRev, chunkTotal, True)
- On Error Resume Next
- DAL().BeginTransaction
- DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, payload = NULL, error_code = NULL, error_message = NULL, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
- If Len(idemKey) > 0 Then
- Api_IdempotencyStore idemKey, reqHash, 200, Job_Resp
- End If
- If Err.Number <> 0 Then
- Job_DbError jobId
- Exit Function
- End If
- DAL().CommitTransaction
- If Err.Number <> 0 Then
- Job_DbError jobId
- Exit Function
- End If
- On Error GoTo 0
- Job_DocId = docId
- Job_HttpStatus = 200
- Job_RunIngest = True
- Exit Function
- End If
-
- ' Chunk first (pure computation), then publish everything in one transaction
- Chunk_Run content, isMd
- If Len(docId) = 0 Then
- docId = Api_NewId()
- revNo = 1
- Else
- revNo = curRev + 1
- End If
- Job_Resp = Job_IngestJson(jobId, docId, revNo, Chunk_Count, False)
-
- 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) & ", " & (Int(Len(Chunk_Text(i)) / 4) + 1) & ", ?)", _
- Array(chunkId, docId, Chunk_Text(i), Job_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 = ?, payload = NULL, error_code = NULL, error_message = NULL, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
- If Len(idemKey) > 0 Then
- Api_IdempotencyStore idemKey, reqHash, 201, Job_Resp
- End If
- If Err.Number <> 0 Then
- Job_DbError jobId
- Exit Function
- End If
- DAL().CommitTransaction
- If Err.Number <> 0 Then
- Job_DbError jobId
- Exit Function
- End If
- On Error GoTo 0
- Job_DocId = docId
- Job_HttpStatus = 201
- Job_RunIngest = True
- End Function
-
- ' Database failure inside the publishing transaction: roll back and leave the job retryable.
- Sub Job_DbError(jobId)
- Dim msg
- msg = "" & Err.Description
- Api_LastDbError = msg
- Err.Clear
- DAL().RollbackTransaction
- Err.Clear
- On Error GoTo 0
- Job_Fail jobId, "internal_error", msg
- End Sub
-
- Sub Job_Fail(jobId, code, message)
- Job_ErrCode = code
- Job_ErrMessage = message
- Job_MarkFailed jobId, code, message
- End Sub
-
- Function Job_HeadingOrNull(h)
- If Len("" & h) = 0 Then
- Job_HeadingOrNull = Null
- Else
- Job_HeadingOrNull = "" & h
- End If
- End Function
-
- ' Worker pass: claims and processes up to maxJobs due jobs (oldest first). Returns "<done> <failed>" counts.
- Function Job_ProcessDue(maxJobs)
- Dim rs, ids, i, done, failed, info, tenant, principal, active, saveT, saveP
- done = 0
- failed = 0
- ids = ""
- Set rs = DAL().Query("SELECT id FROM jobs WHERE payload IS NOT NULL AND (state = 'queued' OR (state = 'running' AND updated_at < ?) OR " & _
- "(state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & ")) ORDER BY created_at LIMIT " & CLng(maxJobs), Job_StaleBefore())
- Do While Not rs.EOF
- ids = ids & rs(0) & vbLf
- rs.MoveNext
- Loop
- rs.Close
- ids = Split(ids, vbLf)
- saveT = Api_TenantId
- saveP = Api_PrincipalId
- For i = 0 To UBound(ids) - 1
- If Job_Claim(ids(i)) Then
- Set rs = DAL().Query("SELECT j.tenant_id, j.created_by, p.status FROM jobs j LEFT JOIN principals p ON p.id = j.created_by WHERE j.id = ?", ids(i))
- tenant = ""
- principal = ""
- active = ""
- If Not rs.EOF Then
- tenant = "" & rs(0)
- principal = "" & rs(1)
- active = "" & rs(2)
- End If
- rs.Close
- If active <> "active" Then
- Job_MarkFailed ids(i), "forbidden", "The submitter is no longer active."
- failed = failed + 1
- Else
- Api_TenantId = tenant
- Api_PrincipalId = principal
- If Job_RunIngest(ids(i), "", "") Then
- done = done + 1
- Emb_AfterWrite tenant, 64
- Else
- failed = failed + 1
- End If
- End If
- End If
- Next
- Api_TenantId = saveT
- Api_PrincipalId = saveP
- Job_ProcessDue = done & " " & failed
- End Function
- %>
|