@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.
Files changed (88) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +166 -32
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +83 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +134 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +67 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +3 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +4 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/boundaries.d.ts +132 -0
  16. package/dist/client/usage/boundaries.d.ts.map +1 -0
  17. package/dist/client/usage/boundaries.js +43 -0
  18. package/dist/client/usage/boundaries.js.map +1 -0
  19. package/dist/client/usage/client.d.ts +37 -0
  20. package/dist/client/usage/client.d.ts.map +1 -0
  21. package/dist/client/usage/client.js +59 -0
  22. package/dist/client/usage/client.js.map +1 -0
  23. package/dist/client/usage/contracts.d.ts +59 -0
  24. package/dist/client/usage/contracts.d.ts.map +1 -0
  25. package/dist/client/usage/contracts.js +63 -0
  26. package/dist/client/usage/contracts.js.map +1 -0
  27. package/dist/client/usage/index.d.ts +7 -0
  28. package/dist/client/usage/index.d.ts.map +1 -0
  29. package/dist/client/usage/index.js +4 -0
  30. package/dist/client/usage/index.js.map +1 -0
  31. package/dist/client/usage/records.d.ts +50 -0
  32. package/dist/client/usage/records.d.ts.map +1 -0
  33. package/dist/client/usage/records.js +54 -0
  34. package/dist/client/usage/records.js.map +1 -0
  35. package/dist/component/_generated/api.d.ts +6 -0
  36. package/dist/component/_generated/api.d.ts.map +1 -1
  37. package/dist/component/_generated/api.js.map +1 -1
  38. package/dist/component/_generated/component.d.ts +79 -0
  39. package/dist/component/_generated/component.d.ts.map +1 -1
  40. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  41. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  42. package/dist/component/earnings/triggers.d.ts +178 -16
  43. package/dist/component/earnings/triggers.d.ts.map +1 -1
  44. package/dist/component/payoutRelease/queries.d.ts +2 -2
  45. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  46. package/dist/component/schema.d.ts +67 -0
  47. package/dist/component/schema.js +5 -0
  48. package/dist/component/schema.js.map +1 -1
  49. package/dist/component/usage/helpers.d.ts +13 -0
  50. package/dist/component/usage/helpers.d.ts.map +1 -0
  51. package/dist/component/usage/helpers.js +34 -0
  52. package/dist/component/usage/helpers.js.map +1 -0
  53. package/dist/component/usage/mutations.d.ts +14 -0
  54. package/dist/component/usage/mutations.d.ts.map +1 -0
  55. package/dist/component/usage/mutations.js +124 -0
  56. package/dist/component/usage/mutations.js.map +1 -0
  57. package/dist/component/usage/queries.d.ts +62 -0
  58. package/dist/component/usage/queries.d.ts.map +1 -0
  59. package/dist/component/usage/queries.js +65 -0
  60. package/dist/component/usage/queries.js.map +1 -0
  61. package/dist/component/usage/schema.d.ts +110 -0
  62. package/dist/component/usage/schema.d.ts.map +1 -0
  63. package/dist/component/usage/schema.js +54 -0
  64. package/dist/component/usage/schema.js.map +1 -0
  65. package/docs/README.md +7 -0
  66. package/docs/development.md +26 -8
  67. package/docs/metered-usage.md +289 -37
  68. package/docs/metering-setup.md +184 -0
  69. package/docs/usage-ledger.md +62 -0
  70. package/package.json +8 -2
  71. package/src/client/index.ts +5 -0
  72. package/src/client/transferContinuation.test.ts +2 -6
  73. package/src/client/usage/boundaries.test.ts +136 -0
  74. package/src/client/usage/boundaries.ts +182 -0
  75. package/src/client/usage/client.ts +97 -0
  76. package/src/client/usage/contracts.test.ts +145 -0
  77. package/src/client/usage/contracts.ts +79 -0
  78. package/src/client/usage/index.ts +34 -0
  79. package/src/client/usage/ledger-client.test.ts +74 -0
  80. package/src/client/usage/records.ts +76 -0
  81. package/src/component/_generated/api.ts +6 -0
  82. package/src/component/_generated/component.ts +106 -0
  83. package/src/component/schema.ts +10 -0
  84. package/src/component/usage/helpers.ts +33 -0
  85. package/src/component/usage/ledger.test.ts +310 -0
  86. package/src/component/usage/mutations.ts +139 -0
  87. package/src/component/usage/queries.ts +69 -0
  88. package/src/component/usage/schema.ts +65 -0
@@ -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
+ });
@@ -0,0 +1,139 @@
1
+ import { v } from "convex/values";
2
+ import type { FunctionHandle } from "convex/server";
3
+ import { mutation } from "../_generated/server.js";
4
+ import {
5
+ prepareUsageRecord,
6
+ type PreparedUsageRecord,
7
+ } from "../../client/usage/records.js";
8
+ import { defineUsagePlan } from "../../client/usage/contracts.js";
9
+ import { assertUsageReplay } from "../../client/usage/boundaries.js";
10
+ import { scopeKey, subscriptionSnapshot } from "./helpers.js";
11
+
12
+ /** Trusted host mutation. Authenticate, authorize scope and verify native binding first. */
13
+ export const record = mutation({
14
+ args: {
15
+ inputJson: v.string(),
16
+ subscriptionJson: v.string(),
17
+ dispatch: v.optional(v.string()),
18
+ reservationId: v.optional(v.id("usageReservations")),
19
+ quota: v.optional(v.number()),
20
+ },
21
+ returns: v.object({
22
+ eventId: v.id("usageEvents"),
23
+ identity: v.string(),
24
+ acceptedAt: v.number(),
25
+ delivery: v.literal("queued"),
26
+ }),
27
+ handler: async (ctx, args) => {
28
+ if (new TextEncoder().encode(args.inputJson).length > 8192)
29
+ throw new Error("Usage payload exceeds size limit");
30
+ const event = prepareUsageRecord(JSON.parse(args.inputJson));
31
+ const key = scopeKey(event.scope);
32
+ const subscription = subscriptionSnapshot(args.subscriptionJson);
33
+ const subscriptionJson = JSON.stringify(subscription);
34
+ const existing = await ctx.db
35
+ .query("usageEvents")
36
+ .withIndex("by_identity", (q) => q.eq("identity", event.identity))
37
+ .unique();
38
+ if (existing) {
39
+ if (
40
+ args.reservationId !== undefined &&
41
+ args.reservationId !== existing.reservationId
42
+ )
43
+ throw new Error("Conflicting usage reservation replay");
44
+ assertUsageReplay(
45
+ JSON.parse(existing.recordJson) as PreparedUsageRecord,
46
+ event,
47
+ );
48
+ if (existing.subscriptionJson !== subscriptionJson)
49
+ throw new Error("Conflicting usage replay");
50
+ const outbox = await ctx.db
51
+ .query("usageOutbox")
52
+ .withIndex("by_event", (q) => q.eq("eventId", existing._id))
53
+ .unique();
54
+ if (!outbox) throw new Error("Usage outbox invariant violated");
55
+ // Acceptance is an immutable receipt; subsequent delivery is read separately.
56
+ return {
57
+ eventId: existing._id,
58
+ identity: existing.identity,
59
+ acceptedAt: existing.acceptedAt,
60
+ delivery: "queued" as const,
61
+ };
62
+ }
63
+ const now = Math.floor(Date.now() / 1000);
64
+ if (event.occurredAt < now - 35 * 86400 || event.occurredAt > now + 300)
65
+ throw new Error("Usage occurrence is outside the native delivery window");
66
+ if (
67
+ event.binding.stripePriceId !== subscription.stripePriceId ||
68
+ event.occurredAt < subscription.period.start ||
69
+ event.occurredAt >= subscription.period.end
70
+ )
71
+ throw new Error("Usage does not match its subscription period/price");
72
+ const quota = args.quota ?? 100000;
73
+ if (!Number.isInteger(quota) || quota < 1 || quota > 100000)
74
+ throw new Error("Invalid usage scope quota");
75
+ const counter = await ctx.db
76
+ .query("usageScopeCounters")
77
+ .withIndex("by_scope", (q) => q.eq("scopeKey", key))
78
+ .unique();
79
+ if ((counter?.count ?? 0) >= quota)
80
+ throw new Error("Usage scope quota exhausted");
81
+ const reservation = args.reservationId
82
+ ? await ctx.db.get("usageReservations", args.reservationId)
83
+ : null;
84
+ if (args.reservationId !== undefined && !reservation)
85
+ throw new Error("Usage reservation is unavailable");
86
+ if (event.binding.plan.model === "prepaid" && !reservation)
87
+ throw new Error("A matching usage reservation is required");
88
+ if (
89
+ reservation &&
90
+ (reservation.scopeKey !== key ||
91
+ reservation.sourceEventId !== event.sourceEventId ||
92
+ JSON.stringify(defineUsagePlan(JSON.parse(reservation.planJson))) !==
93
+ JSON.stringify(event.binding.plan) ||
94
+ reservation.scaledQuantity !== event.scaledQuantity ||
95
+ reservation.state !== "reserved")
96
+ )
97
+ throw new Error("Usage reservation does not match event");
98
+ const eventId = await ctx.db.insert("usageEvents", {
99
+ reservationId: args.reservationId,
100
+ scopeKey: key,
101
+ identity: event.identity,
102
+ recordJson: JSON.stringify(event),
103
+ subscriptionJson,
104
+ occurredAt: event.occurredAt,
105
+ acceptedAt: now,
106
+ });
107
+ await ctx.db.insert("usageOutbox", {
108
+ eventId,
109
+ scopeKey: key,
110
+ state: "queued",
111
+ attempts: 0,
112
+ nextAttemptAt: now,
113
+ providerIdentifier: `bs_usage_${eventId}`,
114
+ dispatch: args.dispatch,
115
+ });
116
+ if (counter)
117
+ await ctx.db.patch("usageScopeCounters", counter._id, {
118
+ count: counter.count + 1,
119
+ });
120
+ else await ctx.db.insert("usageScopeCounters", { scopeKey: key, count: 1 });
121
+ if (reservation)
122
+ await ctx.db.patch("usageReservations", reservation._id, {
123
+ state: "committed",
124
+ eventId,
125
+ });
126
+ if (args.dispatch)
127
+ await ctx.scheduler.runAfter(
128
+ 0,
129
+ args.dispatch as FunctionHandle<"action">,
130
+ { eventId },
131
+ );
132
+ return {
133
+ eventId,
134
+ identity: event.identity,
135
+ acceptedAt: now,
136
+ delivery: "queued" as const,
137
+ };
138
+ },
139
+ });
@@ -0,0 +1,69 @@
1
+ import { v } from "convex/values";
2
+ import {
3
+ paginationOptsValidator,
4
+ paginationResultValidator,
5
+ } from "convex/server";
6
+ import { paginator } from "convex-helpers/server/pagination";
7
+ import { query } from "../_generated/server.js";
8
+ import schema from "../schema.js";
9
+ import { eventDoc, scopeValidator, deliveryValidator } from "./schema.js";
10
+ import { scopeKey } from "./helpers.js";
11
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
12
+
13
+ const view = v.object({ event: eventDoc, delivery: deliveryValidator });
14
+ export const get = query({
15
+ args: { scope: scopeValidator, eventId: v.id("usageEvents") },
16
+ returns: v.union(view, v.null()),
17
+ handler: async (ctx, args) => {
18
+ const key = scopeKey(args.scope);
19
+ const event = await ctx.db.get("usageEvents", args.eventId);
20
+ if (!event || event.scopeKey !== key) return null;
21
+ const outbox = await ctx.db
22
+ .query("usageOutbox")
23
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
24
+ .unique();
25
+ if (!outbox) throw new Error("Usage outbox invariant violated");
26
+ return { event, delivery: outbox.state };
27
+ },
28
+ });
29
+ export const read = query({
30
+ args: {
31
+ scope: scopeValidator,
32
+ period: v.object({ start: v.number(), end: v.number() }),
33
+ paginationOpts: paginationOptsValidator,
34
+ },
35
+ returns: paginationResultValidator(view),
36
+ handler: async (ctx, args) => {
37
+ const key = scopeKey(args.scope);
38
+ const request = validateUsagePageRequest({
39
+ period: args.period,
40
+ limit: args.paginationOpts.numItems,
41
+ cursor: args.paginationOpts.cursor,
42
+ });
43
+ const result = await paginator(ctx.db, schema)
44
+ .query("usageEvents")
45
+ .withIndex("by_scope_time", (q) =>
46
+ q
47
+ .eq("scopeKey", key)
48
+ .gte("occurredAt", request.period.start)
49
+ .lt("occurredAt", request.period.end),
50
+ )
51
+ .order("desc")
52
+ .paginate({
53
+ ...args.paginationOpts,
54
+ maximumRowsRead: 200,
55
+ maximumBytesRead: 1000000,
56
+ });
57
+ const page = await Promise.all(
58
+ result.page.map(async (event) => {
59
+ const outbox = await ctx.db
60
+ .query("usageOutbox")
61
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
62
+ .unique();
63
+ if (!outbox) throw new Error("Usage outbox invariant violated");
64
+ return { event, delivery: outbox.state };
65
+ }),
66
+ );
67
+ return { ...result, page };
68
+ },
69
+ });
@@ -0,0 +1,65 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ export const scopeValidator = v.object({
5
+ stripeAccountId: v.string(),
6
+ customerAccount: v.string(),
7
+ meterId: v.string(),
8
+ livemode: v.boolean(),
9
+ });
10
+ export const deliveryValidator = v.union(
11
+ v.literal("queued"),
12
+ v.literal("sending"),
13
+ v.literal("provider_accepted"),
14
+ v.literal("rejected"),
15
+ v.literal("unknown"),
16
+ v.literal("held"),
17
+ );
18
+ export const eventFields = {
19
+ reservationId: v.optional(v.id("usageReservations")),
20
+ scopeKey: v.string(),
21
+ identity: v.string(),
22
+ recordJson: v.string(),
23
+ subscriptionJson: v.string(),
24
+ occurredAt: v.number(),
25
+ acceptedAt: v.number(),
26
+ };
27
+ export const eventDoc = v.object({
28
+ _id: v.id("usageEvents"),
29
+ _creationTime: v.number(),
30
+ ...eventFields,
31
+ });
32
+ export const usageEventsTable = defineTable(eventFields)
33
+ .index("by_identity", ["identity"])
34
+ .index("by_scope_time", ["scopeKey", "occurredAt"]);
35
+ export const usageOutboxTable = defineTable({
36
+ eventId: v.id("usageEvents"),
37
+ scopeKey: v.string(),
38
+ state: deliveryValidator,
39
+ attempts: v.number(),
40
+ nextAttemptAt: v.number(),
41
+ providerIdentifier: v.string(),
42
+ dispatch: v.optional(v.string()),
43
+ })
44
+ .index("by_event", ["eventId"])
45
+ .index("by_state_next", ["state", "nextAttemptAt"])
46
+ .index("by_scope_state", ["scopeKey", "state"]);
47
+ export const usageScopeCountersTable = defineTable({
48
+ scopeKey: v.string(),
49
+ count: v.number(),
50
+ }).index("by_scope", ["scopeKey"]);
51
+ // Only accounting APIs may create reservations. There is no public arbitrary
52
+ // reservation/grant insertion API. Acceptance commits a matching reservation
53
+ // in the same transaction as its immutable event and outbox intent.
54
+ export const usageReservationsTable = defineTable({
55
+ scopeKey: v.string(),
56
+ sourceEventId: v.string(),
57
+ planJson: v.string(),
58
+ scaledQuantity: v.string(),
59
+ state: v.union(
60
+ v.literal("reserved"),
61
+ v.literal("committed"),
62
+ v.literal("released"),
63
+ ),
64
+ eventId: v.optional(v.id("usageEvents")),
65
+ }).index("by_scope_source", ["scopeKey", "sourceEventId"]);