@zonastery/bursar 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maintenance.js","sourceRoot":"","sources":["../../src/storage/maintenance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AA2CtE,MAAM,2BAA2B,GAAG,CAAC;KAClC,MAAM,CAAC;IACN,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;IAC/D,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;CACzB,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,kFAAkF;AAClF,MAAM,OAAO,iBAAiB;IACC;IAA7B,YAA6B,UAAiC;QAAjC,eAAU,GAAV,UAAU,CAAuB;IAAG,CAAC;IAElE,KAAK,CAAC,OAAO,CAAC,UAAiC,EAAE;QAC/C,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1D,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC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GAAW;IACvE,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAK,KAAgB,GAAG,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,SAAS,CAAC,yBAAyB,GAAG,iCAAiC,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,KAAe,CAAC;AACzB,CAAC;AAED,SAAS,YAAY,CAAC,OAAgC,EAAE,GAAW;IACjE,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE,CAAC;QAC/B,MAAM,IAAI,SAAS,CAAC,yBAAyB,GAAG,oBAAoB,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CACxB,OAAgC,EAChC,GAAW,EACX,SAAY;IAEZ,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,CAAC;IACrD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,SAAS,CAAC,yBAAyB,GAAG,6BAA6B,CAAC,CAAC;IACjF,CAAC;IACD,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,KAAK,EAAgC,CAAC;AAC9D,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { persistedDiagnosticSummary } from \"../shared/diagnostics.js\";\nimport type { QueryFn } from \"../shared/postgres-types.js\";\n\nexport type MaintenanceTaskStatus = \"completed\" | \"skipped\" | \"unsupported\" | \"failed\";\nexport type MaintenanceRunStatus = \"completed\" | \"partial\" | \"failed\";\n\nexport interface MaintenanceTaskResult {\n status: MaintenanceTaskStatus;\n count: number;\n limit: number;\n hasMore: boolean;\n reason?: string;\n error?: string;\n}\n\nexport interface MaintenanceRunResult {\n status: MaintenanceRunStatus;\n count: number;\n hasMore: boolean;\n tasks: {\n expiredLeases: MaintenanceTaskResult;\n expiredCredits: MaintenanceTaskResult;\n duePlanChanges: MaintenanceTaskResult;\n pastDueGracePeriods: MaintenanceTaskResult;\n };\n}\n\nexport interface MaintenanceRunOptions {\n /** Maximum rows handled by each configurable tenant-scoped task. */\n limit?: number;\n /** Effective time used by time-sensitive tasks. Defaults to now. */\n now?: Date;\n}\n\nexport interface MaintenanceOperations {\n expireLeases?: (limit: number) => Promise<number>;\n expireCredits?: (limit: number) => Promise<number>;\n applyDuePlanChanges?: (limit: number) => Promise<number>;\n expirePastDueGracePeriods?: (now: Date) => Promise<number>;\n pastDueGracePeriodLimit?: number;\n pastDueGracePeriodsUnavailableReason?: string;\n}\n\nconst maintenanceRunOptionsSchema = z\n .object({\n limit: z.number().finite().int().min(1).max(1_000).default(100),\n now: z.date().optional(),\n })\n .strict();\n\n/** Host-invoked, tenant-scoped maintenance. This class never schedules itself. */\nexport class BursarMaintenance {\n constructor(private readonly operations: MaintenanceOperations) {}\n\n async runOnce(options: MaintenanceRunOptions = {}): Promise<MaintenanceRunResult> {\n const parsed = maintenanceRunOptionsSchema.parse(options);\n const now = parsed.now ?? new Date();\n const graceLimit = this.operations.pastDueGracePeriodLimit ?? 100;\n if (!Number.isInteger(graceLimit) || graceLimit < 1 || graceLimit > 1_000) {\n throw new RangeError(\"pastDueGracePeriodLimit must be an integer between 1 and 1000\");\n }\n\n const expiredLeases = await runTask(this.operations.expireLeases, parsed.limit, parsed.limit);\n const expiredCredits = await runTask(this.operations.expireCredits, parsed.limit, parsed.limit);\n const duePlanChanges = await runTask(\n this.operations.applyDuePlanChanges,\n parsed.limit,\n parsed.limit,\n );\n const pastDueGracePeriods = this.operations.expirePastDueGracePeriods\n ? await runTask(() => this.operations.expirePastDueGracePeriods!(now), graceLimit, graceLimit)\n : unavailableTask(graceLimit, this.operations.pastDueGracePeriodsUnavailableReason);\n\n const tasks = {\n expiredLeases,\n expiredCredits,\n duePlanChanges,\n pastDueGracePeriods,\n };\n const results = Object.values(tasks);\n const count = results.reduce((total, task) => total + task.count, 0);\n const applicable = results.filter(\n (task) => task.status === \"completed\" || task.status === \"failed\",\n );\n const failed = applicable.filter((task) => task.status === \"failed\").length;\n const status: MaintenanceRunStatus =\n applicable.length > 0 && failed === applicable.length\n ? \"failed\"\n : failed > 0\n ? \"partial\"\n : \"completed\";\n\n return {\n status,\n count,\n hasMore: results.some((task) => task.hasMore),\n tasks,\n };\n }\n}\n\nexport type StorageMaintenanceStatus = \"completed\" | \"busy\" | \"not_due\" | \"failed\";\n\nexport interface StorageMaintenanceCounts {\n usagePayloadsPurged: number;\n recordOnlyUsagePurged: number;\n billingPayloadsPurged: number;\n quotaUsageEventsPurged: number;\n quotaNotificationsPurged: number;\n terminalLeasesCompacted: number;\n usageRollupsPurged: number;\n outboxEventsPurged: number;\n}\n\nexport interface StorageMaintenanceResult {\n status: StorageMaintenanceStatus;\n count: number;\n hasMore: boolean;\n batchSize: number | null;\n counts: StorageMaintenanceCounts;\n lastMaintenanceAt?: string;\n nextMaintenanceAt?: string;\n error?: string;\n}\n\nexport interface OperatorMaintenanceRunOptions {\n /** Run only when due by default; force invokes the bounded pass immediately. */\n mode?: \"ifDue\" | \"force\";\n now?: Date;\n}\n\nexport type StoragePartition = \"usage_charge_payloads\" | \"billing_event_payloads\";\n\nexport interface PartitionMaintenanceResult {\n status: \"completed\" | \"busy\" | \"failed\";\n parentTable: StoragePartition;\n count: number;\n partitionsCreated: number;\n partitionsDropped: number;\n partitionLockTimeouts: number;\n defaultPartitionHasRows: boolean;\n hasMore: boolean;\n error?: string;\n}\n\nconst operatorMaintenanceRunOptionsSchema = z\n .object({\n mode: z.enum([\"ifDue\", \"force\"]).default(\"ifDue\"),\n now: z.date().optional(),\n })\n .strict();\n\nconst partitionSchema = z.enum([\"usage_charge_payloads\", \"billing_event_payloads\"]);\n\n/** Explicit operator-only storage and partition maintenance entry points. */\nexport class BursarOperatorMaintenance {\n constructor(private readonly query: QueryFn) {}\n\n async runOnce(options: OperatorMaintenanceRunOptions = {}): Promise<StorageMaintenanceResult> {\n const parsed = operatorMaintenanceRunOptionsSchema.parse(options);\n const functionName =\n parsed.mode === \"force\" ? \"run_storage_maintenance\" : \"maybe_run_storage_maintenance\";\n try {\n const payload = await callJsonFunction(this.query, functionName, [\n (parsed.now ?? new Date()).toISOString(),\n ]);\n return storageMaintenanceResult(payload);\n } catch (error) {\n return failedStorageMaintenance(error);\n }\n }\n\n async runPartitionOnce(\n parentTable: StoragePartition,\n options: Omit<OperatorMaintenanceRunOptions, \"mode\"> = {},\n ): Promise<PartitionMaintenanceResult> {\n const parent = partitionSchema.parse(parentTable);\n const parsed = operatorMaintenanceRunOptionsSchema.parse({ ...options, mode: \"force\" });\n try {\n const payload = await callJsonFunction(this.query, \"run_storage_partition_maintenance\", [\n parent,\n (parsed.now ?? new Date()).toISOString(),\n ]);\n return partitionMaintenanceResult(parent, payload);\n } catch (error) {\n return {\n status: \"failed\",\n parentTable: parent,\n count: 0,\n partitionsCreated: 0,\n partitionsDropped: 0,\n partitionLockTimeouts: 0,\n defaultPartitionHasRows: false,\n hasMore: true,\n error: persistedDiagnosticSummary(error, \"partition_maintenance_failed\"),\n };\n }\n }\n}\n\nasync function runTask(\n operation: ((limit: number) => Promise<number>) | undefined,\n operationLimit: number,\n reportedLimit: number,\n): Promise<MaintenanceTaskResult> {\n if (!operation) return unavailableTask(reportedLimit);\n try {\n const count = await operation(operationLimit);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new TypeError(\"maintenance task returned an invalid count\");\n }\n return {\n status: \"completed\",\n count,\n limit: reportedLimit,\n hasMore: count === reportedLimit,\n };\n } catch (error) {\n return {\n status: \"failed\",\n count: 0,\n limit: reportedLimit,\n hasMore: true,\n error: persistedDiagnosticSummary(error, \"maintenance_task_failed\"),\n };\n }\n}\n\nfunction unavailableTask(limit: number, reason?: string): MaintenanceTaskResult {\n return {\n status: reason ? \"skipped\" : \"unsupported\",\n count: 0,\n limit,\n hasMore: false,\n ...(reason ? { reason } : {}),\n };\n}\n\nasync function callJsonFunction(\n query: QueryFn,\n functionName:\n | \"run_storage_maintenance\"\n | \"maybe_run_storage_maintenance\"\n | \"run_storage_partition_maintenance\",\n params: unknown[],\n): Promise<Record<string, unknown>> {\n const placeholders = params.map((_, index) => `$${index + 1}`).join(\", \");\n const rows = await query(\n `SELECT bursar.${functionName}(${placeholders}) AS maintenance_result`,\n params,\n );\n const row = rows[0];\n if (!isRecord(row)) throw new TypeError(\"maintenance RPC returned no result\");\n const raw = row.maintenance_result;\n if (isRecord(raw)) return raw;\n if (typeof raw === \"string\") {\n const parsed: unknown = JSON.parse(raw);\n if (isRecord(parsed)) return parsed;\n }\n throw new TypeError(\"maintenance RPC returned a malformed result\");\n}\n\nfunction storageMaintenanceResult(payload: Record<string, unknown>): StorageMaintenanceResult {\n const status = payload.status;\n if (status === \"busy\") {\n return { ...emptyStorageMaintenanceCounts(), status, hasMore: true };\n }\n if (status === \"not_due\") {\n return {\n ...emptyStorageMaintenanceCounts(),\n status,\n hasMore: false,\n ...optionalTimestamp(payload, \"last_maintenance_at\", \"lastMaintenanceAt\"),\n ...optionalTimestamp(payload, \"next_maintenance_at\", \"nextMaintenanceAt\"),\n };\n }\n if (status !== \"completed\") throw new TypeError(\"maintenance RPC returned an unknown status\");\n const counts: StorageMaintenanceCounts = {\n usagePayloadsPurged: nonNegativeInteger(payload, \"usage_payloads_purged\"),\n recordOnlyUsagePurged: nonNegativeInteger(payload, \"record_only_usage_purged\"),\n billingPayloadsPurged: nonNegativeInteger(payload, \"billing_payloads_purged\"),\n quotaUsageEventsPurged: nonNegativeInteger(payload, \"quota_usage_events_purged\"),\n quotaNotificationsPurged: nonNegativeInteger(payload, \"quota_notifications_purged\"),\n terminalLeasesCompacted: nonNegativeInteger(payload, \"terminal_leases_compacted\"),\n usageRollupsPurged: nonNegativeInteger(payload, \"usage_rollups_purged\"),\n outboxEventsPurged: nonNegativeInteger(payload, \"outbox_events_purged\"),\n };\n return {\n status,\n count: Object.values(counts).reduce((total, count) => total + count, 0),\n hasMore: booleanField(payload, \"has_more\"),\n batchSize: nonNegativeInteger(payload, \"batch_size\"),\n counts,\n };\n}\n\nfunction partitionMaintenanceResult(\n parentTable: StoragePartition,\n payload: Record<string, unknown>,\n): PartitionMaintenanceResult {\n if (payload.status === \"busy\") {\n return {\n status: \"busy\",\n parentTable,\n count: 0,\n partitionsCreated: 0,\n partitionsDropped: 0,\n partitionLockTimeouts: 0,\n defaultPartitionHasRows: false,\n hasMore: true,\n };\n }\n if (payload.status !== \"completed\" || payload.parent_table !== parentTable) {\n throw new TypeError(\"partition maintenance RPC returned a malformed result\");\n }\n const partitionsCreated = nonNegativeInteger(payload, \"partitions_created\");\n const partitionsDropped = nonNegativeInteger(payload, \"partitions_dropped\");\n const partitionLockTimeouts = nonNegativeInteger(payload, \"partition_lock_timeouts\");\n return {\n status: \"completed\",\n parentTable,\n count: partitionsCreated + partitionsDropped,\n partitionsCreated,\n partitionsDropped,\n partitionLockTimeouts,\n defaultPartitionHasRows: booleanField(payload, \"default_partition_has_rows\"),\n hasMore: booleanField(payload, \"has_more\"),\n };\n}\n\nfunction failedStorageMaintenance(error: unknown): StorageMaintenanceResult {\n return {\n ...emptyStorageMaintenanceCounts(),\n status: \"failed\",\n hasMore: true,\n error: persistedDiagnosticSummary(error, \"storage_maintenance_failed\"),\n };\n}\n\nfunction emptyStorageMaintenanceCounts(): Omit<\n StorageMaintenanceResult,\n \"status\" | \"hasMore\" | \"error\"\n> {\n return {\n count: 0,\n batchSize: null,\n counts: {\n usagePayloadsPurged: 0,\n recordOnlyUsagePurged: 0,\n billingPayloadsPurged: 0,\n quotaUsageEventsPurged: 0,\n quotaNotificationsPurged: 0,\n terminalLeasesCompacted: 0,\n usageRollupsPurged: 0,\n outboxEventsPurged: 0,\n },\n };\n}\n\nfunction nonNegativeInteger(payload: Record<string, unknown>, key: string): number {\n const value = payload[key];\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new TypeError(`maintenance RPC field ${key} must be a non-negative integer`);\n }\n return value as number;\n}\n\nfunction booleanField(payload: Record<string, unknown>, key: string): boolean {\n const value = payload[key];\n if (typeof value !== \"boolean\") {\n throw new TypeError(`maintenance RPC field ${key} must be a boolean`);\n }\n return value;\n}\n\nfunction optionalTimestamp<K extends \"lastMaintenanceAt\" | \"nextMaintenanceAt\">(\n payload: Record<string, unknown>,\n key: string,\n outputKey: K,\n): Partial<Record<K, string>> {\n const value = payload[key];\n if (value === undefined || value === null) return {};\n if (typeof value !== \"string\") {\n throw new TypeError(`maintenance RPC field ${key} must be a timestamp string`);\n }\n return { [outputKey]: value } as Partial<Record<K, string>>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"]}
@@ -1,4 +1,17 @@
1
1
  import type { OutboxHandler, OutboxStore } from "./ports.js";
2
+ export type OutboxEventOutcomeStatus = "delivered" | "delivery_failed" | "claim_lost";
3
+ export type OutboxClaimLossPhase = "heartbeat" | "complete" | "fail";
4
+ export interface OutboxEventOutcome {
5
+ topic: string;
6
+ attemptCount: number;
7
+ status: OutboxEventOutcomeStatus;
8
+ /** Persistence-safe diagnostic summary; never a raw exception message. */
9
+ summary: string | null;
10
+ durationMs: number;
11
+ retryDelaySeconds: number | null;
12
+ deadLettered: boolean;
13
+ claimLossPhase: OutboxClaimLossPhase | null;
14
+ }
2
15
  export interface OutboxWorkerOptions {
3
16
  batchSize?: number;
4
17
  concurrency?: number;
@@ -8,11 +21,14 @@ export interface OutboxWorkerOptions {
8
21
  maxRetryDelaySeconds?: number;
9
22
  attemptLimit?: number;
10
23
  onError?: (error: unknown) => void | Promise<void>;
24
+ onEventOutcome?: (outcome: OutboxEventOutcome) => void | Promise<void>;
11
25
  }
12
26
  export interface OutboxRunResult {
13
27
  claimed: number;
14
28
  delivered: number;
15
29
  failed: number;
30
+ /** Events that lost or could not prove ownership. */
31
+ claimLost: number;
16
32
  }
17
33
  /**
18
34
  * Generic leased-outbox dispatcher.
@@ -35,7 +51,11 @@ export declare class OutboxWorker {
35
51
  runOnce(): Promise<OutboxRunResult>;
36
52
  private schedule;
37
53
  private reportError;
54
+ private reportOutcome;
38
55
  private dispatchOnce;
39
56
  private dispatchEvent;
57
+ private failDelivery;
58
+ private claimLost;
59
+ private startHeartbeat;
40
60
  }
41
61
  //# sourceMappingURL=outbox-worker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-worker.d.ts","sourceRoot":"","sources":["../../src/storage/outbox-worker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE1E,MAAM,WAAW,mBAAmB;IAClC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;CAChB;AA2BD;;;;;GAKG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,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a;YASP,YAAY;YA8BZ,aAAa;YAmDb,YAAY;IAoC1B,OAAO,CAAC,SAAS;IAmBjB,OAAO,CAAC,cAAc;CA6CvB"}
@@ -1,11 +1,26 @@
1
- import { boundedDiagnosticMessage } from "../shared/diagnostics.js";
2
- function integerOption(value, fallback, name, minimum, maximum) {
3
- const normalized = value ?? fallback;
4
- if (!Number.isInteger(normalized) || normalized < minimum || normalized > maximum) {
5
- throw new RangeError(`${name} must be an integer between ${minimum} and ${maximum}`);
6
- }
7
- return normalized;
8
- }
1
+ import { z } from "zod";
2
+ import { persistedDiagnosticSummary } from "../shared/diagnostics.js";
3
+ const outboxWorkerOptionsSchema = z
4
+ .object({
5
+ batchSize: z.number().finite().int().min(1).max(1_000).default(100),
6
+ concurrency: z.number().finite().int().min(1).max(100).default(4),
7
+ leaseSeconds: z.number().finite().int().min(1).max(3_600).default(60),
8
+ pollIntervalMs: z.number().finite().int().min(10).max(3_600_000).default(1_000),
9
+ retryDelaySeconds: z.number().finite().int().min(1).max(86_400).default(30),
10
+ maxRetryDelaySeconds: z.number().finite().int().min(1).max(86_400).default(3_600),
11
+ attemptLimit: z.number().finite().int().min(1).max(100).default(10),
12
+ onError: z
13
+ .custom((value) => typeof value === "function", "onError must be a function")
14
+ .optional(),
15
+ onEventOutcome: z
16
+ .custom((value) => typeof value === "function", "onEventOutcome must be a function")
17
+ .optional(),
18
+ })
19
+ .strict()
20
+ .refine((options) => options.maxRetryDelaySeconds >= options.retryDelaySeconds, {
21
+ path: ["maxRetryDelaySeconds"],
22
+ message: "must be at least retryDelaySeconds",
23
+ });
9
24
  /**
10
25
  * Generic leased-outbox dispatcher.
11
26
  *
@@ -24,9 +39,10 @@ export class OutboxWorker {
24
39
  constructor(store, handlers, options = {}) {
25
40
  if (handlers.length === 0)
26
41
  throw new TypeError("OutboxWorker requires at least one handler");
27
- if (options.onError !== undefined && typeof options.onError !== "function") {
28
- throw new TypeError("onError must be a function");
42
+ if (typeof store.renew !== "function") {
43
+ throw new TypeError("OutboxWorker store must support claim renewal");
29
44
  }
45
+ const parsedOptions = outboxWorkerOptionsSchema.parse(options);
30
46
  this.store = store;
31
47
  for (const handler of handlers) {
32
48
  if (handler.topics.length === 0) {
@@ -42,18 +58,10 @@ export class OutboxWorker {
42
58
  }
43
59
  this.topics = [...this.handlers.keys()].sort();
44
60
  this.options = {
45
- batchSize: integerOption(options.batchSize, 100, "batchSize", 1, 1_000),
46
- concurrency: integerOption(options.concurrency, 4, "concurrency", 1, 100),
47
- leaseSeconds: integerOption(options.leaseSeconds, 60, "leaseSeconds", 1, 3_600),
48
- pollIntervalMs: integerOption(options.pollIntervalMs, 1_000, "pollIntervalMs", 10, 3_600_000),
49
- retryDelaySeconds: integerOption(options.retryDelaySeconds, 30, "retryDelaySeconds", 1, 86_400),
50
- maxRetryDelaySeconds: integerOption(options.maxRetryDelaySeconds, 3_600, "maxRetryDelaySeconds", 1, 86_400),
51
- attemptLimit: integerOption(options.attemptLimit, 10, "attemptLimit", 1, 1_000),
52
- onError: options.onError ?? null,
61
+ ...parsedOptions,
62
+ onError: parsedOptions.onError ?? null,
63
+ onEventOutcome: parsedOptions.onEventOutcome ?? null,
53
64
  };
54
- if (this.options.maxRetryDelaySeconds < this.options.retryDelaySeconds) {
55
- throw new RangeError("maxRetryDelaySeconds must be at least retryDelaySeconds");
56
- }
57
65
  }
58
66
  async start() {
59
67
  if (this.started)
@@ -103,44 +111,166 @@ export class OutboxWorker {
103
111
  // Observability callbacks must never stop the delivery loop.
104
112
  }
105
113
  }
114
+ reportOutcome(outcome) {
115
+ try {
116
+ const result = this.options.onEventOutcome?.(outcome);
117
+ if (result)
118
+ void Promise.resolve(result).catch(() => { });
119
+ }
120
+ catch {
121
+ // Per-event observers must never stop this or a later delivery.
122
+ }
123
+ }
106
124
  async dispatchOnce() {
107
- const events = await this.store.claim(this.topics, this.options.batchSize, this.options.leaseSeconds);
108
- const result = { claimed: events.length, delivered: 0, failed: 0 };
109
- let cursor = 0;
110
- const consume = async () => {
111
- while (cursor < events.length) {
112
- const event = events[cursor++];
113
- if (!event)
114
- return;
115
- const delivered = await this.dispatchEvent(event);
116
- if (delivered)
125
+ const result = { claimed: 0, delivered: 0, failed: 0, claimLost: 0 };
126
+ let remainingBudget = this.options.batchSize;
127
+ while (remainingBudget > 0) {
128
+ const availableSlots = Math.min(this.options.concurrency, remainingBudget);
129
+ const events = await this.store.claim(this.topics, availableSlots, this.options.leaseSeconds);
130
+ if (events.length === 0)
131
+ break;
132
+ if (events.length > availableSlots) {
133
+ throw new Error(`Outbox store returned ${events.length} events for ${availableSlots} available slots`);
134
+ }
135
+ result.claimed += events.length;
136
+ remainingBudget -= events.length;
137
+ const outcomes = await Promise.all(events.map((event) => this.dispatchEvent(event)));
138
+ for (const outcome of outcomes) {
139
+ if (outcome === "delivered")
117
140
  result.delivered += 1;
118
- else
141
+ else {
119
142
  result.failed += 1;
143
+ if (outcome === "claim_lost")
144
+ result.claimLost += 1;
145
+ }
120
146
  }
121
- };
122
- const consumers = Math.min(this.options.concurrency, events.length);
123
- await Promise.all(Array.from({ length: consumers }, () => consume()));
147
+ if (events.length < availableSlots)
148
+ break;
149
+ }
124
150
  return result;
125
151
  }
126
152
  async dispatchEvent(event) {
153
+ const startedAt = Date.now();
154
+ const heartbeat = this.startHeartbeat(event);
155
+ let deliveryFailure = null;
127
156
  try {
128
157
  const handlers = this.handlers.get(event.topic);
129
158
  if (!handlers?.length)
130
159
  throw new Error(`No handler for outbox topic ${event.topic}`);
131
160
  await Promise.all(handlers.map((handler) => handler.handle(event)));
161
+ }
162
+ catch (error) {
163
+ deliveryFailure = { error };
164
+ }
165
+ const heartbeatResult = await heartbeat.stop();
166
+ if (heartbeatResult.claimLost) {
167
+ return this.claimLost(event, "heartbeat", heartbeatResult.summary, startedAt);
168
+ }
169
+ if (deliveryFailure) {
170
+ return this.failDelivery(event, deliveryFailure.error, startedAt);
171
+ }
172
+ try {
132
173
  if (!(await this.store.complete(event))) {
133
- throw new Error(`Lost outbox claim for event ${event.eventId}`);
174
+ return this.claimLost(event, "complete", persistedDiagnosticSummary(null, "outbox_claim_lost"), startedAt);
134
175
  }
135
- return true;
136
176
  }
137
177
  catch (error) {
138
- const message = boundedDiagnosticMessage(error instanceof Error ? `${error.name}: ${error.message}` : error, "outbox_delivery_failed");
139
- const exponentialDelay = this.options.retryDelaySeconds * 2 ** Math.max(event.attemptCount - 1, 0);
140
- const retryDelay = Math.min(exponentialDelay, this.options.maxRetryDelaySeconds);
141
- await this.store.fail(event, message, retryDelay, this.options.attemptLimit);
142
- return false;
178
+ return this.claimLost(event, "complete", persistedDiagnosticSummary(error, "outbox_claim_lost"), startedAt);
179
+ }
180
+ this.reportOutcome({
181
+ topic: event.topic,
182
+ attemptCount: event.attemptCount,
183
+ status: "delivered",
184
+ summary: null,
185
+ durationMs: Math.max(Date.now() - startedAt, 0),
186
+ retryDelaySeconds: null,
187
+ deadLettered: false,
188
+ claimLossPhase: null,
189
+ });
190
+ return "delivered";
191
+ }
192
+ async failDelivery(event, error, startedAt) {
193
+ const summary = persistedDiagnosticSummary(error, "outbox_delivery_failed");
194
+ const exponentialDelay = this.options.retryDelaySeconds * 2 ** Math.max(event.attemptCount - 1, 0);
195
+ const retryDelay = Math.min(exponentialDelay, this.options.maxRetryDelaySeconds);
196
+ try {
197
+ if (!(await this.store.fail(event, summary, retryDelay, this.options.attemptLimit))) {
198
+ return this.claimLost(event, "fail", summary, startedAt);
199
+ }
200
+ }
201
+ catch (failureError) {
202
+ return this.claimLost(event, "fail", persistedDiagnosticSummary(failureError, "outbox_claim_lost"), startedAt);
143
203
  }
204
+ this.reportOutcome({
205
+ topic: event.topic,
206
+ attemptCount: event.attemptCount,
207
+ status: "delivery_failed",
208
+ summary,
209
+ durationMs: Math.max(Date.now() - startedAt, 0),
210
+ retryDelaySeconds: retryDelay,
211
+ deadLettered: event.attemptCount >= this.options.attemptLimit,
212
+ claimLossPhase: null,
213
+ });
214
+ return "delivery_failed";
215
+ }
216
+ claimLost(event, phase, summary, startedAt) {
217
+ this.reportOutcome({
218
+ topic: event.topic,
219
+ attemptCount: event.attemptCount,
220
+ status: "claim_lost",
221
+ summary: summary ?? persistedDiagnosticSummary(null, "outbox_claim_lost"),
222
+ durationMs: Math.max(Date.now() - startedAt, 0),
223
+ retryDelaySeconds: null,
224
+ deadLettered: false,
225
+ claimLossPhase: phase,
226
+ });
227
+ return "claim_lost";
228
+ }
229
+ startHeartbeat(event) {
230
+ const intervalMs = Math.max(100, Math.floor((this.options.leaseSeconds * 1_000) / 3));
231
+ let timer = null;
232
+ let pending = null;
233
+ let stopped = false;
234
+ let claimLost = false;
235
+ let heartbeatSummary = null;
236
+ const loseClaim = (error) => {
237
+ claimLost = true;
238
+ heartbeatSummary = persistedDiagnosticSummary(error, "outbox_claim_lost");
239
+ if (timer)
240
+ clearTimeout(timer);
241
+ timer = null;
242
+ };
243
+ const schedule = () => {
244
+ if (stopped || claimLost)
245
+ return;
246
+ timer = setTimeout(() => {
247
+ timer = null;
248
+ pending = Promise.resolve()
249
+ .then(async () => {
250
+ if (!(await this.store.renew(event, this.options.leaseSeconds))) {
251
+ loseClaim("outbox_claim_lost");
252
+ }
253
+ })
254
+ .catch((error) => loseClaim(error))
255
+ .finally(() => {
256
+ pending = null;
257
+ schedule();
258
+ });
259
+ }, intervalMs);
260
+ timer.unref?.();
261
+ };
262
+ schedule();
263
+ return {
264
+ stop: async () => {
265
+ stopped = true;
266
+ if (timer)
267
+ clearTimeout(timer);
268
+ timer = null;
269
+ if (pending)
270
+ await pending;
271
+ return { claimLost, summary: heartbeatSummary };
272
+ },
273
+ };
144
274
  }
145
275
  }
146
276
  //# sourceMappingURL=outbox-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-worker.js","sourceRoot":"","sources":["../../src/storage/outbox-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AA+BpE,SAAS,aAAa,CACpB,KAAyB,EACzB,QAAg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EAClE,wBAAwB,CACzB,CAAC;YACF,MAAM,gBAAgB,GACpB,IAAI,CAAC,OAAO,CAAC,iBAAiB,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;YAC5E,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC;YACjF,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC7E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF","sourcesContent":["import { boundedDiagnosticMessage } from \"../shared/diagnostics.js\";\nimport type { OutboxEvent, OutboxHandler, OutboxStore } from \"./ports.js\";\n\nexport interface OutboxWorkerOptions {\n batchSize?: number;\n concurrency?: number;\n leaseSeconds?: number;\n pollIntervalMs?: number;\n retryDelaySeconds?: number;\n maxRetryDelaySeconds?: number;\n attemptLimit?: number;\n onError?: (error: unknown) => void | Promise<void>;\n}\n\nexport interface OutboxRunResult {\n claimed: number;\n delivered: number;\n failed: number;\n}\n\ninterface NormalizedWorkerOptions {\n batchSize: number;\n concurrency: number;\n leaseSeconds: number;\n pollIntervalMs: number;\n retryDelaySeconds: number;\n maxRetryDelaySeconds: number;\n attemptLimit: number;\n onError: ((error: unknown) => void | Promise<void>) | null;\n}\n\nfunction integerOption(\n value: number | undefined,\n fallback: number,\n name: string,\n minimum: number,\n maximum: number,\n): number {\n const normalized = value ?? fallback;\n if (!Number.isInteger(normalized) || normalized < minimum || normalized > maximum) {\n throw new RangeError(`${name} must be an integer between ${minimum} and ${maximum}`);\n }\n return normalized;\n}\n\n/**\n * Generic leased-outbox dispatcher.\n *\n * Handlers must be idempotent because a process can stop after the external\n * write succeeds but before PostgreSQL records the acknowledgement.\n */\nexport class OutboxWorker {\n private readonly store: OutboxStore;\n private readonly handlers = new Map<string, OutboxHandler[]>();\n private readonly topics: string[];\n private readonly options: NormalizedWorkerOptions;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private activeRun: Promise<OutboxRunResult> | null = null;\n private started = false;\n private stopped = false;\n\n constructor(\n store: OutboxStore,\n handlers: readonly OutboxHandler[],\n options: OutboxWorkerOptions = {},\n ) {\n if (handlers.length === 0) throw new TypeError(\"OutboxWorker requires at least one handler\");\n if (options.onError !== undefined && typeof options.onError !== \"function\") {\n throw new TypeError(\"onError must be a function\");\n }\n this.store = store;\n for (const handler of handlers) {\n if (handler.topics.length === 0) {\n throw new TypeError(\"Outbox handlers must declare at least one topic\");\n }\n for (const topic of handler.topics) {\n if (!topic.trim()) throw new TypeError(\"Outbox topics must not be empty\");\n const topicHandlers = this.handlers.get(topic) ?? [];\n topicHandlers.push(handler);\n this.handlers.set(topic, topicHandlers);\n }\n }\n this.topics = [...this.handlers.keys()].sort();\n this.options = {\n batchSize: integerOption(options.batchSize, 100, \"batchSize\", 1, 1_000),\n concurrency: integerOption(options.concurrency, 4, \"concurrency\", 1, 100),\n leaseSeconds: integerOption(options.leaseSeconds, 60, \"leaseSeconds\", 1, 3_600),\n pollIntervalMs: integerOption(options.pollIntervalMs, 1_000, \"pollIntervalMs\", 10, 3_600_000),\n retryDelaySeconds: integerOption(\n options.retryDelaySeconds,\n 30,\n \"retryDelaySeconds\",\n 1,\n 86_400,\n ),\n maxRetryDelaySeconds: integerOption(\n options.maxRetryDelaySeconds,\n 3_600,\n \"maxRetryDelaySeconds\",\n 1,\n 86_400,\n ),\n attemptLimit: integerOption(options.attemptLimit, 10, \"attemptLimit\", 1, 1_000),\n onError: options.onError ?? null,\n };\n if (this.options.maxRetryDelaySeconds < this.options.retryDelaySeconds) {\n throw new RangeError(\"maxRetryDelaySeconds must be at least retryDelaySeconds\");\n }\n }\n\n async start(): Promise<void> {\n if (this.started) return;\n if (this.stopped) throw new Error(\"OutboxWorker cannot be restarted after stop\");\n this.started = true;\n this.schedule(0);\n }\n\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n if (this.activeRun) await this.activeRun;\n }\n\n runOnce(): Promise<OutboxRunResult> {\n if (this.stopped) throw new Error(\"OutboxWorker has been stopped\");\n if (!this.activeRun) {\n this.activeRun = this.dispatchOnce().finally(() => {\n this.activeRun = null;\n });\n }\n return this.activeRun;\n }\n\n private schedule(delayMs: number): void {\n if (this.stopped) return;\n this.timer = setTimeout(() => {\n void this.runOnce()\n .catch((error: unknown) => this.reportError(error))\n .finally(() => this.schedule(this.options.pollIntervalMs));\n }, delayMs);\n this.timer.unref?.();\n }\n\n private reportError(error: unknown): void {\n try {\n const result = this.options.onError?.(error);\n if (result) void Promise.resolve(result).catch(() => {});\n } catch {\n // Observability callbacks must never stop the delivery loop.\n }\n }\n\n private async dispatchOnce(): Promise<OutboxRunResult> {\n const events = await this.store.claim(\n this.topics,\n this.options.batchSize,\n this.options.leaseSeconds,\n );\n const result: OutboxRunResult = { claimed: events.length, delivered: 0, failed: 0 };\n let cursor = 0;\n const consume = async (): Promise<void> => {\n while (cursor < events.length) {\n const event = events[cursor++];\n if (!event) return;\n const delivered = await this.dispatchEvent(event);\n if (delivered) result.delivered += 1;\n else result.failed += 1;\n }\n };\n const consumers = Math.min(this.options.concurrency, events.length);\n await Promise.all(Array.from({ length: consumers }, () => consume()));\n return result;\n }\n\n private async dispatchEvent(event: OutboxEvent): Promise<boolean> {\n try {\n const handlers = this.handlers.get(event.topic);\n if (!handlers?.length) throw new Error(`No handler for outbox topic ${event.topic}`);\n await Promise.all(handlers.map((handler) => handler.handle(event)));\n if (!(await this.store.complete(event))) {\n throw new Error(`Lost outbox claim for event ${event.eventId}`);\n }\n return true;\n } catch (error) {\n const message = boundedDiagnosticMessage(\n error instanceof Error ? `${error.name}: ${error.message}` : error,\n \"outbox_delivery_failed\",\n );\n const exponentialDelay =\n this.options.retryDelaySeconds * 2 ** Math.max(event.attemptCount - 1, 0);\n const retryDelay = Math.min(exponentialDelay, this.options.maxRetryDelaySeconds);\n await this.store.fail(event, message, retryDelay, this.options.attemptLimit);\n return false;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"outbox-worker.js","sourceRoot":"","sources":["../../src/storage/outbox-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AAsCtE,MAAM,yBAAyB,GAAG,CAAC;KAChC,MAAM,CAAC;IACN,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;IACnE,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;IACjE,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;IACrE,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;IAC/E,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;IAC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AAC;QACf,CAAC,CAAC;QAEF,MAAM,QAAQ,GAAG,GAAS,EAAE;YAC1B,IAAI,OAAO,IAAI,SAAS;gBAAE,OAAO;YACjC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBACtB,KAAK,GAAG,IAAI,CAAC;gBACb,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE;qBACxB,IAAI,CAAC,KAAK,IAAI,EAAE;oBACf,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC;wBAChE,SAAS,CAAC,mBAAmB,CAAC,CAAC;oBACjC,CAAC;gBACH,CAAC,CAAC;qBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;qBAC3C,OAAO,CAAC,GAAG,EAAE;oBACZ,OAAO,GAAG,IAAI,CAAC;oBACf,QAAQ,EAAE,CAAC;gBACb,CAAC,CAAC,CAAC;YACP,CAAC,EAAE,UAAU,CAAC,CAAC;YACf,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;QAClB,CAAC,CAAC;QAEF,QAAQ,EAAE,CAAC;QACX,OAAO;YACL,IAAI,EAAE,KAAK,IAAI,EAAE;gBACf,OAAO,GAAG,IAAI,CAAC;gBACf,IAAI,KAAK;oBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;gBAC/B,KAAK,GAAG,IAAI,CAAC;gBACb,IAAI,OAAO;oBAAE,MAAM,OAAO,CAAC;gBAC3B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC;YAClD,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\n\nimport { persistedDiagnosticSummary } from \"../shared/diagnostics.js\";\nimport type { OutboxEvent, OutboxHandler, OutboxStore } from \"./ports.js\";\n\nexport type OutboxEventOutcomeStatus = \"delivered\" | \"delivery_failed\" | \"claim_lost\";\nexport type OutboxClaimLossPhase = \"heartbeat\" | \"complete\" | \"fail\";\n\nexport interface OutboxEventOutcome {\n topic: string;\n attemptCount: number;\n status: OutboxEventOutcomeStatus;\n /** Persistence-safe diagnostic summary; never a raw exception message. */\n summary: string | null;\n durationMs: number;\n retryDelaySeconds: number | null;\n deadLettered: boolean;\n claimLossPhase: OutboxClaimLossPhase | null;\n}\n\nexport interface OutboxWorkerOptions {\n batchSize?: number;\n concurrency?: number;\n leaseSeconds?: number;\n pollIntervalMs?: number;\n retryDelaySeconds?: number;\n maxRetryDelaySeconds?: number;\n attemptLimit?: number;\n onError?: (error: unknown) => void | Promise<void>;\n onEventOutcome?: (outcome: OutboxEventOutcome) => void | Promise<void>;\n}\n\nexport interface OutboxRunResult {\n claimed: number;\n delivered: number;\n failed: number;\n /** Events that lost or could not prove ownership. */\n claimLost: number;\n}\n\nconst outboxWorkerOptionsSchema = z\n .object({\n batchSize: z.number().finite().int().min(1).max(1_000).default(100),\n concurrency: z.number().finite().int().min(1).max(100).default(4),\n leaseSeconds: z.number().finite().int().min(1).max(3_600).default(60),\n pollIntervalMs: z.number().finite().int().min(10).max(3_600_000).default(1_000),\n retryDelaySeconds: z.number().finite().int().min(1).max(86_400).default(30),\n maxRetryDelaySeconds: z.number().finite().int().min(1).max(86_400).default(3_600),\n attemptLimit: z.number().finite().int().min(1).max(100).default(10),\n onError: z\n .custom<(error: unknown) => void | Promise<void>>(\n (value) => typeof value === \"function\",\n \"onError must be a function\",\n )\n .optional(),\n onEventOutcome: z\n .custom<(outcome: OutboxEventOutcome) => void | Promise<void>>(\n (value) => typeof value === \"function\",\n \"onEventOutcome must be a function\",\n )\n .optional(),\n })\n .strict()\n .refine((options) => options.maxRetryDelaySeconds >= options.retryDelaySeconds, {\n path: [\"maxRetryDelaySeconds\"],\n message: \"must be at least retryDelaySeconds\",\n });\n\ntype NormalizedWorkerOptions = Omit<\n z.infer<typeof outboxWorkerOptionsSchema>,\n \"onError\" | \"onEventOutcome\"\n> & {\n onError: ((error: unknown) => void | Promise<void>) | null;\n onEventOutcome: ((outcome: OutboxEventOutcome) => void | Promise<void>) | null;\n};\n\ninterface ClaimHeartbeatResult {\n claimLost: boolean;\n summary: string | null;\n}\n\ninterface ClaimHeartbeat {\n stop(): Promise<ClaimHeartbeatResult>;\n}\n\n/**\n * Generic leased-outbox dispatcher.\n *\n * Handlers must be idempotent because a process can stop after the external\n * write succeeds but before PostgreSQL records the acknowledgement.\n */\nexport class OutboxWorker {\n private readonly store: OutboxStore;\n private readonly handlers = new Map<string, OutboxHandler[]>();\n private readonly topics: string[];\n private readonly options: NormalizedWorkerOptions;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private activeRun: Promise<OutboxRunResult> | null = null;\n private started = false;\n private stopped = false;\n\n constructor(\n store: OutboxStore,\n handlers: readonly OutboxHandler[],\n options: OutboxWorkerOptions = {},\n ) {\n if (handlers.length === 0) throw new TypeError(\"OutboxWorker requires at least one handler\");\n if (typeof store.renew !== \"function\") {\n throw new TypeError(\"OutboxWorker store must support claim renewal\");\n }\n const parsedOptions = outboxWorkerOptionsSchema.parse(options);\n this.store = store;\n for (const handler of handlers) {\n if (handler.topics.length === 0) {\n throw new TypeError(\"Outbox handlers must declare at least one topic\");\n }\n for (const topic of handler.topics) {\n if (!topic.trim()) throw new TypeError(\"Outbox topics must not be empty\");\n const topicHandlers = this.handlers.get(topic) ?? [];\n topicHandlers.push(handler);\n this.handlers.set(topic, topicHandlers);\n }\n }\n this.topics = [...this.handlers.keys()].sort();\n this.options = {\n ...parsedOptions,\n onError: parsedOptions.onError ?? null,\n onEventOutcome: parsedOptions.onEventOutcome ?? null,\n };\n }\n\n async start(): Promise<void> {\n if (this.started) return;\n if (this.stopped) throw new Error(\"OutboxWorker cannot be restarted after stop\");\n this.started = true;\n this.schedule(0);\n }\n\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n if (this.activeRun) await this.activeRun;\n }\n\n runOnce(): Promise<OutboxRunResult> {\n if (this.stopped) throw new Error(\"OutboxWorker has been stopped\");\n if (!this.activeRun) {\n this.activeRun = this.dispatchOnce().finally(() => {\n this.activeRun = null;\n });\n }\n return this.activeRun;\n }\n\n private schedule(delayMs: number): void {\n if (this.stopped) return;\n this.timer = setTimeout(() => {\n void this.runOnce()\n .catch((error: unknown) => this.reportError(error))\n .finally(() => this.schedule(this.options.pollIntervalMs));\n }, delayMs);\n this.timer.unref?.();\n }\n\n private reportError(error: unknown): void {\n try {\n const result = this.options.onError?.(error);\n if (result) void Promise.resolve(result).catch(() => {});\n } catch {\n // Observability callbacks must never stop the delivery loop.\n }\n }\n\n private reportOutcome(outcome: OutboxEventOutcome): void {\n try {\n const result = this.options.onEventOutcome?.(outcome);\n if (result) void Promise.resolve(result).catch(() => {});\n } catch {\n // Per-event observers must never stop this or a later delivery.\n }\n }\n\n private async dispatchOnce(): Promise<OutboxRunResult> {\n const result: OutboxRunResult = { claimed: 0, delivered: 0, failed: 0, claimLost: 0 };\n let remainingBudget = this.options.batchSize;\n\n while (remainingBudget > 0) {\n const availableSlots = Math.min(this.options.concurrency, remainingBudget);\n const events = await this.store.claim(this.topics, availableSlots, this.options.leaseSeconds);\n if (events.length === 0) break;\n if (events.length > availableSlots) {\n throw new Error(\n `Outbox store returned ${events.length} events for ${availableSlots} available slots`,\n );\n }\n\n result.claimed += events.length;\n remainingBudget -= events.length;\n const outcomes = await Promise.all(events.map((event) => this.dispatchEvent(event)));\n for (const outcome of outcomes) {\n if (outcome === \"delivered\") result.delivered += 1;\n else {\n result.failed += 1;\n if (outcome === \"claim_lost\") result.claimLost += 1;\n }\n }\n if (events.length < availableSlots) break;\n }\n\n return result;\n }\n\n private async dispatchEvent(event: OutboxEvent): Promise<OutboxEventOutcomeStatus> {\n const startedAt = Date.now();\n const heartbeat = this.startHeartbeat(event);\n let deliveryFailure: { error: unknown } | null = null;\n try {\n const handlers = this.handlers.get(event.topic);\n if (!handlers?.length) throw new Error(`No handler for outbox topic ${event.topic}`);\n await Promise.all(handlers.map((handler) => handler.handle(event)));\n } catch (error) {\n deliveryFailure = { error };\n }\n\n const heartbeatResult = await heartbeat.stop();\n if (heartbeatResult.claimLost) {\n return this.claimLost(event, \"heartbeat\", heartbeatResult.summary, startedAt);\n }\n if (deliveryFailure) {\n return this.failDelivery(event, deliveryFailure.error, startedAt);\n }\n\n try {\n if (!(await this.store.complete(event))) {\n return this.claimLost(\n event,\n \"complete\",\n persistedDiagnosticSummary(null, \"outbox_claim_lost\"),\n startedAt,\n );\n }\n } catch (error) {\n return this.claimLost(\n event,\n \"complete\",\n persistedDiagnosticSummary(error, \"outbox_claim_lost\"),\n startedAt,\n );\n }\n\n this.reportOutcome({\n topic: event.topic,\n attemptCount: event.attemptCount,\n status: \"delivered\",\n summary: null,\n durationMs: Math.max(Date.now() - startedAt, 0),\n retryDelaySeconds: null,\n deadLettered: false,\n claimLossPhase: null,\n });\n return \"delivered\";\n }\n\n private async failDelivery(\n event: OutboxEvent,\n error: unknown,\n startedAt: number,\n ): Promise<OutboxEventOutcomeStatus> {\n const summary = persistedDiagnosticSummary(error, \"outbox_delivery_failed\");\n const exponentialDelay =\n this.options.retryDelaySeconds * 2 ** Math.max(event.attemptCount - 1, 0);\n const retryDelay = Math.min(exponentialDelay, this.options.maxRetryDelaySeconds);\n\n try {\n if (!(await this.store.fail(event, summary, retryDelay, this.options.attemptLimit))) {\n return this.claimLost(event, \"fail\", summary, startedAt);\n }\n } catch (failureError) {\n return this.claimLost(\n event,\n \"fail\",\n persistedDiagnosticSummary(failureError, \"outbox_claim_lost\"),\n startedAt,\n );\n }\n\n this.reportOutcome({\n topic: event.topic,\n attemptCount: event.attemptCount,\n status: \"delivery_failed\",\n summary,\n durationMs: Math.max(Date.now() - startedAt, 0),\n retryDelaySeconds: retryDelay,\n deadLettered: event.attemptCount >= this.options.attemptLimit,\n claimLossPhase: null,\n });\n return \"delivery_failed\";\n }\n\n private claimLost(\n event: OutboxEvent,\n phase: OutboxClaimLossPhase,\n summary: string | null,\n startedAt: number,\n ): OutboxEventOutcomeStatus {\n this.reportOutcome({\n topic: event.topic,\n attemptCount: event.attemptCount,\n status: \"claim_lost\",\n summary: summary ?? persistedDiagnosticSummary(null, \"outbox_claim_lost\"),\n durationMs: Math.max(Date.now() - startedAt, 0),\n retryDelaySeconds: null,\n deadLettered: false,\n claimLossPhase: phase,\n });\n return \"claim_lost\";\n }\n\n private startHeartbeat(event: OutboxEvent): ClaimHeartbeat {\n const intervalMs = Math.max(100, Math.floor((this.options.leaseSeconds * 1_000) / 3));\n let timer: ReturnType<typeof setTimeout> | null = null;\n let pending: Promise<void> | null = null;\n let stopped = false;\n let claimLost = false;\n let heartbeatSummary: string | null = null;\n\n const loseClaim = (error: unknown): void => {\n claimLost = true;\n heartbeatSummary = persistedDiagnosticSummary(error, \"outbox_claim_lost\");\n if (timer) clearTimeout(timer);\n timer = null;\n };\n\n const schedule = (): void => {\n if (stopped || claimLost) return;\n timer = setTimeout(() => {\n timer = null;\n pending = Promise.resolve()\n .then(async () => {\n if (!(await this.store.renew(event, this.options.leaseSeconds))) {\n loseClaim(\"outbox_claim_lost\");\n }\n })\n .catch((error: unknown) => loseClaim(error))\n .finally(() => {\n pending = null;\n schedule();\n });\n }, intervalMs);\n timer.unref?.();\n };\n\n schedule();\n return {\n stop: async () => {\n stopped = true;\n if (timer) clearTimeout(timer);\n timer = null;\n if (pending) await pending;\n return { claimLost, summary: heartbeatSummary };\n },\n };\n }\n}\n"]}
@@ -10,11 +10,50 @@ export interface OutboxEvent {
10
10
  attemptCount: number;
11
11
  createdAt: string;
12
12
  }
13
- export interface OutboxStore {
13
+ export interface OutboxClaimRenewalStore {
14
+ renew(event: OutboxEvent, leaseSeconds: number): Promise<boolean>;
15
+ }
16
+ export interface OutboxStore extends OutboxClaimRenewalStore {
14
17
  claim(topics: readonly string[], limit: number, leaseSeconds: number): Promise<OutboxEvent[]>;
15
18
  complete(event: OutboxEvent): Promise<boolean>;
16
19
  fail(event: OutboxEvent, error: string, retryDelaySeconds: number, attemptLimit: number): Promise<boolean>;
17
20
  }
21
+ export interface OutboxStats {
22
+ pendingCount: number;
23
+ processingCount: number;
24
+ deliveredCount: number;
25
+ deadLetterCount: number;
26
+ oldestPendingAt: string | null;
27
+ }
28
+ export interface OutboxDeadLetterCursor {
29
+ createdAt: string;
30
+ eventId: string;
31
+ }
32
+ export interface OutboxDeadLetter {
33
+ eventId: string;
34
+ tenantId: string;
35
+ topic: string;
36
+ aggregateType: string;
37
+ aggregateId: string;
38
+ payloadVersion: number;
39
+ attemptCount: number;
40
+ lastError: string | null;
41
+ createdAt: string;
42
+ updatedAt: string;
43
+ }
44
+ export interface OutboxDeadLetterListOptions {
45
+ limit?: number;
46
+ cursor?: OutboxDeadLetterCursor | null;
47
+ }
48
+ export interface OutboxDeadLetterPage {
49
+ items: OutboxDeadLetter[];
50
+ nextCursor: OutboxDeadLetterCursor | null;
51
+ }
52
+ export interface OutboxRecoveryStore extends OutboxStore {
53
+ stats(): Promise<OutboxStats>;
54
+ listDeadLetters(options?: OutboxDeadLetterListOptions): Promise<OutboxDeadLetterPage>;
55
+ requeue(eventId: string): Promise<boolean>;
56
+ }
18
57
  export interface OutboxHandler {
19
58
  readonly topics: readonly string[];
20
59
  handle(event: OutboxEvent): Promise<void>;
@@ -64,7 +103,10 @@ export interface BillingEventPayloadExport {
64
103
  }
65
104
  export interface UsageEventSink {
66
105
  initialize?(): Promise<void>;
106
+ /** Non-mutating compatibility check for a caller-managed projection schema. */
107
+ checkSchemaCompatibility?(): Promise<void>;
67
108
  writeUsage(event: UsageChargeExport, outboxEventId: string): Promise<void>;
109
+ writeUsageBatch?(entries: readonly (readonly [UsageChargeExport, string])[]): Promise<void>;
68
110
  }
69
111
  export interface BillingPayloadArchiveResult {
70
112
  key: string;
@@ -1 +1 @@
1
- {"version":3,"file":"ports.d.ts","sourceRoot":"","sources":["../../src/storage/ports.ts"],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CAAC,CAAC;IAChF,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAChC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ports.js","sourceRoot":"","sources":["../../src/storage/ports.ts"],"names":[],"mappings":"","sourcesContent":["export interface OutboxEvent {\n eventId: string;\n tenantId: string;\n topic: string;\n aggregateType: string;\n aggregateId: string;\n payloadVersion: number;\n payload: Record<string, unknown>;\n claimToken: string;\n attemptCount: number;\n createdAt: string;\n}\n\nexport interface OutboxStore {\n claim(topics: readonly string[], limit: number, leaseSeconds: number): Promise<OutboxEvent[]>;\n complete(event: OutboxEvent): Promise<boolean>;\n fail(\n event: OutboxEvent,\n error: string,\n retryDelaySeconds: number,\n attemptLimit: number,\n ): Promise<boolean>;\n}\n\nexport interface OutboxHandler {\n readonly topics: readonly string[];\n handle(event: OutboxEvent): Promise<void>;\n}\n\nexport interface UsageChargeExport {\n tenantId: string;\n chargeId: string;\n accountId: string;\n subjectId: string;\n operation: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: Record<string, unknown>;\n dimensions: Record<string, unknown>;\n metadata: Record<string, unknown>;\n requested: string;\n charged: string;\n allowanceRequested: string;\n allowanceCovered: string;\n billingDisposition: \"billable\" | \"record_only\";\n catalogRevisionId: string | null;\n planId: string | null;\n rateCardKey: string | null;\n pricingSnapshot: Record<string, unknown>;\n ledgerEntryId: string | null;\n correctionOfChargeId: string | null;\n idempotencyKey: string;\n requestDigest: string;\n eventAt: string;\n createdAt: string;\n}\n\nexport interface BillingEventPayloadExport {\n tenantId: string;\n eventId: string;\n provider: string;\n providerEnvironment: string;\n providerEventId: string;\n eventType: string;\n status: string;\n receivedAt: string;\n completedAt: string | null;\n envelope: Record<string, unknown> | null;\n objectKey: string | null;\n objectVersion: string | null;\n archivedAt: string | null;\n}\n\nexport interface UsageEventSink {\n initialize?(): Promise<void>;\n writeUsage(event: UsageChargeExport, outboxEventId: string): Promise<void>;\n}\n\nexport interface BillingPayloadArchiveResult {\n key: string;\n versionId: string | null;\n}\n\nexport interface BillingPayloadArchive {\n archive(event: BillingEventPayloadExport): Promise<BillingPayloadArchiveResult>;\n close?(): Promise<void> | void;\n}\n"]}
1
+ {"version":3,"file":"ports.js","sourceRoot":"","sources":["../../src/storage/ports.ts"],"names":[],"mappings":"","sourcesContent":["export interface OutboxEvent {\n eventId: string;\n tenantId: string;\n topic: string;\n aggregateType: string;\n aggregateId: string;\n payloadVersion: number;\n payload: Record<string, unknown>;\n claimToken: string;\n attemptCount: number;\n createdAt: string;\n}\n\nexport interface OutboxClaimRenewalStore {\n renew(event: OutboxEvent, leaseSeconds: number): Promise<boolean>;\n}\n\nexport interface OutboxStore extends OutboxClaimRenewalStore {\n claim(topics: readonly string[], limit: number, leaseSeconds: number): Promise<OutboxEvent[]>;\n complete(event: OutboxEvent): Promise<boolean>;\n fail(\n event: OutboxEvent,\n error: string,\n retryDelaySeconds: number,\n attemptLimit: number,\n ): Promise<boolean>;\n}\n\nexport interface OutboxStats {\n pendingCount: number;\n processingCount: number;\n deliveredCount: number;\n deadLetterCount: number;\n oldestPendingAt: string | null;\n}\n\nexport interface OutboxDeadLetterCursor {\n createdAt: string;\n eventId: string;\n}\n\nexport interface OutboxDeadLetter {\n eventId: string;\n tenantId: string;\n topic: string;\n aggregateType: string;\n aggregateId: string;\n payloadVersion: number;\n attemptCount: number;\n lastError: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface OutboxDeadLetterListOptions {\n limit?: number;\n cursor?: OutboxDeadLetterCursor | null;\n}\n\nexport interface OutboxDeadLetterPage {\n items: OutboxDeadLetter[];\n nextCursor: OutboxDeadLetterCursor | null;\n}\n\nexport interface OutboxRecoveryStore extends OutboxStore {\n stats(): Promise<OutboxStats>;\n listDeadLetters(options?: OutboxDeadLetterListOptions): Promise<OutboxDeadLetterPage>;\n requeue(eventId: string): Promise<boolean>;\n}\n\nexport interface OutboxHandler {\n readonly topics: readonly string[];\n handle(event: OutboxEvent): Promise<void>;\n}\n\nexport interface UsageChargeExport {\n tenantId: string;\n chargeId: string;\n accountId: string;\n subjectId: string;\n operation: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: Record<string, unknown>;\n dimensions: Record<string, unknown>;\n metadata: Record<string, unknown>;\n requested: string;\n charged: string;\n allowanceRequested: string;\n allowanceCovered: string;\n billingDisposition: \"billable\" | \"record_only\";\n catalogRevisionId: string | null;\n planId: string | null;\n rateCardKey: string | null;\n pricingSnapshot: Record<string, unknown>;\n ledgerEntryId: string | null;\n correctionOfChargeId: string | null;\n idempotencyKey: string;\n requestDigest: string;\n eventAt: string;\n createdAt: string;\n}\n\nexport interface BillingEventPayloadExport {\n tenantId: string;\n eventId: string;\n provider: string;\n providerEnvironment: string;\n providerEventId: string;\n eventType: string;\n status: string;\n receivedAt: string;\n completedAt: string | null;\n envelope: Record<string, unknown> | null;\n objectKey: string | null;\n objectVersion: string | null;\n archivedAt: string | null;\n}\n\nexport interface UsageEventSink {\n initialize?(): Promise<void>;\n /** Non-mutating compatibility check for a caller-managed projection schema. */\n checkSchemaCompatibility?(): Promise<void>;\n writeUsage(event: UsageChargeExport, outboxEventId: string): Promise<void>;\n writeUsageBatch?(entries: readonly (readonly [UsageChargeExport, string])[]): Promise<void>;\n}\n\nexport interface BillingPayloadArchiveResult {\n key: string;\n versionId: string | null;\n}\n\nexport interface BillingPayloadArchive {\n archive(event: BillingEventPayloadExport): Promise<BillingPayloadArchiveResult>;\n close?(): Promise<void> | void;\n}\n"]}
@@ -1,12 +1,17 @@
1
1
  import type { QueryFn } from "../shared/postgres-types.js";
2
- import type { BillingEventPayloadExport, OutboxEvent, OutboxStore, UsageChargeExport } from "./ports.js";
3
- export declare class PostgresStorageRepository implements OutboxStore {
2
+ import type { BillingEventPayloadExport, OutboxDeadLetterListOptions, OutboxDeadLetterPage, OutboxEvent, OutboxRecoveryStore, OutboxStats, UsageChargeExport } from "./ports.js";
3
+ export declare class PostgresStorageRepository implements OutboxRecoveryStore {
4
4
  private readonly query;
5
5
  private readonly tenantId;
6
6
  constructor(query: QueryFn, tenantId: string);
7
+ private assertEventTenant;
7
8
  claim(topics: readonly string[], limit: number, leaseSeconds: number): Promise<OutboxEvent[]>;
9
+ renew(event: OutboxEvent, leaseSeconds: number): Promise<boolean>;
8
10
  complete(event: OutboxEvent): Promise<boolean>;
9
11
  fail(event: OutboxEvent, error: string, retryDelaySeconds: number, attemptLimit: number): Promise<boolean>;
12
+ stats(): Promise<OutboxStats>;
13
+ listDeadLetters(options?: OutboxDeadLetterListOptions): Promise<OutboxDeadLetterPage>;
14
+ requeue(eventId: string): Promise<boolean>;
10
15
  getUsageCharge(chargeId: string): Promise<UsageChargeExport | null>;
11
16
  getBillingEventPayload(eventId: string): Promise<BillingEventPayloadExport | null>;
12
17
  archiveBillingEventPayload(eventId: string, objectKey: string, objectVersion: string | null): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-repository.d.ts","sourceRoot":"","sources":["../../src/storage/postgres-repository.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,KAAK,EACV,yBAAyB,EACzB,WAAW,EACX,WAAW,EACX,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAqCpB,qBAAa,yBAA0B,YAAW,WAAW;IAEzD,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBADR,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,MAAM;IAG7B,KAAK,CACT,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,KAAK,EAAE,MAAM,EACb,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,WAAW,EAAE,CAAC;IAsBnB,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC;IAS9C,IAAI,CACR,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,MAAM,EACb,iBAAiB,EA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