@fantastic.dev/better-stripe 0.50.3 → 0.52.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/CHANGELOG.md +33 -0
- package/README.md +5 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +166 -32
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +83 -16
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +134 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +67 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +4 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/usage/boundaries.d.ts +132 -0
- package/dist/client/usage/boundaries.d.ts.map +1 -0
- package/dist/client/usage/boundaries.js +43 -0
- package/dist/client/usage/boundaries.js.map +1 -0
- package/dist/client/usage/client.d.ts +37 -0
- package/dist/client/usage/client.d.ts.map +1 -0
- package/dist/client/usage/client.js +59 -0
- package/dist/client/usage/client.js.map +1 -0
- package/dist/client/usage/contracts.d.ts +59 -0
- package/dist/client/usage/contracts.d.ts.map +1 -0
- package/dist/client/usage/contracts.js +63 -0
- package/dist/client/usage/contracts.js.map +1 -0
- package/dist/client/usage/index.d.ts +7 -0
- package/dist/client/usage/index.d.ts.map +1 -0
- package/dist/client/usage/index.js +4 -0
- package/dist/client/usage/index.js.map +1 -0
- package/dist/client/usage/records.d.ts +50 -0
- package/dist/client/usage/records.d.ts.map +1 -0
- package/dist/client/usage/records.js +54 -0
- package/dist/client/usage/records.js.map +1 -0
- package/dist/component/_generated/api.d.ts +6 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +79 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/earnings/triggers.d.ts +178 -16
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/schema.d.ts +67 -0
- package/dist/component/schema.js +5 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/helpers.d.ts +13 -0
- package/dist/component/usage/helpers.d.ts.map +1 -0
- package/dist/component/usage/helpers.js +34 -0
- package/dist/component/usage/helpers.js.map +1 -0
- package/dist/component/usage/mutations.d.ts +14 -0
- package/dist/component/usage/mutations.d.ts.map +1 -0
- package/dist/component/usage/mutations.js +124 -0
- package/dist/component/usage/mutations.js.map +1 -0
- package/dist/component/usage/queries.d.ts +62 -0
- package/dist/component/usage/queries.d.ts.map +1 -0
- package/dist/component/usage/queries.js +65 -0
- package/dist/component/usage/queries.js.map +1 -0
- package/dist/component/usage/schema.d.ts +110 -0
- package/dist/component/usage/schema.d.ts.map +1 -0
- package/dist/component/usage/schema.js +54 -0
- package/dist/component/usage/schema.js.map +1 -0
- package/docs/README.md +7 -0
- package/docs/development.md +26 -8
- package/docs/metered-usage.md +289 -37
- package/docs/metering-setup.md +184 -0
- package/docs/usage-ledger.md +62 -0
- package/package.json +8 -2
- package/src/client/index.ts +5 -0
- package/src/client/transferContinuation.test.ts +2 -6
- package/src/client/usage/boundaries.test.ts +136 -0
- package/src/client/usage/boundaries.ts +182 -0
- package/src/client/usage/client.ts +97 -0
- package/src/client/usage/contracts.test.ts +145 -0
- package/src/client/usage/contracts.ts +79 -0
- package/src/client/usage/index.ts +34 -0
- package/src/client/usage/ledger-client.test.ts +74 -0
- package/src/client/usage/records.ts +76 -0
- package/src/component/_generated/api.ts +6 -0
- package/src/component/_generated/component.ts +106 -0
- package/src/component/schema.ts +10 -0
- package/src/component/usage/helpers.ts +33 -0
- package/src/component/usage/ledger.test.ts +310 -0
- package/src/component/usage/mutations.ts +139 -0
- package/src/component/usage/queries.ts +69 -0
- package/src/component/usage/schema.ts +65 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"./_generated/component.js": {
|
|
47
47
|
"types": "./dist/component/_generated/component.d.ts",
|
|
48
48
|
"default": "./dist/component/_generated/component.js"
|
|
49
|
+
},
|
|
50
|
+
"./usage": {
|
|
51
|
+
"types": "./dist/client/usage/index.d.ts",
|
|
52
|
+
"default": "./dist/client/usage/index.js"
|
|
49
53
|
}
|
|
50
54
|
},
|
|
51
55
|
"main": "./dist/client/index.js",
|
|
@@ -86,6 +90,7 @@
|
|
|
86
90
|
"docs/release-handoff.md",
|
|
87
91
|
"docs/setup-intent-recovery.md",
|
|
88
92
|
"docs/metered-usage.md",
|
|
93
|
+
"docs/metering-setup.md",
|
|
89
94
|
"docs/README.md",
|
|
90
95
|
"docs/overview.md",
|
|
91
96
|
"docs/client-api.md",
|
|
@@ -95,7 +100,8 @@
|
|
|
95
100
|
"docs/testing.md",
|
|
96
101
|
"docs/configuration.md",
|
|
97
102
|
"docs/architecture.md",
|
|
98
|
-
"docs/development.md"
|
|
103
|
+
"docs/development.md",
|
|
104
|
+
"docs/usage-ledger.md"
|
|
99
105
|
],
|
|
100
106
|
"scripts": {
|
|
101
107
|
"build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
|
package/src/client/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import * as setupIntentRead from "./billing/setup-intent-read.js";
|
|
2
|
+
import { UsageLedgerClient } from "./usage/client.js";
|
|
3
|
+
export type { RecordUsageOptions } from "./usage/client.js";
|
|
2
4
|
export type {
|
|
3
5
|
SetupIntentReadOptions,
|
|
4
6
|
SetupIntentObservation,
|
|
@@ -240,6 +242,9 @@ export type BetterStripeComponent = ComponentApi;
|
|
|
240
242
|
// BETTER STRIPE CLIENT
|
|
241
243
|
|
|
242
244
|
export class BetterStripe extends PaymentSourceClient {
|
|
245
|
+
get usage() {
|
|
246
|
+
return new UsageLedgerClient(this.component);
|
|
247
|
+
}
|
|
243
248
|
readonly stripeApiVersion: SupportedStripeApiVersion;
|
|
244
249
|
private _apiKey?: string;
|
|
245
250
|
private _triggers?: SyncTriggers;
|
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
// @vitest-environment edge-runtime
|
|
2
2
|
import { expect, it, vi } from "vitest";
|
|
3
|
-
import schema from "../
|
|
3
|
+
import { schema, modules } from "../test.js";
|
|
4
4
|
import { BetterStripe } from "./index.js";
|
|
5
5
|
import type { RunCtx } from "./helpers.js";
|
|
6
6
|
import { components, initConvexTest } from "./setup.test.js";
|
|
7
7
|
import { componentRef } from "./webhooks/helpers.js";
|
|
8
8
|
it("drains every original reference through the actual public SDK and component", async () => {
|
|
9
9
|
const t = initConvexTest();
|
|
10
|
-
t.registerComponent(
|
|
11
|
-
"betterStripe",
|
|
12
|
-
schema,
|
|
13
|
-
import.meta.glob("../component/**/*.ts"),
|
|
14
|
-
);
|
|
10
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
15
11
|
const client = new BetterStripe(components.betterStripe);
|
|
16
12
|
const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
|
|
17
13
|
for (let i = 0; i < 101; i++)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { assertUsageReplay, validateUsagePageRequest } from "./boundaries.js";
|
|
3
|
+
import { prepareUsageRecord } from "./records.js";
|
|
4
|
+
import { authorizeUsageRecord, type UsageAuthorization } from "./boundaries.js";
|
|
5
|
+
|
|
6
|
+
const event = {
|
|
7
|
+
scope: {
|
|
8
|
+
stripeAccountId: "acct_platform",
|
|
9
|
+
customerAccount: "acct_buyer",
|
|
10
|
+
meterId: "mtr_calls",
|
|
11
|
+
livemode: false,
|
|
12
|
+
},
|
|
13
|
+
binding: {
|
|
14
|
+
stripeCustomerId: "cus_buyer",
|
|
15
|
+
stripePriceId: "price_calls",
|
|
16
|
+
eventName: "calls",
|
|
17
|
+
plan: {
|
|
18
|
+
key: "calls",
|
|
19
|
+
version: "v1",
|
|
20
|
+
model: "pay_as_you_go",
|
|
21
|
+
unit: { name: "call", precision: 2 },
|
|
22
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
sourceEventId: "request_1",
|
|
26
|
+
quantity: "1.20",
|
|
27
|
+
occurredAt: 100,
|
|
28
|
+
};
|
|
29
|
+
it("bounds page requests and uses half-open explicit periods", () => {
|
|
30
|
+
expect(
|
|
31
|
+
validateUsagePageRequest({
|
|
32
|
+
period: { start: 0, end: 100 },
|
|
33
|
+
limit: 100,
|
|
34
|
+
cursor: null,
|
|
35
|
+
}),
|
|
36
|
+
).toEqual({ period: { start: 0, end: 100 }, limit: 100, cursor: null });
|
|
37
|
+
for (const input of [
|
|
38
|
+
{ period: { start: 0, end: 0 }, limit: 10, cursor: null },
|
|
39
|
+
{ period: { start: 10, end: 9 }, limit: 10, cursor: null },
|
|
40
|
+
{ period: { start: 0, end: 1.1 }, limit: 10, cursor: null },
|
|
41
|
+
{ period: { start: 0, end: 100 }, limit: 101, cursor: null },
|
|
42
|
+
{ period: { start: 0, end: 100 }, limit: 0, cursor: null },
|
|
43
|
+
{ period: { start: 0, end: 100 }, limit: 10, cursor: "x".repeat(2049) },
|
|
44
|
+
])
|
|
45
|
+
expect(() => validateUsagePageRequest(input)).toThrow();
|
|
46
|
+
});
|
|
47
|
+
it("accepts an exact replay after normalizing quantities", () => {
|
|
48
|
+
expect(() =>
|
|
49
|
+
assertUsageReplay(
|
|
50
|
+
prepareUsageRecord(event),
|
|
51
|
+
prepareUsageRecord({ ...event, quantity: "1.2" }),
|
|
52
|
+
),
|
|
53
|
+
).not.toThrow();
|
|
54
|
+
});
|
|
55
|
+
it("rejects replay changes to historical terms, routing, time or quantity", () => {
|
|
56
|
+
const original = prepareUsageRecord(event);
|
|
57
|
+
for (const changed of [
|
|
58
|
+
{ ...event, quantity: "1.21" },
|
|
59
|
+
{ ...event, occurredAt: 101 },
|
|
60
|
+
{ ...event, binding: { ...event.binding, stripeCustomerId: "cus_other" } },
|
|
61
|
+
{
|
|
62
|
+
...event,
|
|
63
|
+
binding: {
|
|
64
|
+
...event.binding,
|
|
65
|
+
plan: { ...event.binding.plan, version: "v2" },
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
...event,
|
|
70
|
+
binding: {
|
|
71
|
+
...event.binding,
|
|
72
|
+
plan: {
|
|
73
|
+
...event.binding.plan,
|
|
74
|
+
rate: { currency: "eur", unitAmountDecimal: "2" },
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
])
|
|
79
|
+
expect(() =>
|
|
80
|
+
assertUsageReplay(original, prepareUsageRecord(changed)),
|
|
81
|
+
).toThrow("Conflicting usage replay");
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("runs host authorization and activity policy before accepting any model", async () => {
|
|
85
|
+
const order: string[] = [];
|
|
86
|
+
const policy: UsageAuthorization<{ userId: string }> = {
|
|
87
|
+
async authorize(ctx, request) {
|
|
88
|
+
expect(ctx.userId).toBe("user_1");
|
|
89
|
+
expect(request.operation).toBe("record");
|
|
90
|
+
order.push("authorize");
|
|
91
|
+
},
|
|
92
|
+
async authorizeActivity() {
|
|
93
|
+
order.push("activity");
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
for (const plan of [
|
|
97
|
+
event.binding.plan,
|
|
98
|
+
{
|
|
99
|
+
...event.binding.plan,
|
|
100
|
+
model: "included_overage",
|
|
101
|
+
includedQuantity: "10",
|
|
102
|
+
reset: "billing_period",
|
|
103
|
+
},
|
|
104
|
+
{ ...event.binding.plan, model: "prepaid", insufficientBalance: "reject" },
|
|
105
|
+
]) {
|
|
106
|
+
await authorizeUsageRecord(
|
|
107
|
+
{ userId: "user_1" },
|
|
108
|
+
policy,
|
|
109
|
+
{ ...event, binding: { ...event.binding, plan } },
|
|
110
|
+
async (record) => {
|
|
111
|
+
order.push("accept");
|
|
112
|
+
return record.identity;
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
expect(order).toEqual(
|
|
117
|
+
Array(3).fill(["authorize", "activity", "accept"]).flat(),
|
|
118
|
+
);
|
|
119
|
+
order.length = 0;
|
|
120
|
+
await expect(
|
|
121
|
+
authorizeUsageRecord(
|
|
122
|
+
{ userId: "user_1" },
|
|
123
|
+
{
|
|
124
|
+
...policy,
|
|
125
|
+
async authorizeActivity() {
|
|
126
|
+
throw new Error("Not billable");
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
event,
|
|
130
|
+
async () => {
|
|
131
|
+
order.push("accept");
|
|
132
|
+
},
|
|
133
|
+
),
|
|
134
|
+
).rejects.toThrow("Not billable");
|
|
135
|
+
expect(order).toEqual(["authorize"]);
|
|
136
|
+
});
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import type { PreparedUsageRecord, UsageScope } from "./records.js";
|
|
2
|
+
import { prepareUsageRecord } from "./records.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { defineUsagePlan } from "./contracts.js";
|
|
5
|
+
|
|
6
|
+
export type UsagePeriod = { start: number; end: number };
|
|
7
|
+
export type UsagePageRequest = {
|
|
8
|
+
period: UsagePeriod;
|
|
9
|
+
limit: number;
|
|
10
|
+
cursor: string | null;
|
|
11
|
+
};
|
|
12
|
+
export type UsageAvailability<T> =
|
|
13
|
+
| { status: "available"; value: T; observedAt: number }
|
|
14
|
+
| {
|
|
15
|
+
status: "unavailable" | "unsupported";
|
|
16
|
+
reason: string;
|
|
17
|
+
retryable: boolean;
|
|
18
|
+
};
|
|
19
|
+
export type UsageAuthorization<Context> = {
|
|
20
|
+
/** Throw on denial. Resolve identity and tenant ownership in the host. */
|
|
21
|
+
authorize(
|
|
22
|
+
ctx: Context,
|
|
23
|
+
request: {
|
|
24
|
+
scope: UsageScope;
|
|
25
|
+
operation: "record" | "read" | "reconcile" | "correct" | "configure";
|
|
26
|
+
},
|
|
27
|
+
): Promise<void>;
|
|
28
|
+
/** Throw when the server-verified activity is not billable. */
|
|
29
|
+
authorizeActivity(ctx: Context, record: PreparedUsageRecord): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Independent observations; none is inferred from another field. */
|
|
33
|
+
export type UsageObservations = {
|
|
34
|
+
localAcceptedQuantity: string;
|
|
35
|
+
providerAcceptedQuantity: string;
|
|
36
|
+
aggregate: UsageAvailability<{ quantity: string; complete: boolean }>;
|
|
37
|
+
estimate: UsageAvailability<{ amountDecimal: string; currency: string }>;
|
|
38
|
+
invoice: UsageAvailability<{
|
|
39
|
+
invoiceId: string;
|
|
40
|
+
status: "draft" | "open" | "paid" | "void" | "uncollectible";
|
|
41
|
+
amount: string;
|
|
42
|
+
currency: string;
|
|
43
|
+
}>;
|
|
44
|
+
};
|
|
45
|
+
export type UsageCorrectionRequest = {
|
|
46
|
+
scope: UsageScope;
|
|
47
|
+
sourceEventId: string;
|
|
48
|
+
correctionId: string;
|
|
49
|
+
reason: string;
|
|
50
|
+
/** Cancellation preserves the original event. Replacement is a new event. */
|
|
51
|
+
operation: "cancel";
|
|
52
|
+
};
|
|
53
|
+
export type UsageRetentionPolicy = {
|
|
54
|
+
/** Financial evidence has no automatic deletion path. */
|
|
55
|
+
financialEvidence: "retain";
|
|
56
|
+
/** Execution payload cleanup must never erase event/payment/correction history. */
|
|
57
|
+
executionJournalDays: number;
|
|
58
|
+
};
|
|
59
|
+
export type UsageTransitionRequest = {
|
|
60
|
+
scope: UsageScope;
|
|
61
|
+
fromVersion: string;
|
|
62
|
+
toVersion: string;
|
|
63
|
+
effectiveAt: number;
|
|
64
|
+
pendingUsage: "drain_before_transition";
|
|
65
|
+
reservations: "resolve_before_transition";
|
|
66
|
+
existingCredits: "retain_original_terms";
|
|
67
|
+
};
|
|
68
|
+
export type UsageSubscriptionBinding = {
|
|
69
|
+
subscriptionId: string;
|
|
70
|
+
subscriptionItemId: string;
|
|
71
|
+
stripePriceId: string;
|
|
72
|
+
period: UsagePeriod;
|
|
73
|
+
interval: "month";
|
|
74
|
+
};
|
|
75
|
+
export type UsageCreditProvenance = {
|
|
76
|
+
grantId: string;
|
|
77
|
+
purchasePaymentIntentId: string;
|
|
78
|
+
currency: string;
|
|
79
|
+
originalAmount: string;
|
|
80
|
+
/** Quantity projections retain their original plan version and unit. */
|
|
81
|
+
planVersion: string;
|
|
82
|
+
reservationId: string;
|
|
83
|
+
scaledQuantity: string;
|
|
84
|
+
};
|
|
85
|
+
export type UsageCorrectionOutcome = {
|
|
86
|
+
correctionId: string;
|
|
87
|
+
sourceEventId: string;
|
|
88
|
+
state:
|
|
89
|
+
| "requested"
|
|
90
|
+
| "provider_accepted"
|
|
91
|
+
| "confirmed"
|
|
92
|
+
| "held"
|
|
93
|
+
| "unsupported"
|
|
94
|
+
| "invoice_adjustment_required";
|
|
95
|
+
providerAdjustmentId: string | null;
|
|
96
|
+
reason: string;
|
|
97
|
+
};
|
|
98
|
+
export type UsageReceipt = {
|
|
99
|
+
eventId: string;
|
|
100
|
+
identity: string;
|
|
101
|
+
acceptedAt: number;
|
|
102
|
+
delivery: import("./records.js").UsageDeliveryState;
|
|
103
|
+
};
|
|
104
|
+
export type UsageHistoryPage = {
|
|
105
|
+
events: Array<{ receipt: UsageReceipt; record: PreparedUsageRecord }>;
|
|
106
|
+
cursor: string | null;
|
|
107
|
+
isDone: boolean;
|
|
108
|
+
};
|
|
109
|
+
export type UsageProviderCapabilities = {
|
|
110
|
+
aggregation: "sum";
|
|
111
|
+
scaledIntegerQuantities: true;
|
|
112
|
+
realTimeBalance: false;
|
|
113
|
+
eventCancellation: "provider_window";
|
|
114
|
+
invoiceFinalization: "asynchronous";
|
|
115
|
+
};
|
|
116
|
+
/** Contract for host adapters; this interface does not supply a billing engine. */
|
|
117
|
+
export interface UsageContractPort {
|
|
118
|
+
record(record: PreparedUsageRecord): Promise<UsageReceipt>;
|
|
119
|
+
read(request: {
|
|
120
|
+
scope: UsageScope;
|
|
121
|
+
page: UsagePageRequest;
|
|
122
|
+
}): Promise<UsageHistoryPage>;
|
|
123
|
+
reconcile(request: {
|
|
124
|
+
scope: UsageScope;
|
|
125
|
+
period: UsagePeriod;
|
|
126
|
+
}): Promise<UsageAvailability<UsageObservations>>;
|
|
127
|
+
capabilities(
|
|
128
|
+
scope: UsageScope,
|
|
129
|
+
): Promise<UsageAvailability<UsageProviderCapabilities>>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
133
|
+
const pageSchema = z.strictObject({
|
|
134
|
+
period: z.strictObject({ start: seconds, end: seconds }),
|
|
135
|
+
limit: z.number().int().min(1).max(100),
|
|
136
|
+
cursor: z.string().min(1).max(2048).nullable(),
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
export function validateUsagePageRequest(input: unknown): UsagePageRequest {
|
|
140
|
+
const request = pageSchema.parse(input);
|
|
141
|
+
if (request.period.end <= request.period.start)
|
|
142
|
+
throw new Error("Usage period must have a positive duration");
|
|
143
|
+
return request;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function assertUsageReplay(
|
|
147
|
+
original: PreparedUsageRecord,
|
|
148
|
+
candidate: PreparedUsageRecord,
|
|
149
|
+
): void {
|
|
150
|
+
const signature = (record: PreparedUsageRecord) =>
|
|
151
|
+
JSON.stringify([
|
|
152
|
+
record.schemaVersion,
|
|
153
|
+
record.identity,
|
|
154
|
+
record.sourceEventId,
|
|
155
|
+
record.scope.livemode,
|
|
156
|
+
record.scope.stripeAccountId,
|
|
157
|
+
record.scope.customerAccount,
|
|
158
|
+
record.scope.meterId,
|
|
159
|
+
record.quantity,
|
|
160
|
+
record.scaledQuantity,
|
|
161
|
+
record.occurredAt,
|
|
162
|
+
record.binding.stripeCustomerId,
|
|
163
|
+
record.binding.stripePriceId,
|
|
164
|
+
record.binding.eventName,
|
|
165
|
+
record.binding.apiVersion,
|
|
166
|
+
defineUsagePlan(record.binding.plan),
|
|
167
|
+
]);
|
|
168
|
+
if (signature(original) !== signature(candidate))
|
|
169
|
+
throw new Error("Conflicting usage replay");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function authorizeUsageRecord<Context, Result>(
|
|
173
|
+
ctx: Context,
|
|
174
|
+
policy: UsageAuthorization<Context>,
|
|
175
|
+
input: unknown,
|
|
176
|
+
accept: (record: PreparedUsageRecord) => Promise<Result>,
|
|
177
|
+
): Promise<Result> {
|
|
178
|
+
const record = prepareUsageRecord(input);
|
|
179
|
+
await policy.authorize(ctx, { scope: record.scope, operation: "record" });
|
|
180
|
+
await policy.authorizeActivity(ctx, record);
|
|
181
|
+
return accept(record);
|
|
182
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
2
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
3
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
4
|
+
import {
|
|
5
|
+
prepareUsageRecord,
|
|
6
|
+
type PreparedUsageRecord,
|
|
7
|
+
type UsageScope,
|
|
8
|
+
type UsageDeliveryState,
|
|
9
|
+
} from "./records.js";
|
|
10
|
+
import {
|
|
11
|
+
validateUsagePageRequest,
|
|
12
|
+
type UsagePageRequest,
|
|
13
|
+
type UsageSubscriptionBinding,
|
|
14
|
+
type UsageReceipt,
|
|
15
|
+
} from "./boundaries.js";
|
|
16
|
+
import type { Doc, Id } from "../../component/_generated/dataModel.js";
|
|
17
|
+
import type { FunctionHandle } from "convex/server";
|
|
18
|
+
export type RecordUsageOptions = {
|
|
19
|
+
event: unknown;
|
|
20
|
+
subscription: UsageSubscriptionBinding;
|
|
21
|
+
reservationId?: Id<"usageReservations">;
|
|
22
|
+
dispatch?: FunctionHandle<"action">;
|
|
23
|
+
quota?: number;
|
|
24
|
+
};
|
|
25
|
+
export type UsageEventView = {
|
|
26
|
+
receipt: UsageReceipt;
|
|
27
|
+
record: PreparedUsageRecord;
|
|
28
|
+
subscription: UsageSubscriptionBinding;
|
|
29
|
+
delivery: UsageDeliveryState;
|
|
30
|
+
};
|
|
31
|
+
type StoredView = { event: Doc<"usageEvents">; delivery: UsageDeliveryState };
|
|
32
|
+
function decode({ event, delivery }: StoredView): UsageEventView {
|
|
33
|
+
return {
|
|
34
|
+
receipt: {
|
|
35
|
+
eventId: event._id,
|
|
36
|
+
identity: event.identity,
|
|
37
|
+
acceptedAt: event.acceptedAt,
|
|
38
|
+
delivery: "queued",
|
|
39
|
+
},
|
|
40
|
+
record: JSON.parse(event.recordJson) as PreparedUsageRecord,
|
|
41
|
+
subscription: JSON.parse(
|
|
42
|
+
event.subscriptionJson,
|
|
43
|
+
) as UsageSubscriptionBinding,
|
|
44
|
+
delivery,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Trusted host facade. Authenticate and authorize each exact scope first. */
|
|
48
|
+
export class UsageLedgerClient {
|
|
49
|
+
constructor(private readonly component: Component) {}
|
|
50
|
+
async record(ctx: RunCtx, opts: RecordUsageOptions): Promise<UsageReceipt> {
|
|
51
|
+
const event = prepareUsageRecord(opts.event);
|
|
52
|
+
const input = {
|
|
53
|
+
scope: event.scope,
|
|
54
|
+
binding: event.binding,
|
|
55
|
+
sourceEventId: event.sourceEventId,
|
|
56
|
+
quantity: event.quantity,
|
|
57
|
+
occurredAt: event.occurredAt,
|
|
58
|
+
};
|
|
59
|
+
return runMutationOrThrow(
|
|
60
|
+
ctx,
|
|
61
|
+
componentRef(this.component, "usage/mutations/record"),
|
|
62
|
+
{
|
|
63
|
+
inputJson: JSON.stringify(input),
|
|
64
|
+
subscriptionJson: JSON.stringify(opts.subscription),
|
|
65
|
+
dispatch: opts.dispatch,
|
|
66
|
+
reservationId: opts.reservationId,
|
|
67
|
+
quota: opts.quota,
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
async get(
|
|
72
|
+
ctx: RunCtx,
|
|
73
|
+
opts: { scope: UsageScope; eventId: string },
|
|
74
|
+
): Promise<UsageEventView | null> {
|
|
75
|
+
const result = (await ctx.runQuery(
|
|
76
|
+
componentRef(this.component, "usage/queries/get"),
|
|
77
|
+
opts,
|
|
78
|
+
)) as StoredView | null;
|
|
79
|
+
return result ? decode(result) : null;
|
|
80
|
+
}
|
|
81
|
+
async read(ctx: RunCtx, opts: { scope: UsageScope; page: UsagePageRequest }) {
|
|
82
|
+
const page = validateUsagePageRequest(opts.page);
|
|
83
|
+
const result = (await ctx.runQuery(
|
|
84
|
+
componentRef(this.component, "usage/queries/read"),
|
|
85
|
+
{
|
|
86
|
+
scope: opts.scope,
|
|
87
|
+
period: page.period,
|
|
88
|
+
paginationOpts: { numItems: page.limit, cursor: page.cursor },
|
|
89
|
+
},
|
|
90
|
+
)) as { page: StoredView[]; continueCursor: string; isDone: boolean };
|
|
91
|
+
return {
|
|
92
|
+
events: result.page.map(decode),
|
|
93
|
+
cursor: result.isDone ? null : result.continueCursor,
|
|
94
|
+
isDone: result.isDone,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { defineUsagePlan, parseUsageQuantity } from "./contracts.js";
|
|
3
|
+
|
|
4
|
+
const base = {
|
|
5
|
+
key: "api_requests",
|
|
6
|
+
version: "v1",
|
|
7
|
+
unit: { name: "request", precision: 3 },
|
|
8
|
+
rate: { currency: "usd", unitAmountDecimal: "0.02" },
|
|
9
|
+
};
|
|
10
|
+
it.each([
|
|
11
|
+
{ ...base, model: "pay_as_you_go" },
|
|
12
|
+
{
|
|
13
|
+
...base,
|
|
14
|
+
model: "included_overage",
|
|
15
|
+
includedQuantity: "1000",
|
|
16
|
+
reset: "billing_period",
|
|
17
|
+
},
|
|
18
|
+
{ ...base, model: "prepaid", insufficientBalance: "reject" },
|
|
19
|
+
])("validates a serializable plan for $model", (input) => {
|
|
20
|
+
expect(defineUsagePlan(input)).toEqual(input);
|
|
21
|
+
expect(JSON.parse(JSON.stringify(defineUsagePlan(input)))).toEqual(input);
|
|
22
|
+
});
|
|
23
|
+
it("rejects invalid or ambiguous model configuration", () => {
|
|
24
|
+
for (const input of [
|
|
25
|
+
{ ...base, model: "unknown" },
|
|
26
|
+
{ ...base, model: "pay_as_you_go", includedQuantity: "5" },
|
|
27
|
+
{
|
|
28
|
+
...base,
|
|
29
|
+
model: "included_overage",
|
|
30
|
+
includedQuantity: "1.0001",
|
|
31
|
+
reset: "billing_period",
|
|
32
|
+
},
|
|
33
|
+
{ ...base, model: "prepaid", insufficientBalance: "allow" },
|
|
34
|
+
{ ...base, model: "prepaid" },
|
|
35
|
+
{
|
|
36
|
+
...base,
|
|
37
|
+
model: "pay_as_you_go",
|
|
38
|
+
rate: { currency: "USD", unitAmountDecimal: "0.1" },
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
...base,
|
|
42
|
+
model: "pay_as_you_go",
|
|
43
|
+
rate: { currency: "usd", unitAmountDecimal: 0.1 },
|
|
44
|
+
},
|
|
45
|
+
])
|
|
46
|
+
expect(() => defineUsagePlan(input)).toThrow();
|
|
47
|
+
});
|
|
48
|
+
it("represents exact quantities beyond JavaScript's safe integer range", () => {
|
|
49
|
+
expect(parseUsageQuantity("9007199254740993.01", 2)).toEqual({
|
|
50
|
+
quantity: "9007199254740993.01",
|
|
51
|
+
scaledQuantity: "900719925474099301",
|
|
52
|
+
precision: 2,
|
|
53
|
+
});
|
|
54
|
+
expect(parseUsageQuantity("1.2300", 4)).toEqual({
|
|
55
|
+
quantity: "1.23",
|
|
56
|
+
scaledQuantity: "12300",
|
|
57
|
+
precision: 4,
|
|
58
|
+
});
|
|
59
|
+
expect(parseUsageQuantity("0.000", 3)).toEqual({
|
|
60
|
+
quantity: "0",
|
|
61
|
+
scaledQuantity: "0",
|
|
62
|
+
precision: 3,
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
it("rejects rounding, noncanonical numbers, excessive precision and unsafe input", () => {
|
|
66
|
+
for (const value of [
|
|
67
|
+
"-1",
|
|
68
|
+
"+1",
|
|
69
|
+
"1e3",
|
|
70
|
+
"01",
|
|
71
|
+
"1.",
|
|
72
|
+
".1",
|
|
73
|
+
" 1",
|
|
74
|
+
"1.0001",
|
|
75
|
+
"NaN",
|
|
76
|
+
1,
|
|
77
|
+
Infinity,
|
|
78
|
+
null,
|
|
79
|
+
])
|
|
80
|
+
expect(() => parseUsageQuantity(value, 3)).toThrow();
|
|
81
|
+
for (const precision of [-1, 1.5, 7, NaN])
|
|
82
|
+
expect(() => parseUsageQuantity("1", precision)).toThrow();
|
|
83
|
+
expect(() => parseUsageQuantity("1000000000000000000", 0)).toThrow();
|
|
84
|
+
});
|
|
85
|
+
it("copies configuration so caller mutation cannot change validated terms", () => {
|
|
86
|
+
const input = {
|
|
87
|
+
...base,
|
|
88
|
+
unit: { ...base.unit },
|
|
89
|
+
rate: { ...base.rate },
|
|
90
|
+
model: "pay_as_you_go",
|
|
91
|
+
};
|
|
92
|
+
const plan = defineUsagePlan(input);
|
|
93
|
+
input.rate.unitAmountDecimal = "999";
|
|
94
|
+
expect(plan.rate.unitAmountDecimal).toBe("0.02");
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("keeps event identity scoped and independent of plan revisions", async () => {
|
|
98
|
+
const { prepareUsageRecord } = await import("./records.js");
|
|
99
|
+
const input = {
|
|
100
|
+
scope: {
|
|
101
|
+
stripeAccountId: "acct_platform",
|
|
102
|
+
customerAccount: "acct_buyer",
|
|
103
|
+
meterId: "mtr_requests",
|
|
104
|
+
livemode: false,
|
|
105
|
+
},
|
|
106
|
+
binding: {
|
|
107
|
+
stripeCustomerId: "cus_mapped",
|
|
108
|
+
eventName: "requests_v1",
|
|
109
|
+
stripePriceId: "price_requests",
|
|
110
|
+
plan: { ...base, model: "pay_as_you_go" },
|
|
111
|
+
},
|
|
112
|
+
sourceEventId: "job_123",
|
|
113
|
+
quantity: "1.230",
|
|
114
|
+
occurredAt: 1000,
|
|
115
|
+
};
|
|
116
|
+
const first = prepareUsageRecord(input);
|
|
117
|
+
expect(first.quantity).toBe("1.23");
|
|
118
|
+
expect(first.scaledQuantity).toBe("1230");
|
|
119
|
+
expect(
|
|
120
|
+
prepareUsageRecord({
|
|
121
|
+
...input,
|
|
122
|
+
binding: {
|
|
123
|
+
...input.binding,
|
|
124
|
+
plan: { ...input.binding.plan, version: "v2" },
|
|
125
|
+
},
|
|
126
|
+
}).identity,
|
|
127
|
+
).toBe(first.identity);
|
|
128
|
+
expect(
|
|
129
|
+
prepareUsageRecord({
|
|
130
|
+
...input,
|
|
131
|
+
scope: { ...input.scope, customerAccount: "acct_other" },
|
|
132
|
+
}).identity,
|
|
133
|
+
).not.toBe(first.identity);
|
|
134
|
+
expect(
|
|
135
|
+
prepareUsageRecord({ ...input, scope: { ...input.scope, livemode: true } })
|
|
136
|
+
.identity,
|
|
137
|
+
).not.toBe(first.identity);
|
|
138
|
+
expect(() => prepareUsageRecord({ ...input, occurredAt: 1.5 })).toThrow();
|
|
139
|
+
expect(() =>
|
|
140
|
+
prepareUsageRecord({
|
|
141
|
+
...input,
|
|
142
|
+
binding: { ...input.binding, stripeCustomerId: "acct_buyer" },
|
|
143
|
+
}),
|
|
144
|
+
).toThrow();
|
|
145
|
+
});
|