@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,64 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { PaymentsReportCadence } from "../config/config";
|
|
7
|
+
import { PaymentsRail } from "./rail";
|
|
8
|
+
import { PaymentsSubject } from "./subject";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Where a reported period stands.
|
|
12
|
+
*
|
|
13
|
+
* - `sampling` — a `daily-peak` day. The row holds the day's high-water mark; a lower later answer never
|
|
14
|
+
* lowers it. A day is never sent itself: its period's report is the highest of its days, and the day rows
|
|
15
|
+
* are the audit of that number.
|
|
16
|
+
* - `claimed` — a report is being sent, or was sent and not yet confirmed. Claimed **before** the store is
|
|
17
|
+
* called, so a second run arriving mid-call finds the row taken. A claim whose call failed stays claimed,
|
|
18
|
+
* and the next run sends it again **under the same idempotency key** — the row's id — so a call that did
|
|
19
|
+
* land and lost only its answer is recorded once by the store rather than billed twice.
|
|
20
|
+
* - `reported` — the store accepted it. Nothing reports this period again.
|
|
21
|
+
*/
|
|
22
|
+
export const UsageReportStatus = z
|
|
23
|
+
.enum(["sampling", "claimed", "reported"])
|
|
24
|
+
.describe(
|
|
25
|
+
"Where one row stands: a daily-peak day's sample, a period's report in flight, or a period reported and final.",
|
|
26
|
+
);
|
|
27
|
+
export type UsageReportStatus = z.infer<typeof UsageReportStatus>;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One reported period of one subscription — the row in `pithy_payments_usage_reports`, keyed
|
|
31
|
+
* `UNIQUE (rail, providerSubscriptionId, period)`.
|
|
32
|
+
*
|
|
33
|
+
* **The key is the idempotency.** A replayed run, two runs racing, a Workflow step retried after the store
|
|
34
|
+
* answered — each finds the row and sends nothing, because the period has one row and a row is claimed
|
|
35
|
+
* before anything is sent.
|
|
36
|
+
*
|
|
37
|
+
* **The quantity is the adopter's, never a meter's.** It is the answer `resolveQuantity` gave, and nothing
|
|
38
|
+
* here reads `pithy_payments_meter_counters`: the kit does not sell overage.
|
|
39
|
+
*/
|
|
40
|
+
export const PaymentsUsageReport = z
|
|
41
|
+
.object({
|
|
42
|
+
id: z.string().describe("The row's UUID."),
|
|
43
|
+
rail: PaymentsRail.describe("The store the count is reported to."),
|
|
44
|
+
providerSubscriptionId: z.string().describe("The store's own subscription id — `sub_…`."),
|
|
45
|
+
purchaseId: z.string().describe("The purchase row of the period this report is about."),
|
|
46
|
+
productId: z.string().describe("The catalog product being billed by quantity."),
|
|
47
|
+
subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
|
|
48
|
+
subjectId: PaymentsSubject.shape.subjectId.describe("The subject the subscription belongs to."),
|
|
49
|
+
cadence: PaymentsReportCadence.describe("How the product reports — once per period, or each day's peak."),
|
|
50
|
+
period: z
|
|
51
|
+
.string()
|
|
52
|
+
.describe(
|
|
53
|
+
"Which period this is: the billing period's end as ISO-8601 for a period's report, under either cadence; the UTC day `YYYY-MM-DD` for a `daily-peak` day's sample.",
|
|
54
|
+
),
|
|
55
|
+
quantity: z.number().int().nonnegative().describe("The count reported, or for a sampling day the peak so far."),
|
|
56
|
+
status: UsageReportStatus.describe("Where the period stands."),
|
|
57
|
+
sampledAt: SQLiteDate.describe("When the resolver was last asked for this period."),
|
|
58
|
+
reportedAt: SQLiteDate.nullable().describe("When the store accepted the report, or null until it has."),
|
|
59
|
+
createdAt: SQLiteDate.describe("When the period was first seen."),
|
|
60
|
+
updatedAt: SQLiteDate.describe("When the row last changed."),
|
|
61
|
+
})
|
|
62
|
+
.describe("One reported period of one subscription — the row in `pithy_payments_usage_reports`.");
|
|
63
|
+
export type PaymentsUsageReport = z.output<typeof PaymentsUsageReport>;
|
|
64
|
+
export type PaymentsUsageReportRow = z.input<typeof PaymentsUsageReport>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { PaymentsSubject } from "./subject";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Why a subject was not reported on one run. Each is counted and named, and none is ever turned into a
|
|
10
|
+
* number: a skip bills last period's number and leaves a line an operator can act on, where a guess bills a
|
|
11
|
+
* wrong one silently.
|
|
12
|
+
*/
|
|
13
|
+
export const UsageFindingReason = z
|
|
14
|
+
.enum(["unanswered", "not_integer", "negative", "below_min", "above_max", "resolver_failed", "report_failed"])
|
|
15
|
+
.describe(
|
|
16
|
+
"Why a subject was not reported: the resolver answered nothing, answered a non-integer, a negative, a count outside the product's min or max, or threw — or the store refused the report.",
|
|
17
|
+
);
|
|
18
|
+
export type UsageFindingReason = z.infer<typeof UsageFindingReason>;
|
|
19
|
+
|
|
20
|
+
/** One subject a run did not report, and why. */
|
|
21
|
+
export const UsageFinding = z
|
|
22
|
+
.object({
|
|
23
|
+
subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
|
|
24
|
+
subjectId: PaymentsSubject.shape.subjectId.describe("The subject."),
|
|
25
|
+
productId: z.string().describe("The product whose count was not reported."),
|
|
26
|
+
reason: UsageFindingReason.describe("Why."),
|
|
27
|
+
})
|
|
28
|
+
.describe("One subject a usage run did not report, and why.");
|
|
29
|
+
export type UsageFinding = z.infer<typeof UsageFinding>;
|
|
30
|
+
|
|
31
|
+
/** The most findings one run keeps by name. The counts are always whole; the names are a sample past this. */
|
|
32
|
+
export const MAX_USAGE_FINDINGS = 100;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* One usage-reporting pass, kept — the row in `pithy_payments_usage_runs`. The same shape and the same
|
|
36
|
+
* reason as `pithy_payments_reconcile_runs`: a silent job and a job that is not running look identical, and
|
|
37
|
+
* a run that reported nothing is the answer to "is it healthy".
|
|
38
|
+
*/
|
|
39
|
+
export const PaymentsUsageRun = z
|
|
40
|
+
.object({
|
|
41
|
+
id: z.string().describe("The run's UUID."),
|
|
42
|
+
startedAt: SQLiteDate.describe("When the pass began."),
|
|
43
|
+
finishedAt: SQLiteDate.describe("When the pass finished."),
|
|
44
|
+
scanned: z.number().int().nonnegative().describe("Subscriptions examined."),
|
|
45
|
+
reported: z.number().int().nonnegative().describe("Periods a store accepted a report for on this run."),
|
|
46
|
+
sampled: z.number().int().nonnegative().describe("Daily-peak samples taken for a day still open."),
|
|
47
|
+
alreadyReported: z
|
|
48
|
+
.number()
|
|
49
|
+
.int()
|
|
50
|
+
.nonnegative()
|
|
51
|
+
.describe("Periods found already reported or claimed, so nothing was sent. The replay count."),
|
|
52
|
+
skipped: z.number().int().nonnegative().describe("Subjects whose resolver answered nothing."),
|
|
53
|
+
invalid: z
|
|
54
|
+
.number()
|
|
55
|
+
.int()
|
|
56
|
+
.nonnegative()
|
|
57
|
+
.describe("Subjects whose resolver answered a non-integer, a negative, or a count outside min and max."),
|
|
58
|
+
failed: z.number().int().nonnegative().describe("Subjects whose resolver threw, or whose report a store refused."),
|
|
59
|
+
findings: sqliteJson(z.array(UsageFinding)).describe(
|
|
60
|
+
`The subjects not reported, and why — up to ${MAX_USAGE_FINDINGS}. The counts above are whole either way.`,
|
|
61
|
+
),
|
|
62
|
+
createdAt: SQLiteDate.describe("When this row was written."),
|
|
63
|
+
})
|
|
64
|
+
.describe("One usage-reporting pass — when it ran and its tally — the row in `pithy_payments_usage_runs`.");
|
|
65
|
+
export type PaymentsUsageRun = z.output<typeof PaymentsUsageRun>;
|
|
66
|
+
export type PaymentsUsageRunRow = z.input<typeof PaymentsUsageRun>;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
import {
|
|
6
|
+
type AllowanceDeclarations,
|
|
7
|
+
declaredFeatureNames,
|
|
8
|
+
declaredQuotaNames,
|
|
9
|
+
type FeatureMap,
|
|
10
|
+
type QuotaMap,
|
|
11
|
+
type QuotaValue,
|
|
12
|
+
} from "../config/allowances";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* How much a subject may have, resolved — the one implementation of the order every reader shares.
|
|
16
|
+
*
|
|
17
|
+
* **The order, and it fails closed:**
|
|
18
|
+
*
|
|
19
|
+
* 1. The subject's **override**, when it names this allowance. A pin beats everything, `unrestricted`
|
|
20
|
+
* included, so `unrestricted` with `emails: 20000` is unlimited everywhere except email.
|
|
21
|
+
* 2. **`unrestricted`**, when the override carries it: unlimited and on, for every name — including one
|
|
22
|
+
* declared after the override was written, which is why it is a mode and not a list.
|
|
23
|
+
* 3. The **highest** value among every key the subject holds that speaks to this name. `null` (unlimited)
|
|
24
|
+
* beats every number, and a feature is on when any held key turns it on. A customer holding two products
|
|
25
|
+
* is owed the larger of what they bought, and an upgrade overlapping an old subscription's tail must
|
|
26
|
+
* never read as a downgrade for those weeks.
|
|
27
|
+
* 4. **`defaults`**, the free floor, for a name no held key speaks to.
|
|
28
|
+
* 5. **`0` for a quota, `false` for a feature.** Never unlimited. A name that resolved to unlimited because
|
|
29
|
+
* nothing declared it is a paywall that silently does not exist.
|
|
30
|
+
*
|
|
31
|
+
* **The reader takes no key, and that is the point.** A caller does not know which tier the subject is on,
|
|
32
|
+
* and during an upgrade overlap it holds two. Resolving across every held key is what makes a tier ladder
|
|
33
|
+
* unnecessary: an adopter compares numbers, never ranks, and the kit stays without an opinion on whether
|
|
34
|
+
* `growth` outranks `start`.
|
|
35
|
+
*
|
|
36
|
+
* Pure: the caller hands in the held keys and the override row, so the order is testable without a
|
|
37
|
+
* database, and the gate's middleware, the admin read and the meters all reach the same answer.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** Where an allowance's value came from. `none` is the hard floor: nothing declared spoke to it. */
|
|
41
|
+
export type AllowanceSource = "unrestricted" | "override" | "plan" | "default" | "none";
|
|
42
|
+
|
|
43
|
+
/** What a subject's override says. Sparse: a name it does not carry resolves normally. */
|
|
44
|
+
export interface AllowanceOverride {
|
|
45
|
+
/** Unlimited and on, for every name present and future, except the names the patch pins. */
|
|
46
|
+
unrestricted: boolean;
|
|
47
|
+
/** Pinned quotas, by name. */
|
|
48
|
+
quotas: QuotaMap;
|
|
49
|
+
/** Pinned features, by name. */
|
|
50
|
+
features: FeatureMap;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One resolved value and where it came from. */
|
|
54
|
+
export interface ResolvedValue<T> {
|
|
55
|
+
/** The value. */
|
|
56
|
+
value: T;
|
|
57
|
+
/** Where it came from. */
|
|
58
|
+
source: AllowanceSource;
|
|
59
|
+
/** The entitlement key that supplied it, when `source` is `plan`. Null otherwise. */
|
|
60
|
+
key: string | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One quota, resolved: what applies now, and what would apply with the override removed. */
|
|
64
|
+
export interface ResolvedQuota {
|
|
65
|
+
/** The quota name. */
|
|
66
|
+
name: string;
|
|
67
|
+
/** What applies now. */
|
|
68
|
+
effective: ResolvedValue<QuotaValue>;
|
|
69
|
+
/** What would apply with no override — the plan's own number, for a pane to show and revert to. */
|
|
70
|
+
inherited: ResolvedValue<QuotaValue>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One feature, resolved. */
|
|
74
|
+
export interface ResolvedFeature {
|
|
75
|
+
/** The feature name. */
|
|
76
|
+
name: string;
|
|
77
|
+
/** What applies now. */
|
|
78
|
+
effective: ResolvedValue<boolean>;
|
|
79
|
+
/** What would apply with no override. */
|
|
80
|
+
inherited: ResolvedValue<boolean>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Every declared allowance for one subject, resolved. */
|
|
84
|
+
export interface ResolvedAllowances {
|
|
85
|
+
/** Every declared quota, by name order. */
|
|
86
|
+
quotas: ResolvedQuota[];
|
|
87
|
+
/** Every declared feature, by name order. */
|
|
88
|
+
features: ResolvedFeature[];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What resolution reads: the declarations, the keys granting now, and the override row if there is one. */
|
|
92
|
+
export interface AllowanceInput {
|
|
93
|
+
/** The project's declarations. */
|
|
94
|
+
declarations: AllowanceDeclarations;
|
|
95
|
+
/** Every entitlement key the subject holds that grants access now. */
|
|
96
|
+
held: ReadonlySet<string>;
|
|
97
|
+
/** The subject's override, or null. */
|
|
98
|
+
override: AllowanceOverride | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Whether `candidate` is more than `current` — `null` is unlimited and beats every number. */
|
|
102
|
+
function larger(candidate: QuotaValue, current: QuotaValue): boolean {
|
|
103
|
+
if (current === null) return false;
|
|
104
|
+
if (candidate === null) return true;
|
|
105
|
+
return candidate > current;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A quota map's value for a name the caller has already checked is present. `?? 0` would be wrong here and
|
|
110
|
+
* dangerously so: `null` is unlimited, and a nullish fallback reads it as nothing.
|
|
111
|
+
*/
|
|
112
|
+
function quotaAt(map: QuotaMap, name: string): QuotaValue {
|
|
113
|
+
const value = map[name];
|
|
114
|
+
return value === undefined ? 0 : value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Held keys in a stable order, so the key named as a value's source does not depend on set order. */
|
|
118
|
+
function heldInOrder(held: ReadonlySet<string>): string[] {
|
|
119
|
+
return [...held].sort();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The value a quota has with no override: highest held, then the floor, then zero. */
|
|
123
|
+
function inheritedQuota(input: AllowanceInput, name: string): ResolvedValue<QuotaValue> {
|
|
124
|
+
let best: ResolvedValue<QuotaValue> | undefined;
|
|
125
|
+
for (const key of heldInOrder(input.held)) {
|
|
126
|
+
const declaration = input.declarations.entitlements[key];
|
|
127
|
+
if (declaration === undefined || !(name in declaration.quotas)) continue;
|
|
128
|
+
const value = quotaAt(declaration.quotas, name);
|
|
129
|
+
if (best === undefined || larger(value, best.value)) best = { value, source: "plan", key };
|
|
130
|
+
}
|
|
131
|
+
if (best !== undefined) return best;
|
|
132
|
+
const floor = input.declarations.defaults?.quotas;
|
|
133
|
+
if (floor !== undefined && name in floor) return { value: quotaAt(floor, name), source: "default", key: null };
|
|
134
|
+
return { value: 0, source: "none", key: null };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The value a feature has with no override: on if any held key says on, then the floor, then off. */
|
|
138
|
+
function inheritedFeature(input: AllowanceInput, name: string): ResolvedValue<boolean> {
|
|
139
|
+
let spoke: ResolvedValue<boolean> | undefined;
|
|
140
|
+
for (const key of heldInOrder(input.held)) {
|
|
141
|
+
const declaration = input.declarations.entitlements[key];
|
|
142
|
+
if (declaration === undefined || !(name in declaration.features)) continue;
|
|
143
|
+
if (declaration.features[name] === true) return { value: true, source: "plan", key };
|
|
144
|
+
spoke ??= { value: false, source: "plan", key };
|
|
145
|
+
}
|
|
146
|
+
if (spoke !== undefined) return spoke;
|
|
147
|
+
const floor = input.declarations.defaults?.features;
|
|
148
|
+
if (floor !== undefined && name in floor) return { value: floor[name] === true, source: "default", key: null };
|
|
149
|
+
return { value: false, source: "none", key: null };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** One quota, resolved through the whole order. */
|
|
153
|
+
export function resolveQuota(input: AllowanceInput, name: string): ResolvedQuota {
|
|
154
|
+
const inherited = inheritedQuota(input, name);
|
|
155
|
+
const override = input.override;
|
|
156
|
+
if (override !== null && name in override.quotas) {
|
|
157
|
+
return { name, effective: { value: quotaAt(override.quotas, name), source: "override", key: null }, inherited };
|
|
158
|
+
}
|
|
159
|
+
if (override?.unrestricted) return { name, effective: { value: null, source: "unrestricted", key: null }, inherited };
|
|
160
|
+
return { name, effective: inherited, inherited };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** One feature, resolved through the whole order. */
|
|
164
|
+
export function resolveFeature(input: AllowanceInput, name: string): ResolvedFeature {
|
|
165
|
+
const inherited = inheritedFeature(input, name);
|
|
166
|
+
const override = input.override;
|
|
167
|
+
if (override !== null && name in override.features) {
|
|
168
|
+
return {
|
|
169
|
+
name,
|
|
170
|
+
effective: { value: override.features[name] === true, source: "override", key: null },
|
|
171
|
+
inherited,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
if (override?.unrestricted) return { name, effective: { value: true, source: "unrestricted", key: null }, inherited };
|
|
175
|
+
return { name, effective: inherited, inherited };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Every declared quota and feature for one subject. What the admin read projects. */
|
|
179
|
+
export function resolveAllowances(input: AllowanceInput): ResolvedAllowances {
|
|
180
|
+
return {
|
|
181
|
+
quotas: declaredQuotaNames(input.declarations).map((name) => resolveQuota(input, name)),
|
|
182
|
+
features: declaredFeatureNames(input.declarations).map((name) => resolveFeature(input, name)),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Refuse a read of a quota nobody declared, naming it and listing what is declared.
|
|
188
|
+
*
|
|
189
|
+
* **A hard failure, never a default.** `quota(c, "emals")` resolving to `0` would deny quietly, and
|
|
190
|
+
* resolving to unlimited would be a paywall that does not exist — and a typo in a name is exactly the bug
|
|
191
|
+
* that reads as either. `core/internal`, because it is the adopter's code that is wrong, and an operator
|
|
192
|
+
* reading the log is who fixes it.
|
|
193
|
+
*/
|
|
194
|
+
export function requireDeclaredQuota(declarations: AllowanceDeclarations, name: string): void {
|
|
195
|
+
const declared = declaredQuotaNames(declarations);
|
|
196
|
+
if (declared.includes(name)) return;
|
|
197
|
+
throw new InternalError({
|
|
198
|
+
message: `No quota "${name}" is declared.`,
|
|
199
|
+
action: "Declare it under `quotas` on an entitlement or in `defaults` in pithy.config.ts, or correct the name.",
|
|
200
|
+
detail: `quota("${name}") names nothing the payments declarations mention. Declared quotas: ${declared.join(", ") || "none"}.`,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The same refusal for a feature. */
|
|
205
|
+
export function requireDeclaredFeature(declarations: AllowanceDeclarations, name: string): void {
|
|
206
|
+
const declared = declaredFeatureNames(declarations);
|
|
207
|
+
if (declared.includes(name)) return;
|
|
208
|
+
throw new InternalError({
|
|
209
|
+
message: `No feature "${name}" is declared.`,
|
|
210
|
+
action: "Declare it under `features` on an entitlement or in `defaults` in pithy.config.ts, or correct the name.",
|
|
211
|
+
detail: `feature("${name}") names nothing the payments declarations mention. Declared features: ${declared.join(", ") || "none"}.`,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
@@ -42,9 +42,9 @@ import { PaymentsEntitlementNotInCatalogError } from "../error/errors";
|
|
|
42
42
|
* exported, and the exported grant takes a {@link PaymentsConfig} it cannot be called without. A caller
|
|
43
43
|
* cannot reach the unchecked half from outside this module, and the type says why.
|
|
44
44
|
*
|
|
45
|
-
* Comping a key nothing sells is therefore **declared** rather than achieved by nobody checking:
|
|
46
|
-
* `
|
|
47
|
-
*
|
|
45
|
+
* Comping a key nothing sells is therefore **declared** rather than achieved by nobody checking: a key the
|
|
46
|
+
* `entitlements` map in `pithy.config.ts` declares and no product sells is comp-only, grantable, and
|
|
47
|
+
* published on the catalog read beside the products. The check reads
|
|
48
48
|
* `grantableEntitlements`, so that escape travels with it. Only grants are constrained. A revoke is not, or
|
|
49
49
|
* dropping a product from the catalog would be irreversible for every account still holding its key — which
|
|
50
50
|
* is why {@link revokeEntitlement} takes no config, and must never grow one.
|
|
@@ -96,8 +96,8 @@ export interface ManualEntitlementOptions {
|
|
|
96
96
|
* Grant an entitlement by hand, and hold it against the projection. Idempotent; overwrites whatever the
|
|
97
97
|
* projection last derived for this key, and survives every later purchase event for it.
|
|
98
98
|
*
|
|
99
|
-
* Refuses a key this project does not define —
|
|
100
|
-
*
|
|
99
|
+
* Refuses a key this project does not define — the `entitlements` map does not declare it — before any row
|
|
100
|
+
* is written. The config is a parameter rather than a closure because a grant
|
|
101
101
|
* without one is the defect: see the module doc.
|
|
102
102
|
*/
|
|
103
103
|
export async function grantEntitlement(
|
|
@@ -113,7 +113,7 @@ export async function grantEntitlement(
|
|
|
113
113
|
// The set goes in `detail`, which the HTTP codec strips. An operator reading the customer's logs gets
|
|
114
114
|
// the near miss spelled out; the caller learns only which key it sent, because what this project sells
|
|
115
115
|
// is a separate disclosure behind `payments:catalog:read`.
|
|
116
|
-
detail:
|
|
116
|
+
detail: `\`entitlements\` declares no "${input.entitlement}". Declared: ${[...grantable].sort().join(", ") || "nothing"}.`,
|
|
117
117
|
});
|
|
118
118
|
}
|
|
119
119
|
return writeEntitlement(d1, input, true, options);
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import { grantedEntitlementKeys, type MeterLimit } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
6
|
+
import type { MeterCharge, UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
|
|
7
|
+
import { InternalError, messageOf, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
8
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
9
|
+
import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
10
|
+
import { sql } from "kysely";
|
|
11
|
+
import type { AllowanceDeclarations } from "../config/allowances";
|
|
12
|
+
import type { KitMeter, PaymentsMeters } from "../config/config";
|
|
13
|
+
import { PaymentsMeterCounter } from "../data/meterCounter";
|
|
14
|
+
import { knownPeriodStart } from "../data/period";
|
|
15
|
+
import { PaymentsPurchase } from "../data/purchase";
|
|
16
|
+
import { grantingStatuses } from "../data/status";
|
|
17
|
+
import { encodeSubjectReference, PaymentsSubject } from "../data/subject";
|
|
18
|
+
import {
|
|
19
|
+
PAYMENTS_METER_COUNTERS_TABLE,
|
|
20
|
+
PAYMENTS_PURCHASES_TABLE,
|
|
21
|
+
type PaymentsDatabase,
|
|
22
|
+
paymentsDatabase,
|
|
23
|
+
} from "../data/tables";
|
|
24
|
+
import { PaymentsQuotaExceededError } from "../error/errors";
|
|
25
|
+
import { resolveEntitlements } from "../projection/resolve";
|
|
26
|
+
import { type AllowanceInput, resolveQuota } from "./allowance";
|
|
27
|
+
import { allowanceOverride, readOverride } from "./override";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The kit's own meters — what the kit counts because it writes the rows.
|
|
31
|
+
*
|
|
32
|
+
* | meter | counted from | enforced by |
|
|
33
|
+
* |----------------|-----------------------|---------------------------------------------|
|
|
34
|
+
* | `emails` | this table, per period | `@pithy-sh/email`, at enqueue, through {@link paymentsUsageMeter} |
|
|
35
|
+
* | `storageBytes` | `pithy_storage_objects` | `@pithy-sh/storage`, through `meterLimit` |
|
|
36
|
+
* | `mediaItems` | `pithy_media_*` | `@pithy-sh/media`, through `meterLimit` |
|
|
37
|
+
*
|
|
38
|
+
* The two that are levels — bytes held, items held — are counted by the capability that holds them, in the
|
|
39
|
+
* statement that writes the row, which is the only place a concurrent burst cannot walk past. Payments only
|
|
40
|
+
* says what the ceiling is. The one that is a flow — emails sent this period — is counted here, in
|
|
41
|
+
* `pithy_payments_meter_counters`, because no row anybody keeps answers "how many this period" once the
|
|
42
|
+
* email capability has pruned its jobs.
|
|
43
|
+
*
|
|
44
|
+
* **Enforcement is opt-in per meter.** Declaring `quotas: { emails: 500 }` makes 500 readable; turning the
|
|
45
|
+
* `emails` meter on makes it binding. A cap that arrives by surprise breaks an adopter already over it.
|
|
46
|
+
*
|
|
47
|
+
* **A counter read that fails refuses, and logs.** Storage already says which way round to err: over-counting
|
|
48
|
+
* briefly and reclaiming is the right way round, and under-counting has no recovery. The cost is stated
|
|
49
|
+
* rather than discovered: a bug of ours becomes a refused send for a paying customer, and a password reset is
|
|
50
|
+
* a bad place to invent a failure. Opt-in enforcement bounds it — an adopter who would rather over-deliver
|
|
51
|
+
* than drop leaves the meter advisory and keeps the check in their own route. Whoever reverses this should
|
|
52
|
+
* have to argue with that paragraph first.
|
|
53
|
+
*
|
|
54
|
+
* **A meter refuses; it never bills.** Nothing here reports a count to a store, and the usage-reporting pass
|
|
55
|
+
* never reads this table: the kit does not sell overage.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/** What every allowance read and every meter needs from the config. */
|
|
59
|
+
export interface PaymentsAllowances {
|
|
60
|
+
/** The declarations. */
|
|
61
|
+
declarations: AllowanceDeclarations;
|
|
62
|
+
/** Which kit meters enforce. */
|
|
63
|
+
meters: PaymentsMeters;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether a kit meter is enforced in this config. Anything not a kit meter is not. */
|
|
67
|
+
export function meterEnforced(meters: PaymentsMeters, meter: string): meter is KitMeter {
|
|
68
|
+
return (meters as Record<string, { enforce?: boolean } | undefined>)[meter]?.enforce === true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Everything resolution needs for one subject, read now: the keys granting access and the override row. A
|
|
73
|
+
* caller acting for nobody holds nothing and has no override, and resolves to the floor.
|
|
74
|
+
*/
|
|
75
|
+
export async function allowanceInputFor(
|
|
76
|
+
db: PaymentsDatabase | undefined,
|
|
77
|
+
declarations: AllowanceDeclarations,
|
|
78
|
+
subject: PaymentsSubject | undefined,
|
|
79
|
+
now: Date,
|
|
80
|
+
): Promise<AllowanceInput> {
|
|
81
|
+
if (subject === undefined || db === undefined) return { declarations, held: new Set(), override: null };
|
|
82
|
+
const [entitlements, override] = await Promise.all([
|
|
83
|
+
resolveEntitlements(db, subject, now),
|
|
84
|
+
readOverride(db, subject),
|
|
85
|
+
]);
|
|
86
|
+
return { declarations, held: grantedEntitlementKeys(entitlements, now), override: allowanceOverride(override) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The first instant of `now`'s calendar month, in UTC. The period of a subject payments knows no billing period for. */
|
|
90
|
+
export function calendarMonthStart(now: Date): Date {
|
|
91
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* When the subject's current period began: the start of its current billing period where payments knows one,
|
|
96
|
+
* the calendar month where it does not — a free-floor account still has a month.
|
|
97
|
+
*
|
|
98
|
+
* The current period is a granting subscription row whose window holds `now`; `data/period.ts` says which
|
|
99
|
+
* rails' rows state where that period began. Two at once — an upgrade overlapping an old subscription's tail —
|
|
100
|
+
* is answered by the newest, which is the one the customer is now paying for.
|
|
101
|
+
*/
|
|
102
|
+
export async function meterPeriodStart(db: PaymentsDatabase, subject: PaymentsSubject, now: Date): Promise<Date> {
|
|
103
|
+
const at = now.getTime();
|
|
104
|
+
const row = await db
|
|
105
|
+
.selectFrom(PAYMENTS_PURCHASES_TABLE)
|
|
106
|
+
.select(["rail", "purchasedAt", "payload"])
|
|
107
|
+
.where("subjectType", "=", subject.subjectType)
|
|
108
|
+
.where("subjectId", "=", subject.subjectId)
|
|
109
|
+
.where("type", "=", "subscription")
|
|
110
|
+
.where("status", "in", grantingStatuses(true))
|
|
111
|
+
// biome-ignore lint/suspicious/noExplicitAny: ms-epoch numbers against the encoded columns.
|
|
112
|
+
.where("purchasedAt", "<=", at as any)
|
|
113
|
+
// biome-ignore lint/suspicious/noExplicitAny: as above.
|
|
114
|
+
.where("expiresAt", ">", at as any)
|
|
115
|
+
.orderBy("purchasedAt", "desc")
|
|
116
|
+
.limit(1)
|
|
117
|
+
.executeTakeFirst();
|
|
118
|
+
if (row === undefined) return calendarMonthStart(now);
|
|
119
|
+
const purchase = PaymentsPurchase.pick({ rail: true, purchasedAt: true, payload: true }).parse(row);
|
|
120
|
+
return knownPeriodStart(purchase) ?? calendarMonthStart(now);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Charge `amount` of `meter` against `subject` — or refuse, and write nothing.
|
|
125
|
+
*
|
|
126
|
+
* **The check and the write are one statement.** An upsert on `(subject, meter, periodStart)` whose update
|
|
127
|
+
* is conditioned on `used + amount <= limit`, with `RETURNING` to read back whether it landed. SQLite
|
|
128
|
+
* evaluates the condition under its write lock, so a burst of concurrent sends is serialized by the database
|
|
129
|
+
* and the first that would pass the limit changes nothing — the guarantee `@pithy-sh/storage`'s conditional
|
|
130
|
+
* insert makes, for the same reason: D1 has no interactive transaction to make two statements one.
|
|
131
|
+
*
|
|
132
|
+
* An unlimited subject — `null`, from a plan or from `unrestricted` — is counted and never refused.
|
|
133
|
+
*/
|
|
134
|
+
export async function chargeMeter(
|
|
135
|
+
db: PaymentsDatabase,
|
|
136
|
+
allowances: PaymentsAllowances,
|
|
137
|
+
charge: { subject: PaymentsSubject; meter: string; amount: number; now: Date },
|
|
138
|
+
): Promise<void> {
|
|
139
|
+
if (!meterEnforced(allowances.meters, charge.meter)) return;
|
|
140
|
+
const input = await allowanceInputFor(db, allowances.declarations, charge.subject, charge.now);
|
|
141
|
+
const limit = resolveQuota(input, charge.meter).effective.value;
|
|
142
|
+
const periodStart = await meterPeriodStart(db, charge.subject, charge.now);
|
|
143
|
+
const refused = () =>
|
|
144
|
+
new PaymentsQuotaExceededError({
|
|
145
|
+
params: { meter: charge.meter, limit: limit ?? 0 },
|
|
146
|
+
detail: `${encodeSubjectReference(charge.subject)} is at its ${charge.meter} quota of ${limit} for the period from ${periodStart.toISOString()}.`,
|
|
147
|
+
});
|
|
148
|
+
if (limit !== null && charge.amount > limit) throw refused();
|
|
149
|
+
|
|
150
|
+
const at = charge.now.getTime();
|
|
151
|
+
const record = PaymentsMeterCounter.encode({
|
|
152
|
+
id: crypto.randomUUID(),
|
|
153
|
+
subjectType: charge.subject.subjectType,
|
|
154
|
+
subjectId: charge.subject.subjectId,
|
|
155
|
+
meter: charge.meter,
|
|
156
|
+
periodStart,
|
|
157
|
+
used: charge.amount,
|
|
158
|
+
createdAt: charge.now,
|
|
159
|
+
updatedAt: charge.now,
|
|
160
|
+
});
|
|
161
|
+
const landed = await db
|
|
162
|
+
.insertInto(PAYMENTS_METER_COUNTERS_TABLE)
|
|
163
|
+
// biome-ignore lint/suspicious/noExplicitAny: the row is the schema's z.input side; Kysely's insert type derives from it.
|
|
164
|
+
.values(record as any)
|
|
165
|
+
.onConflict((oc) => {
|
|
166
|
+
const update = oc.columns(["subjectType", "subjectId", "meter", "periodStart"]).doUpdateSet({
|
|
167
|
+
// biome-ignore lint/suspicious/noExplicitAny: an expression, not a value.
|
|
168
|
+
used: sql`${sql.ref(`${PAYMENTS_METER_COUNTERS_TABLE}.used`)} + excluded.used` as any,
|
|
169
|
+
// biome-ignore lint/suspicious/noExplicitAny: as above.
|
|
170
|
+
updatedAt: at as any,
|
|
171
|
+
});
|
|
172
|
+
return limit === null
|
|
173
|
+
? update
|
|
174
|
+
: update.where(sql<boolean>`${sql.ref(`${PAYMENTS_METER_COUNTERS_TABLE}.used`)} + excluded.used <= ${limit}`);
|
|
175
|
+
})
|
|
176
|
+
.returning("used")
|
|
177
|
+
.executeTakeFirst();
|
|
178
|
+
if (landed === undefined) throw refused();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The ceiling a capability enforces on a level it counts itself — `storageBytes`, `mediaItems` — for a
|
|
183
|
+
* subject, or `{ enforced: false }` where the meter is advisory and the capability keeps its own.
|
|
184
|
+
*
|
|
185
|
+
* **The ceiling names the organization it covers.** An organization's plan is the organization's, so the
|
|
186
|
+
* capability must sum every member's rows against it, not the caller's alone — `tenant` says so, the same
|
|
187
|
+
* value the holder's `tenant` carries. A user subject, or nobody, is `null`: the caller's own rows.
|
|
188
|
+
*/
|
|
189
|
+
export async function meterLimitFor(
|
|
190
|
+
db: PaymentsDatabase,
|
|
191
|
+
allowances: PaymentsAllowances,
|
|
192
|
+
subject: PaymentsSubject | undefined,
|
|
193
|
+
meter: string,
|
|
194
|
+
now: Date,
|
|
195
|
+
): Promise<MeterLimit> {
|
|
196
|
+
if (!meterEnforced(allowances.meters, meter)) return { enforced: false };
|
|
197
|
+
const input = await allowanceInputFor(db, allowances.declarations, subject, now);
|
|
198
|
+
return {
|
|
199
|
+
enforced: true,
|
|
200
|
+
limit: resolveQuota(input, meter).effective.value,
|
|
201
|
+
tenant: subject?.subjectType === "organization" ? subject.subjectId : null,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The meter `@pithy-sh/email` finds among the composed capabilities and charges at enqueue — the env-side
|
|
207
|
+
* half of the seam, for the callers with no request. See `@pithy-sh/core/src/entitlement/meter.ts`.
|
|
208
|
+
*
|
|
209
|
+
* A refusal is the provider's own `payments/quota_exceeded`. Anything else that goes wrong — a malformed
|
|
210
|
+
* holder, a D1 read that throws — is logged and refused as `core/internal`, never let through: see this
|
|
211
|
+
* module's note on which way round to err.
|
|
212
|
+
*/
|
|
213
|
+
export function paymentsUsageMeter(allowances: PaymentsAllowances, database = "DB"): UsageMeter {
|
|
214
|
+
return {
|
|
215
|
+
provider: "payments",
|
|
216
|
+
async charge(env: Record<string, unknown>, charge: MeterCharge): Promise<void> {
|
|
217
|
+
if (!meterEnforced(allowances.meters, charge.meter)) return;
|
|
218
|
+
const log: Logger = charge.log ?? createWorkerLogger({ name: "payments" });
|
|
219
|
+
const subject = PaymentsSubject.safeParse(charge.subject);
|
|
220
|
+
if (!subject.success || !Number.isInteger(charge.amount) || charge.amount < 1) {
|
|
221
|
+
throw new ValidationError({
|
|
222
|
+
message: "That usage charge names no valid holder or amount.",
|
|
223
|
+
action: "Charge a whole amount from 1 against a subject the payments subject schema accepts.",
|
|
224
|
+
detail: `meter ${charge.meter}, amount ${charge.amount}`,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const d1 = env[database] as D1Database | undefined;
|
|
229
|
+
if (!d1) {
|
|
230
|
+
throw new InternalError({
|
|
231
|
+
detail: `No \`${database}\` binding on env; the ${charge.meter} meter cannot count.`,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
await chargeMeter(paymentsDatabase(d1), allowances, {
|
|
235
|
+
subject: subject.data,
|
|
236
|
+
meter: charge.meter,
|
|
237
|
+
amount: charge.amount,
|
|
238
|
+
now: charge.now ?? new Date(),
|
|
239
|
+
});
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (error instanceof PaymentsQuotaExceededError) throw error;
|
|
242
|
+
log.error("usage meter charge failed", { meter: charge.meter, cause: messageOf(error) });
|
|
243
|
+
if (error instanceof PithyError && error.payload.code !== "core/internal") throw error;
|
|
244
|
+
throw new InternalError({
|
|
245
|
+
message: "Usage could not be checked, so nothing was written.",
|
|
246
|
+
action: "Read the preceding log line for why the meter read failed.",
|
|
247
|
+
detail: `the ${charge.meter} meter could not be charged; refusing rather than serving unbounded.`,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|