Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

327 lines
14KB

  1. <%
  2. '=======================================================================================================================
  3. ' Durable ingestion jobs (spec FR-016, NFR-002, AC-12, section 11).
  4. '
  5. ' A job row stores the normalized input (payload) until it succeeds, so nothing acknowledged is lost:
  6. ' queued accepted, not processed yet (POST /ingestion/jobs with "async": true, or POST /jobs/:id/retry)
  7. ' running claimed by a request or the worker; a claim older than JOB_LEASE_MINUTES is treated as interrupted
  8. ' succeeded the document revision is published (payload cleared)
  9. ' failed error_code internal_error is retried by the worker up to JOB_MAX_ATTEMPTS attempts; other codes
  10. ' (invalid_payload, namespace_not_found, forbidden) need a fix and POST /jobs/:id/retry
  11. '
  12. ' Claiming is a conditional UPDATE (RowsAffected = 1), so a request and the worker never process the same job at
  13. ' once. Publishing the revision and marking the job succeeded happen in one transaction, and identical text is a
  14. ' no-op ("unchanged"), so a retried or resumed job never publishes duplicate chunks.
  15. ' The worker (scripts/embed.asp, action worker or jobs) calls Job_ProcessDue; it re-checks the submitter's write
  16. ' permission at processing time, with Api_TenantId/Api_PrincipalId set to the job's tenant and submitter.
  17. '=======================================================================================================================
  18. Const JOB_MAX_ATTEMPTS = 3
  19. Const JOB_LEASE_MINUTES = 5
  20. ' Results of the last Job_RunIngest
  21. Dim Job_Resp, Job_DocId, Job_HttpStatus, Job_ErrCode, Job_ErrMessage
  22. Function Job_JStr(v)
  23. If IsNull(v) Or IsEmpty(v) Then
  24. Job_JStr = "null"
  25. Else
  26. Job_JStr = JsonLite_Quote("" & v)
  27. End If
  28. End Function
  29. Function Job_Payload(nsId, title, fmt, sourceUri, content)
  30. Job_Payload = "{""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _
  31. ",""format"":" & JsonLite_Quote(fmt) & ",""source_uri"":" & Job_JStr(sourceUri) & ",""content"":" & JsonLite_Quote(content) & "}"
  32. End Function
  33. ' Inserts the job (raises on a database error). running = True claims it for the current request (attempt 1).
  34. Function Job_Create(tenantId, principalId, nsId, payload, running)
  35. Dim id, ts, st, att
  36. id = Api_NewId()
  37. ts = Api_Now()
  38. If running Then
  39. st = "running"
  40. att = 1
  41. Else
  42. st = "queued"
  43. att = 0
  44. End If
  45. DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at, payload) " & _
  46. "VALUES (?, ?, 'ingest', '" & st & "', " & att & ", ?, ?, ?, ?, ?)", Array(id, tenantId, nsId, principalId, ts, ts, payload)
  47. Job_Create = id
  48. End Function
  49. Function Job_StaleBefore()
  50. Dim d
  51. d = DateAdd("n", -JOB_LEASE_MINUTES, Now())
  52. Job_StaleBefore = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
  53. Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
  54. End Function
  55. ' Claims a due job for processing: queued, an interrupted claim, or a retryable failure with attempts left.
  56. Function Job_Claim(jobId)
  57. Dim r
  58. Set r = DAL().Exec("UPDATE jobs SET state = 'running', attempt_count = attempt_count + 1, updated_at = ? WHERE id = ? AND payload IS NOT NULL AND (" & _
  59. "state = 'queued' OR (state = 'running' AND updated_at < ?) OR (state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & "))", _
  60. Array(Api_Now(), jobId, Job_StaleBefore()))
  61. Job_Claim = (r.RowsAffected = 1)
  62. End Function
  63. Sub Job_MarkFailed(jobId, code, message)
  64. Dim msg
  65. msg = "" & message
  66. If LCase("" & GetAppSetting("Environment")) <> "development" And code = "internal_error" Then
  67. msg = "" ' driver text can name internals; kept only in development
  68. End If
  69. On Error Resume Next
  70. DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", _
  71. Array(code, Left(msg, 500), Api_Now(), jobId)
  72. Err.Clear
  73. On Error GoTo 0
  74. End Sub
  75. Function Job_IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
  76. Job_IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
  77. ",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
  78. End Function
  79. ' Processes a claimed ingest job. Api_TenantId/Api_PrincipalId must be the job's tenant and submitter. idemKey/reqHash
  80. ' (request path only) store the idempotent response inside the publishing transaction. Returns True on success
  81. ' (Job_Resp, Job_DocId, Job_HttpStatus 201 or 200 for unchanged); otherwise the job is failed with Job_ErrCode.
  82. Function Job_RunIngest(jobId, idemKey, reqHash)
  83. Dim rs, payload, input, nsId, title, fmt, sourceUri, content, norm, hash, docId, curRev, unchanged, chunkTotal
  84. Dim revNo, ts, i, chunkId, isMd, k
  85. Job_RunIngest = False
  86. Job_Resp = ""
  87. Job_DocId = ""
  88. Job_HttpStatus = 0
  89. Job_ErrCode = ""
  90. Job_ErrMessage = ""
  91. Set rs = DAL().Query("SELECT payload FROM jobs WHERE id = ? AND tenant_id = ?", Array(jobId, Api_TenantId))
  92. payload = Null
  93. If Not rs.EOF Then
  94. payload = rs(0)
  95. End If
  96. rs.Close
  97. If IsNull(payload) Then
  98. Job_Fail jobId, "invalid_payload", "The job has no stored input."
  99. Exit Function
  100. End If
  101. Set input = JsonLite_Parse("" & payload)
  102. If input Is Nothing Then
  103. Job_Fail jobId, "invalid_payload", "The stored input is not valid JSON."
  104. Exit Function
  105. End If
  106. If Not (input.Exists("namespace_id") And input.Exists("title") And input.Exists("format") And input.Exists("content")) Then
  107. Job_Fail jobId, "invalid_payload", "The stored input is incomplete."
  108. Exit Function
  109. End If
  110. nsId = "" & input.Item("namespace_id")
  111. title = "" & input.Item("title")
  112. fmt = "" & input.Item("format")
  113. content = "" & input.Item("content")
  114. sourceUri = Null
  115. If input.Exists("source_uri") Then
  116. If Not IsNull(input.Item("source_uri")) Then
  117. sourceUri = "" & input.Item("source_uri")
  118. End If
  119. End If
  120. ' Permission is checked again at processing time (a grant may have been removed since the job was accepted).
  121. If Not Api_CanAccessNamespace(nsId, "write") Then
  122. If IsNull(Api_NamespacePath(nsId)) Then
  123. Job_Fail jobId, "namespace_not_found", "The namespace no longer exists."
  124. Else
  125. Job_Fail jobId, "forbidden", "The submitter no longer has write permission on the namespace."
  126. End If
  127. Exit Function
  128. End If
  129. isMd = (fmt = "markdown")
  130. norm = Chunk_Normalize(content)
  131. hash = Api_Sha256(norm)
  132. ' Find an existing document: by source_uri when given, otherwise by identical title and text
  133. docId = ""
  134. curRev = 0
  135. If Not IsNull(sourceUri) Then
  136. Set rs = DAL().Query("SELECT id, current_revision FROM documents WHERE tenant_id = ? AND namespace_id = ? AND source_uri = ?", Array(Api_TenantId, nsId, sourceUri))
  137. Else
  138. 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 " & _
  139. "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))
  140. End If
  141. If Not rs.EOF Then
  142. docId = "" & rs(0)
  143. curRev = CLng(rs(1))
  144. End If
  145. rs.Close
  146. unchanged = False
  147. If Len(docId) > 0 Then
  148. Set rs = DAL().Query("SELECT content_hash, chunk_count FROM document_revisions WHERE document_id = ? AND revision = ?", Array(docId, curRev))
  149. If Not rs.EOF Then
  150. If "" & rs(0) = hash Then
  151. unchanged = True
  152. chunkTotal = CLng(rs(1))
  153. End If
  154. End If
  155. rs.Close
  156. End If
  157. ts = Api_Now()
  158. If unchanged Then
  159. Job_Resp = Job_IngestJson(jobId, docId, curRev, chunkTotal, True)
  160. On Error Resume Next
  161. DAL().BeginTransaction
  162. 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)
  163. If Len(idemKey) > 0 Then
  164. Api_IdempotencyStore idemKey, reqHash, 200, Job_Resp
  165. End If
  166. If Err.Number <> 0 Then
  167. Job_DbError jobId
  168. Exit Function
  169. End If
  170. DAL().CommitTransaction
  171. If Err.Number <> 0 Then
  172. Job_DbError jobId
  173. Exit Function
  174. End If
  175. On Error GoTo 0
  176. Job_DocId = docId
  177. Job_HttpStatus = 200
  178. Job_RunIngest = True
  179. Exit Function
  180. End If
  181. ' Chunk first (pure computation), then publish everything in one transaction
  182. Chunk_Run content, isMd
  183. If Len(docId) = 0 Then
  184. docId = Api_NewId()
  185. revNo = 1
  186. Else
  187. revNo = curRev + 1
  188. End If
  189. Job_Resp = Job_IngestJson(jobId, docId, revNo, Chunk_Count, False)
  190. On Error Resume Next
  191. DAL().BeginTransaction
  192. If revNo = 1 Then
  193. DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  194. Array(docId, Api_TenantId, nsId, fmt, title, Api_PrincipalId, ts, ts)
  195. If Not IsNull(sourceUri) Then
  196. DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(sourceUri, docId)
  197. End If
  198. Else
  199. DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev)
  200. Emb_MarkDeleteChunks docId, curRev
  201. End If
  202. 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 & ", ?, ?)", _
  203. Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
  204. For i = 0 To Chunk_Count - 1
  205. chunkId = Api_NewId()
  206. 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) & ", ?)", _
  207. Array(chunkId, docId, Chunk_Text(i), Job_HeadingOrNull(Chunk_Heading(i)), ts)
  208. DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
  209. Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
  210. Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo
  211. Next
  212. If revNo > 1 Then
  213. DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
  214. End If
  215. 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)
  216. If Len(idemKey) > 0 Then
  217. Api_IdempotencyStore idemKey, reqHash, 201, Job_Resp
  218. End If
  219. If Err.Number <> 0 Then
  220. Job_DbError jobId
  221. Exit Function
  222. End If
  223. DAL().CommitTransaction
  224. If Err.Number <> 0 Then
  225. Job_DbError jobId
  226. Exit Function
  227. End If
  228. On Error GoTo 0
  229. Job_DocId = docId
  230. Job_HttpStatus = 201
  231. Job_RunIngest = True
  232. End Function
  233. ' Database failure inside the publishing transaction: roll back and leave the job retryable.
  234. Sub Job_DbError(jobId)
  235. Dim msg
  236. msg = "" & Err.Description
  237. Api_LastDbError = msg
  238. Err.Clear
  239. DAL().RollbackTransaction
  240. Err.Clear
  241. On Error GoTo 0
  242. Job_Fail jobId, "internal_error", msg
  243. End Sub
  244. Sub Job_Fail(jobId, code, message)
  245. Job_ErrCode = code
  246. Job_ErrMessage = message
  247. Job_MarkFailed jobId, code, message
  248. End Sub
  249. Function Job_HeadingOrNull(h)
  250. If Len("" & h) = 0 Then
  251. Job_HeadingOrNull = Null
  252. Else
  253. Job_HeadingOrNull = "" & h
  254. End If
  255. End Function
  256. ' Worker pass: claims and processes up to maxJobs due jobs (oldest first). Returns "<done> <failed>" counts.
  257. Function Job_ProcessDue(maxJobs)
  258. Dim rs, ids, i, done, failed, info, tenant, principal, active, saveT, saveP
  259. done = 0
  260. failed = 0
  261. ids = ""
  262. Set rs = DAL().Query("SELECT id FROM jobs WHERE payload IS NOT NULL AND (state = 'queued' OR (state = 'running' AND updated_at < ?) OR " & _
  263. "(state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & ")) ORDER BY created_at LIMIT " & CLng(maxJobs), Job_StaleBefore())
  264. Do While Not rs.EOF
  265. ids = ids & rs(0) & vbLf
  266. rs.MoveNext
  267. Loop
  268. rs.Close
  269. ids = Split(ids, vbLf)
  270. saveT = Api_TenantId
  271. saveP = Api_PrincipalId
  272. For i = 0 To UBound(ids) - 1
  273. If Job_Claim(ids(i)) Then
  274. 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))
  275. tenant = ""
  276. principal = ""
  277. active = ""
  278. If Not rs.EOF Then
  279. tenant = "" & rs(0)
  280. principal = "" & rs(1)
  281. active = "" & rs(2)
  282. End If
  283. rs.Close
  284. If active <> "active" Then
  285. Job_MarkFailed ids(i), "forbidden", "The submitter is no longer active."
  286. failed = failed + 1
  287. Else
  288. Api_TenantId = tenant
  289. Api_PrincipalId = principal
  290. If Job_RunIngest(ids(i), "", "") Then
  291. done = done + 1
  292. Emb_AfterWrite tenant, 64
  293. Else
  294. failed = failed + 1
  295. End If
  296. End If
  297. End If
  298. Next
  299. Api_TenantId = saveT
  300. Api_PrincipalId = saveP
  301. Job_ProcessDue = done & " " & failed
  302. End Function
  303. %>

Powered by TurnKey Linux.