@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
@@ -1,73 +1,177 @@
1
1
  import { Bursar } from "../bursar.js";
2
+ import { z } from "zod";
2
3
  import { ConfigError, ImportError as BursarImportError, isRetryableBursarError, CatalogNotLoadedError, StoreClosedError, } from "../errors.js";
3
4
  import { retryBursarOperation } from "../retry.js";
4
5
  import { PostgresBillingStore } from "../billing/postgres/store.js";
5
6
  import { PostgresStore } from "../credits/postgres/store.js";
7
+ import { normalizeProviderEnvironment, } from "../providers/environment.js";
6
8
  import { normalizeTenantId, PostgresClient, postgresPoolConfig, } from "../shared/postgres-client.js";
7
9
  import { ClickHouseUsageStore } from "./adapters/clickhouse.js";
8
10
  import { S3BillingArchive } from "./adapters/s3.js";
11
+ import { RuntimeDiagnosticsTracker, } from "./diagnostics.js";
12
+ import { BursarMaintenance, BursarOperatorMaintenance } from "./maintenance.js";
9
13
  import { OutboxWorker } from "./outbox-worker.js";
10
14
  import { PostgresStorageRepository } from "./postgres-repository.js";
15
+ const runtimeStartOptionsSchema = z
16
+ .object({
17
+ loadCatalog: z.boolean().default(true),
18
+ maxAttempts: z.number().finite().int().min(1).max(Number.MAX_SAFE_INTEGER).default(1),
19
+ retryDelayMs: z.number().finite().min(0).max(5_000).default(250),
20
+ shouldRetry: z
21
+ .custom((value) => typeof value === "function", "shouldRetry must be a function")
22
+ .optional(),
23
+ maxElapsedMs: z.number().finite().min(0).max(2_147_483_647).optional(),
24
+ signal: z
25
+ .custom((value) => typeof value === "object" &&
26
+ value !== null &&
27
+ typeof value.throwIfAborted === "function", "signal must be an AbortSignal")
28
+ .optional(),
29
+ })
30
+ .strict();
31
+ /** Coalesce concurrently dispatched usage events into one optional sink write. */
32
+ class UsageWriteBatcher {
33
+ sink;
34
+ pending = [];
35
+ scheduled = false;
36
+ constructor(sink) {
37
+ this.sink = sink;
38
+ }
39
+ write(event, outboxEventId) {
40
+ if (!this.sink.writeUsageBatch)
41
+ return this.sink.writeUsage(event, outboxEventId);
42
+ return new Promise((resolve, reject) => {
43
+ this.pending.push({ event, outboxEventId, resolve, reject });
44
+ if (this.scheduled)
45
+ return;
46
+ this.scheduled = true;
47
+ queueMicrotask(() => {
48
+ void this.flush();
49
+ });
50
+ });
51
+ }
52
+ async flush() {
53
+ const pending = this.pending.splice(0);
54
+ this.scheduled = false;
55
+ try {
56
+ await this.sink.writeUsageBatch(pending.map(({ event, outboxEventId }) => [event, outboxEventId]));
57
+ for (const write of pending)
58
+ write.resolve();
59
+ }
60
+ catch (error) {
61
+ for (const write of pending)
62
+ write.reject(error);
63
+ }
64
+ }
65
+ }
11
66
  /**
12
67
  * Node composition root for Bursar's stores and optional data infrastructure.
13
68
  *
14
69
  * Without S3 or ClickHouse it constructs the same PostgreSQL-only Bursar and
15
- * no outbox polling loop. All components share one PostgreSQL pool.
70
+ * no outbox polling loop. Tenant and operator work always use distinct pools.
16
71
  */
17
72
  export class BursarRuntime {
18
73
  bursar;
19
74
  creditStore;
20
75
  billingStore;
76
+ maintenance;
77
+ operatorMaintenance;
21
78
  worker;
79
+ outboxRecovery;
22
80
  clickhouse;
23
81
  s3;
24
82
  pool;
83
+ operatorPool;
25
84
  ownsPool;
85
+ ownsOperatorPool;
26
86
  postgres;
27
87
  query;
28
88
  tenantId;
29
89
  tenantSlug;
90
+ diagnosticsTracker;
91
+ usageBatcher;
92
+ providerEnvironment;
30
93
  startPromise = null;
31
94
  closePromise = null;
32
95
  started = false;
33
96
  closed = false;
34
97
  /** Construct a runtime while keeping pool ownership inside the SDK. */
35
98
  static async create(options) {
36
- if (typeof options.postgres !== "string") {
37
- return new BursarRuntime(options.postgres, false, options);
99
+ if (options.operatorPostgres === undefined || options.operatorPostgres === null) {
100
+ throw new TypeError("operatorPostgres is required");
38
101
  }
39
- if (!options.postgres.trim()) {
102
+ if (typeof options.postgres === "string" && !options.postgres.trim()) {
40
103
  throw new TypeError("postgres connection string must not be empty");
41
104
  }
42
- let pg;
43
- try {
44
- pg = await import("pg");
45
- }
46
- catch (cause) {
47
- throw new BursarImportError("pg is required for the Bursar runtime: npm install pg", {
48
- cause,
49
- });
105
+ if (typeof options.operatorPostgres === "string" && !options.operatorPostgres.trim()) {
106
+ throw new TypeError("operatorPostgres connection string must not be empty");
50
107
  }
51
- const pool = new pg.Pool(postgresPoolConfig(options.postgres, options.postgresOptions));
52
- try {
53
- return new BursarRuntime(pool, true, options);
108
+ if (options.postgres === options.operatorPostgres) {
109
+ throw new TypeError("postgres and operatorPostgres must use distinct connections");
54
110
  }
55
- catch (error) {
111
+ let pg;
112
+ if (typeof options.postgres === "string" || typeof options.operatorPostgres === "string") {
56
113
  try {
57
- await pool.end();
114
+ pg = await import("pg");
58
115
  }
59
- catch {
60
- // Preserve the composition error; no runtime exists to report cleanup.
116
+ catch (cause) {
117
+ throw new BursarImportError("pg is required for the Bursar runtime: npm install pg", {
118
+ cause,
119
+ });
61
120
  }
121
+ }
122
+ const ownsPool = typeof options.postgres === "string";
123
+ const ownsOperatorPool = typeof options.operatorPostgres === "string";
124
+ let pool;
125
+ let operatorPool;
126
+ try {
127
+ pool =
128
+ typeof options.postgres === "string"
129
+ ? new pg.Pool(postgresPoolConfig(options.postgres, options.postgresOptions))
130
+ : options.postgres;
131
+ operatorPool =
132
+ typeof options.operatorPostgres === "string"
133
+ ? new pg.Pool(postgresPoolConfig(options.operatorPostgres, options.postgresOptions))
134
+ : options.operatorPostgres;
135
+ return new BursarRuntime(pool, ownsPool, operatorPool, ownsOperatorPool, options);
136
+ }
137
+ catch (error) {
138
+ await Promise.allSettled([
139
+ ...(ownsPool && pool ? [pool.end()] : []),
140
+ ...(ownsOperatorPool && operatorPool ? [operatorPool.end()] : []),
141
+ ]);
62
142
  throw error;
63
143
  }
64
144
  }
65
- constructor(pool, ownsPool, options) {
145
+ constructor(pool, ownsPool, operatorPool, ownsOperatorPool, options) {
66
146
  this.pool = pool;
147
+ this.operatorPool = operatorPool;
67
148
  this.ownsPool = ownsPool;
149
+ this.ownsOperatorPool = ownsOperatorPool;
68
150
  this.tenantId = normalizeTenantId(options.tenantId);
151
+ this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
69
152
  this.tenantSlug =
70
153
  options.tenantSlug === undefined ? null : normalizeTenantSlug(options.tenantSlug);
154
+ for (const optionName of ["bursar", "s3", "clickhouse"]) {
155
+ if (options[optionName] === null) {
156
+ throw new TypeError(`${optionName} must not be null`);
157
+ }
158
+ }
159
+ const bursarOptions = options.bursar ?? {};
160
+ if (bursarOptions.creditsOptions === null) {
161
+ throw new TypeError("bursar.creditsOptions must not be null");
162
+ }
163
+ if (bursarOptions.creditsOptions &&
164
+ ("analytics" in bursarOptions.creditsOptions || "usageStore" in bursarOptions.creditsOptions)) {
165
+ throw new TypeError("BursarRuntime owns creditsOptions.analytics and usageStore");
166
+ }
167
+ if (bursarOptions.commerceOptions === null) {
168
+ throw new TypeError("bursar.commerceOptions must not be null");
169
+ }
170
+ if (bursarOptions.commerceOptions &&
171
+ ("tenantId" in bursarOptions.commerceOptions ||
172
+ "providerEnvironment" in bursarOptions.commerceOptions)) {
173
+ throw new TypeError("BursarRuntime owns commerceOptions.tenantId and providerEnvironment");
174
+ }
71
175
  if (options.clickhouse &&
72
176
  !("writeUsage" in options.clickhouse) &&
73
177
  normalizeTenantId(options.clickhouse.tenantId) !== this.tenantId) {
@@ -78,6 +182,7 @@ export class BursarRuntime {
78
182
  ? options.clickhouse
79
183
  : new ClickHouseUsageStore({ ...options.clickhouse, tenantId: this.tenantId })
80
184
  : null;
185
+ this.usageBatcher = this.clickhouse ? new UsageWriteBatcher(this.clickhouse) : null;
81
186
  this.s3 = options.s3
82
187
  ? "archive" in options.s3
83
188
  ? options.s3
@@ -87,19 +192,21 @@ export class BursarRuntime {
87
192
  postgres: pool,
88
193
  tenantId: this.tenantId,
89
194
  ...(options.postgresOptions ?? {}),
195
+ providerEnvironment: this.providerEnvironment,
90
196
  usageBackend: this.clickhouse ? "clickhouse" : "postgres",
91
197
  });
92
198
  this.billingStore = new PostgresBillingStore({
93
199
  postgres: pool,
94
200
  tenantId: this.tenantId,
95
201
  ...(options.postgresOptions ?? {}),
202
+ providerEnvironment: this.providerEnvironment,
96
203
  billingPayloadBackend: this.s3 ? "s3" : "postgres",
97
204
  });
98
- const bursarOptions = options.bursar ?? {};
99
205
  const commerceOptions = bursarOptions.commerceOptions
100
206
  ? {
101
207
  ...bursarOptions.commerceOptions,
102
208
  tenantId: this.tenantId,
209
+ providerEnvironment: this.providerEnvironment,
103
210
  }
104
211
  : undefined;
105
212
  this.bursar = new Bursar({
@@ -115,20 +222,63 @@ export class BursarRuntime {
115
222
  : undefined,
116
223
  },
117
224
  });
118
- this.postgres = new PostgresClient(pool, {
225
+ this.postgres = new PostgresClient(operatorPool, {
119
226
  ...(options.postgresOptions ?? {}),
120
227
  tenantId: this.tenantId,
228
+ providerEnvironment: this.providerEnvironment,
121
229
  accessRole: "bursar_operator",
122
230
  usageBackend: this.clickhouse ? "clickhouse" : "postgres",
123
231
  billingPayloadBackend: this.s3 ? "s3" : "postgres",
124
232
  });
125
233
  this.query = this.postgres.query;
234
+ this.maintenance = new BursarMaintenance({
235
+ expireLeases: (limit) => this.creditStore.expireLeases(limit),
236
+ expireCredits: async (limit) => (await this.creditStore.sweepExpiredCredits(false, undefined, limit)).expiredCount,
237
+ applyDuePlanChanges: (limit) => this.creditStore.applyDuePlanChanges(limit),
238
+ expirePastDueGracePeriods: this.bursar.billing
239
+ ? (now) => this.bursar.billing.expirePastDueGracePeriods(now)
240
+ : undefined,
241
+ pastDueGracePeriodLimit: 100,
242
+ pastDueGracePeriodsUnavailableReason: this.bursar.billing
243
+ ? undefined
244
+ : "billing is not configured",
245
+ });
246
+ this.operatorMaintenance = new BursarOperatorMaintenance(this.query);
126
247
  const repository = new PostgresStorageRepository(this.query, this.tenantId);
248
+ this.outboxRecovery = repository;
127
249
  const handlers = this.createHandlers(repository);
250
+ const configuredOutboxOptions = options.outbox === false || options.outbox === undefined ? {} : options.outbox;
251
+ const originalOnError = configuredOutboxOptions.onError;
252
+ let diagnosticsTracker = null;
253
+ const workerOptions = {
254
+ ...configuredOutboxOptions,
255
+ onError: async (error) => {
256
+ diagnosticsTracker?.recordWorkerError(error);
257
+ await originalOnError?.(error);
258
+ },
259
+ };
128
260
  this.worker =
129
261
  handlers.length > 0 && options.outbox !== false
130
- ? new OutboxWorker(repository, handlers, options.outbox)
262
+ ? new OutboxWorker(repository, handlers, workerOptions)
131
263
  : null;
264
+ this.diagnosticsTracker = new RuntimeDiagnosticsTracker({
265
+ checkPostgres: async () => {
266
+ const rows = await this.query("SELECT 1 AS bursar_reachable");
267
+ const row = rows[0];
268
+ if (!row ||
269
+ typeof row !== "object" ||
270
+ !("bursar_reachable" in row) ||
271
+ row.bursar_reachable !== 1) {
272
+ throw new Error("PostgreSQL reachability check returned an invalid result");
273
+ }
274
+ },
275
+ getCatalogRevision: async () => {
276
+ const revision = await this.bursar.catalog.getActive();
277
+ return revision ? { id: revision.id, version: revision.version } : null;
278
+ },
279
+ getOutboxStatus: outboxStatusProvider(repository),
280
+ }, this.worker !== null);
281
+ diagnosticsTracker = this.diagnosticsTracker;
132
282
  }
133
283
  start(options = {}) {
134
284
  if (this.closed) {
@@ -145,38 +295,60 @@ export class BursarRuntime {
145
295
  return this.startPromise;
146
296
  }
147
297
  async startRuntime(options) {
298
+ const startOptions = runtimeStartOptionsSchema.parse(options);
148
299
  if (this.tenantSlug)
149
300
  await this.verifyTenantIdentity();
150
- if (options.loadCatalog ?? true) {
151
- const maxAttempts = options.maxAttempts ?? 1;
152
- const shouldRetry = options.shouldRetry ??
301
+ if (startOptions.loadCatalog) {
302
+ const shouldRetry = startOptions.shouldRetry ??
153
303
  ((error) => error instanceof CatalogNotLoadedError || isRetryableBursarError(error));
154
304
  await retryBursarOperation(() => this.bursar.loadCatalog(), {
155
- maxAttempts,
156
- baseDelayMs: options.retryDelayMs ?? 250,
305
+ maxAttempts: startOptions.maxAttempts,
306
+ baseDelayMs: startOptions.retryDelayMs,
157
307
  maxDelayMs: 5_000,
158
- maxElapsedMs: options.maxElapsedMs,
159
- signal: options.signal,
308
+ maxElapsedMs: startOptions.maxElapsedMs,
309
+ signal: startOptions.signal,
160
310
  shouldRetry,
161
311
  });
162
312
  }
163
313
  await this.clickhouse?.initialize?.();
314
+ await this.clickhouse?.checkSchemaCompatibility?.();
164
315
  await this.worker?.start();
316
+ if (this.worker)
317
+ this.diagnosticsTracker.markWorkerStarted();
165
318
  this.started = true;
166
319
  }
167
- health() {
168
- const catalogLoaded = this.bursar.catalog.isLoaded;
169
- return {
170
- ready: this.started && !this.closed && catalogLoaded,
320
+ state() {
321
+ return this.diagnosticsTracker.state({
322
+ started: this.started,
323
+ closed: this.closed,
324
+ catalogLoaded: this.bursar.catalog.isLoaded,
325
+ });
326
+ }
327
+ checkDependencies(options = {}) {
328
+ return this.diagnosticsTracker.checkDependencies({
171
329
  started: this.started,
172
330
  closed: this.closed,
173
- catalogLoaded,
331
+ catalogLoaded: this.bursar.catalog.isLoaded,
332
+ }, options);
333
+ }
334
+ health() {
335
+ const state = this.state();
336
+ return {
337
+ ready: state.ready,
338
+ financialReady: state.financialReady,
339
+ projectionReady: state.projectionReady,
340
+ degraded: state.degraded,
341
+ started: state.started,
342
+ closed: state.closed,
343
+ catalogLoaded: state.catalogLoaded,
174
344
  };
175
345
  }
176
346
  async flush() {
177
347
  if (this.closed)
178
348
  throw new StoreClosedError("BursarRuntime has been closed");
179
- return this.worker?.runOnce() ?? { claimed: 0, delivered: 0, failed: 0 };
349
+ if (!this.worker)
350
+ return { claimed: 0, delivered: 0, failed: 0, claimLost: 0 };
351
+ return this.diagnosticsTracker.observeManualRun(() => this.worker.runOnce());
180
352
  }
181
353
  close() {
182
354
  if (this.closePromise)
@@ -202,6 +374,10 @@ export class BursarRuntime {
202
374
  catch (error) {
203
375
  failures.push(error);
204
376
  }
377
+ finally {
378
+ if (this.worker)
379
+ this.diagnosticsTracker.markWorkerStopped();
380
+ }
205
381
  const resources = await Promise.allSettled([
206
382
  Promise.resolve().then(() => this.s3?.close?.()),
207
383
  Promise.resolve().then(() => this.creditStore.close()),
@@ -220,6 +396,14 @@ export class BursarRuntime {
220
396
  failures.push(error);
221
397
  }
222
398
  }
399
+ if (this.ownsOperatorPool) {
400
+ try {
401
+ await this.operatorPool.end();
402
+ }
403
+ catch (error) {
404
+ failures.push(error);
405
+ }
406
+ }
223
407
  if (failures.length === 1)
224
408
  throw failures[0];
225
409
  if (failures.length > 1) {
@@ -246,7 +430,9 @@ export class BursarRuntime {
246
430
  if (usage.chargeId !== outboxEvent.aggregateId) {
247
431
  throw new Error("Usage export charge does not match its outbox event");
248
432
  }
249
- await this.clickhouse?.writeUsage(usage, outboxEvent.eventId);
433
+ if (!this.usageBatcher)
434
+ throw new Error("ClickHouse usage sink is not configured");
435
+ await this.usageBatcher.write(usage, outboxEvent.eventId);
250
436
  },
251
437
  });
252
438
  }
@@ -300,6 +486,51 @@ export class BursarRuntime {
300
486
  export async function createBursarRuntime(options) {
301
487
  return BursarRuntime.create(options);
302
488
  }
489
+ function outboxStatusProvider(repository) {
490
+ const stats = repository.stats;
491
+ return async (limit) => {
492
+ let raw;
493
+ try {
494
+ raw = await stats.call(repository, { limit });
495
+ }
496
+ catch (error) {
497
+ if (!isInputShapeError(error))
498
+ throw error;
499
+ raw = await stats.call(repository, limit);
500
+ }
501
+ if (!isJsonObject(raw))
502
+ throw new TypeError("outbox stats returned a malformed result");
503
+ return {
504
+ pendingCount: statsCount(raw, "pendingCount", "pending_count", "pending"),
505
+ processingCount: statsCount(raw, "processingCount", "processing_count", "processing"),
506
+ deliveredCount: statsCount(raw, "deliveredCount", "delivered_count", "delivered"),
507
+ deadLetterCount: statsCount(raw, "deadLetterCount", "dead_letter_count", "dead_letter"),
508
+ oldestPendingAt: statsTimestamp(raw, "oldestPendingAt", "oldest_pending_at"),
509
+ };
510
+ };
511
+ }
512
+ function statsCount(raw, ...keys) {
513
+ const value = keys.map((key) => raw[key]).find((candidate) => candidate !== undefined);
514
+ if (!Number.isSafeInteger(value) || value < 0) {
515
+ throw new TypeError(`outbox stats field ${keys[0]} must be a non-negative integer`);
516
+ }
517
+ return value;
518
+ }
519
+ function statsTimestamp(raw, ...keys) {
520
+ const value = keys.map((key) => raw[key]).find((candidate) => candidate !== undefined);
521
+ if (value === null || value === undefined)
522
+ return null;
523
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
524
+ return value.toISOString();
525
+ if (typeof value === "string")
526
+ return value;
527
+ throw new TypeError(`outbox stats field ${keys[0]} must be a timestamp string or null`);
528
+ }
529
+ function isInputShapeError(error) {
530
+ return (error instanceof TypeError ||
531
+ error instanceof RangeError ||
532
+ (error instanceof Error && error.name === "ZodError"));
533
+ }
303
534
  function normalizeTenantSlug(value) {
304
535
  if (typeof value !== "string")
305
536
  throw new TypeError("tenantSlug must be a string");