@fantastic.dev/better-stripe 0.57.0 → 0.58.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 +6 -0
- package/README.md +3 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +122 -36
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +45 -2
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +122 -36
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +45 -2
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/usage/allowanceClient.d.ts +51 -0
- package/dist/client/usage/allowanceClient.d.ts.map +1 -0
- package/dist/client/usage/allowanceClient.js +64 -0
- package/dist/client/usage/allowanceClient.js.map +1 -0
- package/dist/client/usage/allowanceTerms.d.ts +64 -0
- package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
- package/dist/client/usage/allowanceTerms.js +101 -0
- package/dist/client/usage/allowanceTerms.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 +2 -2
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/index.d.ts +2 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usageExports.d.ts +2 -0
- package/dist/client/usageExports.d.ts.map +1 -1
- package/dist/component/_generated/api.d.ts +8 -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 +70 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +16 -16
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/earnings/triggers.d.ts +110 -18
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +45 -2
- package/dist/component/schema.js +3 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/mutations.d.ts.map +1 -1
- package/dist/component/usage/mutations.js +4 -0
- package/dist/component/usage/mutations.js.map +1 -1
- package/dist/component/usage/schema.d.ts +3 -2
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +2 -1
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageAllowance/helpers.d.ts +78 -0
- package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
- package/dist/component/usageAllowance/helpers.js +99 -0
- package/dist/component/usageAllowance/helpers.js.map +1 -0
- package/dist/component/usageAllowance/mutations.d.ts +37 -0
- package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
- package/dist/component/usageAllowance/mutations.js +99 -0
- package/dist/component/usageAllowance/mutations.js.map +1 -0
- package/dist/component/usageAllowance/queries.d.ts +36 -0
- package/dist/component/usageAllowance/queries.d.ts.map +1 -0
- package/dist/component/usageAllowance/queries.js +113 -0
- package/dist/component/usageAllowance/queries.js.map +1 -0
- package/dist/component/usageAllowance/reservations.d.ts +25 -0
- package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
- package/dist/component/usageAllowance/reservations.js +150 -0
- package/dist/component/usageAllowance/reservations.js.map +1 -0
- package/dist/component/usageAllowance/schema.d.ts +77 -0
- package/dist/component/usageAllowance/schema.d.ts.map +1 -0
- package/dist/component/usageAllowance/schema.js +32 -0
- package/dist/component/usageAllowance/schema.js.map +1 -0
- package/docs/README.md +2 -0
- package/docs/usage-limits.md +217 -0
- package/package.json +2 -1
- package/src/client/usage/allowanceClient.test.ts +93 -0
- package/src/client/usage/allowanceClient.ts +134 -0
- package/src/client/usage/allowanceTerms.test.ts +131 -0
- package/src/client/usage/allowanceTerms.ts +172 -0
- package/src/client/usage/client.ts +2 -2
- package/src/client/usage/index.ts +8 -0
- package/src/client/usageExports.ts +8 -0
- package/src/component/_generated/api.ts +8 -0
- package/src/component/_generated/component.ts +94 -0
- package/src/component/schema.ts +6 -0
- package/src/component/usage/allowance.test.ts +435 -0
- package/src/component/usage/mutations.ts +13 -0
- package/src/component/usage/schema.ts +4 -1
- package/src/component/usageAllowance/helpers.ts +137 -0
- package/src/component/usageAllowance/mutations.ts +139 -0
- package/src/component/usageAllowance/queries.ts +133 -0
- package/src/component/usageAllowance/reservations.ts +220 -0
- package/src/component/usageAllowance/schema.ts +36 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { prepareUsageRecord, } from "../../client/usage/records.js";
|
|
2
|
+
import { allowanceStatus, limitPolicy, } from "../../client/usage/allowanceTerms.js";
|
|
3
|
+
import { parseUsageQuantity } from "../../client/usage/contracts.js";
|
|
4
|
+
import { subscriptionSnapshot, scopeKey } from "../usage/helpers.js";
|
|
5
|
+
import { terms, json, canonical, policyRow, active, history, overlapping, scopeOverlap, configuredScope, } from "./helpers.js";
|
|
6
|
+
export async function reserve(ctx, inputJson, subscriptionJson) {
|
|
7
|
+
const event = prepareUsageRecord(json(inputJson)), subscription = subscriptionSnapshot(subscriptionJson), original = terms({
|
|
8
|
+
scope: event.scope,
|
|
9
|
+
binding: event.binding,
|
|
10
|
+
subscription,
|
|
11
|
+
});
|
|
12
|
+
const input = canonical(event), sub = canonical(subscription);
|
|
13
|
+
const prior = await ctx.db
|
|
14
|
+
.query("usageReservations")
|
|
15
|
+
.withIndex("by_scope_source", (q) => q
|
|
16
|
+
.eq("scopeKey", original.scopeKey)
|
|
17
|
+
.eq("sourceEventId", event.sourceEventId))
|
|
18
|
+
.unique();
|
|
19
|
+
if (prior) {
|
|
20
|
+
if (prior.accountingKind !== "allowance" ||
|
|
21
|
+
prior.inputJson !== input ||
|
|
22
|
+
prior.subscriptionJson !== sub)
|
|
23
|
+
throw new Error("Allowance reservation replay conflict");
|
|
24
|
+
return {
|
|
25
|
+
reservationId: prior._id,
|
|
26
|
+
state: prior.state,
|
|
27
|
+
revision: Number(prior.allocationsJson),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const accepted = await ctx.db
|
|
31
|
+
.query("usageEvents")
|
|
32
|
+
.withIndex("by_identity", (q) => q.eq("identity", event.identity))
|
|
33
|
+
.unique();
|
|
34
|
+
if (accepted)
|
|
35
|
+
throw new Error("Accepted usage cannot be reserved again");
|
|
36
|
+
const row = await policyRow(ctx, original.key);
|
|
37
|
+
if (!row || row.bindingJson !== original.bindingJson)
|
|
38
|
+
throw new Error("Allowance policy unavailable");
|
|
39
|
+
await active(ctx, original.binding, event);
|
|
40
|
+
const policy = limitPolicy(JSON.parse(row.policyJson), original.binding), status = allowanceStatus(original.binding, policy, row, Math.floor(Date.now() / 1000));
|
|
41
|
+
if (!policy.entitled)
|
|
42
|
+
return {
|
|
43
|
+
state: "denied",
|
|
44
|
+
reason: "not_entitled",
|
|
45
|
+
revision: row.revision,
|
|
46
|
+
};
|
|
47
|
+
if (status.hardLimitRemainingQuantity !== null &&
|
|
48
|
+
BigInt(event.scaledQuantity) >
|
|
49
|
+
BigInt(parseUsageQuantity(status.hardLimitRemainingQuantity, event.binding.plan.unit.precision).scaledQuantity))
|
|
50
|
+
return {
|
|
51
|
+
state: "denied",
|
|
52
|
+
reason: "hard_limit",
|
|
53
|
+
revision: row.revision,
|
|
54
|
+
};
|
|
55
|
+
const reserved = BigInt(row.reserved) + BigInt(event.scaledQuantity);
|
|
56
|
+
if (reserved + BigInt(row.consumed) > 999999999999999999n)
|
|
57
|
+
throw new Error("Allowance accounting quantity bound exceeded");
|
|
58
|
+
const reservationId = await ctx.db.insert("usageReservations", {
|
|
59
|
+
scopeKey: original.scopeKey,
|
|
60
|
+
sourceEventId: event.sourceEventId,
|
|
61
|
+
planJson: JSON.stringify(event.binding.plan),
|
|
62
|
+
scaledQuantity: event.scaledQuantity,
|
|
63
|
+
state: "reserved",
|
|
64
|
+
accountingKind: "allowance",
|
|
65
|
+
accountKey: row.key,
|
|
66
|
+
inputJson: input,
|
|
67
|
+
subscriptionJson: sub,
|
|
68
|
+
allocationsJson: String(row.revision),
|
|
69
|
+
});
|
|
70
|
+
await ctx.db.patch("usageAllowancePolicies", row._id, {
|
|
71
|
+
reserved: reserved.toString(),
|
|
72
|
+
});
|
|
73
|
+
await history(ctx, row, "reservation", {
|
|
74
|
+
reservationId,
|
|
75
|
+
event,
|
|
76
|
+
subscription,
|
|
77
|
+
revision: row.revision,
|
|
78
|
+
});
|
|
79
|
+
return { reservationId, state: "reserved", revision: row.revision };
|
|
80
|
+
}
|
|
81
|
+
export async function requireReservation(ctx, event, subscription, reservation) {
|
|
82
|
+
if (event.binding.plan.model === "prepaid")
|
|
83
|
+
return;
|
|
84
|
+
const original = terms({
|
|
85
|
+
scope: event.scope,
|
|
86
|
+
binding: event.binding,
|
|
87
|
+
subscription,
|
|
88
|
+
});
|
|
89
|
+
const row = (await overlapping(ctx, original.nativeKey, subscription.period)) ??
|
|
90
|
+
(await scopeOverlap(ctx, original.scopeKey, subscription.period));
|
|
91
|
+
if (!row && (await configuredScope(ctx, original)))
|
|
92
|
+
throw new Error("New allowance period requires policy configuration and reservation");
|
|
93
|
+
if (row &&
|
|
94
|
+
(row.bindingJson !== original.bindingJson ||
|
|
95
|
+
!reservation ||
|
|
96
|
+
reservation.accountingKind !== "allowance" ||
|
|
97
|
+
reservation.accountKey !== row.key))
|
|
98
|
+
throw new Error("Matching allowance reservation required");
|
|
99
|
+
}
|
|
100
|
+
export async function commit(ctx, reservation, event, subscription, eventId) {
|
|
101
|
+
if (reservation.accountingKind !== "allowance" ||
|
|
102
|
+
!reservation.accountKey ||
|
|
103
|
+
reservation.inputJson !== canonical(event) ||
|
|
104
|
+
reservation.subscriptionJson !== canonical(subscription))
|
|
105
|
+
throw new Error("Allowance reservation provenance mismatch");
|
|
106
|
+
const row = await policyRow(ctx, reservation.accountKey);
|
|
107
|
+
if (!row || BigInt(row.reserved) < BigInt(reservation.scaledQuantity))
|
|
108
|
+
throw new Error("Allowance reservation backing unavailable");
|
|
109
|
+
await ctx.db.patch("usageAllowancePolicies", row._id, {
|
|
110
|
+
reserved: (BigInt(row.reserved) - BigInt(reservation.scaledQuantity)).toString(),
|
|
111
|
+
consumed: (BigInt(row.consumed) + BigInt(reservation.scaledQuantity)).toString(),
|
|
112
|
+
});
|
|
113
|
+
await history(ctx, row, "commit", {
|
|
114
|
+
reservationId: reservation._id,
|
|
115
|
+
eventId,
|
|
116
|
+
revision: Number(reservation.allocationsJson),
|
|
117
|
+
scaledQuantity: reservation.scaledQuantity,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
export async function release(ctx, scope, reservationId, reason) {
|
|
121
|
+
const row = await ctx.db.get("usageReservations", reservationId);
|
|
122
|
+
if (!row ||
|
|
123
|
+
row.scopeKey !== scopeKey(scope) ||
|
|
124
|
+
row.accountingKind !== "allowance" ||
|
|
125
|
+
!row.accountKey)
|
|
126
|
+
throw new Error("Allowance reservation unavailable");
|
|
127
|
+
if (row.state === "committed" || row.eventId)
|
|
128
|
+
throw new Error("Committed usage requires an auditable correction");
|
|
129
|
+
if (row.state === "released") {
|
|
130
|
+
if (row.releaseReason !== reason)
|
|
131
|
+
throw new Error("Allowance release replay conflict");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const policy = await policyRow(ctx, row.accountKey);
|
|
135
|
+
if (!policy || BigInt(policy.reserved) < BigInt(row.scaledQuantity))
|
|
136
|
+
throw new Error("Allowance reservation invariant violated");
|
|
137
|
+
await ctx.db.patch("usageAllowancePolicies", policy._id, {
|
|
138
|
+
reserved: (BigInt(policy.reserved) - BigInt(row.scaledQuantity)).toString(),
|
|
139
|
+
});
|
|
140
|
+
await ctx.db.patch("usageReservations", row._id, {
|
|
141
|
+
state: "released",
|
|
142
|
+
releaseReason: reason,
|
|
143
|
+
});
|
|
144
|
+
await history(ctx, policy, "release", {
|
|
145
|
+
reservationId,
|
|
146
|
+
reason,
|
|
147
|
+
scaledQuantity: row.scaledQuantity,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=reservations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reservations.js","sourceRoot":"","sources":["../../../src/component/usageAllowance/reservations.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,kBAAkB,GAGnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,eAAe,EACf,WAAW,GACZ,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EACL,KAAK,EACL,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,OAAO,EACP,WAAW,EACX,YAAY,EACZ,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,GAAgB,EAChB,SAAiB,EACjB,gBAAwB;IAExB,MAAM,KAAK,GAAG,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,EAC/C,YAAY,GAAG,oBAAoB,CAAC,gBAAgB,CAAC,EACrD,QAAQ,GAAG,KAAK,CAAC;QACf,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY;KACb,CAAC,CAAC;IACL,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,EAC5B,GAAG,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC;IAChC,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,EAAE;SACvB,KAAK,CAAC,mBAAmB,CAAC;SAC1B,SAAS,CAAC,iBAAiB,EAAE,CAAC,CAAC,EAAE,EAAE,CAClC,CAAC;SACE,EAAE,CAAC,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,CAAC,CAAC,QAAQ,EAAE;KAC5E,CAAC,CAAC;IACH,MAAM,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,GAAG,EAAE;QAC/C,KAAK,EAAE,UAAU;QACjB,aAAa,EAAE,MAAM;KACtB,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE;QACpC,aAAa;QACb,MAAM;QACN,cAAc,EAAE,GAAG,CAAC,cAAc;KACnC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export declare const fields: {
|
|
2
|
+
key: import("convex/values").VString<string, "required">;
|
|
3
|
+
nativeKey: import("convex/values").VString<string, "required">;
|
|
4
|
+
scopeKey: import("convex/values").VString<string, "required">;
|
|
5
|
+
bindingJson: import("convex/values").VString<string, "required">;
|
|
6
|
+
start: import("convex/values").VFloat64<number, "required">;
|
|
7
|
+
end: import("convex/values").VFloat64<number, "required">;
|
|
8
|
+
policyJson: import("convex/values").VString<string, "required">;
|
|
9
|
+
revision: import("convex/values").VFloat64<number, "required">;
|
|
10
|
+
consumed: import("convex/values").VString<string, "required">;
|
|
11
|
+
reserved: import("convex/values").VString<string, "required">;
|
|
12
|
+
historyCount: import("convex/values").VFloat64<number, "required">;
|
|
13
|
+
};
|
|
14
|
+
export declare const policiesTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
|
|
15
|
+
bindingJson: string;
|
|
16
|
+
consumed: string;
|
|
17
|
+
end: number;
|
|
18
|
+
historyCount: number;
|
|
19
|
+
key: string;
|
|
20
|
+
nativeKey: string;
|
|
21
|
+
policyJson: string;
|
|
22
|
+
reserved: string;
|
|
23
|
+
revision: number;
|
|
24
|
+
scopeKey: string;
|
|
25
|
+
start: number;
|
|
26
|
+
}, {
|
|
27
|
+
key: import("convex/values").VString<string, "required">;
|
|
28
|
+
nativeKey: import("convex/values").VString<string, "required">;
|
|
29
|
+
scopeKey: import("convex/values").VString<string, "required">;
|
|
30
|
+
bindingJson: import("convex/values").VString<string, "required">;
|
|
31
|
+
start: import("convex/values").VFloat64<number, "required">;
|
|
32
|
+
end: import("convex/values").VFloat64<number, "required">;
|
|
33
|
+
policyJson: import("convex/values").VString<string, "required">;
|
|
34
|
+
revision: import("convex/values").VFloat64<number, "required">;
|
|
35
|
+
consumed: import("convex/values").VString<string, "required">;
|
|
36
|
+
reserved: import("convex/values").VString<string, "required">;
|
|
37
|
+
historyCount: import("convex/values").VFloat64<number, "required">;
|
|
38
|
+
}, "required", "bindingJson" | "consumed" | "end" | "historyCount" | "key" | "nativeKey" | "policyJson" | "reserved" | "revision" | "scopeKey" | "start">, {
|
|
39
|
+
by_key: ["key", "_creationTime"];
|
|
40
|
+
by_native_start: ["nativeKey", "start", "_creationTime"];
|
|
41
|
+
by_scope_start: ["scopeKey", "start", "_creationTime"];
|
|
42
|
+
}, {}, {}>;
|
|
43
|
+
export declare const historyFields: {
|
|
44
|
+
key: import("convex/values").VString<string, "required">;
|
|
45
|
+
kind: import("convex/values").VUnion<"commit" | "policy" | "release" | "reservation", [import("convex/values").VLiteral<"policy", "required">, import("convex/values").VLiteral<"reservation", "required">, import("convex/values").VLiteral<"commit", "required">, import("convex/values").VLiteral<"release", "required">], "required", never>;
|
|
46
|
+
evidenceJson: import("convex/values").VString<string, "required">;
|
|
47
|
+
at: import("convex/values").VFloat64<number, "required">;
|
|
48
|
+
};
|
|
49
|
+
export declare const historyDoc: import("convex/values").VObject<{
|
|
50
|
+
_creationTime: number;
|
|
51
|
+
_id: import("convex/values").GenericId<"usageAllowanceHistory">;
|
|
52
|
+
at: number;
|
|
53
|
+
evidenceJson: string;
|
|
54
|
+
key: string;
|
|
55
|
+
kind: "commit" | "policy" | "release" | "reservation";
|
|
56
|
+
}, {
|
|
57
|
+
key: import("convex/values").VString<string, "required">;
|
|
58
|
+
kind: import("convex/values").VUnion<"commit" | "policy" | "release" | "reservation", [import("convex/values").VLiteral<"policy", "required">, import("convex/values").VLiteral<"reservation", "required">, import("convex/values").VLiteral<"commit", "required">, import("convex/values").VLiteral<"release", "required">], "required", never>;
|
|
59
|
+
evidenceJson: import("convex/values").VString<string, "required">;
|
|
60
|
+
at: import("convex/values").VFloat64<number, "required">;
|
|
61
|
+
_id: import("convex/values").VId<import("convex/values").GenericId<"usageAllowanceHistory">, "required">;
|
|
62
|
+
_creationTime: import("convex/values").VFloat64<number, "required">;
|
|
63
|
+
}, "required", "_creationTime" | "_id" | "at" | "evidenceJson" | "key" | "kind">;
|
|
64
|
+
export declare const historyTable: import("convex/server").TableDefinition<import("convex/values").VObject<{
|
|
65
|
+
at: number;
|
|
66
|
+
evidenceJson: string;
|
|
67
|
+
key: string;
|
|
68
|
+
kind: "commit" | "policy" | "release" | "reservation";
|
|
69
|
+
}, {
|
|
70
|
+
key: import("convex/values").VString<string, "required">;
|
|
71
|
+
kind: import("convex/values").VUnion<"commit" | "policy" | "release" | "reservation", [import("convex/values").VLiteral<"policy", "required">, import("convex/values").VLiteral<"reservation", "required">, import("convex/values").VLiteral<"commit", "required">, import("convex/values").VLiteral<"release", "required">], "required", never>;
|
|
72
|
+
evidenceJson: import("convex/values").VString<string, "required">;
|
|
73
|
+
at: import("convex/values").VFloat64<number, "required">;
|
|
74
|
+
}, "required", "at" | "evidenceJson" | "key" | "kind">, {
|
|
75
|
+
by_key: ["key", "_creationTime"];
|
|
76
|
+
}, {}, {}>;
|
|
77
|
+
//# sourceMappingURL=schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/component/usageAllowance/schema.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,MAAM;IACjB,GAAG;IACH,SAAS;IACT,QAAQ;IACR,WAAW;IACX,KAAK;IACL,GAAG;IACH,UAAU;IACV,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,YAAY;CACb,CAAC;AACF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAGuB,CAAC;AAClD,eAAO,MAAM,aAAa;IACxB,GAAG;IACH,IAAI;IAMJ,YAAY;IACZ,EAAE;CACH,CAAC;AACF,eAAO,MAAM,UAAU;;;;;;;;;;;;;;gFAIrB,CAAC;AACH,eAAO,MAAM,YAAY;;;;;;;;;;;;UAAsD,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { defineTable } from "convex/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
export const fields = {
|
|
4
|
+
key: v.string(),
|
|
5
|
+
nativeKey: v.string(),
|
|
6
|
+
scopeKey: v.string(),
|
|
7
|
+
bindingJson: v.string(),
|
|
8
|
+
start: v.number(),
|
|
9
|
+
end: v.number(),
|
|
10
|
+
policyJson: v.string(),
|
|
11
|
+
revision: v.number(),
|
|
12
|
+
consumed: v.string(),
|
|
13
|
+
reserved: v.string(),
|
|
14
|
+
historyCount: v.number(),
|
|
15
|
+
};
|
|
16
|
+
export const policiesTable = defineTable(fields)
|
|
17
|
+
.index("by_key", ["key"])
|
|
18
|
+
.index("by_native_start", ["nativeKey", "start"])
|
|
19
|
+
.index("by_scope_start", ["scopeKey", "start"]);
|
|
20
|
+
export const historyFields = {
|
|
21
|
+
key: v.string(),
|
|
22
|
+
kind: v.union(v.literal("policy"), v.literal("reservation"), v.literal("commit"), v.literal("release")),
|
|
23
|
+
evidenceJson: v.string(),
|
|
24
|
+
at: v.number(),
|
|
25
|
+
};
|
|
26
|
+
export const historyDoc = v.object({
|
|
27
|
+
_id: v.id("usageAllowanceHistory"),
|
|
28
|
+
_creationTime: v.number(),
|
|
29
|
+
...historyFields,
|
|
30
|
+
});
|
|
31
|
+
export const historyTable = defineTable(historyFields).index("by_key", ["key"]);
|
|
32
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/component/usageAllowance/schema.ts"],"names":[],"mappings":"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AAM,EAAE;CACf,CAAC;AACF,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC;IACjC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,uBAAuB,CAAC;IAClC,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE;IACzB,GAAG,aAAa;CACjB,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,WAAW,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC"}
|
package/docs/README.md
CHANGED
|
@@ -68,3 +68,5 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
|
|
|
68
68
|
[Managed metered subscriptions and invoice lifecycle](usage-subscriptions.md) covers all three models, Checkout, renewal, closeout and native test clocks.
|
|
69
69
|
|
|
70
70
|
- [Payment-backed prepaid usage](./usage-credits.md)
|
|
71
|
+
|
|
72
|
+
- [Included usage and limits](./usage-limits.md) covers atomic caps, reservations, period resets and exact overage estimates.
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Included usage and optional usage limits
|
|
2
|
+
|
|
3
|
+
BetterStripe supplies atomic quantity accounting for monthly included usage and
|
|
4
|
+
optional pay-as-you-go caps. Use native Stripe graduated prices for included
|
|
5
|
+
usage, provisioned by the [usage catalog](./usage-catalog.md), and enroll the
|
|
6
|
+
customer through [managed subscriptions](./usage-subscriptions.md). The free
|
|
7
|
+
first tier and original overage rate remain the billing terms. Limits control
|
|
8
|
+
access to work; they do not change the price or collect money.
|
|
9
|
+
|
|
10
|
+
Prepaid uses the separate [payment-backed credit APIs](./usage-credits.md).
|
|
11
|
+
`configureAllowance` rejects prepaid plans. No monetary wallet or extra usage
|
|
12
|
+
charge is created by allowance accounting.
|
|
13
|
+
|
|
14
|
+
## Configure before accepting usage
|
|
15
|
+
|
|
16
|
+
Authenticate and authorize policy management in a host mutation. Resolve the
|
|
17
|
+
payer, native customer, meter and original terms on the server. Do not accept
|
|
18
|
+
these identities or policy edits directly from an untrusted browser.
|
|
19
|
+
|
|
20
|
+
Use a binding returned by `stripe.usage.ensureSubscription`, `observeSubscription`
|
|
21
|
+
or `getSubscription`. Observe the current native subscription before initializing
|
|
22
|
+
a renewed period. A managed subscription must be active and its period must
|
|
23
|
+
still be open. This works with the supported managed collection methods.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
const original = subscription.bindings[0];
|
|
27
|
+
await stripe.usage.configureAllowance(ctx, {
|
|
28
|
+
...original,
|
|
29
|
+
expectedRevision: 0,
|
|
30
|
+
policy: {
|
|
31
|
+
entitled: true,
|
|
32
|
+
reset: "billing_period",
|
|
33
|
+
rollover: "none",
|
|
34
|
+
overage: "allow",
|
|
35
|
+
limit: { mode: "hard", quantity: "12000" },
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Configure every metered binding that needs limits. The plan supplies
|
|
41
|
+
`includedQuantity`, unit precision and the original decimal overage rate.
|
|
42
|
+
`limit.quantity` is total usage for the period, including free units, expressed as
|
|
43
|
+
an exact decimal string in that unit. A hard limit of 12000 with 10000 included
|
|
44
|
+
units permits 2000 billable overage units. `overage: "reject"` additionally caps
|
|
45
|
+
usage at the included quantity. The smaller hard cap wins.
|
|
46
|
+
|
|
47
|
+
`limit: { mode: "soft", quantity: "12000" }` reports a warning at the threshold
|
|
48
|
+
and continues accepting usage. `limit: { mode: "none" }` has no separate usage
|
|
49
|
+
threshold. `entitled: false` rejects new reservations. Pay-as-you-go supports
|
|
50
|
+
these optional total-usage thresholds with `overage: "allow"`; it has no free
|
|
51
|
+
included units. Prepaid insufficient-balance enforcement comes from paid grants.
|
|
52
|
+
|
|
53
|
+
This native v1 policy explicitly resets at the original monthly billing-period
|
|
54
|
+
boundary and has no rollover. Carrying free units or resetting on a calendar
|
|
55
|
+
month would disagree with the native price and is rejected. Change billing terms
|
|
56
|
+
at a verified future period, using the subscription lifecycle. Do not mutate an
|
|
57
|
+
existing period's free tier, price, currency, version or units.
|
|
58
|
+
|
|
59
|
+
Setup over existing unaccounted period usage is rejected. Reconcile that history
|
|
60
|
+
and enable the policy at the next verified period rather than granting a fresh
|
|
61
|
+
allowance over work already accepted. An overlapping period, new subscription or
|
|
62
|
+
changed binding cannot reset an existing counter. Once a native payer/meter or
|
|
63
|
+
logical scope has a policy, recording usage without a matching policy reservation
|
|
64
|
+
remains blocked at renewal until the next period is configured.
|
|
65
|
+
|
|
66
|
+
## Reserve before work, then commit with the ledger
|
|
67
|
+
|
|
68
|
+
Authorize the real activity in the host. Use its stable business identity for
|
|
69
|
+
`sourceEventId`, original occurrence time, and exact unit quantity. Reserve the
|
|
70
|
+
maximum quantity the work is allowed to perform. Commit that exact quantity;
|
|
71
|
+
changing it requires a new, explicitly authorized operation.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const event = {
|
|
75
|
+
scope: original.scope,
|
|
76
|
+
binding: original.binding,
|
|
77
|
+
sourceEventId: activity.id,
|
|
78
|
+
quantity: "5",
|
|
79
|
+
occurredAt: activity.occurredAt,
|
|
80
|
+
};
|
|
81
|
+
const reservation = await stripe.usage.reserveAllowance(ctx, {
|
|
82
|
+
event,
|
|
83
|
+
subscription: original.subscription,
|
|
84
|
+
});
|
|
85
|
+
if (reservation.state === "denied") {
|
|
86
|
+
return { allowed: false, reason: reservation.reason };
|
|
87
|
+
}
|
|
88
|
+
if (reservation.state === "released") {
|
|
89
|
+
return { allowed: false, reason: "work_previously_released" };
|
|
90
|
+
}
|
|
91
|
+
if (reservation.state === "reserved") {
|
|
92
|
+
// The worker must deduplicate real work using activity.id across retries.
|
|
93
|
+
await performIdempotentWork(activity.id);
|
|
94
|
+
}
|
|
95
|
+
const receipt = await stripe.usage.record(ctx, {
|
|
96
|
+
event,
|
|
97
|
+
subscription: original.subscription,
|
|
98
|
+
reservationId: reservation.reservationId,
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Reserve and record must run from a context that supports component mutations.
|
|
103
|
+
External work belongs in an action or durable worker. A query used to render a
|
|
104
|
+
button never grants permission to run work. Concurrent reservations update the
|
|
105
|
+
same counter transactionally, and hard-cap decisions include both consumed and
|
|
106
|
+
reserved units. Ledger acceptance commits the reservation, immutable event and
|
|
107
|
+
outbox in one transaction. A failed transaction rolls all of them back.
|
|
108
|
+
|
|
109
|
+
Exact reservation and record retries return their prior result. Changed quantity,
|
|
110
|
+
price, subscription, occurrence time or source identity conflicts. A committed
|
|
111
|
+
reservation must not run work again. A released reservation stays released.
|
|
112
|
+
Historical source identities remain reserved across periods and subscriptions.
|
|
113
|
+
|
|
114
|
+
A timeout or unknown worker result retains reserved capacity. Confirm work did
|
|
115
|
+
not happen before releasing it. There is no automatic lease expiry that could
|
|
116
|
+
admit a second job while the original job still runs.
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
await stripe.usage.releaseAllowance(ctx, {
|
|
120
|
+
scope: original.scope,
|
|
121
|
+
reservationId: reservation.reservationId,
|
|
122
|
+
reason: "work_failed", // or "abandoned_before_work"
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Release retries with the same reason are idempotent. A different reason conflicts.
|
|
127
|
+
Committed usage cannot be released. Delivery rejection, uncertainty, delayed
|
|
128
|
+
native aggregates or an unpaid invoice do not restore allowance. Corrections
|
|
129
|
+
retain the original event and terms and require an auditable correction outcome;
|
|
130
|
+
never decrement counters based on an invoice preview or an optimistic UI action.
|
|
131
|
+
The correction workflow is documented separately as it becomes available.
|
|
132
|
+
|
|
133
|
+
## Edit access policy without resetting consumption
|
|
134
|
+
|
|
135
|
+
Read `getAllowanceStatus` and pass its `revision` as `expectedRevision` when changing
|
|
136
|
+
limits or entitlement. An exact policy replay returns the current revision;
|
|
137
|
+
a different policy with a stale revision fails. Cap and entitlement changes keep
|
|
138
|
+
all consumed and reserved units. Lowering a cap below those units denies new work.
|
|
139
|
+
Already reserved work retains its original authorization and can commit once,
|
|
140
|
+
even after entitlement is disabled or the cap is lowered. To cancel that work,
|
|
141
|
+
stop the worker and explicitly release its uncommitted reservation.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
const status = await stripe.usage.getAllowanceStatus(ctx, original);
|
|
145
|
+
if (status) {
|
|
146
|
+
await stripe.usage.configureAllowance(ctx, {
|
|
147
|
+
...original,
|
|
148
|
+
expectedRevision: status.revision,
|
|
149
|
+
policy: { ...status.policy, entitled: false },
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
A new verified billing period gets a new counter. Historical counters and
|
|
155
|
+
reservations remain readable. A late reservation from a closing or old period
|
|
156
|
+
cannot become current-period usage. New acceptance closes 60 seconds before the
|
|
157
|
+
native period ends, matching the managed delivery lifecycle.
|
|
158
|
+
|
|
159
|
+
## Read status, evidence and reconciliation
|
|
160
|
+
|
|
161
|
+
`getAllowanceStatus(ctx, original)` returns `null` for an unavailable exact binding.
|
|
162
|
+
Otherwise it returns revision, observation time, period, policy, consumed and
|
|
163
|
+
reserved quantities, free units remaining after reservations, committed billable
|
|
164
|
+
overage, soft-limit state and remaining hard-cap capacity. `accepting` also
|
|
165
|
+
checks the current stored managed enrollment and closes on retirement or expiry.
|
|
166
|
+
It is a display observation; only a successful atomic reservation permits work.
|
|
167
|
+
Refresh the managed subscription through its native observation API when provider
|
|
168
|
+
state changes. A cached database view cannot prove a newly changed native state.
|
|
169
|
+
|
|
170
|
+
`committedEstimate` prices only committed usage. `projectedEstimate` also includes
|
|
171
|
+
reservations. Both use the original rate and exact decimal minor currency units.
|
|
172
|
+
They exclude fixed fees, tax, discounts and payment collection. The result always
|
|
173
|
+
reports `cashCollection: "none"`. Do not render estimates as available money,
|
|
174
|
+
paid invoices or seller/affiliate earnings.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
const local = await stripe.usage.reconcileAllowance(ctx, original);
|
|
178
|
+
const page = await stripe.usage.readAllowanceHistory(ctx, {
|
|
179
|
+
...original,
|
|
180
|
+
limit: 25,
|
|
181
|
+
cursor: null,
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The history reader pages immutable policy, reservation, commit and release evidence
|
|
186
|
+
for the exact binding. Limits are 1–100 rows, with a returned cursor. Evidence is
|
|
187
|
+
retained, with a quota of 100000 history records per period. Accounting mutations
|
|
188
|
+
fail atomically when that retained quota is exhausted.
|
|
189
|
+
|
|
190
|
+
`reconcileAllowance` compares the counter with immutable accepted events and open
|
|
191
|
+
reservations. It returns `matched` only with complete matching local evidence.
|
|
192
|
+
The read is bounded to 500 events and 500 open reservations; larger or conflicting
|
|
193
|
+
histories return `held`, never a false match. It does not repair or restore units.
|
|
194
|
+
Stop new work and investigate a held result through the paged ledger/history
|
|
195
|
+
readers. Native quantity/invoice comparison remains available through
|
|
196
|
+
`getReconciliation`, `getProviderUsage` and `readInvoiceUsage`; those observations do
|
|
197
|
+
not enforce or reset access caps. A native invoice's payment status cannot prove
|
|
198
|
+
new cash collection on its own.
|
|
199
|
+
|
|
200
|
+
## Developer and agent setup checklist
|
|
201
|
+
|
|
202
|
+
1. Use an ordinary Stripe test sandbox. No Metronome account or token is needed.
|
|
203
|
+
2. Follow [sandbox setup](./metering-setup.md), then provision the native catalog
|
|
204
|
+
and managed subscription with the package APIs. Keep secret keys server-side.
|
|
205
|
+
3. Select the included plan or an optional pay-as-you-go limit. Choose explicit
|
|
206
|
+
entitlement, reset, no-rollover, overage and hard/soft threshold policy.
|
|
207
|
+
4. Configure each current binding before accepting usage. Observe native renewal,
|
|
208
|
+
then initialize the next period before running more work.
|
|
209
|
+
5. Authorize activities, reserve, perform idempotent work and record the same
|
|
210
|
+
original event. Start the existing durable delivery workflow for its outbox.
|
|
211
|
+
6. Expose scoped status/history queries and authorized policy commands. Handle
|
|
212
|
+
denied, released, committed and unknown work states explicitly.
|
|
213
|
+
7. Test competing last-capacity requests, replay, failed work, policy revision
|
|
214
|
+
conflicts, renewal and stale UI. Compare accounting and native observations
|
|
215
|
+
without turning lag into permission to grant additional units.
|
|
216
|
+
|
|
217
|
+
Native pricing reference: [Stripe usage-based pricing models](https://docs.stripe.com/billing/subscriptions/usage-based/pricing-models).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.58.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -107,6 +107,7 @@
|
|
|
107
107
|
"docs/usage-observations.md",
|
|
108
108
|
"docs/usage-subscriptions.md",
|
|
109
109
|
"docs/usage-credits.md",
|
|
110
|
+
"docs/usage-limits.md",
|
|
110
111
|
"docs/evidence/native-metering"
|
|
111
112
|
],
|
|
112
113
|
"scripts": {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
2
|
+
import { BetterStripe } from "../index.js";
|
|
3
|
+
import type { RunCtx } from "../helpers.js";
|
|
4
|
+
import { fixture } from "./subscriptionTransport.fixtures.js";
|
|
5
|
+
import { request } from "./subscription.fixtures.js";
|
|
6
|
+
import { ensureManagedSubscription } from "./subscriptionProvider.js";
|
|
7
|
+
afterEach(() => vi.useRealTimers());
|
|
8
|
+
it("configures, reserves, reads and releases through the public component facade", async () => {
|
|
9
|
+
vi.useFakeTimers();
|
|
10
|
+
vi.setSystemTime(700000);
|
|
11
|
+
const f = fixture(),
|
|
12
|
+
client = new BetterStripe(f.component);
|
|
13
|
+
const view = await f.t.action((ctx) =>
|
|
14
|
+
ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
|
|
15
|
+
);
|
|
16
|
+
const original = view.bindings[0];
|
|
17
|
+
const policy = {
|
|
18
|
+
reset: "billing_period",
|
|
19
|
+
rollover: "none",
|
|
20
|
+
entitled: true,
|
|
21
|
+
overage: "reject",
|
|
22
|
+
limit: { mode: "none" },
|
|
23
|
+
} as const;
|
|
24
|
+
expect(
|
|
25
|
+
await f.t.action((ctx) =>
|
|
26
|
+
client.usage.configureAllowance(ctx as RunCtx, {
|
|
27
|
+
...original,
|
|
28
|
+
policy,
|
|
29
|
+
expectedRevision: 0,
|
|
30
|
+
}),
|
|
31
|
+
),
|
|
32
|
+
).toEqual({ revision: 1 });
|
|
33
|
+
const event = {
|
|
34
|
+
scope: original.scope,
|
|
35
|
+
binding: original.binding,
|
|
36
|
+
sourceEventId: "work1",
|
|
37
|
+
quantity: "6",
|
|
38
|
+
occurredAt: 700,
|
|
39
|
+
};
|
|
40
|
+
const reservation = await f.t.action((ctx) =>
|
|
41
|
+
client.usage.reserveAllowance(ctx as RunCtx, {
|
|
42
|
+
event,
|
|
43
|
+
subscription: original.subscription,
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
expect(reservation.state).toBe("reserved");
|
|
47
|
+
expect(
|
|
48
|
+
await f.t.query((ctx) =>
|
|
49
|
+
client.usage.getAllowanceStatus(ctx as RunCtx, original),
|
|
50
|
+
),
|
|
51
|
+
).toMatchObject({
|
|
52
|
+
consumedQuantity: "0",
|
|
53
|
+
reservedQuantity: "6",
|
|
54
|
+
hardLimitRemainingQuantity: "4",
|
|
55
|
+
});
|
|
56
|
+
const denied = await f.t.action((ctx) =>
|
|
57
|
+
client.usage.reserveAllowance(ctx as RunCtx, {
|
|
58
|
+
event: { ...event, sourceEventId: "work2" },
|
|
59
|
+
subscription: original.subscription,
|
|
60
|
+
}),
|
|
61
|
+
);
|
|
62
|
+
expect(denied).toMatchObject({ state: "denied", reason: "hard_limit" });
|
|
63
|
+
if (reservation.state === "denied") throw new Error("Unexpected denial");
|
|
64
|
+
await f.t.action((ctx) =>
|
|
65
|
+
client.usage.releaseAllowance(ctx as RunCtx, {
|
|
66
|
+
scope: original.scope,
|
|
67
|
+
reservationId: reservation.reservationId,
|
|
68
|
+
reason: "work_failed",
|
|
69
|
+
}),
|
|
70
|
+
);
|
|
71
|
+
expect(
|
|
72
|
+
await f.t.query((ctx) =>
|
|
73
|
+
client.usage.reconcileAllowance(ctx as RunCtx, original),
|
|
74
|
+
),
|
|
75
|
+
).toMatchObject({ status: "matched", repaired: false });
|
|
76
|
+
const page = await f.t.query((ctx) =>
|
|
77
|
+
client.usage.readAllowanceHistory(ctx as RunCtx, {
|
|
78
|
+
...original,
|
|
79
|
+
limit: 1,
|
|
80
|
+
cursor: null,
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
expect(page.records).toHaveLength(1);
|
|
84
|
+
expect(page.cursor).not.toBeNull();
|
|
85
|
+
expect(
|
|
86
|
+
await f.t.query((ctx) =>
|
|
87
|
+
client.usage.getAllowanceStatus(ctx as RunCtx, {
|
|
88
|
+
...original,
|
|
89
|
+
scope: { ...original.scope, customerAccount: "acct_other" },
|
|
90
|
+
}),
|
|
91
|
+
),
|
|
92
|
+
).toBeNull();
|
|
93
|
+
});
|