@fantastic.dev/better-stripe 0.51.0 → 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 +14 -0
- package/README.md +1 -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/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/records.d.ts +1 -1
- package/dist/client/usage/records.d.ts.map +1 -1
- package/dist/client/usage/records.js +1 -1
- package/dist/client/usage/records.js.map +1 -1
- 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 +2 -0
- package/docs/metered-usage.md +2 -2
- package/docs/metering-setup.md +2 -1
- package/docs/usage-ledger.md +62 -0
- package/package.json +3 -2
- package/src/client/index.ts +5 -0
- package/src/client/usage/client.ts +97 -0
- package/src/client/usage/ledger-client.test.ts +74 -0
- package/src/client/usage/records.ts +1 -1
- 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
|
@@ -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,74 @@
|
|
|
1
|
+
import { componentsGeneric, type FunctionReference } from "convex/server";
|
|
2
|
+
import { expect, it } from "vitest";
|
|
3
|
+
import { initConvexTest } from "../setup.test.js";
|
|
4
|
+
import schema from "../../component/schema.js";
|
|
5
|
+
import { modules } from "../../test.js";
|
|
6
|
+
import { BetterStripe } from "../index.js";
|
|
7
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
8
|
+
it("records and reads through the public facade without resolving a Stripe secret", async () => {
|
|
9
|
+
const t = initConvexTest();
|
|
10
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
11
|
+
const stripe = new BetterStripe(
|
|
12
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
13
|
+
);
|
|
14
|
+
const ctx = {
|
|
15
|
+
runQuery: (
|
|
16
|
+
ref: FunctionReference<"query">,
|
|
17
|
+
args: Record<string, unknown>,
|
|
18
|
+
) => t.query(ref, args),
|
|
19
|
+
runMutation: (
|
|
20
|
+
ref: FunctionReference<"mutation">,
|
|
21
|
+
args: Record<string, unknown>,
|
|
22
|
+
) => t.mutation(ref, args),
|
|
23
|
+
} as RunCtx;
|
|
24
|
+
const now = Math.floor(Date.now() / 1000);
|
|
25
|
+
const scope = {
|
|
26
|
+
stripeAccountId: "acct_platform",
|
|
27
|
+
customerAccount: "acct_buyer",
|
|
28
|
+
meterId: "mtr_calls",
|
|
29
|
+
livemode: false,
|
|
30
|
+
};
|
|
31
|
+
const event = {
|
|
32
|
+
scope,
|
|
33
|
+
binding: {
|
|
34
|
+
stripeCustomerId: "cus_buyer",
|
|
35
|
+
stripePriceId: "price_calls",
|
|
36
|
+
eventName: "calls",
|
|
37
|
+
plan: {
|
|
38
|
+
key: "calls",
|
|
39
|
+
version: "v1",
|
|
40
|
+
model: "pay_as_you_go",
|
|
41
|
+
unit: { name: "call", precision: 0 },
|
|
42
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
sourceEventId: "activity_1",
|
|
46
|
+
quantity: "1",
|
|
47
|
+
occurredAt: now,
|
|
48
|
+
};
|
|
49
|
+
const result = await stripe.usage.record(ctx, {
|
|
50
|
+
event,
|
|
51
|
+
subscription: {
|
|
52
|
+
subscriptionId: "sub_calls",
|
|
53
|
+
subscriptionItemId: "si_calls",
|
|
54
|
+
stripePriceId: "price_calls",
|
|
55
|
+
period: { start: now - 1, end: now + 100 },
|
|
56
|
+
interval: "month",
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
expect(result).toMatchObject({ delivery: "queued" });
|
|
60
|
+
expect(
|
|
61
|
+
await stripe.usage.get(ctx, { scope, eventId: result.eventId }),
|
|
62
|
+
).toMatchObject({
|
|
63
|
+
record: { sourceEventId: "activity_1" },
|
|
64
|
+
delivery: "queued",
|
|
65
|
+
});
|
|
66
|
+
const page = await stripe.usage.read(ctx, {
|
|
67
|
+
scope,
|
|
68
|
+
page: { period: { start: now - 1, end: now + 2 }, limit: 10, cursor: null },
|
|
69
|
+
});
|
|
70
|
+
expect(page).toMatchObject({
|
|
71
|
+
isDone: true,
|
|
72
|
+
events: [{ record: { quantity: "1" }, delivery: "queued" }],
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
type UsagePlan,
|
|
8
8
|
} from "./contracts.js";
|
|
9
9
|
|
|
10
|
-
const scopeSchema = z.strictObject({
|
|
10
|
+
export const scopeSchema = z.strictObject({
|
|
11
11
|
stripeAccountId: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
|
|
12
12
|
customerAccount: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
|
|
13
13
|
meterId: z.string().regex(/^mtr_[a-zA-Z0-9_]+$/),
|
|
@@ -162,6 +162,9 @@ import type * as settlement_clawbackSchema from "../settlement/clawbackSchema.js
|
|
|
162
162
|
import type * as settlement_clawbacks from "../settlement/clawbacks.js";
|
|
163
163
|
import type * as settlement_mutations from "../settlement/mutations.js";
|
|
164
164
|
import type * as settlement_queries from "../settlement/queries.js";
|
|
165
|
+
import type * as usage_helpers from "../usage/helpers.js";
|
|
166
|
+
import type * as usage_mutations from "../usage/mutations.js";
|
|
167
|
+
import type * as usage_queries from "../usage/queries.js";
|
|
165
168
|
import type * as webhooks_mutations from "../webhooks/mutations.js";
|
|
166
169
|
import type * as webhooks_queries from "../webhooks/queries.js";
|
|
167
170
|
import type * as webhooks_validators from "../webhooks/validators.js";
|
|
@@ -328,6 +331,9 @@ const fullApi: ApiFromModules<{
|
|
|
328
331
|
"settlement/clawbacks": typeof settlement_clawbacks;
|
|
329
332
|
"settlement/mutations": typeof settlement_mutations;
|
|
330
333
|
"settlement/queries": typeof settlement_queries;
|
|
334
|
+
"usage/helpers": typeof usage_helpers;
|
|
335
|
+
"usage/mutations": typeof usage_mutations;
|
|
336
|
+
"usage/queries": typeof usage_queries;
|
|
331
337
|
"webhooks/mutations": typeof webhooks_mutations;
|
|
332
338
|
"webhooks/queries": typeof webhooks_queries;
|
|
333
339
|
"webhooks/validators": typeof webhooks_validators;
|
|
@@ -8270,6 +8270,112 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
8270
8270
|
>;
|
|
8271
8271
|
};
|
|
8272
8272
|
};
|
|
8273
|
+
usage: {
|
|
8274
|
+
mutations: {
|
|
8275
|
+
record: FunctionReference<
|
|
8276
|
+
"mutation",
|
|
8277
|
+
"internal",
|
|
8278
|
+
{
|
|
8279
|
+
dispatch?: string;
|
|
8280
|
+
inputJson: string;
|
|
8281
|
+
quota?: number;
|
|
8282
|
+
reservationId?: string;
|
|
8283
|
+
subscriptionJson: string;
|
|
8284
|
+
},
|
|
8285
|
+
{
|
|
8286
|
+
acceptedAt: number;
|
|
8287
|
+
delivery: "queued";
|
|
8288
|
+
eventId: string;
|
|
8289
|
+
identity: string;
|
|
8290
|
+
},
|
|
8291
|
+
Name
|
|
8292
|
+
>;
|
|
8293
|
+
};
|
|
8294
|
+
queries: {
|
|
8295
|
+
get: FunctionReference<
|
|
8296
|
+
"query",
|
|
8297
|
+
"internal",
|
|
8298
|
+
{
|
|
8299
|
+
eventId: string;
|
|
8300
|
+
scope: {
|
|
8301
|
+
customerAccount: string;
|
|
8302
|
+
livemode: boolean;
|
|
8303
|
+
meterId: string;
|
|
8304
|
+
stripeAccountId: string;
|
|
8305
|
+
};
|
|
8306
|
+
},
|
|
8307
|
+
{
|
|
8308
|
+
delivery:
|
|
8309
|
+
| "queued"
|
|
8310
|
+
| "sending"
|
|
8311
|
+
| "provider_accepted"
|
|
8312
|
+
| "rejected"
|
|
8313
|
+
| "unknown"
|
|
8314
|
+
| "held";
|
|
8315
|
+
event: {
|
|
8316
|
+
_creationTime: number;
|
|
8317
|
+
_id: string;
|
|
8318
|
+
acceptedAt: number;
|
|
8319
|
+
identity: string;
|
|
8320
|
+
occurredAt: number;
|
|
8321
|
+
recordJson: string;
|
|
8322
|
+
reservationId?: string;
|
|
8323
|
+
scopeKey: string;
|
|
8324
|
+
subscriptionJson: string;
|
|
8325
|
+
};
|
|
8326
|
+
} | null,
|
|
8327
|
+
Name
|
|
8328
|
+
>;
|
|
8329
|
+
read: FunctionReference<
|
|
8330
|
+
"query",
|
|
8331
|
+
"internal",
|
|
8332
|
+
{
|
|
8333
|
+
paginationOpts: {
|
|
8334
|
+
cursor: string | null;
|
|
8335
|
+
endCursor?: string | null;
|
|
8336
|
+
id?: number;
|
|
8337
|
+
maximumBytesRead?: number;
|
|
8338
|
+
maximumRowsRead?: number;
|
|
8339
|
+
numItems: number;
|
|
8340
|
+
};
|
|
8341
|
+
period: { end: number; start: number };
|
|
8342
|
+
scope: {
|
|
8343
|
+
customerAccount: string;
|
|
8344
|
+
livemode: boolean;
|
|
8345
|
+
meterId: string;
|
|
8346
|
+
stripeAccountId: string;
|
|
8347
|
+
};
|
|
8348
|
+
},
|
|
8349
|
+
{
|
|
8350
|
+
continueCursor: string;
|
|
8351
|
+
isDone: boolean;
|
|
8352
|
+
page: Array<{
|
|
8353
|
+
delivery:
|
|
8354
|
+
| "queued"
|
|
8355
|
+
| "sending"
|
|
8356
|
+
| "provider_accepted"
|
|
8357
|
+
| "rejected"
|
|
8358
|
+
| "unknown"
|
|
8359
|
+
| "held";
|
|
8360
|
+
event: {
|
|
8361
|
+
_creationTime: number;
|
|
8362
|
+
_id: string;
|
|
8363
|
+
acceptedAt: number;
|
|
8364
|
+
identity: string;
|
|
8365
|
+
occurredAt: number;
|
|
8366
|
+
recordJson: string;
|
|
8367
|
+
reservationId?: string;
|
|
8368
|
+
scopeKey: string;
|
|
8369
|
+
subscriptionJson: string;
|
|
8370
|
+
};
|
|
8371
|
+
}>;
|
|
8372
|
+
pageStatus?: "SplitRecommended" | "SplitRequired" | null;
|
|
8373
|
+
splitCursor?: string | null;
|
|
8374
|
+
},
|
|
8375
|
+
Name
|
|
8376
|
+
>;
|
|
8377
|
+
};
|
|
8378
|
+
};
|
|
8273
8379
|
webhooks: {
|
|
8274
8380
|
mutations: {
|
|
8275
8381
|
insertWebhookEvent: FunctionReference<
|
package/src/component/schema.ts
CHANGED
|
@@ -69,6 +69,12 @@ import {
|
|
|
69
69
|
commissionDecisionsTable,
|
|
70
70
|
} from "./settlement/schema";
|
|
71
71
|
import { defineSchema } from "convex/server";
|
|
72
|
+
import {
|
|
73
|
+
usageEventsTable,
|
|
74
|
+
usageOutboxTable,
|
|
75
|
+
usageScopeCountersTable,
|
|
76
|
+
usageReservationsTable,
|
|
77
|
+
} from "./usage/schema.js";
|
|
72
78
|
|
|
73
79
|
import {
|
|
74
80
|
checkoutSessionsTable,
|
|
@@ -89,6 +95,10 @@ import { pricesTable, productsTable } from "./products/schema";
|
|
|
89
95
|
import { webhookEventsTable } from "./webhooks/schema";
|
|
90
96
|
|
|
91
97
|
export default defineSchema({
|
|
98
|
+
usageEvents: usageEventsTable,
|
|
99
|
+
usageOutbox: usageOutboxTable,
|
|
100
|
+
usageScopeCounters: usageScopeCountersTable,
|
|
101
|
+
usageReservations: usageReservationsTable,
|
|
92
102
|
refundSyncClaims: refundSyncClaimsTable,
|
|
93
103
|
processingCostReconciliationOperations,
|
|
94
104
|
recoveryWorkflowOperations,
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { scopeSchema } from "../../client/usage/records.js";
|
|
3
|
+
import type { UsageScope } from "../../client/usage/records.js";
|
|
4
|
+
export function scopeKey(input: UsageScope) {
|
|
5
|
+
const key = JSON.stringify(scopeSchema.parse(input));
|
|
6
|
+
if (key.length > 512) throw new Error("Usage scope exceeds size limit");
|
|
7
|
+
return key;
|
|
8
|
+
}
|
|
9
|
+
const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
10
|
+
const subscriptionSchema = z.strictObject({
|
|
11
|
+
subscriptionId: z
|
|
12
|
+
.string()
|
|
13
|
+
.regex(/^sub_[a-zA-Z0-9]+$/)
|
|
14
|
+
.max(100),
|
|
15
|
+
subscriptionItemId: z
|
|
16
|
+
.string()
|
|
17
|
+
.regex(/^si_[a-zA-Z0-9]+$/)
|
|
18
|
+
.max(100),
|
|
19
|
+
stripePriceId: z
|
|
20
|
+
.string()
|
|
21
|
+
.regex(/^price_[a-zA-Z0-9]+$/)
|
|
22
|
+
.max(100),
|
|
23
|
+
period: z.strictObject({ start: seconds, end: seconds }),
|
|
24
|
+
interval: z.literal("month"),
|
|
25
|
+
});
|
|
26
|
+
export function subscriptionSnapshot(json: string) {
|
|
27
|
+
if (new TextEncoder().encode(json).length > 2048)
|
|
28
|
+
throw new Error("Usage subscription exceeds size limit");
|
|
29
|
+
const subscription = subscriptionSchema.parse(JSON.parse(json));
|
|
30
|
+
if (subscription.period.end <= subscription.period.start)
|
|
31
|
+
throw new Error("Invalid usage subscription period");
|
|
32
|
+
return subscription;
|
|
33
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { convexTest } from "convex-test";
|
|
2
|
+
import { makeFunctionReference } from "convex/server";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { record as registeredRecord } from "./mutations.js";
|
|
5
|
+
import type { MutationCtx } from "../_generated/server.js";
|
|
6
|
+
import { schema, modules } from "../../test.js";
|
|
7
|
+
|
|
8
|
+
// Codegen runs after the first failing tests; these are genuine function refs.
|
|
9
|
+
const record = makeFunctionReference<"mutation">("usage/mutations:record");
|
|
10
|
+
const read = makeFunctionReference<"query">("usage/queries:read");
|
|
11
|
+
const get = makeFunctionReference<"query">("usage/queries:get");
|
|
12
|
+
const now = Math.floor(Date.now() / 1000);
|
|
13
|
+
const scope = {
|
|
14
|
+
stripeAccountId: "acct_platform",
|
|
15
|
+
customerAccount: "acct_buyer",
|
|
16
|
+
meterId: "mtr_calls",
|
|
17
|
+
livemode: false,
|
|
18
|
+
};
|
|
19
|
+
const event = {
|
|
20
|
+
scope,
|
|
21
|
+
binding: {
|
|
22
|
+
stripeCustomerId: "cus_buyer",
|
|
23
|
+
stripePriceId: "price_calls",
|
|
24
|
+
eventName: "calls",
|
|
25
|
+
plan: {
|
|
26
|
+
key: "calls",
|
|
27
|
+
version: "v1",
|
|
28
|
+
model: "pay_as_you_go",
|
|
29
|
+
unit: { name: "call", precision: 2 },
|
|
30
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
sourceEventId: "activity_1",
|
|
34
|
+
quantity: "1.20",
|
|
35
|
+
occurredAt: now,
|
|
36
|
+
};
|
|
37
|
+
const subscription = {
|
|
38
|
+
subscriptionId: "sub_calls",
|
|
39
|
+
subscriptionItemId: "si_calls",
|
|
40
|
+
stripePriceId: "price_calls",
|
|
41
|
+
period: { start: now - 100, end: now + 1000 },
|
|
42
|
+
interval: "month",
|
|
43
|
+
};
|
|
44
|
+
const args = (input = event) => ({
|
|
45
|
+
inputJson: JSON.stringify(input),
|
|
46
|
+
subscriptionJson: JSON.stringify(subscription),
|
|
47
|
+
});
|
|
48
|
+
it("atomically persists a single immutable event and outbox for competing identical replays", async () => {
|
|
49
|
+
const t = convexTest(schema, modules);
|
|
50
|
+
const results = await Promise.all([
|
|
51
|
+
t.mutation(record, args()),
|
|
52
|
+
t.mutation(record, args({ ...event, quantity: "1.2" })),
|
|
53
|
+
]);
|
|
54
|
+
expect(results[0]).toEqual(results[1]);
|
|
55
|
+
await t.run(async (ctx) => {
|
|
56
|
+
const events = await ctx.db.query("usageEvents").take(10);
|
|
57
|
+
const outbox = await ctx.db.query("usageOutbox").take(10);
|
|
58
|
+
expect(events).toHaveLength(1);
|
|
59
|
+
expect(outbox).toHaveLength(1);
|
|
60
|
+
expect(outbox[0].eventId).toBe(events[0]._id);
|
|
61
|
+
expect(JSON.parse(events[0].recordJson).scaledQuantity).toBe("120");
|
|
62
|
+
expect(await ctx.db.query("usageScopeCounters").first()).toMatchObject({
|
|
63
|
+
count: 1,
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
it("rejects changed versions, amounts, timestamps and subscription bindings without rewriting history", async () => {
|
|
68
|
+
const t = convexTest(schema, modules);
|
|
69
|
+
await t.mutation(record, args());
|
|
70
|
+
for (const changed of [
|
|
71
|
+
{ ...event, quantity: "2" },
|
|
72
|
+
{ ...event, occurredAt: now - 1 },
|
|
73
|
+
{
|
|
74
|
+
...event,
|
|
75
|
+
binding: {
|
|
76
|
+
...event.binding,
|
|
77
|
+
plan: { ...event.binding.plan, version: "v2" },
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
])
|
|
81
|
+
await expect(t.mutation(record, args(changed))).rejects.toThrow(
|
|
82
|
+
"Conflicting usage replay",
|
|
83
|
+
);
|
|
84
|
+
await expect(
|
|
85
|
+
t.mutation(record, {
|
|
86
|
+
...args(),
|
|
87
|
+
subscriptionJson: JSON.stringify({
|
|
88
|
+
...subscription,
|
|
89
|
+
subscriptionId: "sub_other",
|
|
90
|
+
}),
|
|
91
|
+
}),
|
|
92
|
+
).rejects.toThrow("Conflicting usage replay");
|
|
93
|
+
});
|
|
94
|
+
it("isolates payer/meter/realm/mode and currency snapshots", async () => {
|
|
95
|
+
const t = convexTest(schema, modules);
|
|
96
|
+
for (const changed of [
|
|
97
|
+
event,
|
|
98
|
+
{ ...event, scope: { ...scope, customerAccount: "acct_other" } },
|
|
99
|
+
{ ...event, scope: { ...scope, meterId: "mtr_other" } },
|
|
100
|
+
{ ...event, scope: { ...scope, stripeAccountId: "acct_other" } },
|
|
101
|
+
{ ...event, scope: { ...scope, livemode: true } },
|
|
102
|
+
])
|
|
103
|
+
await t.mutation(record, args(changed));
|
|
104
|
+
await expect(
|
|
105
|
+
t.mutation(
|
|
106
|
+
record,
|
|
107
|
+
args({
|
|
108
|
+
...event,
|
|
109
|
+
binding: {
|
|
110
|
+
...event.binding,
|
|
111
|
+
plan: {
|
|
112
|
+
...event.binding.plan,
|
|
113
|
+
rate: { currency: "eur", unitAmountDecimal: "2" },
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
),
|
|
118
|
+
).rejects.toThrow("Conflicting usage replay");
|
|
119
|
+
expect(
|
|
120
|
+
await t.run((ctx) => ctx.db.query("usageEvents").take(10)),
|
|
121
|
+
).toHaveLength(5);
|
|
122
|
+
});
|
|
123
|
+
it("rejects out-of-window/period input, oversized payloads and quota exhaustion but returns original replay", async () => {
|
|
124
|
+
const t = convexTest(schema, modules);
|
|
125
|
+
for (const occurredAt of [
|
|
126
|
+
now - 35 * 86400 - 10,
|
|
127
|
+
now + 600,
|
|
128
|
+
subscription.period.end,
|
|
129
|
+
])
|
|
130
|
+
await expect(
|
|
131
|
+
t.mutation(record, args({ ...event, occurredAt })),
|
|
132
|
+
).rejects.toThrow();
|
|
133
|
+
await expect(
|
|
134
|
+
t.mutation(record, { ...args(), inputJson: " ".repeat(8193) }),
|
|
135
|
+
).rejects.toThrow();
|
|
136
|
+
const first = await t.mutation(record, { ...args(), quota: 1 });
|
|
137
|
+
expect(await t.mutation(record, { ...args(), quota: 1 })).toEqual(first);
|
|
138
|
+
await expect(
|
|
139
|
+
t.mutation(record, {
|
|
140
|
+
...args({ ...event, sourceEventId: "activity_2" }),
|
|
141
|
+
quota: 1,
|
|
142
|
+
}),
|
|
143
|
+
).rejects.toThrow("Usage scope quota exhausted");
|
|
144
|
+
});
|
|
145
|
+
it("rolls back event, counter and reservation commit if scheduling fails", async () => {
|
|
146
|
+
const t = convexTest(schema, modules);
|
|
147
|
+
const reservationId = await t.run((ctx) =>
|
|
148
|
+
ctx.db.insert("usageReservations", {
|
|
149
|
+
scopeKey: JSON.stringify(scope),
|
|
150
|
+
sourceEventId: event.sourceEventId,
|
|
151
|
+
planJson: JSON.stringify(event.binding.plan),
|
|
152
|
+
scaledQuantity: "120",
|
|
153
|
+
state: "reserved",
|
|
154
|
+
}),
|
|
155
|
+
);
|
|
156
|
+
await expect(
|
|
157
|
+
t.run((ctx) => {
|
|
158
|
+
const handler = (
|
|
159
|
+
registeredRecord as unknown as {
|
|
160
|
+
_handler: (
|
|
161
|
+
ctx: MutationCtx,
|
|
162
|
+
args: {
|
|
163
|
+
inputJson: string;
|
|
164
|
+
subscriptionJson: string;
|
|
165
|
+
dispatch?: string;
|
|
166
|
+
reservationId?: import("../_generated/dataModel.js").Id<"usageReservations">;
|
|
167
|
+
},
|
|
168
|
+
) => Promise<unknown>;
|
|
169
|
+
}
|
|
170
|
+
)._handler;
|
|
171
|
+
return handler(
|
|
172
|
+
{
|
|
173
|
+
...ctx,
|
|
174
|
+
scheduler: {
|
|
175
|
+
...ctx.scheduler,
|
|
176
|
+
runAfter: async () => {
|
|
177
|
+
throw new Error("Scheduling unavailable");
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
} as MutationCtx,
|
|
181
|
+
{
|
|
182
|
+
...args(),
|
|
183
|
+
dispatch: "function://;usage/delivery:dispatch",
|
|
184
|
+
reservationId,
|
|
185
|
+
},
|
|
186
|
+
);
|
|
187
|
+
}),
|
|
188
|
+
).rejects.toThrow("Scheduling unavailable");
|
|
189
|
+
expect(await t.run((ctx) => ctx.db.query("usageEvents").take(10))).toEqual(
|
|
190
|
+
[],
|
|
191
|
+
);
|
|
192
|
+
expect(await t.run((ctx) => ctx.db.query("usageOutbox").take(10))).toEqual(
|
|
193
|
+
[],
|
|
194
|
+
);
|
|
195
|
+
expect(
|
|
196
|
+
await t.run((ctx) => ctx.db.query("usageScopeCounters").take(10)),
|
|
197
|
+
).toEqual([]);
|
|
198
|
+
expect(
|
|
199
|
+
await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
|
|
200
|
+
).toMatchObject({ state: "reserved" });
|
|
201
|
+
});
|
|
202
|
+
it("requires and atomically commits the exact prepaid reservation", async () => {
|
|
203
|
+
const t = convexTest(schema, modules);
|
|
204
|
+
const input = {
|
|
205
|
+
...event,
|
|
206
|
+
binding: {
|
|
207
|
+
...event.binding,
|
|
208
|
+
plan: {
|
|
209
|
+
...event.binding.plan,
|
|
210
|
+
model: "prepaid",
|
|
211
|
+
insufficientBalance: "reject",
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
await expect(t.mutation(record, args(input))).rejects.toThrow(
|
|
216
|
+
"A matching usage reservation is required",
|
|
217
|
+
);
|
|
218
|
+
const reservationId = await t.run((ctx) =>
|
|
219
|
+
ctx.db.insert("usageReservations", {
|
|
220
|
+
scopeKey: JSON.stringify(scope),
|
|
221
|
+
sourceEventId: input.sourceEventId,
|
|
222
|
+
planJson: JSON.stringify(input.binding.plan),
|
|
223
|
+
scaledQuantity: "120",
|
|
224
|
+
state: "reserved",
|
|
225
|
+
}),
|
|
226
|
+
);
|
|
227
|
+
await t.mutation(record, { ...args(input), reservationId });
|
|
228
|
+
expect(
|
|
229
|
+
await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
|
|
230
|
+
).toMatchObject({ state: "committed" });
|
|
231
|
+
const secondReservation = await t.run((ctx) =>
|
|
232
|
+
ctx.db.insert("usageReservations", {
|
|
233
|
+
scopeKey: JSON.stringify(scope),
|
|
234
|
+
sourceEventId: input.sourceEventId,
|
|
235
|
+
planJson: JSON.stringify(input.binding.plan),
|
|
236
|
+
scaledQuantity: "120",
|
|
237
|
+
state: "reserved",
|
|
238
|
+
}),
|
|
239
|
+
);
|
|
240
|
+
await expect(
|
|
241
|
+
t.mutation(record, { ...args(input), reservationId: secondReservation }),
|
|
242
|
+
).rejects.toThrow("Conflicting usage reservation replay");
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("pages an explicit period without exposing guessed or cross-scope events", async () => {
|
|
246
|
+
const t = convexTest(schema, modules);
|
|
247
|
+
const first = await t.mutation(record, args());
|
|
248
|
+
await t.mutation(
|
|
249
|
+
record,
|
|
250
|
+
args({ ...event, sourceEventId: "activity_2", occurredAt: now + 1 }),
|
|
251
|
+
);
|
|
252
|
+
expect(
|
|
253
|
+
await t.query(get, {
|
|
254
|
+
scope: { ...scope, customerAccount: "acct_other" },
|
|
255
|
+
eventId: first.eventId,
|
|
256
|
+
}),
|
|
257
|
+
).toBeNull();
|
|
258
|
+
const request = {
|
|
259
|
+
scope,
|
|
260
|
+
period: { start: now, end: now + 2 },
|
|
261
|
+
paginationOpts: { numItems: 1, cursor: null },
|
|
262
|
+
};
|
|
263
|
+
const page = await t.query(read, request);
|
|
264
|
+
expect(page.page).toHaveLength(1);
|
|
265
|
+
expect(page.isDone).toBe(false);
|
|
266
|
+
const next = await t.query(read, {
|
|
267
|
+
...request,
|
|
268
|
+
paginationOpts: { numItems: 1, cursor: page.continueCursor },
|
|
269
|
+
});
|
|
270
|
+
expect(next.page).toHaveLength(1);
|
|
271
|
+
expect(next.page[0].event._id).not.toBe(page.page[0].event._id);
|
|
272
|
+
const empty = await t.query(read, {
|
|
273
|
+
...request,
|
|
274
|
+
period: { start: now - 2, end: now },
|
|
275
|
+
});
|
|
276
|
+
expect(empty.page).toEqual([]);
|
|
277
|
+
await expect(
|
|
278
|
+
t.query(read, {
|
|
279
|
+
...request,
|
|
280
|
+
paginationOpts: { numItems: 101, cursor: null },
|
|
281
|
+
}),
|
|
282
|
+
).rejects.toThrow();
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("rejects a supplied missing reservation even for pay-as-you-go", async () => {
|
|
286
|
+
const t = convexTest(schema, modules);
|
|
287
|
+
const reservationId = await t.run(async (ctx) => {
|
|
288
|
+
const id = await ctx.db.insert("usageReservations", {
|
|
289
|
+
scopeKey: JSON.stringify(scope),
|
|
290
|
+
sourceEventId: event.sourceEventId,
|
|
291
|
+
planJson: JSON.stringify(event.binding.plan),
|
|
292
|
+
scaledQuantity: "120",
|
|
293
|
+
state: "reserved",
|
|
294
|
+
});
|
|
295
|
+
await ctx.db.delete("usageReservations", id);
|
|
296
|
+
return id;
|
|
297
|
+
});
|
|
298
|
+
await expect(
|
|
299
|
+
t.mutation(record, { ...args(), reservationId }),
|
|
300
|
+
).rejects.toThrow("Usage reservation is unavailable");
|
|
301
|
+
expect(await t.run((ctx) => ctx.db.query("usageEvents").take(10))).toEqual(
|
|
302
|
+
[],
|
|
303
|
+
);
|
|
304
|
+
expect(await t.run((ctx) => ctx.db.query("usageOutbox").take(10))).toEqual(
|
|
305
|
+
[],
|
|
306
|
+
);
|
|
307
|
+
expect(
|
|
308
|
+
await t.run((ctx) => ctx.db.query("usageScopeCounters").take(10)),
|
|
309
|
+
).toEqual([]);
|
|
310
|
+
});
|