@fantastic.dev/better-stripe 0.54.0 → 0.55.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 (122) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +112 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +40 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +112 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +40 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +5 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/usage/client.d.ts +2 -2
  14. package/dist/client/usage/client.d.ts.map +1 -1
  15. package/dist/client/usage/client.js +2 -2
  16. package/dist/client/usage/client.js.map +1 -1
  17. package/dist/client/usage/index.d.ts +5 -0
  18. package/dist/client/usage/index.d.ts.map +1 -1
  19. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  20. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  21. package/dist/client/usage/invoiceObservation.js +157 -0
  22. package/dist/client/usage/invoiceObservation.js.map +1 -0
  23. package/dist/client/usage/observationClient.d.ts +83 -0
  24. package/dist/client/usage/observationClient.d.ts.map +1 -0
  25. package/dist/client/usage/observationClient.js +157 -0
  26. package/dist/client/usage/observationClient.js.map +1 -0
  27. package/dist/client/usage/observationTypes.d.ts +63 -0
  28. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  29. package/dist/client/usage/observationTypes.js +59 -0
  30. package/dist/client/usage/observationTypes.js.map +1 -0
  31. package/dist/client/usage/providerObservation.d.ts +4 -0
  32. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  33. package/dist/client/usage/providerObservation.js +96 -0
  34. package/dist/client/usage/providerObservation.js.map +1 -0
  35. package/dist/client/usage/reconciliation.d.ts +12 -0
  36. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  37. package/dist/client/usage/reconciliation.js +48 -0
  38. package/dist/client/usage/reconciliation.js.map +1 -0
  39. package/dist/client/usage/summary.d.ts +50 -0
  40. package/dist/client/usage/summary.d.ts.map +1 -0
  41. package/dist/client/usage/summary.js +110 -0
  42. package/dist/client/usage/summary.js.map +1 -0
  43. package/dist/component/_generated/api.d.ts +8 -0
  44. package/dist/component/_generated/api.d.ts.map +1 -1
  45. package/dist/component/_generated/api.js.map +1 -1
  46. package/dist/component/_generated/component.d.ts +95 -0
  47. package/dist/component/_generated/component.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  51. package/dist/component/earnings/triggers.d.ts +104 -18
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +40 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +7 -2
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usageDelivery/fields.d.ts +1 -0
  60. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  61. package/dist/component/usageDelivery/fields.js +1 -0
  62. package/dist/component/usageDelivery/fields.js.map +1 -1
  63. package/dist/component/usageDelivery/helpers.d.ts +1 -0
  64. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  65. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  66. package/dist/component/usageDelivery/mutations.js +8 -1
  67. package/dist/component/usageDelivery/mutations.js.map +1 -1
  68. package/dist/component/usageDelivery/queries.d.ts +2 -0
  69. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  70. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  71. package/dist/component/usageDelivery/steps.js +8 -1
  72. package/dist/component/usageDelivery/steps.js.map +1 -1
  73. package/dist/component/usageObservations/helpers.d.ts +38 -0
  74. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  75. package/dist/component/usageObservations/helpers.js +80 -0
  76. package/dist/component/usageObservations/helpers.js.map +1 -0
  77. package/dist/component/usageObservations/history.d.ts +6 -0
  78. package/dist/component/usageObservations/history.d.ts.map +1 -0
  79. package/dist/component/usageObservations/history.js +29 -0
  80. package/dist/component/usageObservations/history.js.map +1 -0
  81. package/dist/component/usageObservations/mutations.d.ts +6 -0
  82. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  83. package/dist/component/usageObservations/mutations.js +39 -0
  84. package/dist/component/usageObservations/mutations.js.map +1 -0
  85. package/dist/component/usageObservations/queries.d.ts +78 -0
  86. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  87. package/dist/component/usageObservations/queries.js +131 -0
  88. package/dist/component/usageObservations/queries.js.map +1 -0
  89. package/dist/component/usageObservations/schema.d.ts +72 -0
  90. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  91. package/dist/component/usageObservations/schema.js +29 -0
  92. package/dist/component/usageObservations/schema.js.map +1 -0
  93. package/docs/README.md +2 -0
  94. package/docs/metering-setup.md +2 -0
  95. package/docs/usage-observations.md +152 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +18 -0
  98. package/src/client/usage/client.ts +2 -2
  99. package/src/client/usage/index.ts +18 -0
  100. package/src/client/usage/invoiceObservation.test.ts +195 -0
  101. package/src/client/usage/invoiceObservation.ts +203 -0
  102. package/src/client/usage/observationClient.ts +233 -0
  103. package/src/client/usage/observationTypes.ts +101 -0
  104. package/src/client/usage/providerObservation.test.ts +207 -0
  105. package/src/client/usage/providerObservation.ts +124 -0
  106. package/src/client/usage/reconciliation.test.ts +117 -0
  107. package/src/client/usage/reconciliation.ts +86 -0
  108. package/src/client/usage/summary.test.ts +222 -0
  109. package/src/client/usage/summary.ts +188 -0
  110. package/src/component/_generated/api.ts +8 -0
  111. package/src/component/_generated/component.ts +135 -0
  112. package/src/component/schema.ts +6 -0
  113. package/src/component/usageDelivery/fields.ts +1 -0
  114. package/src/component/usageDelivery/mutations.ts +26 -1
  115. package/src/component/usageDelivery/steps.ts +39 -1
  116. package/src/component/usageObservations/helpers.ts +95 -0
  117. package/src/component/usageObservations/history.test.ts +87 -0
  118. package/src/component/usageObservations/history.ts +39 -0
  119. package/src/component/usageObservations/mutations.ts +39 -0
  120. package/src/component/usageObservations/queries.test.ts +162 -0
  121. package/src/component/usageObservations/queries.ts +145 -0
  122. package/src/component/usageObservations/schema.ts +40 -0
@@ -1,3 +1,4 @@
1
+ import { appendDeliveryHistory } from "../usageObservations/history.js";
1
2
  import { internalMutation } from "../_generated/server.js";
2
3
  import { v } from "convex/values";
3
4
  import { refFields, request, status } from "./schema.js";
@@ -30,6 +31,13 @@ export const claim = internalMutation({
30
31
  state: outbox.firstSendAt === undefined ? "held" : "unknown",
31
32
  reason: "delivery_window_expired",
32
33
  });
34
+ await appendDeliveryHistory(
35
+ ctx,
36
+ args.eventId,
37
+ "window_expired",
38
+ outbox.attempts,
39
+ `window:${outbox.attempts}`,
40
+ );
33
41
  return { kind: "done" as const };
34
42
  }
35
43
  if (outbox.state === "sending") {
@@ -45,6 +53,13 @@ export const claim = internalMutation({
45
53
  state: "unknown",
46
54
  reason: "provider_outcome_unknown",
47
55
  });
56
+ await appendDeliveryHistory(
57
+ ctx,
58
+ args.eventId,
59
+ "unknown",
60
+ outbox.attempts,
61
+ `result:${outbox.attempts}:unknown`,
62
+ );
48
63
  return { kind: "done" as const };
49
64
  }
50
65
  const keys = lockKeys(record);
@@ -85,6 +100,13 @@ export const claim = internalMutation({
85
100
  leaseUntil: now + 900,
86
101
  reason: undefined,
87
102
  });
103
+ await appendDeliveryHistory(
104
+ ctx,
105
+ args.eventId,
106
+ "started",
107
+ attempt,
108
+ `started:${attempt}`,
109
+ );
88
110
  return {
89
111
  kind: "ready" as const,
90
112
  request: {
@@ -153,6 +175,14 @@ export const save = internalMutation({
153
175
  eventId: undefined,
154
176
  });
155
177
  }
178
+ await appendDeliveryHistory(
179
+ ctx,
180
+ args.eventId,
181
+ result.status,
182
+ args.attempt,
183
+ `result:${args.attempt}:${result.status}`,
184
+ result.status === "accepted" ? result.created : undefined,
185
+ );
156
186
  return statusOf((await read(ctx, args)).outbox);
157
187
  },
158
188
  });
@@ -161,11 +191,19 @@ export const exhaust = internalMutation({
161
191
  returns: v.null(),
162
192
  handler: async (ctx, args) => {
163
193
  const { outbox } = await read(ctx, args);
164
- if (outbox.state === "queued")
194
+ if (outbox.state === "queued") {
165
195
  await ctx.db.patch("usageOutbox", outbox._id, {
166
196
  state: "held",
167
197
  reason: "retry_exhausted",
168
198
  });
199
+ await appendDeliveryHistory(
200
+ ctx,
201
+ args.eventId,
202
+ "retry_exhausted",
203
+ outbox.attempts,
204
+ `exhaust:${outbox.attempts}`,
205
+ );
206
+ }
169
207
  return null;
170
208
  },
171
209
  });
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
3
+ import {
4
+ observationOptions,
5
+ type UsageObservationOptions,
6
+ } from "../../client/usage/observationTypes.js";
7
+ import { scopeKey } from "../usage/helpers.js";
8
+ import { decimalFromScaled } from "../../client/usage/summary.js";
9
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
10
+ const period = z.strictObject({ start: integer, end: integer });
11
+ const scaled = z.string().regex(/^\d{1,30}$/),
12
+ quantity = z.string().regex(/^\d{1,30}(\.\d{1,6})?$/);
13
+ const value = z.strictObject({
14
+ period,
15
+ quantity,
16
+ scaledQuantity: scaled,
17
+ complete: z.boolean(),
18
+ nextCursor: z.string().max(2048).nullable(),
19
+ aggregationLagPossible: z.literal(true),
20
+ stale: z.literal(false),
21
+ entries: z
22
+ .array(
23
+ z.strictObject({
24
+ id: z.string().min(1).max(2048),
25
+ start: integer,
26
+ end: integer,
27
+ scaledQuantity: scaled,
28
+ }),
29
+ )
30
+ .max(100),
31
+ });
32
+ const availability = z.union([
33
+ z.strictObject({
34
+ status: z.literal("available"),
35
+ observedAt: integer,
36
+ value,
37
+ }),
38
+ z.strictObject({
39
+ status: z.enum(["unavailable", "unsupported"]),
40
+ reason: z.enum([
41
+ "minute_alignment_required",
42
+ "provider_binding_mismatch",
43
+ "unsupported_scope",
44
+ "aggregation_pending",
45
+ "provider_history_incomplete",
46
+ "provider_precision_unsupported",
47
+ "provider_unavailable",
48
+ ]),
49
+ retryable: z.boolean(),
50
+ }),
51
+ ]);
52
+ export async function source(json: string) {
53
+ if (new TextEncoder().encode(json).length > 8192)
54
+ throw new Error("Usage observation source exceeds limit");
55
+ const opts = observationOptions(JSON.parse(json) as UsageObservationOptions);
56
+ const sourceJson = JSON.stringify(opts);
57
+ return {
58
+ opts,
59
+ sourceJson,
60
+ scopeKey: scopeKey(opts.scope),
61
+ key: await canonicalFingerprint(opts),
62
+ };
63
+ }
64
+ export function observation(
65
+ json: string,
66
+ opts: ReturnType<typeof observationOptions>,
67
+ ) {
68
+ if (new TextEncoder().encode(json).length > 65536)
69
+ throw new Error("Invalid usage provider observation");
70
+ const parsed = availability.safeParse(JSON.parse(json));
71
+ if (!parsed.success) throw new Error("Invalid usage provider observation");
72
+ const result = parsed.data;
73
+ if (result.status === "available") {
74
+ const v = result.value;
75
+ if (
76
+ result.observedAt > Date.now() / 1000 + 300 ||
77
+ JSON.stringify(v.period) !== JSON.stringify(opts.period) ||
78
+ v.quantity !==
79
+ decimalFromScaled(
80
+ BigInt(v.scaledQuantity),
81
+ opts.binding.plan.unit.precision,
82
+ ) ||
83
+ v.entries.reduce((sum, e) => sum + BigInt(e.scaledQuantity), 0n) !==
84
+ BigInt(v.scaledQuantity) ||
85
+ v.entries.some(
86
+ (e) =>
87
+ e.start < opts.period.start ||
88
+ e.end > opts.period.end ||
89
+ e.end <= e.start,
90
+ )
91
+ )
92
+ throw new Error("Invalid usage provider observation");
93
+ }
94
+ return JSON.stringify(result);
95
+ }
@@ -0,0 +1,87 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ const ref = (name: string) => makeFunctionReference<"mutation">(name);
6
+ it("retains paged delivery attempts and outcomes without admitting a foreign scope", async () => {
7
+ const t = convexTest(schema, modules),
8
+ now = Math.floor(Date.now() / 1000);
9
+ const scope = {
10
+ stripeAccountId: "acct_platform",
11
+ customerAccount: "acct_buyer",
12
+ meterId: "mtr_calls",
13
+ livemode: false,
14
+ };
15
+ const receipt = await t.mutation(ref("usage/mutations:record"), {
16
+ inputJson: JSON.stringify({
17
+ scope,
18
+ binding: {
19
+ stripeCustomerId: "cus_buyer",
20
+ stripePriceId: "price_calls",
21
+ eventName: "calls",
22
+ plan: {
23
+ key: "calls",
24
+ version: "v1",
25
+ model: "pay_as_you_go",
26
+ unit: { name: "call", precision: 0 },
27
+ rate: { currency: "usd", unitAmountDecimal: "2" },
28
+ },
29
+ },
30
+ sourceEventId: "one",
31
+ quantity: "1",
32
+ occurredAt: now,
33
+ }),
34
+ subscriptionJson: JSON.stringify({
35
+ subscriptionId: "sub_calls",
36
+ subscriptionItemId: "si_calls",
37
+ stripePriceId: "price_calls",
38
+ period: { start: now - 1, end: now + 86400 },
39
+ interval: "month",
40
+ }),
41
+ });
42
+ await t.run(async (ctx) => {
43
+ const row = (await ctx.db.query("usageOutbox").first())!;
44
+ await ctx.db.patch("usageOutbox", row._id, { definitionVersion: 1 });
45
+ });
46
+ const claimed = await t.mutation(ref("usageDelivery/steps:claim"), {
47
+ scope,
48
+ eventId: receipt.eventId,
49
+ });
50
+ await t.mutation(ref("usageDelivery/steps:save"), {
51
+ ...claimed.request,
52
+ outcome: { status: "accepted", created: now },
53
+ });
54
+ const history = makeFunctionReference<"query">(
55
+ "usageObservations/queries:deliveryHistory",
56
+ );
57
+ const args = {
58
+ scope,
59
+ eventId: receipt.eventId,
60
+ paginationOpts: { cursor: null, numItems: 1 },
61
+ };
62
+ const first = await t.query(history, args);
63
+ expect(first).toMatchObject({
64
+ page: [{ phase: "started", attempt: 1, sequence: 1 }],
65
+ isDone: false,
66
+ legacyHistoryMissing: false,
67
+ });
68
+ const second = await t.query(history, {
69
+ ...args,
70
+ paginationOpts: { cursor: first.continueCursor, numItems: 1 },
71
+ });
72
+ expect(second).toMatchObject({
73
+ page: [{ phase: "accepted", attempt: 1, sequence: 2 }],
74
+ });
75
+ expect(
76
+ await t.query(history, {
77
+ ...args,
78
+ paginationOpts: { cursor: second.continueCursor, numItems: 1 },
79
+ }),
80
+ ).toMatchObject({ page: [], isDone: true });
81
+ await expect(
82
+ t.query(history, {
83
+ ...args,
84
+ scope: { ...scope, customerAccount: "acct_other" },
85
+ }),
86
+ ).rejects.toThrow();
87
+ });
@@ -0,0 +1,39 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import type { Id } from "../_generated/dataModel.js";
3
+ import type { Infer } from "convex/values";
4
+ import type { historyPhase } from "./schema.js";
5
+ export async function appendDeliveryHistory(
6
+ ctx: MutationCtx,
7
+ eventId: Id<"usageEvents">,
8
+ phase: Infer<typeof historyPhase>,
9
+ attempt: number,
10
+ identity: string,
11
+ created?: number,
12
+ ) {
13
+ const prior = await ctx.db
14
+ .query("usageDeliveryHistory")
15
+ .withIndex("by_event_identity", (q) =>
16
+ q.eq("eventId", eventId).eq("identity", identity),
17
+ )
18
+ .unique();
19
+ if (prior) return;
20
+ const outbox = await ctx.db
21
+ .query("usageOutbox")
22
+ .withIndex("by_event", (q) => q.eq("eventId", eventId))
23
+ .unique();
24
+ if (!outbox) throw new Error("Usage history event unavailable");
25
+ const sequence = (outbox.historySequence ?? 0) + 1;
26
+ if (!Number.isSafeInteger(sequence))
27
+ throw new Error("Usage history sequence exhausted");
28
+ await ctx.db.insert("usageDeliveryHistory", {
29
+ eventId,
30
+ scopeKey: outbox.scopeKey,
31
+ sequence,
32
+ attempt,
33
+ phase,
34
+ identity,
35
+ recordedAt: Math.floor(Date.now() / 1000),
36
+ ...(created !== undefined ? { created } : {}),
37
+ });
38
+ await ctx.db.patch("usageOutbox", outbox._id, { historySequence: sequence });
39
+ }
@@ -0,0 +1,39 @@
1
+ import { mutation } from "../_generated/server.js";
2
+ import { v } from "convex/values";
3
+ import { source, observation } from "./helpers.js";
4
+ export const save = mutation({
5
+ args: {
6
+ sourceJson: v.string(),
7
+ observationJson: v.string(),
8
+ startedAt: v.number(),
9
+ },
10
+ returns: v.null(),
11
+ handler: async (ctx, args) => {
12
+ if (
13
+ !Number.isSafeInteger(args.startedAt) ||
14
+ args.startedAt < 0 ||
15
+ args.startedAt > Date.now() + 300000
16
+ )
17
+ throw new Error("Invalid observation start time");
18
+ const binding = await source(args.sourceJson),
19
+ observationJson = observation(args.observationJson, binding.opts);
20
+ const prior = await ctx.db
21
+ .query("usageProviderObservations")
22
+ .withIndex("by_key", (q) => q.eq("key", binding.key))
23
+ .unique();
24
+ if (prior && prior.sourceJson !== binding.sourceJson)
25
+ throw new Error("Usage observation binding conflict");
26
+ if (prior && prior.startedAt > args.startedAt) return null;
27
+ const fields = {
28
+ key: binding.key,
29
+ scopeKey: binding.scopeKey,
30
+ sourceJson: binding.sourceJson,
31
+ observationJson,
32
+ startedAt: args.startedAt,
33
+ };
34
+ if (prior)
35
+ await ctx.db.patch("usageProviderObservations", prior._id, fields);
36
+ else await ctx.db.insert("usageProviderObservations", fields);
37
+ return null;
38
+ },
39
+ });
@@ -0,0 +1,162 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ const summary = makeFunctionReference<"query">(
6
+ "usageObservations/queries:summary",
7
+ ),
8
+ record = makeFunctionReference<"mutation">("usage/mutations:record");
9
+ it("bounds local summaries and never includes another scope", async () => {
10
+ const t = convexTest(schema, modules),
11
+ now = Math.floor(Date.now() / 1000),
12
+ period = { start: now - 5, end: now + 100 };
13
+ const scope = {
14
+ stripeAccountId: "acct_platform",
15
+ customerAccount: "acct_buyer",
16
+ meterId: "mtr_calls",
17
+ livemode: false,
18
+ };
19
+ for (const sourceEventId of ["a", "b"])
20
+ await t.mutation(record, {
21
+ inputJson: JSON.stringify({
22
+ scope,
23
+ binding: {
24
+ stripeCustomerId: "cus_buyer",
25
+ stripePriceId: "price_calls",
26
+ eventName: "calls",
27
+ plan: {
28
+ key: "calls",
29
+ version: "v1",
30
+ model: "pay_as_you_go",
31
+ unit: { name: "call", precision: 0 },
32
+ rate: { currency: "usd", unitAmountDecimal: "2" },
33
+ },
34
+ },
35
+ sourceEventId,
36
+ quantity: "1",
37
+ occurredAt: now,
38
+ }),
39
+ subscriptionJson: JSON.stringify({
40
+ subscriptionId: "sub_calls",
41
+ subscriptionItemId: "si_calls",
42
+ stripePriceId: "price_calls",
43
+ period,
44
+ interval: "month",
45
+ }),
46
+ });
47
+ expect(
48
+ JSON.parse(await t.query(summary, { scope, period, maxRecords: 1 })),
49
+ ).toMatchObject({
50
+ complete: false,
51
+ eventCount: 1,
52
+ groups: [
53
+ {
54
+ acceptedQuantity: "1",
55
+ estimate: { status: "unavailable", reason: "local_history_incomplete" },
56
+ },
57
+ ],
58
+ });
59
+ expect(
60
+ JSON.parse(
61
+ await t.query(summary, {
62
+ scope: { ...scope, customerAccount: "acct_other" },
63
+ period,
64
+ maxRecords: 10,
65
+ }),
66
+ ),
67
+ ).toMatchObject({ complete: true, eventCount: 0, groups: [] });
68
+ await expect(
69
+ t.query(summary, { scope, period, maxRecords: 501 }),
70
+ ).rejects.toThrow();
71
+ });
72
+
73
+ it("retains immutable scoped cache bindings and rejects stale projections and raw payloads", async () => {
74
+ const t = convexTest(schema, modules),
75
+ now = Math.floor(Date.now() / 1000),
76
+ period = { start: 600, end: 1200 };
77
+ const source = {
78
+ scope: {
79
+ stripeAccountId: "acct_platform",
80
+ customerAccount: "acct_buyer",
81
+ meterId: "mtr_calls",
82
+ livemode: false,
83
+ },
84
+ binding: {
85
+ stripeCustomerId: "cus_buyer",
86
+ stripePriceId: "price_calls",
87
+ eventName: "calls",
88
+ plan: {
89
+ key: "calls",
90
+ version: "v1",
91
+ model: "pay_as_you_go",
92
+ unit: { name: "call", precision: 0 },
93
+ rate: { currency: "usd", unitAmountDecimal: "2" },
94
+ },
95
+ },
96
+ subscription: {
97
+ subscriptionId: "sub_calls",
98
+ subscriptionItemId: "si_calls",
99
+ stripePriceId: "price_calls",
100
+ period,
101
+ interval: "month",
102
+ },
103
+ period,
104
+ limit: 100,
105
+ cursor: null,
106
+ };
107
+ const save = makeFunctionReference<"mutation">(
108
+ "usageObservations/mutations:save",
109
+ ),
110
+ cached = makeFunctionReference<"query">("usageObservations/queries:cached");
111
+ const observation = {
112
+ status: "available",
113
+ observedAt: now,
114
+ value: {
115
+ period,
116
+ quantity: "1",
117
+ scaledQuantity: "1",
118
+ complete: true,
119
+ nextCursor: null,
120
+ aggregationLagPossible: true,
121
+ stale: false,
122
+ entries: [
123
+ { id: "mtrusg_one", start: 600, end: 1200, scaledQuantity: "1" },
124
+ ],
125
+ },
126
+ };
127
+ const args = {
128
+ sourceJson: JSON.stringify(source),
129
+ observationJson: JSON.stringify(observation),
130
+ startedAt: Date.now(),
131
+ };
132
+ await t.mutation(save, args);
133
+ await t.mutation(save, {
134
+ ...args,
135
+ startedAt: args.startedAt - 1,
136
+ observationJson: JSON.stringify({
137
+ status: "unavailable",
138
+ reason: "provider_unavailable",
139
+ retryable: true,
140
+ }),
141
+ });
142
+ expect(
143
+ JSON.parse(await t.query(cached, { sourceJson: args.sourceJson })),
144
+ ).toMatchObject({ status: "available", value: { quantity: "1" } });
145
+ expect(
146
+ await t.query(cached, {
147
+ sourceJson: JSON.stringify({
148
+ ...source,
149
+ scope: { ...source.scope, customerAccount: "acct_other" },
150
+ }),
151
+ }),
152
+ ).toBeNull();
153
+ await expect(
154
+ t.mutation(save, {
155
+ ...args,
156
+ observationJson: JSON.stringify({
157
+ ...observation,
158
+ privateMetadata: "private",
159
+ }),
160
+ }),
161
+ ).rejects.toThrow("Invalid usage provider observation");
162
+ });
@@ -0,0 +1,145 @@
1
+ import {
2
+ paginationOptsValidator,
3
+ paginationResultValidator,
4
+ } from "convex/server";
5
+ import { paginator } from "convex-helpers/server/pagination";
6
+ import schema from "../schema.js";
7
+ import { refFields } from "../usageDelivery/schema.js";
8
+ import { read } from "../usageDelivery/helpers.js";
9
+ import { historyDoc } from "./schema.js";
10
+ import { errorDoc } from "../usageDelivery/fields.js";
11
+ import { source } from "./helpers.js";
12
+ import { query } from "../_generated/server.js";
13
+ import { v } from "convex/values";
14
+ import { scopeValidator } from "../usage/schema.js";
15
+ import { scopeKey, subscriptionSnapshot } from "../usage/helpers.js";
16
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
17
+ import { summarizeUsageRecords } from "../../client/usage/summary.js";
18
+ import type { PreparedUsageRecord } from "../../client/usage/records.js";
19
+ export const summary = query({
20
+ args: {
21
+ scope: scopeValidator,
22
+ period: v.object({ start: v.number(), end: v.number() }),
23
+ maxRecords: v.number(),
24
+ },
25
+ returns: v.string(),
26
+ handler: async (ctx, args) => {
27
+ const key = scopeKey(args.scope);
28
+ validateUsagePageRequest({ period: args.period, limit: 1, cursor: null });
29
+ if (
30
+ !Number.isInteger(args.maxRecords) ||
31
+ args.maxRecords < 1 ||
32
+ args.maxRecords > 500
33
+ )
34
+ throw new Error("Usage summary read budget must be 1–500");
35
+ const rows = await ctx.db
36
+ .query("usageEvents")
37
+ .withIndex("by_scope_time", (q) =>
38
+ q
39
+ .eq("scopeKey", key)
40
+ .gte("occurredAt", args.period.start)
41
+ .lt("occurredAt", args.period.end),
42
+ )
43
+ .take(args.maxRecords + 1);
44
+ const views = await Promise.all(
45
+ rows.slice(0, args.maxRecords).map(async (event) => {
46
+ const [outbox, error] = await Promise.all([
47
+ ctx.db
48
+ .query("usageOutbox")
49
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
50
+ .unique(),
51
+ ctx.db
52
+ .query("usageDeliveryErrors")
53
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
54
+ .first(),
55
+ ]);
56
+ if (!outbox) throw new Error("Usage outbox invariant violated");
57
+ return {
58
+ record: JSON.parse(event.recordJson) as PreparedUsageRecord,
59
+ subscription: subscriptionSnapshot(event.subscriptionJson),
60
+ delivery: outbox.state,
61
+ hasValidationError: error !== null,
62
+ };
63
+ }),
64
+ );
65
+ return JSON.stringify(
66
+ summarizeUsageRecords(views, {
67
+ period: args.period,
68
+ observedAt: Math.floor(Date.now() / 1000),
69
+ complete: rows.length <= args.maxRecords,
70
+ }),
71
+ );
72
+ },
73
+ });
74
+
75
+ export const cached = query({
76
+ args: { sourceJson: v.string() },
77
+ returns: v.union(v.string(), v.null()),
78
+ handler: async (ctx, args) => {
79
+ const binding = await source(args.sourceJson);
80
+ const row = await ctx.db
81
+ .query("usageProviderObservations")
82
+ .withIndex("by_key", (q) => q.eq("key", binding.key))
83
+ .unique();
84
+ return row &&
85
+ row.scopeKey === binding.scopeKey &&
86
+ row.sourceJson === binding.sourceJson
87
+ ? row.observationJson
88
+ : null;
89
+ },
90
+ });
91
+
92
+ function validate(numItems: number, cursor: string | null) {
93
+ validateUsagePageRequest({
94
+ period: { start: 0, end: 1 },
95
+ limit: numItems,
96
+ cursor,
97
+ });
98
+ }
99
+ const paginated = paginationResultValidator(historyDoc);
100
+ export const deliveryHistory = query({
101
+ args: { ...refFields, paginationOpts: paginationOptsValidator },
102
+ returns: v.object({ ...paginated.fields, legacyHistoryMissing: v.boolean() }),
103
+ handler: async (ctx, args) => {
104
+ const { outbox } = await read(ctx, args);
105
+ validate(args.paginationOpts.numItems, args.paginationOpts.cursor);
106
+ const [page, first] = await Promise.all([
107
+ paginator(ctx.db, schema)
108
+ .query("usageDeliveryHistory")
109
+ .withIndex("by_event_sequence", (q) => q.eq("eventId", args.eventId))
110
+ .order("asc")
111
+ .paginate({
112
+ ...args.paginationOpts,
113
+ maximumRowsRead: 200,
114
+ maximumBytesRead: 1000000,
115
+ }),
116
+ ctx.db
117
+ .query("usageDeliveryHistory")
118
+ .withIndex("by_event_identity", (q) =>
119
+ q.eq("eventId", args.eventId).eq("identity", "started:1"),
120
+ )
121
+ .unique(),
122
+ ]);
123
+ return {
124
+ ...page,
125
+ legacyHistoryMissing: outbox.attempts > 0 && first === null,
126
+ };
127
+ },
128
+ });
129
+ export const validationHistory = query({
130
+ args: { ...refFields, paginationOpts: paginationOptsValidator },
131
+ returns: paginationResultValidator(errorDoc),
132
+ handler: async (ctx, args) => {
133
+ await read(ctx, args);
134
+ validate(args.paginationOpts.numItems, args.paginationOpts.cursor);
135
+ return paginator(ctx.db, schema)
136
+ .query("usageDeliveryErrors")
137
+ .withIndex("by_event", (q) => q.eq("eventId", args.eventId))
138
+ .order("desc")
139
+ .paginate({
140
+ ...args.paginationOpts,
141
+ maximumRowsRead: 200,
142
+ maximumBytesRead: 1000000,
143
+ });
144
+ },
145
+ });
@@ -0,0 +1,40 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const observationsTable = defineTable({
4
+ key: v.string(),
5
+ scopeKey: v.string(),
6
+ sourceJson: v.string(),
7
+ observationJson: v.string(),
8
+ startedAt: v.number(),
9
+ }).index("by_key", ["key"]);
10
+
11
+ export const historyPhase = v.union(
12
+ v.literal("started"),
13
+ v.literal("accepted"),
14
+ v.literal("rate_limited"),
15
+ v.literal("unavailable"),
16
+ v.literal("unknown"),
17
+ v.literal("rejected"),
18
+ v.literal("held"),
19
+ v.literal("resumed"),
20
+ v.literal("window_expired"),
21
+ v.literal("retry_exhausted"),
22
+ );
23
+ export const historyFields = {
24
+ scopeKey: v.string(),
25
+ eventId: v.id("usageEvents"),
26
+ sequence: v.number(),
27
+ attempt: v.number(),
28
+ phase: historyPhase,
29
+ identity: v.string(),
30
+ recordedAt: v.number(),
31
+ created: v.optional(v.number()),
32
+ };
33
+ export const historyDoc = v.object({
34
+ _id: v.id("usageDeliveryHistory"),
35
+ _creationTime: v.number(),
36
+ ...historyFields,
37
+ });
38
+ export const historyTable = defineTable(historyFields)
39
+ .index("by_event_sequence", ["eventId", "sequence"])
40
+ .index("by_event_identity", ["eventId", "identity"]);