@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
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { ConfigError } from "../errors.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
4
2
|
import { retryBursarOperation } from "../retry.js";
|
|
5
3
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
|
-
import {
|
|
4
|
+
import { CatalogRuntime } from "./catalog-runtime.js";
|
|
5
|
+
import { isAmount, rejectNativeCreditAmount } from "./amount.js";
|
|
7
6
|
import { raiseLeaseError } from "./service-errors.js";
|
|
7
|
+
import { requireStableKey, scopedStableKey } from "../shared/idempotency.js";
|
|
8
8
|
export class CreditLeaseWorkflow {
|
|
9
9
|
store;
|
|
10
10
|
catalogRuntime;
|
|
@@ -71,22 +71,23 @@ export class CreditLeaseWorkflow {
|
|
|
71
71
|
* policy, and concurrency enforcement to the database in one atomic call.
|
|
72
72
|
*/
|
|
73
73
|
async reserve(userId, metricsOrAmount, options) {
|
|
74
|
+
rejectNativeCreditAmount(metricsOrAmount);
|
|
75
|
+
const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
74
76
|
await this.maybeLazyExpire(userId);
|
|
75
77
|
this.logger.debug("[CreditsService] reserve", {
|
|
76
|
-
feature: options
|
|
77
|
-
operationType: options
|
|
78
|
+
feature: options.feature,
|
|
79
|
+
operationType: options.operationType,
|
|
78
80
|
});
|
|
79
|
-
const operationType = options
|
|
80
|
-
const expectedPolicy = await this.expectedAdmissionPolicy(userId, operationType, options
|
|
81
|
+
const operationType = options.operationType ?? (isAmount(metricsOrAmount) ? "usage" : metricsOrAmount.operation);
|
|
82
|
+
const expectedPolicy = await this.expectedAdmissionPolicy(userId, operationType, options.billingMode);
|
|
81
83
|
const priced = await this.costOf(metricsOrAmount, userId);
|
|
82
84
|
const amount = priced.amount;
|
|
83
|
-
const model = priced.model ?? options
|
|
84
|
-
const ttlSeconds = options
|
|
85
|
-
const feature = options
|
|
85
|
+
const model = priced.model ?? options.model ?? null;
|
|
86
|
+
const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;
|
|
87
|
+
const feature = options.feature ?? null;
|
|
86
88
|
const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
|
|
87
89
|
const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
|
|
88
90
|
const region = typeof dimensions.region === "string" ? dimensions.region : null;
|
|
89
|
-
const leaseIdempotencyKey = options?.idempotencyKey ?? `lease:${randomUUID()}`;
|
|
90
91
|
const result = await this.store.createLease(userId, amount, operationType, {
|
|
91
92
|
idempotencyKey: leaseIdempotencyKey,
|
|
92
93
|
billingMode: expectedPolicy.billingMode,
|
|
@@ -94,7 +95,7 @@ export class CreditLeaseWorkflow {
|
|
|
94
95
|
maxConcurrent: expectedPolicy.maxConcurrent,
|
|
95
96
|
ttlSeconds,
|
|
96
97
|
model,
|
|
97
|
-
metadata: options
|
|
98
|
+
metadata: options.metadata,
|
|
98
99
|
feature,
|
|
99
100
|
region,
|
|
100
101
|
measures,
|
|
@@ -136,9 +137,12 @@ export class CreditLeaseWorkflow {
|
|
|
136
137
|
* signals as applicable.
|
|
137
138
|
*/
|
|
138
139
|
async settle(userId, leaseId, metricsOrAmount, options) {
|
|
140
|
+
rejectNativeCreditAmount(metricsOrAmount);
|
|
139
141
|
await this.maybeLazyExpire(userId);
|
|
140
142
|
this.logger.debug("[CreditsService] settle", { leaseId });
|
|
141
|
-
const idempotencyKey = options?.idempotencyKey
|
|
143
|
+
const idempotencyKey = options?.idempotencyKey === undefined
|
|
144
|
+
? `lease:${leaseId}:settle`
|
|
145
|
+
: requireStableKey(options.idempotencyKey);
|
|
142
146
|
const feature = options?.feature ?? null;
|
|
143
147
|
const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);
|
|
144
148
|
const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
|
|
@@ -245,6 +249,7 @@ export class CreditLeaseWorkflow {
|
|
|
245
249
|
* Never use this as an admission gate; only ``reserve`` is authoritative.
|
|
246
250
|
*/
|
|
247
251
|
async canAfford(userId, metricsOrAmount, options) {
|
|
252
|
+
rejectNativeCreditAmount(metricsOrAmount);
|
|
248
253
|
await this.maybeLazyExpire(userId);
|
|
249
254
|
const feature = options?.feature ?? null;
|
|
250
255
|
const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);
|
|
@@ -315,7 +320,7 @@ export class CreditLeaseWorkflow {
|
|
|
315
320
|
* covered by the lease TTL (and the store's reaper).
|
|
316
321
|
*/
|
|
317
322
|
async runBilled(userId, options) {
|
|
318
|
-
const operationKey = options.operationKey
|
|
323
|
+
const operationKey = requireStableKey(options.operationKey, "operationKey");
|
|
319
324
|
const operation = await this.beginBilledOperation(userId, {
|
|
320
325
|
estimate: options.estimate,
|
|
321
326
|
operationKey,
|
|
@@ -348,22 +353,20 @@ export class CreditLeaseWorkflow {
|
|
|
348
353
|
* replaying the whole lifecycle cannot acquire a second hold.
|
|
349
354
|
*/
|
|
350
355
|
async beginBilledOperation(userId, options) {
|
|
351
|
-
|
|
352
|
-
throw new ConfigError("operationKey must not be empty");
|
|
353
|
-
}
|
|
356
|
+
const operationKey = requireStableKey(options.operationKey, "operationKey");
|
|
354
357
|
const lease = await this.reserve(userId, options.estimate, {
|
|
355
358
|
operationType: options.operationType,
|
|
356
359
|
billingMode: options.billingMode,
|
|
357
360
|
ttl: options.ttl,
|
|
358
361
|
feature: options.feature,
|
|
359
362
|
metadata: options.metadata,
|
|
360
|
-
idempotencyKey:
|
|
363
|
+
idempotencyKey: scopedStableKey(operationKey, "reserve"),
|
|
361
364
|
});
|
|
362
365
|
return {
|
|
363
366
|
leaseId: lease.leaseId,
|
|
364
|
-
operationKey
|
|
367
|
+
operationKey,
|
|
365
368
|
settle: async (actual, metadata) => this.settle(userId, lease.leaseId, actual, {
|
|
366
|
-
idempotencyKey:
|
|
369
|
+
idempotencyKey: scopedStableKey(operationKey, "settle"),
|
|
367
370
|
feature: options.feature,
|
|
368
371
|
metadata: metadata ?? options.metadata,
|
|
369
372
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,UAAU,EA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AC,aAAa;YACpC,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,GAAG,OAAO,CAAC,YAAY,UAAU;SAClD,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CACjC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE;gBACzC,cAAc,EAAE,GAAG,OAAO,CAAC,YAAY,SAAS;gBAChD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { ConfigError } from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { isAmount, CatalogRuntime } from \"./catalog-runtime.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n ) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseSuccess> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options?.feature,\n operationType: options?.operationType,\n });\n const operationType =\n options?.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options?.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options?.model ?? null;\n const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options?.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n const leaseIdempotencyKey = options?.idempotencyKey ?? `lease:${randomUUID()}`;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options?.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey = options?.idempotencyKey ?? `lease:${leaseId}:settle`;\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: Record<string, unknown> = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta as CreditMetadata,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = options.operationKey ?? `billed:${randomUUID()}`;\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n if (!options.operationKey.trim()) {\n throw new ConfigError(\"operationKey must not be empty\");\n }\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: `${options.operationKey}:reserve`,\n });\n return {\n leaseId: lease.leaseId,\n operationKey: options.operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: `${options.operationKey}:settle`,\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAwB7E,MAAM,OAAO,mBAAmB;IAEX;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAKA;IACA;IACA;IAhBnB,YACmB,KAAkB,EAClB,cAA8B,EAC9B,MAAwB,EACxB,cAAiC,EACjC,MAAoB,EACpB,cAA8B,EAC9B,oBAAmC,EACnC,UAAkB,EAClB,IAIR,EACQ,eAA0E,EAC1E,eAAkD,EAClD,cAA2E;QAf3E,UAAK,GAAL,KAAK,CAAa;QAClB,mBAAc,GAAd,cAAc,CAAgB;QAC9B,WAAM,GAAN,MAAM,CAAkB;QACxB,mBAAc,GAAd,cAAc,CAAmB;QACjC,WAAM,GAAN,MAAM,CAAc;QACpB,mBAAc,GAAd,cAAc,CAAgB;QAC9B,yBAAoB,GAApB,oBAAoB,CAAe;QACnC,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAIZ;QACQ,oBAA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AE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { isAmount, rejectNativeCreditAmount } from \"./amount.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport { requireStableKey, scopedStableKey } from \"../shared/idempotency.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n ) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n rejectNativeCreditAmount(metricsOrAmount);\n const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options.feature,\n operationType: options.operationType,\n });\n const operationType =\n options.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options.model ?? null;\n const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey =\n options?.idempotencyKey === undefined\n ? `lease:${leaseId}:settle`\n : requireStableKey(options.idempotencyKey);\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: Record<string, unknown> = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta as CreditMetadata,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: scopedStableKey(operationKey, \"reserve\"),\n });\n return {\n leaseId: lease.leaseId,\n operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: scopedStableKey(operationKey, \"settle\"),\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAK3D,KAAK,eAAe,GAAG,CACrB,IAAI,EAAE,eAAe,EACrB,MAAM,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC3B,IAAI,CAAC;AAEV;;;;;GAKG;AACH,qBAAa,iBAAiB;IAO1B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAPzB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAChF,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgC;gBAG7D,MAAM,EAAE,gBAAgB,GAAG,IAAI,GAAG,SAAS,EAC1B,IAAI,EAAE,eAAe,EACrB,MAAM,EAAE,gBAAgB;IAa3C,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAalD,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAWpE,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,OAAO,EACtB,YAAY,EAAE,OAAO,GACpB,OAAO,CAAC,IAAI,CAAC;YAkCF,IAAI;CAmBnB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { LRUCache } from "lru-cache";
|
|
3
|
+
import { toDecimal } from "./amount.js";
|
|
3
4
|
const DEFAULT_MAX_TRACKED_USERS = 100_000;
|
|
4
5
|
/**
|
|
5
6
|
* Owns edge-trigger state for low-balance and overdraft notifications.
|
|
@@ -17,9 +18,7 @@ export class LowBalanceMonitor {
|
|
|
17
18
|
this.emit = emit;
|
|
18
19
|
this.logger = logger;
|
|
19
20
|
this.thresholds = config?.thresholds?.length
|
|
20
|
-
? config.thresholds
|
|
21
|
-
.map((value) => (value instanceof Decimal ? value : new Decimal(value)))
|
|
22
|
-
.sort((left, right) => right.comparedTo(left))
|
|
21
|
+
? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))
|
|
23
22
|
: null;
|
|
24
23
|
this.handler = config?.onTrigger ?? null;
|
|
25
24
|
const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAMrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,yBAAyB,GAAG,OAAO,CAAC;AAQ1C;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IAOT;IACA;IAPF,UAAU,CAAmB;IAC7B,OAAO,CAAwD;IAC/D,cAAc,CAAgC;IAE/D,YACE,MAA2C,EAC1B,IAAqB,EACrB,MAAwB;QADxB,SAAI,GAAJ,IAAI,CAAiB;QACrB,WAAM,GAAN,MAAM,CAAkB;QAEzC,IAAI,CAAC,UAAU,GAAG,MAAM,EAAE,UAAU,EAAE,MAAM;YAC1C,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,I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,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAUlE,QAA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,IAAI,CAAC;QACtB,QAAQ,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;CAcpC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { pgBoolean, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BalanceRowSchema = z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,OAAO,EAAE,OAAO;IAChB,kBAAkB,EAAE,OAAO;CAC5B,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,MAAM,EAAE,OAAO;IACf,WAA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,CAAC,CAAC,CAAC,IAAI;YACvE,UAAU,EAAE,GAAG,CAAC,QAAQ;YACxB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,8BAA8B,CAC/B,CAAC;IACJ,CAAC;IAED,8DAA8D;IAC9D,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,EAAE,gCAAgC,CAA4B,CAAC;QAC1F,OAAO,SAAS,CACd,kBAAkB,EAClB;YACE,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,SAAS,EAAE,GAAG,CAAC,SAAS;SACzB,EACD,gCAAgC,CACjC,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,KAAK,CAAC,mBAAmB,CAAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n | Record<string, unknown>\n | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n | Record<string, unknown>\n | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,SAAS,EACT,YAAY,EACZ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Q;YACtB,SAAS,EAAE,GAAG,CAAC,SAAS;SACzB,EACD,gCAAgC,CACjC,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,KAAK,CAAC,mBAAmB,CAAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { postgresUuid, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BucketRowSchema = z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE7F,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,E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AI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CACvC,SAAS,CAAC,eAAe,EAAE,GAAG,EAAE,oCAAoC,CAAC,CACtE,CAAC;QACF,MAAM,YAAY,GAAG,OAAO;aACzB,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;aAC/D,QAAQ,EAAE,CAAC;QACd,OAAO,SAAS,CACd,uBAAuB,EACvB;YACE,OAAO,EAAE,MAAM;YACf,OAAO;YACP,aAAa,EAAE,YAAY;SAC5B,EACD,oCAAoC,CACrC,CAAC;IACJ,CAAC;IAED,mCAAmC;IACnC,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK,EAAE,MAAe,EAAE,KAAK,GAAG,GAAG;QACpE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QACxF,OAAO,SAAS,CACd,cAAc,EACd,UAAU,CAAC,IAAI,EAAE,sCAAsC,CAAC,EACxD,sCAAsC,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BucketRowSchema = z\n .object({\n bucket_key: z.string().min(1),\n label: z.string().min(1),\n priority: z.number().int().nonnegative(),\n expires: z.boolean(),\n balance: decimal,\n })\n .strict();\n\nconst BucketEnvelopeRowSchema = z\n .object({\n user_id: postgresUuid,\n buckets: z.array(BucketRowSchema),\n total_balance: decimal,\n })\n .strict();\n\nconst SweepRowSchema = z\n .object({\n expired_count: z.number().int().nonnegative(),\n expired_amount: decimal,\n expired_by_bucket: z.record(z.string().min(1), decimal),\n })\n .strict();\n\nexport type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;\nexport type SweepRow = z.infer<typeof SweepRowSchema>;\n\n/** Repository for credit bucket operations. */\nexport class BucketRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch per-bucket credit balances for a user. */\n async getBucketBalances(userId: string): Promise<BucketEnvelopeRow> {\n const rows = await this.callproc(\"get_credit_bucket_balances\", [userId]);\n const buckets = (rows ?? []).map((row) =>\n safeParse(BucketRowSchema, row, \"BucketRepository.getBucketBalances\"),\n );\n const totalBalance = buckets\n .reduce((total, row) => total.plus(row.balance), new Decimal(0))\n .toString();\n return safeParse(\n BucketEnvelopeRowSchema,\n {\n user_id: userId,\n buckets,\n total_balance: totalBalance,\n },\n \"BucketRepository.getBucketBalances\",\n );\n }\n\n /** Sweep expired credit grants. */\n async sweepExpiredCredits(dryRun = false, userId?: string, limit = 100): Promise<SweepRow> {\n const rows = await this.callproc(\"sweep_expired_lots\", [limit, userId ?? null, dryRun]);\n return safeParse(\n SweepRowSchema,\n requireRow(rows, \"BucketRepository.sweepExpiredCredits\"),\n \"BucketRepository.sweepExpiredCredits\",\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO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CAAC;QACvB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;QACtB,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC;QACnB,QAAQ,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,YAAY,CAAC;IAyDzB,wEAAwE;IAClE,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC;IAQhG,qDAAqD;IAC/C,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAiBxE,4EAA4E;IACtE,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAuCxF,uEAAuE;IACjE,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CASnD"}
|
|
@@ -2,7 +2,8 @@ import { z } from "zod";
|
|
|
2
2
|
import { DeductionRowSchema } from "./deduction.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
|
-
import Decimal from "decimal.js";
|
|
5
|
+
import { Decimal } from "decimal.js";
|
|
6
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
6
7
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
7
8
|
const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
|
|
8
9
|
const parsed = value instanceof Date ? value : new Date(value);
|
|
@@ -165,7 +166,8 @@ export class LeaseRepository {
|
|
|
165
166
|
params.metadata,
|
|
166
167
|
]);
|
|
167
168
|
const row = safeParse(SettleLeaseRpcRowSchema, requireRow(rows, "LeaseRepository.settleLease"), "LeaseRepository.settleLease");
|
|
168
|
-
if (row.error_code === null &&
|
|
169
|
+
if (row.error_code === null &&
|
|
170
|
+
!new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))) {
|
|
169
171
|
throw new StoreError("LeaseRepository.settleLease: committed amount differs from the request", {
|
|
170
172
|
indeterminate: true,
|
|
171
173
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,E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AAC,UAAU;aACtB,EACD,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport Decimal from \"decimal.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (row.error_code === null && !new Decimal(row.settled_amount).equals(params.amount)) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;QAC5E,OAAO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,CAC7B,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|