@pithy-sh/payments 0.3.10 → 0.5.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 (215) hide show
  1. package/README.md +11 -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 +38 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +59 -1
  16. package/dist/client/hooks.d.ts +63 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +96 -2
  19. package/dist/client/paddleLink.d.ts +31 -0
  20. package/dist/client/paddleLink.d.ts.map +1 -0
  21. package/dist/client/paddleLink.js +37 -0
  22. package/dist/client/projection.d.ts +29 -0
  23. package/dist/client/projection.d.ts.map +1 -1
  24. package/dist/config/allowances.d.ts +71 -0
  25. package/dist/config/allowances.d.ts.map +1 -0
  26. package/dist/config/allowances.js +115 -0
  27. package/dist/config/config.d.ts +155 -9
  28. package/dist/config/config.d.ts.map +1 -1
  29. package/dist/config/config.js +164 -14
  30. package/dist/data/meterCounter.d.ts +34 -0
  31. package/dist/data/meterCounter.d.ts.map +1 -0
  32. package/dist/data/meterCounter.js +33 -0
  33. package/dist/data/override.d.ts +56 -0
  34. package/dist/data/override.d.ts.map +1 -0
  35. package/dist/data/override.js +58 -0
  36. package/dist/data/paddleIds.d.ts +28 -0
  37. package/dist/data/paddleIds.d.ts.map +1 -0
  38. package/dist/data/paddleIds.js +73 -0
  39. package/dist/data/period.d.ts +10 -0
  40. package/dist/data/period.d.ts.map +1 -0
  41. package/dist/data/period.js +37 -0
  42. package/dist/data/purchase.d.ts +1 -0
  43. package/dist/data/purchase.d.ts.map +1 -1
  44. package/dist/data/purchase.js +1 -0
  45. package/dist/data/tables.d.ts +17 -1
  46. package/dist/data/tables.d.ts.map +1 -1
  47. package/dist/data/tables.js +24 -4
  48. package/dist/data/usageReport.d.ts +68 -0
  49. package/dist/data/usageReport.d.ts.map +1 -0
  50. package/dist/data/usageReport.js +55 -0
  51. package/dist/data/usageRun.d.ts +93 -0
  52. package/dist/data/usageRun.d.ts.map +1 -0
  53. package/dist/data/usageRun.js +50 -0
  54. package/dist/entitlement/allowance.d.ts +100 -0
  55. package/dist/entitlement/allowance.d.ts.map +1 -0
  56. package/dist/entitlement/allowance.js +171 -0
  57. package/dist/entitlement/manual.d.ts +5 -5
  58. package/dist/entitlement/manual.js +3 -3
  59. package/dist/entitlement/meter.d.ts +98 -0
  60. package/dist/entitlement/meter.d.ts.map +1 -0
  61. package/dist/entitlement/meter.js +177 -0
  62. package/dist/entitlement/override.d.ts +119 -0
  63. package/dist/entitlement/override.d.ts.map +1 -0
  64. package/dist/entitlement/override.js +256 -0
  65. package/dist/entitlement/resolver.d.ts +2 -1
  66. package/dist/entitlement/resolver.d.ts.map +1 -1
  67. package/dist/entitlement/resolver.js +32 -1
  68. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  69. package/dist/entitlement/unimplementedSubject.js +3 -2
  70. package/dist/error/errors.d.ts +19 -0
  71. package/dist/error/errors.d.ts.map +1 -1
  72. package/dist/error/errors.js +35 -2
  73. package/dist/http/responses.d.ts +390 -5
  74. package/dist/http/responses.d.ts.map +1 -1
  75. package/dist/http/responses.js +169 -13
  76. package/dist/http/routes.d.ts +6 -2
  77. package/dist/http/routes.d.ts.map +1 -1
  78. package/dist/http/routes.js +478 -52
  79. package/dist/http/schemas.d.ts +75 -1
  80. package/dist/http/schemas.d.ts.map +1 -1
  81. package/dist/http/schemas.js +80 -3
  82. package/dist/http/scopes.d.ts +25 -0
  83. package/dist/http/scopes.d.ts.map +1 -1
  84. package/dist/http/scopes.js +60 -1
  85. package/dist/http/view.d.ts +22 -4
  86. package/dist/http/view.d.ts.map +1 -1
  87. package/dist/http/view.js +88 -7
  88. package/dist/http/webhookGuard.d.ts.map +1 -1
  89. package/dist/http/webhookGuard.js +1 -1
  90. package/dist/index.d.ts +2 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +3 -2
  93. package/dist/migrations/0002_allowances.d.ts +26 -0
  94. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  95. package/dist/migrations/0002_allowances.js +62 -0
  96. package/dist/peer.d.ts +1 -0
  97. package/dist/peer.d.ts.map +1 -1
  98. package/dist/projection/event.d.ts +1 -0
  99. package/dist/projection/event.d.ts.map +1 -1
  100. package/dist/projection/event.js +1 -0
  101. package/dist/projection/writer.d.ts.map +1 -1
  102. package/dist/projection/writer.js +3 -1
  103. package/dist/rails/contract.d.ts +6 -0
  104. package/dist/rails/contract.d.ts.map +1 -1
  105. package/dist/rails/google/playApi.d.ts.map +1 -1
  106. package/dist/rails/google/playApi.js +2 -0
  107. package/dist/rails/paddle/events.d.ts.map +1 -1
  108. package/dist/rails/paddle/events.js +2 -1
  109. package/dist/rails/paddle/objects.d.ts +2 -0
  110. package/dist/rails/paddle/objects.d.ts.map +1 -1
  111. package/dist/rails/paddle/objects.js +7 -2
  112. package/dist/rails/paddle/refresh.d.ts +10 -5
  113. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  114. package/dist/rails/paddle/refresh.js +8 -5
  115. package/dist/rails/paddle/refund.d.ts.map +1 -1
  116. package/dist/rails/paddle/refund.js +10 -2
  117. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  118. package/dist/rails/paddle/subscription.js +8 -3
  119. package/dist/rails/paddle/usage.d.ts +11 -0
  120. package/dist/rails/paddle/usage.d.ts.map +1 -0
  121. package/dist/rails/paddle/usage.js +49 -0
  122. package/dist/rails/paddle/verify.d.ts.map +1 -1
  123. package/dist/rails/paddle/verify.js +2 -3
  124. package/dist/rails/quantity.d.ts +12 -0
  125. package/dist/rails/quantity.d.ts.map +1 -0
  126. package/dist/rails/quantity.js +16 -0
  127. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  128. package/dist/rails/stripe/checkout.js +1 -1
  129. package/dist/rails/stripe/objects.d.ts.map +1 -1
  130. package/dist/rails/stripe/objects.js +3 -0
  131. package/dist/rails/stripe/usage.d.ts +10 -0
  132. package/dist/rails/stripe/usage.d.ts.map +1 -0
  133. package/dist/rails/stripe/usage.js +49 -0
  134. package/dist/secret/registry.d.ts.map +1 -1
  135. package/dist/secret/registry.js +3 -2
  136. package/dist/usage/pass.d.ts +120 -0
  137. package/dist/usage/pass.d.ts.map +1 -0
  138. package/dist/usage/pass.js +363 -0
  139. package/dist/usage/reporter.d.ts +36 -0
  140. package/dist/usage/reporter.d.ts.map +1 -0
  141. package/dist/usage/reporter.js +2 -0
  142. package/dist/version.generated.d.ts +1 -1
  143. package/dist/version.generated.d.ts.map +1 -1
  144. package/dist/version.generated.js +1 -1
  145. package/dist/workflows/specs.d.ts +28 -0
  146. package/dist/workflows/specs.d.ts.map +1 -1
  147. package/dist/workflows/specs.js +26 -1
  148. package/dist/workflows/usage.d.ts +38 -0
  149. package/dist/workflows/usage.d.ts.map +1 -0
  150. package/dist/workflows/usage.js +77 -0
  151. package/dist/workflows/worker.js +2 -2
  152. package/dist/workflows/workerConfig.d.ts.map +1 -1
  153. package/dist/workflows/workerConfig.js +8 -2
  154. package/docs/entitlements.md +249 -0
  155. package/docs/lemon-squeezy.md +1 -0
  156. package/docs/paddle.md +18 -2
  157. package/package.json +7 -7
  158. package/pithy.manifest.json +3 -8
  159. package/src/admin/coverage.ts +28 -0
  160. package/src/admin/read.ts +173 -1
  161. package/src/audit/actions.ts +13 -0
  162. package/src/capability.ts +87 -9
  163. package/src/client/api.ts +79 -0
  164. package/src/client/hooks.ts +122 -0
  165. package/src/client/paddleLink.ts +41 -0
  166. package/src/client/projection.ts +31 -0
  167. package/src/config/allowances.ts +211 -0
  168. package/src/config/config.ts +283 -15
  169. package/src/data/meterCounter.ts +38 -0
  170. package/src/data/override.ts +74 -0
  171. package/src/data/paddleIds.ts +74 -0
  172. package/src/data/period.ts +53 -0
  173. package/src/data/purchase.ts +9 -0
  174. package/src/data/tables.ts +25 -1
  175. package/src/data/usageReport.ts +64 -0
  176. package/src/data/usageRun.ts +66 -0
  177. package/src/entitlement/allowance.ts +213 -0
  178. package/src/entitlement/manual.ts +6 -6
  179. package/src/entitlement/meter.ts +252 -0
  180. package/src/entitlement/override.ts +381 -0
  181. package/src/entitlement/resolver.ts +43 -2
  182. package/src/entitlement/unimplementedSubject.ts +3 -4
  183. package/src/error/errors.ts +44 -1
  184. package/src/http/responses.ts +338 -10
  185. package/src/http/routes.ts +1089 -460
  186. package/src/http/schemas.ts +171 -2
  187. package/src/http/scopes.ts +68 -0
  188. package/src/http/view.ts +112 -7
  189. package/src/http/webhookGuard.ts +3 -2
  190. package/src/index.ts +18 -0
  191. package/src/migrations/0002_allowances.ts +149 -0
  192. package/src/projection/event.ts +9 -0
  193. package/src/projection/writer.ts +4 -0
  194. package/src/rails/contract.ts +6 -0
  195. package/src/rails/google/playApi.ts +2 -0
  196. package/src/rails/paddle/events.ts +2 -1
  197. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  198. package/src/rails/paddle/objects.ts +6 -0
  199. package/src/rails/paddle/refresh.ts +17 -10
  200. package/src/rails/paddle/refund.ts +10 -2
  201. package/src/rails/paddle/subscription.ts +8 -3
  202. package/src/rails/paddle/usage.ts +66 -0
  203. package/src/rails/paddle/verify.ts +6 -4
  204. package/src/rails/quantity.ts +14 -0
  205. package/src/rails/stripe/checkout.ts +3 -1
  206. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  207. package/src/rails/stripe/objects.ts +4 -0
  208. package/src/rails/stripe/usage.ts +61 -0
  209. package/src/secret/registry.ts +3 -2
  210. package/src/usage/pass.ts +539 -0
  211. package/src/usage/reporter.ts +38 -0
  212. package/src/version.generated.ts +1 -1
  213. package/src/workflows/specs.ts +34 -0
  214. package/src/workflows/usage.ts +97 -0
  215. package/src/workflows/workerConfig.ts +9 -3
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import { PaymentsProviderUnavailableError } from "../../error/errors";
6
+ import type { UsageReporter, UsageReportRequest } from "../../usage/reporter";
7
+ import { type StripeHttpFetch, stripeHttpFetch, stripeJson } from "./api";
8
+
9
+ /**
10
+ * Reporting a count to Stripe: one Billing Meter event per reported period.
11
+ *
12
+ * `POST /v1/billing/meter_events` with the meter's `event_name`, the customer, the count as `value`, and the
13
+ * period's row id as `identifier` — which Stripe enforces as unique, so a report sent twice is one event. The
14
+ * subscription's metered price reads the meter, and the meter's own aggregation over the period — a setting
15
+ * on the meter in Stripe, not here — is what the invoice bills. The pass sends one event per period for both
16
+ * cadences — a `daily-peak` event carries the period's highest day — so a summing meter bills that count.
17
+ *
18
+ * The timestamp is the report's own `at`, which the pass dates inside the period it bills, so the event
19
+ * lands on that period's invoice.
20
+ */
21
+
22
+ /** What Stripe answers for a recorded meter event — as much as proves it recorded this one. */
23
+ const StripeMeterEvent = z
24
+ .object({
25
+ object: z.literal("billing.meter_event").describe("Always `billing.meter_event`."),
26
+ event_name: z.string().describe("The meter the event was recorded against."),
27
+ identifier: z.string().describe("The idempotency identifier the event was recorded under."),
28
+ })
29
+ .loose()
30
+ .describe("A Stripe Billing Meter event, as Stripe answers its creation.");
31
+
32
+ /** The Stripe reporter, over the secret key and a transport. */
33
+ export function stripeUsageReporter(options: { secretKey: string; transport?: StripeHttpFetch }): UsageReporter {
34
+ const transport = options.transport ?? stripeHttpFetch;
35
+ return {
36
+ async report(request: UsageReportRequest): Promise<void> {
37
+ const meter = request.billing.stripe?.meterEventName;
38
+ if (meter === undefined || request.providerCustomerId === undefined) {
39
+ throw new PaymentsProviderUnavailableError({
40
+ detail: `Stripe usage for ${request.providerSubscriptionId} has no ${meter === undefined ? "meter event name" : "customer"} to report against.`,
41
+ });
42
+ }
43
+ const answer = await stripeJson(transport, "/billing/meter_events", {
44
+ what: "a meter event",
45
+ secretKey: options.secretKey,
46
+ form: {
47
+ event_name: meter,
48
+ identifier: request.idempotencyKey,
49
+ timestamp: Math.floor(request.at.getTime() / 1000),
50
+ payload: { stripe_customer_id: request.providerCustomerId, value: String(request.quantity) },
51
+ },
52
+ });
53
+ const event = StripeMeterEvent.safeParse(answer);
54
+ if (!event.success || event.data.identifier !== request.idempotencyKey) {
55
+ throw new PaymentsProviderUnavailableError({
56
+ detail: `Stripe answered the meter event for ${request.providerSubscriptionId} with something that is not that event.`,
57
+ });
58
+ }
59
+ },
60
+ };
61
+ }
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { pithyCommand } from "@pithy-sh/core/src/cli/command";
4
5
  import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
5
6
  import { z } from "zod";
6
7
  import type { PaymentsRail } from "../data/rail";
@@ -289,8 +290,8 @@ export function railCredentials<R extends PaymentsRail>(
289
290
  const block = credentials[rail];
290
291
  if (!block) {
291
292
  throw new PaymentsRailNotConfiguredError({
292
- detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`pithy secrets set\` for it.`,
293
- action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`pithy secrets set ${PAYMENTS_PROVIDER_SECRET}\`.`,
293
+ detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\` for it.`,
294
+ action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\`.`,
294
295
  });
295
296
  }
296
297
  return block as NonNullable<PaymentsProviderCredentials[R]>;
@@ -0,0 +1,539 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
6
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
7
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
8
+ import { sql } from "kysely";
9
+ import { type PaymentsConfig, type PaymentsReportedBilling, reportedProducts } from "../config/config";
10
+ import { knownPeriodStart } from "../data/period";
11
+ import { PaymentsPurchase } from "../data/purchase";
12
+ import { grantingStatuses } from "../data/status";
13
+ import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
14
+ import {
15
+ PAYMENTS_PURCHASES_TABLE,
16
+ PAYMENTS_USAGE_REPORTS_TABLE,
17
+ PAYMENTS_USAGE_RUNS_TABLE,
18
+ type PaymentsDatabase,
19
+ paymentsDatabase,
20
+ } from "../data/tables";
21
+ import { PaymentsUsageReport } from "../data/usageReport";
22
+ import { MAX_USAGE_FINDINGS, PaymentsUsageRun, type UsageFinding, type UsageFindingReason } from "../data/usageRun";
23
+ import { providerAccountForSubject } from "../projection/owner";
24
+ import type { UsageReporter } from "./reporter";
25
+
26
+ /**
27
+ * The usage-reporting pass: ask the adopter how many, and tell the store.
28
+ *
29
+ * **Configuration decides what is billable and how often; a function decides the number.** The same split
30
+ * as `billingSubject` / `resolveSubject`, for the same reason — `PaymentsConfig` round-trips through JSON, so
31
+ * a function cannot live in it. `resolveQuantity` rides on the `payments(...)` options and reaches this pass
32
+ * through the composed capability, never through config.
33
+ *
34
+ * **Pulled, not pushed.** A cron walks the subscribed subjects and reports, the shape the reconcile pass
35
+ * already has. No proration, no mid-cycle rewrite of a subscription's items, and a missed report bills last
36
+ * period's number rather than the wrong number indefinitely.
37
+ *
38
+ * ## What it never does
39
+ *
40
+ * - **Report a guess.** A resolver answering `undefined` reports nothing for that subject, and is counted as
41
+ * skipped — never `0`, because a zeroed meter is a bill of nothing for a customer who owes something. A
42
+ * non-integer, a negative, or a count outside the product's `min`/`max` is skipped and named — never
43
+ * clamped, because a clamped value is a wrong number billed silently.
44
+ * - **Stop for one subject.** A resolver that throws is a failure in the tally, and the sweep goes on.
45
+ * - **Report a period twice.** One row per `(rail, subscription, period)`, claimed before the store is
46
+ * called, and the row id sent as the store's idempotency key.
47
+ * - **Read a meter.** The kit does not sell overage. What a kit meter counted is never a billable number,
48
+ * and nothing here imports one.
49
+ *
50
+ * ## The two cadences
51
+ *
52
+ * - `period-end` — one report per subscription per billing period, keyed on the period's end and sent on
53
+ * the first run inside its last {@link PERIOD_END_WINDOW_MS}, dated at that run. Every later run in the
54
+ * period finds the row.
55
+ * - `daily-peak` — every run asks, and the day's row keeps the highest answer; a lower later answer never
56
+ * lowers it. **A day is never sent on its own.** The period's report is the highest of its days, sent once,
57
+ * in the period's last {@link PERIOD_END_WINDOW_MS} — keyed and dated exactly as a `period-end` report.
58
+ * Both stores add up what they are sent: Stripe's meter sums its events, and every Paddle charge is a line
59
+ * on the bill. A report per day would bill the sum of thirty daily peaks, not the period's peak. The day
60
+ * rows stay behind, and they are the audit: the number billed is the largest of them up to the report.
61
+ *
62
+ * A `daily-peak` report goes out when the last day opens, as a `period-end` one does, so a peak reached in
63
+ * the period's final hours after it was sent is not billed. Under-billing an hour is the right way round.
64
+ */
65
+
66
+ /** How close to a period's end a `period-end` report goes out. A day, so an hourly or daily cron lands inside it. */
67
+ export const PERIOD_END_WINDOW_MS = 86_400_000;
68
+
69
+ /** How long after a period's end its subscription is still reported — a run that missed the window by a little. */
70
+ const LATE_WINDOW_MS = 86_400_000;
71
+
72
+ /** What `resolveQuantity` is told besides who: the env, the product, and when. */
73
+ export interface PaymentsQuantityContext {
74
+ /** The worker env — the adopter's bindings, for counting their own rows. */
75
+ env: Record<string, unknown>;
76
+ /** The quantity-billed product being reported. */
77
+ productId: string;
78
+ /** What one unit is, from the product's `billing.unit`. */
79
+ unit: string;
80
+ /** The run's clock. */
81
+ now: Date;
82
+ }
83
+
84
+ /**
85
+ * The adopter's count for one subject — students, coaches, seats. `undefined` reports nothing this period.
86
+ *
87
+ * Called with no request: the pass runs on a schedule. So it is handed the env, not a Hono context, and counts
88
+ * from the adopter's own rows. Payments never counts members.
89
+ */
90
+ export type PaymentsQuantityResolver = (
91
+ context: PaymentsQuantityContext,
92
+ subject: PaymentsSubject,
93
+ ) => Promise<number | undefined>;
94
+
95
+ /** What one pass needs. */
96
+ export interface UsagePassDeps {
97
+ /** The app database. */
98
+ d1: D1Database;
99
+ /** The resolved config. */
100
+ config: PaymentsConfig;
101
+ /** The adopter's resolver. */
102
+ resolveQuantity: PaymentsQuantityResolver;
103
+ /** One reporter per rail this pass may report on. A rail with none is counted as a failure per period. */
104
+ reporters: Partial<Record<"stripe" | "paddle", UsageReporter>>;
105
+ /** The env handed to the resolver. */
106
+ env: Record<string, unknown>;
107
+ /** The clock. */
108
+ now: () => Date;
109
+ /** Where every skip and failure is logged. */
110
+ log: Logger;
111
+ /** The id minter. Defaults to `crypto.randomUUID`. */
112
+ newId?: () => string;
113
+ }
114
+
115
+ /** The tally one pass records. */
116
+ export interface UsagePassTally {
117
+ /** The run's id. */
118
+ id: string;
119
+ /** Subscriptions examined. */
120
+ scanned: number;
121
+ /** Periods a store accepted. */
122
+ reported: number;
123
+ /** Daily-peak samples taken. */
124
+ sampled: number;
125
+ /** Periods found already reported, so nothing was sent. */
126
+ alreadyReported: number;
127
+ /** Subjects whose resolver answered nothing. */
128
+ skipped: number;
129
+ /** Subjects whose resolver answered a number that may not be billed. */
130
+ invalid: number;
131
+ /** Subjects whose resolver threw, or whose report a store refused. */
132
+ failed: number;
133
+ /** The subjects not reported, and why, up to {@link MAX_USAGE_FINDINGS}. */
134
+ findings: UsageFinding[];
135
+ }
136
+
137
+ /** One subscription's current period, as the purchases table holds it. */
138
+ interface CurrentPeriod {
139
+ purchase: PaymentsPurchase;
140
+ providerSubscriptionId: string;
141
+ periodEnd: Date;
142
+ }
143
+
144
+ /** Whether a resolver's answer may be billed, and if not, why. */
145
+ export function judgeQuantity(
146
+ answer: unknown,
147
+ billing: Pick<PaymentsReportedBilling, "min" | "max">,
148
+ ): { ok: true; quantity: number } | { ok: false; reason: UsageFindingReason } {
149
+ if (answer === undefined) return { ok: false, reason: "unanswered" };
150
+ if (typeof answer !== "number" || !Number.isInteger(answer)) return { ok: false, reason: "not_integer" };
151
+ if (answer < 0) return { ok: false, reason: "negative" };
152
+ if (answer < billing.min) return { ok: false, reason: "below_min" };
153
+ if (answer > billing.max) return { ok: false, reason: "above_max" };
154
+ return { ok: true, quantity: answer };
155
+ }
156
+
157
+ /** The UTC day `at` falls in, as `YYYY-MM-DD`. A `daily-peak` period's key. */
158
+ export function utcDay(at: Date): string {
159
+ return at.toISOString().slice(0, 10);
160
+ }
161
+
162
+ /**
163
+ * Every subscription of one product on one rail whose current period is live, or ended within the late
164
+ * window — newest period per subscription, because each billing period is its own purchase row.
165
+ */
166
+ async function currentPeriods(
167
+ db: PaymentsDatabase,
168
+ config: PaymentsConfig,
169
+ productId: string,
170
+ rail: "stripe" | "paddle",
171
+ now: Date,
172
+ ): Promise<CurrentPeriod[]> {
173
+ const at = now.getTime();
174
+ const rows = await db
175
+ .selectFrom(PAYMENTS_PURCHASES_TABLE)
176
+ .selectAll()
177
+ .where("productId", "=", productId)
178
+ .where("rail", "=", rail)
179
+ .where("type", "=", "subscription")
180
+ .where("status", "in", grantingStatuses(config.graceGrantsAccess))
181
+ // biome-ignore lint/suspicious/noExplicitAny: ms-epoch numbers against the encoded columns.
182
+ .where("purchasedAt", "<=", at as any)
183
+ // biome-ignore lint/suspicious/noExplicitAny: as above.
184
+ .where("expiresAt", ">", (at - LATE_WINDOW_MS) as any)
185
+ .orderBy("purchasedAt", "desc")
186
+ .execute();
187
+ const newest = new Map<string, CurrentPeriod>();
188
+ for (const row of rows) {
189
+ const purchase = PaymentsPurchase.parse(row);
190
+ const subscription = purchase.originalTransactionId;
191
+ if (subscription === null || purchase.expiresAt === null || newest.has(subscription)) continue;
192
+ newest.set(subscription, {
193
+ purchase,
194
+ providerSubscriptionId: subscription,
195
+ periodEnd: purchase.expiresAt,
196
+ });
197
+ }
198
+ return [...newest.values()];
199
+ }
200
+
201
+ /** One period's row, if there is one. */
202
+ async function readReport(
203
+ db: PaymentsDatabase,
204
+ rail: string,
205
+ subscription: string,
206
+ period: string,
207
+ ): Promise<PaymentsUsageReport | undefined> {
208
+ const row = await db
209
+ .selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
210
+ .selectAll()
211
+ .where("rail", "=", rail as "stripe")
212
+ .where("providerSubscriptionId", "=", subscription)
213
+ .where("period", "=", period)
214
+ .executeTakeFirst();
215
+ return row === undefined ? undefined : PaymentsUsageReport.parse(row);
216
+ }
217
+
218
+ /** Run one pass, record its tally, and return it. */
219
+ export async function runUsageReport(deps: UsagePassDeps): Promise<UsagePassTally> {
220
+ const db = paymentsDatabase(deps.d1);
221
+ const newId = deps.newId ?? (() => crypto.randomUUID());
222
+ const startedAt = deps.now();
223
+ const tally: UsagePassTally = {
224
+ id: newId(),
225
+ scanned: 0,
226
+ reported: 0,
227
+ sampled: 0,
228
+ alreadyReported: 0,
229
+ skipped: 0,
230
+ invalid: 0,
231
+ failed: 0,
232
+ findings: [],
233
+ };
234
+
235
+ const note = (subject: PaymentsSubject, productId: string, reason: UsageFindingReason): void => {
236
+ if (reason === "unanswered") tally.skipped++;
237
+ else if (reason === "resolver_failed" || reason === "report_failed") tally.failed++;
238
+ else tally.invalid++;
239
+ if (tally.findings.length < MAX_USAGE_FINDINGS) tally.findings.push({ ...subject, productId, reason });
240
+ deps.log.warn("usage not reported", { subject: encodeSubjectReference(subject), productId, reason });
241
+ };
242
+
243
+ /** Ask the resolver, and judge the answer. Undefined when nothing may be billed — already noted. */
244
+ const ask = async (period: CurrentPeriod, productId: string, billing: PaymentsReportedBilling, now: Date) => {
245
+ const subject: PaymentsSubject = { subjectType: period.purchase.subjectType, subjectId: period.purchase.subjectId };
246
+ let answer: unknown;
247
+ try {
248
+ answer = await deps.resolveQuantity({ env: deps.env, productId, unit: billing.unit, now }, subject);
249
+ } catch (error) {
250
+ deps.log.error("usage resolver failed", {
251
+ subject: encodeSubjectReference(subject),
252
+ productId,
253
+ cause: messageOf(error),
254
+ });
255
+ note(subject, productId, "resolver_failed");
256
+ return undefined;
257
+ }
258
+ const judged = judgeQuantity(answer, billing);
259
+ if (!judged.ok) {
260
+ note(subject, productId, judged.reason);
261
+ return undefined;
262
+ }
263
+ return judged.quantity;
264
+ };
265
+
266
+ /** Send one claimed row to its store, and settle the row either way. */
267
+ const send = async (
268
+ period: CurrentPeriod,
269
+ productId: string,
270
+ billing: PaymentsReportedBilling,
271
+ report: PaymentsUsageReport,
272
+ at: Date,
273
+ ): Promise<void> => {
274
+ const rail = period.purchase.rail as "stripe" | "paddle";
275
+ const subject: PaymentsSubject = { subjectType: period.purchase.subjectType, subjectId: period.purchase.subjectId };
276
+ const reporter = deps.reporters[rail];
277
+ try {
278
+ if (reporter === undefined) throw new Error(`no ${rail} reporter is configured for this pass`);
279
+ await reporter.report({
280
+ providerSubscriptionId: period.providerSubscriptionId,
281
+ providerCustomerId: rail === "stripe" ? await providerAccountForSubject(db, "stripe", subject) : undefined,
282
+ quantity: report.quantity,
283
+ period: report.period,
284
+ at,
285
+ billing,
286
+ idempotencyKey: `usage_${report.id}`,
287
+ });
288
+ } catch (error) {
289
+ deps.log.error("usage report failed", {
290
+ subject: encodeSubjectReference(subject),
291
+ productId,
292
+ rail,
293
+ period: report.period,
294
+ cause: messageOf(error),
295
+ });
296
+ // Left claimed, so the next run sends it again under the same key. The failure may have been the
297
+ // answer going missing rather than the call, and the store records one key once.
298
+ note(subject, productId, "report_failed");
299
+ return;
300
+ }
301
+ const now = deps.now().getTime();
302
+ await withD1Retry(() =>
303
+ db
304
+ .updateTable(PAYMENTS_USAGE_REPORTS_TABLE)
305
+ // biome-ignore lint/suspicious/noExplicitAny: the SQLite row shape.
306
+ .set({ status: "reported", reportedAt: now, updatedAt: now } as any)
307
+ .where("id", "=", report.id)
308
+ .execute(),
309
+ );
310
+ tally.reported++;
311
+ };
312
+
313
+ for (const { id: productId, billing } of reportedProducts(deps.config)) {
314
+ for (const rail of billing.rails) {
315
+ if (rail !== "stripe" && rail !== "paddle") continue;
316
+ const now = deps.now();
317
+ for (const period of await currentPeriods(db, deps.config, productId, rail, now)) {
318
+ tally.scanned++;
319
+ if (billing.cadence === "period-end") {
320
+ await periodEnd(period, productId, billing, now);
321
+ } else {
322
+ await dailyPeak(period, productId, billing, now);
323
+ }
324
+ }
325
+ }
326
+ }
327
+
328
+ /** `period-end`: inside the window, once per period. */
329
+ async function periodEnd(
330
+ period: CurrentPeriod,
331
+ productId: string,
332
+ billing: PaymentsReportedBilling,
333
+ now: Date,
334
+ ): Promise<void> {
335
+ if (now.getTime() < period.periodEnd.getTime() - PERIOD_END_WINDOW_MS) return;
336
+ // Keyed on the period's end, which every rail's row states and every renewal moves — where the start is
337
+ // a column only some rails keep current (`data/period.ts`).
338
+ const key = period.periodEnd.toISOString();
339
+ const existing = await readReport(db, period.purchase.rail, period.providerSubscriptionId, key);
340
+ if (existing?.status === "reported") {
341
+ tally.alreadyReported++;
342
+ return;
343
+ }
344
+ // A claim left by a run that died between the store's answer and ours: send it again, under its own key.
345
+ if (existing?.status === "claimed") {
346
+ await send(period, productId, billing, existing, reportDate(period, now));
347
+ return;
348
+ }
349
+ const quantity = await ask(period, productId, billing, now);
350
+ if (quantity === undefined) return;
351
+ const claimed = await claim(period, productId, billing, key, quantity, now, "claimed");
352
+ if (claimed === undefined) {
353
+ tally.alreadyReported++;
354
+ return;
355
+ }
356
+ await send(period, productId, billing, claimed, reportDate(period, now));
357
+ }
358
+
359
+ /**
360
+ * `daily-peak`: sample today, and in the period's last day report the highest day the period sampled.
361
+ * Once per period, keyed on its end — the same row, key and date a `period-end` report has.
362
+ */
363
+ async function dailyPeak(
364
+ period: CurrentPeriod,
365
+ productId: string,
366
+ billing: PaymentsReportedBilling,
367
+ now: Date,
368
+ ): Promise<void> {
369
+ if (now.getTime() < period.periodEnd.getTime()) {
370
+ const quantity = await ask(period, productId, billing, now);
371
+ if (quantity !== undefined) {
372
+ await sample(period, productId, billing, utcDay(now), quantity, now);
373
+ tally.sampled++;
374
+ }
375
+ }
376
+ if (now.getTime() < period.periodEnd.getTime() - PERIOD_END_WINDOW_MS) return;
377
+ const key = period.periodEnd.toISOString();
378
+ const existing = await readReport(db, period.purchase.rail, period.providerSubscriptionId, key);
379
+ if (existing?.status === "reported") {
380
+ tally.alreadyReported++;
381
+ return;
382
+ }
383
+ if (existing?.status === "claimed") {
384
+ await send(period, productId, billing, existing, reportDate(period, now));
385
+ return;
386
+ }
387
+ // No day answered: the resolver's refusals were each noted when it was asked, and nothing is a guess.
388
+ const peak = await periodPeak(period, key);
389
+ if (peak === undefined) return;
390
+ const claimed = await claim(period, productId, billing, key, peak, now, "claimed");
391
+ if (claimed === undefined) {
392
+ tally.alreadyReported++;
393
+ return;
394
+ }
395
+ await send(period, productId, billing, claimed, reportDate(period, now));
396
+ }
397
+
398
+ /**
399
+ * The highest day one period sampled, or undefined when it sampled none.
400
+ *
401
+ * **A period's days are the ones after the previous period's.** The lower bound is the later of the
402
+ * period's start, where the row states one (`data/period.ts`), and the day the subscription's previous
403
+ * report was keyed on — so a high day last period is never billed again this one, on a rail whose start
404
+ * is not stored too. The day a renewal falls on belongs to both: its peak was reached in one of them.
405
+ */
406
+ async function periodPeak(period: CurrentPeriod, key: string): Promise<number | undefined> {
407
+ const rail = period.purchase.rail as "stripe";
408
+ const previous = await db
409
+ .selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
410
+ .select("period")
411
+ .where("rail", "=", rail)
412
+ .where("providerSubscriptionId", "=", period.providerSubscriptionId)
413
+ // A period's report is the only row that is ever claimed or reported; a day only ever samples.
414
+ .where("status", "in", ["claimed", "reported"])
415
+ .where("period", "<", key)
416
+ .orderBy("period", "desc")
417
+ .limit(1)
418
+ .executeTakeFirst();
419
+ const bounds = [knownPeriodStart(period.purchase), previous && new Date(previous.period)]
420
+ .filter((at): at is Date => at instanceof Date && !Number.isNaN(at.getTime()))
421
+ .map(utcDay);
422
+ let days = db
423
+ .selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
424
+ .select((eb) => eb.fn.max<number | null>("quantity").as("peak"))
425
+ .where("rail", "=", rail)
426
+ .where("providerSubscriptionId", "=", period.providerSubscriptionId)
427
+ .where("status", "=", "sampling")
428
+ .where("period", "<=", utcDay(period.periodEnd));
429
+ const from = bounds.sort().at(-1);
430
+ if (from !== undefined) days = days.where("period", ">=", from);
431
+ const row = await days.executeTakeFirst();
432
+ return row?.peak ?? undefined;
433
+ }
434
+
435
+ /** Write a period's row as claimed or sampling, or nothing when a row for it exists. */
436
+ async function claim(
437
+ period: CurrentPeriod,
438
+ productId: string,
439
+ billing: PaymentsReportedBilling,
440
+ key: string,
441
+ quantity: number,
442
+ now: Date,
443
+ status: "claimed" | "sampling",
444
+ ): Promise<PaymentsUsageReport | undefined> {
445
+ const record = PaymentsUsageReport.encode({
446
+ id: newId(),
447
+ rail: period.purchase.rail,
448
+ providerSubscriptionId: period.providerSubscriptionId,
449
+ purchaseId: period.purchase.id,
450
+ productId,
451
+ subjectType: period.purchase.subjectType,
452
+ subjectId: period.purchase.subjectId,
453
+ cadence: billing.cadence,
454
+ period: key,
455
+ quantity,
456
+ status,
457
+ sampledAt: now,
458
+ reportedAt: null,
459
+ createdAt: now,
460
+ updatedAt: now,
461
+ });
462
+ const inserted = await db
463
+ .insertInto(PAYMENTS_USAGE_REPORTS_TABLE)
464
+ // biome-ignore lint/suspicious/noExplicitAny: the SQLite row shape.
465
+ .values(record as any)
466
+ .onConflict((oc) => oc.columns(["rail", "providerSubscriptionId", "period"]).doNothing())
467
+ .returning("id")
468
+ .executeTakeFirst();
469
+ if (inserted === undefined) return undefined;
470
+ return PaymentsUsageReport.parse(record);
471
+ }
472
+
473
+ /** Record a day's sample: the first of the day inserts, every later one keeps the higher. */
474
+ async function sample(
475
+ period: CurrentPeriod,
476
+ productId: string,
477
+ billing: PaymentsReportedBilling,
478
+ day: string,
479
+ quantity: number,
480
+ now: Date,
481
+ ): Promise<void> {
482
+ const created = await claim(period, productId, billing, day, quantity, now, "sampling");
483
+ if (created !== undefined) return;
484
+ // The higher of the stored peak and this answer, inside the statement — two samples racing cannot lower it.
485
+ const peak = {
486
+ quantity: sql`max(${sql.ref("quantity")}, ${quantity})`,
487
+ sampledAt: now.getTime(),
488
+ updatedAt: now.getTime(),
489
+ };
490
+ await db
491
+ .updateTable(PAYMENTS_USAGE_REPORTS_TABLE)
492
+ // biome-ignore lint/suspicious/noExplicitAny: an expression and two encoded timestamps.
493
+ .set(peak as any)
494
+ .where("rail", "=", period.purchase.rail as "stripe")
495
+ .where("providerSubscriptionId", "=", period.providerSubscriptionId)
496
+ .where("period", "=", day)
497
+ .where("status", "=", "sampling")
498
+ .execute();
499
+ }
500
+
501
+ const finishedAt = deps.now();
502
+ const run = PaymentsUsageRun.encode({
503
+ id: tally.id,
504
+ startedAt,
505
+ finishedAt,
506
+ scanned: tally.scanned,
507
+ reported: tally.reported,
508
+ sampled: tally.sampled,
509
+ alreadyReported: tally.alreadyReported,
510
+ skipped: tally.skipped,
511
+ invalid: tally.invalid,
512
+ failed: tally.failed,
513
+ findings: tally.findings,
514
+ createdAt: finishedAt,
515
+ });
516
+ await withD1Retry(() =>
517
+ db
518
+ .insertInto(PAYMENTS_USAGE_RUNS_TABLE)
519
+ // biome-ignore lint/suspicious/noExplicitAny: the row is the schema's z.input side; Kysely's insert type derives from it.
520
+ .values(run as any)
521
+ .execute(),
522
+ );
523
+ deps.log.info("usage report finished", {
524
+ run: tally.id,
525
+ scanned: tally.scanned,
526
+ reported: tally.reported,
527
+ sampled: tally.sampled,
528
+ alreadyReported: tally.alreadyReported,
529
+ skipped: tally.skipped,
530
+ invalid: tally.invalid,
531
+ failed: tally.failed,
532
+ });
533
+ return tally;
534
+ }
535
+
536
+ /** A `period-end` report's date: the run's own, but never past the period's end — it bills that period. */
537
+ function reportDate(period: CurrentPeriod, now: Date): Date {
538
+ return now.getTime() < period.periodEnd.getTime() ? now : new Date(period.periodEnd.getTime() - 1000);
539
+ }
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PaymentsReportedBilling } from "../config/config";
5
+
6
+ /**
7
+ * What a store is told about one reported period, and the one method a rail implements to tell it.
8
+ *
9
+ * **Every report carries an idempotency key, and both stores honor one.** Stripe dedupes a meter event by its
10
+ * `identifier`; Paddle dedupes a write by its `Paddle-Idempotency-Key`. The key is the period's own row id, so
11
+ * a run that crashed after the store answered and before the row said so sends the same key again, and the
12
+ * store records the period once. That is what lets a claimed period be retried rather than abandoned.
13
+ *
14
+ * **The quantity is the adopter's.** It is the number `resolveQuantity` answered, validated against the
15
+ * product's `min` and `max`. Nothing a kit meter counted ever reaches this type.
16
+ */
17
+ export interface UsageReportRequest {
18
+ /** The subscription at the store — `sub_…`. */
19
+ providerSubscriptionId: string;
20
+ /** The store's customer for this subscription — Stripe's `cus_…` — when the rail needs one. */
21
+ providerCustomerId: string | undefined;
22
+ /** The count. A whole number inside the product's bounds. */
23
+ quantity: number;
24
+ /** Which period this is, as the row keys it. */
25
+ period: string;
26
+ /** The instant the report is dated — inside the period it bills. */
27
+ at: Date;
28
+ /** The product's reported billing — the meter it feeds, the price it charges. */
29
+ billing: PaymentsReportedBilling;
30
+ /** Sent to the store so a repeated report is recorded once. */
31
+ idempotencyKey: string;
32
+ }
33
+
34
+ /** One rail's half of reporting. Throws when the store did not accept the report. */
35
+ export interface UsageReporter {
36
+ /** Tell the store. Resolves when it accepted; throws when it did not. */
37
+ report(request: UsageReportRequest): Promise<void>;
38
+ }
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/payments";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.3.10";
16
+ export const PACKAGE_VERSION = "0.5.0";