@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.
- package/README.md +22 -14
- package/dist/billing/auto-recharge-service.d.ts +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +9 -6
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +4 -1
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +2 -1
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +2 -3
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +38 -49
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +22 -10
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -2
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +7 -7
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +6 -2
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +21 -6
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +2 -15
- package/dist/billing/service-types.d.ts.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -1
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +1 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +11 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +2 -2
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +1 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts +21 -11
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +40 -4
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/index.d.ts +0 -1
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js +0 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +154 -106
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +9 -5
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +0 -6
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-utils.d.ts +1 -1
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +1 -6
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +8 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +8 -0
- package/dist/credits/amount.d.ts.map +1 -0
- package/dist/credits/amount.js +32 -0
- package/dist/credits/amount.js.map +1 -0
- package/dist/credits/catalog-runtime.d.ts +5 -7
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +4 -13
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +2 -2
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +24 -21
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +3 -4
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +18 -14
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +30 -18
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +1 -1
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +21 -16
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +21 -17
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +81 -38
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +26 -23
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +4 -2
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +1 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.js +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/evaluator.d.ts +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/parser.d.ts +1 -0
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +15 -3
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr.d.ts +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +1 -1
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +31 -29
- package/dist/generated/pricing-config.types.d.ts +6 -18
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -3
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +14 -29
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +3 -3
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +11 -6
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +8 -13
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +23 -15
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +4 -6
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +44 -82
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js +0 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +6 -0
- package/dist/providers/environment.d.ts.map +1 -0
- package/dist/providers/environment.js +10 -0
- package/dist/providers/environment.js.map +1 -0
- package/dist/providers/index.d.ts +3 -7
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -5
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +6 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +18 -50
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +82 -14
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +3 -3
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +37 -24
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +9 -20
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +8 -0
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +49 -0
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/idempotency.d.ts +9 -0
- package/dist/shared/idempotency.d.ts.map +1 -0
- package/dist/shared/idempotency.js +34 -0
- package/dist/shared/idempotency.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +7 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +21 -4
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +9 -2
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +142 -36
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +44 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +59 -21
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +227 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +266 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +20 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +172 -42
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +43 -1
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +7 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +155 -54
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +30 -9
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +268 -37
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +37 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +115 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +62 -36
package/dist/storage/runtime.js
CHANGED
|
@@ -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.
|
|
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 (
|
|
37
|
-
|
|
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
|
-
|
|
43
|
-
|
|
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
|
-
|
|
52
|
-
|
|
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
|
-
|
|
111
|
+
let pg;
|
|
112
|
+
if (typeof options.postgres === "string" || typeof options.operatorPostgres === "string") {
|
|
56
113
|
try {
|
|
57
|
-
await
|
|
114
|
+
pg = await import("pg");
|
|
58
115
|
}
|
|
59
|
-
catch {
|
|
60
|
-
|
|
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(
|
|
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,
|
|
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 (
|
|
151
|
-
const
|
|
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:
|
|
305
|
+
maxAttempts: startOptions.maxAttempts,
|
|
306
|
+
baseDelayMs: startOptions.retryDelayMs,
|
|
157
307
|
maxDelayMs: 5_000,
|
|
158
|
-
maxElapsedMs:
|
|
159
|
-
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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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");
|