@zonastery/bursar 2.0.0 → 2.0.2
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 +21 -14
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +6 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +3 -0
- 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/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.js +4 -4
- 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/store.d.ts +5 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +5 -0
- 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.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/events.d.ts +3 -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/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 +99 -59
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +8 -4
- 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/types.d.ts +0 -5
- 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 +7 -0
- 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 +4 -6
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +3 -12
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +23 -20
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +2 -3
- 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.map +1 -1
- package/dist/credits/postgres/store.d.ts +15 -11
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +24 -15
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/service-types.d.ts +17 -15
- 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 +16 -17
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +61 -33
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +16 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +3 -1
- 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/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.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/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 +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -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/providers/_shared.js +1 -1
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +3 -1
- 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 +5 -13
- 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 +22 -71
- 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.js +11 -11
- 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 -19
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.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 +4 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +6 -2
- 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/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +22 -21
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +67 -46
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +11 -7
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +52 -8
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +52 -36
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,kBAAkB,EAElB,aAAa,EACb,eAAe,EAEf,0BAA0B,EAC1B,iBAAiB,EACjB,uBAAuB,EACvB,WAAW,EACX,UAAU,EACV,YAAY,EACZ,wBAAwB,EACxB,sBAAsB,EACtB,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,WAAW,EACX,mBAAmB,EACnB,UAAU,EACV,eAAe,EACf,iBAAiB,EAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAE,kBAAkB,EAAmB,MAAM,aAAa,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAQlD,OAAO,KAAK,EACV,iBAAiB,EACjB,2BAA2B,EAC3B,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,6BAA6B,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;OAMG;IACG,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;YAoEjB,QAAQ;IAYtB;;;;;OAKG;IACG,mBAAmB,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,WAAW,CAAC;CAGhE"}
|
package/dist/credits/service.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import Decimal from "decimal.js";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
2
|
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
4
3
|
import { raiseDeductError } from "./service-errors.js";
|
|
5
4
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
5
|
import { CreditQueries } from "./queries.js";
|
|
7
|
-
import { CatalogRuntime
|
|
6
|
+
import { CatalogRuntime } from "./catalog-runtime.js";
|
|
7
|
+
import { toDecimal } from "./amount.js";
|
|
8
8
|
import { CreditLeaseWorkflow } from "./lease-workflow.js";
|
|
9
|
+
import { requireStableKey } from "../shared/idempotency.js";
|
|
9
10
|
/**
|
|
10
11
|
* Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
|
|
11
12
|
* Long batch/agentic jobs call the configured lease TTL before this elapses.
|
|
@@ -273,9 +274,14 @@ export class CreditsService {
|
|
|
273
274
|
}
|
|
274
275
|
/** Add credits to a user's account. */
|
|
275
276
|
async addCredits(userId, amount, options) {
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
277
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
278
|
+
const type = options.type ?? "adjustment";
|
|
279
|
+
this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
|
|
280
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
|
|
281
|
+
...options,
|
|
282
|
+
type,
|
|
283
|
+
idempotencyKey,
|
|
284
|
+
});
|
|
279
285
|
this.emit("credits.added", userId, {
|
|
280
286
|
entryId: result.entryId,
|
|
281
287
|
amount: result.amount,
|
|
@@ -295,13 +301,19 @@ export class CreditsService {
|
|
|
295
301
|
* bypass the usage-based `deduct()` flow.
|
|
296
302
|
*/
|
|
297
303
|
async deductCredits(userId, amount, options) {
|
|
298
|
-
const
|
|
304
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
305
|
+
const entryType = options.entryType ?? "adjustment";
|
|
299
306
|
this.logger.info("[CreditsService] deductCredits", {
|
|
300
307
|
amount,
|
|
301
308
|
entryType,
|
|
302
|
-
bucket: options
|
|
309
|
+
bucket: options.bucket,
|
|
310
|
+
});
|
|
311
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), {
|
|
312
|
+
type: entryType,
|
|
313
|
+
metadata: options.metadata,
|
|
314
|
+
bucket: options.bucket,
|
|
315
|
+
idempotencyKey,
|
|
303
316
|
});
|
|
304
|
-
const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
|
|
305
317
|
this.emit("credits.deducted", userId, {
|
|
306
318
|
entryId: result.entryId,
|
|
307
319
|
amount: result.amount,
|
|
@@ -342,24 +354,31 @@ export class CreditsService {
|
|
|
342
354
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
343
355
|
*/
|
|
344
356
|
async grantSubscriptionCycle(userId, amount, options) {
|
|
357
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
345
358
|
this.logger.info("[CreditsService] grantSubscriptionCycle", {
|
|
346
359
|
amount,
|
|
347
|
-
bucket: options
|
|
348
|
-
planKey: options
|
|
360
|
+
bucket: options.bucket,
|
|
361
|
+
planKey: options.planKey,
|
|
349
362
|
});
|
|
350
|
-
if (options
|
|
363
|
+
if (options.expiresAt != null && options.ttlDays != null) {
|
|
351
364
|
throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
|
|
352
365
|
}
|
|
353
|
-
const bucket = options
|
|
354
|
-
const expiresAt = options
|
|
366
|
+
const bucket = options.bucket ?? "subscription";
|
|
367
|
+
const expiresAt = options.ttlDays != null
|
|
355
368
|
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
356
|
-
: options
|
|
369
|
+
: options.expiresAt;
|
|
357
370
|
const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
|
|
358
|
-
const result = await this.store.addCredits(userId, amountDec,
|
|
371
|
+
const result = await this.store.addCredits(userId, amountDec, {
|
|
372
|
+
type: "purchase",
|
|
373
|
+
metadata: options.metadata,
|
|
374
|
+
expiresAt,
|
|
375
|
+
bucket,
|
|
376
|
+
idempotencyKey,
|
|
377
|
+
});
|
|
359
378
|
// The store contract exposes the mutation's replay result directly, avoiding
|
|
360
379
|
// a racy lifetime-balance comparison and an extra database round trip.
|
|
361
380
|
const isFreshGrant = !result.idempotent;
|
|
362
|
-
if (options
|
|
381
|
+
if (options.planKey) {
|
|
363
382
|
// A fresh cycle intentionally re-anchors plan-assignment windows. On a
|
|
364
383
|
// webhook replay, repair a previously interrupted grant->assignment saga
|
|
365
384
|
// without re-anchoring an assignment that already succeeded.
|
|
@@ -372,8 +391,8 @@ export class CreditsService {
|
|
|
372
391
|
amount: amountDec,
|
|
373
392
|
newBalance: result.newBalance,
|
|
374
393
|
bucket,
|
|
375
|
-
planKey: options
|
|
376
|
-
idempotencyKey
|
|
394
|
+
planKey: options.planKey ?? null,
|
|
395
|
+
idempotencyKey,
|
|
377
396
|
idempotent: result.idempotent,
|
|
378
397
|
});
|
|
379
398
|
return result;
|
|
@@ -421,18 +440,18 @@ export class CreditsService {
|
|
|
421
440
|
await this.maybeLazyExpire(userId);
|
|
422
441
|
this.logger.debug("[CreditsService] deduct", {
|
|
423
442
|
model: metrics.dimensions?.model,
|
|
424
|
-
feature: options
|
|
443
|
+
feature: options.feature,
|
|
425
444
|
});
|
|
426
445
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
427
446
|
const plan = await this.store.getUserPlan(userId);
|
|
428
|
-
const effectiveIdempotencyKey = options?.idempotencyKey
|
|
447
|
+
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
429
448
|
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
430
449
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
431
450
|
const cost = breakdown.total;
|
|
432
451
|
// Build ledger metadata: caller fields FIRST, system fields LAST so the
|
|
433
452
|
// protected system fields win.
|
|
434
453
|
const meta = {};
|
|
435
|
-
if (options
|
|
454
|
+
if (options.metadata) {
|
|
436
455
|
for (const [k, v] of Object.entries(options.metadata)) {
|
|
437
456
|
if (v != null)
|
|
438
457
|
meta[k] = v;
|
|
@@ -446,7 +465,7 @@ export class CreditsService {
|
|
|
446
465
|
const deductionOptions = {
|
|
447
466
|
idempotencyKey: effectiveIdempotencyKey,
|
|
448
467
|
operation: metrics.operation,
|
|
449
|
-
feature: options
|
|
468
|
+
feature: options.feature ?? null,
|
|
450
469
|
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
451
470
|
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
452
471
|
measures: { ...(metrics.measures ?? {}) },
|
|
@@ -464,7 +483,7 @@ export class CreditsService {
|
|
|
464
483
|
error: result.error,
|
|
465
484
|
amount: cost,
|
|
466
485
|
model: metrics.dimensions?.model,
|
|
467
|
-
feature: options
|
|
486
|
+
feature: options.feature,
|
|
468
487
|
});
|
|
469
488
|
this.emit("credits.deduct_failed", userId, {
|
|
470
489
|
error: result.error,
|
|
@@ -502,10 +521,10 @@ export class CreditsService {
|
|
|
502
521
|
async recordUsage(userId, metrics, options) {
|
|
503
522
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
504
523
|
const plan = await this.store.getUserPlan(userId);
|
|
505
|
-
const effectiveIdempotencyKey = options?.idempotencyKey
|
|
524
|
+
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
506
525
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
507
526
|
const meta = {};
|
|
508
|
-
if (options
|
|
527
|
+
if (options.metadata) {
|
|
509
528
|
for (const [key, value] of Object.entries(options.metadata)) {
|
|
510
529
|
if (value != null)
|
|
511
530
|
meta[key] = value;
|
|
@@ -543,13 +562,18 @@ export class CreditsService {
|
|
|
543
562
|
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
|
|
544
563
|
}
|
|
545
564
|
async refundCredits(entryId, options) {
|
|
546
|
-
const
|
|
565
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
566
|
+
const refundAmount = options.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
|
|
547
567
|
this.logger.info("[CreditsService] refundCredits", {
|
|
548
568
|
entryId,
|
|
549
569
|
refundAmount,
|
|
550
|
-
reason: options
|
|
570
|
+
reason: options.reason,
|
|
571
|
+
});
|
|
572
|
+
const result = await this.store.refundCredits(entryId, {
|
|
573
|
+
...options,
|
|
574
|
+
amount: refundAmount,
|
|
575
|
+
idempotencyKey,
|
|
551
576
|
});
|
|
552
|
-
const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
|
|
553
577
|
if (result.error !== null) {
|
|
554
578
|
this.logger.warn("[CreditsService] refundCredits failed", {
|
|
555
579
|
entryId,
|
|
@@ -559,7 +583,7 @@ export class CreditsService {
|
|
|
559
583
|
this.emit("credits.refund_failed", result.userId, {
|
|
560
584
|
entryId,
|
|
561
585
|
error: result.error,
|
|
562
|
-
reason: options
|
|
586
|
+
reason: options.reason ?? null,
|
|
563
587
|
});
|
|
564
588
|
}
|
|
565
589
|
throw new RefundError(`Refund rejected: ${result.error}`);
|
|
@@ -569,7 +593,7 @@ export class CreditsService {
|
|
|
569
593
|
refundEntryId: result.refundEntryId,
|
|
570
594
|
amount: result.amount,
|
|
571
595
|
newBalance: result.newBalance,
|
|
572
|
-
reason: options
|
|
596
|
+
reason: options.reason ?? null,
|
|
573
597
|
});
|
|
574
598
|
return result;
|
|
575
599
|
}
|
|
@@ -577,10 +601,11 @@ export class CreditsService {
|
|
|
577
601
|
* Deduct from a team's shared balance pool.
|
|
578
602
|
*
|
|
579
603
|
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
580
|
-
* then debits the team balance. Threads
|
|
604
|
+
* then debits the team balance. Threads a required ``idempotencyKey`` through
|
|
581
605
|
* to the store so retried team charges are not double-counted.
|
|
582
606
|
*/
|
|
583
607
|
async deductTeam(teamId, userId, metrics, options) {
|
|
608
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
584
609
|
await this.maybeLazyExpire(userId);
|
|
585
610
|
// Lazy expiry is scoped to the individual member's credits, not the team's
|
|
586
611
|
// shared pool — there's no per-team expiry concept.
|
|
@@ -604,13 +629,16 @@ export class CreditsService {
|
|
|
604
629
|
};
|
|
605
630
|
}
|
|
606
631
|
const teamMetadata = {
|
|
607
|
-
...(options
|
|
632
|
+
...(options.metadata ?? {}),
|
|
608
633
|
operation: metrics.operation,
|
|
609
634
|
measures: { ...(metrics.measures ?? {}) },
|
|
610
635
|
dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
|
|
611
636
|
breakdownTotal: breakdown.total.toString(),
|
|
612
637
|
};
|
|
613
|
-
const result = await this.store.deductTeam(teamId, userId, cost,
|
|
638
|
+
const result = await this.store.deductTeam(teamId, userId, cost, {
|
|
639
|
+
metadata: teamMetadata,
|
|
640
|
+
idempotencyKey,
|
|
641
|
+
});
|
|
614
642
|
// Surface store errors: emit credits.deduct_failed and throw,
|
|
615
643
|
// mirroring the Python credit service implementation. Previously returned a silent
|
|
616
644
|
// success-shaped object with an .error field, so failed charges looked OK.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"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,KAAK,KAAK,2BAA2B,EAAE,CAAC;gBACjD,MAAM,IAAI,eAAe,CACvB,wCAAwC,MAAM,UAAU,MAAM,eAAe,IAAI,EAAE,CACpF,CAAC;YACJ,CAAC;YACD,MAAM,IAAI,wBAAwB,CAChC,0BAA0B,MAAM,CAAC,KAAK,UAAU,MAAM,UAAU,MAAM,eAAe,IAAI,EAAE,CAC5F,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE;YACpC,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,MAAM;YACN,UAAU,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACO,KAAK,CAAC,QAAQ,CAAC,MAAe,EAAE,MAAe;QACrD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime, toDecimal } from \"./catalog-runtime.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: Decimal | number, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.store.executeGrantProgram(request);\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(\n config: Record<string, unknown>,\n label?: string | null,\n ): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: Decimal | number,\n options?: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const type = options?.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options?.bucket });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"addCredits\"),\n type,\n options?.metadata,\n options?.expiresAt,\n options?.bucket,\n options?.idempotencyKey,\n );\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: Decimal | number,\n options?: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const entryType = options?.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options?.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n entryType,\n options?.metadata ?? null,\n null,\n options?.bucket ?? undefined,\n options?.idempotencyKey,\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: Decimal | number,\n options?: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options?.bucket,\n planKey: options?.planKey,\n });\n if (options?.expiresAt != null && options?.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options?.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options?.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options?.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(\n userId,\n amountDec,\n \"purchase\",\n options?.metadata,\n expiresAt,\n bucket,\n options?.idempotencyKey,\n );\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options?.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options?.planKey ?? null,\n idempotencyKey: options?.idempotencyKey ?? null,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.leases.reserve(userId, metricsOrAmount, options);\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.leases.settle(userId, leaseId, metricsOrAmount, options);\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.leases.release(userId, leaseId);\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options?: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options?.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: Record<string, unknown> = {};\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options?.feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options?.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options?: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (options?.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options?: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options?: RefundCreditsOptions): Promise<RefundSuccess> {\n const refundAmount =\n options?.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options?.reason,\n });\n const result = await this.store.refundCredits(\n entryId,\n refundAmount,\n options?.reason,\n options?.metadata,\n options?.idempotencyKey,\n );\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options?.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options?.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads an optional ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options?: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options?.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(\n teamId,\n userId,\n cost,\n teamMetadata,\n options?.idempotencyKey,\n );\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AA+CtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD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,EAAE,CACpF,CAAC;YACJ,CAAC;YACD,MAAM,IAAI,wBAAwB,CAChC,0BAA0B,MAAM,CAAC,KAAK,UAAU,MAAM,UAAU,MAAM,eAAe,IAAI,EAAE,CAC5F,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE;YACpC,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,MAAM;YACN,UAAU,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACO,KAAK,CAAC,QAAQ,CAAC,MAAe,EAAE,MAAe;QACrD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { toDecimal } from \"./amount.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport { requireStableKey } from \"../shared/idempotency.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: ExactAmount, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.store.executeGrantProgram(request);\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const type = options.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options.bucket });\n const result = await this.store.addCredits(userId, positiveAmount(amount, \"addCredits\"), {\n ...options,\n type,\n idempotencyKey,\n });\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: ExactAmount,\n options: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const entryType = options.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n {\n type: entryType,\n metadata: options.metadata,\n bucket: options.bucket,\n idempotencyKey,\n },\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options.bucket,\n planKey: options.planKey,\n });\n if (options.expiresAt != null && options.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(userId, amountDec, {\n type: \"purchase\",\n metadata: options.metadata,\n expiresAt,\n bucket,\n idempotencyKey,\n });\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options.planKey ?? null,\n idempotencyKey,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.leases.reserve(userId, metricsOrAmount, options);\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.leases.settle(userId, leaseId, metricsOrAmount, options);\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.leases.release(userId, leaseId);\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options.feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const refundAmount =\n options.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options.reason,\n });\n const result = await this.store.refundCredits(entryId, {\n ...options,\n amount: refundAmount,\n idempotencyKey,\n });\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads a required ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(teamId, userId, cost, {\n metadata: teamMetadata,\n idempotencyKey,\n });\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
|