您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

349 行
15KB

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

Powered by TurnKey Linux.