@pithy-sh/payments 0.4.0 → 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.
- package/README.md +10 -3
- package/dist/admin/coverage.d.ts.map +1 -1
- package/dist/admin/coverage.js +26 -2
- package/dist/admin/read.d.ts +48 -1
- package/dist/admin/read.d.ts.map +1 -1
- package/dist/admin/read.js +89 -2
- package/dist/audit/actions.d.ts +13 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +14 -1
- package/dist/capability.d.ts +33 -2
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +52 -9
- package/dist/client/api.d.ts +19 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +34 -1
- package/dist/client/hooks.d.ts +20 -1
- package/dist/client/hooks.d.ts.map +1 -1
- package/dist/client/hooks.js +40 -2
- package/dist/client/projection.d.ts +29 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/config/allowances.d.ts +71 -0
- package/dist/config/allowances.d.ts.map +1 -0
- package/dist/config/allowances.js +115 -0
- package/dist/config/config.d.ts +155 -9
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js +164 -14
- package/dist/data/meterCounter.d.ts +34 -0
- package/dist/data/meterCounter.d.ts.map +1 -0
- package/dist/data/meterCounter.js +33 -0
- package/dist/data/override.d.ts +56 -0
- package/dist/data/override.d.ts.map +1 -0
- package/dist/data/override.js +58 -0
- package/dist/data/period.d.ts +10 -0
- package/dist/data/period.d.ts.map +1 -0
- package/dist/data/period.js +37 -0
- package/dist/data/purchase.d.ts +1 -0
- package/dist/data/purchase.d.ts.map +1 -1
- package/dist/data/purchase.js +1 -0
- package/dist/data/tables.d.ts +17 -1
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +24 -4
- package/dist/data/usageReport.d.ts +68 -0
- package/dist/data/usageReport.d.ts.map +1 -0
- package/dist/data/usageReport.js +55 -0
- package/dist/data/usageRun.d.ts +93 -0
- package/dist/data/usageRun.d.ts.map +1 -0
- package/dist/data/usageRun.js +50 -0
- package/dist/entitlement/allowance.d.ts +100 -0
- package/dist/entitlement/allowance.d.ts.map +1 -0
- package/dist/entitlement/allowance.js +171 -0
- package/dist/entitlement/manual.d.ts +5 -5
- package/dist/entitlement/manual.js +3 -3
- package/dist/entitlement/meter.d.ts +98 -0
- package/dist/entitlement/meter.d.ts.map +1 -0
- package/dist/entitlement/meter.js +177 -0
- package/dist/entitlement/override.d.ts +119 -0
- package/dist/entitlement/override.d.ts.map +1 -0
- package/dist/entitlement/override.js +256 -0
- package/dist/entitlement/resolver.d.ts +2 -1
- package/dist/entitlement/resolver.d.ts.map +1 -1
- package/dist/entitlement/resolver.js +32 -1
- package/dist/error/errors.d.ts +19 -0
- package/dist/error/errors.d.ts.map +1 -1
- package/dist/error/errors.js +35 -2
- package/dist/http/responses.d.ts +367 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +146 -7
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +270 -16
- package/dist/http/schemas.d.ts +54 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +61 -2
- package/dist/http/scopes.d.ts +25 -0
- package/dist/http/scopes.d.ts.map +1 -1
- package/dist/http/scopes.js +60 -1
- package/dist/http/view.d.ts +22 -4
- package/dist/http/view.d.ts.map +1 -1
- package/dist/http/view.js +88 -7
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/migrations/0002_allowances.d.ts +26 -0
- package/dist/migrations/0002_allowances.d.ts.map +1 -0
- package/dist/migrations/0002_allowances.js +62 -0
- package/dist/peer.d.ts +1 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/projection/event.d.ts +1 -0
- package/dist/projection/event.d.ts.map +1 -1
- package/dist/projection/event.js +1 -0
- package/dist/projection/writer.d.ts.map +1 -1
- package/dist/projection/writer.js +3 -1
- package/dist/rails/contract.d.ts +6 -0
- package/dist/rails/contract.d.ts.map +1 -1
- package/dist/rails/google/playApi.d.ts.map +1 -1
- package/dist/rails/google/playApi.js +2 -0
- package/dist/rails/paddle/objects.d.ts +2 -0
- package/dist/rails/paddle/objects.d.ts.map +1 -1
- package/dist/rails/paddle/objects.js +7 -2
- package/dist/rails/paddle/usage.d.ts +11 -0
- package/dist/rails/paddle/usage.d.ts.map +1 -0
- package/dist/rails/paddle/usage.js +49 -0
- package/dist/rails/quantity.d.ts +12 -0
- package/dist/rails/quantity.d.ts.map +1 -0
- package/dist/rails/quantity.js +16 -0
- package/dist/rails/stripe/checkout.d.ts.map +1 -1
- package/dist/rails/stripe/checkout.js +1 -1
- package/dist/rails/stripe/objects.d.ts.map +1 -1
- package/dist/rails/stripe/objects.js +3 -0
- package/dist/rails/stripe/usage.d.ts +10 -0
- package/dist/rails/stripe/usage.d.ts.map +1 -0
- package/dist/rails/stripe/usage.js +49 -0
- package/dist/usage/pass.d.ts +120 -0
- package/dist/usage/pass.d.ts.map +1 -0
- package/dist/usage/pass.js +363 -0
- package/dist/usage/reporter.d.ts +36 -0
- package/dist/usage/reporter.d.ts.map +1 -0
- package/dist/usage/reporter.js +2 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/dist/workflows/specs.d.ts +28 -0
- package/dist/workflows/specs.d.ts.map +1 -1
- package/dist/workflows/specs.js +26 -1
- package/dist/workflows/usage.d.ts +38 -0
- package/dist/workflows/usage.d.ts.map +1 -0
- package/dist/workflows/usage.js +77 -0
- package/dist/workflows/worker.js +2 -2
- package/docs/entitlements.md +249 -0
- package/docs/lemon-squeezy.md +1 -0
- package/docs/paddle.md +1 -0
- package/package.json +5 -5
- package/pithy.manifest.json +3 -8
- package/src/admin/coverage.ts +28 -0
- package/src/admin/read.ts +173 -1
- package/src/audit/actions.ts +13 -0
- package/src/capability.ts +87 -9
- package/src/client/api.ts +44 -0
- package/src/client/hooks.ts +44 -0
- package/src/client/projection.ts +31 -0
- package/src/config/allowances.ts +211 -0
- package/src/config/config.ts +283 -15
- package/src/data/meterCounter.ts +38 -0
- package/src/data/override.ts +74 -0
- package/src/data/period.ts +53 -0
- package/src/data/purchase.ts +9 -0
- package/src/data/tables.ts +25 -1
- package/src/data/usageReport.ts +64 -0
- package/src/data/usageRun.ts +66 -0
- package/src/entitlement/allowance.ts +213 -0
- package/src/entitlement/manual.ts +6 -6
- package/src/entitlement/meter.ts +252 -0
- package/src/entitlement/override.ts +381 -0
- package/src/entitlement/resolver.ts +43 -2
- package/src/error/errors.ts +44 -1
- package/src/http/responses.ts +305 -4
- package/src/http/routes.ts +365 -11
- package/src/http/schemas.ts +139 -1
- package/src/http/scopes.ts +68 -0
- package/src/http/view.ts +112 -7
- package/src/index.ts +18 -0
- package/src/migrations/0002_allowances.ts +149 -0
- package/src/projection/event.ts +9 -0
- package/src/projection/writer.ts +4 -0
- package/src/rails/contract.ts +6 -0
- package/src/rails/google/playApi.ts +2 -0
- package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
- package/src/rails/paddle/objects.ts +6 -0
- package/src/rails/paddle/usage.ts +66 -0
- package/src/rails/quantity.ts +14 -0
- package/src/rails/stripe/checkout.ts +3 -1
- package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
- package/src/rails/stripe/objects.ts +4 -0
- package/src/rails/stripe/usage.ts +61 -0
- package/src/usage/pass.ts +539 -0
- package/src/usage/reporter.ts +38 -0
- package/src/version.generated.ts +1 -1
- package/src/workflows/specs.ts +34 -0
- package/src/workflows/usage.ts +97 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
4
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
5
|
+
import { type PaymentsConfig, type PaymentsReportedBilling } from "../config/config";
|
|
6
|
+
import { type PaymentsSubject } from "../data/subject";
|
|
7
|
+
import { type UsageFinding, type UsageFindingReason } from "../data/usageRun";
|
|
8
|
+
import type { UsageReporter } from "./reporter";
|
|
9
|
+
/**
|
|
10
|
+
* The usage-reporting pass: ask the adopter how many, and tell the store.
|
|
11
|
+
*
|
|
12
|
+
* **Configuration decides what is billable and how often; a function decides the number.** The same split
|
|
13
|
+
* as `billingSubject` / `resolveSubject`, for the same reason — `PaymentsConfig` round-trips through JSON, so
|
|
14
|
+
* a function cannot live in it. `resolveQuantity` rides on the `payments(...)` options and reaches this pass
|
|
15
|
+
* through the composed capability, never through config.
|
|
16
|
+
*
|
|
17
|
+
* **Pulled, not pushed.** A cron walks the subscribed subjects and reports, the shape the reconcile pass
|
|
18
|
+
* already has. No proration, no mid-cycle rewrite of a subscription's items, and a missed report bills last
|
|
19
|
+
* period's number rather than the wrong number indefinitely.
|
|
20
|
+
*
|
|
21
|
+
* ## What it never does
|
|
22
|
+
*
|
|
23
|
+
* - **Report a guess.** A resolver answering `undefined` reports nothing for that subject, and is counted as
|
|
24
|
+
* skipped — never `0`, because a zeroed meter is a bill of nothing for a customer who owes something. A
|
|
25
|
+
* non-integer, a negative, or a count outside the product's `min`/`max` is skipped and named — never
|
|
26
|
+
* clamped, because a clamped value is a wrong number billed silently.
|
|
27
|
+
* - **Stop for one subject.** A resolver that throws is a failure in the tally, and the sweep goes on.
|
|
28
|
+
* - **Report a period twice.** One row per `(rail, subscription, period)`, claimed before the store is
|
|
29
|
+
* called, and the row id sent as the store's idempotency key.
|
|
30
|
+
* - **Read a meter.** The kit does not sell overage. What a kit meter counted is never a billable number,
|
|
31
|
+
* and nothing here imports one.
|
|
32
|
+
*
|
|
33
|
+
* ## The two cadences
|
|
34
|
+
*
|
|
35
|
+
* - `period-end` — one report per subscription per billing period, keyed on the period's end and sent on
|
|
36
|
+
* the first run inside its last {@link PERIOD_END_WINDOW_MS}, dated at that run. Every later run in the
|
|
37
|
+
* period finds the row.
|
|
38
|
+
* - `daily-peak` — every run asks, and the day's row keeps the highest answer; a lower later answer never
|
|
39
|
+
* lowers it. **A day is never sent on its own.** The period's report is the highest of its days, sent once,
|
|
40
|
+
* in the period's last {@link PERIOD_END_WINDOW_MS} — keyed and dated exactly as a `period-end` report.
|
|
41
|
+
* Both stores add up what they are sent: Stripe's meter sums its events, and every Paddle charge is a line
|
|
42
|
+
* on the bill. A report per day would bill the sum of thirty daily peaks, not the period's peak. The day
|
|
43
|
+
* rows stay behind, and they are the audit: the number billed is the largest of them up to the report.
|
|
44
|
+
*
|
|
45
|
+
* A `daily-peak` report goes out when the last day opens, as a `period-end` one does, so a peak reached in
|
|
46
|
+
* the period's final hours after it was sent is not billed. Under-billing an hour is the right way round.
|
|
47
|
+
*/
|
|
48
|
+
/** How close to a period's end a `period-end` report goes out. A day, so an hourly or daily cron lands inside it. */
|
|
49
|
+
export declare const PERIOD_END_WINDOW_MS = 86400000;
|
|
50
|
+
/** What `resolveQuantity` is told besides who: the env, the product, and when. */
|
|
51
|
+
export interface PaymentsQuantityContext {
|
|
52
|
+
/** The worker env — the adopter's bindings, for counting their own rows. */
|
|
53
|
+
env: Record<string, unknown>;
|
|
54
|
+
/** The quantity-billed product being reported. */
|
|
55
|
+
productId: string;
|
|
56
|
+
/** What one unit is, from the product's `billing.unit`. */
|
|
57
|
+
unit: string;
|
|
58
|
+
/** The run's clock. */
|
|
59
|
+
now: Date;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The adopter's count for one subject — students, coaches, seats. `undefined` reports nothing this period.
|
|
63
|
+
*
|
|
64
|
+
* Called with no request: the pass runs on a schedule. So it is handed the env, not a Hono context, and counts
|
|
65
|
+
* from the adopter's own rows. Payments never counts members.
|
|
66
|
+
*/
|
|
67
|
+
export type PaymentsQuantityResolver = (context: PaymentsQuantityContext, subject: PaymentsSubject) => Promise<number | undefined>;
|
|
68
|
+
/** What one pass needs. */
|
|
69
|
+
export interface UsagePassDeps {
|
|
70
|
+
/** The app database. */
|
|
71
|
+
d1: D1Database;
|
|
72
|
+
/** The resolved config. */
|
|
73
|
+
config: PaymentsConfig;
|
|
74
|
+
/** The adopter's resolver. */
|
|
75
|
+
resolveQuantity: PaymentsQuantityResolver;
|
|
76
|
+
/** One reporter per rail this pass may report on. A rail with none is counted as a failure per period. */
|
|
77
|
+
reporters: Partial<Record<"stripe" | "paddle", UsageReporter>>;
|
|
78
|
+
/** The env handed to the resolver. */
|
|
79
|
+
env: Record<string, unknown>;
|
|
80
|
+
/** The clock. */
|
|
81
|
+
now: () => Date;
|
|
82
|
+
/** Where every skip and failure is logged. */
|
|
83
|
+
log: Logger;
|
|
84
|
+
/** The id minter. Defaults to `crypto.randomUUID`. */
|
|
85
|
+
newId?: () => string;
|
|
86
|
+
}
|
|
87
|
+
/** The tally one pass records. */
|
|
88
|
+
export interface UsagePassTally {
|
|
89
|
+
/** The run's id. */
|
|
90
|
+
id: string;
|
|
91
|
+
/** Subscriptions examined. */
|
|
92
|
+
scanned: number;
|
|
93
|
+
/** Periods a store accepted. */
|
|
94
|
+
reported: number;
|
|
95
|
+
/** Daily-peak samples taken. */
|
|
96
|
+
sampled: number;
|
|
97
|
+
/** Periods found already reported, so nothing was sent. */
|
|
98
|
+
alreadyReported: number;
|
|
99
|
+
/** Subjects whose resolver answered nothing. */
|
|
100
|
+
skipped: number;
|
|
101
|
+
/** Subjects whose resolver answered a number that may not be billed. */
|
|
102
|
+
invalid: number;
|
|
103
|
+
/** Subjects whose resolver threw, or whose report a store refused. */
|
|
104
|
+
failed: number;
|
|
105
|
+
/** The subjects not reported, and why, up to {@link MAX_USAGE_FINDINGS}. */
|
|
106
|
+
findings: UsageFinding[];
|
|
107
|
+
}
|
|
108
|
+
/** Whether a resolver's answer may be billed, and if not, why. */
|
|
109
|
+
export declare function judgeQuantity(answer: unknown, billing: Pick<PaymentsReportedBilling, "min" | "max">): {
|
|
110
|
+
ok: true;
|
|
111
|
+
quantity: number;
|
|
112
|
+
} | {
|
|
113
|
+
ok: false;
|
|
114
|
+
reason: UsageFindingReason;
|
|
115
|
+
};
|
|
116
|
+
/** The UTC day `at` falls in, as `YYYY-MM-DD`. A `daily-peak` period's key. */
|
|
117
|
+
export declare function utcDay(at: Date): string;
|
|
118
|
+
/** Run one pass, record its tally, and return it. */
|
|
119
|
+
export declare function runUsageReport(deps: UsagePassDeps): Promise<UsagePassTally>;
|
|
120
|
+
//# sourceMappingURL=pass.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pass.d.ts","sourceRoot":"","sources":["../../src/usage/pass.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAG5D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAE/D,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,uBAAuB,EAAoB,MAAM,kBAAkB,CAAC;AAIvG,OAAO,EAA0B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAS/E,OAAO,EAAwC,KAAK,YAAY,EAAE,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEpH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,qHAAqH;AACrH,eAAO,MAAM,oBAAoB,WAAa,CAAC;AAK/C,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,4EAA4E;IAC5E,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7B,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,GAAG,EAAE,IAAI,CAAC;CACX;AAED;;;;;GAKG;AACH,MAAM,MAAM,wBAAwB,GAAG,CACrC,OAAO,EAAE,uBAAuB,EAChC,OAAO,EAAE,eAAe,KACrB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAEjC,2BAA2B;AAC3B,MAAM,WAAW,aAAa;IAC5B,wBAAwB;IACxB,EAAE,EAAE,UAAU,CAAC;IACf,2BAA2B;IAC3B,MAAM,EAAE,cAAc,CAAC;IACvB,8BAA8B;IAC9B,eAAe,EAAE,wBAAwB,CAAC;IAC1C,0GAA0G;IAC1G,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,QAAQ,GAAG,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC;IAC/D,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7B,iBAAiB;IACjB,GAAG,EAAE,MAAM,IAAI,CAAC;IAChB,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AAED,kCAAkC;AAClC,MAAM,WAAW,cAAc;IAC7B,oBAAoB;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,8BAA8B;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,gCAAgC;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,gCAAgC;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,2DAA2D;IAC3D,eAAe,EAAE,MAAM,CAAC;IACxB,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,OAAO,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,QAAQ,EAAE,YAAY,EAAE,CAAC;CAC1B;AASD,kEAAkE;AAClE,wBAAgB,aAAa,CAC3B,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,IAAI,CAAC,uBAAuB,EAAE,KAAK,GAAG,KAAK,CAAC,GACpD;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAA;CAAE,CAO5E;AAED,+EAA+E;AAC/E,wBAAgB,MAAM,CAAC,EAAE,EAAE,IAAI,GAAG,MAAM,CAEvC;AA0DD,qDAAqD;AACrD,wBAAsB,cAAc,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CA2TjF"}
|
|
@@ -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"}
|
|
@@ -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.
|
|
6
|
+
export declare const PACKAGE_VERSION = "0.5.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.
|
|
7
|
+
const PACKAGE_VERSION = "0.5.0";
|
|
8
8
|
//#endregion
|
|
9
9
|
export { PACKAGE_NAME, PACKAGE_VERSION };
|
|
@@ -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"}
|
package/dist/workflows/specs.js
CHANGED
|
@@ -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
|