@zonastery/bursar 2.1.1 → 2.2.0

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 (334) hide show
  1. package/README.md +20 -3
  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-service.d.ts +19 -3
  6. package/dist/billing/billing-service.d.ts.map +1 -1
  7. package/dist/billing/billing-service.js +34 -5
  8. package/dist/billing/billing-service.js.map +1 -1
  9. package/dist/billing/billing-store.d.ts +12 -6
  10. package/dist/billing/billing-store.d.ts.map +1 -1
  11. package/dist/billing/billing-store.js +2 -0
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +20 -3
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +1 -0
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +40 -13
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +2 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +82 -16
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +2 -0
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +160 -48
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +6 -3
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +5 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  40. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  41. package/dist/billing/postgres/repositories/invoice.js +33 -3
  42. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  43. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/offer.js +2 -1
  45. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  46. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  47. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/payment.js +25 -17
  49. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  50. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  51. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/subscription-change.js +24 -4
  53. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription.js +40 -43
  57. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  58. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  59. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/topup.js +9 -5
  61. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  62. package/dist/billing/postgres/store.d.ts +24 -31
  63. package/dist/billing/postgres/store.d.ts.map +1 -1
  64. package/dist/billing/postgres/store.js +110 -113
  65. package/dist/billing/postgres/store.js.map +1 -1
  66. package/dist/billing/types/catalog.d.ts +1 -0
  67. package/dist/billing/types/catalog.d.ts.map +1 -1
  68. package/dist/billing/types/catalog.js.map +1 -1
  69. package/dist/billing/types/documents.d.ts +15 -1
  70. package/dist/billing/types/documents.d.ts.map +1 -1
  71. package/dist/billing/types/documents.js.map +1 -1
  72. package/dist/billing/types/events.d.ts +2 -0
  73. package/dist/billing/types/events.d.ts.map +1 -1
  74. package/dist/billing/types/events.js +15 -0
  75. package/dist/billing/types/events.js.map +1 -1
  76. package/dist/billing/types/subscriptions.d.ts +10 -0
  77. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  78. package/dist/billing/types/subscriptions.js.map +1 -1
  79. package/dist/breakdown.d.ts +2 -24
  80. package/dist/breakdown.d.ts.map +1 -1
  81. package/dist/breakdown.js +1 -29
  82. package/dist/breakdown.js.map +1 -1
  83. package/dist/bursar.d.ts +5 -17
  84. package/dist/bursar.d.ts.map +1 -1
  85. package/dist/bursar.js +26 -44
  86. package/dist/bursar.js.map +1 -1
  87. package/dist/cli.js +0 -6
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commerce/service.d.ts +1 -0
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +162 -38
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts +2 -0
  94. package/dist/commerce/types.d.ts.map +1 -1
  95. package/dist/commerce/types.js.map +1 -1
  96. package/dist/config/normalize.d.ts +3 -1
  97. package/dist/config/normalize.d.ts.map +1 -1
  98. package/dist/config/normalize.js +12 -5
  99. package/dist/config/normalize.js.map +1 -1
  100. package/dist/config/parse-access.d.ts.map +1 -1
  101. package/dist/config/parse-access.js +4 -1
  102. package/dist/config/parse-access.js.map +1 -1
  103. package/dist/config/parse-commerce.d.ts.map +1 -1
  104. package/dist/config/parse-commerce.js +32 -17
  105. package/dist/config/parse-commerce.js.map +1 -1
  106. package/dist/config/parse-credits.d.ts.map +1 -1
  107. package/dist/config/parse-credits.js +5 -5
  108. package/dist/config/parse-credits.js.map +1 -1
  109. package/dist/config/parse-plans.d.ts.map +1 -1
  110. package/dist/config/parse-plans.js +13 -9
  111. package/dist/config/parse-plans.js.map +1 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +7 -5
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +2 -0
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +11 -1
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config.d.ts +2 -2
  120. package/dist/config.d.ts.map +1 -1
  121. package/dist/config.js +94 -86
  122. package/dist/config.js.map +1 -1
  123. package/dist/credits/amount.d.ts.map +1 -1
  124. package/dist/credits/amount.js +5 -4
  125. package/dist/credits/amount.js.map +1 -1
  126. package/dist/credits/catalog-runtime.d.ts +15 -2
  127. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  128. package/dist/credits/catalog-runtime.js +74 -18
  129. package/dist/credits/catalog-runtime.js.map +1 -1
  130. package/dist/credits/lease-workflow.d.ts +3 -1
  131. package/dist/credits/lease-workflow.d.ts.map +1 -1
  132. package/dist/credits/lease-workflow.js +47 -38
  133. package/dist/credits/lease-workflow.js.map +1 -1
  134. package/dist/credits/low-balance-monitor.d.ts +2 -7
  135. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  136. package/dist/credits/low-balance-monitor.js +6 -57
  137. package/dist/credits/low-balance-monitor.js.map +1 -1
  138. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  139. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  140. package/dist/credits/postgres/repositories/analytics.js +25 -7
  141. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  142. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  143. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  144. package/dist/credits/postgres/repositories/balance.js +33 -14
  145. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  146. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  147. package/dist/credits/postgres/repositories/bucket.js +2 -2
  148. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  149. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  150. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  151. package/dist/credits/postgres/repositories/catalog.js +2 -12
  152. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  153. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +9 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  158. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  159. package/dist/credits/postgres/repositories/lease.js +46 -12
  160. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  161. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  162. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  163. package/dist/credits/postgres/repositories/plan.js +4 -1
  164. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  165. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  166. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/team.js +9 -5
  168. package/dist/credits/postgres/repositories/team.js.map +1 -1
  169. package/dist/credits/postgres/store.d.ts +29 -20
  170. package/dist/credits/postgres/store.d.ts.map +1 -1
  171. package/dist/credits/postgres/store.js +329 -250
  172. package/dist/credits/postgres/store.js.map +1 -1
  173. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  174. package/dist/credits/postgres/value-mappers.js +4 -4
  175. package/dist/credits/postgres/value-mappers.js.map +1 -1
  176. package/dist/credits/rated-wire.d.ts +7 -0
  177. package/dist/credits/rated-wire.d.ts.map +1 -0
  178. package/dist/credits/rated-wire.js +70 -0
  179. package/dist/credits/rated-wire.js.map +1 -0
  180. package/dist/credits/service-errors.d.ts.map +1 -1
  181. package/dist/credits/service-errors.js +8 -1
  182. package/dist/credits/service-errors.js.map +1 -1
  183. package/dist/credits/service-types.d.ts +5 -7
  184. package/dist/credits/service-types.d.ts.map +1 -1
  185. package/dist/credits/service-types.js.map +1 -1
  186. package/dist/credits/service.d.ts +11 -9
  187. package/dist/credits/service.d.ts.map +1 -1
  188. package/dist/credits/service.js +156 -138
  189. package/dist/credits/service.js.map +1 -1
  190. package/dist/credits/store.d.ts +11 -3
  191. package/dist/credits/store.d.ts.map +1 -1
  192. package/dist/credits/store.js +9 -0
  193. package/dist/credits/store.js.map +1 -1
  194. package/dist/credits/types/account.d.ts +9 -1
  195. package/dist/credits/types/account.d.ts.map +1 -1
  196. package/dist/credits/types/account.js.map +1 -1
  197. package/dist/credits/types/admission.d.ts +1 -0
  198. package/dist/credits/types/admission.d.ts.map +1 -1
  199. package/dist/credits/types/admission.js.map +1 -1
  200. package/dist/credits/types/grants.d.ts +12 -0
  201. package/dist/credits/types/grants.d.ts.map +1 -1
  202. package/dist/credits/types/grants.js.map +1 -1
  203. package/dist/credits/types/ledger.d.ts +13 -0
  204. package/dist/credits/types/ledger.d.ts.map +1 -1
  205. package/dist/credits/types/ledger.js.map +1 -1
  206. package/dist/credits/types/quotas.d.ts +2 -1
  207. package/dist/credits/types/quotas.d.ts.map +1 -1
  208. package/dist/credits/types/quotas.js.map +1 -1
  209. package/dist/engine.d.ts.map +1 -1
  210. package/dist/engine.js +51 -34
  211. package/dist/engine.js.map +1 -1
  212. package/dist/errors.d.ts +12 -1
  213. package/dist/errors.d.ts.map +1 -1
  214. package/dist/errors.js +13 -0
  215. package/dist/errors.js.map +1 -1
  216. package/dist/expr/evaluator.d.ts.map +1 -1
  217. package/dist/expr/evaluator.js +29 -9
  218. package/dist/expr/evaluator.js.map +1 -1
  219. package/dist/expr/language.js +1 -1
  220. package/dist/expr/language.js.map +1 -1
  221. package/dist/expr.d.ts.map +1 -1
  222. package/dist/expr.js +5 -6
  223. package/dist/expr.js.map +1 -1
  224. package/dist/generated/pricing-config.schema.json +102 -202
  225. package/dist/generated/pricing-config.types.d.ts +7 -1
  226. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  227. package/dist/generated/pricing-config.types.js.map +1 -1
  228. package/dist/index.d.ts +6 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +3 -2
  231. package/dist/index.js.map +1 -1
  232. package/dist/load-config-file.d.ts.map +1 -1
  233. package/dist/load-config-file.js +38 -12
  234. package/dist/load-config-file.js.map +1 -1
  235. package/dist/metrics.d.ts +1 -1
  236. package/dist/metrics.d.ts.map +1 -1
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/node.d.ts +1 -1
  239. package/dist/node.d.ts.map +1 -1
  240. package/dist/node.js.map +1 -1
  241. package/dist/pricing-decimal.d.ts +7 -0
  242. package/dist/pricing-decimal.d.ts.map +1 -0
  243. package/dist/pricing-decimal.js +43 -0
  244. package/dist/pricing-decimal.js.map +1 -0
  245. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  246. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  247. package/dist/providers/dodo/better-auth-core.js +2 -2
  248. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  249. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  250. package/dist/providers/dodo/better-auth.js +16 -2
  251. package/dist/providers/dodo/better-auth.js.map +1 -1
  252. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  253. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  254. package/dist/providers/dodo/event-mapper.js +120 -18
  255. package/dist/providers/dodo/event-mapper.js.map +1 -1
  256. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  257. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  258. package/dist/providers/dodo/nextjs-core.js +2 -2
  259. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  260. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  261. package/dist/providers/dodo/nextjs.js +16 -6
  262. package/dist/providers/dodo/nextjs.js.map +1 -1
  263. package/dist/providers/dodo/provider.d.ts +5 -2
  264. package/dist/providers/dodo/provider.d.ts.map +1 -1
  265. package/dist/providers/dodo/provider.js +33 -6
  266. package/dist/providers/dodo/provider.js.map +1 -1
  267. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  268. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  269. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  270. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  271. package/dist/providers/index.d.ts +1 -1
  272. package/dist/providers/index.d.ts.map +1 -1
  273. package/dist/providers/index.js.map +1 -1
  274. package/dist/providers/mock/provider.d.ts +4 -1
  275. package/dist/providers/mock/provider.d.ts.map +1 -1
  276. package/dist/providers/mock/provider.js +3 -1
  277. package/dist/providers/mock/provider.js.map +1 -1
  278. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  279. package/dist/providers/stripe/event-mapper.js +48 -20
  280. package/dist/providers/stripe/event-mapper.js.map +1 -1
  281. package/dist/providers/stripe/provider.d.ts +4 -1
  282. package/dist/providers/stripe/provider.d.ts.map +1 -1
  283. package/dist/providers/stripe/provider.js +64 -23
  284. package/dist/providers/stripe/provider.js.map +1 -1
  285. package/dist/providers/types.d.ts +11 -1
  286. package/dist/providers/types.d.ts.map +1 -1
  287. package/dist/providers/types.js +9 -0
  288. package/dist/providers/types.js.map +1 -1
  289. package/dist/shared/postgres-client.d.ts +3 -0
  290. package/dist/shared/postgres-client.d.ts.map +1 -1
  291. package/dist/shared/postgres-client.js +61 -49
  292. package/dist/shared/postgres-client.js.map +1 -1
  293. package/dist/shared/provider-rejection.d.ts +3 -0
  294. package/dist/shared/provider-rejection.d.ts.map +1 -0
  295. package/dist/shared/provider-rejection.js +17 -0
  296. package/dist/shared/provider-rejection.js.map +1 -0
  297. package/dist/shared/timestamp.d.ts +2 -0
  298. package/dist/shared/timestamp.d.ts.map +1 -1
  299. package/dist/shared/timestamp.js +7 -0
  300. package/dist/shared/timestamp.js.map +1 -1
  301. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  302. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  303. package/dist/storage/adapters/clickhouse.js +18 -17
  304. package/dist/storage/adapters/clickhouse.js.map +1 -1
  305. package/dist/storage/adapters/s3.d.ts +5 -0
  306. package/dist/storage/adapters/s3.d.ts.map +1 -1
  307. package/dist/storage/adapters/s3.js +46 -14
  308. package/dist/storage/adapters/s3.js.map +1 -1
  309. package/dist/storage/diagnostics.d.ts +3 -7
  310. package/dist/storage/diagnostics.d.ts.map +1 -1
  311. package/dist/storage/diagnostics.js +6 -15
  312. package/dist/storage/diagnostics.js.map +1 -1
  313. package/dist/storage/outbox-worker.d.ts.map +1 -1
  314. package/dist/storage/outbox-worker.js +4 -3
  315. package/dist/storage/outbox-worker.js.map +1 -1
  316. package/dist/storage/ports.d.ts +3 -0
  317. package/dist/storage/ports.d.ts.map +1 -1
  318. package/dist/storage/ports.js.map +1 -1
  319. package/dist/storage/postgres-repository.d.ts +1 -3
  320. package/dist/storage/postgres-repository.d.ts.map +1 -1
  321. package/dist/storage/postgres-repository.js +10 -4
  322. package/dist/storage/postgres-repository.js.map +1 -1
  323. package/dist/storage/runtime.d.ts +15 -10
  324. package/dist/storage/runtime.d.ts.map +1 -1
  325. package/dist/storage/runtime.js +74 -68
  326. package/dist/storage/runtime.js.map +1 -1
  327. package/dist/telemetry/index.d.ts +1 -1
  328. package/dist/telemetry/index.js +1 -1
  329. package/dist/telemetry/index.js.map +1 -1
  330. package/package.json +73 -71
  331. package/dist/credits/queries.d.ts +0 -33
  332. package/dist/credits/queries.d.ts.map +0 -1
  333. package/dist/credits/queries.js +0 -71
  334. package/dist/credits/queries.js.map +0 -1
@@ -3,11 +3,11 @@ import { LRUCache } from "lru-cache";
3
3
  import { z } from "zod";
4
4
  import { canonicalBursarConfigDict, } from "../config.js";
5
5
  import { PricingEngine as PricingEngineClass } from "../engine.js";
6
- import { LeaseNotFoundError, CatalogNotLoadedError } from "../errors.js";
6
+ import { LeaseNotFoundError, CatalogNotLoadedError, StaleQuoteError } from "../errors.js";
7
7
  import { isAmount, rejectNativeCreditAmount, toDecimal } from "./amount.js";
8
8
  function toNonNegativeAmount(value) {
9
9
  const amount = toDecimal(value);
10
- if (!amount.isFinite() || amount.isNegative()) {
10
+ if (!amount.isFinite() || amount.lt(0)) {
11
11
  throw new RangeError("amount must be finite and non-negative");
12
12
  }
13
13
  return amount;
@@ -18,8 +18,13 @@ export class CatalogRuntime {
18
18
  logger;
19
19
  cacheTtlMs;
20
20
  engine;
21
+ generation = 0;
22
+ invalidated = false;
21
23
  cache;
22
- versionEngines = new Map();
24
+ versionEngines = new LRUCache({
25
+ max: 100,
26
+ });
27
+ engineVersions = new WeakMap();
23
28
  constructor(store, engine, logger, cacheTtlMs) {
24
29
  this.store = store;
25
30
  this.logger = logger;
@@ -33,11 +38,14 @@ export class CatalogRuntime {
33
38
  // same fresh value just like the Python SDK's refresh lock.
34
39
  allowStale: false,
35
40
  fetchMethod: async () => {
41
+ const generation = ++this.generation;
36
42
  const engine = await this.fetchEngineFromStore();
43
+ this.assertCurrentGeneration(generation);
37
44
  // `lru-cache` installs the returned value when the fetch completes.
38
45
  // Calling cache.set() from inside fetchMethod aborts the in-flight
39
46
  // refresh with a "replaced" error.
40
47
  this.engine = engine;
48
+ this.invalidated = false;
41
49
  this.versionEngines.clear();
42
50
  return engine;
43
51
  },
@@ -49,7 +57,15 @@ export class CatalogRuntime {
49
57
  return this.engine;
50
58
  }
51
59
  async loadFromStore() {
52
- this.setEngine(await this.fetchEngineFromStore());
60
+ const generation = ++this.generation;
61
+ const engine = await this.fetchEngineFromStore();
62
+ this.assertCurrentGeneration(generation);
63
+ this.setEngine(engine);
64
+ }
65
+ assertCurrentGeneration(generation) {
66
+ if (generation !== this.generation) {
67
+ throw new CatalogNotLoadedError("Catalog changed while loading; reload it again");
68
+ }
53
69
  }
54
70
  async fetchEngineFromStore() {
55
71
  this.logger.info("[CatalogService] loading active catalog");
@@ -58,22 +74,28 @@ export class CatalogRuntime {
58
74
  this.logger.warn("[CatalogService] no active catalog revision in store");
59
75
  throw new CatalogNotLoadedError("No active catalog revision is available");
60
76
  }
61
- return PricingEngineClass.fromDict(active.config, this.store.providerEnvironment);
77
+ const engine = PricingEngineClass.fromDict(active.config, this.store.providerEnvironment);
78
+ this.engineVersions.set(engine, active.version);
79
+ return engine;
62
80
  }
63
81
  async refreshIfStale() {
64
- if (this.cacheTtlMs === 0)
82
+ if (this.cacheTtlMs === 0 && !this.invalidated)
65
83
  return;
66
84
  await this.cache.fetch("catalog");
67
85
  }
68
86
  invalidate() {
87
+ this.generation++;
88
+ this.invalidated = true;
69
89
  this.cache.delete("catalog");
70
90
  }
71
91
  async publishAndActivate(config, label, rollout) {
72
- this.logger.info("[CatalogService] publishing and activating catalog", { label });
92
+ this.logger.info("[CatalogService] publishing and activating catalog", {
93
+ label,
94
+ });
73
95
  const canonical = canonicalBursarConfigDict(config, this.store.providerEnvironment);
74
- const nextEngine = PricingEngineClass.fromDict(canonical, this.store.providerEnvironment);
75
96
  const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);
76
- this.setEngine(nextEngine);
97
+ this.clearEngine();
98
+ await this.loadFromStore();
77
99
  return revisionId;
78
100
  }
79
101
  async publishDraft(config, label) {
@@ -81,28 +103,39 @@ export class CatalogRuntime {
81
103
  }
82
104
  async activateRevision(version, rollout) {
83
105
  const id = await this.store.activateCatalogRevision(version, rollout);
106
+ this.clearEngine();
84
107
  await this.loadFromStore();
85
108
  return id;
86
109
  }
87
- async costOf(metricsOrAmount, userId, leaseId) {
110
+ async costOf(metricsOrAmount, userId, leaseId, planSnapshot) {
88
111
  rejectNativeCreditAmount(metricsOrAmount);
89
112
  if (isAmount(metricsOrAmount)) {
90
- return { amount: toNonNegativeAmount(metricsOrAmount), model: null };
113
+ return {
114
+ amount: toNonNegativeAmount(metricsOrAmount),
115
+ model: null,
116
+ catalogVersion: null,
117
+ };
91
118
  }
92
119
  let engine;
93
120
  let rateCard;
121
+ let catalogVersion = null;
94
122
  if (leaseId != null) {
95
123
  if (userId == null)
96
124
  throw new TypeError("userId is required when pricing a lease");
97
125
  const context = await this.store.getLeasePricingContext(userId, leaseId);
98
126
  if (!context)
99
127
  throw new LeaseNotFoundError(`Lease not found. User=${userId}`);
128
+ if (metricsOrAmount.operation !== context.operationType) {
129
+ throw new TypeError("usage metrics operation must match the reserved operation");
130
+ }
100
131
  engine = await this.engineForCatalogVersion(context.catalogVersion);
132
+ catalogVersion = context.catalogVersion;
101
133
  rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);
102
134
  }
103
135
  else {
104
- engine = await this.engineForUser(userId ?? null);
105
- const plan = userId == null ? null : await this.store.getUserPlan(userId);
136
+ const plan = userId == null ? null : (planSnapshot ?? (await this.store.getUserPlan(userId)));
137
+ engine = await this.engineForPlan(plan);
138
+ catalogVersion = plan?.catalogVersion ?? this.pricingVersion(engine);
106
139
  rateCard = plan?.rateCard ?? undefined;
107
140
  }
108
141
  const breakdown = engine.calculate(metricsOrAmount, {
@@ -110,19 +143,42 @@ export class CatalogRuntime {
110
143
  });
111
144
  return {
112
145
  amount: breakdown.total,
146
+ catalogVersion,
113
147
  model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,
114
148
  };
115
149
  }
150
+ expectedPricing(plan, version) {
151
+ return version == null ? null : { planId: plan.planId, catalogVersion: version };
152
+ }
153
+ async withFreshQuote(action) {
154
+ try {
155
+ return await action();
156
+ }
157
+ catch (error) {
158
+ if (!(error instanceof StaleQuoteError))
159
+ throw error;
160
+ await this.loadFromStore();
161
+ return action();
162
+ }
163
+ }
164
+ pricingVersion(engine) {
165
+ return this.engineVersions.get(engine) ?? null;
166
+ }
167
+ clearEngine() {
168
+ this.generation++;
169
+ this.engine = null;
170
+ this.versionEngines.clear();
171
+ this.cache.delete("catalog");
172
+ }
116
173
  setEngine(engine) {
174
+ this.generation++;
117
175
  this.engine = engine;
176
+ this.invalidated = false;
118
177
  this.versionEngines.clear();
119
178
  this.cache.set("catalog", engine);
120
179
  }
121
- async engineForUser(userId) {
122
- if (userId == null)
123
- return this.requireEngine();
124
- const plan = await this.store.getUserPlan(userId);
125
- const catalogVersion = plan.catalogVersion ?? null;
180
+ async engineForPlan(plan) {
181
+ const catalogVersion = plan?.catalogVersion ?? null;
126
182
  if (catalogVersion == null) {
127
183
  await this.refreshIfStale();
128
184
  return this.requireEngine();
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,yBAAyB,GAG1B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,IAAI,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAIzE,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE5E,SAAS,mBAAmB,CAAC,KAAkB;IAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;QAC9C,MAAM,IAAI,UAAU,CAAC,wCAAwC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mFAAmF;AACnF,MAAM,OAAO,cAAc;IAMN,KAAK;IAEL,MAAM;IACN,UAAU;IARrB,MAAM,CAAuB;IACpB,KAAK,CAAkC;IACvC,cAAc,GAAG,IAAI,GAAG,EAAyB,CAAC;IAEnE,YACmB,KAAkB,EACnC,MAA4B,EACX,MAAwB,EACxB,UAAkB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C;QAED,MAAM,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC1F,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { z } from \"zod\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config, this.store.providerEnvironment);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config, this.store.providerEnvironment);\n const nextEngine = PricingEngineClass.fromDict(canonical, this.store.providerEnvironment);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(\n canonicalBursarConfigDict(config, this.store.providerEnvironment),\n label,\n );\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config, this.store.providerEnvironment);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
1
+ {"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,yBAAyB,GAG1B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,IAAI,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAK1F,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE5E,SAAS,mBAAmB,CAAC,KAAkB;IAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,UAAU,CAAC,wCAAwC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mFAAmF;AACnF,MAAM,OAAO,cAAc;IAWN,KAAK;IAEL,MAAM;IACN,UAAU;IAbrB,MAAM,CAAuB;IAC7B,UAAU,GAAG,CAAC,CAAC;IACf,WAAW,GAAG,KAAK,CAAC;IACX,KAAK,CAAkC;IACvC,cAAc,GAAG,IAAI,QAAQ,CAAwB;QACpE,GAAG,EAAE,GAAG;KACT,CAAC,CAAC;IACc,cAAc,GAAG,IAAI,OAAO,EAAyB,CAAC;IAEvE,YACmB,KAAkB,EACnC,MAA4B,EACX,MAAwB,EACxB,UAAkB;qBAHlB,KAAK;sBAEL,MAAM;0BACN,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C,aAAa,EAAE,CAAC;QAC9B,CAAC;QAED,OAAO,IAAI,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAC;IACtD,CAAC;IAEO,KAAK,CAAC,uBAAuB,CAAC,cAAsB;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACvD,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC;QACnE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;YACpB,MAAM,IAAI,qBAAqB,CAC7B,oBAAoB,cAAc,qCAAqC,CACxE,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC1F,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { z } from \"zod\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError, StaleQuoteError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { GetUserPlanResult } from \"./types/index.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.lt(0)) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private generation = 0;\n private invalidated = false;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new LRUCache<number, PricingEngine>({\n max: 100,\n });\n private readonly engineVersions = new WeakMap<PricingEngine, number>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const generation = ++this.generation;\n const engine = await this.fetchEngineFromStore();\n this.assertCurrentGeneration(generation);\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.invalidated = false;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n const generation = ++this.generation;\n const engine = await this.fetchEngineFromStore();\n this.assertCurrentGeneration(generation);\n this.setEngine(engine);\n }\n\n private assertCurrentGeneration(generation: number): void {\n if (generation !== this.generation) {\n throw new CatalogNotLoadedError(\"Catalog changed while loading; reload it again\");\n }\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n const engine = PricingEngineClass.fromDict(active.config, this.store.providerEnvironment);\n this.engineVersions.set(engine, active.version);\n return engine;\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0 && !this.invalidated) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.generation++;\n this.invalidated = true;\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", {\n label,\n });\n const canonical = canonicalBursarConfigDict(config, this.store.providerEnvironment);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.clearEngine();\n await this.loadFromStore();\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(\n canonicalBursarConfigDict(config, this.store.providerEnvironment),\n label,\n );\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n this.clearEngine();\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n planSnapshot?: GetUserPlanResult,\n ): Promise<{\n amount: Decimal;\n model: string | null;\n catalogVersion: number | null;\n }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return {\n amount: toNonNegativeAmount(metricsOrAmount),\n model: null,\n catalogVersion: null,\n };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n let catalogVersion: number | null = null;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n if (metricsOrAmount.operation !== context.operationType) {\n throw new TypeError(\"usage metrics operation must match the reserved operation\");\n }\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n catalogVersion = context.catalogVersion;\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n const plan = userId == null ? null : (planSnapshot ?? (await this.store.getUserPlan(userId)));\n engine = await this.engineForPlan(plan);\n catalogVersion = plan?.catalogVersion ?? this.pricingVersion(engine);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n catalogVersion,\n model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,\n };\n }\n\n expectedPricing(plan: GetUserPlanResult, version: number | null) {\n return version == null ? null : { planId: plan.planId, catalogVersion: version };\n }\n\n async withFreshQuote<T>(action: () => Promise<T>): Promise<T> {\n try {\n return await action();\n } catch (error) {\n if (!(error instanceof StaleQuoteError)) throw error;\n await this.loadFromStore();\n return action();\n }\n }\n\n pricingVersion(engine: PricingEngine): number | null {\n return this.engineVersions.get(engine) ?? null;\n }\n\n private clearEngine(): void {\n this.generation++;\n this.engine = null;\n this.versionEngines.clear();\n this.cache.delete(\"catalog\");\n }\n\n private setEngine(engine: PricingEngine): void {\n this.generation++;\n this.engine = engine;\n this.invalidated = false;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForPlan(plan: GetUserPlanResult | null): Promise<PricingEngine> {\n const catalogVersion = plan?.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config, this.store.providerEnvironment);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
@@ -36,6 +36,7 @@ export declare class CreditLeaseWorkflow {
36
36
  * policy, and concurrency enforcement to the database in one atomic call.
37
37
  */
38
38
  reserve(userId: string, metricsOrAmount: MetricsOrAmount, options: ReserveOptions): Promise<LeaseSuccess>;
39
+ private reserveOnce;
39
40
  /**
40
41
  * Charge the actual cost against a lease and finalize it.
41
42
  *
@@ -84,7 +85,8 @@ export declare class CreditLeaseWorkflow {
84
85
  * Begin a replay-safe billable operation that can span framework callbacks.
85
86
  *
86
87
  * The operation key is namespaced into distinct reserve and settle keys, so
87
- * replaying the whole lifecycle cannot acquire a second hold.
88
+ * replaying acquisition cannot acquire a second hold. These keys do not
89
+ * deduplicate the caller's work or its external effects.
88
90
  */
89
91
  beginBilledOperation(userId: string, options: BeginBilledOperationOptions): Promise<BilledOperation>;
90
92
  }
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.d.ts","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,OAAO,KAAK,EACV,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,eAAe,EACf,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,aAAa,EACd,MAAM,oBAAoB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Aa,CAAC,CAcrE;IAED,4EAA4E;IACtE,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC,CAWvF;IAED;;;;OAIG;IACG,SAAS,CACb,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,eAAe,EAChC,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,eAAe,CAAC,CAsD1B;IAED,sGAAsG;IAChG,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAGrE;IAED;;;;;;;;;OASG;IACG,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAEpE;IAED;;;;;;;;OAQG;IACG,SAAS,CAAC,CAAC,EACf,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAC3B,OAAO,CAAC;QAAE,MAAM,EAAE,CAAC,CAAC;QAAC,SAAS,EAAE,eAAe,CAAA;KAAE,CAAC,CAkCpD;IAED;;;;;;OAMG;IACG,oBAAoB,CACxB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,eAAe,CAAC,CA0B1B;CACF"}
@@ -1,3 +1,4 @@
1
+ import { ratedMeasures, ratedDimensions, callerMetadata } from "./rated-wire.js";
1
2
  import { Decimal } from "decimal.js";
2
3
  import { z } from "zod";
3
4
  import { retryBursarOperation } from "../retry.js";
@@ -33,8 +34,8 @@ export class CreditLeaseWorkflow {
33
34
  this.maybeLazyExpire = maybeLazyExpire;
34
35
  this.afterDeduction = afterDeduction;
35
36
  }
36
- async expectedAdmissionPolicy(userId, operationType, billingModeOverride) {
37
- const plan = await this.store.getUserPlan(userId);
37
+ async expectedAdmissionPolicy(userId, operationType, billingModeOverride, planSnapshot) {
38
+ const plan = planSnapshot ?? (await this.store.getUserPlan(userId));
38
39
  const creditPolicy = plan.planId == null ? null : plan.creditPolicy;
39
40
  const planMode = plan.planId == null
40
41
  ? this.policy === "overdraft"
@@ -62,8 +63,8 @@ export class CreditLeaseWorkflow {
62
63
  * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact
63
64
  * `Decimal`, no truncation); a raw amount is used as-is with no model.
64
65
  */
65
- async costOf(metricsOrAmount, userId, leaseId) {
66
- return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);
66
+ async costOf(metricsOrAmount, userId, leaseId, planSnapshot) {
67
+ return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId, planSnapshot);
67
68
  }
68
69
  /**
69
70
  * Atomically acquire a lease — the only authoritative admission control.
@@ -72,6 +73,9 @@ export class CreditLeaseWorkflow {
72
73
  * policy, and concurrency enforcement to the database in one atomic call.
73
74
  */
74
75
  async reserve(userId, metricsOrAmount, options) {
76
+ return this.catalogRuntime.withFreshQuote(() => this.reserveOnce(userId, metricsOrAmount, options));
77
+ }
78
+ async reserveOnce(userId, metricsOrAmount, options) {
75
79
  rejectNativeCreditAmount(metricsOrAmount);
76
80
  const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);
77
81
  await this.maybeLazyExpire(userId);
@@ -80,23 +84,28 @@ export class CreditLeaseWorkflow {
80
84
  operationType: options.operationType,
81
85
  });
82
86
  const operationType = options.operationType ?? (isAmount(metricsOrAmount) ? "usage" : metricsOrAmount.operation);
83
- const expectedPolicy = await this.expectedAdmissionPolicy(userId, operationType, options.billingMode);
84
- const priced = await this.costOf(metricsOrAmount, userId);
87
+ if (!isAmount(metricsOrAmount) && operationType !== metricsOrAmount.operation) {
88
+ throw new TypeError("operationType must match the usage metrics operation");
89
+ }
90
+ const plan = await this.store.getUserPlan(userId);
91
+ const expectedPolicy = await this.expectedAdmissionPolicy(userId, operationType, options.billingMode, plan);
92
+ const priced = await this.costOf(metricsOrAmount, userId, null, plan);
85
93
  const amount = priced.amount;
86
94
  const model = priced.model ?? options.model ?? null;
87
95
  const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;
88
96
  const feature = options.feature ?? null;
89
- const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
90
- const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
97
+ const measures = isAmount(metricsOrAmount) ? {} : ratedMeasures(metricsOrAmount.measures);
98
+ const dimensions = isAmount(metricsOrAmount) ? {} : ratedDimensions(metricsOrAmount.dimensions);
91
99
  const region = z.string().safeParse(dimensions.region).data ?? null;
92
100
  const result = await this.store.createLease(userId, amount, operationType, {
93
101
  idempotencyKey: leaseIdempotencyKey,
102
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, priced.catalogVersion),
94
103
  billingMode: expectedPolicy.billingMode,
95
104
  floor: expectedPolicy.floor,
96
105
  maxConcurrent: expectedPolicy.maxConcurrent,
97
106
  ttlSeconds,
98
107
  model,
99
- metadata: options.metadata,
108
+ metadata: callerMetadata(options.metadata),
100
109
  feature,
101
110
  region,
102
111
  measures,
@@ -146,35 +155,18 @@ export class CreditLeaseWorkflow {
146
155
  : requireStableKey(options.idempotencyKey);
147
156
  const feature = options?.feature ?? null;
148
157
  const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);
149
- const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
150
- const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
158
+ const measures = isAmount(metricsOrAmount) ? {} : ratedMeasures(metricsOrAmount.measures);
159
+ const dimensions = isAmount(metricsOrAmount) ? {} : ratedDimensions(metricsOrAmount.dimensions);
151
160
  const region = z.string().safeParse(dimensions.region).data ?? null;
152
161
  // Build ledger metadata with caller fields first and protected system fields last.
153
- const txMeta = {};
154
- if (isAmount(metricsOrAmount)) {
155
- if (options?.metadata) {
156
- for (const [k, v] of Object.entries(options.metadata)) {
157
- if (v != null)
158
- txMeta[k] = v;
159
- }
160
- }
161
- if (idempotencyKey)
162
- txMeta["idempotencyKey"] = idempotencyKey;
163
- }
164
- else {
165
- if (options?.metadata) {
166
- for (const [k, v] of Object.entries(options.metadata)) {
167
- if (v != null)
168
- txMeta[k] = v;
169
- }
170
- }
162
+ const txMeta = callerMetadata(options?.metadata, !isAmount(metricsOrAmount));
163
+ if (!isAmount(metricsOrAmount)) {
171
164
  txMeta["operation"] = metricsOrAmount.operation;
172
- txMeta["measures"] = { ...(metricsOrAmount.measures ?? {}) };
173
- txMeta["dimensions"] = { ...(metricsOrAmount.dimensions ?? {}) };
174
- txMeta["breakdownTotal"] = amount.toString();
175
- if (idempotencyKey)
176
- txMeta["idempotencyKey"] = idempotencyKey;
165
+ txMeta["measures"] = measures;
166
+ txMeta["dimensions"] = dimensions;
167
+ txMeta["breakdownTotal"] = amount.toFixed(6);
177
168
  }
169
+ txMeta["idempotency_key"] = idempotencyKey;
178
170
  const result = await this.store.settleLease(userId, leaseId, amount, {
179
171
  idempotencyKey,
180
172
  feature,
@@ -223,7 +215,10 @@ export class CreditLeaseWorkflow {
223
215
  this.logger.debug("[CreditsService] release", { leaseId });
224
216
  const result = await this.store.releaseLease(userId, leaseId);
225
217
  if (result.released) {
226
- this.logger.info("[CreditsService] lease released", { leaseId, reason: result.reason });
218
+ this.logger.info("[CreditsService] lease released", {
219
+ leaseId,
220
+ reason: result.reason,
221
+ });
227
222
  this.emit("credits.reservation_released", userId, {
228
223
  leaseId,
229
224
  reason: result.reason,
@@ -251,13 +246,18 @@ export class CreditLeaseWorkflow {
251
246
  */
252
247
  async canAfford(userId, metricsOrAmount, options) {
253
248
  rejectNativeCreditAmount(metricsOrAmount);
249
+ if (!isAmount(metricsOrAmount) &&
250
+ options?.operationType != null &&
251
+ options.operationType !== metricsOrAmount.operation) {
252
+ throw new TypeError("operationType must match the usage metrics operation");
253
+ }
254
254
  await this.maybeLazyExpire(userId);
255
255
  const feature = options?.feature ?? null;
256
256
  const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);
257
257
  const avail = await this.store.getAvailable(userId);
258
258
  let expectedPolicy;
259
259
  try {
260
- expectedPolicy = await this.expectedAdmissionPolicy(userId, options?.operationType ?? "usage", options?.billingMode);
260
+ expectedPolicy = await this.expectedAdmissionPolicy(userId, options?.operationType ?? (isAmount(metricsOrAmount) ? "usage" : metricsOrAmount.operation), options?.billingMode);
261
261
  }
262
262
  catch {
263
263
  return {
@@ -337,7 +337,15 @@ export class CreditLeaseWorkflow {
337
337
  ({ result: workResult, actual } = await options.doWork());
338
338
  }
339
339
  catch (err) {
340
- await operation.release();
340
+ try {
341
+ await operation.release();
342
+ }
343
+ catch (releaseError) {
344
+ this.logger.error("[CreditsService] failed to release lease after work failed", {
345
+ leaseId: operation.leaseId,
346
+ error: releaseError instanceof Error ? releaseError.message : String(releaseError),
347
+ });
348
+ }
341
349
  throw err;
342
350
  }
343
351
  // Never release after work succeeds. A settlement failure may be a
@@ -351,7 +359,8 @@ export class CreditLeaseWorkflow {
351
359
  * Begin a replay-safe billable operation that can span framework callbacks.
352
360
  *
353
361
  * The operation key is namespaced into distinct reserve and settle keys, so
354
- * replaying the whole lifecycle cannot acquire a second hold.
362
+ * replaying acquisition cannot acquire a second hold. These keys do not
363
+ * deduplicate the caller's work or its external effects.
355
364
  */
356
365
  async beginBilledOperation(userId, options) {
357
366
  const operationKey = requireStableKey(options.operationKey, "operationKey");
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC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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 { z } from \"zod\";\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 { StructuredObject } from \"../shared/json.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: (type: CreditEventType, userId: string, data?: StructuredObject) => 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 = z.string().safeParse(dimensions.region).data ?? 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 = z.string().safeParse(dimensions.region).data ?? null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: CreditMetadata = {};\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,\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
+ {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AA0B7E,MAAM,OAAO,mBAAmB;IAEX,KAAK;IACL,cAAc;IACd,MAAM;IACN,cAAc;IACd,MAAM;IACN,cAAc;IACd,oBAAoB;IACpB,UAAU;IACV,IAAI;IACJ,eAAe;IACf,eAAe;IACf,cAAc;IAZjC,YACmB,KAAkB,EAClB,cAA8B,EAC9B,MAAwB,EACxB,cAAiC,EACjC,MAAoB,EACpB,cAA8B,EAC9B,oBAAmC,EACnC,UAAkB,EAClB,IAA8E,EAC9E,eAA0E,EAC1E,eAAkD,EAClD,cAA2E;qBAX3E,KAAK;8BACL,cAAc;sBACd,MAAM;8BACN,cAAc;sBACd,MAAM;8BACN,cAAc;oCACd,oBAAoB;0BACpB,UAAU;oBACV,IAAI;+BACJ,eAAe;+BACf,eAAe;8B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E,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 { ratedMeasures, ratedDimensions, callerMetadata } from \"./rated-wire.js\";\nimport { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\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 { StructuredObject } from \"../shared/json.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n GetUserPlanResult,\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: (type: CreditEventType, userId: string, data?: StructuredObject) => 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 planSnapshot?: GetUserPlanResult,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = planSnapshot ?? (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 planSnapshot?: GetUserPlanResult,\n ): Promise<{\n amount: Decimal;\n model: string | null;\n catalogVersion: number | null;\n }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId, planSnapshot);\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 return this.catalogRuntime.withFreshQuote(() =>\n this.reserveOnce(userId, metricsOrAmount, options),\n );\n }\n\n private async reserveOnce(\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 if (!isAmount(metricsOrAmount) && operationType !== metricsOrAmount.operation) {\n throw new TypeError(\"operationType must match the usage metrics operation\");\n }\n const plan = await this.store.getUserPlan(userId);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n plan,\n );\n const priced = await this.costOf(metricsOrAmount, userId, null, plan);\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) ? {} : ratedMeasures(metricsOrAmount.measures);\n const dimensions = isAmount(metricsOrAmount) ? {} : ratedDimensions(metricsOrAmount.dimensions);\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n expectedPricing: this.catalogRuntime.expectedPricing(plan, priced.catalogVersion),\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: callerMetadata(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) ? {} : ratedMeasures(metricsOrAmount.measures);\n const dimensions = isAmount(metricsOrAmount) ? {} : ratedDimensions(metricsOrAmount.dimensions);\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: CreditMetadata = callerMetadata(options?.metadata, !isAmount(metricsOrAmount));\n if (!isAmount(metricsOrAmount)) {\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = measures;\n txMeta[\"dimensions\"] = dimensions;\n txMeta[\"breakdownTotal\"] = amount.toFixed(6);\n }\n txMeta[\"idempotency_key\"] = idempotencyKey;\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,\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\", {\n leaseId,\n reason: result.reason,\n });\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 if (\n !isAmount(metricsOrAmount) &&\n options?.operationType != null &&\n options.operationType !== metricsOrAmount.operation\n ) {\n throw new TypeError(\"operationType must match the usage metrics operation\");\n }\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 ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation),\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 try {\n await operation.release();\n } catch (releaseError) {\n this.logger.error(\"[CreditsService] failed to release lease after work failed\", {\n leaseId: operation.leaseId,\n error: releaseError instanceof Error ? releaseError.message : String(releaseError),\n });\n }\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 acquisition cannot acquire a second hold. These keys do not\n * deduplicate the caller's work or its external effects.\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"]}
@@ -6,21 +6,16 @@ import type { DeductionSuccess } from "./types/index.js";
6
6
  import type { LowBalanceConfig } from "./service-types.js";
7
7
  type EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;
8
8
  /**
9
- * Owns edge-trigger state for low-balance and overdraft notifications.
10
- *
11
- * Keeping this state outside CreditsService makes the event semantics
12
- * independently testable and keeps the service focused on orchestration.
9
+ * Emits notifications from committed balance changes without per-user state.
13
10
  */
14
11
  export declare class LowBalanceMonitor {
15
12
  private readonly emit;
16
13
  private readonly logger;
17
14
  private readonly thresholds;
18
15
  private readonly handler;
19
- private readonly breachedByUser;
20
16
  constructor(config: LowBalanceConfig | null | undefined, emit: EmitCreditEvent, logger: NormalizedLogger);
21
- rearmAfterCredit(userId: string, balance: Decimal): void;
22
17
  afterCharge(userId: string, result: DeductionSuccess): Promise<void>;
23
- signalCrossing(userId: string, balanceBefore: Decimal, balanceAfter: Decimal): Promise<void>;
18
+ signalCrossing(userId: string, balanceBefore: Decimal, balanceAfter: Decimal, context?: StructuredObject): Promise<void>;
24
19
  private fire;
25
20
  }
26
21
  export {};