@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.
Files changed (173) hide show
  1. package/README.md +21 -14
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-store.d.ts +3 -0
  6. package/dist/billing/billing-store.d.ts.map +1 -1
  7. package/dist/billing/billing-store.js +2 -0
  8. package/dist/billing/billing-store.js.map +1 -1
  9. package/dist/billing/event-handlers.d.ts +2 -3
  10. package/dist/billing/event-handlers.d.ts.map +1 -1
  11. package/dist/billing/event-handlers.js +38 -49
  12. package/dist/billing/event-handlers.js.map +1 -1
  13. package/dist/billing/event-processor.js +4 -4
  14. package/dist/billing/event-processor.js.map +1 -1
  15. package/dist/billing/financial-event-handlers.d.ts +2 -2
  16. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  17. package/dist/billing/financial-event-handlers.js +7 -7
  18. package/dist/billing/financial-event-handlers.js.map +1 -1
  19. package/dist/billing/postgres/store.d.ts +5 -1
  20. package/dist/billing/postgres/store.d.ts.map +1 -1
  21. package/dist/billing/postgres/store.js +5 -0
  22. package/dist/billing/postgres/store.js.map +1 -1
  23. package/dist/billing/service-types.d.ts +2 -15
  24. package/dist/billing/service-types.d.ts.map +1 -1
  25. package/dist/billing/service-types.js.map +1 -1
  26. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  27. package/dist/billing/types/auto-recharge.js.map +1 -1
  28. package/dist/billing/types/events.d.ts +3 -2
  29. package/dist/billing/types/events.d.ts.map +1 -1
  30. package/dist/billing/types/events.js +2 -2
  31. package/dist/billing/types/events.js.map +1 -1
  32. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  33. package/dist/billing/types/subscriptions.js.map +1 -1
  34. package/dist/bursar.d.ts +21 -11
  35. package/dist/bursar.d.ts.map +1 -1
  36. package/dist/bursar.js +40 -4
  37. package/dist/bursar.js.map +1 -1
  38. package/dist/catalog.d.ts.map +1 -1
  39. package/dist/catalog.js +1 -1
  40. package/dist/catalog.js.map +1 -1
  41. package/dist/commerce/index.d.ts +0 -1
  42. package/dist/commerce/index.d.ts.map +1 -1
  43. package/dist/commerce/index.js +0 -1
  44. package/dist/commerce/index.js.map +1 -1
  45. package/dist/commerce/service.d.ts.map +1 -1
  46. package/dist/commerce/service.js +99 -59
  47. package/dist/commerce/service.js.map +1 -1
  48. package/dist/commerce/types.d.ts +8 -4
  49. package/dist/commerce/types.d.ts.map +1 -1
  50. package/dist/commerce/types.js.map +1 -1
  51. package/dist/config/parse-credits.d.ts.map +1 -1
  52. package/dist/config/parse-credits.js +0 -6
  53. package/dist/config/parse-credits.js.map +1 -1
  54. package/dist/config/types.d.ts +0 -5
  55. package/dist/config/types.d.ts.map +1 -1
  56. package/dist/config/types.js.map +1 -1
  57. package/dist/config.d.ts.map +1 -1
  58. package/dist/config.js +7 -0
  59. package/dist/config.js.map +1 -1
  60. package/dist/credits/amount.d.ts +8 -0
  61. package/dist/credits/amount.d.ts.map +1 -0
  62. package/dist/credits/amount.js +32 -0
  63. package/dist/credits/amount.js.map +1 -0
  64. package/dist/credits/catalog-runtime.d.ts +4 -6
  65. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  66. package/dist/credits/catalog-runtime.js +3 -12
  67. package/dist/credits/catalog-runtime.js.map +1 -1
  68. package/dist/credits/lease-workflow.d.ts +1 -1
  69. package/dist/credits/lease-workflow.d.ts.map +1 -1
  70. package/dist/credits/lease-workflow.js +23 -20
  71. package/dist/credits/lease-workflow.js.map +1 -1
  72. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  73. package/dist/credits/low-balance-monitor.js +2 -3
  74. package/dist/credits/low-balance-monitor.js.map +1 -1
  75. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  76. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  77. package/dist/credits/postgres/store.d.ts +15 -11
  78. package/dist/credits/postgres/store.d.ts.map +1 -1
  79. package/dist/credits/postgres/store.js +24 -15
  80. package/dist/credits/postgres/store.js.map +1 -1
  81. package/dist/credits/service-types.d.ts +17 -15
  82. package/dist/credits/service-types.d.ts.map +1 -1
  83. package/dist/credits/service-types.js.map +1 -1
  84. package/dist/credits/service.d.ts +16 -17
  85. package/dist/credits/service.d.ts.map +1 -1
  86. package/dist/credits/service.js +61 -33
  87. package/dist/credits/service.js.map +1 -1
  88. package/dist/credits/store.d.ts +16 -22
  89. package/dist/credits/store.d.ts.map +1 -1
  90. package/dist/credits/store.js +3 -1
  91. package/dist/credits/store.js.map +1 -1
  92. package/dist/credits/types/account.d.ts +1 -1
  93. package/dist/credits/types/account.d.ts.map +1 -1
  94. package/dist/credits/types/account.js.map +1 -1
  95. package/dist/credits/types/grants.d.ts.map +1 -1
  96. package/dist/credits/types/grants.js.map +1 -1
  97. package/dist/expr/ast.d.ts.map +1 -1
  98. package/dist/expr/ast.js.map +1 -1
  99. package/dist/expr/parser.d.ts +1 -0
  100. package/dist/expr/parser.d.ts.map +1 -1
  101. package/dist/expr/parser.js +15 -3
  102. package/dist/expr/parser.js.map +1 -1
  103. package/dist/generated/pricing-config.schema.json +31 -29
  104. package/dist/generated/pricing-config.types.d.ts +6 -18
  105. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  106. package/dist/generated/pricing-config.types.js.map +1 -1
  107. package/dist/index.d.ts +4 -2
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +1 -0
  110. package/dist/index.js.map +1 -1
  111. package/dist/load-config-file.d.ts +2 -3
  112. package/dist/load-config-file.d.ts.map +1 -1
  113. package/dist/load-config-file.js +14 -29
  114. package/dist/load-config-file.js.map +1 -1
  115. package/dist/providers/_shared.js +1 -1
  116. package/dist/providers/_shared.js.map +1 -1
  117. package/dist/providers/dodo/client-contract.d.ts +3 -1
  118. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  119. package/dist/providers/dodo/client-contract.js.map +1 -1
  120. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  121. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  122. package/dist/providers/dodo/event-mapper.js +5 -13
  123. package/dist/providers/dodo/event-mapper.js.map +1 -1
  124. package/dist/providers/dodo/provider.d.ts +4 -6
  125. package/dist/providers/dodo/provider.d.ts.map +1 -1
  126. package/dist/providers/dodo/provider.js +22 -71
  127. package/dist/providers/dodo/provider.js.map +1 -1
  128. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  129. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  130. package/dist/providers/dodo/webhook-bridge.js +0 -1
  131. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  132. package/dist/providers/environment.d.ts +6 -0
  133. package/dist/providers/environment.d.ts.map +1 -0
  134. package/dist/providers/environment.js +10 -0
  135. package/dist/providers/environment.js.map +1 -0
  136. package/dist/providers/index.d.ts +3 -7
  137. package/dist/providers/index.d.ts.map +1 -1
  138. package/dist/providers/index.js +1 -5
  139. package/dist/providers/index.js.map +1 -1
  140. package/dist/providers/mock/provider.d.ts +6 -8
  141. package/dist/providers/mock/provider.d.ts.map +1 -1
  142. package/dist/providers/mock/provider.js +18 -50
  143. package/dist/providers/mock/provider.js.map +1 -1
  144. package/dist/providers/stripe/event-mapper.js +11 -11
  145. package/dist/providers/stripe/event-mapper.js.map +1 -1
  146. package/dist/providers/stripe/provider.d.ts +3 -3
  147. package/dist/providers/stripe/provider.d.ts.map +1 -1
  148. package/dist/providers/stripe/provider.js +37 -24
  149. package/dist/providers/stripe/provider.js.map +1 -1
  150. package/dist/providers/types.d.ts +9 -19
  151. package/dist/providers/types.d.ts.map +1 -1
  152. package/dist/providers/types.js.map +1 -1
  153. package/dist/shared/idempotency.d.ts +9 -0
  154. package/dist/shared/idempotency.d.ts.map +1 -0
  155. package/dist/shared/idempotency.js +34 -0
  156. package/dist/shared/idempotency.js.map +1 -0
  157. package/dist/shared/postgres-client.d.ts +4 -0
  158. package/dist/shared/postgres-client.d.ts.map +1 -1
  159. package/dist/shared/postgres-client.js +6 -2
  160. package/dist/shared/postgres-client.js.map +1 -1
  161. package/dist/shared/postgres-errors.d.ts.map +1 -1
  162. package/dist/shared/postgres-errors.js.map +1 -1
  163. package/dist/storage/outbox-worker.d.ts.map +1 -1
  164. package/dist/storage/outbox-worker.js +22 -21
  165. package/dist/storage/outbox-worker.js.map +1 -1
  166. package/dist/storage/postgres-repository.d.ts.map +1 -1
  167. package/dist/storage/postgres-repository.js +67 -46
  168. package/dist/storage/postgres-repository.js.map +1 -1
  169. package/dist/storage/runtime.d.ts +11 -7
  170. package/dist/storage/runtime.d.ts.map +1 -1
  171. package/dist/storage/runtime.js +52 -8
  172. package/dist/storage/runtime.js.map +1 -1
  173. package/package.json +52 -36
@@ -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,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAwBtD,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,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,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,OAAO,MAAM,YAAY,CAAC;AACjC,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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C,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,eAAe,CAAC,YAAY,EAAE,SAAS,CAAC;SACzD,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY;YACZ,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,eAAe,CAAC,YAAY,EAAE,QAAQ,CAAC;gBACvD,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 { 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;AAGjC,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;AAI3D,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;IAe3C,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAalD,WAAW,CAAC,MAAM,EAAE,M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WpE,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
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;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAOrC,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;iBACd,GAAG,CAAC,CAAC,KAAK,EAAE,EA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AAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,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\";\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\n .map((value) => (value instanceof Decimal ? value : new Decimal(value)))\n .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
+ {"version":3,"file":"low-balance-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,YAAY,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,MAAc,EAAE,OAAgB,EAAE,SAAkB;QACrE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,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,QAAA,MAAM,gBAAgB;;;;kBAMX,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAgDrB,CAAC;AAEL,QAAA,MAAM,kBAAkB;;;;kBAMb,CAAC;AAEZ,QAAA,MAAM,0BAA0B;;;;;;;;kBA+B5B,CAAC;AAEL,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAC1D,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC,CAAC;AAE9E;;;;;;GAMG;AACH,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ;gB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AM,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,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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AAC,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,7 +1,8 @@
1
1
  import Decimal from "decimal.js";
2
- import { type CatalogRollout } from "../../config.js";
2
+ import { type BursarConfigData, type CatalogRollout } from "../../config.js";
3
3
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
4
- import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
4
+ import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
5
+ import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "../service-types.js";
5
6
  import { CreditStore } from "../store.js";
6
7
  import type { CreateLeaseOptions, SettleLeaseOptions } from "../store.js";
7
8
  export type PgPool = PostgresPool;
@@ -12,11 +13,14 @@ export interface PostgresStoreOptions extends PostgresConnectionOptions {
12
13
  postgres: string | PgPool;
13
14
  /** Tenant UUID bound to every store transaction. */
14
15
  tenantId: string;
16
+ /** Explicit financial namespace for catalog provider references. */
17
+ providerEnvironment: NonNullable<PostgresConnectionOptions["providerEnvironment"]>;
15
18
  /** Injectable `pg.Pool` constructor for custom runtimes and tests. */
16
19
  poolConstructor?: PgPoolConstructor;
17
20
  usageBackend?: "postgres" | "clickhouse";
18
21
  }
19
22
  export declare class PostgresStore extends CreditStore {
23
+ readonly providerEnvironment: NonNullable<PostgresConnectionOptions["providerEnvironment"]>;
20
24
  private readonly postgres;
21
25
  private _balanceRepo;
22
26
  private _deductionRepo;
@@ -41,10 +45,10 @@ export declare class PostgresStore extends CreditStore {
41
45
  private static readonly SCALAR_RPC_NAMES;
42
46
  private callproc;
43
47
  getBalance(userId: string): Promise<BalanceResult>;
44
- addCredits(userId: string, amount: Decimal, type?: string, metadata?: CreditMetadata | null, expiresAt?: Date | null, bucket?: string | null, idempotencyKey?: string | null): Promise<AddCreditsResult>;
45
- deductWithAllowance(userId: string, amount: Decimal, options?: DeductWithAllowanceOptions): Promise<DeductionResult>;
46
- recordUsage(userId: string, operation: string, amount: Decimal, options?: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
47
- createLease(userId: string, amount: Decimal, operationType: string, options?: CreateLeaseOptions): Promise<LeaseResult>;
48
+ addCredits(userId: string, amount: Decimal, options: AddCreditsOptions): Promise<AddCreditsResult>;
49
+ deductWithAllowance(userId: string, amount: Decimal, options: DeductWithAllowanceOptions): Promise<DeductionResult>;
50
+ recordUsage(userId: string, operation: string, amount: Decimal, options: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
51
+ createLease(userId: string, amount: Decimal, operationType: string, options: CreateLeaseOptions): Promise<LeaseResult>;
48
52
  settleLease(userId: string, leaseId: string, amount: Decimal, options?: SettleLeaseOptions): Promise<DeductionResult>;
49
53
  getLeasePricingContext(userId: string, leaseId: string): Promise<LeasePricingContext | null>;
50
54
  releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;
@@ -53,11 +57,11 @@ export declare class PostgresStore extends CreditStore {
53
57
  getAvailable(userId: string): Promise<AvailableResult>;
54
58
  getActiveCatalog(): Promise<CatalogRevision | null>;
55
59
  private loadActiveCatalog;
56
- publishAndActivateCatalog(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
57
- publishCatalogDraft(config: Record<string, unknown>, label?: string | null): Promise<string>;
60
+ publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
61
+ publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
58
62
  getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
59
63
  getCatalogRevision(version: number): Promise<CatalogRevision | null>;
60
- activateCatalogRevision(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
64
+ activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
61
65
  getUserPlan(userId: string): Promise<GetUserPlanResult>;
62
66
  checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;
63
67
  setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
@@ -70,7 +74,7 @@ export declare class PostgresStore extends CreditStore {
70
74
  listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;
71
75
  checkAllowance(userId: string): Promise<AllowanceResult | null>;
72
76
  revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;
73
- refundCredits(entryId: string, amount?: Decimal, reason?: string, metadata?: CreditMetadata | null, idempotencyKey?: string | null): Promise<RefundResult>;
77
+ refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;
74
78
  aggregateStats(start: Date, end: Date): Promise<AggregateStats>;
75
79
  spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]>;
76
80
  spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]>;
@@ -86,7 +90,7 @@ export declare class PostgresStore extends CreditStore {
86
90
  addTeamMember(teamId: string, userId: string, role?: TeamRole, spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
87
91
  getTeamMembers(teamId: string): Promise<TeamMember[]>;
88
92
  removeTeamMember(teamId: string, userId: string): Promise<boolean>;
89
- deductTeam(teamId: string, userId: string, amount: Decimal, metadata?: CreditMetadata | null, idempotencyKey?: string | null): Promise<TeamDeductionResult>;
93
+ deductTeam(teamId: string, userId: string, amount: Decimal, options: DeductTeamOptions): Promise<TeamDeductionResult>;
90
94
  sweepExpiredCredits(dryRun?: boolean, userId?: string, limit?: number): Promise<SweepResult>;
91
95
  getBucketBalances(userId: string): Promise<BucketBalancesResult>;
92
96
  executeGrantProgram(request: ExecuteGrantProgramRequest): Promise<GrantProgramAwardResult[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC,OAAO,EAML,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,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AC;IAWjE,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,IAAI,GAAE,QAAmB,EACzB,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI,GACxB,OAAO,CAAC,mBAAmB,CAAC;IAczB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAUrD,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAIlE,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAsCzB,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAYvF,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAYhE,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC;CAiCtC"}
@@ -1,8 +1,8 @@
1
1
  import Decimal from "decimal.js";
2
- import { randomUUID } from "node:crypto";
3
2
  import { StoreClosedError, StoreError } from "../../errors.js";
4
3
  import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
5
4
  import { PostgresClient, } from "../../shared/postgres-client.js";
5
+ import { requireStableKey } from "../../shared/idempotency.js";
6
6
  import { CreditStore } from "../store.js";
7
7
  import { BalanceRepository } from "./repositories/balance.js";
8
8
  import { DeductionRepository } from "./repositories/deduction.js";
@@ -23,6 +23,7 @@ function requireText(value, context) {
23
23
  return value;
24
24
  }
25
25
  export class PostgresStore extends CreditStore {
26
+ providerEnvironment;
26
27
  postgres;
27
28
  _balanceRepo = null;
28
29
  _deductionRepo = null;
@@ -88,8 +89,10 @@ export class PostgresStore extends CreditStore {
88
89
  if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
89
90
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
90
91
  }
92
+ this.providerEnvironment = options.providerEnvironment;
91
93
  this.postgres = new PostgresClient(options.postgres, {
92
94
  tenantId: options.tenantId,
95
+ providerEnvironment: options.providerEnvironment,
93
96
  usageBackend: options.usageBackend,
94
97
  poolConstructor: options.poolConstructor,
95
98
  connectionTimeoutMs: options.connectionTimeoutMs,
@@ -145,12 +148,13 @@ export class PostgresStore extends CreditStore {
145
148
  lifetimePurchased: dec(row.lifetime_purchased),
146
149
  };
147
150
  }
148
- async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, bucket, idempotencyKey) {
149
- const meta = { ...(metadata ?? {}) };
150
- if (expiresAt) {
151
- meta.expires_at = expiresAt instanceof Date ? expiresAt.toISOString() : String(expiresAt);
151
+ async addCredits(userId, amount, options) {
152
+ const stableKey = requireStableKey(options?.idempotencyKey);
153
+ const meta = { ...(options?.metadata ?? {}) };
154
+ if (options?.expiresAt) {
155
+ meta.expires_at = options.expiresAt.toISOString();
152
156
  }
153
- const row = await this.balanceRepo.addCredits(userId, decParam(amount), type, JSON.stringify(meta), expiresAt ? expiresAt.toISOString() : null, bucket ?? null, idempotencyKey ?? `credit:${randomUUID()}`);
157
+ const row = await this.balanceRepo.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
154
158
  if (row.error !== null) {
155
159
  throw new StoreError(`post_credit: ${row.error}`);
156
160
  }
@@ -165,7 +169,7 @@ export class PostgresStore extends CreditStore {
165
169
  };
166
170
  }
167
171
  async deductWithAllowance(userId, amount, options) {
168
- const idempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
172
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
169
173
  const operation = options?.operation ??
170
174
  (typeof options?.metadata?.operation === "string" ? options.metadata.operation : "usage");
171
175
  const model = options?.model ?? null;
@@ -212,7 +216,7 @@ export class PostgresStore extends CreditStore {
212
216
  };
213
217
  }
214
218
  async recordUsage(userId, operation, amount, options) {
215
- const idempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
219
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
216
220
  const row = await this.deductionRepo.recordUsage({
217
221
  userId,
218
222
  operation,
@@ -243,11 +247,12 @@ export class PostgresStore extends CreditStore {
243
247
  };
244
248
  }
245
249
  async createLease(userId, amount, operationType, options) {
250
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
246
251
  const row = await this.leaseRepo.createLease({
247
252
  userId,
248
253
  amount: decParam(amount),
249
254
  operationType,
250
- idempotencyKey: options?.idempotencyKey ?? `lease:${randomUUID()}`,
255
+ idempotencyKey,
251
256
  ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
252
257
  metadata: JSON.stringify(options?.metadata ?? {}),
253
258
  feature: options?.feature ?? null,
@@ -283,11 +288,14 @@ export class PostgresStore extends CreditStore {
283
288
  };
284
289
  }
285
290
  async settleLease(userId, leaseId, amount, options) {
291
+ const idempotencyKey = options?.idempotencyKey === undefined
292
+ ? `lease:${leaseId}:settle`
293
+ : requireStableKey(options.idempotencyKey);
286
294
  const row = await this.leaseRepo.settleLease({
287
295
  userId,
288
296
  leaseId,
289
297
  amount: decParam(amount),
290
- idempotencyKey: options?.idempotencyKey ?? `lease:${leaseId}:settle`,
298
+ idempotencyKey,
291
299
  feature: options?.feature ?? null,
292
300
  model: options?.model ?? null,
293
301
  region: options?.region ?? null,
@@ -617,8 +625,9 @@ export class PostgresStore extends CreditStore {
617
625
  balanceAfter: dec(row.balance_after),
618
626
  };
619
627
  }
620
- async refundCredits(entryId, amount, reason, metadata, idempotencyKey) {
621
- const row = await this.deductionRepo.refundCredits(entryId, amount != null ? decParam(amount) : null, idempotencyKey ?? `refund:${entryId}:${amount != null ? decParam(amount) : "remaining"}`, reason ?? null, JSON.stringify(metadata ?? {}));
628
+ async refundCredits(entryId, options) {
629
+ const stableKey = requireStableKey(options?.idempotencyKey);
630
+ const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new Decimal(options.amount)) : null, stableKey, options?.reason ?? null, JSON.stringify(options?.metadata ?? {}));
622
631
  if (row.error !== null) {
623
632
  return {
624
633
  refundEntryId: null,
@@ -769,9 +778,9 @@ export class PostgresStore extends CreditStore {
769
778
  async removeTeamMember(teamId, userId) {
770
779
  return this.teamRepo.removeTeamMember(teamId, userId);
771
780
  }
772
- async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
773
- const meta = { ...(metadata ?? {}) };
774
- const effectiveIdempotencyKey = idempotencyKey ?? `team-usage:${randomUUID()}`;
781
+ async deductTeam(teamId, userId, amount, options) {
782
+ const meta = { ...(options?.metadata ?? {}) };
783
+ const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
775
784
  meta.idempotency_key = effectiveIdempotencyKey;
776
785
  const operation = typeof meta.operation === "string" && meta.operation.length > 0
777
786
  ? meta.operation