@pithy-sh/payments 0.4.0 → 0.6.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 (180) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +2 -1
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
@@ -0,0 +1,363 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { encodeSubjectReference } from "../data/subject.js";
4
+ import { reportedProducts } from "../config/config.js";
5
+ import { grantingStatuses } from "../data/status.js";
6
+ import { PaymentsPurchase } from "../data/purchase.js";
7
+ import { PaymentsUsageReport } from "../data/usageReport.js";
8
+ import { PaymentsUsageRun } from "../data/usageRun.js";
9
+ import { PAYMENTS_PURCHASES_TABLE, PAYMENTS_USAGE_REPORTS_TABLE, PAYMENTS_USAGE_RUNS_TABLE, paymentsDatabase } from "../data/tables.js";
10
+ import { knownPeriodStart } from "../data/period.js";
11
+ import { providerAccountForSubject } from "../projection/owner.js";
12
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
13
+ import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
14
+ import { sql } from "kysely";
15
+ //#region src/usage/pass.ts
16
+ /**
17
+ * The usage-reporting pass: ask the adopter how many, and tell the store.
18
+ *
19
+ * **Configuration decides what is billable and how often; a function decides the number.** The same split
20
+ * as `billingSubject` / `resolveSubject`, for the same reason — `PaymentsConfig` round-trips through JSON, so
21
+ * a function cannot live in it. `resolveQuantity` rides on the `payments(...)` options and reaches this pass
22
+ * through the composed capability, never through config.
23
+ *
24
+ * **Pulled, not pushed.** A cron walks the subscribed subjects and reports, the shape the reconcile pass
25
+ * already has. No proration, no mid-cycle rewrite of a subscription's items, and a missed report bills last
26
+ * period's number rather than the wrong number indefinitely.
27
+ *
28
+ * ## What it never does
29
+ *
30
+ * - **Report a guess.** A resolver answering `undefined` reports nothing for that subject, and is counted as
31
+ * skipped — never `0`, because a zeroed meter is a bill of nothing for a customer who owes something. A
32
+ * non-integer, a negative, or a count outside the product's `min`/`max` is skipped and named — never
33
+ * clamped, because a clamped value is a wrong number billed silently.
34
+ * - **Stop for one subject.** A resolver that throws is a failure in the tally, and the sweep goes on.
35
+ * - **Report a period twice.** One row per `(rail, subscription, period)`, claimed before the store is
36
+ * called, and the row id sent as the store's idempotency key.
37
+ * - **Read a meter.** The kit does not sell overage. What a kit meter counted is never a billable number,
38
+ * and nothing here imports one.
39
+ *
40
+ * ## The two cadences
41
+ *
42
+ * - `period-end` — one report per subscription per billing period, keyed on the period's end and sent on
43
+ * the first run inside its last {@link PERIOD_END_WINDOW_MS}, dated at that run. Every later run in the
44
+ * period finds the row.
45
+ * - `daily-peak` — every run asks, and the day's row keeps the highest answer; a lower later answer never
46
+ * lowers it. **A day is never sent on its own.** The period's report is the highest of its days, sent once,
47
+ * in the period's last {@link PERIOD_END_WINDOW_MS} — keyed and dated exactly as a `period-end` report.
48
+ * Both stores add up what they are sent: Stripe's meter sums its events, and every Paddle charge is a line
49
+ * on the bill. A report per day would bill the sum of thirty daily peaks, not the period's peak. The day
50
+ * rows stay behind, and they are the audit: the number billed is the largest of them up to the report.
51
+ *
52
+ * A `daily-peak` report goes out when the last day opens, as a `period-end` one does, so a peak reached in
53
+ * the period's final hours after it was sent is not billed. Under-billing an hour is the right way round.
54
+ */
55
+ /** How close to a period's end a `period-end` report goes out. A day, so an hourly or daily cron lands inside it. */
56
+ const PERIOD_END_WINDOW_MS = 864e5;
57
+ /** How long after a period's end its subscription is still reported — a run that missed the window by a little. */
58
+ const LATE_WINDOW_MS = 864e5;
59
+ /** Whether a resolver's answer may be billed, and if not, why. */
60
+ function judgeQuantity(answer, billing) {
61
+ if (answer === void 0) return {
62
+ ok: false,
63
+ reason: "unanswered"
64
+ };
65
+ if (typeof answer !== "number" || !Number.isInteger(answer)) return {
66
+ ok: false,
67
+ reason: "not_integer"
68
+ };
69
+ if (answer < 0) return {
70
+ ok: false,
71
+ reason: "negative"
72
+ };
73
+ if (answer < billing.min) return {
74
+ ok: false,
75
+ reason: "below_min"
76
+ };
77
+ if (answer > billing.max) return {
78
+ ok: false,
79
+ reason: "above_max"
80
+ };
81
+ return {
82
+ ok: true,
83
+ quantity: answer
84
+ };
85
+ }
86
+ /** The UTC day `at` falls in, as `YYYY-MM-DD`. A `daily-peak` period's key. */
87
+ function utcDay(at) {
88
+ return at.toISOString().slice(0, 10);
89
+ }
90
+ /**
91
+ * Every subscription of one product on one rail whose current period is live, or ended within the late
92
+ * window — newest period per subscription, because each billing period is its own purchase row.
93
+ */
94
+ async function currentPeriods(db, config, productId, rail, now) {
95
+ const at = now.getTime();
96
+ const rows = await db.selectFrom(PAYMENTS_PURCHASES_TABLE).selectAll().where("productId", "=", productId).where("rail", "=", rail).where("type", "=", "subscription").where("status", "in", grantingStatuses(config.graceGrantsAccess)).where("purchasedAt", "<=", at).where("expiresAt", ">", at - LATE_WINDOW_MS).orderBy("purchasedAt", "desc").execute();
97
+ const newest = /* @__PURE__ */ new Map();
98
+ for (const row of rows) {
99
+ const purchase = PaymentsPurchase.parse(row);
100
+ const subscription = purchase.originalTransactionId;
101
+ if (subscription === null || purchase.expiresAt === null || newest.has(subscription)) continue;
102
+ newest.set(subscription, {
103
+ purchase,
104
+ providerSubscriptionId: subscription,
105
+ periodEnd: purchase.expiresAt
106
+ });
107
+ }
108
+ return [...newest.values()];
109
+ }
110
+ /** One period's row, if there is one. */
111
+ async function readReport(db, rail, subscription, period) {
112
+ const row = await db.selectFrom(PAYMENTS_USAGE_REPORTS_TABLE).selectAll().where("rail", "=", rail).where("providerSubscriptionId", "=", subscription).where("period", "=", period).executeTakeFirst();
113
+ return row === void 0 ? void 0 : PaymentsUsageReport.parse(row);
114
+ }
115
+ /** Run one pass, record its tally, and return it. */
116
+ async function runUsageReport(deps) {
117
+ const db = paymentsDatabase(deps.d1);
118
+ const newId = deps.newId ?? (() => crypto.randomUUID());
119
+ const startedAt = deps.now();
120
+ const tally = {
121
+ id: newId(),
122
+ scanned: 0,
123
+ reported: 0,
124
+ sampled: 0,
125
+ alreadyReported: 0,
126
+ skipped: 0,
127
+ invalid: 0,
128
+ failed: 0,
129
+ findings: []
130
+ };
131
+ const note = (subject, productId, reason) => {
132
+ if (reason === "unanswered") tally.skipped++;
133
+ else if (reason === "resolver_failed" || reason === "report_failed") tally.failed++;
134
+ else tally.invalid++;
135
+ if (tally.findings.length < 100) tally.findings.push({
136
+ ...subject,
137
+ productId,
138
+ reason
139
+ });
140
+ deps.log.warn("usage not reported", {
141
+ subject: encodeSubjectReference(subject),
142
+ productId,
143
+ reason
144
+ });
145
+ };
146
+ /** Ask the resolver, and judge the answer. Undefined when nothing may be billed — already noted. */
147
+ const ask = async (period, productId, billing, now) => {
148
+ const subject = {
149
+ subjectType: period.purchase.subjectType,
150
+ subjectId: period.purchase.subjectId
151
+ };
152
+ let answer;
153
+ try {
154
+ answer = await deps.resolveQuantity({
155
+ env: deps.env,
156
+ productId,
157
+ unit: billing.unit,
158
+ now
159
+ }, subject);
160
+ } catch (error) {
161
+ deps.log.error("usage resolver failed", {
162
+ subject: encodeSubjectReference(subject),
163
+ productId,
164
+ cause: messageOf(error)
165
+ });
166
+ note(subject, productId, "resolver_failed");
167
+ return;
168
+ }
169
+ const judged = judgeQuantity(answer, billing);
170
+ if (!judged.ok) {
171
+ note(subject, productId, judged.reason);
172
+ return;
173
+ }
174
+ return judged.quantity;
175
+ };
176
+ /** Send one claimed row to its store, and settle the row either way. */
177
+ const send = async (period, productId, billing, report, at) => {
178
+ const rail = period.purchase.rail;
179
+ const subject = {
180
+ subjectType: period.purchase.subjectType,
181
+ subjectId: period.purchase.subjectId
182
+ };
183
+ const reporter = deps.reporters[rail];
184
+ try {
185
+ if (reporter === void 0) throw new Error(`no ${rail} reporter is configured for this pass`);
186
+ await reporter.report({
187
+ providerSubscriptionId: period.providerSubscriptionId,
188
+ providerCustomerId: rail === "stripe" ? await providerAccountForSubject(db, "stripe", subject) : void 0,
189
+ quantity: report.quantity,
190
+ period: report.period,
191
+ at,
192
+ billing,
193
+ idempotencyKey: `usage_${report.id}`
194
+ });
195
+ } catch (error) {
196
+ deps.log.error("usage report failed", {
197
+ subject: encodeSubjectReference(subject),
198
+ productId,
199
+ rail,
200
+ period: report.period,
201
+ cause: messageOf(error)
202
+ });
203
+ note(subject, productId, "report_failed");
204
+ return;
205
+ }
206
+ const now = deps.now().getTime();
207
+ await withD1Retry(() => db.updateTable(PAYMENTS_USAGE_REPORTS_TABLE).set({
208
+ status: "reported",
209
+ reportedAt: now,
210
+ updatedAt: now
211
+ }).where("id", "=", report.id).execute());
212
+ tally.reported++;
213
+ };
214
+ for (const { id: productId, billing } of reportedProducts(deps.config)) for (const rail of billing.rails) {
215
+ if (rail !== "stripe" && rail !== "paddle") continue;
216
+ const now = deps.now();
217
+ for (const period of await currentPeriods(db, deps.config, productId, rail, now)) {
218
+ tally.scanned++;
219
+ if (billing.cadence === "period-end") await periodEnd(period, productId, billing, now);
220
+ else await dailyPeak(period, productId, billing, now);
221
+ }
222
+ }
223
+ /** `period-end`: inside the window, once per period. */
224
+ async function periodEnd(period, productId, billing, now) {
225
+ if (now.getTime() < period.periodEnd.getTime() - 864e5) return;
226
+ const key = period.periodEnd.toISOString();
227
+ const existing = await readReport(db, period.purchase.rail, period.providerSubscriptionId, key);
228
+ if (existing?.status === "reported") {
229
+ tally.alreadyReported++;
230
+ return;
231
+ }
232
+ if (existing?.status === "claimed") {
233
+ await send(period, productId, billing, existing, reportDate(period, now));
234
+ return;
235
+ }
236
+ const quantity = await ask(period, productId, billing, now);
237
+ if (quantity === void 0) return;
238
+ const claimed = await claim(period, productId, billing, key, quantity, now, "claimed");
239
+ if (claimed === void 0) {
240
+ tally.alreadyReported++;
241
+ return;
242
+ }
243
+ await send(period, productId, billing, claimed, reportDate(period, now));
244
+ }
245
+ /**
246
+ * `daily-peak`: sample today, and in the period's last day report the highest day the period sampled.
247
+ * Once per period, keyed on its end — the same row, key and date a `period-end` report has.
248
+ */
249
+ async function dailyPeak(period, productId, billing, now) {
250
+ if (now.getTime() < period.periodEnd.getTime()) {
251
+ const quantity = await ask(period, productId, billing, now);
252
+ if (quantity !== void 0) {
253
+ await sample(period, productId, billing, utcDay(now), quantity, now);
254
+ tally.sampled++;
255
+ }
256
+ }
257
+ if (now.getTime() < period.periodEnd.getTime() - 864e5) return;
258
+ const key = period.periodEnd.toISOString();
259
+ const existing = await readReport(db, period.purchase.rail, period.providerSubscriptionId, key);
260
+ if (existing?.status === "reported") {
261
+ tally.alreadyReported++;
262
+ return;
263
+ }
264
+ if (existing?.status === "claimed") {
265
+ await send(period, productId, billing, existing, reportDate(period, now));
266
+ return;
267
+ }
268
+ const peak = await periodPeak(period, key);
269
+ if (peak === void 0) return;
270
+ const claimed = await claim(period, productId, billing, key, peak, now, "claimed");
271
+ if (claimed === void 0) {
272
+ tally.alreadyReported++;
273
+ return;
274
+ }
275
+ await send(period, productId, billing, claimed, reportDate(period, now));
276
+ }
277
+ /**
278
+ * The highest day one period sampled, or undefined when it sampled none.
279
+ *
280
+ * **A period's days are the ones after the previous period's.** The lower bound is the later of the
281
+ * period's start, where the row states one (`data/period.ts`), and the day the subscription's previous
282
+ * report was keyed on — so a high day last period is never billed again this one, on a rail whose start
283
+ * is not stored too. The day a renewal falls on belongs to both: its peak was reached in one of them.
284
+ */
285
+ async function periodPeak(period, key) {
286
+ const rail = period.purchase.rail;
287
+ const previous = await db.selectFrom(PAYMENTS_USAGE_REPORTS_TABLE).select("period").where("rail", "=", rail).where("providerSubscriptionId", "=", period.providerSubscriptionId).where("status", "in", ["claimed", "reported"]).where("period", "<", key).orderBy("period", "desc").limit(1).executeTakeFirst();
288
+ const bounds = [knownPeriodStart(period.purchase), previous && new Date(previous.period)].filter((at) => at instanceof Date && !Number.isNaN(at.getTime())).map(utcDay);
289
+ let days = db.selectFrom(PAYMENTS_USAGE_REPORTS_TABLE).select((eb) => eb.fn.max("quantity").as("peak")).where("rail", "=", rail).where("providerSubscriptionId", "=", period.providerSubscriptionId).where("status", "=", "sampling").where("period", "<=", utcDay(period.periodEnd));
290
+ const from = bounds.sort().at(-1);
291
+ if (from !== void 0) days = days.where("period", ">=", from);
292
+ return (await days.executeTakeFirst())?.peak ?? void 0;
293
+ }
294
+ /** Write a period's row as claimed or sampling, or nothing when a row for it exists. */
295
+ async function claim(period, productId, billing, key, quantity, now, status) {
296
+ const record = PaymentsUsageReport.encode({
297
+ id: newId(),
298
+ rail: period.purchase.rail,
299
+ providerSubscriptionId: period.providerSubscriptionId,
300
+ purchaseId: period.purchase.id,
301
+ productId,
302
+ subjectType: period.purchase.subjectType,
303
+ subjectId: period.purchase.subjectId,
304
+ cadence: billing.cadence,
305
+ period: key,
306
+ quantity,
307
+ status,
308
+ sampledAt: now,
309
+ reportedAt: null,
310
+ createdAt: now,
311
+ updatedAt: now
312
+ });
313
+ if (await db.insertInto("pithyPaymentsUsageReports").values(record).onConflict((oc) => oc.columns([
314
+ "rail",
315
+ "providerSubscriptionId",
316
+ "period"
317
+ ]).doNothing()).returning("id").executeTakeFirst() === void 0) return void 0;
318
+ return PaymentsUsageReport.parse(record);
319
+ }
320
+ /** Record a day's sample: the first of the day inserts, every later one keeps the higher. */
321
+ async function sample(period, productId, billing, day, quantity, now) {
322
+ if (await claim(period, productId, billing, day, quantity, now, "sampling") !== void 0) return;
323
+ const peak = {
324
+ quantity: sql`max(${sql.ref("quantity")}, ${quantity})`,
325
+ sampledAt: now.getTime(),
326
+ updatedAt: now.getTime()
327
+ };
328
+ await db.updateTable(PAYMENTS_USAGE_REPORTS_TABLE).set(peak).where("rail", "=", period.purchase.rail).where("providerSubscriptionId", "=", period.providerSubscriptionId).where("period", "=", day).where("status", "=", "sampling").execute();
329
+ }
330
+ const finishedAt = deps.now();
331
+ const run = PaymentsUsageRun.encode({
332
+ id: tally.id,
333
+ startedAt,
334
+ finishedAt,
335
+ scanned: tally.scanned,
336
+ reported: tally.reported,
337
+ sampled: tally.sampled,
338
+ alreadyReported: tally.alreadyReported,
339
+ skipped: tally.skipped,
340
+ invalid: tally.invalid,
341
+ failed: tally.failed,
342
+ findings: tally.findings,
343
+ createdAt: finishedAt
344
+ });
345
+ await withD1Retry(() => db.insertInto(PAYMENTS_USAGE_RUNS_TABLE).values(run).execute());
346
+ deps.log.info("usage report finished", {
347
+ run: tally.id,
348
+ scanned: tally.scanned,
349
+ reported: tally.reported,
350
+ sampled: tally.sampled,
351
+ alreadyReported: tally.alreadyReported,
352
+ skipped: tally.skipped,
353
+ invalid: tally.invalid,
354
+ failed: tally.failed
355
+ });
356
+ return tally;
357
+ }
358
+ /** A `period-end` report's date: the run's own, but never past the period's end — it bills that period. */
359
+ function reportDate(period, now) {
360
+ return now.getTime() < period.periodEnd.getTime() ? now : /* @__PURE__ */ new Date(period.periodEnd.getTime() - 1e3);
361
+ }
362
+ //#endregion
363
+ export { PERIOD_END_WINDOW_MS, judgeQuantity, runUsageReport, utcDay };
@@ -0,0 +1,36 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PaymentsReportedBilling } from "../config/config";
4
+ /**
5
+ * What a store is told about one reported period, and the one method a rail implements to tell it.
6
+ *
7
+ * **Every report carries an idempotency key, and both stores honor one.** Stripe dedupes a meter event by its
8
+ * `identifier`; Paddle dedupes a write by its `Paddle-Idempotency-Key`. The key is the period's own row id, so
9
+ * a run that crashed after the store answered and before the row said so sends the same key again, and the
10
+ * store records the period once. That is what lets a claimed period be retried rather than abandoned.
11
+ *
12
+ * **The quantity is the adopter's.** It is the number `resolveQuantity` answered, validated against the
13
+ * product's `min` and `max`. Nothing a kit meter counted ever reaches this type.
14
+ */
15
+ export interface UsageReportRequest {
16
+ /** The subscription at the store — `sub_…`. */
17
+ providerSubscriptionId: string;
18
+ /** The store's customer for this subscription — Stripe's `cus_…` — when the rail needs one. */
19
+ providerCustomerId: string | undefined;
20
+ /** The count. A whole number inside the product's bounds. */
21
+ quantity: number;
22
+ /** Which period this is, as the row keys it. */
23
+ period: string;
24
+ /** The instant the report is dated — inside the period it bills. */
25
+ at: Date;
26
+ /** The product's reported billing — the meter it feeds, the price it charges. */
27
+ billing: PaymentsReportedBilling;
28
+ /** Sent to the store so a repeated report is recorded once. */
29
+ idempotencyKey: string;
30
+ }
31
+ /** One rail's half of reporting. Throws when the store did not accept the report. */
32
+ export interface UsageReporter {
33
+ /** Tell the store. Resolves when it accepted; throws when it did not. */
34
+ report(request: UsageReportRequest): Promise<void>;
35
+ }
36
+ //# sourceMappingURL=reporter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reporter.d.ts","sourceRoot":"","sources":["../../src/usage/reporter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAEhE;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IACjC,+CAA+C;IAC/C,sBAAsB,EAAE,MAAM,CAAC;IAC/B,+FAA+F;IAC/F,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC;IACjB,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,oEAAoE;IACpE,EAAE,EAAE,IAAI,CAAC;IACT,iFAAiF;IACjF,OAAO,EAAE,uBAAuB,CAAC;IACjC,+DAA+D;IAC/D,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,qFAAqF;AACrF,MAAM,WAAW,aAAa;IAC5B,yEAAyE;IACzE,MAAM,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD"}
@@ -0,0 +1,2 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/payments";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.4.0";
6
+ export declare const PACKAGE_VERSION = "0.6.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/payments";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.4.0";
7
+ const PACKAGE_VERSION = "0.6.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -1 +1 @@
1
- {"version":3,"file":"report.d.ts","sourceRoot":"","sources":["../../src/workflows/report.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAE/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAqBnD;;;;;;;;;;;GAWG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAQnD;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,IAAI,CAG7E"}
1
+ {"version":3,"file":"report.d.ts","sourceRoot":"","sources":["../../src/workflows/report.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAE/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAqBnD;;;;;;;;;;;GAWG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAUnD;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,IAAI,CAG7E"}
@@ -101,4 +101,32 @@ export declare const paymentsWorkflows: {
101
101
  * exists — and the key format comes from core's {@link workflowKey} either way, so the two cannot drift.
102
102
  */
103
103
  export declare const paymentsWorkflowRegistry: WorkflowRegistry;
104
+ /**
105
+ * What one usage-reporting run should cover. Nothing: a cron passes no input, and the pass covers every
106
+ * quantity-billed product. The object exists so a dispatch is validated like every other.
107
+ */
108
+ export declare const PaymentsUsageParams: z.ZodObject<{}, z.core.$strip>;
109
+ export type PaymentsUsageParams = z.infer<typeof PaymentsUsageParams>;
110
+ /**
111
+ * The usage-reporting pass — a Workflow **the adopter's own Worker hosts**, unlike reconciliation.
112
+ *
113
+ * **Why not the payments host.** The pass calls `resolveQuantity`, which is the adopter's function and lives
114
+ * only in the Worker whose `pithy.config.ts` passed it. The prebuilt host parses a config from a var and has
115
+ * no adopter code at all. So the class is exported from the app Worker's own entry — the same five lines as
116
+ * any app-declared Workflow, calling `reportPaymentsUsage` in `workflows/usage.ts` — and the body finds the
117
+ * composed capability, and the resolver on it, the way a Workflow that sends mail finds the composed email
118
+ * capability.
119
+ *
120
+ * Hourly, so a `daily-peak` day is sampled through the day and every period's report — under either
121
+ * cadence — lands in its last day whatever hour the period ends at. Contributed by `payments()` only when the catalog sells a
122
+ * reported product; a project that bills nothing by quantity binds nothing for it.
123
+ */
124
+ export declare const paymentsUsageWorkflows: {
125
+ readonly usage: {
126
+ readonly binding: "PAYMENTS_USAGE";
127
+ readonly params: z.ZodObject<{}, z.core.$strip>;
128
+ readonly schedule: "15 * * * *";
129
+ readonly optional: true;
130
+ };
131
+ };
104
132
  //# sourceMappingURL=specs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"specs.d.ts","sourceRoot":"","sources":["../../src/workflows/specs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAmB,MAAM,kCAAkC,CAAC;AAC1F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;;;GAYG;AAEH,uGAAuG;AACvG,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAE9C,wGAAwG;AACxG,eAAO,MAAM,+BAA+B,SAAU,CAAC;AAEvD,4FAA4F;AAC5F,eAAO,MAAM,2BAA2B,SAAU,CAAC;AAEnD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;iBA4D8E,CAAC;AACnH,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAE9E;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB;;iBAE1B,OAAO,EAAE,oBAAoB;iBAC7B,SAAS,EAAE,2BAA2B;iBACtC,MAAM;;;;;;;;;;;;;;;;;;;iBACN,QAAQ,EAAE,WAAW;iBACrB,QAAQ;;CAEwB,CAAC;AAErC;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,EAAE,gBAKtC,CAAC"}
1
+ {"version":3,"file":"specs.d.ts","sourceRoot":"","sources":["../../src/workflows/specs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAmB,MAAM,kCAAkC,CAAC;AAC1F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;;;GAYG;AAEH,uGAAuG;AACvG,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAE9C,wGAAwG;AACxG,eAAO,MAAM,+BAA+B,SAAU,CAAC;AAEvD,4FAA4F;AAC5F,eAAO,MAAM,2BAA2B,SAAU,CAAC;AAEnD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;iBA4D8E,CAAC;AACnH,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAE9E;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB;;iBAE1B,OAAO,EAAE,oBAAoB;iBAC7B,SAAS,EAAE,2BAA2B;iBACtC,MAAM;;;;;;;;;;;;;;;;;;;iBACN,QAAQ,EAAE,WAAW;iBACrB,QAAQ;;CAEwB,CAAC;AAErC;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,EAAE,gBAKtC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,gCAEsF,CAAC;AACvH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB;;iBAE/B,OAAO,EAAE,gBAAgB;iBAGzB,MAAM;iBACN,QAAQ,EAAE,YAAY;iBACtB,QAAQ;;CAEwB,CAAC"}
@@ -82,5 +82,30 @@ const paymentsWorkflowRegistry = Object.fromEntries(Object.entries(paymentsWorkf
82
82
  spec
83
83
  }];
84
84
  }));
85
+ /**
86
+ * What one usage-reporting run should cover. Nothing: a cron passes no input, and the pass covers every
87
+ * quantity-billed product. The object exists so a dispatch is validated like every other.
88
+ */
89
+ const PaymentsUsageParams = z.object({}).describe("One usage-reporting run. No parameters: a cron passes none, and the pass covers every reported product.");
90
+ /**
91
+ * The usage-reporting pass — a Workflow **the adopter's own Worker hosts**, unlike reconciliation.
92
+ *
93
+ * **Why not the payments host.** The pass calls `resolveQuantity`, which is the adopter's function and lives
94
+ * only in the Worker whose `pithy.config.ts` passed it. The prebuilt host parses a config from a var and has
95
+ * no adopter code at all. So the class is exported from the app Worker's own entry — the same five lines as
96
+ * any app-declared Workflow, calling `reportPaymentsUsage` in `workflows/usage.ts` — and the body finds the
97
+ * composed capability, and the resolver on it, the way a Workflow that sends mail finds the composed email
98
+ * capability.
99
+ *
100
+ * Hourly, so a `daily-peak` day is sampled through the day and every period's report — under either
101
+ * cadence — lands in its last day whatever hour the period ends at. Contributed by `payments()` only when the catalog sells a
102
+ * reported product; a project that bills nothing by quantity binds nothing for it.
103
+ */
104
+ const paymentsUsageWorkflows = { usage: {
105
+ binding: "PAYMENTS_USAGE",
106
+ params: PaymentsUsageParams,
107
+ schedule: "15 * * * *",
108
+ optional: true
109
+ } };
85
110
  //#endregion
86
- export { DEFAULT_EXPIRING_WITHIN_SECONDS, DEFAULT_STALE_AFTER_SECONDS, PAYMENTS_CAPABILITY, PaymentsReconcileParams, paymentsWorkflowRegistry, paymentsWorkflows };
111
+ export { DEFAULT_EXPIRING_WITHIN_SECONDS, DEFAULT_STALE_AFTER_SECONDS, PAYMENTS_CAPABILITY, PaymentsReconcileParams, PaymentsUsageParams, paymentsUsageWorkflows, paymentsWorkflowRegistry, paymentsWorkflows };
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type TerminalErrorConstructor, type WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
4
+ import { type UsagePassTally } from "../usage/pass";
5
+ /**
6
+ * The usage-reporting Workflow's body — run by a class **the adopter's own Worker** exports, because it calls
7
+ * their `resolveQuantity` and that function exists nowhere else.
8
+ *
9
+ * // apps/api/src/index.ts, beside the `createEntrypoint` it already exports
10
+ * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
11
+ * import { NonRetryableError } from "cloudflare:workflows";
12
+ * import { reportPaymentsUsage } from "@pithy-sh/payments/src/workflows/usage";
13
+ *
14
+ * export class PaymentsUsageWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
15
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
16
+ * return reportPaymentsUsage(this.env, event, step, NonRetryableError);
17
+ * }
18
+ * }
19
+ *
20
+ * plus a `workflows` entry binding `PAYMENTS_USAGE` to that class and the spec's cron —
21
+ * `packages/payments/docs/entitlements.md` has the stanza. **The class is the adopter's, the body is the
22
+ * kit's**, which is the split every app-declared Workflow already has: Cloudflare resolves a `class_name` in
23
+ * the script that binds it, so the class must be exported from the app's own entry, and a class shipped here
24
+ * would be one more module the build reads as a Workflow host it is not.
25
+ *
26
+ * The body finds the composed payments capability the way a Workflow that sends mail finds the composed email
27
+ * one: the class is exported from the same entry that calls `createBackend`, so the composition has happened
28
+ * in this isolate, and `resolveQuantity` is on the capability, never in a config that crossed a var.
29
+ *
30
+ * One journalled step. The pass is idempotent end to end — every period has one row, claimed before the store
31
+ * is called, and the row id is the store's idempotency key — so a retried step reports nothing twice.
32
+ */
33
+ export declare function reportPaymentsUsage(env: Record<string, unknown>, event: {
34
+ payload?: unknown;
35
+ workflowName?: string;
36
+ instanceId?: string;
37
+ }, step: WorkflowStepLike, terminalError: TerminalErrorConstructor): Promise<UsagePassTally | null>;
38
+ //# sourceMappingURL=usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/workflows/usage.ts"],"names":[],"mappings":"AAMA,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,gBAAgB,EACtB,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAKpE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,mBAAmB,CACvC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,KAAK,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,EACxE,IAAI,EAAE,gBAAgB,EACtB,aAAa,EAAE,wBAAwB,GACtC,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAyChC"}
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/registry.js";
4
+ import { PaymentsUsageParams } from "./specs.js";
5
+ import { isPaymentsCapability } from "../capability.js";
6
+ import { runUsageReport } from "../usage/pass.js";
7
+ import { paymentsWorkflowRetry } from "./retryPolicy.js";
8
+ import { paddleUsageReporter } from "../rails/paddle/usage.js";
9
+ import { stripeUsageReporter } from "../rails/stripe/usage.js";
10
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
11
+ import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
12
+ import { composedCapability } from "@pithy-sh/core/src/capability/composition";
13
+ import { classifiedSteps } from "@pithy-sh/core/src/workflow/faults";
14
+ //#region src/workflows/usage.ts
15
+ /**
16
+ * The usage-reporting Workflow's body — run by a class **the adopter's own Worker** exports, because it calls
17
+ * their `resolveQuantity` and that function exists nowhere else.
18
+ *
19
+ * // apps/api/src/index.ts, beside the `createEntrypoint` it already exports
20
+ * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
21
+ * import { NonRetryableError } from "cloudflare:workflows";
22
+ * import { reportPaymentsUsage } from "@pithy-sh/payments/src/workflows/usage";
23
+ *
24
+ * export class PaymentsUsageWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
25
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
26
+ * return reportPaymentsUsage(this.env, event, step, NonRetryableError);
27
+ * }
28
+ * }
29
+ *
30
+ * plus a `workflows` entry binding `PAYMENTS_USAGE` to that class and the spec's cron —
31
+ * `packages/payments/docs/entitlements.md` has the stanza. **The class is the adopter's, the body is the
32
+ * kit's**, which is the split every app-declared Workflow already has: Cloudflare resolves a `class_name` in
33
+ * the script that binds it, so the class must be exported from the app's own entry, and a class shipped here
34
+ * would be one more module the build reads as a Workflow host it is not.
35
+ *
36
+ * The body finds the composed payments capability the way a Workflow that sends mail finds the composed email
37
+ * one: the class is exported from the same entry that calls `createBackend`, so the composition has happened
38
+ * in this isolate, and `resolveQuantity` is on the capability, never in a config that crossed a var.
39
+ *
40
+ * One journalled step. The pass is idempotent end to end — every period has one row, claimed before the store
41
+ * is called, and the row id is the store's idempotency key — so a retried step reports nothing twice.
42
+ */
43
+ async function reportPaymentsUsage(env, event, step, terminalError) {
44
+ PaymentsUsageParams.parse(event.payload ?? {});
45
+ const log = bindWorkflowContext(createWorkerLogger({ name: "payments:usage" }), {
46
+ workflow: event.workflowName ?? "payments-usage",
47
+ instance: event.instanceId ?? "unknown",
48
+ env: typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : "unknown"
49
+ });
50
+ const payments = composedCapability("payments", isPaymentsCapability);
51
+ const usage = payments.paymentsUsage;
52
+ if (usage === void 0) {
53
+ log.warn("usage reporting has no resolver; nothing reported");
54
+ return null;
55
+ }
56
+ const config = payments.paymentsConfig;
57
+ return classifiedSteps(step, paymentsWorkflowRetry, terminalError).do("report usage", async () => {
58
+ const credentials = (await sharedSecretsStore(env, paymentsSecretsRegistry)).get(PAYMENTS_PROVIDER_SECRET);
59
+ const reporters = {};
60
+ if (credentials.stripe !== void 0) reporters.stripe = stripeUsageReporter({ secretKey: credentials.stripe.secretKey });
61
+ if (credentials.paddle !== void 0 && config.paddle !== void 0) reporters.paddle = paddleUsageReporter({
62
+ apiKey: credentials.paddle.apiKey,
63
+ environment: config.paddle.environment
64
+ });
65
+ return runUsageReport({
66
+ d1: env.DB,
67
+ config,
68
+ resolveQuantity: usage.resolveQuantity,
69
+ reporters,
70
+ env,
71
+ now: () => /* @__PURE__ */ new Date(),
72
+ log
73
+ });
74
+ });
75
+ }
76
+ //#endregion
77
+ export { reportPaymentsUsage };
@@ -10,11 +10,11 @@ import { sweepPaddle } from "./paddleSweep.js";
10
10
  import { auditLogEmit, logReconcileReport } from "./report.js";
11
11
  import { paymentsWorkflowRetry } from "./retryPolicy.js";
12
12
  import { reconcileWorkerConfig } from "./workerConfig.js";
13
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
13
14
  import { configureSharedSecrets, sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
15
+ import { classifiedSteps } from "@pithy-sh/core/src/workflow/faults";
14
16
  import { WorkflowEntrypoint } from "cloudflare:workers";
15
17
  import { NonRetryableError } from "cloudflare:workflows";
16
- import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
17
- import { classifiedSteps } from "@pithy-sh/core/src/workflow/faults";
18
18
  //#region src/workflows/worker.ts
19
19
  configureSharedSecrets({ registry: paymentsSecretsRegistry });
20
20
  /**