@owlmeans/server-payment 0.1.19-rc.0 → 0.1.19

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 (114) hide show
  1. package/README.md +1 -1
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +47 -5
  4. package/build/access/types.d.ts +8 -1
  5. package/build/access/types.d.ts.map +1 -1
  6. package/build/access.d.ts.map +1 -1
  7. package/build/access.js +8 -2
  8. package/build/access.js.map +1 -1
  9. package/build/catalogue/types.d.ts +3 -1
  10. package/build/catalogue/types.d.ts.map +1 -1
  11. package/build/catalogue.d.ts.map +1 -1
  12. package/build/catalogue.js +15 -10
  13. package/build/catalogue.js.map +1 -1
  14. package/build/commit/types.d.ts +17 -2
  15. package/build/commit/types.d.ts.map +1 -1
  16. package/build/commit.d.ts.map +1 -1
  17. package/build/commit.js +40 -5
  18. package/build/commit.js.map +1 -1
  19. package/build/consts.d.ts +17 -0
  20. package/build/consts.d.ts.map +1 -1
  21. package/build/consts.js +19 -0
  22. package/build/consts.js.map +1 -1
  23. package/build/entitlement.d.ts.map +1 -1
  24. package/build/entitlement.js +7 -1
  25. package/build/entitlement.js.map +1 -1
  26. package/build/grant-fold/types.d.ts +41 -0
  27. package/build/grant-fold/types.d.ts.map +1 -0
  28. package/build/grant-fold/types.js +2 -0
  29. package/build/grant-fold/types.js.map +1 -0
  30. package/build/grant-fold.d.ts +4 -0
  31. package/build/grant-fold.d.ts.map +1 -0
  32. package/build/grant-fold.js +64 -0
  33. package/build/grant-fold.js.map +1 -0
  34. package/build/grants/types.d.ts +39 -0
  35. package/build/grants/types.d.ts.map +1 -0
  36. package/build/grants/types.js +2 -0
  37. package/build/grants/types.js.map +1 -0
  38. package/build/grants.d.ts +6 -0
  39. package/build/grants.d.ts.map +1 -0
  40. package/build/grants.js +141 -0
  41. package/build/grants.js.map +1 -0
  42. package/build/index.d.ts +4 -0
  43. package/build/index.d.ts.map +1 -1
  44. package/build/index.js +2 -0
  45. package/build/index.js.map +1 -1
  46. package/build/observer.d.ts +3 -0
  47. package/build/observer.d.ts.map +1 -1
  48. package/build/observer.js +6 -0
  49. package/build/observer.js.map +1 -1
  50. package/build/reconcile/types.d.ts +4 -2
  51. package/build/reconcile/types.d.ts.map +1 -1
  52. package/build/reconcile.d.ts.map +1 -1
  53. package/build/reconcile.js +3 -1
  54. package/build/reconcile.js.map +1 -1
  55. package/build/resource.d.ts +2 -1
  56. package/build/resource.d.ts.map +1 -1
  57. package/build/resource.js +10 -2
  58. package/build/resource.js.map +1 -1
  59. package/build/schemas.d.ts +2 -1
  60. package/build/schemas.d.ts.map +1 -1
  61. package/build/schemas.js +16 -2
  62. package/build/schemas.js.map +1 -1
  63. package/build/service.d.ts +3 -3
  64. package/build/service.d.ts.map +1 -1
  65. package/build/service.js +7 -5
  66. package/build/service.js.map +1 -1
  67. package/build/subscription/types.d.ts +12 -2
  68. package/build/subscription/types.d.ts.map +1 -1
  69. package/build/subscription.d.ts.map +1 -1
  70. package/build/subscription.js +14 -3
  71. package/build/subscription.js.map +1 -1
  72. package/build/types.d.ts +125 -0
  73. package/build/types.d.ts.map +1 -1
  74. package/build/usage/types.d.ts +25 -8
  75. package/build/usage/types.d.ts.map +1 -1
  76. package/build/usage.d.ts.map +1 -1
  77. package/build/usage.js +201 -46
  78. package/build/usage.js.map +1 -1
  79. package/build/utils/types.d.ts +5 -0
  80. package/build/utils/types.d.ts.map +1 -1
  81. package/build/utils.d.ts.map +1 -1
  82. package/build/utils.js +4 -2
  83. package/build/utils.js.map +1 -1
  84. package/package.json +19 -19
  85. package/src/access/types.ts +8 -1
  86. package/src/access.ts +12 -3
  87. package/src/catalogue/types.ts +3 -1
  88. package/src/catalogue.ts +17 -13
  89. package/src/commit/types.ts +17 -2
  90. package/src/commit.ts +47 -6
  91. package/src/consts.ts +20 -0
  92. package/src/entitlement.ts +8 -1
  93. package/src/grant-fold/types.ts +42 -0
  94. package/src/grant-fold.ts +89 -0
  95. package/src/grants/types.ts +42 -0
  96. package/src/grants.ts +171 -0
  97. package/src/index.ts +4 -0
  98. package/src/observer.ts +8 -1
  99. package/src/reconcile/types.ts +4 -2
  100. package/src/reconcile.ts +3 -1
  101. package/src/resource.ts +20 -7
  102. package/src/schemas.ts +20 -5
  103. package/src/service.ts +9 -6
  104. package/src/subscription/types.ts +12 -2
  105. package/src/subscription.ts +15 -2
  106. package/src/types.ts +129 -0
  107. package/src/usage/types.ts +25 -8
  108. package/src/usage.ts +235 -48
  109. package/src/utils/types.ts +5 -0
  110. package/src/utils.ts +6 -2
  111. package/tests/fake-stripe.ts +24 -7
  112. package/tests/grants.spec.ts +276 -0
  113. package/tests/internal-plan.spec.ts +112 -0
  114. package/tests/usage.integration.spec.ts +32 -0
package/src/usage.ts CHANGED
@@ -1,17 +1,24 @@
1
- import { LimitExhausted, LimitKind, LimitMisdeclared, LimitUnknown, LimitWindow, OCCUPANCY_WINDOW, SUBSCRIPTION_WEEK_MS, SUBSCRIPTION_WEEK_PREFIX, type LimitDeclaration, type LimitView, entitlementViewHelper, planLimitHelper, promoHelper } from '@owlmeans/payment'
1
+ import {
2
+ LimitExhausted, LimitKind, LimitMisdeclared, LimitUnknown, LimitWindow, OCCUPANCY_WINDOW, PlanRequired,
3
+ SUBSCRIPTION_WEEK_MS, SUBSCRIPTION_WEEK_PREFIX, type LimitDeclaration, type LimitView, entitlementViewHelper,
4
+ planLimitHelper, promoHelper,
5
+ } from '@owlmeans/payment'
2
6
  import { UnsupportedArgumentError } from '@owlmeans/resource'
3
7
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
8
  import { memoHelper } from '@owlmeans/context'
5
9
  import type {
6
- ConsumeRequest, CounterReconciliation, EffectivePlan, LimitOutcome, OccupancyOutcome, PaymentUsageCounterRecord,
7
- PaymentUsageRecord, ReleaseRequest,
10
+ ConsumeRequest, CounterReconciliation, EffectivePlan, LimitOutcome, OccupancyOutcome, PaymentGrantRecord,
11
+ PaymentUsageCounterRecord, PaymentUsageRecord, ReleaseRequest,
8
12
  } from './types.js'
9
13
  import { log } from './log.js'
14
+ import { EntitlementGrantKind, EntitlementGrantStatus } from './consts.js'
10
15
  import { DAY_WINDOW, MONTH_WINDOW } from './consts.local.js'
11
16
  import type { CounterKey, LedgerSum, UsageHelper } from './usage/types.js'
12
17
  import { paymentAccessOf } from './access.js'
13
18
  import { paymentUtils } from './utils.js'
14
19
  import { catalogueOf } from './catalogue.js'
20
+ import { grantFoldHelper } from './grant-fold.js'
21
+ import { entitlementGrantsOf } from './grants.js'
15
22
 
16
23
  /**
17
24
  * The usage ledger and its counters.
@@ -22,6 +29,13 @@ import { catalogueOf } from './catalogue.js'
22
29
  * counter may over-count, never over-admit.** A crash between the two leaves a unit counted that no
23
30
  * event spent, which `reconcileCounters` repairs from the ledger; the opposite order would let two
24
31
  * concurrent requests both read "room left" and both spend it.
32
+ *
33
+ * Entitlement grants of `units` extend a limit beyond its plan. A unit is taken from a grant only
34
+ * when the plan's own counter has no room: a conditional increment of the grant's `used` (room for
35
+ * the unit AND for whatever the plan counter holds over its own ceiling), then the event in the
36
+ * window `grant:<grantId>` — the same order, the same invariant. A release returns the unit to the
37
+ * grant it was taken from; reconciliation rebuilds a grant's `used` from its events and never folds
38
+ * them into a counter window.
25
39
  */
26
40
 
27
41
  /** When a stored window renews: the first instant of the next day, month or subscription week. */
@@ -78,20 +92,67 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
78
92
  const readCounter = async (key: CounterKey): Promise<PaymentUsageCounterRecord | null> =>
79
93
  await access.usageCounters().load({ entityId: key.entityId, limitKey: key.limitKey, window: key.window })
80
94
 
95
+ /**
96
+ * A limit's numbers after a ledger operation: the counter of `key` (its ceiling `limit`, else the
97
+ * counter's own) with the grants `units` folded in. `window` is where the event lives — the
98
+ * counter's, or a grant's.
99
+ */
81
100
  const outcomeOf = async (
82
101
  key: CounterKey, eventKey: string, flags: { admitted: boolean, replayed: boolean }, limit?: number,
102
+ units: readonly PaymentGrantRecord[] = [], window: string = key.window,
83
103
  ): Promise<LimitOutcome> => {
84
104
  const counter = await readCounter(key)
85
- const used = Math.max(0, counter?.used ?? 0)
86
- const ceiling = limit ?? counter?.limit ?? 0
105
+ const used = Math.max(0, counter?.used ?? 0) + grantFoldHelper.unitsFold(units).used
106
+ const ceiling = (limit ?? counter?.limit ?? 0) + grantFoldHelper.unitsFold(units).amount
87
107
  const resetsAt = resetsAtOfWindow(key.window)
88
108
 
89
109
  return {
90
- ...flags, limitKey: key.limitKey, window: key.window, used, limit: ceiling,
110
+ ...flags, limitKey: key.limitKey, window, used, limit: ceiling,
91
111
  remaining: Math.max(0, ceiling - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey,
92
112
  }
93
113
  }
94
114
 
115
+ /**
116
+ * Take `amount` units from the first grant (in consumption order) that has room for them AND for
117
+ * what the plan counter holds over its own ceiling — so the folded total never exceeds the folded
118
+ * ceiling. One conditional increment per grant, guarded by `used` and the status: never over-admits.
119
+ */
120
+ const holdOnGrant = async (
121
+ key: CounterKey, units: readonly PaymentGrantRecord[], amount: number, limit: number,
122
+ ): Promise<PaymentGrantRecord | null> => {
123
+ if (units.length === 0) {
124
+ return null
125
+ }
126
+ const overflow = Math.max(0, ((await readCounter(key))?.used ?? 0) - limit)
127
+ const grants = access.grantRecords().collection
128
+ for (const grant of units) {
129
+ const room = (grant.amount ?? 0) - amount - overflow
130
+ if (grant.id == null || room < 0) {
131
+ continue
132
+ }
133
+ const doc = await grants.findOneAndUpdate(
134
+ paymentUtils.idCriteria(grant.id, { status: EntitlementGrantStatus.Active, used: { $lte: room } }),
135
+ { $inc: { used: amount } }, { returnDocument: 'after' },
136
+ ) as { used?: number } | null
137
+ if (doc != null) {
138
+ return { ...grant, used: doc.used ?? (grant.used ?? 0) + amount }
139
+ }
140
+ }
141
+
142
+ return null
143
+ }
144
+
145
+ /** Give `amount` units back to a grant, never below zero. */
146
+ const returnToGrant = async (grantId: string, amount: number): Promise<void> => {
147
+ const grants = access.grantRecords().collection
148
+ const doc = await grants.findOneAndUpdate(
149
+ paymentUtils.idCriteria(grantId, { used: { $gte: amount } }), { $inc: { used: -amount } },
150
+ )
151
+ if (doc == null) {
152
+ await grants.updateOne(paymentUtils.idCriteria(grantId), { $set: { used: 0 } })
153
+ }
154
+ }
155
+
95
156
  /** The counter increment that IS the admission decision. `null` when there is no room. */
96
157
  const admit = async (
97
158
  key: CounterKey, amount: number, limit: number, planSku: string, at: Date,
@@ -146,56 +207,131 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
146
207
  const key: CounterKey = {
147
208
  entityId: req.entityId, limitKey: req.limitKey, window: planLimitHelper.windowKeyOf(declaration.kind, declaration.window, at, effective?.subscription?.createdAt),
148
209
  }
210
+ // The limit's grants in force: consumed only once the plan's own counter has no room.
211
+ const units = grantFoldHelper.unitsOf(effective.grants ?? [], req.limitKey)
149
212
  const ledger = access.usageEvents()
150
213
 
214
+ /**
215
+ * What an event already written answers: the limit as it stands now when the event is of the
216
+ * current window or of a grant; its own window's counter otherwise (`ceiling`, else the counter's).
217
+ */
218
+ const replay = async (event: PaymentUsageRecord | null, ceiling?: number): Promise<LimitOutcome> => {
219
+ const window = event?.window ?? key.window
220
+ const flags = { admitted: isActiveConsumption(event), replayed: true }
221
+
222
+ return window === key.window || grantFoldHelper.grantIdOf(window) != null
223
+ ? await outcomeOf(key, req.eventKey, flags, limit, units, window)
224
+ : await outcomeOf({ ...key, window }, req.eventKey, flags, ceiling)
225
+ }
226
+
151
227
  // A retry of an event already written answers from the ledger before admission is asked: at the
152
228
  // ceiling, admission would refuse the very unit this key already holds. A released key is final.
153
229
  const earlier = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
154
230
  if (earlier != null) {
155
- return await outcomeOf({ ...key, window: earlier.window }, req.eventKey, {
156
- admitted: isActiveConsumption(earlier), replayed: true,
157
- }, earlier.window === key.window ? limit : undefined)
231
+ return await replay(earlier)
232
+ }
233
+
234
+ const append = async (window: string, undo: () => Promise<void>): Promise<LimitOutcome | null> => {
235
+ try {
236
+ await ledger.create({
237
+ ...key, window, delta: amount, eventKey: req.eventKey, ref: req.ref, reason: req.reason,
238
+ planSku: effective.plan.sku, createdAt: at,
239
+ })
240
+ } catch (error) {
241
+ // Undo the admission. Should the undo itself fail, the count is over — never over-admitted.
242
+ await undo().catch(failure => { log.error('Usage undo failed', failure) })
243
+ if (!paymentUtils.isDuplicateKey(error)) {
244
+ throw error
245
+ }
246
+ // A concurrent consume of the same key won the event: replay its outcome.
247
+ const winner = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
248
+ return await replay(winner, limit)
249
+ }
250
+
251
+ return null
158
252
  }
159
253
 
160
254
  const counter = await admit(key, amount, limit, effective.plan.sku, at)
161
- if (counter == null) {
162
- // A concurrent consume of this very key may hold the last unit: that is a replay, not a refusal.
163
- const concurrent = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
164
- if (concurrent != null) {
165
- return await outcomeOf({ ...key, window: concurrent.window }, req.eventKey, {
166
- admitted: isActiveConsumption(concurrent), replayed: true,
167
- }, concurrent.window === key.window ? limit : undefined)
255
+ if (counter != null) {
256
+ const replayed = await append(key.window, async () => { await decrement(key, amount, at) })
257
+ if (replayed != null) {
258
+ return replayed
259
+ }
260
+ const fold = grantFoldHelper.unitsFold(units)
261
+ const used = Math.max(0, counter.used) + fold.used
262
+ const ceiling = limit + fold.amount
263
+ const resetsAt = resetsAtOfWindow(key.window)
264
+
265
+ return {
266
+ admitted: true, replayed: false, limitKey: req.limitKey, window: key.window, used, limit: ceiling,
267
+ remaining: Math.max(0, ceiling - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey: req.eventKey,
168
268
  }
169
- const current = await readCounter(key)
170
- const resetsAt = declaration.kind === LimitKind.Window && declaration.window != null
171
- ? planLimitHelper.windowBoundsOf(declaration.window, at, effective?.subscription?.createdAt).resetsAt : undefined
172
- throw new LimitExhausted({ key: req.limitKey, used: current?.used ?? 0, limit, resetsAt })
173
269
  }
174
270
 
271
+ // A concurrent consume of this very key may hold the last unit: that is a replay, not a refusal.
272
+ const concurrent = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
273
+ if (concurrent != null) {
274
+ return await replay(concurrent)
275
+ }
276
+
277
+ // The plan's own allowance has no room: a unit of a grant of this limit, when one has room.
278
+ const held = await holdOnGrant(key, units, amount, limit)
279
+ if (held != null) {
280
+ const window = grantFoldHelper.windowOf(held.id!)
281
+ const replayed = await append(window, async () => { await returnToGrant(held.id!, amount) })
282
+ if (replayed != null) {
283
+ return replayed
284
+ }
285
+
286
+ return await outcomeOf(key, req.eventKey, { admitted: true, replayed: false }, limit,
287
+ units.map(grant => grant.id === held.id ? held : grant), window)
288
+ }
289
+
290
+ const current = await readCounter(key)
291
+ const fold = grantFoldHelper.unitsFold(units)
292
+ const resetsAt = declaration.kind === LimitKind.Window && declaration.window != null
293
+ ? planLimitHelper.windowBoundsOf(declaration.window, at, effective?.subscription?.createdAt).resetsAt : undefined
294
+ throw new LimitExhausted({
295
+ key: req.limitKey, used: (current?.used ?? 0) + fold.used, limit: limit + fold.amount, resetsAt,
296
+ })
297
+ }
298
+
299
+ /**
300
+ * What a release answers: the counter of the event's window with the limit's grants in force
301
+ * folded in; for a unit held on a grant, the limit as it stands now (its current window).
302
+ */
303
+ const releaseOutcomeOf = async (
304
+ req: ReleaseRequest, consumed: PaymentUsageRecord, flags: { admitted: boolean, replayed: boolean },
305
+ ): Promise<LimitOutcome> => {
306
+ const at = new Date()
307
+ if (grantFoldHelper.grantIdOf(consumed.window) == null) {
308
+ const units = grantFoldHelper.unitsOf(await entitlementGrantsOf(ctx).inForce(req.entityId, at), req.limitKey)
309
+ return await outcomeOf({ entityId: req.entityId, limitKey: req.limitKey, window: consumed.window }, req.eventKey,
310
+ flags, undefined, units)
311
+ }
175
312
  try {
176
- await ledger.create({
177
- ...key, delta: amount, eventKey: req.eventKey, ref: req.ref, reason: req.reason,
178
- planSku: effective.plan.sku, createdAt: at,
179
- })
313
+ const effective = await catalogueOf(ctx).resolveEffectivePlan(req.entityId, at)
314
+ const declaration = declarationOf(effective, req.limitKey)
315
+ const key: CounterKey = {
316
+ entityId: req.entityId, limitKey: req.limitKey,
317
+ window: planLimitHelper.windowKeyOf(declaration.kind, declaration.window, at, effective.subscription?.createdAt),
318
+ }
319
+
320
+ return await outcomeOf(key, req.eventKey, flags, ceilingOf(declaration, effective, at),
321
+ grantFoldHelper.unitsOf(effective.grants ?? [], req.limitKey), consumed.window)
180
322
  } catch (error) {
181
- // Undo the admission. Should the undo itself fail, the counter over-counts — never over-admits.
182
- await decrement(key, amount, at).catch(undo => { log.error('Usage undo failed', undo) })
183
- if (!paymentUtils.isDuplicateKey(error)) {
323
+ if (!(error instanceof LimitUnknown) && !(error instanceof PlanRequired)) {
184
324
  throw error
185
325
  }
186
- // A concurrent consume of the same key won the event: replay its outcome.
187
- const winner = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
188
- return await outcomeOf({ ...key, window: winner?.window ?? key.window }, req.eventKey, {
189
- admitted: isActiveConsumption(winner), replayed: true,
190
- }, limit)
191
- }
326
+ // No plan declares the limit any more: only its grants are left to report.
327
+ const fold = grantFoldHelper.unitsFold(
328
+ grantFoldHelper.unitsOf(await entitlementGrantsOf(ctx).inForce(req.entityId, at), req.limitKey),
329
+ )
192
330
 
193
- const used = Math.max(0, counter.used)
194
- const resetsAt = resetsAtOfWindow(key.window)
195
-
196
- return {
197
- admitted: true, replayed: false, limitKey: req.limitKey, window: key.window, used, limit,
198
- remaining: Math.max(0, limit - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey: req.eventKey,
331
+ return {
332
+ ...flags, limitKey: req.limitKey, window: consumed.window, used: fold.used, limit: fold.amount,
333
+ remaining: Math.max(0, fold.amount - fold.used), eventKey: req.eventKey,
334
+ }
199
335
  }
200
336
  }
201
337
 
@@ -209,8 +345,10 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
209
345
  }
210
346
  }
211
347
  const key: CounterKey = { entityId: req.entityId, limitKey: req.limitKey, window: consumed.window }
348
+ // A unit held on a grant goes back to that grant, never to a counter.
349
+ const grantId = grantFoldHelper.grantIdOf(consumed.window)
212
350
  if (consumed.releasedAt != null) {
213
- return await outcomeOf(key, req.eventKey, { admitted: true, replayed: true })
351
+ return await releaseOutcomeOf(req, consumed, { admitted: true, replayed: true })
214
352
  }
215
353
  const amount = Math.min(req.amount ?? consumed.delta, consumed.delta)
216
354
  if (!Number.isSafeInteger(amount) || amount < 1) {
@@ -228,15 +366,19 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
228
366
  if (!paymentUtils.isDuplicateKey(error)) {
229
367
  throw error
230
368
  }
231
- // An earlier attempt appended the release and decremented; only the stamp is missing.
369
+ // An earlier attempt appended the release and gave the unit back; only the stamp is missing.
232
370
  appended = false
233
371
  }
234
372
  if (appended) {
235
- await decrement(key, amount, at)
373
+ if (grantId != null) {
374
+ await returnToGrant(grantId, amount)
375
+ } else {
376
+ await decrement(key, amount, at)
377
+ }
236
378
  }
237
379
  await ledger.update({ ...consumed, releasedAt: at })
238
380
 
239
- return await outcomeOf(key, req.eventKey, { admitted: true, replayed: false })
381
+ return await releaseOutcomeOf(req, consumed, { admitted: true, replayed: false })
240
382
  }
241
383
 
242
384
  const consumptionOf = async (
@@ -262,7 +404,7 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
262
404
  const counter = await readCounter({ entityId, limitKey, window })
263
405
  const [view] = entitlementViewHelper.limitViewsOf({ limits: { [limitKey]: declaration } }, counter != null ? [{ key: limitKey, window, used: counter.used }] : [], effective.subscription?.createdAt, at)
264
406
 
265
- return view
407
+ return grantFoldHelper.foldLimitView(view, effective.grants ?? [])
266
408
  }
267
409
 
268
410
  const ledgerSums = async (match: Partial<CounterKey>): Promise<LedgerSum[]> => {
@@ -313,11 +455,16 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
313
455
  if (declaration.kind !== LimitKind.Occupancy) {
314
456
  throw new LimitMisdeclared(`${limitKey}:not-occupancy`)
315
457
  }
316
- const limit = ceilingOf(declaration, effective, at)
458
+ const ceiling = ceilingOf(declaration, effective, at)
317
459
  const key: CounterKey = { entityId, limitKey, window: OCCUPANCY_WINDOW }
460
+ // What the grants in force hold is theirs; the plan counter holds the rest of what exists. A
461
+ // revoked or ended grant's units fall back on the plan counter here — over its ceiling, flagged.
462
+ const fold = grantFoldHelper.unitsFold(grantFoldHelper.unitsOf(effective.grants ?? [], limitKey))
463
+ const held = Math.max(0, actual - fold.used)
464
+ const limit = ceiling + fold.amount
318
465
 
319
466
  const [sum] = await ledgerSums(key)
320
- const delta = actual - (sum?.used ?? 0)
467
+ const delta = held - (sum?.used ?? 0)
321
468
  if (delta !== 0) {
322
469
  const eventKey = `reconcile:${limitKey}:${planLimitHelper.windowKeyOf(LimitKind.Window, LimitWindow.Day, at)}`
323
470
  try {
@@ -336,13 +483,47 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
336
483
  const over = Math.max(0, actual - limit)
337
484
  const overSince = over > 0 ? (counter?.overSince != null ? new Date(counter.overSince) : at) : undefined
338
485
  await setCounter(key, {
339
- used: actual, limit, planSku: effective.plan.sku, updatedAt: at, reconciledAt: at,
486
+ used: held, limit: ceiling, planSku: effective.plan.sku, updatedAt: at, reconciledAt: at,
340
487
  ...(overSince != null ? { overSince } : {}),
341
488
  }, overSince == null ? ['overSince'] : [])
342
489
 
343
490
  return { limitKey, used: actual, limit, over, ...(overSince != null ? { overSince } : {}) }
344
491
  }
345
492
 
493
+ /**
494
+ * Rebuild every units grant's `used` of an entity from its events (`sums` of its `grant:<id>`
495
+ * windows); a grant without events holds nothing.
496
+ */
497
+ const reconcileGrants = async (entityId: string, sums: readonly LedgerSum[]): Promise<CounterReconciliation> => {
498
+ const records = access.grantRecordsOf()
499
+ if (records == null) {
500
+ return { counters: 0, repaired: 0 }
501
+ }
502
+ const byGrant = new Map<string, number>()
503
+ for (const sum of sums) {
504
+ const grantId = grantFoldHelper.grantIdOf(sum.window)
505
+ if (grantId != null) {
506
+ byGrant.set(grantId, (byGrant.get(grantId) ?? 0) + sum.used)
507
+ }
508
+ }
509
+ const { items } = await records.list({ entityId, kind: EntitlementGrantKind.Units }, { size: 0 })
510
+ let counters = 0
511
+ let repaired = 0
512
+ for (const grant of items) {
513
+ if (grant.id == null) {
514
+ continue
515
+ }
516
+ const used = Math.max(0, byGrant.get(grant.id) ?? 0)
517
+ counters++
518
+ if (used !== (grant.used ?? 0)) {
519
+ repaired++
520
+ await records.collection.updateOne(paymentUtils.idCriteria(grant.id), { $set: { used } })
521
+ }
522
+ }
523
+
524
+ return { counters, repaired }
525
+ }
526
+
346
527
  const reconcileLedgerCounters = async (entityId?: string): Promise<CounterReconciliation> => {
347
528
  const at = new Date()
348
529
  const sums = await ledgerSums(entityId != null ? { entityId } : {})
@@ -365,7 +546,9 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
365
546
  return declaration != null && effective != null ? ceilingOf(declaration, effective, at) : fallback
366
547
  }
367
548
 
368
- const ledger = new Map(sums.filter(sum => sum.entityId === entity)
549
+ // A grant's events rebuild that grant, never a counter window.
550
+ const own = sums.filter(sum => sum.entityId === entity)
551
+ const ledger = new Map(own.filter(sum => grantFoldHelper.grantIdOf(sum.window) == null)
369
552
  .map(sum => [`${sum.limitKey}${sum.window}`, sum.used]))
370
553
  const { items: stored } = await access.usageCounters().list({ entityId: entity }, { size: 0 })
371
554
  const seen = new Set<string>()
@@ -417,6 +600,10 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
417
600
  used: 0, limit: limitOf(limitKey, 0), planSku: effective?.plan.sku, updatedAt: at, reconciledAt: at,
418
601
  })
419
602
  }
603
+
604
+ const grants = await reconcileGrants(entity, own)
605
+ counters += grants.counters
606
+ repaired += grants.repaired
420
607
  }
421
608
 
422
609
  return { counters, repaired }
@@ -25,6 +25,11 @@ export interface PaymentUtils {
25
25
  ) => Promise<boolean>
26
26
  /** A conditional single-document delete — `true` when the filter matched (the guard held). */
27
27
  conditionalDelete: (resource: CollectionHolder, filter: Record<string, unknown>) => Promise<boolean>
28
+ /**
29
+ * A raw collection filter addressing ONE record by its id (`_id`), plus `filter` — what a
30
+ * conditional raw write (`$inc` guarded by a value) of a record known by id matches on.
31
+ */
32
+ idCriteria: (id: string, filter?: Record<string, unknown>) => Record<string, unknown>
28
33
  /** An error's message for an audit record, never a stack. */
29
34
  errorText: (error: unknown) => string
30
35
  }
package/src/utils.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type Stripe from 'stripe'
2
- import { MONGO_DUPLICATE_KEY } from '@owlmeans/mongo-resource'
2
+ import { MONGO_DUPLICATE_KEY, mongoRefHelper } from '@owlmeans/mongo-resource'
3
3
  import { WebhookSetupError, type PaymentService } from '@owlmeans/payment'
4
4
  import type { Context as ApiContext } from '@owlmeans/server-api'
5
5
  import { CONSUMER_RIGHTS_SERVICE } from './consts.js'
@@ -55,11 +55,15 @@ export const createPaymentUtils = (): PaymentUtils => {
55
55
  return (result.deletedCount ?? 0) > 0
56
56
  }
57
57
 
58
+ const idCriteria = (id: string, filter: Record<string, unknown> = {}): Record<string, unknown> =>
59
+ mongoRefHelper.marshalCriteria({ ...filter, id }, new Map()) as Record<string, unknown>
60
+
58
61
  const errorText = (error: unknown): string =>
59
62
  (error instanceof Error ? error.message : String(error)).slice(0, 1000)
60
63
 
61
64
  return {
62
- apiVersionOf, isDuplicateKey, isMissingObject, idOf, dateOf, compact, conditionalSet, conditionalDelete, errorText,
65
+ apiVersionOf, isDuplicateKey, isMissingObject, idOf, dateOf, compact, conditionalSet, conditionalDelete,
66
+ idCriteria, errorText,
63
67
  }
64
68
  }
65
69
 
@@ -14,19 +14,19 @@ import {
14
14
  } from '../src/config.js'
15
15
  import {
16
16
  RES_BILLING_PROFILE, RES_CONSUMER_CONSENT, RES_CONSUMER_DECLARATION, RES_CONSUMER_EVENT, RES_PAYGATE_CUSTOMER,
17
- RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_PURCHASE, RES_PAYMENT_SUBSCRIPTION,
17
+ RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_GRANT, RES_PAYMENT_PURCHASE, RES_PAYMENT_SUBSCRIPTION,
18
18
  RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
19
19
  } from '../src/consts.js'
20
20
  import { appendConsumerRights } from '../src/consumer/service.js'
21
21
  import {
22
22
  makeBillingProfileResource, makeConsumerConsentResource, makeConsumerDeclarationResource,
23
- makeConsumerEventResource, makeFingerprintResource, makeFulfillmentResource, makePaygateCustomerResource,
24
- makePurchaseResource, makeSubscriptionResource, makeUsageCounterResource, makeUsageResource, makeWebhookResource,
23
+ makeConsumerEventResource, makeFingerprintResource, makeFulfillmentResource, makeGrantResource,
24
+ makePaygateCustomerResource, makePurchaseResource, makeSubscriptionResource, makeUsageCounterResource, makeUsageResource, makeWebhookResource,
25
25
  } from '../src/resource.js'
26
26
  import { appendPaymentGatewayService } from '../src/service.js'
27
27
  import type {
28
28
  GatewayServiceOptions, CancellationEvent, Config, ConsentEvent, ConsumerRightsDef, ConsumerRightsOptions,
29
- DisputeEvent, PaymentFailedEvent, PaymentPlanDef, PortalBrandingDef, PricingDef, RefundEvent, SubscriptionEvent,
29
+ DisputeEvent, EntitlementGrantEvent, PaymentFailedEvent, PaymentPlanDef, PortalBrandingDef, PricingDef, RefundEvent, SubscriptionEvent,
30
30
  TopUpCompletion, UsageMeter, WithdrawalEvent,
31
31
  } from '../src/types.js'
32
32
  import { paymentAccessOf } from '../src/access.js'
@@ -731,7 +731,13 @@ export const memoryResource = <T extends ResourceRecord>(resource: MongoResource
731
731
  return before - store.rows.length
732
732
  }
733
733
 
734
- const matchRaw = (filter: Rec) => store.rows.find(row => recordQueryHelper.matchCriteria(row, filter))
734
+ // A raw filter addresses a record by `_id` (`paymentUtils.idCriteria`); the rows carry it as `id`.
735
+ const rawFilter = (filter: Rec): Rec => {
736
+ if (!('_id' in filter)) return filter
737
+ const { _id: rawId, ...rest } = filter
738
+ return { ...rest, id: String(rawId) }
739
+ }
740
+ const matchRaw = (filter: Rec) => store.rows.find(row => recordQueryHelper.matchCriteria(row, rawFilter(filter)))
735
741
  const upsert = (filter: Rec, update: Rec, opts: Rec = {}): { doc: Rec | null, inserted: boolean } => {
736
742
  const found = matchRaw(filter)
737
743
  if (found != null) {
@@ -739,7 +745,7 @@ export const memoryResource = <T extends ResourceRecord>(resource: MongoResource
739
745
  return { doc: found, inserted: false }
740
746
  }
741
747
  if (opts.upsert !== true) return { doc: null, inserted: false }
742
- const doc: Rec = Object.fromEntries(Object.entries(filter).filter(([, value]) =>
748
+ const doc: Rec = Object.fromEntries(Object.entries(rawFilter(filter)).filter(([, value]) =>
743
749
  value === null || typeof value !== 'object' || value instanceof Date))
744
750
  applyUpdate(doc, update, true)
745
751
  if (violates(doc)) throw duplicate()
@@ -856,10 +862,13 @@ export interface Observed {
856
862
  consent: ConsentEvent[]
857
863
  withdrawal: WithdrawalEvent[]
858
864
  cancellation: CancellationEvent[]
865
+ grant: EntitlementGrantEvent[]
859
866
  /** Throw from the next `n` subscription callbacks. */
860
867
  failSubscription: number
861
868
  failTopUp: number
862
869
  failWithdrawal: number
870
+ /** Throw from the next `n` entitlement grant callbacks. */
871
+ failGrant: number
863
872
  /** Run inside every top-up / subscription callback, before it records the event. */
864
873
  onTopUp?: (event: TopUpCompletion) => Promise<void>
865
874
  onSubscription?: (event: SubscriptionEvent) => Promise<void>
@@ -922,6 +931,7 @@ export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<Fa
922
931
  [RES_CONSUMER_CONSENT, makeConsumerConsentResource()],
923
932
  [RES_CONSUMER_DECLARATION, makeConsumerDeclarationResource()],
924
933
  [RES_CONSUMER_EVENT, makeConsumerEventResource()],
934
+ [RES_PAYMENT_GRANT, makeGrantResource()],
925
935
  ] as const
926
936
  for (const [alias, resource] of resources) {
927
937
  stores[alias] = memoryResource(resource as unknown as MongoResource<ResourceRecord>)
@@ -950,7 +960,7 @@ export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<Fa
950
960
 
951
961
  const observed: Observed = {
952
962
  topUp: [], subscription: [], refund: [], dispute: [], paymentFailed: [], consent: [], withdrawal: [],
953
- cancellation: [], failSubscription: 0, failTopUp: 0, failWithdrawal: 0,
963
+ cancellation: [], grant: [], failSubscription: 0, failTopUp: 0, failWithdrawal: 0, failGrant: 0,
954
964
  }
955
965
  const completions = paymentAccessOf(ctx).observer()
956
966
  await completions.ready()
@@ -982,6 +992,13 @@ export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<Fa
982
992
  observed.withdrawal.push(event)
983
993
  })
984
994
  completions.onCancellation(async event => { observed.cancellation.push(event) })
995
+ completions.onEntitlementGrant(async event => {
996
+ if (observed.failGrant > 0) {
997
+ observed.failGrant--
998
+ throw new Error('sweeps unavailable')
999
+ }
1000
+ observed.grant.push(event)
1001
+ })
985
1002
 
986
1003
  return { ctx, stripe, state, stores, observed, mails: mailer.captured, mailer }
987
1004
  }