@fantastic.dev/better-stripe 0.93.0 → 0.94.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 (27) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts +41 -0
  4. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/operationJournal.js +378 -0
  6. package/dist/client/billing/renewalAttach/internal/operationJournal.js.map +1 -0
  7. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +19 -5
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +142 -4
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  13. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  14. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  15. package/dist/component/balanceFunding/queries.d.ts +1 -1
  16. package/docs/renewal-context-reads.md +33 -5
  17. package/package.json +1 -1
  18. package/src/client/billing/renewalAttach/internal/operationJournal.acknowledgement.integration.test.ts +500 -0
  19. package/src/client/billing/renewalAttach/internal/operationJournal.c10.integration.test.ts +560 -0
  20. package/src/client/billing/renewalAttach/internal/operationJournal.controls.integration.test.ts +356 -0
  21. package/src/client/billing/renewalAttach/internal/operationJournal.integration.test.ts +181 -1
  22. package/src/client/billing/renewalAttach/internal/operationJournal.methods.integration.test.ts +534 -0
  23. package/src/client/billing/renewalAttach/internal/operationJournal.ts +561 -0
  24. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +187 -8
  25. package/src/client/billing/renewalAttach/internal/producer/producerGuards.integration.test.ts +323 -0
  26. package/src/client/billing/renewalAttach/internal/producer/producerInitial.integration.test.ts +301 -0
  27. package/src/client/billing/renewalAttach/internal/producer/producerIsolation.integration.test.ts +531 -0
@@ -1,11 +1,10 @@
1
1
  import type { GenericActionCtx, GenericDataModel } from "convex/server";
2
- import type { Id } from "../../../../../component/_generated/dataModel.js";
3
2
  import type { Component } from "../../../../helpers.js";
4
3
  import { RenewalContextClient } from "../../../../renewalContextClient.js";
5
4
 
6
5
  export type ClassActionInput = Readonly<{
7
6
  actualActionCtx: GenericActionCtx<GenericDataModel>;
8
- operationId: Id<"renewalOperations">;
7
+ operationId: string;
9
8
  }>;
10
9
  type Bootstrap = Readonly<{
11
10
  prototype: object;
@@ -131,7 +130,7 @@ export function finishClassRoot(actualRoot: object, raw: Bootstrap): void {
131
130
  }
132
131
  }
133
132
 
134
- /** EMPTY profiles refuse before entry, client selection or Action reflection. */
133
+ /** Operational EMPTY profiles refuse before entry, selector or Action reflection. */
135
134
  export async function captureMaintainedActionSelection(
136
135
  actualRoot: object,
137
136
  _input: ClassActionInput,
@@ -146,10 +145,190 @@ export async function captureMaintainedActionSelection(
146
145
  throw Error("CLASS_ACTION_PROFILE_UNBOUND");
147
146
  }
148
147
 
149
- /** Positive per-Action admission is not implemented by the inert bootstrap. */
148
+ type ReadyRoot = Extract<RootCell, { phase: "ready" }>;
149
+ type ActionContext = ClassActionInput["actualActionCtx"];
150
+ type JournalRPC = Readonly<{
151
+ receiver: ActionContext;
152
+ component: Component;
153
+ operationId: string;
154
+ metaReceiver: ActionContext["meta"];
155
+ getMetadata: ActionContext["meta"]["getFunctionMetadata"];
156
+ runQuery: ActionContext["runQuery"];
157
+ runMutation: ActionContext["runMutation"];
158
+ tag: object;
159
+ }>;
160
+ type PendingJournal = {
161
+ root: object;
162
+ cell: ReadyRoot;
163
+ input: ClassActionInput;
164
+ entered: boolean;
165
+ binding: object | null;
166
+ };
167
+ type JournalState = Readonly<{
168
+ root: object;
169
+ cell: ReadyRoot;
170
+ rpc: JournalRPC;
171
+ }>;
172
+ const pendingJournalEntries = new WeakMap<object, PendingJournal>();
173
+ const journalBindings = new WeakMap<object, JournalState>();
174
+ const closedJournalBindings = new WeakSet<object>();
175
+ function journalUnbound(): never {
176
+ throw Error("CLASS_ACTION_JOURNAL_UNBOUND");
177
+ }
178
+ function journalPointersMatch(state: JournalState): boolean {
179
+ const { root, cell, rpc } = state;
180
+ return (
181
+ roots.get(root) === cell &&
182
+ Object.getPrototypeOf(root) === cell.bootstrap.prototype &&
183
+ rpc.receiver.meta === rpc.metaReceiver &&
184
+ rpc.metaReceiver.getFunctionMetadata === rpc.getMetadata &&
185
+ rpc.receiver.runQuery === rpc.runQuery &&
186
+ rpc.receiver.runMutation === rpc.runMutation
187
+ );
188
+ }
189
+
190
+ /** Checked private bookkeeping identity only; never an operational selection. */
191
+ export function readCheckedJournalActionRPC(binding: unknown): JournalRPC {
192
+ if (typeof binding !== "object" || binding === null) journalUnbound();
193
+ const state = journalBindings.get(binding);
194
+ if (!state || closedJournalBindings.has(binding)) journalUnbound();
195
+ try {
196
+ if (!journalPointersMatch(state)) journalUnbound();
197
+ } catch {
198
+ closedJournalBindings.add(binding);
199
+ journalUnbound();
200
+ }
201
+ return state.rpc;
202
+ }
203
+
204
+ /** Fixed class entry for journal DATA, independent of operational qualification. */
205
+ export async function captureMaintainedJournalBinding(
206
+ actualRoot: object,
207
+ input: ClassActionInput,
208
+ ): Promise<object> {
209
+ const cell = roots.get(actualRoot);
210
+ if (
211
+ !cell ||
212
+ cell.phase !== "ready" ||
213
+ Object.getPrototypeOf(actualRoot) !== cell.bootstrap.prototype
214
+ )
215
+ rootUnbound();
216
+ const keys = Reflect.ownKeys(input);
217
+ const context = Object.getOwnPropertyDescriptor(input, "actualActionCtx");
218
+ const operation = Object.getOwnPropertyDescriptor(input, "operationId");
219
+ if (
220
+ keys.length !== 2 ||
221
+ !keys.every((key) => key === "actualActionCtx" || key === "operationId") ||
222
+ !context ||
223
+ !("value" in context) ||
224
+ !context.enumerable ||
225
+ !operation ||
226
+ !("value" in operation) ||
227
+ !operation.enumerable ||
228
+ typeof operation.value !== "string" ||
229
+ operation.value.length === 0
230
+ )
231
+ journalUnbound();
232
+ const entryInput: ClassActionInput = Object.freeze({
233
+ actualActionCtx: context.value,
234
+ operationId: operation.value,
235
+ });
236
+ const entry: PendingJournal = {
237
+ root: actualRoot,
238
+ cell,
239
+ input: entryInput,
240
+ entered: false,
241
+ binding: null,
242
+ };
243
+ pendingJournalEntries.set(entryInput, entry);
244
+ try {
245
+ const result: unknown = await Reflect.apply(
246
+ cell.bootstrap.enter,
247
+ actualRoot,
248
+ [entryInput],
249
+ );
250
+ if (
251
+ typeof result !== "object" ||
252
+ result === null ||
253
+ result !== entry.binding ||
254
+ pendingJournalEntries.get(entryInput) !== entry ||
255
+ !entry.entered
256
+ )
257
+ journalUnbound();
258
+ const state = journalBindings.get(result);
259
+ if (
260
+ !state ||
261
+ state.root !== actualRoot ||
262
+ state.cell !== cell ||
263
+ state.rpc.operationId !== entryInput.operationId
264
+ )
265
+ journalUnbound();
266
+ readCheckedJournalActionRPC(result);
267
+ return result;
268
+ } catch (error) {
269
+ if (entry.binding) closedJournalBindings.add(entry.binding);
270
+ throw error;
271
+ } finally {
272
+ pendingJournalEntries.delete(entryInput);
273
+ }
274
+ }
275
+
276
+ /** Only the actual constructor-captured private entry can complete pending DATA. */
150
277
  export async function beginClassAction(
151
- _actualRoot: object,
152
- _input: ClassActionInput,
153
- ): Promise<never> {
154
- return rootUnbound();
278
+ actualRoot: object,
279
+ input: ClassActionInput,
280
+ ): Promise<object> {
281
+ const entry = pendingJournalEntries.get(input);
282
+ if (
283
+ !entry ||
284
+ entry.root !== actualRoot ||
285
+ entry.input !== input ||
286
+ entry.entered ||
287
+ roots.get(actualRoot) !== entry.cell
288
+ )
289
+ return rootUnbound();
290
+ entry.entered = true;
291
+ const receiver = input.actualActionCtx;
292
+ if (typeof receiver !== "object" || receiver === null) journalUnbound();
293
+ const metaReceiver = receiver.meta;
294
+ const getMetadata = metaReceiver?.getFunctionMetadata;
295
+ const runQuery = receiver.runQuery;
296
+ const runMutation = receiver.runMutation;
297
+ if (
298
+ typeof getMetadata !== "function" ||
299
+ typeof runQuery !== "function" ||
300
+ typeof runMutation !== "function"
301
+ )
302
+ journalUnbound();
303
+ const rpc: JournalRPC = Object.freeze({
304
+ receiver,
305
+ component: entry.cell.component,
306
+ operationId: input.operationId,
307
+ metaReceiver,
308
+ getMetadata,
309
+ runQuery,
310
+ runMutation,
311
+ tag: Object.freeze({}),
312
+ });
313
+ const metadata = await getMetadata.call(metaReceiver);
314
+ const state: JournalState = Object.freeze({
315
+ root: actualRoot,
316
+ cell: entry.cell,
317
+ rpc,
318
+ });
319
+ if (
320
+ metadata.type !== "action" ||
321
+ typeof metadata.name !== "string" ||
322
+ metadata.name.length === 0 ||
323
+ typeof metadata.componentPath !== "string" ||
324
+ (metadata.visibility !== "public" && metadata.visibility !== "internal") ||
325
+ pendingJournalEntries.get(input) !== entry ||
326
+ entry.binding !== null ||
327
+ !journalPointersMatch(state)
328
+ )
329
+ journalUnbound();
330
+ const binding = Object.freeze({});
331
+ journalBindings.set(binding, state);
332
+ entry.binding = binding;
333
+ return binding;
155
334
  }
@@ -0,0 +1,323 @@
1
+ import assert from "node:assert/strict";
2
+ import { BetterStripe } from "../../../../index.js";
3
+ import { components } from "../../../../../../example/convex/_generated/api.js";
4
+ import { captureMaintainedActionSelection } from "./classOwnedActionRoot.js";
5
+ import {
6
+ createClassActionOperationJournal,
7
+ consumeClassReservation,
8
+ } from "../operationJournal.js";
9
+ import { convexTest } from "convex-test";
10
+ import {
11
+ actionGeneric,
12
+ componentsGeneric,
13
+ defineSchema,
14
+ makeFunctionReference,
15
+ type FunctionReturnType,
16
+ } from "convex/server";
17
+ import { getConvexSize, getDocumentSize, v } from "convex/values";
18
+ import { afterEach, expect, it, vi } from "vitest";
19
+ import { modules, schema } from "../../../../../test.js";
20
+ import { query } from "../../../../../component/_generated/server.js";
21
+ import type { Doc } from "../../../../../component/_generated/dataModel.js";
22
+ import {
23
+ canonical,
24
+ codecFixture,
25
+ VALUE_LIMIT,
26
+ } from "../../../../../component/renewalOperations/timingPolicy.fixtures.js";
27
+ const refs = components.betterStripe.renewalOperations;
28
+ const nested = componentsGeneric();
29
+ const route = makeFunctionReference<"action", { operationId: string }, null>(
30
+ "winningConcurrent:run",
31
+ );
32
+ type Reserved = FunctionReturnType<typeof refs.mutations.reserveAttempt>;
33
+ type Physical = {
34
+ operations: Doc<"renewalOperations">[];
35
+ attempts: Doc<"renewalOperationAttempts">[];
36
+ events: Doc<"renewalOperationEvents">[];
37
+ payloads: Doc<"renewalOperationPayloads">[];
38
+ };
39
+ const inspection = {
40
+ physical: query({
41
+ args: {},
42
+ handler: async (ctx): Promise<Physical> => ({
43
+ operations: await ctx.db.query("renewalOperations").take(4),
44
+ attempts: await ctx.db.query("renewalOperationAttempts").take(4),
45
+ events: await ctx.db.query("renewalOperationEvents").take(4),
46
+ payloads: await ctx.db.query("renewalOperationPayloads").take(5),
47
+ }),
48
+ }),
49
+ };
50
+ afterEach(() => vi.unstubAllGlobals());
51
+
52
+ it("WINNING-CONCURRENT isolates two actual Action call handles on one SDK", async () => {
53
+ const h = await codecFixture();
54
+ const logicalIds = [
55
+ h.record.logicalOperationId,
56
+ h.record.logicalOperationId + "-winning-concurrent",
57
+ ];
58
+ const records = [
59
+ h.recordJSON,
60
+ canonical({ ...h.record, logicalOperationId: logicalIds[1] }),
61
+ ];
62
+ const sdk = new BetterStripe(components.betterStripe, {
63
+ STRIPE_SECRET_KEY: "sk_test_invalid_winning_concurrent",
64
+ });
65
+ const descriptor = Object.getOwnPropertyDescriptor(sdk, "_apiKey");
66
+ assert(descriptor && "value" in descriptor && descriptor.configurable);
67
+ let selectorReads = 0;
68
+ Object.defineProperty(sdk, "_apiKey", {
69
+ configurable: true,
70
+ enumerable: descriptor.enumerable,
71
+ get() {
72
+ selectorReads++;
73
+ throw Error("CONCURRENT_SELECTOR_TOUCHED");
74
+ },
75
+ });
76
+ try {
77
+ const expected = new Map<string, string>();
78
+ const replies: Reserved[] = [];
79
+ const tags = new Set<object>();
80
+ const calls = new Set<object>();
81
+ let captured = 0;
82
+ let release = () => {};
83
+ const bothCaptured = new Promise<void>((resolve) => {
84
+ release = resolve;
85
+ });
86
+ let timer: ReturnType<typeof setTimeout> | undefined;
87
+ const host = {
88
+ run: actionGeneric({
89
+ args: { operationId: v.string() },
90
+ handler: async (ctx, args): Promise<null> => {
91
+ expect(await ctx.meta.getFunctionMetadata()).toEqual({
92
+ name: "winningConcurrent:run",
93
+ componentPath: "",
94
+ type: "action",
95
+ visibility: "public",
96
+ });
97
+ const recordJSON = expected.get(args.operationId);
98
+ assert(recordJSON);
99
+ expect(
100
+ await ctx.runQuery(refs.queries.loadAuthorizedOperation, args),
101
+ ).toEqual({
102
+ recordVersion: 2,
103
+ ...args,
104
+ recordJSON,
105
+ revision: 0,
106
+ activeAttempt: null,
107
+ initialBasis: null,
108
+ });
109
+ await expect(
110
+ captureMaintainedActionSelection(sdk, {
111
+ actualActionCtx: ctx,
112
+ operationId: args.operationId,
113
+ }),
114
+ ).rejects.toThrow(/^CLASS_ACTION_PROFILE_UNBOUND$/);
115
+ const journal = await createClassActionOperationJournal(sdk, {
116
+ actualActionCtx: ctx,
117
+ operationId: args.operationId,
118
+ });
119
+ expect((await journal.loadAuthorizedOperation())?.recordJSON).toBe(
120
+ recordJSON,
121
+ );
122
+ captured++;
123
+ if (captured === 2) release();
124
+ await Promise.race([bothCaptured, timeout]);
125
+ const fresh = await journal.reserveFreshAttempt({
126
+ expectedRevision: 0,
127
+ stage: "attach",
128
+ expectedRequestBinding: h.record.requestBinding,
129
+ recordJSON,
130
+ });
131
+ assert(fresh.result.disposition === "acquired");
132
+ replies.push(fresh.result);
133
+ const reservation = fresh.result.reservation;
134
+ expect(reservation.operationId).toBe(args.operationId);
135
+ expect(reservation.recordJSON).toBe(recordJSON);
136
+ expect(
137
+ await ctx.runQuery(refs.queries.readAttempt, {
138
+ ...args,
139
+ attemptId: reservation.attemptId,
140
+ }),
141
+ ).toEqual({ reservation, events: [] });
142
+ expect(getConvexSize(fresh.result)).toBeLessThanOrEqual(VALUE_LIMIT);
143
+ expect(fresh.call).not.toBeNull();
144
+ assert(fresh.call !== null);
145
+ const call = fresh.call;
146
+ calls.add(call);
147
+ const consumed = consumeClassReservation(call, journal);
148
+ expect(consumed.reservation).toBe(reservation);
149
+ tags.add(consumed.tag);
150
+ expect(() => consumeClassReservation(call, journal)).toThrow(
151
+ /^CLASS_JOURNAL_CALL_UNBOUND$/,
152
+ );
153
+ expect(selectorReads).toBe(0);
154
+ return null;
155
+ },
156
+ }),
157
+ };
158
+ const t = convexTest(defineSchema({}), {
159
+ "./_generated/api.ts": async () => ({}),
160
+ "./winningConcurrent.ts": async () => host,
161
+ });
162
+ expect(
163
+ Object.prototype.hasOwnProperty.call(
164
+ modules,
165
+ "./component/winningConcurrentInspection.ts",
166
+ ),
167
+ ).toBe(false);
168
+ t.registerComponent("betterStripe", schema, {
169
+ ...modules,
170
+ "./component/winningConcurrentInspection.ts": async () => inspection,
171
+ });
172
+ const physical = async (): Promise<Physical> =>
173
+ t.query(nested.betterStripe.winningConcurrentInspection.physical, {});
174
+ expect(await physical()).toEqual({
175
+ operations: [],
176
+ attempts: [],
177
+ events: [],
178
+ payloads: [],
179
+ });
180
+ const ids: string[] = [];
181
+ for (let index = 0; index < records.length; index++) {
182
+ const created = await t.mutation(
183
+ refs.mutations.createAuthorizedOperation,
184
+ {
185
+ authorizationScope: h.record.authorization.scope,
186
+ authorizationRevision: h.record.authorization.revision,
187
+ logicalOperationId: logicalIds[index],
188
+ recordJSON: records[index],
189
+ },
190
+ );
191
+ assert(created.status === "created");
192
+ ids.push(created.operationId);
193
+ expected.set(created.operationId, records[index]);
194
+ }
195
+ expect(new Set(ids).size).toBe(2);
196
+ const before = await physical();
197
+ expect({
198
+ operations: before.operations.length,
199
+ attempts: before.attempts.length,
200
+ events: before.events.length,
201
+ payloads: before.payloads.length,
202
+ }).toEqual({ operations: 2, attempts: 0, events: 0, payloads: 2 });
203
+ for (const operation of before.operations) {
204
+ expect(operation).toMatchObject({
205
+ recordVersion: 2,
206
+ state: "PREPARED",
207
+ revision: 0,
208
+ });
209
+ const source = before.payloads.find(
210
+ (row) => row._id === operation.payloadId,
211
+ );
212
+ assert(source);
213
+ expect(source.json).toBe(expected.get(operation._id));
214
+ expect(source.owner).toEqual({
215
+ kind: "operation",
216
+ operationId: operation._id,
217
+ });
218
+ }
219
+ let stable = before;
220
+ let failed = false;
221
+ const timeout = new Promise<never>((_, reject) => {
222
+ timer = setTimeout(
223
+ () => reject(Error("WINNING_CONCURRENT_CAPTURE_STOP")),
224
+ 1000,
225
+ );
226
+ });
227
+ try {
228
+ const settled = await Promise.allSettled(
229
+ ids.map((operationId) => t.action(route, { operationId })),
230
+ );
231
+ const originalFailure = settled.find(
232
+ (result) => result.status === "rejected",
233
+ );
234
+ try {
235
+ const after = await physical();
236
+ expect(after.operations).toHaveLength(2);
237
+ expect(after.attempts).toHaveLength(replies.length);
238
+ expect(after.events).toEqual([]);
239
+ expect(after.payloads).toEqual(before.payloads);
240
+ for (const original of before.operations) {
241
+ const reply = replies.find(
242
+ (result) =>
243
+ result.disposition === "acquired" &&
244
+ result.reservation.operationId === original._id,
245
+ );
246
+ if (!reply) {
247
+ expect(
248
+ after.operations.find((row) => row._id === original._id),
249
+ ).toEqual(original);
250
+ continue;
251
+ }
252
+ assert(reply.disposition === "acquired");
253
+ const reservation = reply.reservation;
254
+ expect(
255
+ after.operations.find((row) => row._id === original._id),
256
+ ).toEqual({
257
+ ...original,
258
+ state: "RESERVED",
259
+ revision: 1,
260
+ activeAttemptId: reservation.attemptId,
261
+ });
262
+ const actualAttempt = after.attempts.find(
263
+ (row) => row._id === reservation.attemptId,
264
+ );
265
+ assert(actualAttempt);
266
+ const { attemptId, recordJSON: _recordJSON, ...fields } = reservation;
267
+ expect(actualAttempt).toEqual({
268
+ ...fields,
269
+ _id: attemptId,
270
+ _creationTime: actualAttempt._creationTime,
271
+ lastSequence: 0,
272
+ });
273
+ }
274
+ for (const rows of Object.values(after))
275
+ for (const row of rows)
276
+ expect(getDocumentSize(row)).toBeLessThanOrEqual(VALUE_LIMIT);
277
+ stable = after;
278
+ } catch (error) {
279
+ if (originalFailure?.status === "rejected") {
280
+ console.info("WINNING_CONCURRENT_INSPECTION_FAILED");
281
+ throw originalFailure.reason;
282
+ }
283
+ throw error;
284
+ }
285
+ if (originalFailure?.status === "rejected") throw originalFailure.reason;
286
+ expect(settled.map((result) => result.status)).toEqual([
287
+ "fulfilled",
288
+ "fulfilled",
289
+ ]);
290
+ expect(captured).toBe(2);
291
+ expect(replies).toHaveLength(2);
292
+ expect(calls.size).toBe(2);
293
+ expect(tags.size).toBe(2);
294
+ } catch (error) {
295
+ failed = true;
296
+ throw error;
297
+ } finally {
298
+ if (timer !== undefined) clearTimeout(timer);
299
+ try {
300
+ expect(await physical()).toEqual(stable);
301
+ expect(selectorReads).toBe(0);
302
+ expect(h.fetchCalls()).toBe(0);
303
+ console.info(
304
+ "WINNING_CONCURRENT_SETTLEMENT",
305
+ JSON.stringify({
306
+ captured,
307
+ replies: replies.length,
308
+ calls: calls.size,
309
+ tags: tags.size,
310
+ physicalEqual: true,
311
+ selectorReads,
312
+ fetchCalls: 0,
313
+ }),
314
+ );
315
+ } catch (error) {
316
+ if (!failed) throw error;
317
+ console.info("WINNING_CONCURRENT_FINAL_INSPECTION_FAILED");
318
+ }
319
+ }
320
+ } finally {
321
+ Object.defineProperty(sdk, "_apiKey", descriptor);
322
+ }
323
+ });