@fantastic.dev/better-stripe 0.52.0 → 0.54.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 +12 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +160 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +80 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +160 -2
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +80 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/products/catalogClient.d.ts +23 -0
- package/dist/client/products/catalogClient.d.ts.map +1 -1
- package/dist/client/products/catalogClient.js +32 -0
- package/dist/client/products/catalogClient.js.map +1 -1
- package/dist/client/products/fixedPrice.d.ts +4 -0
- package/dist/client/products/fixedPrice.d.ts.map +1 -0
- package/dist/client/products/fixedPrice.js +10 -0
- package/dist/client/products/fixedPrice.js.map +1 -0
- package/dist/client/products/products.d.ts.map +1 -1
- package/dist/client/products/products.js +3 -0
- package/dist/client/products/products.js.map +1 -1
- package/dist/client/usage/catalog.d.ts +7 -0
- package/dist/client/usage/catalog.d.ts.map +1 -0
- package/dist/client/usage/catalog.js +55 -0
- package/dist/client/usage/catalog.js.map +1 -0
- package/dist/client/usage/catalogLifecycle.d.ts +25 -0
- package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
- package/dist/client/usage/catalogLifecycle.js +64 -0
- package/dist/client/usage/catalogLifecycle.js.map +1 -0
- package/dist/client/usage/catalogMath.d.ts +3 -0
- package/dist/client/usage/catalogMath.d.ts.map +1 -0
- package/dist/client/usage/catalogMath.js +21 -0
- package/dist/client/usage/catalogMath.js.map +1 -0
- package/dist/client/usage/catalogPrices.d.ts +5 -0
- package/dist/client/usage/catalogPrices.d.ts.map +1 -0
- package/dist/client/usage/catalogPrices.js +178 -0
- package/dist/client/usage/catalogPrices.js.map +1 -0
- package/dist/client/usage/catalogRead.d.ts +25 -0
- package/dist/client/usage/catalogRead.d.ts.map +1 -0
- package/dist/client/usage/catalogRead.js +71 -0
- package/dist/client/usage/catalogRead.js.map +1 -0
- package/dist/client/usage/catalogTypes.d.ts +97 -0
- package/dist/client/usage/catalogTypes.d.ts.map +1 -0
- package/dist/client/usage/catalogTypes.js +106 -0
- package/dist/client/usage/catalogTypes.js.map +1 -0
- package/dist/client/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +3 -3
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/deliveryClient.d.ts +64 -0
- package/dist/client/usage/deliveryClient.d.ts.map +1 -0
- package/dist/client/usage/deliveryClient.js +60 -0
- package/dist/client/usage/deliveryClient.js.map +1 -0
- package/dist/client/usage/deliveryProtocol.d.ts +130 -0
- package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
- package/dist/client/usage/deliveryProtocol.js +21 -0
- package/dist/client/usage/deliveryProtocol.js.map +1 -0
- package/dist/client/usage/deliveryProvider.d.ts +32 -0
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
- package/dist/client/usage/deliveryProvider.js +127 -0
- package/dist/client/usage/deliveryProvider.js.map +1 -0
- package/dist/client/usage/index.d.ts +3 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usage/index.js +1 -0
- package/dist/client/usage/index.js.map +1 -1
- package/dist/client/webhooks/handler.d.ts.map +1 -1
- package/dist/client/webhooks/handler.js +2 -1
- package/dist/client/webhooks/handler.js.map +1 -1
- package/dist/client/webhooks/meterErrors.d.ts +5 -0
- package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
- package/dist/client/webhooks/meterErrors.js +98 -0
- package/dist/client/webhooks/meterErrors.js.map +1 -0
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -0
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/client/webhooks/v2.d.ts.map +1 -1
- package/dist/client/webhooks/v2.js +5 -0
- package/dist/client/webhooks/v2.js.map +1 -1
- package/dist/component/_generated/api.d.ts +18 -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 +232 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/earnings/triggers.d.ts +150 -2
- 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/refundHistory/queries.d.ts +1 -1
- package/dist/component/schema.d.ts +80 -1
- package/dist/component/schema.js +5 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/schema.d.ts +96 -1
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +11 -2
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageCatalog/mutations.d.ts +25 -0
- package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
- package/dist/component/usageCatalog/mutations.js +75 -0
- package/dist/component/usageCatalog/mutations.js.map +1 -0
- package/dist/component/usageCatalog/queries.d.ts +33 -0
- package/dist/component/usageCatalog/queries.d.ts.map +1 -0
- package/dist/component/usageCatalog/queries.js +26 -0
- package/dist/component/usageCatalog/queries.js.map +1 -0
- package/dist/component/usageCatalog/schema.d.ts +57 -0
- package/dist/component/usageCatalog/schema.d.ts.map +1 -0
- package/dist/component/usageCatalog/schema.js +22 -0
- package/dist/component/usageCatalog/schema.js.map +1 -0
- package/dist/component/usageDelivery/bridge.d.ts +25 -0
- package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
- package/dist/component/usageDelivery/bridge.js +45 -0
- package/dist/component/usageDelivery/bridge.js.map +1 -0
- package/dist/component/usageDelivery/fields.d.ts +78 -0
- package/dist/component/usageDelivery/fields.d.ts.map +1 -0
- package/dist/component/usageDelivery/fields.js +38 -0
- package/dist/component/usageDelivery/fields.js.map +1 -0
- package/dist/component/usageDelivery/helpers.d.ts +83 -0
- package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
- package/dist/component/usageDelivery/helpers.js +63 -0
- package/dist/component/usageDelivery/helpers.js.map +1 -0
- package/dist/component/usageDelivery/mutations.d.ts +97 -0
- package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
- package/dist/component/usageDelivery/mutations.js +153 -0
- package/dist/component/usageDelivery/mutations.js.map +1 -0
- package/dist/component/usageDelivery/queries.d.ts +113 -0
- package/dist/component/usageDelivery/queries.d.ts.map +1 -0
- package/dist/component/usageDelivery/queries.js +22 -0
- package/dist/component/usageDelivery/queries.js.map +1 -0
- package/dist/component/usageDelivery/schema.d.ts +79 -0
- package/dist/component/usageDelivery/schema.d.ts.map +1 -0
- package/dist/component/usageDelivery/schema.js +30 -0
- package/dist/component/usageDelivery/schema.js.map +1 -0
- package/dist/component/usageDelivery/steps.d.ts +85 -0
- package/dist/component/usageDelivery/steps.d.ts.map +1 -0
- package/dist/component/usageDelivery/steps.js +154 -0
- package/dist/component/usageDelivery/steps.js.map +1 -0
- package/dist/component/usageDelivery/workflow.d.ts +15 -0
- package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
- package/dist/component/usageDelivery/workflow.js +28 -0
- package/dist/component/usageDelivery/workflow.js.map +1 -0
- package/docs/README.md +5 -1
- package/docs/metering-setup.md +3 -1
- package/docs/usage-catalog.md +106 -0
- package/docs/usage-delivery.md +143 -0
- package/package.json +4 -2
- package/src/client/index.ts +23 -0
- package/src/client/products/catalogClient.ts +77 -0
- package/src/client/products/fixedPrice.test.ts +57 -0
- package/src/client/products/fixedPrice.ts +13 -0
- package/src/client/products/products.ts +2 -0
- package/src/client/usage/catalog.test.ts +464 -0
- package/src/client/usage/catalog.ts +117 -0
- package/src/client/usage/catalogLifecycle.ts +128 -0
- package/src/client/usage/catalogMath.test.ts +13 -0
- package/src/client/usage/catalogMath.ts +22 -0
- package/src/client/usage/catalogPrices.ts +251 -0
- package/src/client/usage/catalogRead.ts +98 -0
- package/src/client/usage/catalogTypes.ts +170 -0
- package/src/client/usage/client.ts +5 -2
- package/src/client/usage/deliveryClient.ts +130 -0
- package/src/client/usage/deliveryProtocol.ts +26 -0
- package/src/client/usage/deliveryProvider.test.ts +207 -0
- package/src/client/usage/deliveryProvider.ts +155 -0
- package/src/client/usage/index.ts +13 -0
- package/src/client/webhooks/handler.ts +2 -1
- package/src/client/webhooks/meterErrors.test.ts +164 -0
- package/src/client/webhooks/meterErrors.ts +118 -0
- package/src/client/webhooks/processors.ts +2 -0
- package/src/client/webhooks/v2.ts +5 -0
- package/src/component/_generated/api.ts +18 -0
- package/src/component/_generated/component.ts +380 -0
- package/src/component/schema.ts +8 -0
- package/src/component/usage/schema.ts +11 -2
- package/src/component/usageCatalog/mutations.ts +79 -0
- package/src/component/usageCatalog/queries.ts +32 -0
- package/src/component/usageCatalog/schema.ts +21 -0
- package/src/component/usageDelivery/bridge.ts +56 -0
- package/src/component/usageDelivery/concurrency.test.ts +62 -0
- package/src/component/usageDelivery/fields.ts +59 -0
- package/src/component/usageDelivery/helpers.ts +77 -0
- package/src/component/usageDelivery/mutations.ts +185 -0
- package/src/component/usageDelivery/queries.ts +25 -0
- package/src/component/usageDelivery/schema.ts +33 -0
- package/src/component/usageDelivery/steps.ts +171 -0
- package/src/component/usageDelivery/workflow.test.ts +402 -0
- package/src/component/usageDelivery/workflow.ts +36 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createFunctionHandle, type FunctionReference } from "convex/server";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import {
|
|
7
|
+
scopeSchema,
|
|
8
|
+
type UsageScope,
|
|
9
|
+
type UsageDeliveryState,
|
|
10
|
+
} from "./records.js";
|
|
11
|
+
import {
|
|
12
|
+
deliverUsageProvider,
|
|
13
|
+
type UsageDeliveryRequest,
|
|
14
|
+
type UsageDeliveryOutcome,
|
|
15
|
+
type UsageDeliveryProviderOptions,
|
|
16
|
+
} from "./deliveryProvider.js";
|
|
17
|
+
export type UsageDeliveryRef = { scope: UsageScope; eventId: string };
|
|
18
|
+
export type UsageDeliveryStatus = {
|
|
19
|
+
validationErrors: Array<{
|
|
20
|
+
providerEventId: string;
|
|
21
|
+
code: string;
|
|
22
|
+
observedAt: number;
|
|
23
|
+
}>;
|
|
24
|
+
validationHistoryComplete: boolean;
|
|
25
|
+
eventId: string;
|
|
26
|
+
state: UsageDeliveryState;
|
|
27
|
+
attempts: number;
|
|
28
|
+
held: boolean;
|
|
29
|
+
reason?: string;
|
|
30
|
+
providerIdentifier: string;
|
|
31
|
+
receipt?: { identifier: string; created: number };
|
|
32
|
+
};
|
|
33
|
+
export type UsageDeliveryStartOptions = UsageDeliveryRef & {
|
|
34
|
+
provider: FunctionReference<
|
|
35
|
+
"action",
|
|
36
|
+
"internal",
|
|
37
|
+
UsageDeliveryRequest,
|
|
38
|
+
UsageDeliveryRequest & { outcome: UsageDeliveryOutcome }
|
|
39
|
+
>;
|
|
40
|
+
};
|
|
41
|
+
function ref(input: UsageDeliveryRef) {
|
|
42
|
+
return {
|
|
43
|
+
scope: scopeSchema.parse(input.scope),
|
|
44
|
+
eventId: z.string().min(1).max(100).parse(input.eventId),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export class UsageDeliveryClient {
|
|
48
|
+
constructor(protected readonly component: Component) {}
|
|
49
|
+
async startDelivery(
|
|
50
|
+
ctx: RunCtx,
|
|
51
|
+
opts: UsageDeliveryStartOptions,
|
|
52
|
+
): Promise<UsageDeliveryStatus> {
|
|
53
|
+
return runMutationOrThrow(
|
|
54
|
+
ctx,
|
|
55
|
+
componentRef(this.component, "usageDelivery/mutations/start"),
|
|
56
|
+
{
|
|
57
|
+
...ref(opts),
|
|
58
|
+
provider: await createFunctionHandle(opts.provider),
|
|
59
|
+
definitionVersion: 1,
|
|
60
|
+
},
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
async startDeliveryBatch(
|
|
64
|
+
ctx: RunCtx,
|
|
65
|
+
opts: {
|
|
66
|
+
scope: UsageScope;
|
|
67
|
+
eventIds: string[];
|
|
68
|
+
provider: UsageDeliveryStartOptions["provider"];
|
|
69
|
+
},
|
|
70
|
+
) {
|
|
71
|
+
const ids = z
|
|
72
|
+
.array(z.string().min(1).max(100))
|
|
73
|
+
.min(1)
|
|
74
|
+
.max(10)
|
|
75
|
+
.parse(opts.eventIds);
|
|
76
|
+
const results: UsageDeliveryStatus[] = [];
|
|
77
|
+
for (const eventId of ids)
|
|
78
|
+
results.push(
|
|
79
|
+
await this.startDelivery(ctx, {
|
|
80
|
+
scope: opts.scope,
|
|
81
|
+
eventId,
|
|
82
|
+
provider: opts.provider,
|
|
83
|
+
}),
|
|
84
|
+
);
|
|
85
|
+
return results;
|
|
86
|
+
}
|
|
87
|
+
getDelivery(
|
|
88
|
+
ctx: RunCtx,
|
|
89
|
+
input: UsageDeliveryRef,
|
|
90
|
+
): Promise<UsageDeliveryStatus> {
|
|
91
|
+
return ctx.runQuery(
|
|
92
|
+
componentRef(this.component, "usageDelivery/queries/get"),
|
|
93
|
+
ref(input),
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
holdDelivery(
|
|
97
|
+
ctx: RunCtx,
|
|
98
|
+
input: UsageDeliveryRef,
|
|
99
|
+
): Promise<UsageDeliveryStatus> {
|
|
100
|
+
return runMutationOrThrow(
|
|
101
|
+
ctx,
|
|
102
|
+
componentRef(this.component, "usageDelivery/mutations/hold"),
|
|
103
|
+
ref(input),
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
resumeDelivery(
|
|
107
|
+
ctx: RunCtx,
|
|
108
|
+
input: UsageDeliveryRef,
|
|
109
|
+
): Promise<UsageDeliveryStatus> {
|
|
110
|
+
return runMutationOrThrow(
|
|
111
|
+
ctx,
|
|
112
|
+
componentRef(this.component, "usageDelivery/mutations/resume"),
|
|
113
|
+
ref(input),
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
async cancelDelivery(ctx: RunCtx, input: UsageDeliveryRef) {
|
|
117
|
+
await this.getDelivery(ctx, input);
|
|
118
|
+
return {
|
|
119
|
+
status: "unsupported" as const,
|
|
120
|
+
reason: "native_event_cancellation_requires_adjustment" as const,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
deliver(
|
|
124
|
+
ctx: RunCtx,
|
|
125
|
+
input: UsageDeliveryRequest,
|
|
126
|
+
options: UsageDeliveryProviderOptions,
|
|
127
|
+
) {
|
|
128
|
+
return deliverUsageProvider(this.component, ctx, input, options);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
/** Register only as a host internal action. Never accept provider options from a browser. */
|
|
3
|
+
export const usageDeliveryArgs = {
|
|
4
|
+
scope: v.object({
|
|
5
|
+
stripeAccountId: v.string(),
|
|
6
|
+
customerAccount: v.string(),
|
|
7
|
+
meterId: v.string(),
|
|
8
|
+
livemode: v.boolean(),
|
|
9
|
+
}),
|
|
10
|
+
eventId: v.string(),
|
|
11
|
+
attempt: v.number(),
|
|
12
|
+
definitionVersion: v.literal(1),
|
|
13
|
+
apiVersion: v.string(),
|
|
14
|
+
identifier: v.string(),
|
|
15
|
+
};
|
|
16
|
+
export const usageDeliveryOutcomeValidator = v.union(
|
|
17
|
+
v.object({ status: v.literal("accepted"), created: v.number() }),
|
|
18
|
+
v.object({ status: v.literal("rate_limited") }),
|
|
19
|
+
v.object({ status: v.literal("unavailable") }),
|
|
20
|
+
v.object({ status: v.literal("unknown") }),
|
|
21
|
+
v.object({ status: v.literal("rejected") }),
|
|
22
|
+
);
|
|
23
|
+
export const usageDeliveryResult = v.object({
|
|
24
|
+
...usageDeliveryArgs,
|
|
25
|
+
outcome: usageDeliveryOutcomeValidator,
|
|
26
|
+
});
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { expect, it, vi } from "vitest";
|
|
3
|
+
import { componentsGeneric } from "convex/server";
|
|
4
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
5
|
+
import { STRIPE_API_VERSION } from "../constants.js";
|
|
6
|
+
import { prepareUsageRecord } from "./records.js";
|
|
7
|
+
import { deliverUsageProvider } from "./deliveryProvider.js";
|
|
8
|
+
const scope = {
|
|
9
|
+
stripeAccountId: "acct_platform",
|
|
10
|
+
customerAccount: "acct_buyer",
|
|
11
|
+
meterId: "mtr_calls",
|
|
12
|
+
livemode: false,
|
|
13
|
+
};
|
|
14
|
+
function setup(status = 200, errorCode = "parameter_invalid_integer") {
|
|
15
|
+
const now = Math.floor(Date.now() / 1000);
|
|
16
|
+
const record = prepareUsageRecord({
|
|
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: 2 },
|
|
27
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
sourceEventId: "one",
|
|
31
|
+
quantity: "1.2",
|
|
32
|
+
occurredAt: now,
|
|
33
|
+
});
|
|
34
|
+
const saved = {
|
|
35
|
+
event: {
|
|
36
|
+
recordJson: JSON.stringify(record),
|
|
37
|
+
subscriptionJson: JSON.stringify({
|
|
38
|
+
subscriptionId: "sub_calls",
|
|
39
|
+
subscriptionItemId: "si_calls",
|
|
40
|
+
stripePriceId: "price_calls",
|
|
41
|
+
period: { start: now - 1, end: now + 86400 },
|
|
42
|
+
interval: "month",
|
|
43
|
+
}),
|
|
44
|
+
},
|
|
45
|
+
outbox: {
|
|
46
|
+
state: "sending",
|
|
47
|
+
attempts: 1,
|
|
48
|
+
definitionVersion: 1,
|
|
49
|
+
providerIdentifier: "bs_usage_event",
|
|
50
|
+
firstSendAt: now,
|
|
51
|
+
leaseUntil: now + 900,
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
const ctx = {
|
|
55
|
+
runQuery: vi.fn().mockResolvedValue(saved),
|
|
56
|
+
} as unknown as RunCtx;
|
|
57
|
+
const requests: Array<{
|
|
58
|
+
path: string;
|
|
59
|
+
headers: Headers;
|
|
60
|
+
body: URLSearchParams;
|
|
61
|
+
}> = [];
|
|
62
|
+
const httpClient = Stripe.createFetchHttpClient(async (input, init) => {
|
|
63
|
+
const path = new URL(String(input)).pathname,
|
|
64
|
+
body = new URLSearchParams(String(init?.body ?? ""));
|
|
65
|
+
requests.push({ path, body, headers: new Headers(init?.headers) });
|
|
66
|
+
const value =
|
|
67
|
+
path === "/v1/account"
|
|
68
|
+
? { id: "acct_platform" }
|
|
69
|
+
: path === "/v1/balance"
|
|
70
|
+
? { livemode: false }
|
|
71
|
+
: path === "/v1/billing/meters/mtr_calls"
|
|
72
|
+
? {
|
|
73
|
+
id: "mtr_calls",
|
|
74
|
+
livemode: false,
|
|
75
|
+
status: "active",
|
|
76
|
+
event_name: "calls",
|
|
77
|
+
default_aggregation: { formula: "sum" },
|
|
78
|
+
customer_mapping: {
|
|
79
|
+
type: "by_id",
|
|
80
|
+
event_payload_key: "stripe_customer_id",
|
|
81
|
+
},
|
|
82
|
+
value_settings: { event_payload_key: "value" },
|
|
83
|
+
event_time_window: null,
|
|
84
|
+
}
|
|
85
|
+
: path === "/v1/subscriptions/sub_calls"
|
|
86
|
+
? {
|
|
87
|
+
id: "sub_calls",
|
|
88
|
+
livemode: false,
|
|
89
|
+
customer: "cus_buyer",
|
|
90
|
+
customer_account: "acct_buyer",
|
|
91
|
+
}
|
|
92
|
+
: status === 200
|
|
93
|
+
? {
|
|
94
|
+
object: "billing.meter_event",
|
|
95
|
+
identifier: body.get("identifier"),
|
|
96
|
+
event_name: "calls",
|
|
97
|
+
livemode: false,
|
|
98
|
+
timestamp: now,
|
|
99
|
+
created: now,
|
|
100
|
+
payload: { stripe_customer_id: "cus_buyer", value: "120" },
|
|
101
|
+
}
|
|
102
|
+
: {
|
|
103
|
+
error: {
|
|
104
|
+
type: status === 429 ? "rate_limit_error" : "api_error",
|
|
105
|
+
message: "private provider detail",
|
|
106
|
+
code: errorCode,
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
if (path === "/v1/billing/meter_events" && status === 0)
|
|
110
|
+
throw new Error("Lost accepted response");
|
|
111
|
+
return new Response(JSON.stringify(value), {
|
|
112
|
+
status: path === "/v1/billing/meter_events" ? status : 200,
|
|
113
|
+
headers: { "content-type": "application/json" },
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
const request = {
|
|
117
|
+
scope,
|
|
118
|
+
eventId: "event",
|
|
119
|
+
attempt: 1,
|
|
120
|
+
definitionVersion: 1 as const,
|
|
121
|
+
apiVersion: STRIPE_API_VERSION,
|
|
122
|
+
identifier: "bs_usage_event",
|
|
123
|
+
};
|
|
124
|
+
return { ctx, request, requests, httpClient, saved };
|
|
125
|
+
}
|
|
126
|
+
it("sends scaled native values with stable identifiers and no SDK retries", async () => {
|
|
127
|
+
const f = setup();
|
|
128
|
+
const result = await deliverUsageProvider(
|
|
129
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
130
|
+
f.ctx,
|
|
131
|
+
f.request,
|
|
132
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
133
|
+
);
|
|
134
|
+
expect(result).toMatchObject({
|
|
135
|
+
...f.request,
|
|
136
|
+
outcome: { status: "accepted" },
|
|
137
|
+
});
|
|
138
|
+
const posts = f.requests.filter((r) => r.path === "/v1/billing/meter_events");
|
|
139
|
+
expect(posts).toHaveLength(1);
|
|
140
|
+
expect(posts[0].body.get("payload[value]")).toBe("120");
|
|
141
|
+
expect(posts[0].headers.get("idempotency-key")).toBe("bs_usage_event");
|
|
142
|
+
expect(posts[0].headers.get("stripe-version")).toBe(STRIPE_API_VERSION);
|
|
143
|
+
});
|
|
144
|
+
it.each([
|
|
145
|
+
[429, "rate_limited"],
|
|
146
|
+
[500, "unknown"],
|
|
147
|
+
[401, "unavailable"],
|
|
148
|
+
[400, "rejected"],
|
|
149
|
+
])(
|
|
150
|
+
"classifies HTTP %i without leaking raw errors",
|
|
151
|
+
async (status, expected) => {
|
|
152
|
+
const f = setup(status);
|
|
153
|
+
const result = await deliverUsageProvider(
|
|
154
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
155
|
+
f.ctx,
|
|
156
|
+
f.request,
|
|
157
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
158
|
+
);
|
|
159
|
+
expect(result).toMatchObject({ outcome: { status: expected } });
|
|
160
|
+
expect(JSON.stringify(result)).not.toContain("private provider detail");
|
|
161
|
+
expect(
|
|
162
|
+
f.requests.filter((r) => r.path === "/v1/billing/meter_events"),
|
|
163
|
+
).toHaveLength(1);
|
|
164
|
+
},
|
|
165
|
+
);
|
|
166
|
+
it("does not send after the deduplication window or with unavailable credentials", async () => {
|
|
167
|
+
const f = setup();
|
|
168
|
+
f.saved.outbox.firstSendAt -= 24 * 3600;
|
|
169
|
+
expect(
|
|
170
|
+
await deliverUsageProvider(
|
|
171
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
172
|
+
f.ctx,
|
|
173
|
+
f.request,
|
|
174
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
175
|
+
),
|
|
176
|
+
).toMatchObject({ outcome: { status: "unknown" } });
|
|
177
|
+
expect(f.requests).toHaveLength(0);
|
|
178
|
+
const other = setup();
|
|
179
|
+
expect(
|
|
180
|
+
await deliverUsageProvider(
|
|
181
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
182
|
+
other.ctx,
|
|
183
|
+
other.request,
|
|
184
|
+
{},
|
|
185
|
+
),
|
|
186
|
+
).toMatchObject({ outcome: { status: "unavailable" } });
|
|
187
|
+
expect(other.requests).toHaveLength(0);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("holds duplicate/uncertain errors and a lost response instead of retrying transport", async () => {
|
|
191
|
+
for (const [status, code] of [
|
|
192
|
+
[400, "duplicate_meter_event"],
|
|
193
|
+
[0, "lost"],
|
|
194
|
+
] as const) {
|
|
195
|
+
const f = setup(status, code);
|
|
196
|
+
const result = await deliverUsageProvider(
|
|
197
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
198
|
+
f.ctx,
|
|
199
|
+
f.request,
|
|
200
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
201
|
+
);
|
|
202
|
+
expect(result).toMatchObject({ outcome: { status: "unknown" } });
|
|
203
|
+
expect(
|
|
204
|
+
f.requests.filter((r) => r.path === "/v1/billing/meter_events"),
|
|
205
|
+
).toHaveLength(1);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import type { StripeApiVersion } from "../stripe-types.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import { resolveStripeApiVersion } from "../apiVersion.js";
|
|
7
|
+
import { scopeSchema, type PreparedUsageRecord } from "./records.js";
|
|
8
|
+
import { verifyRealm, verifyMeter, UsageCatalogError } from "./catalogTypes.js";
|
|
9
|
+
import { subscriptionSnapshot } from "../../component/usage/helpers.js";
|
|
10
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
11
|
+
export const usageDeliveryRequest = z.strictObject({
|
|
12
|
+
scope: scopeSchema,
|
|
13
|
+
eventId: z.string().min(1).max(100),
|
|
14
|
+
attempt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
15
|
+
definitionVersion: z.literal(1),
|
|
16
|
+
apiVersion: z.string(),
|
|
17
|
+
identifier: z
|
|
18
|
+
.string()
|
|
19
|
+
.regex(/^bs_usage_[a-zA-Z0-9_]+$/)
|
|
20
|
+
.max(100),
|
|
21
|
+
});
|
|
22
|
+
export type UsageDeliveryRequest = z.infer<typeof usageDeliveryRequest>;
|
|
23
|
+
export type UsageDeliveryOutcome =
|
|
24
|
+
| { status: "accepted"; created: number }
|
|
25
|
+
| { status: "rate_limited" | "unavailable" | "unknown" | "rejected" };
|
|
26
|
+
export type UsageDeliveryProviderOptions = {
|
|
27
|
+
stripeSecretKey?: string;
|
|
28
|
+
httpClient?: Stripe.HttpClient;
|
|
29
|
+
};
|
|
30
|
+
/** Internal host action only. Options never enter component or Workflow state. */
|
|
31
|
+
export async function deliverUsageProvider(
|
|
32
|
+
component: Component,
|
|
33
|
+
ctx: RunCtx,
|
|
34
|
+
input: UsageDeliveryRequest,
|
|
35
|
+
options: UsageDeliveryProviderOptions,
|
|
36
|
+
): Promise<UsageDeliveryRequest & { outcome: UsageDeliveryOutcome }> {
|
|
37
|
+
const args = usageDeliveryRequest.parse(input);
|
|
38
|
+
const done = (outcome: UsageDeliveryOutcome) => ({ ...args, outcome });
|
|
39
|
+
if (!options.stripeSecretKey) return done({ status: "unavailable" });
|
|
40
|
+
let writing = false;
|
|
41
|
+
try {
|
|
42
|
+
const apiVersion = resolveStripeApiVersion(args.apiVersion);
|
|
43
|
+
const stripe = new Stripe(options.stripeSecretKey, {
|
|
44
|
+
apiVersion: apiVersion as StripeApiVersion,
|
|
45
|
+
maxNetworkRetries: 0,
|
|
46
|
+
timeout: 15000,
|
|
47
|
+
...(options.httpClient ? { httpClient: options.httpClient } : {}),
|
|
48
|
+
});
|
|
49
|
+
const read = () =>
|
|
50
|
+
ctx.runQuery(componentRef(component, "usageDelivery/queries/snapshot"), {
|
|
51
|
+
scope: args.scope,
|
|
52
|
+
eventId: args.eventId,
|
|
53
|
+
}) as Promise<{ event: Doc<"usageEvents">; outbox: Doc<"usageOutbox"> }>;
|
|
54
|
+
const saved = await read(),
|
|
55
|
+
record = JSON.parse(saved.event.recordJson) as PreparedUsageRecord;
|
|
56
|
+
const eligible = (outbox: Doc<"usageOutbox">) =>
|
|
57
|
+
outbox.state === "sending" &&
|
|
58
|
+
!outbox.held &&
|
|
59
|
+
outbox.attempts === args.attempt &&
|
|
60
|
+
outbox.definitionVersion === args.definitionVersion &&
|
|
61
|
+
outbox.providerIdentifier === args.identifier &&
|
|
62
|
+
outbox.firstSendAt !== undefined &&
|
|
63
|
+
Date.now() / 1000 - outbox.firstSendAt < 23 * 3600 &&
|
|
64
|
+
(outbox.leaseUntil ?? 0) > Date.now() / 1000 + 60;
|
|
65
|
+
if (
|
|
66
|
+
!eligible(saved.outbox) ||
|
|
67
|
+
record.binding.apiVersion !== apiVersion ||
|
|
68
|
+
JSON.stringify(record.scope) !== JSON.stringify(args.scope)
|
|
69
|
+
)
|
|
70
|
+
return done({ status: "unknown" });
|
|
71
|
+
const now = Math.floor(Date.now() / 1000);
|
|
72
|
+
if (record.occurredAt < now - 35 * 86400 || record.occurredAt > now + 300)
|
|
73
|
+
return done({ status: "rejected" });
|
|
74
|
+
await verifyRealm(stripe, {
|
|
75
|
+
stripeAccountId: args.scope.stripeAccountId,
|
|
76
|
+
livemode: args.scope.livemode,
|
|
77
|
+
});
|
|
78
|
+
const binding = subscriptionSnapshot(saved.event.subscriptionJson);
|
|
79
|
+
const [meter, subscription] = await Promise.all([
|
|
80
|
+
stripe.billing.meters.retrieve(args.scope.meterId),
|
|
81
|
+
stripe.subscriptions.retrieve(binding.subscriptionId),
|
|
82
|
+
]);
|
|
83
|
+
if (
|
|
84
|
+
meter.id !== args.scope.meterId ||
|
|
85
|
+
subscription.id !== binding.subscriptionId ||
|
|
86
|
+
subscription.livemode !== args.scope.livemode ||
|
|
87
|
+
subscription.customer_account !== args.scope.customerAccount ||
|
|
88
|
+
(typeof subscription.customer === "string"
|
|
89
|
+
? subscription.customer
|
|
90
|
+
: subscription.customer?.id) !== record.binding.stripeCustomerId
|
|
91
|
+
)
|
|
92
|
+
return done({ status: "rejected" });
|
|
93
|
+
verifyMeter(meter, {
|
|
94
|
+
scope: args.scope,
|
|
95
|
+
plan: record.binding.plan,
|
|
96
|
+
eventName: record.binding.eventName,
|
|
97
|
+
displayName: meter.display_name,
|
|
98
|
+
});
|
|
99
|
+
if (!eligible((await read()).outbox)) return done({ status: "unknown" });
|
|
100
|
+
writing = true;
|
|
101
|
+
const response = await stripe.billing.meterEvents.create(
|
|
102
|
+
{
|
|
103
|
+
event_name: record.binding.eventName,
|
|
104
|
+
identifier: args.identifier,
|
|
105
|
+
timestamp: record.occurredAt,
|
|
106
|
+
payload: {
|
|
107
|
+
stripe_customer_id: record.binding.stripeCustomerId,
|
|
108
|
+
value: record.scaledQuantity,
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
{ idempotencyKey: args.identifier },
|
|
112
|
+
);
|
|
113
|
+
if (
|
|
114
|
+
response.identifier !== args.identifier ||
|
|
115
|
+
response.event_name !== record.binding.eventName ||
|
|
116
|
+
response.livemode !== args.scope.livemode ||
|
|
117
|
+
response.timestamp !== record.occurredAt ||
|
|
118
|
+
response.payload.stripe_customer_id !== record.binding.stripeCustomerId ||
|
|
119
|
+
String(response.payload.value) !== record.scaledQuantity ||
|
|
120
|
+
!Number.isSafeInteger(response.created) ||
|
|
121
|
+
response.created < 0
|
|
122
|
+
)
|
|
123
|
+
return done({ status: "unknown" });
|
|
124
|
+
return done({ status: "accepted", created: response.created });
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (!writing)
|
|
127
|
+
return done({
|
|
128
|
+
status:
|
|
129
|
+
error instanceof UsageCatalogError &&
|
|
130
|
+
error.code === "unsupported_scope"
|
|
131
|
+
? "rejected"
|
|
132
|
+
: "unavailable",
|
|
133
|
+
});
|
|
134
|
+
const status =
|
|
135
|
+
error instanceof Stripe.errors.StripeError ? error.statusCode : undefined;
|
|
136
|
+
if (status === 429) return done({ status: "rate_limited" });
|
|
137
|
+
if (status === 401 || status === 403)
|
|
138
|
+
return done({ status: "unavailable" });
|
|
139
|
+
const code =
|
|
140
|
+
error instanceof Stripe.errors.StripeError ? error.code : undefined;
|
|
141
|
+
if (
|
|
142
|
+
status === 404 ||
|
|
143
|
+
(status === 400 &&
|
|
144
|
+
code !== undefined &&
|
|
145
|
+
[
|
|
146
|
+
"parameter_invalid_integer",
|
|
147
|
+
"parameter_invalid_empty",
|
|
148
|
+
"parameter_missing",
|
|
149
|
+
"resource_missing",
|
|
150
|
+
].includes(code))
|
|
151
|
+
)
|
|
152
|
+
return done({ status: "rejected" });
|
|
153
|
+
return done({ status: "unknown" });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -32,3 +32,16 @@ export type {
|
|
|
32
32
|
UsageProviderCapabilities,
|
|
33
33
|
UsageContractPort,
|
|
34
34
|
} from "./boundaries.js";
|
|
35
|
+
|
|
36
|
+
export type {
|
|
37
|
+
UsageDeliveryRequest,
|
|
38
|
+
UsageDeliveryOutcome,
|
|
39
|
+
UsageDeliveryProviderOptions,
|
|
40
|
+
} from "./deliveryProvider.js";
|
|
41
|
+
export type {
|
|
42
|
+
UsageDeliveryRef,
|
|
43
|
+
UsageDeliveryStatus,
|
|
44
|
+
UsageDeliveryStartOptions,
|
|
45
|
+
} from "./deliveryClient.js";
|
|
46
|
+
|
|
47
|
+
export { usageDeliveryArgs, usageDeliveryResult } from "./deliveryProtocol.js";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isMeterErrorEvent } from "./meterErrors.js";
|
|
1
2
|
import type Stripe from "stripe";
|
|
2
3
|
|
|
3
4
|
import type { Component } from "../helpers.js";
|
|
@@ -41,7 +42,7 @@ export async function handleWebhookRequest(
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
const eventType = (parsedBody.type as string) ?? "";
|
|
44
|
-
const isV2Event = eventType.startsWith("v2.");
|
|
45
|
+
const isV2Event = eventType.startsWith("v2.") || isMeterErrorEvent(eventType);
|
|
45
46
|
|
|
46
47
|
const stripeSecretKey = config?.stripeSecretKey;
|
|
47
48
|
const stripeApiVersion = config?.stripeApiVersion;
|