@fantastic.dev/better-stripe 0.92.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 (96) hide show
  1. package/CHANGELOG.md +12 -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 +44 -0
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +251 -0
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -0
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +562 -0
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +281 -0
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +562 -0
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +281 -0
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +3 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +16 -3
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/component/_generated/api.d.ts +6 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -1
  25. package/dist/component/_generated/api.js.map +1 -1
  26. package/dist/component/_generated/component.d.ts +406 -0
  27. package/dist/component/_generated/component.d.ts.map +1 -1
  28. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  29. package/dist/component/balanceFunding/queries.d.ts +1 -1
  30. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  31. package/dist/component/earnings/triggers.d.ts +294 -0
  32. package/dist/component/earnings/triggers.d.ts.map +1 -1
  33. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  34. package/dist/component/renewalOperations/helpers.d.ts +236 -0
  35. package/dist/component/renewalOperations/helpers.d.ts.map +1 -0
  36. package/dist/component/renewalOperations/helpers.js +457 -0
  37. package/dist/component/renewalOperations/helpers.js.map +1 -0
  38. package/dist/component/renewalOperations/mutations.d.ts +252 -0
  39. package/dist/component/renewalOperations/mutations.d.ts.map +1 -0
  40. package/dist/component/renewalOperations/mutations.js +340 -0
  41. package/dist/component/renewalOperations/mutations.js.map +1 -0
  42. package/dist/component/renewalOperations/queries.d.ts +163 -0
  43. package/dist/component/renewalOperations/queries.d.ts.map +1 -0
  44. package/dist/component/renewalOperations/queries.js +167 -0
  45. package/dist/component/renewalOperations/queries.js.map +1 -0
  46. package/dist/component/renewalOperations/schema.d.ts +1988 -0
  47. package/dist/component/renewalOperations/schema.d.ts.map +1 -0
  48. package/dist/component/renewalOperations/schema.js +227 -0
  49. package/dist/component/renewalOperations/schema.js.map +1 -0
  50. package/dist/component/schema.d.ts +281 -0
  51. package/dist/component/schema.js +5 -0
  52. package/dist/component/schema.js.map +1 -1
  53. package/dist/component/usage/allowance.fixtures.d.ts +281 -0
  54. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  55. package/dist/component/usageCredits/accounting.fixtures.d.ts +297 -16
  56. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  57. package/dist/shared/renewalOperationJournal.d.ts +43 -0
  58. package/dist/shared/renewalOperationJournal.d.ts.map +1 -0
  59. package/dist/shared/renewalOperationJournal.js +294 -0
  60. package/dist/shared/renewalOperationJournal.js.map +1 -0
  61. package/docs/renewal-context-reads.md +180 -0
  62. package/package.json +1 -1
  63. package/src/client/billing/renewalAttach/internal/operationJournal.acknowledgement.integration.test.ts +500 -0
  64. package/src/client/billing/renewalAttach/internal/operationJournal.c10.integration.test.ts +560 -0
  65. package/src/client/billing/renewalAttach/internal/operationJournal.controls.integration.test.ts +356 -0
  66. package/src/client/billing/renewalAttach/internal/operationJournal.integration.test.ts +560 -0
  67. package/src/client/billing/renewalAttach/internal/operationJournal.methods.integration.test.ts +534 -0
  68. package/src/client/billing/renewalAttach/internal/operationJournal.ts +561 -0
  69. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +334 -0
  70. package/src/client/billing/renewalAttach/internal/producer/producerGuards.integration.test.ts +323 -0
  71. package/src/client/billing/renewalAttach/internal/producer/producerInitial.integration.test.ts +301 -0
  72. package/src/client/billing/renewalAttach/internal/producer/producerIsolation.integration.test.ts +531 -0
  73. package/src/client/index.ts +24 -3
  74. package/src/component/_generated/api.ts +6 -0
  75. package/src/component/_generated/component.ts +450 -0
  76. package/src/component/renewalOperations/acknowledgement.fixtures.ts +552 -0
  77. package/src/component/renewalOperations/acknowledgement.test.ts +573 -0
  78. package/src/component/renewalOperations/acknowledgementReads.test.ts +442 -0
  79. package/src/component/renewalOperations/acknowledgementV2.test.ts +493 -0
  80. package/src/component/renewalOperations/acknowledgementV2Publication.test.ts +373 -0
  81. package/src/component/renewalOperations/basisBinding.test.ts +567 -0
  82. package/src/component/renewalOperations/basisLifecycle.test.ts +569 -0
  83. package/src/component/renewalOperations/boundHistory.test.ts +474 -0
  84. package/src/component/renewalOperations/helpers.ts +592 -0
  85. package/src/component/renewalOperations/historyReads.test.ts +595 -0
  86. package/src/component/renewalOperations/initialBasis.test.ts +578 -0
  87. package/src/component/renewalOperations/journal.test.ts +567 -0
  88. package/src/component/renewalOperations/mutations.ts +456 -0
  89. package/src/component/renewalOperations/payload.test.ts +589 -0
  90. package/src/component/renewalOperations/payloadEncoding.test.ts +592 -0
  91. package/src/component/renewalOperations/queries.ts +204 -0
  92. package/src/component/renewalOperations/schema.ts +268 -0
  93. package/src/component/renewalOperations/timingPolicy.fixtures.ts +193 -0
  94. package/src/component/renewalOperations/timingPolicy.test.ts +523 -0
  95. package/src/component/schema.ts +11 -0
  96. package/src/shared/renewalOperationJournal.ts +333 -0
@@ -0,0 +1,334 @@
1
+ import type { GenericActionCtx, GenericDataModel } from "convex/server";
2
+ import type { Component } from "../../../../helpers.js";
3
+ import { RenewalContextClient } from "../../../../renewalContextClient.js";
4
+
5
+ export type ClassActionInput = Readonly<{
6
+ actualActionCtx: GenericActionCtx<GenericDataModel>;
7
+ operationId: string;
8
+ }>;
9
+ type Bootstrap = Readonly<{
10
+ prototype: object;
11
+ select: () => unknown;
12
+ enter: (input: ClassActionInput) => unknown;
13
+ }>;
14
+ type RootCell =
15
+ | Readonly<{ phase: "awaiting"; component: Component }>
16
+ | Readonly<{ phase: "ready"; component: Component; bootstrap: Bootstrap }>
17
+ | Readonly<{ phase: "failed" }>;
18
+ const roots = new WeakMap<object, RootCell>();
19
+ const pending = new WeakMap<object, Bootstrap>();
20
+ const finishing = new WeakSet<object>();
21
+ const bootstrapSymbol = Symbol("betterstripe-class-root-bootstrap");
22
+ export const CLASS_ROOT_CONSTRUCTION_PERMIT = Symbol(
23
+ "betterstripe-root-permit",
24
+ );
25
+ function rootUnbound(): never {
26
+ throw Error("CLASS_ACTION_ROOT_UNBOUND");
27
+ }
28
+
29
+ /** Internal neutral base; construction alone grants no operational authority. */
30
+ export abstract class ClassOwnedActionRoot extends RenewalContextClient {
31
+ protected constructor(
32
+ component: Component,
33
+ permit: typeof CLASS_ROOT_CONSTRUCTION_PERMIT,
34
+ ) {
35
+ if (permit !== CLASS_ROOT_CONSTRUCTION_PERMIT) rootUnbound();
36
+ super(component);
37
+ roots.set(this, Object.freeze({ phase: "awaiting", component }));
38
+ }
39
+
40
+ protected finishMaintainedRootConstruction(): void {
41
+ const cell = roots.get(this);
42
+ const bootstrap = pending.get(this);
43
+ const descriptor = Object.getOwnPropertyDescriptor(this, bootstrapSymbol);
44
+ if (
45
+ !cell ||
46
+ cell.phase !== "awaiting" ||
47
+ !finishing.has(this) ||
48
+ !bootstrap ||
49
+ !descriptor ||
50
+ !("value" in descriptor) ||
51
+ descriptor.value !== bootstrap ||
52
+ descriptor.enumerable ||
53
+ descriptor.writable ||
54
+ !descriptor.configurable
55
+ )
56
+ rootUnbound();
57
+ roots.set(
58
+ this,
59
+ Object.freeze({ phase: "ready", component: cell.component, bootstrap }),
60
+ );
61
+ }
62
+ }
63
+ const finalizerCandidate: unknown = Object.getOwnPropertyDescriptor(
64
+ ClassOwnedActionRoot.prototype,
65
+ "finishMaintainedRootConstruction",
66
+ )?.value;
67
+ if (typeof finalizerCandidate !== "function") rootUnbound();
68
+ const actualFinalizer = finalizerCandidate;
69
+
70
+ /**
71
+ * Called by the maintained constructor under trusted package-internal imports.
72
+ * Hostile code importing the private base and permit is outside this gate.
73
+ */
74
+ export function finishClassRoot(actualRoot: object, raw: Bootstrap): void {
75
+ const cell = roots.get(actualRoot);
76
+ if (!cell || cell.phase !== "awaiting") rootUnbound();
77
+ try {
78
+ const keys = Reflect.ownKeys(raw);
79
+ const prototype = Object.getOwnPropertyDescriptor(raw, "prototype");
80
+ const select = Object.getOwnPropertyDescriptor(raw, "select");
81
+ const enter = Object.getOwnPropertyDescriptor(raw, "enter");
82
+ if (
83
+ keys.length !== 3 ||
84
+ !keys.every(
85
+ (key) =>
86
+ typeof key === "string" &&
87
+ ["prototype", "select", "enter"].includes(key),
88
+ ) ||
89
+ !prototype ||
90
+ !("value" in prototype) ||
91
+ !prototype.enumerable ||
92
+ prototype.value === null ||
93
+ typeof prototype.value !== "object" ||
94
+ !select ||
95
+ !("value" in select) ||
96
+ !select.enumerable ||
97
+ typeof select.value !== "function" ||
98
+ !enter ||
99
+ !("value" in enter) ||
100
+ !enter.enumerable ||
101
+ typeof enter.value !== "function" ||
102
+ roots.get(actualRoot) !== cell
103
+ )
104
+ rootUnbound();
105
+ // Values are captured before the temporary descriptor exists; none is called.
106
+ const bootstrap: Bootstrap = Object.freeze({
107
+ prototype: prototype.value,
108
+ select: select.value,
109
+ enter: enter.value,
110
+ });
111
+ pending.set(actualRoot, bootstrap);
112
+ Object.defineProperty(actualRoot, bootstrapSymbol, {
113
+ value: bootstrap,
114
+ enumerable: false,
115
+ writable: false,
116
+ configurable: true,
117
+ });
118
+ finishing.add(actualRoot);
119
+ Reflect.apply(actualFinalizer, actualRoot, []);
120
+ } catch {
121
+ roots.set(actualRoot, Object.freeze({ phase: "failed" }));
122
+ rootUnbound();
123
+ } finally {
124
+ finishing.delete(actualRoot);
125
+ pending.delete(actualRoot);
126
+ if (!Reflect.deleteProperty(actualRoot, bootstrapSymbol)) {
127
+ roots.set(actualRoot, Object.freeze({ phase: "failed" }));
128
+ rootUnbound();
129
+ }
130
+ }
131
+ }
132
+
133
+ /** Operational EMPTY profiles refuse before entry, selector or Action reflection. */
134
+ export async function captureMaintainedActionSelection(
135
+ actualRoot: object,
136
+ _input: ClassActionInput,
137
+ ): Promise<never> {
138
+ const cell = roots.get(actualRoot);
139
+ if (
140
+ !cell ||
141
+ cell.phase !== "ready" ||
142
+ Object.getPrototypeOf(actualRoot) !== cell.bootstrap.prototype
143
+ )
144
+ rootUnbound();
145
+ throw Error("CLASS_ACTION_PROFILE_UNBOUND");
146
+ }
147
+
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. */
277
+ export async function beginClassAction(
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;
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
+ });