@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.
- 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 +2 -1
- 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 +77 -0
- package/dist/data/usageRun.d.ts.map +1 -0
- package/dist/data/usageRun.js +50 -0
- package/dist/data/webhookEvent.d.ts +1 -1
- 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 +23 -3
- 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 +2 -1
- 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/report.d.ts.map +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 +48 -4
- 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/report.ts +4 -2
- package/src/workflows/specs.ts +34 -0
- package/src/workflows/usage.ts +97 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { type MeterLimit } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
4
|
+
import type { UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
|
|
5
|
+
import type { AllowanceDeclarations } from "../config/allowances";
|
|
6
|
+
import type { KitMeter, PaymentsMeters } from "../config/config";
|
|
7
|
+
import { PaymentsSubject } from "../data/subject";
|
|
8
|
+
import { type PaymentsDatabase } from "../data/tables";
|
|
9
|
+
import { type AllowanceInput } from "./allowance";
|
|
10
|
+
/**
|
|
11
|
+
* The kit's own meters — what the kit counts because it writes the rows.
|
|
12
|
+
*
|
|
13
|
+
* | meter | counted from | enforced by |
|
|
14
|
+
* |----------------|-----------------------|---------------------------------------------|
|
|
15
|
+
* | `emails` | this table, per period | `@pithy-sh/email`, at enqueue, through {@link paymentsUsageMeter} |
|
|
16
|
+
* | `storageBytes` | `pithy_storage_objects` | `@pithy-sh/storage`, through `meterLimit` |
|
|
17
|
+
* | `mediaItems` | `pithy_media_*` | `@pithy-sh/media`, through `meterLimit` |
|
|
18
|
+
*
|
|
19
|
+
* The two that are levels — bytes held, items held — are counted by the capability that holds them, in the
|
|
20
|
+
* statement that writes the row, which is the only place a concurrent burst cannot walk past. Payments only
|
|
21
|
+
* says what the ceiling is. The one that is a flow — emails sent this period — is counted here, in
|
|
22
|
+
* `pithy_payments_meter_counters`, because no row anybody keeps answers "how many this period" once the
|
|
23
|
+
* email capability has pruned its jobs.
|
|
24
|
+
*
|
|
25
|
+
* **Enforcement is opt-in per meter.** Declaring `quotas: { emails: 500 }` makes 500 readable; turning the
|
|
26
|
+
* `emails` meter on makes it binding. A cap that arrives by surprise breaks an adopter already over it.
|
|
27
|
+
*
|
|
28
|
+
* **A counter read that fails refuses, and logs.** Storage already says which way round to err: over-counting
|
|
29
|
+
* briefly and reclaiming is the right way round, and under-counting has no recovery. The cost is stated
|
|
30
|
+
* rather than discovered: a bug of ours becomes a refused send for a paying customer, and a password reset is
|
|
31
|
+
* a bad place to invent a failure. Opt-in enforcement bounds it — an adopter who would rather over-deliver
|
|
32
|
+
* than drop leaves the meter advisory and keeps the check in their own route. Whoever reverses this should
|
|
33
|
+
* have to argue with that paragraph first.
|
|
34
|
+
*
|
|
35
|
+
* **A meter refuses; it never bills.** Nothing here reports a count to a store, and the usage-reporting pass
|
|
36
|
+
* never reads this table: the kit does not sell overage.
|
|
37
|
+
*/
|
|
38
|
+
/** What every allowance read and every meter needs from the config. */
|
|
39
|
+
export interface PaymentsAllowances {
|
|
40
|
+
/** The declarations. */
|
|
41
|
+
declarations: AllowanceDeclarations;
|
|
42
|
+
/** Which kit meters enforce. */
|
|
43
|
+
meters: PaymentsMeters;
|
|
44
|
+
}
|
|
45
|
+
/** Whether a kit meter is enforced in this config. Anything not a kit meter is not. */
|
|
46
|
+
export declare function meterEnforced(meters: PaymentsMeters, meter: string): meter is KitMeter;
|
|
47
|
+
/**
|
|
48
|
+
* Everything resolution needs for one subject, read now: the keys granting access and the override row. A
|
|
49
|
+
* caller acting for nobody holds nothing and has no override, and resolves to the floor.
|
|
50
|
+
*/
|
|
51
|
+
export declare function allowanceInputFor(db: PaymentsDatabase | undefined, declarations: AllowanceDeclarations, subject: PaymentsSubject | undefined, now: Date): Promise<AllowanceInput>;
|
|
52
|
+
/** The first instant of `now`'s calendar month, in UTC. The period of a subject payments knows no billing period for. */
|
|
53
|
+
export declare function calendarMonthStart(now: Date): Date;
|
|
54
|
+
/**
|
|
55
|
+
* When the subject's current period began: the start of its current billing period where payments knows one,
|
|
56
|
+
* the calendar month where it does not — a free-floor account still has a month.
|
|
57
|
+
*
|
|
58
|
+
* The current period is a granting subscription row whose window holds `now`; `data/period.ts` says which
|
|
59
|
+
* rails' rows state where that period began. Two at once — an upgrade overlapping an old subscription's tail —
|
|
60
|
+
* is answered by the newest, which is the one the customer is now paying for.
|
|
61
|
+
*/
|
|
62
|
+
export declare function meterPeriodStart(db: PaymentsDatabase, subject: PaymentsSubject, now: Date): Promise<Date>;
|
|
63
|
+
/**
|
|
64
|
+
* Charge `amount` of `meter` against `subject` — or refuse, and write nothing.
|
|
65
|
+
*
|
|
66
|
+
* **The check and the write are one statement.** An upsert on `(subject, meter, periodStart)` whose update
|
|
67
|
+
* is conditioned on `used + amount <= limit`, with `RETURNING` to read back whether it landed. SQLite
|
|
68
|
+
* evaluates the condition under its write lock, so a burst of concurrent sends is serialized by the database
|
|
69
|
+
* and the first that would pass the limit changes nothing — the guarantee `@pithy-sh/storage`'s conditional
|
|
70
|
+
* insert makes, for the same reason: D1 has no interactive transaction to make two statements one.
|
|
71
|
+
*
|
|
72
|
+
* An unlimited subject — `null`, from a plan or from `unrestricted` — is counted and never refused.
|
|
73
|
+
*/
|
|
74
|
+
export declare function chargeMeter(db: PaymentsDatabase, allowances: PaymentsAllowances, charge: {
|
|
75
|
+
subject: PaymentsSubject;
|
|
76
|
+
meter: string;
|
|
77
|
+
amount: number;
|
|
78
|
+
now: Date;
|
|
79
|
+
}): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* The ceiling a capability enforces on a level it counts itself — `storageBytes`, `mediaItems` — for a
|
|
82
|
+
* subject, or `{ enforced: false }` where the meter is advisory and the capability keeps its own.
|
|
83
|
+
*
|
|
84
|
+
* **The ceiling names the organization it covers.** An organization's plan is the organization's, so the
|
|
85
|
+
* capability must sum every member's rows against it, not the caller's alone — `tenant` says so, the same
|
|
86
|
+
* value the holder's `tenant` carries. A user subject, or nobody, is `null`: the caller's own rows.
|
|
87
|
+
*/
|
|
88
|
+
export declare function meterLimitFor(db: PaymentsDatabase, allowances: PaymentsAllowances, subject: PaymentsSubject | undefined, meter: string, now: Date): Promise<MeterLimit>;
|
|
89
|
+
/**
|
|
90
|
+
* The meter `@pithy-sh/email` finds among the composed capabilities and charges at enqueue — the env-side
|
|
91
|
+
* half of the seam, for the callers with no request. See `@pithy-sh/core/src/entitlement/meter.ts`.
|
|
92
|
+
*
|
|
93
|
+
* A refusal is the provider's own `payments/quota_exceeded`. Anything else that goes wrong — a malformed
|
|
94
|
+
* holder, a D1 read that throws — is logged and refused as `core/internal`, never let through: see this
|
|
95
|
+
* module's note on which way round to err.
|
|
96
|
+
*/
|
|
97
|
+
export declare function paymentsUsageMeter(allowances: PaymentsAllowances, database?: string): UsageMeter;
|
|
98
|
+
//# sourceMappingURL=meter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"meter.d.ts","sourceRoot":"","sources":["../../src/entitlement/meter.ts"],"names":[],"mappings":"AAIA,OAAO,EAA0B,KAAK,UAAU,EAAE,MAAM,4CAA4C,CAAC;AACrG,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,sCAAsC,CAAC;AAKpF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAKjE,OAAO,EAA0B,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAGL,KAAK,gBAAgB,EAEtB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,KAAK,cAAc,EAAgB,MAAM,aAAa,CAAC;AAGhE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,uEAAuE;AACvE,MAAM,WAAW,kBAAkB;IACjC,wBAAwB;IACxB,YAAY,EAAE,qBAAqB,CAAC;IACpC,gCAAgC;IAChC,MAAM,EAAE,cAAc,CAAC;CACxB;AAED,uFAAuF;AACvF,wBAAgB,aAAa,CAAC,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,QAAQ,CAEtF;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,gBAAgB,GAAG,SAAS,EAChC,YAAY,EAAE,qBAAqB,EACnC,OAAO,EAAE,eAAe,GAAG,SAAS,EACpC,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,cAAc,CAAC,CAOzB;AAED,yHAAyH;AACzH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAElD;AAED;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,gBAAgB,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAmB/G;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,gBAAgB,EACpB,UAAU,EAAE,kBAAkB,EAC9B,MAAM,EAAE;IAAE,OAAO,EAAE,eAAe,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,IAAI,CAAA;CAAE,GAC7E,OAAO,CAAC,IAAI,CAAC,CAyCf;AAED;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,gBAAgB,EACpB,UAAU,EAAE,kBAAkB,EAC9B,OAAO,EAAE,eAAe,GAAG,SAAS,EACpC,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,UAAU,CAAC,CAQrB;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,kBAAkB,EAAE,QAAQ,SAAO,GAAG,UAAU,CAuC9F"}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { PaymentsSubject, encodeSubjectReference } from "../data/subject.js";
|
|
4
|
+
import { PaymentsMeterCounter } from "../data/meterCounter.js";
|
|
5
|
+
import { grantingStatuses } from "../data/status.js";
|
|
6
|
+
import { PaymentsPurchase } from "../data/purchase.js";
|
|
7
|
+
import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables.js";
|
|
8
|
+
import { knownPeriodStart } from "../data/period.js";
|
|
9
|
+
import { PaymentsQuotaExceededError } from "../error/errors.js";
|
|
10
|
+
import { resolveEntitlements } from "../projection/resolve.js";
|
|
11
|
+
import { resolveQuota } from "./allowance.js";
|
|
12
|
+
import { allowanceOverride, readOverride } from "./override.js";
|
|
13
|
+
import { InternalError, PithyError, ValidationError, messageOf } from "@pithy-sh/core/src/error/pithyError";
|
|
14
|
+
import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
15
|
+
import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
16
|
+
import { sql } from "kysely";
|
|
17
|
+
//#region src/entitlement/meter.ts
|
|
18
|
+
/** Whether a kit meter is enforced in this config. Anything not a kit meter is not. */
|
|
19
|
+
function meterEnforced(meters, meter) {
|
|
20
|
+
return meters[meter]?.enforce === true;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Everything resolution needs for one subject, read now: the keys granting access and the override row. A
|
|
24
|
+
* caller acting for nobody holds nothing and has no override, and resolves to the floor.
|
|
25
|
+
*/
|
|
26
|
+
async function allowanceInputFor(db, declarations, subject, now) {
|
|
27
|
+
if (subject === void 0 || db === void 0) return {
|
|
28
|
+
declarations,
|
|
29
|
+
held: /* @__PURE__ */ new Set(),
|
|
30
|
+
override: null
|
|
31
|
+
};
|
|
32
|
+
const [entitlements, override] = await Promise.all([resolveEntitlements(db, subject, now), readOverride(db, subject)]);
|
|
33
|
+
return {
|
|
34
|
+
declarations,
|
|
35
|
+
held: grantedEntitlementKeys(entitlements, now),
|
|
36
|
+
override: allowanceOverride(override)
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** The first instant of `now`'s calendar month, in UTC. The period of a subject payments knows no billing period for. */
|
|
40
|
+
function calendarMonthStart(now) {
|
|
41
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* When the subject's current period began: the start of its current billing period where payments knows one,
|
|
45
|
+
* the calendar month where it does not — a free-floor account still has a month.
|
|
46
|
+
*
|
|
47
|
+
* The current period is a granting subscription row whose window holds `now`; `data/period.ts` says which
|
|
48
|
+
* rails' rows state where that period began. Two at once — an upgrade overlapping an old subscription's tail —
|
|
49
|
+
* is answered by the newest, which is the one the customer is now paying for.
|
|
50
|
+
*/
|
|
51
|
+
async function meterPeriodStart(db, subject, now) {
|
|
52
|
+
const at = now.getTime();
|
|
53
|
+
const row = await db.selectFrom(PAYMENTS_PURCHASES_TABLE).select([
|
|
54
|
+
"rail",
|
|
55
|
+
"purchasedAt",
|
|
56
|
+
"payload"
|
|
57
|
+
]).where("subjectType", "=", subject.subjectType).where("subjectId", "=", subject.subjectId).where("type", "=", "subscription").where("status", "in", grantingStatuses(true)).where("purchasedAt", "<=", at).where("expiresAt", ">", at).orderBy("purchasedAt", "desc").limit(1).executeTakeFirst();
|
|
58
|
+
if (row === void 0) return calendarMonthStart(now);
|
|
59
|
+
const purchase = PaymentsPurchase.pick({
|
|
60
|
+
rail: true,
|
|
61
|
+
purchasedAt: true,
|
|
62
|
+
payload: true
|
|
63
|
+
}).parse(row);
|
|
64
|
+
return knownPeriodStart(purchase) ?? calendarMonthStart(now);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Charge `amount` of `meter` against `subject` — or refuse, and write nothing.
|
|
68
|
+
*
|
|
69
|
+
* **The check and the write are one statement.** An upsert on `(subject, meter, periodStart)` whose update
|
|
70
|
+
* is conditioned on `used + amount <= limit`, with `RETURNING` to read back whether it landed. SQLite
|
|
71
|
+
* evaluates the condition under its write lock, so a burst of concurrent sends is serialized by the database
|
|
72
|
+
* and the first that would pass the limit changes nothing — the guarantee `@pithy-sh/storage`'s conditional
|
|
73
|
+
* insert makes, for the same reason: D1 has no interactive transaction to make two statements one.
|
|
74
|
+
*
|
|
75
|
+
* An unlimited subject — `null`, from a plan or from `unrestricted` — is counted and never refused.
|
|
76
|
+
*/
|
|
77
|
+
async function chargeMeter(db, allowances, charge) {
|
|
78
|
+
if (!meterEnforced(allowances.meters, charge.meter)) return;
|
|
79
|
+
const input = await allowanceInputFor(db, allowances.declarations, charge.subject, charge.now);
|
|
80
|
+
const limit = resolveQuota(input, charge.meter).effective.value;
|
|
81
|
+
const periodStart = await meterPeriodStart(db, charge.subject, charge.now);
|
|
82
|
+
const refused = () => new PaymentsQuotaExceededError({
|
|
83
|
+
params: {
|
|
84
|
+
meter: charge.meter,
|
|
85
|
+
limit: limit ?? 0
|
|
86
|
+
},
|
|
87
|
+
detail: `${encodeSubjectReference(charge.subject)} is at its ${charge.meter} quota of ${limit} for the period from ${periodStart.toISOString()}.`
|
|
88
|
+
});
|
|
89
|
+
if (limit !== null && charge.amount > limit) throw refused();
|
|
90
|
+
const at = charge.now.getTime();
|
|
91
|
+
const record = PaymentsMeterCounter.encode({
|
|
92
|
+
id: crypto.randomUUID(),
|
|
93
|
+
subjectType: charge.subject.subjectType,
|
|
94
|
+
subjectId: charge.subject.subjectId,
|
|
95
|
+
meter: charge.meter,
|
|
96
|
+
periodStart,
|
|
97
|
+
used: charge.amount,
|
|
98
|
+
createdAt: charge.now,
|
|
99
|
+
updatedAt: charge.now
|
|
100
|
+
});
|
|
101
|
+
if (await db.insertInto("pithyPaymentsMeterCounters").values(record).onConflict((oc) => {
|
|
102
|
+
const update = oc.columns([
|
|
103
|
+
"subjectType",
|
|
104
|
+
"subjectId",
|
|
105
|
+
"meter",
|
|
106
|
+
"periodStart"
|
|
107
|
+
]).doUpdateSet({
|
|
108
|
+
used: sql`${sql.ref(`pithyPaymentsMeterCounters.used`)} + excluded.used`,
|
|
109
|
+
updatedAt: at
|
|
110
|
+
});
|
|
111
|
+
return limit === null ? update : update.where(sql`${sql.ref(`pithyPaymentsMeterCounters.used`)} + excluded.used <= ${limit}`);
|
|
112
|
+
}).returning("used").executeTakeFirst() === void 0) throw refused();
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The ceiling a capability enforces on a level it counts itself — `storageBytes`, `mediaItems` — for a
|
|
116
|
+
* subject, or `{ enforced: false }` where the meter is advisory and the capability keeps its own.
|
|
117
|
+
*
|
|
118
|
+
* **The ceiling names the organization it covers.** An organization's plan is the organization's, so the
|
|
119
|
+
* capability must sum every member's rows against it, not the caller's alone — `tenant` says so, the same
|
|
120
|
+
* value the holder's `tenant` carries. A user subject, or nobody, is `null`: the caller's own rows.
|
|
121
|
+
*/
|
|
122
|
+
async function meterLimitFor(db, allowances, subject, meter, now) {
|
|
123
|
+
if (!meterEnforced(allowances.meters, meter)) return { enforced: false };
|
|
124
|
+
const input = await allowanceInputFor(db, allowances.declarations, subject, now);
|
|
125
|
+
return {
|
|
126
|
+
enforced: true,
|
|
127
|
+
limit: resolveQuota(input, meter).effective.value,
|
|
128
|
+
tenant: subject?.subjectType === "organization" ? subject.subjectId : null
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The meter `@pithy-sh/email` finds among the composed capabilities and charges at enqueue — the env-side
|
|
133
|
+
* half of the seam, for the callers with no request. See `@pithy-sh/core/src/entitlement/meter.ts`.
|
|
134
|
+
*
|
|
135
|
+
* A refusal is the provider's own `payments/quota_exceeded`. Anything else that goes wrong — a malformed
|
|
136
|
+
* holder, a D1 read that throws — is logged and refused as `core/internal`, never let through: see this
|
|
137
|
+
* module's note on which way round to err.
|
|
138
|
+
*/
|
|
139
|
+
function paymentsUsageMeter(allowances, database = "DB") {
|
|
140
|
+
return {
|
|
141
|
+
provider: "payments",
|
|
142
|
+
async charge(env, charge) {
|
|
143
|
+
if (!meterEnforced(allowances.meters, charge.meter)) return;
|
|
144
|
+
const log = charge.log ?? createWorkerLogger({ name: "payments" });
|
|
145
|
+
const subject = PaymentsSubject.safeParse(charge.subject);
|
|
146
|
+
if (!subject.success || !Number.isInteger(charge.amount) || charge.amount < 1) throw new ValidationError({
|
|
147
|
+
message: "That usage charge names no valid holder or amount.",
|
|
148
|
+
action: "Charge a whole amount from 1 against a subject the payments subject schema accepts.",
|
|
149
|
+
detail: `meter ${charge.meter}, amount ${charge.amount}`
|
|
150
|
+
});
|
|
151
|
+
try {
|
|
152
|
+
const d1 = env[database];
|
|
153
|
+
if (!d1) throw new InternalError({ detail: `No \`${database}\` binding on env; the ${charge.meter} meter cannot count.` });
|
|
154
|
+
await chargeMeter(paymentsDatabase(d1), allowances, {
|
|
155
|
+
subject: subject.data,
|
|
156
|
+
meter: charge.meter,
|
|
157
|
+
amount: charge.amount,
|
|
158
|
+
now: charge.now ?? /* @__PURE__ */ new Date()
|
|
159
|
+
});
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (error instanceof PaymentsQuotaExceededError) throw error;
|
|
162
|
+
log.error("usage meter charge failed", {
|
|
163
|
+
meter: charge.meter,
|
|
164
|
+
cause: messageOf(error)
|
|
165
|
+
});
|
|
166
|
+
if (error instanceof PithyError && error.payload.code !== "core/internal") throw error;
|
|
167
|
+
throw new InternalError({
|
|
168
|
+
message: "Usage could not be checked, so nothing was written.",
|
|
169
|
+
action: "Read the preceding log line for why the meter read failed.",
|
|
170
|
+
detail: `the ${charge.meter} meter could not be charged; refusing rather than serving unbounded.`
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
export { allowanceInputFor, calendarMonthStart, chargeMeter, meterEnforced, meterLimitFor, meterPeriodStart, paymentsUsageMeter };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
4
|
+
import { type AllowanceDeclarations, type FeatureMap, type QuotaMap } from "../config/allowances";
|
|
5
|
+
import { PaymentsOverride } from "../data/override";
|
|
6
|
+
import { type PaymentsSubject } from "../data/subject";
|
|
7
|
+
import { type PaymentsDatabase } from "../data/tables";
|
|
8
|
+
import type { AllowanceOverride } from "./allowance";
|
|
9
|
+
/**
|
|
10
|
+
* Per-subject overrides — the writes behind the control plane's set and clear, and the read every resolver
|
|
11
|
+
* shares.
|
|
12
|
+
*
|
|
13
|
+
* **The first runtime-writable input to an entitlement decision in the kit**, so each rule below is one of the
|
|
14
|
+
* things that keeps it narrow:
|
|
15
|
+
*
|
|
16
|
+
* - **A name must be declared.** A patch naming `emals` is refused naming it and listing what is declared,
|
|
17
|
+
* the shape a grant of an unknown key already gets. `unrestricted` names nothing, so it is exempt.
|
|
18
|
+
* - **A ceiling is a ceiling.** Where a declaration states `overrideMax`, a set past it is refused naming the
|
|
19
|
+
* limit — never clamped, because a clamped number is a wrong number nobody chose.
|
|
20
|
+
* - **A write is a merge by name.** A set changes only the names it carries, so coming back months later to
|
|
21
|
+
* add 100 to one allowance is a request naming one allowance — and one operator's stale pane cannot erase
|
|
22
|
+
* another's pin by omission.
|
|
23
|
+
* - **A write names the version it read.** A version behind the row is `payments/override_stale`, and nothing
|
|
24
|
+
* is written. The compare is inside the write's own `WHERE`, so two writers racing on one row cannot both
|
|
25
|
+
* pass a check made a statement earlier.
|
|
26
|
+
* - **A version never repeats.** A clear keeps the row, empty, at the next version rather than deleting it,
|
|
27
|
+
* so a pane still holding a cleared row's version is behind, not current again.
|
|
28
|
+
* - **A clear only moves a subject back toward its plan.** Unpinning a name on an `unrestricted` subject
|
|
29
|
+
* would lift it to unlimited, which is the unrestricted scope's grant, so a clear naming such a pin is
|
|
30
|
+
* refused. A whole clear takes `unrestricted` with it, which narrows, and is allowed.
|
|
31
|
+
* - **A reason is required on every set**, and the audit event carries it. Six months later, the question
|
|
32
|
+
* anybody asks about an override is why.
|
|
33
|
+
*/
|
|
34
|
+
/** A subject's override row, or undefined when it has none. */
|
|
35
|
+
export declare function readOverride(db: PaymentsDatabase, subject: PaymentsSubject): Promise<PaymentsOverride | undefined>;
|
|
36
|
+
/** The resolver's view of a row: the three facts resolution reads, or null for no override — a cleared row included. */
|
|
37
|
+
export declare function allowanceOverride(row: PaymentsOverride | undefined): AllowanceOverride | null;
|
|
38
|
+
/** The version a write must name: the row's — a cleared row's included — or 0 when there has never been one. */
|
|
39
|
+
export declare function overrideVersion(row: PaymentsOverride | undefined): number;
|
|
40
|
+
/** What a set or a clear changed, for the audit event and the response. */
|
|
41
|
+
export interface OverrideChange {
|
|
42
|
+
/** The row before the write, or undefined when there was none. */
|
|
43
|
+
before: PaymentsOverride | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* The row after the write, or undefined when the subject has never had one. A clear leaves an empty row
|
|
46
|
+
* ({@link isEmptyOverride}), which carries the version the next write must name.
|
|
47
|
+
*/
|
|
48
|
+
after: PaymentsOverride | undefined;
|
|
49
|
+
}
|
|
50
|
+
/** The clock and the id minter. */
|
|
51
|
+
export interface OverrideWriteOptions {
|
|
52
|
+
/** The write timestamp. Defaults to now. */
|
|
53
|
+
now?: Date;
|
|
54
|
+
/** The id minter for a row that does not exist yet. Defaults to `crypto.randomUUID`. */
|
|
55
|
+
newId?: () => string;
|
|
56
|
+
}
|
|
57
|
+
/** A sparse patch: the names to pin, and nothing about the names it omits. */
|
|
58
|
+
export interface OverridePatch {
|
|
59
|
+
/** Quotas to pin, by name. */
|
|
60
|
+
quotas?: QuotaMap;
|
|
61
|
+
/** Features to pin, by name. */
|
|
62
|
+
features?: FeatureMap;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The ceiling an override of `name` is bounded by for a subject holding `held`, or undefined for none.
|
|
66
|
+
*
|
|
67
|
+
* **The keys the subject holds decide, because the ceiling belongs to the tier.** `growth` states that its
|
|
68
|
+
* customers' email allowance may be shaded up to 100,000. Among the held keys that declare the quota, the
|
|
69
|
+
* most permissive applies — and a held key declaring the quota with *no* ceiling leaves it unbounded, since a
|
|
70
|
+
* ceiling that gets in the way of a genuine deal is worse than none. A subject holding no key that declares
|
|
71
|
+
* the quota is bounded the same way by every declaration of it.
|
|
72
|
+
*/
|
|
73
|
+
export declare function overrideCeiling(declarations: AllowanceDeclarations, held: ReadonlySet<string>, name: string): number | undefined;
|
|
74
|
+
/** What a set carries besides the change itself. */
|
|
75
|
+
interface OverrideWrite {
|
|
76
|
+
/** Who. */
|
|
77
|
+
subject: PaymentsSubject;
|
|
78
|
+
/** The version the caller read. 0 when it read no override. */
|
|
79
|
+
version: number;
|
|
80
|
+
/** Why. */
|
|
81
|
+
reason: string;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Pin numbers and switches for one subject. A merge: the names the patch carries change, every other pin
|
|
85
|
+
* stands, and every name never pinned keeps tracking the plan.
|
|
86
|
+
*/
|
|
87
|
+
export declare function setOverride(d1: D1Database, declarations: AllowanceDeclarations, input: OverrideWrite & OverridePatch, options?: OverrideWriteOptions): Promise<OverrideChange>;
|
|
88
|
+
/**
|
|
89
|
+
* Turn `unrestricted` on or off for one subject. Its own write, behind its own scope: it is the largest grant
|
|
90
|
+
* the kit has, and the only one whose reach grows by itself as names are declared. Pins stand either way.
|
|
91
|
+
* Never bounded by `overrideMax` — being unbounded is what it is for.
|
|
92
|
+
*/
|
|
93
|
+
export declare function setUnrestricted(d1: D1Database, input: OverrideWrite & {
|
|
94
|
+
unrestricted: boolean;
|
|
95
|
+
}, options?: OverrideWriteOptions): Promise<OverrideChange>;
|
|
96
|
+
/** What a clear names: some pins, or — with neither list — the whole override. */
|
|
97
|
+
export interface OverrideClear {
|
|
98
|
+
/** Who. */
|
|
99
|
+
subject: PaymentsSubject;
|
|
100
|
+
/** The version the caller read. Optional: a clear that names none is not checked. */
|
|
101
|
+
version?: number;
|
|
102
|
+
/** Quota pins to remove. */
|
|
103
|
+
quotas?: readonly string[];
|
|
104
|
+
/** Feature pins to remove. */
|
|
105
|
+
features?: readonly string[];
|
|
106
|
+
/** Why, when the caller says. A clear keeps the last set's reason otherwise. */
|
|
107
|
+
reason?: string;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Remove pins, or the whole override. **Idempotent**: clearing an override that does not exist — or that a
|
|
111
|
+
* clear already emptied — is the state the caller asked for, and answers with nothing changed rather than a
|
|
112
|
+
* 404. A name unpinned resolves from the plan again on the next read.
|
|
113
|
+
*
|
|
114
|
+
* **A whole clear keeps the row**, empty, at the next version — see {@link isEmptyOverride} for why a version
|
|
115
|
+
* must never repeat. Every read treats that row as no override.
|
|
116
|
+
*/
|
|
117
|
+
export declare function clearOverride(d1: D1Database, input: OverrideClear, options?: OverrideWriteOptions): Promise<OverrideChange>;
|
|
118
|
+
export {};
|
|
119
|
+
//# sourceMappingURL=override.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"override.d.ts","sourceRoot":"","sources":["../../src/entitlement/override.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAI5D,OAAO,EACL,KAAK,qBAAqB,EAG1B,KAAK,UAAU,EACf,KAAK,QAAQ,EACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAmB,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAA0B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAA4B,KAAK,gBAAgB,EAAoB,MAAM,gBAAgB,CAAC;AAGnG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,+DAA+D;AAC/D,wBAAsB,YAAY,CAChC,EAAE,EAAE,gBAAgB,EACpB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAQvC;AAED,wHAAwH;AACxH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,iBAAiB,GAAG,IAAI,CAG7F;AAED,gHAAgH;AAChH,wBAAgB,eAAe,CAAC,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,MAAM,CAEzE;AAED,2EAA2E;AAC3E,MAAM,WAAW,cAAc;IAC7B,kEAAkE;IAClE,MAAM,EAAE,gBAAgB,GAAG,SAAS,CAAC;IACrC;;;OAGG;IACH,KAAK,EAAE,gBAAgB,GAAG,SAAS,CAAC;CACrC;AAED,mCAAmC;AACnC,MAAM,WAAW,oBAAoB;IACnC,4CAA4C;IAC5C,GAAG,CAAC,EAAE,IAAI,CAAC;IACX,wFAAwF;IACxF,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AAED,8EAA8E;AAC9E,MAAM,WAAW,aAAa;IAC5B,8BAA8B;IAC9B,MAAM,CAAC,EAAE,QAAQ,CAAC;IAClB,gCAAgC;IAChC,QAAQ,CAAC,EAAE,UAAU,CAAC;CACvB;AAsBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,YAAY,EAAE,qBAAqB,EACnC,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,EACzB,IAAI,EAAE,MAAM,GACX,MAAM,GAAG,SAAS,CAWpB;AAsBD,oDAAoD;AACpD,UAAU,aAAa;IACrB,WAAW;IACX,OAAO,EAAE,eAAe,CAAC;IACzB,+DAA+D;IAC/D,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW;IACX,MAAM,EAAE,MAAM,CAAC;CAChB;AA2FD;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,UAAU,EACd,YAAY,EAAE,qBAAqB,EACnC,KAAK,EAAE,aAAa,GAAG,aAAa,EACpC,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,cAAc,CAAC,CAczB;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACnC,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,aAAa,GAAG;IAAE,YAAY,EAAE,OAAO,CAAA;CAAE,EAChD,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,cAAc,CAAC,CAOzB;AAED,kFAAkF;AAClF,MAAM,WAAW,aAAa;IAC5B,WAAW;IACX,OAAO,EAAE,eAAe,CAAC;IACzB,qFAAqF;IACrF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4BAA4B;IAC5B,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,8BAA8B;IAC9B,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAyBD;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,aAAa,EACpB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,cAAc,CAAC,CAwBzB"}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { encodeSubjectReference } from "../data/subject.js";
|
|
4
|
+
import { declaredFeatureNames, declaredQuotaNames } from "../config/allowances.js";
|
|
5
|
+
import { PaymentsOverride, isEmptyOverride } from "../data/override.js";
|
|
6
|
+
import { PAYMENTS_OVERRIDES_TABLE, paymentsDatabase } from "../data/tables.js";
|
|
7
|
+
import { PaymentsOverrideStaleError } from "../error/errors.js";
|
|
8
|
+
import { resolveEntitlements } from "../projection/resolve.js";
|
|
9
|
+
import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
10
|
+
import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
11
|
+
import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
|
|
12
|
+
//#region src/entitlement/override.ts
|
|
13
|
+
/**
|
|
14
|
+
* Per-subject overrides — the writes behind the control plane's set and clear, and the read every resolver
|
|
15
|
+
* shares.
|
|
16
|
+
*
|
|
17
|
+
* **The first runtime-writable input to an entitlement decision in the kit**, so each rule below is one of the
|
|
18
|
+
* things that keeps it narrow:
|
|
19
|
+
*
|
|
20
|
+
* - **A name must be declared.** A patch naming `emals` is refused naming it and listing what is declared,
|
|
21
|
+
* the shape a grant of an unknown key already gets. `unrestricted` names nothing, so it is exempt.
|
|
22
|
+
* - **A ceiling is a ceiling.** Where a declaration states `overrideMax`, a set past it is refused naming the
|
|
23
|
+
* limit — never clamped, because a clamped number is a wrong number nobody chose.
|
|
24
|
+
* - **A write is a merge by name.** A set changes only the names it carries, so coming back months later to
|
|
25
|
+
* add 100 to one allowance is a request naming one allowance — and one operator's stale pane cannot erase
|
|
26
|
+
* another's pin by omission.
|
|
27
|
+
* - **A write names the version it read.** A version behind the row is `payments/override_stale`, and nothing
|
|
28
|
+
* is written. The compare is inside the write's own `WHERE`, so two writers racing on one row cannot both
|
|
29
|
+
* pass a check made a statement earlier.
|
|
30
|
+
* - **A version never repeats.** A clear keeps the row, empty, at the next version rather than deleting it,
|
|
31
|
+
* so a pane still holding a cleared row's version is behind, not current again.
|
|
32
|
+
* - **A clear only moves a subject back toward its plan.** Unpinning a name on an `unrestricted` subject
|
|
33
|
+
* would lift it to unlimited, which is the unrestricted scope's grant, so a clear naming such a pin is
|
|
34
|
+
* refused. A whole clear takes `unrestricted` with it, which narrows, and is allowed.
|
|
35
|
+
* - **A reason is required on every set**, and the audit event carries it. Six months later, the question
|
|
36
|
+
* anybody asks about an override is why.
|
|
37
|
+
*/
|
|
38
|
+
/** A subject's override row, or undefined when it has none. */
|
|
39
|
+
async function readOverride(db, subject) {
|
|
40
|
+
const row = await db.selectFrom(PAYMENTS_OVERRIDES_TABLE).selectAll().where("subjectType", "=", subject.subjectType).where("subjectId", "=", subject.subjectId).executeTakeFirst();
|
|
41
|
+
return row === void 0 ? void 0 : PaymentsOverride.parse(row);
|
|
42
|
+
}
|
|
43
|
+
/** The resolver's view of a row: the three facts resolution reads, or null for no override — a cleared row included. */
|
|
44
|
+
function allowanceOverride(row) {
|
|
45
|
+
if (row === void 0 || isEmptyOverride(row)) return null;
|
|
46
|
+
return {
|
|
47
|
+
unrestricted: row.unrestricted,
|
|
48
|
+
quotas: row.quotas,
|
|
49
|
+
features: row.features
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** The version a write must name: the row's — a cleared row's included — or 0 when there has never been one. */
|
|
53
|
+
function overrideVersion(row) {
|
|
54
|
+
return row?.version ?? 0;
|
|
55
|
+
}
|
|
56
|
+
/** Refuse a patch naming anything the declarations do not mention, naming it and listing what is declared. */
|
|
57
|
+
function requireDeclaredNames(declarations, patch) {
|
|
58
|
+
const quotas = declaredQuotaNames(declarations);
|
|
59
|
+
for (const name of Object.keys(patch.quotas ?? {})) {
|
|
60
|
+
if (quotas.includes(name)) continue;
|
|
61
|
+
throw new ValidationError({
|
|
62
|
+
message: `No quota "${name}" is declared. Declared quotas: ${quotas.join(", ") || "none"}.`,
|
|
63
|
+
action: "Override a quota this project declares, or declare it in pithy.config.ts first."
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const features = declaredFeatureNames(declarations);
|
|
67
|
+
for (const name of Object.keys(patch.features ?? {})) {
|
|
68
|
+
if (features.includes(name)) continue;
|
|
69
|
+
throw new ValidationError({
|
|
70
|
+
message: `No feature "${name}" is declared. Declared features: ${features.join(", ") || "none"}.`,
|
|
71
|
+
action: "Override a feature this project declares, or declare it in pithy.config.ts first."
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The ceiling an override of `name` is bounded by for a subject holding `held`, or undefined for none.
|
|
77
|
+
*
|
|
78
|
+
* **The keys the subject holds decide, because the ceiling belongs to the tier.** `growth` states that its
|
|
79
|
+
* customers' email allowance may be shaded up to 100,000. Among the held keys that declare the quota, the
|
|
80
|
+
* most permissive applies — and a held key declaring the quota with *no* ceiling leaves it unbounded, since a
|
|
81
|
+
* ceiling that gets in the way of a genuine deal is worse than none. A subject holding no key that declares
|
|
82
|
+
* the quota is bounded the same way by every declaration of it.
|
|
83
|
+
*/
|
|
84
|
+
function overrideCeiling(declarations, held, name) {
|
|
85
|
+
const speaking = Object.entries(declarations.entitlements).filter(([, declaration]) => name in declaration.quotas);
|
|
86
|
+
const heldSpeaking = speaking.filter(([key]) => held.has(key));
|
|
87
|
+
const deciding = heldSpeaking.length > 0 ? heldSpeaking : speaking;
|
|
88
|
+
let ceiling;
|
|
89
|
+
for (const [, declaration] of deciding) {
|
|
90
|
+
const stated = declaration.overrideMax?.[name];
|
|
91
|
+
if (stated === void 0) return void 0;
|
|
92
|
+
ceiling = ceiling === void 0 ? stated : Math.max(ceiling, stated);
|
|
93
|
+
}
|
|
94
|
+
return ceiling;
|
|
95
|
+
}
|
|
96
|
+
/** Refuse a quota pin past its ceiling, naming the limit. Unlimited (`null`) is past every ceiling. */
|
|
97
|
+
function requireWithinCeilings(declarations, held, quotas) {
|
|
98
|
+
for (const [name, value] of Object.entries(quotas)) {
|
|
99
|
+
const ceiling = overrideCeiling(declarations, held, name);
|
|
100
|
+
if (ceiling === void 0) continue;
|
|
101
|
+
if (value !== null && value <= ceiling) continue;
|
|
102
|
+
throw new ValidationError({
|
|
103
|
+
message: `"${name}" may be overridden up to ${ceiling}, and ${value === null ? "unlimited" : value} is past it.`,
|
|
104
|
+
action: `Send a number no larger than ${ceiling}, or raise \`overrideMax.${name}\` in pithy.config.ts. Unlimited for every name is \`unrestricted\`.`
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** The stale refusal, with the two versions in `detail`. */
|
|
109
|
+
function stale(subject, sent, current) {
|
|
110
|
+
return new PaymentsOverrideStaleError({ detail: `The override for ${encodeSubjectReference(subject)} is at version ${current}; the write named ${sent}.` });
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Write `next` over the subject's row, but only if the row is still at `write.version`.
|
|
114
|
+
*
|
|
115
|
+
* The compare is the statement's own: an update `WHERE version = ?` on an existing row, and an insert that
|
|
116
|
+
* does nothing on conflict for a row that did not exist. Zero rows written is the stale answer either way,
|
|
117
|
+
* because the two writers it protects were never going to be serialized by anything else.
|
|
118
|
+
*/
|
|
119
|
+
async function writeVersioned(d1, write, change, options) {
|
|
120
|
+
const db = paymentsDatabase(d1);
|
|
121
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
122
|
+
const before = await readOverride(db, write.subject);
|
|
123
|
+
const current = overrideVersion(before);
|
|
124
|
+
if (write.version !== current) throw stale(write.subject, write.version, current);
|
|
125
|
+
const next = change(before);
|
|
126
|
+
const record = PaymentsOverride.encode({
|
|
127
|
+
id: before?.id ?? (options.newId ?? (() => crypto.randomUUID()))(),
|
|
128
|
+
subjectType: write.subject.subjectType,
|
|
129
|
+
subjectId: write.subject.subjectId,
|
|
130
|
+
unrestricted: next.unrestricted,
|
|
131
|
+
quotas: next.quotas,
|
|
132
|
+
features: next.features,
|
|
133
|
+
version: current + 1,
|
|
134
|
+
reason: write.reason,
|
|
135
|
+
createdAt: before?.createdAt ?? now,
|
|
136
|
+
updatedAt: now
|
|
137
|
+
});
|
|
138
|
+
const changes = {
|
|
139
|
+
unrestricted: record.unrestricted,
|
|
140
|
+
quotas: record.quotas,
|
|
141
|
+
features: record.features,
|
|
142
|
+
version: record.version,
|
|
143
|
+
reason: record.reason,
|
|
144
|
+
updatedAt: record.updatedAt
|
|
145
|
+
};
|
|
146
|
+
if (await withD1Retry(async () => before === void 0 ? db.insertInto("pithyPaymentsOverrides").values(record).onConflict((oc) => oc.columns(["subjectType", "subjectId"]).doNothing()).returning("id").executeTakeFirst() : db.updateTable("pithyPaymentsOverrides").set(changes).where("subjectType", "=", write.subject.subjectType).where("subjectId", "=", write.subject.subjectId).where("version", "=", current).returning("id").executeTakeFirst()) === void 0) {
|
|
147
|
+
const moved = await readOverride(db, write.subject);
|
|
148
|
+
throw stale(write.subject, write.version, overrideVersion(moved));
|
|
149
|
+
}
|
|
150
|
+
const after = await readOverride(db, write.subject);
|
|
151
|
+
if (after === void 0) throw new InternalError({
|
|
152
|
+
message: "The override could not be recorded.",
|
|
153
|
+
detail: `Wrote the override for ${encodeSubjectReference(write.subject)} but could not read it back.`
|
|
154
|
+
});
|
|
155
|
+
return {
|
|
156
|
+
before,
|
|
157
|
+
after
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** The keys a subject holds that grant access now — what a ceiling is decided by. */
|
|
161
|
+
async function heldNow(db, subject, now) {
|
|
162
|
+
return grantedEntitlementKeys(await resolveEntitlements(db, subject, now), now);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Pin numbers and switches for one subject. A merge: the names the patch carries change, every other pin
|
|
166
|
+
* stands, and every name never pinned keeps tracking the plan.
|
|
167
|
+
*/
|
|
168
|
+
async function setOverride(d1, declarations, input, options = {}) {
|
|
169
|
+
requireDeclaredNames(declarations, input);
|
|
170
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
171
|
+
requireWithinCeilings(declarations, await heldNow(paymentsDatabase(d1), input.subject, now), input.quotas ?? {});
|
|
172
|
+
return writeVersioned(d1, input, (before) => ({
|
|
173
|
+
unrestricted: before?.unrestricted ?? false,
|
|
174
|
+
quotas: {
|
|
175
|
+
...before?.quotas ?? {},
|
|
176
|
+
...input.quotas ?? {}
|
|
177
|
+
},
|
|
178
|
+
features: {
|
|
179
|
+
...before?.features ?? {},
|
|
180
|
+
...input.features ?? {}
|
|
181
|
+
}
|
|
182
|
+
}), {
|
|
183
|
+
...options,
|
|
184
|
+
now
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Turn `unrestricted` on or off for one subject. Its own write, behind its own scope: it is the largest grant
|
|
189
|
+
* the kit has, and the only one whose reach grows by itself as names are declared. Pins stand either way.
|
|
190
|
+
* Never bounded by `overrideMax` — being unbounded is what it is for.
|
|
191
|
+
*/
|
|
192
|
+
async function setUnrestricted(d1, input, options = {}) {
|
|
193
|
+
return writeVersioned(d1, input, (before) => ({
|
|
194
|
+
unrestricted: input.unrestricted,
|
|
195
|
+
quotas: before?.quotas ?? {},
|
|
196
|
+
features: before?.features ?? {}
|
|
197
|
+
}), options);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Refuse a partial clear that would lift a pin on an `unrestricted` subject to unlimited.
|
|
201
|
+
*
|
|
202
|
+
* On an unrestricted row a pin is the one thing holding a name below unlimited, so removing it is not a move
|
|
203
|
+
* back toward the plan — it is the largest grant the kit has, made one name at a time, by a credential that
|
|
204
|
+
* holds only the clear scope. Turning `unrestricted` off first, behind its own scope, or clearing the whole
|
|
205
|
+
* override, are the two ways that narrow.
|
|
206
|
+
*/
|
|
207
|
+
function requireNarrowingClear(row, input) {
|
|
208
|
+
if (!row.unrestricted) return;
|
|
209
|
+
const lifted = [...(input.quotas ?? []).filter((name) => name in row.quotas), ...(input.features ?? []).filter((name) => name in row.features)];
|
|
210
|
+
if (lifted.length === 0) return;
|
|
211
|
+
throw new ValidationError({
|
|
212
|
+
message: `This subject is unrestricted, so unpinning ${lifted.map((name) => `"${name}"`).join(", ")} would make it unlimited.`,
|
|
213
|
+
action: "Turn unrestricted off first through its own route, or clear the whole override — both move the subject back toward its plan.",
|
|
214
|
+
detail: `A clear only narrows. On an unrestricted override a pin is all that holds a name below unlimited, and lifting that is the unrestricted scope's grant.`
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Remove pins, or the whole override. **Idempotent**: clearing an override that does not exist — or that a
|
|
219
|
+
* clear already emptied — is the state the caller asked for, and answers with nothing changed rather than a
|
|
220
|
+
* 404. A name unpinned resolves from the plan again on the next read.
|
|
221
|
+
*
|
|
222
|
+
* **A whole clear keeps the row**, empty, at the next version — see {@link isEmptyOverride} for why a version
|
|
223
|
+
* must never repeat. Every read treats that row as no override.
|
|
224
|
+
*/
|
|
225
|
+
async function clearOverride(d1, input, options = {}) {
|
|
226
|
+
const before = await readOverride(paymentsDatabase(d1), input.subject);
|
|
227
|
+
if (before === void 0 || isEmptyOverride(before)) return {
|
|
228
|
+
before: void 0,
|
|
229
|
+
after: before
|
|
230
|
+
};
|
|
231
|
+
if (input.version !== void 0 && input.version !== before.version) throw stale(input.subject, input.version, before.version);
|
|
232
|
+
const whole = input.quotas === void 0 && input.features === void 0;
|
|
233
|
+
if (!whole) requireNarrowingClear(before, input);
|
|
234
|
+
return writeVersioned(d1, {
|
|
235
|
+
subject: input.subject,
|
|
236
|
+
version: before.version,
|
|
237
|
+
reason: input.reason ?? before.reason
|
|
238
|
+
}, (current) => {
|
|
239
|
+
if (whole) return {
|
|
240
|
+
unrestricted: false,
|
|
241
|
+
quotas: {},
|
|
242
|
+
features: {}
|
|
243
|
+
};
|
|
244
|
+
const quotas = { ...current?.quotas ?? {} };
|
|
245
|
+
for (const name of input.quotas ?? []) delete quotas[name];
|
|
246
|
+
const features = { ...current?.features ?? {} };
|
|
247
|
+
for (const name of input.features ?? []) delete features[name];
|
|
248
|
+
return {
|
|
249
|
+
unrestricted: current?.unrestricted ?? false,
|
|
250
|
+
quotas,
|
|
251
|
+
features
|
|
252
|
+
};
|
|
253
|
+
}, options);
|
|
254
|
+
}
|
|
255
|
+
//#endregion
|
|
256
|
+
export { allowanceOverride, clearOverride, overrideCeiling, overrideVersion, readOverride, setOverride, setUnrestricted };
|