@fantastic.dev/better-stripe 0.53.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 (184) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +226 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +97 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +226 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +97 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +8 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/client.d.ts +2 -2
  16. package/dist/client/usage/client.d.ts.map +1 -1
  17. package/dist/client/usage/client.js +3 -3
  18. package/dist/client/usage/client.js.map +1 -1
  19. package/dist/client/usage/deliveryClient.d.ts +64 -0
  20. package/dist/client/usage/deliveryClient.d.ts.map +1 -0
  21. package/dist/client/usage/deliveryClient.js +60 -0
  22. package/dist/client/usage/deliveryClient.js.map +1 -0
  23. package/dist/client/usage/deliveryProtocol.d.ts +130 -0
  24. package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
  25. package/dist/client/usage/deliveryProtocol.js +21 -0
  26. package/dist/client/usage/deliveryProtocol.js.map +1 -0
  27. package/dist/client/usage/deliveryProvider.d.ts +32 -0
  28. package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
  29. package/dist/client/usage/deliveryProvider.js +127 -0
  30. package/dist/client/usage/deliveryProvider.js.map +1 -0
  31. package/dist/client/usage/index.d.ts +8 -0
  32. package/dist/client/usage/index.d.ts.map +1 -1
  33. package/dist/client/usage/index.js +1 -0
  34. package/dist/client/usage/index.js.map +1 -1
  35. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  36. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  37. package/dist/client/usage/invoiceObservation.js +157 -0
  38. package/dist/client/usage/invoiceObservation.js.map +1 -0
  39. package/dist/client/usage/observationClient.d.ts +83 -0
  40. package/dist/client/usage/observationClient.d.ts.map +1 -0
  41. package/dist/client/usage/observationClient.js +157 -0
  42. package/dist/client/usage/observationClient.js.map +1 -0
  43. package/dist/client/usage/observationTypes.d.ts +63 -0
  44. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  45. package/dist/client/usage/observationTypes.js +59 -0
  46. package/dist/client/usage/observationTypes.js.map +1 -0
  47. package/dist/client/usage/providerObservation.d.ts +4 -0
  48. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  49. package/dist/client/usage/providerObservation.js +96 -0
  50. package/dist/client/usage/providerObservation.js.map +1 -0
  51. package/dist/client/usage/reconciliation.d.ts +12 -0
  52. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  53. package/dist/client/usage/reconciliation.js +48 -0
  54. package/dist/client/usage/reconciliation.js.map +1 -0
  55. package/dist/client/usage/summary.d.ts +50 -0
  56. package/dist/client/usage/summary.d.ts.map +1 -0
  57. package/dist/client/usage/summary.js +110 -0
  58. package/dist/client/usage/summary.js.map +1 -0
  59. package/dist/client/webhooks/handler.d.ts.map +1 -1
  60. package/dist/client/webhooks/handler.js +2 -1
  61. package/dist/client/webhooks/handler.js.map +1 -1
  62. package/dist/client/webhooks/meterErrors.d.ts +5 -0
  63. package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
  64. package/dist/client/webhooks/meterErrors.js +98 -0
  65. package/dist/client/webhooks/meterErrors.js.map +1 -0
  66. package/dist/client/webhooks/v2.d.ts.map +1 -1
  67. package/dist/client/webhooks/v2.js +5 -0
  68. package/dist/client/webhooks/v2.js.map +1 -1
  69. package/dist/component/_generated/api.d.ts +22 -0
  70. package/dist/component/_generated/api.d.ts.map +1 -1
  71. package/dist/component/_generated/api.js.map +1 -1
  72. package/dist/component/_generated/component.d.ts +265 -0
  73. package/dist/component/_generated/component.d.ts.map +1 -1
  74. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  75. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  76. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  77. package/dist/component/earnings/triggers.d.ts +206 -18
  78. package/dist/component/earnings/triggers.d.ts.map +1 -1
  79. package/dist/component/schema.d.ts +97 -1
  80. package/dist/component/schema.js +6 -0
  81. package/dist/component/schema.js.map +1 -1
  82. package/dist/component/usage/schema.d.ts +101 -1
  83. package/dist/component/usage/schema.d.ts.map +1 -1
  84. package/dist/component/usage/schema.js +11 -2
  85. package/dist/component/usage/schema.js.map +1 -1
  86. package/dist/component/usageDelivery/bridge.d.ts +25 -0
  87. package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
  88. package/dist/component/usageDelivery/bridge.js +45 -0
  89. package/dist/component/usageDelivery/bridge.js.map +1 -0
  90. package/dist/component/usageDelivery/fields.d.ts +79 -0
  91. package/dist/component/usageDelivery/fields.d.ts.map +1 -0
  92. package/dist/component/usageDelivery/fields.js +39 -0
  93. package/dist/component/usageDelivery/fields.js.map +1 -0
  94. package/dist/component/usageDelivery/helpers.d.ts +84 -0
  95. package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
  96. package/dist/component/usageDelivery/helpers.js +63 -0
  97. package/dist/component/usageDelivery/helpers.js.map +1 -0
  98. package/dist/component/usageDelivery/mutations.d.ts +97 -0
  99. package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
  100. package/dist/component/usageDelivery/mutations.js +160 -0
  101. package/dist/component/usageDelivery/mutations.js.map +1 -0
  102. package/dist/component/usageDelivery/queries.d.ts +115 -0
  103. package/dist/component/usageDelivery/queries.d.ts.map +1 -0
  104. package/dist/component/usageDelivery/queries.js +22 -0
  105. package/dist/component/usageDelivery/queries.js.map +1 -0
  106. package/dist/component/usageDelivery/schema.d.ts +79 -0
  107. package/dist/component/usageDelivery/schema.d.ts.map +1 -0
  108. package/dist/component/usageDelivery/schema.js +30 -0
  109. package/dist/component/usageDelivery/schema.js.map +1 -0
  110. package/dist/component/usageDelivery/steps.d.ts +85 -0
  111. package/dist/component/usageDelivery/steps.d.ts.map +1 -0
  112. package/dist/component/usageDelivery/steps.js +161 -0
  113. package/dist/component/usageDelivery/steps.js.map +1 -0
  114. package/dist/component/usageDelivery/workflow.d.ts +15 -0
  115. package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
  116. package/dist/component/usageDelivery/workflow.js +28 -0
  117. package/dist/component/usageDelivery/workflow.js.map +1 -0
  118. package/dist/component/usageObservations/helpers.d.ts +38 -0
  119. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  120. package/dist/component/usageObservations/helpers.js +80 -0
  121. package/dist/component/usageObservations/helpers.js.map +1 -0
  122. package/dist/component/usageObservations/history.d.ts +6 -0
  123. package/dist/component/usageObservations/history.d.ts.map +1 -0
  124. package/dist/component/usageObservations/history.js +29 -0
  125. package/dist/component/usageObservations/history.js.map +1 -0
  126. package/dist/component/usageObservations/mutations.d.ts +6 -0
  127. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  128. package/dist/component/usageObservations/mutations.js +39 -0
  129. package/dist/component/usageObservations/mutations.js.map +1 -0
  130. package/dist/component/usageObservations/queries.d.ts +78 -0
  131. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  132. package/dist/component/usageObservations/queries.js +131 -0
  133. package/dist/component/usageObservations/queries.js.map +1 -0
  134. package/dist/component/usageObservations/schema.d.ts +72 -0
  135. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  136. package/dist/component/usageObservations/schema.js +29 -0
  137. package/dist/component/usageObservations/schema.js.map +1 -0
  138. package/docs/README.md +5 -1
  139. package/docs/metering-setup.md +3 -1
  140. package/docs/usage-delivery.md +143 -0
  141. package/docs/usage-observations.md +152 -0
  142. package/package.json +4 -2
  143. package/src/client/index.ts +34 -0
  144. package/src/client/usage/client.ts +5 -2
  145. package/src/client/usage/deliveryClient.ts +130 -0
  146. package/src/client/usage/deliveryProtocol.ts +26 -0
  147. package/src/client/usage/deliveryProvider.test.ts +207 -0
  148. package/src/client/usage/deliveryProvider.ts +155 -0
  149. package/src/client/usage/index.ts +31 -0
  150. package/src/client/usage/invoiceObservation.test.ts +195 -0
  151. package/src/client/usage/invoiceObservation.ts +203 -0
  152. package/src/client/usage/observationClient.ts +233 -0
  153. package/src/client/usage/observationTypes.ts +101 -0
  154. package/src/client/usage/providerObservation.test.ts +207 -0
  155. package/src/client/usage/providerObservation.ts +124 -0
  156. package/src/client/usage/reconciliation.test.ts +117 -0
  157. package/src/client/usage/reconciliation.ts +86 -0
  158. package/src/client/usage/summary.test.ts +222 -0
  159. package/src/client/usage/summary.ts +188 -0
  160. package/src/client/webhooks/handler.ts +2 -1
  161. package/src/client/webhooks/meterErrors.test.ts +164 -0
  162. package/src/client/webhooks/meterErrors.ts +118 -0
  163. package/src/client/webhooks/v2.ts +5 -0
  164. package/src/component/_generated/api.ts +22 -0
  165. package/src/component/_generated/component.ts +437 -0
  166. package/src/component/schema.ts +12 -0
  167. package/src/component/usage/schema.ts +11 -2
  168. package/src/component/usageDelivery/bridge.ts +56 -0
  169. package/src/component/usageDelivery/concurrency.test.ts +62 -0
  170. package/src/component/usageDelivery/fields.ts +60 -0
  171. package/src/component/usageDelivery/helpers.ts +77 -0
  172. package/src/component/usageDelivery/mutations.ts +210 -0
  173. package/src/component/usageDelivery/queries.ts +25 -0
  174. package/src/component/usageDelivery/schema.ts +33 -0
  175. package/src/component/usageDelivery/steps.ts +209 -0
  176. package/src/component/usageDelivery/workflow.test.ts +402 -0
  177. package/src/component/usageDelivery/workflow.ts +36 -0
  178. package/src/component/usageObservations/helpers.ts +95 -0
  179. package/src/component/usageObservations/history.test.ts +87 -0
  180. package/src/component/usageObservations/history.ts +39 -0
  181. package/src/component/usageObservations/mutations.ts +39 -0
  182. package/src/component/usageObservations/queries.test.ts +162 -0
  183. package/src/component/usageObservations/queries.ts +145 -0
  184. package/src/component/usageObservations/schema.ts +40 -0
@@ -0,0 +1,101 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import {
4
+ prepareUsageRecord,
5
+ type PreparedUsageRecord,
6
+ type UsageScope,
7
+ } from "./records.js";
8
+ import {
9
+ validateUsagePageRequest,
10
+ type UsageAvailability,
11
+ type UsagePeriod,
12
+ type UsageSubscriptionBinding,
13
+ } from "./boundaries.js";
14
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
15
+ import { verifyRealm, verifyMeter } from "./catalogTypes.js";
16
+ export type UsageObservationOptions = {
17
+ scope: UsageScope;
18
+ binding: PreparedUsageRecord["binding"];
19
+ subscription: UsageSubscriptionBinding;
20
+ period: UsagePeriod;
21
+ limit?: number;
22
+ cursor?: string | null;
23
+ };
24
+ export type UsageAggregateValue = {
25
+ period: UsagePeriod;
26
+ quantity: string;
27
+ scaledQuantity: string;
28
+ complete: boolean;
29
+ nextCursor: string | null;
30
+ aggregationLagPossible: true;
31
+ stale: boolean;
32
+ entries: Array<{
33
+ id: string;
34
+ start: number;
35
+ end: number;
36
+ scaledQuantity: string;
37
+ }>;
38
+ };
39
+ export type UsageAggregateObservation = UsageAvailability<UsageAggregateValue>;
40
+ export function observationOptions(input: UsageObservationOptions) {
41
+ const page = validateUsagePageRequest({
42
+ period: input.period,
43
+ limit: input.limit ?? 100,
44
+ cursor: input.cursor ?? null,
45
+ });
46
+ const { scope, binding } = prepareUsageRecord({
47
+ scope: input.scope,
48
+ binding: input.binding,
49
+ sourceEventId: "observation",
50
+ quantity: "0",
51
+ occurredAt: page.period.start,
52
+ });
53
+ const subscription = subscriptionSnapshot(JSON.stringify(input.subscription));
54
+ if (subscription.stripePriceId !== binding.stripePriceId)
55
+ throw new Error("Usage observation price binding mismatch");
56
+ return {
57
+ scope,
58
+ binding,
59
+ subscription,
60
+ period: page.period,
61
+ limit: page.limit,
62
+ cursor: page.cursor,
63
+ };
64
+ }
65
+ export async function verifyObservationSource(
66
+ stripe: Stripe,
67
+ opts: ReturnType<typeof observationOptions>,
68
+ ): Promise<boolean> {
69
+ await verifyRealm(stripe, {
70
+ stripeAccountId: opts.scope.stripeAccountId,
71
+ livemode: opts.scope.livemode,
72
+ });
73
+ const [meter, subscription] = await Promise.all([
74
+ stripe.billing.meters.retrieve(opts.scope.meterId),
75
+ stripe.subscriptions.retrieve(opts.subscription.subscriptionId),
76
+ ]);
77
+ if (
78
+ meter.id !== opts.scope.meterId ||
79
+ subscription.id !== opts.subscription.subscriptionId ||
80
+ subscription.livemode !== opts.scope.livemode ||
81
+ subscription.customer_account !== opts.scope.customerAccount ||
82
+ (typeof subscription.customer === "string"
83
+ ? subscription.customer
84
+ : subscription.customer?.id) !== opts.binding.stripeCustomerId
85
+ )
86
+ return false;
87
+ verifyMeter(
88
+ meter,
89
+ {
90
+ scope: opts.scope,
91
+ plan: opts.binding.plan,
92
+ eventName: opts.binding.eventName,
93
+ displayName: meter.display_name,
94
+ },
95
+ false,
96
+ );
97
+ return true;
98
+ }
99
+ export const observationKeyOptions = z.strictObject({
100
+ maxAgeSeconds: z.number().int().min(1).max(86400).default(60),
101
+ });
@@ -0,0 +1,207 @@
1
+ import { componentsGeneric, type FunctionReference } from "convex/server";
2
+ import { BetterStripe } from "../index.js";
3
+ import { initConvexTest } from "../setup.test.js";
4
+ import { schema, modules } from "../../test.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import Stripe from "stripe";
7
+ import { expect, it, vi } from "vitest";
8
+ import { STRIPE_API_VERSION } from "../constants.js";
9
+ import { prepareUsageRecord } from "./records.js";
10
+ import { observeProviderUsage } from "./providerObservation.js";
11
+ const scope = {
12
+ stripeAccountId: "acct_platform",
13
+ customerAccount: "acct_buyer",
14
+ meterId: "mtr_calls",
15
+ livemode: false,
16
+ };
17
+ const period = { start: 600, end: 1200 };
18
+ const binding = prepareUsageRecord({
19
+ scope,
20
+ binding: {
21
+ stripeCustomerId: "cus_buyer",
22
+ stripePriceId: "price_calls",
23
+ eventName: "calls",
24
+ plan: {
25
+ key: "calls",
26
+ version: "v1",
27
+ model: "pay_as_you_go",
28
+ unit: { name: "call", precision: 2 },
29
+ rate: { currency: "usd", unitAmountDecimal: "2" },
30
+ },
31
+ },
32
+ sourceEventId: "validation",
33
+ quantity: "0",
34
+ occurredAt: 600,
35
+ }).binding;
36
+ const options = {
37
+ scope,
38
+ binding,
39
+ subscription: {
40
+ subscriptionId: "sub_calls",
41
+ subscriptionItemId: "si_calls",
42
+ stripePriceId: "price_calls",
43
+ period,
44
+ interval: "month" as const,
45
+ },
46
+ period,
47
+ limit: 100,
48
+ cursor: null,
49
+ };
50
+ function setup(value = 125, hasMore = false, empty = false) {
51
+ const requests: Array<URL> = [];
52
+ const httpClient = Stripe.createFetchHttpClient(async (input) => {
53
+ const url = new URL(String(input));
54
+ requests.push(url);
55
+ const result =
56
+ url.pathname === "/v1/account"
57
+ ? { id: "acct_platform" }
58
+ : url.pathname === "/v1/balance"
59
+ ? { livemode: false }
60
+ : url.pathname === "/v1/billing/meters/mtr_calls"
61
+ ? {
62
+ id: "mtr_calls",
63
+ livemode: false,
64
+ status: "active",
65
+ event_name: "calls",
66
+ default_aggregation: { formula: "sum" },
67
+ customer_mapping: {
68
+ type: "by_id",
69
+ event_payload_key: "stripe_customer_id",
70
+ },
71
+ value_settings: { event_payload_key: "value" },
72
+ event_time_window: null,
73
+ }
74
+ : url.pathname === "/v1/subscriptions/sub_calls"
75
+ ? {
76
+ id: "sub_calls",
77
+ livemode: false,
78
+ customer: "cus_buyer",
79
+ customer_account: "acct_buyer",
80
+ }
81
+ : {
82
+ object: "list",
83
+ data: empty
84
+ ? []
85
+ : [
86
+ {
87
+ id: "mtrusg_one",
88
+ object: "billing.meter_event_summary",
89
+ meter: "mtr_calls",
90
+ livemode: false,
91
+ start_time: 600,
92
+ end_time: 1200,
93
+ aggregated_value: value,
94
+ },
95
+ ],
96
+ has_more: hasMore,
97
+ };
98
+ return new Response(JSON.stringify(result), {
99
+ status: 200,
100
+ headers: { "content-type": "application/json" },
101
+ });
102
+ });
103
+ const stripe = new Stripe("sk_test_observe", {
104
+ apiVersion: STRIPE_API_VERSION,
105
+ maxNetworkRetries: 0,
106
+ httpClient,
107
+ });
108
+ return { stripe, requests, httpClient };
109
+ }
110
+ it("reads exact native quantities and preserves the original customer/period", async () => {
111
+ const f = setup();
112
+ expect(await observeProviderUsage(f.stripe, options)).toMatchObject({
113
+ status: "available",
114
+ value: {
115
+ quantity: "1.25",
116
+ scaledQuantity: "125",
117
+ complete: true,
118
+ aggregationLagPossible: true,
119
+ period,
120
+ },
121
+ });
122
+ const request = f.requests.find((r) =>
123
+ r.pathname.endsWith("event_summaries"),
124
+ )!;
125
+ expect(request.searchParams.get("customer")).toBe("cus_buyer");
126
+ expect(request.searchParams.get("start_time")).toBe("600");
127
+ expect(request.searchParams.get("end_time")).toBe("1200");
128
+ });
129
+ it("reports absent aggregation instead of zero and preserves incomplete pagination", async () => {
130
+ expect(
131
+ await observeProviderUsage(setup(0, false, true).stripe, options),
132
+ ).toMatchObject({ status: "unavailable", reason: "aggregation_pending" });
133
+ expect(
134
+ await observeProviderUsage(setup(0, true).stripe, options),
135
+ ).toMatchObject({
136
+ status: "available",
137
+ value: { quantity: "0", complete: false, nextCursor: "mtrusg_one" },
138
+ });
139
+ });
140
+ it("rejects unaligned windows and unsafe provider numbers without rounding", async () => {
141
+ const f = setup();
142
+ expect(
143
+ await observeProviderUsage(f.stripe, {
144
+ ...options,
145
+ period: { start: 601, end: 1200 },
146
+ }),
147
+ ).toMatchObject({
148
+ status: "unsupported",
149
+ reason: "minute_alignment_required",
150
+ });
151
+ expect(f.requests).toHaveLength(0);
152
+ expect(
153
+ await observeProviderUsage(
154
+ setup(Number.MAX_SAFE_INTEGER + 1).stripe,
155
+ options,
156
+ ),
157
+ ).toMatchObject({
158
+ status: "unavailable",
159
+ reason: "provider_precision_unsupported",
160
+ });
161
+ });
162
+
163
+ it("caches through the public facade without resending usage and exposes stale data", async () => {
164
+ const t = initConvexTest();
165
+ t.registerComponent("betterStripe", schema, modules);
166
+ const client = new BetterStripe(
167
+ componentsGeneric().betterStripe as unknown as Component,
168
+ );
169
+ const ctx = {
170
+ runQuery: (
171
+ ref: FunctionReference<"query">,
172
+ args: Record<string, unknown>,
173
+ ) => t.query(ref, args),
174
+ runMutation: (
175
+ ref: FunctionReference<"mutation">,
176
+ args: Record<string, unknown>,
177
+ ) => t.mutation(ref, args),
178
+ } as RunCtx;
179
+ const f = setup();
180
+ expect(await client.usage.getProviderUsage(ctx, options)).toMatchObject({
181
+ status: "unavailable",
182
+ reason: "provider_not_observed",
183
+ });
184
+ const result = await client.usage.reconcile(ctx, options, {
185
+ stripeSecretKey: "sk_test_observe",
186
+ httpClient: f.httpClient,
187
+ });
188
+ expect(result).toMatchObject({
189
+ local: { complete: true, eventCount: 0 },
190
+ aggregate: { status: "available", value: { quantity: "1.25" } },
191
+ comparison: { status: "mismatch" },
192
+ invoice: { status: "unavailable" },
193
+ });
194
+ expect(
195
+ f.requests.every((url) => !url.pathname.endsWith("meter_events")),
196
+ ).toBe(true);
197
+ const now = Date.now(),
198
+ clock = vi.spyOn(Date, "now").mockReturnValue(now + 61000);
199
+ try {
200
+ expect(await client.usage.getReconciliation(ctx, options)).toMatchObject({
201
+ aggregate: { status: "available", value: { stale: true } },
202
+ comparison: { status: "unavailable", reason: "aggregate_stale" },
203
+ });
204
+ } finally {
205
+ clock.mockRestore();
206
+ }
207
+ });
@@ -0,0 +1,124 @@
1
+ import type Stripe from "stripe";
2
+ import { UsageCatalogError } from "./catalogTypes.js";
3
+ import { decimalFromScaled } from "./summary.js";
4
+ import {
5
+ observationOptions,
6
+ verifyObservationSource,
7
+ type UsageObservationOptions,
8
+ type UsageAggregateObservation,
9
+ } from "./observationTypes.js";
10
+ export async function observeProviderUsage(
11
+ stripe: Stripe,
12
+ input: UsageObservationOptions,
13
+ ): Promise<UsageAggregateObservation> {
14
+ const opts = observationOptions(input),
15
+ observedAt = Math.floor(Date.now() / 1000);
16
+ const unavailable = (reason: string): UsageAggregateObservation => ({
17
+ status: "unavailable",
18
+ reason,
19
+ retryable: true,
20
+ });
21
+ if (opts.period.start % 60 || opts.period.end % 60)
22
+ return {
23
+ status: "unsupported",
24
+ reason: "minute_alignment_required",
25
+ retryable: false,
26
+ };
27
+ try {
28
+ if (!(await verifyObservationSource(stripe, opts)))
29
+ return {
30
+ status: "unsupported",
31
+ reason: "provider_binding_mismatch",
32
+ retryable: false,
33
+ };
34
+ const result = await stripe.billing.meters.listEventSummaries(
35
+ opts.scope.meterId,
36
+ {
37
+ customer: opts.binding.stripeCustomerId,
38
+ start_time: opts.period.start,
39
+ end_time: opts.period.end,
40
+ limit: opts.limit,
41
+ starting_after: opts.cursor ?? undefined,
42
+ },
43
+ );
44
+ if (!result.data.length)
45
+ return unavailable(
46
+ result.has_more ? "provider_history_incomplete" : "aggregation_pending",
47
+ );
48
+ if (result.data.length > opts.limit)
49
+ return unavailable("provider_history_incomplete");
50
+ const seen = new Set<string>();
51
+ let scaled = 0n;
52
+ const intervals: Array<{ start: number; end: number }> = [],
53
+ entries: Array<{
54
+ id: string;
55
+ start: number;
56
+ end: number;
57
+ scaledQuantity: string;
58
+ }> = [];
59
+ for (const summary of result.data) {
60
+ if (
61
+ summary.object !== "billing.meter_event_summary" ||
62
+ summary.meter !== opts.scope.meterId ||
63
+ summary.livemode !== opts.scope.livemode ||
64
+ !summary.id ||
65
+ summary.id.length > 2048 ||
66
+ seen.has(summary.id) ||
67
+ !Number.isSafeInteger(summary.start_time) ||
68
+ !Number.isSafeInteger(summary.end_time) ||
69
+ summary.start_time < opts.period.start ||
70
+ summary.end_time > opts.period.end ||
71
+ summary.end_time <= summary.start_time ||
72
+ intervals.some(
73
+ (w) => summary.start_time < w.end && summary.end_time > w.start,
74
+ )
75
+ )
76
+ return unavailable("provider_history_incomplete");
77
+ if (
78
+ !Number.isSafeInteger(summary.aggregated_value) ||
79
+ summary.aggregated_value < 0
80
+ )
81
+ return unavailable("provider_precision_unsupported");
82
+ seen.add(summary.id);
83
+ intervals.push({ start: summary.start_time, end: summary.end_time });
84
+ const value = BigInt(summary.aggregated_value);
85
+ scaled += value;
86
+ entries.push({
87
+ id: summary.id,
88
+ start: summary.start_time,
89
+ end: summary.end_time,
90
+ scaledQuantity: value.toString(),
91
+ });
92
+ }
93
+ const covered =
94
+ intervals.reduce((sum, w) => sum + w.end - w.start, 0) ===
95
+ opts.period.end - opts.period.start;
96
+ return {
97
+ status: "available",
98
+ observedAt,
99
+ value: {
100
+ period: opts.period,
101
+ quantity: decimalFromScaled(scaled, opts.binding.plan.unit.precision),
102
+ scaledQuantity: scaled.toString(),
103
+ complete: !result.has_more && opts.cursor === null && covered,
104
+ nextCursor: result.has_more
105
+ ? result.data[result.data.length - 1].id
106
+ : null,
107
+ aggregationLagPossible: true,
108
+ stale: false,
109
+ entries,
110
+ },
111
+ };
112
+ } catch (error) {
113
+ if (
114
+ error instanceof UsageCatalogError &&
115
+ error.code === "unsupported_scope"
116
+ )
117
+ return {
118
+ status: "unsupported",
119
+ reason: "unsupported_scope",
120
+ retryable: false,
121
+ };
122
+ return unavailable("provider_unavailable");
123
+ }
124
+ }
@@ -0,0 +1,117 @@
1
+ import { expect, it } from "vitest";
2
+ import { compareUsageObservations } from "./reconciliation.js";
3
+ import { summarizeUsageRecords } from "./summary.js";
4
+ import { prepareUsageRecord } from "./records.js";
5
+ const period = { start: 600, end: 1200 },
6
+ scope = {
7
+ stripeAccountId: "acct_platform",
8
+ customerAccount: "acct_buyer",
9
+ meterId: "mtr_calls",
10
+ livemode: false,
11
+ };
12
+ const record = prepareUsageRecord({
13
+ scope,
14
+ binding: {
15
+ stripeCustomerId: "cus_buyer",
16
+ stripePriceId: "price_calls",
17
+ eventName: "calls",
18
+ plan: {
19
+ key: "calls",
20
+ version: "v1",
21
+ model: "pay_as_you_go",
22
+ unit: { name: "call", precision: 0 },
23
+ rate: { currency: "usd", unitAmountDecimal: "2" },
24
+ },
25
+ },
26
+ sourceEventId: "one",
27
+ quantity: "2",
28
+ occurredAt: 700,
29
+ });
30
+ const subscription = {
31
+ subscriptionId: "sub_calls",
32
+ subscriptionItemId: "si_calls",
33
+ stripePriceId: "price_calls",
34
+ period,
35
+ interval: "month" as const,
36
+ };
37
+ const local = summarizeUsageRecords(
38
+ [
39
+ {
40
+ record,
41
+ subscription,
42
+ delivery: "provider_accepted",
43
+ hasValidationError: false,
44
+ },
45
+ ],
46
+ { period, complete: true, observedAt: 1201 },
47
+ );
48
+ const aggregate = {
49
+ status: "available" as const,
50
+ observedAt: 1201,
51
+ value: {
52
+ period,
53
+ quantity: "2",
54
+ scaledQuantity: "2",
55
+ complete: true,
56
+ nextCursor: null,
57
+ aggregationLagPossible: true as const,
58
+ stale: false,
59
+ entries: [{ id: "mtrusg_one", start: 600, end: 1200, scaledQuantity: "2" }],
60
+ },
61
+ };
62
+ it("separates observed matches from mismatches without changing usage", () => {
63
+ expect(
64
+ compareUsageObservations(local, aggregate, record.binding),
65
+ ).toMatchObject({
66
+ status: "observed_match",
67
+ localAcceptedQuantity: "2",
68
+ providerAcceptedQuantity: "2",
69
+ providerAggregateQuantity: "2",
70
+ });
71
+ expect(
72
+ compareUsageObservations(
73
+ local,
74
+ {
75
+ ...aggregate,
76
+ value: { ...aggregate.value, quantity: "0", scaledQuantity: "0" },
77
+ },
78
+ record.binding,
79
+ ),
80
+ ).toMatchObject({
81
+ status: "mismatch",
82
+ reason: "aggregation_lag_or_external_usage",
83
+ });
84
+ expect(record.quantity).toBe("2");
85
+ });
86
+ it("cannot compare stale, incomplete, absent or differently routed observations", () => {
87
+ expect(
88
+ compareUsageObservations(
89
+ local,
90
+ { ...aggregate, value: { ...aggregate.value, stale: true } },
91
+ record.binding,
92
+ ),
93
+ ).toMatchObject({ status: "unavailable", reason: "aggregate_stale" });
94
+ expect(
95
+ compareUsageObservations(
96
+ { ...local, complete: false },
97
+ aggregate,
98
+ record.binding,
99
+ ),
100
+ ).toMatchObject({
101
+ status: "unavailable",
102
+ reason: "local_history_incomplete",
103
+ });
104
+ expect(
105
+ compareUsageObservations(
106
+ local,
107
+ { status: "unavailable", reason: "aggregation_pending", retryable: true },
108
+ record.binding,
109
+ ),
110
+ ).toMatchObject({ status: "unavailable", providerAggregateQuantity: null });
111
+ expect(
112
+ compareUsageObservations(local, aggregate, {
113
+ ...record.binding,
114
+ stripePriceId: "price_changed",
115
+ }),
116
+ ).toMatchObject({ status: "unavailable", reason: "ambiguous_local_terms" });
117
+ });
@@ -0,0 +1,86 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { UsageLocalSummary } from "./summary.js";
3
+ import { decimalFromScaled } from "./summary.js";
4
+ import type { UsageAggregateObservation } from "./observationTypes.js";
5
+ import type { PreparedUsageRecord } from "./records.js";
6
+ export type UsageComparison = {
7
+ status: "observed_match" | "mismatch" | "unavailable";
8
+ reason: string;
9
+ localAcceptedQuantity: string | null;
10
+ providerAcceptedQuantity: string | null;
11
+ providerAggregateQuantity: string | null;
12
+ };
13
+ export function compareUsageObservations(
14
+ local: UsageLocalSummary,
15
+ aggregate: UsageAggregateObservation,
16
+ binding: PreparedUsageRecord["binding"],
17
+ ): UsageComparison {
18
+ const value: UsageComparison = {
19
+ status: "unavailable",
20
+ reason: "provider_unavailable",
21
+ localAcceptedQuantity: null,
22
+ providerAcceptedQuantity: null,
23
+ providerAggregateQuantity:
24
+ aggregate.status === "available" ? aggregate.value.quantity : null,
25
+ };
26
+ const unavailable = (reason: string) => ({ ...value, reason });
27
+ if (!local.complete) return unavailable("local_history_incomplete");
28
+ if (
29
+ local.groups.some(
30
+ (group) =>
31
+ JSON.stringify(convexToJson(group.binding)) !==
32
+ JSON.stringify(convexToJson(binding)),
33
+ )
34
+ )
35
+ return unavailable("ambiguous_local_terms");
36
+ const accepted = local.groups.reduce(
37
+ (sum, group) => sum + BigInt(group.acceptedScaledQuantity),
38
+ 0n,
39
+ ),
40
+ provider = local.groups.reduce(
41
+ (sum, group) => sum + BigInt(group.providerAcceptedScaledQuantity),
42
+ 0n,
43
+ );
44
+ value.localAcceptedQuantity = decimalFromScaled(
45
+ accepted,
46
+ binding.plan.unit.precision,
47
+ );
48
+ value.providerAcceptedQuantity = decimalFromScaled(
49
+ provider,
50
+ binding.plan.unit.precision,
51
+ );
52
+ if (aggregate.status !== "available") return unavailable(aggregate.reason);
53
+ if (aggregate.value.stale) return unavailable("aggregate_stale");
54
+ if (!aggregate.value.complete)
55
+ return unavailable("provider_history_incomplete");
56
+ if (
57
+ local.period.start !== aggregate.value.period.start ||
58
+ local.period.end !== aggregate.value.period.end
59
+ )
60
+ return unavailable("period_mismatch");
61
+ if (
62
+ local.groups.some(
63
+ (g) =>
64
+ g.deliveryQuantities.unknown !== "0" ||
65
+ g.deliveryQuantities.sending !== "0",
66
+ )
67
+ )
68
+ return unavailable("delivery_unresolved");
69
+ if (local.groups.some((g) => g.validationErrorEventCount > 0))
70
+ return {
71
+ ...value,
72
+ status: "mismatch",
73
+ reason: "provider_validation_errors",
74
+ };
75
+ return {
76
+ ...value,
77
+ status:
78
+ provider === BigInt(aggregate.value.scaledQuantity)
79
+ ? "observed_match"
80
+ : "mismatch",
81
+ reason:
82
+ provider === BigInt(aggregate.value.scaledQuantity)
83
+ ? "observations_equal"
84
+ : "aggregation_lag_or_external_usage",
85
+ };
86
+ }