@fantastic.dev/better-stripe 0.38.0 → 0.39.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 (127) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +21 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/costRecovery.d.ts +18 -0
  13. package/dist/client/costRecovery.d.ts.map +1 -1
  14. package/dist/client/costRecovery.js +4 -0
  15. package/dist/client/costRecovery.js.map +1 -1
  16. package/dist/client/index.d.ts +1 -0
  17. package/dist/client/index.d.ts.map +1 -1
  18. package/dist/client/index.js +1 -0
  19. package/dist/client/index.js.map +1 -1
  20. package/dist/client/processingCostDeficit/index.d.ts +27 -0
  21. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  22. package/dist/client/processingCostDeficit/index.js +54 -0
  23. package/dist/client/processingCostDeficit/index.js.map +1 -0
  24. package/dist/component/_generated/api.d.ts +284 -0
  25. package/dist/component/_generated/api.d.ts.map +1 -0
  26. package/dist/component/_generated/api.js +31 -0
  27. package/dist/component/_generated/api.js.map +1 -0
  28. package/dist/component/_generated/component.d.ts +527 -0
  29. package/dist/component/_generated/component.d.ts.map +1 -1
  30. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  31. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  32. package/dist/component/balanceFunding/helpers.js +68 -0
  33. package/dist/component/balanceFunding/helpers.js.map +1 -0
  34. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  35. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  36. package/dist/component/balanceFunding/importHandler.js +130 -0
  37. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  38. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  39. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  40. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  41. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  42. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  43. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  44. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  45. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  46. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  47. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  48. package/dist/component/balanceFunding/mutations.js +106 -0
  49. package/dist/component/balanceFunding/mutations.js.map +1 -0
  50. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  51. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  52. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  53. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  54. package/dist/component/balanceFunding/queries.d.ts +151 -0
  55. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  56. package/dist/component/balanceFunding/queries.js +180 -0
  57. package/dist/component/balanceFunding/queries.js.map +1 -0
  58. package/dist/component/balanceFunding/schema.d.ts +748 -0
  59. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/schema.js +124 -0
  61. package/dist/component/balanceFunding/schema.js.map +1 -0
  62. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  63. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  65. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  66. package/dist/component/convex.config.d.ts.map +1 -1
  67. package/dist/component/convex.config.js +2 -0
  68. package/dist/component/convex.config.js.map +1 -1
  69. package/dist/component/costRecovery/completion.d.ts +1 -0
  70. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  71. package/dist/component/costRecovery/helpers.d.ts +1 -0
  72. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  73. package/dist/component/costRecovery/mutations.d.ts +5 -0
  74. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  75. package/dist/component/costRecovery/preparation.d.ts +50 -0
  76. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  77. package/dist/component/costRecovery/preparation.js +108 -0
  78. package/dist/component/costRecovery/preparation.js.map +1 -0
  79. package/dist/component/costRecovery/queries.d.ts +1 -0
  80. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  81. package/dist/component/costRecovery/reservations.d.ts +2 -0
  82. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  83. package/dist/component/costRecovery/schema.d.ts +7 -2
  84. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  85. package/dist/component/costRecovery/schema.js +1 -0
  86. package/dist/component/costRecovery/schema.js.map +1 -1
  87. package/dist/component/durableExecution/runtime.d.ts +3 -0
  88. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  89. package/dist/component/durableExecution/runtime.js +12 -0
  90. package/dist/component/durableExecution/runtime.js.map +1 -0
  91. package/dist/component/earnings/triggers.d.ts +242 -2
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/schema.d.ts +253 -1
  94. package/dist/component/schema.js +4 -0
  95. package/dist/component/schema.js.map +1 -1
  96. package/package.json +4 -2
  97. package/src/client/costRecovery.test.ts +34 -0
  98. package/src/client/costRecovery.ts +21 -0
  99. package/src/client/index.ts +1 -0
  100. package/src/client/processingCostDeficit/README.md +35 -0
  101. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  102. package/src/client/processingCostDeficit/index.ts +91 -0
  103. package/src/component/_generated/api.ts +23 -1
  104. package/src/component/_generated/component.ts +693 -0
  105. package/src/component/balanceFunding/failure.test.ts +116 -0
  106. package/src/component/balanceFunding/helpers.ts +102 -0
  107. package/src/component/balanceFunding/import.test.ts +221 -0
  108. package/src/component/balanceFunding/importHandler.ts +146 -0
  109. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  110. package/src/component/balanceFunding/lookup.test.ts +113 -0
  111. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  112. package/src/component/balanceFunding/mutations.ts +136 -0
  113. package/src/component/balanceFunding/preparation.test.ts +146 -0
  114. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  115. package/src/component/balanceFunding/queries.ts +221 -0
  116. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  117. package/src/component/balanceFunding/schema.ts +169 -0
  118. package/src/component/balanceFunding/state.test.ts +352 -0
  119. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  120. package/src/component/balanceFunding/validation.test.ts +100 -0
  121. package/src/component/convex.config.ts +2 -0
  122. package/src/component/costRecovery/preparation.test.ts +355 -0
  123. package/src/component/costRecovery/preparation.ts +124 -0
  124. package/src/component/costRecovery/schema.ts +1 -0
  125. package/src/component/durableExecution/composition.test.ts +568 -0
  126. package/src/component/durableExecution/runtime.ts +12 -0
  127. package/src/component/schema.ts +8 -0
@@ -0,0 +1,568 @@
1
+ import {
2
+ type WorkflowId,
3
+ vResultValidator,
4
+ vWorkflowId,
5
+ } from "@convex-dev/workflow";
6
+ import {
7
+ Workpool,
8
+ type WorkId,
9
+ type WorkpoolComponent,
10
+ } from "@convex-dev/workpool";
11
+ import workpoolTest from "@convex-dev/workpool/test";
12
+ import workflowTest from "@convex-dev/workflow/test";
13
+ import { convexTest } from "convex-test";
14
+ import {
15
+ anyApi,
16
+ componentsGeneric,
17
+ createFunctionHandle,
18
+ defineSchema,
19
+ defineTable,
20
+ internalActionGeneric,
21
+ internalMutationGeneric,
22
+ internalQueryGeneric,
23
+ type FunctionHandle,
24
+ type FunctionReference,
25
+ } from "convex/server";
26
+ import { v } from "convex/values";
27
+ import Stripe from "stripe";
28
+ import { executionWorkflow } from "./runtime.js";
29
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
30
+
31
+ const nested = componentsGeneric();
32
+ const manager = executionWorkflow;
33
+ const independent = new Workpool(
34
+ nested.independent as unknown as WorkpoolComponent,
35
+ {
36
+ maxParallelism: 1,
37
+ retryActionsByDefault: false,
38
+ },
39
+ );
40
+ const request = {
41
+ operationKey: v.string(),
42
+ stripeAccountId: v.string(),
43
+ apiVersion: v.string(),
44
+ };
45
+ const receipt = v.object({ stripeId: v.string(), apiVersion: v.string() });
46
+ type Request = {
47
+ operationKey: string;
48
+ stripeAccountId: string;
49
+ apiVersion: string;
50
+ };
51
+ type Receipt = { stripeId: string; apiVersion: string };
52
+ const workflowRef = anyApi.fixture.workflow as FunctionReference<
53
+ "mutation",
54
+ "internal"
55
+ >;
56
+ let calls: Request[];
57
+ let failUntil: number;
58
+ let providerUnknown: boolean;
59
+ let definitionChanged: boolean;
60
+ let active: number;
61
+ let peak: number;
62
+ let commitFailures: number;
63
+ let commitCalls: number;
64
+ let providerDelay: number;
65
+ let providerGate: Promise<void> | null;
66
+ let transport: {
67
+ authenticated: boolean;
68
+ version: string | null;
69
+ account: string | null;
70
+ }[];
71
+ const testSecret = "sk_test_runtime_composition_fixture";
72
+ const host = {
73
+ enqueue: internalMutationGeneric({
74
+ args: request,
75
+ returns: v.string(),
76
+ handler: async (ctx, args): Promise<string> =>
77
+ ctx.runMutation(nested.betterStripe.fixture.enqueue, {
78
+ ...args,
79
+ provider: await createFunctionHandle(anyApi.host.provider),
80
+ }),
81
+ }),
82
+ provider: internalActionGeneric({
83
+ args: request,
84
+ returns: receipt,
85
+ handler: async (_ctx, args): Promise<Receipt> => {
86
+ calls.push(args);
87
+ active++;
88
+ peak = Math.max(peak, active);
89
+ try {
90
+ if (providerGate) await providerGate;
91
+ if (providerDelay)
92
+ await new Promise((resolve) => setTimeout(resolve, providerDelay));
93
+ if (calls.length <= failUntil)
94
+ throw new Error("transient transport unavailable");
95
+ // Only Stripe transport is replaced. The SDK reads credentials at action
96
+ // execution and uses the selected preview version/account header.
97
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
98
+ apiVersion: args.apiVersion as Stripe.LatestApiVersion,
99
+ maxNetworkRetries: 0,
100
+ httpClient: Stripe.createFetchHttpClient(async (_url, init) => {
101
+ const headers = new Headers(init?.headers);
102
+ transport.push({
103
+ authenticated:
104
+ headers.get("Authorization") === `Bearer ${testSecret}`,
105
+ version: headers.get("Stripe-Version"),
106
+ account: headers.get("Stripe-Account"),
107
+ });
108
+ if (providerUnknown)
109
+ throw new TypeError(
110
+ "provider response lost after possible effect",
111
+ );
112
+ return new Response(
113
+ JSON.stringify({ id: "cus_fixture", object: "customer" }),
114
+ {
115
+ status: 200,
116
+ headers: { "content-type": "application/json" },
117
+ },
118
+ );
119
+ }),
120
+ });
121
+ const customer = await stripe.customers.retrieve(
122
+ "cus_fixture",
123
+ {},
124
+ {
125
+ stripeAccount: args.stripeAccountId,
126
+ },
127
+ );
128
+ return { stripeId: customer.id, apiVersion: args.apiVersion };
129
+ } finally {
130
+ active--;
131
+ }
132
+ },
133
+ }),
134
+ start: internalMutationGeneric({
135
+ args: { ...request, retry: v.boolean(), wait: v.boolean() },
136
+ returns: v.string(),
137
+ handler: async (ctx, args): Promise<string> => {
138
+ const provider = await createFunctionHandle(anyApi.host.provider);
139
+ return ctx.runMutation(nested.betterStripe.fixture.start, {
140
+ ...args,
141
+ provider,
142
+ });
143
+ },
144
+ }),
145
+ };
146
+ const fixture = {
147
+ enqueue: internalMutationGeneric({
148
+ args: { ...request, provider: v.string() },
149
+ returns: v.string(),
150
+ handler: async (ctx, args): Promise<string> =>
151
+ independent.enqueueAction(
152
+ ctx,
153
+ args.provider as FunctionHandle<"action", Request, Receipt>,
154
+ {
155
+ operationKey: args.operationKey,
156
+ stripeAccountId: args.stripeAccountId,
157
+ apiVersion: args.apiVersion,
158
+ },
159
+ {
160
+ retry: false,
161
+ onComplete: anyApi.fixture.queueComplete,
162
+ context: { operationKey: args.operationKey },
163
+ },
164
+ ),
165
+ }),
166
+ queueComplete: internalMutationGeneric({
167
+ args: {
168
+ workId: v.string(),
169
+ result: vResultValidator,
170
+ context: v.object({ operationKey: v.string() }),
171
+ },
172
+ returns: v.null(),
173
+ handler: async (ctx, args) => {
174
+ await ctx.db.insert("completions", {
175
+ operationKey: args.context.operationKey,
176
+ kind: args.result.kind,
177
+ });
178
+ return null;
179
+ },
180
+ }),
181
+ queueStatus: internalQueryGeneric({
182
+ args: { id: v.string() },
183
+ returns: v.any(),
184
+ handler: async (ctx, { id }) => independent.status(ctx, id as WorkId),
185
+ }),
186
+ ledger: internalQueryGeneric({
187
+ args: {},
188
+ returns: v.any(),
189
+ handler: async (ctx) => ({
190
+ receipts: await ctx.db.query("receipts").take(10),
191
+ completions: await ctx.db.query("completions").take(10),
192
+ }),
193
+ }),
194
+ commit: internalMutationGeneric({
195
+ args: { operationKey: v.string(), receipt },
196
+ returns: v.null(),
197
+ handler: async (ctx, args) => {
198
+ commitCalls++;
199
+ if (commitCalls <= commitFailures)
200
+ throw new Error("receipt persistence unavailable");
201
+ await ctx.db.insert("receipts", { operationKey: args.operationKey });
202
+ return null;
203
+ },
204
+ }),
205
+ complete: internalMutationGeneric({
206
+ args: {
207
+ workflowId: vWorkflowId,
208
+ result: vResultValidator,
209
+ context: v.object({ operationKey: v.string() }),
210
+ },
211
+ returns: v.null(),
212
+ handler: async (ctx, args) => {
213
+ await ctx.db.insert("completions", {
214
+ operationKey: args.context.operationKey,
215
+ kind: args.result.kind,
216
+ });
217
+ return null;
218
+ },
219
+ }),
220
+ control: internalMutationGeneric({
221
+ args: {
222
+ id: v.string(),
223
+ command: v.union(
224
+ v.literal("cancel"),
225
+ v.literal("restart"),
226
+ v.literal("cleanup"),
227
+ v.literal("signal"),
228
+ ),
229
+ },
230
+ returns: v.any(),
231
+ handler: async (ctx, { id, command }) => {
232
+ if (command === "cancel") {
233
+ await manager.cancel(ctx, id as WorkflowId);
234
+ return null;
235
+ }
236
+ if (command === "restart") {
237
+ await manager.restart(ctx, id as WorkflowId, {
238
+ from: anyApi.fixture.commit,
239
+ });
240
+ return null;
241
+ }
242
+ if (command === "signal") {
243
+ await manager.sendEvent(ctx, {
244
+ workflowId: id as WorkflowId,
245
+ name: "reconcile",
246
+ value: null,
247
+ });
248
+ return null;
249
+ }
250
+ return manager.cleanup(ctx, id as WorkflowId);
251
+ },
252
+ }),
253
+ history: internalQueryGeneric({
254
+ args: { id: v.string() },
255
+ returns: v.any(),
256
+ handler: async (ctx, { id }) => ({
257
+ workflows: await manager.list(ctx, {
258
+ paginationOpts: { cursor: null, numItems: 10 },
259
+ }),
260
+ steps: await manager.listSteps(ctx, id as WorkflowId, {
261
+ paginationOpts: { cursor: null, numItems: 10 },
262
+ }),
263
+ receipts: await ctx.db.query("receipts").take(10),
264
+ completions: await ctx.db.query("completions").take(10),
265
+ }),
266
+ }),
267
+ status: internalQueryGeneric({
268
+ args: { id: v.string() },
269
+ returns: v.any(),
270
+ handler: async (ctx, { id }) => manager.status(ctx, id as WorkflowId),
271
+ }),
272
+ workflow: manager
273
+ .define({
274
+ args: {
275
+ ...request,
276
+ provider: v.string(),
277
+ retry: v.boolean(),
278
+ wait: v.boolean(),
279
+ },
280
+ returns: receipt,
281
+ })
282
+ .handler(async (step, args): Promise<Receipt> => {
283
+ const result = await step.runAction(
284
+ args.provider as FunctionHandle<"action", Request, Receipt>,
285
+ {
286
+ operationKey: args.operationKey,
287
+ stripeAccountId: args.stripeAccountId,
288
+ apiVersion: definitionChanged
289
+ ? "changed-definition-version"
290
+ : args.apiVersion,
291
+ },
292
+ {
293
+ name: "provider-v1",
294
+ retry: args.retry
295
+ ? { maxAttempts: 2, initialBackoffMs: 1, base: 2 }
296
+ : false,
297
+ },
298
+ );
299
+ if (args.wait) await step.awaitEvent({ name: "reconcile" });
300
+ await step.runMutation(anyApi.fixture.commit, {
301
+ operationKey: args.operationKey,
302
+ receipt: result,
303
+ });
304
+ return result;
305
+ }),
306
+ start: internalMutationGeneric({
307
+ args: {
308
+ ...request,
309
+ provider: v.string(),
310
+ retry: v.boolean(),
311
+ wait: v.boolean(),
312
+ },
313
+ returns: v.string(),
314
+ handler: async (ctx, args): Promise<string> =>
315
+ manager.start(ctx, workflowRef, args, {
316
+ onComplete: anyApi.fixture.complete,
317
+ context: { operationKey: args.operationKey },
318
+ }),
319
+ }),
320
+ };
321
+ function setup() {
322
+ const app = convexTest(defineSchema({}), {
323
+ "./_generated/api.ts": async () => ({}),
324
+ "./host.ts": async () => host,
325
+ });
326
+ app.registerComponent(
327
+ "betterStripe",
328
+ defineSchema({
329
+ receipts: defineTable({ operationKey: v.string() }),
330
+ completions: defineTable({ operationKey: v.string(), kind: v.string() }),
331
+ }),
332
+ {
333
+ "./_generated/api.ts": async () => ({}),
334
+ "./fixture.ts": async () => fixture,
335
+ },
336
+ );
337
+ const child = workflowTest.register(app, "betterStripe/workflow");
338
+ workpoolTest.register(app, "betterStripe/independent");
339
+ return { t: app, child };
340
+ }
341
+ const args = {
342
+ operationKey: "operation:1:apply:v1",
343
+ stripeAccountId: "acct_scope",
344
+ apiVersion: "2026-02-25.preview",
345
+ retry: false,
346
+ wait: false,
347
+ };
348
+ beforeEach(() => {
349
+ vi.useFakeTimers();
350
+ vi.stubEnv("STRIPE_SECRET_KEY", testSecret);
351
+ calls = [];
352
+ failUntil = 0;
353
+ providerUnknown = false;
354
+ definitionChanged = false;
355
+ active = 0;
356
+ peak = 0;
357
+ transport = [];
358
+ commitFailures = 0;
359
+ commitCalls = 0;
360
+ providerDelay = 0;
361
+ providerGate = null;
362
+ });
363
+ afterEach(() => {
364
+ vi.useRealTimers();
365
+ vi.unstubAllEnvs();
366
+ });
367
+
368
+ it("executes a host credential action through nested Workflow/Workpool with version and scope", async () => {
369
+ const { t } = setup();
370
+ const id = await t.mutation(anyApi.host.start, args);
371
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
372
+ const status = await t.query(nested.betterStripe.fixture.status, { id });
373
+ expect(status).toEqual({
374
+ type: "completed",
375
+ result: { stripeId: "cus_fixture", apiVersion: args.apiVersion },
376
+ });
377
+ expect(transport).toEqual([
378
+ {
379
+ authenticated: true,
380
+ version: args.apiVersion,
381
+ account: args.stripeAccountId,
382
+ },
383
+ ]);
384
+ expect(calls).toEqual([
385
+ {
386
+ operationKey: args.operationKey,
387
+ stripeAccountId: args.stripeAccountId,
388
+ apiVersion: args.apiVersion,
389
+ },
390
+ ]);
391
+ expect(JSON.stringify(status)).not.toContain(testSecret);
392
+ });
393
+
394
+ it("replays the saved provider receipt after a later persistence failure", async () => {
395
+ commitFailures = 1;
396
+ const { t } = setup();
397
+ const id = await t.mutation(anyApi.host.start, args);
398
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
399
+ expect(
400
+ await t.query(nested.betterStripe.fixture.status, { id }),
401
+ ).toMatchObject({ type: "failed" });
402
+ await t.mutation(nested.betterStripe.fixture.control, {
403
+ id,
404
+ command: "restart",
405
+ });
406
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
407
+ expect(
408
+ await t.query(nested.betterStripe.fixture.status, { id }),
409
+ ).toMatchObject({ type: "completed" });
410
+ expect(calls).toHaveLength(1);
411
+ expect(commitCalls).toBe(2);
412
+ const history = await t.query(nested.betterStripe.fixture.history, { id });
413
+ expect(history.receipts).toHaveLength(1);
414
+ expect(JSON.stringify(history)).not.toContain(testSecret);
415
+ expect(JSON.stringify(history)).toContain(args.operationKey);
416
+ expect(
417
+ await t.mutation(nested.betterStripe.fixture.control, {
418
+ id,
419
+ command: "cleanup",
420
+ }),
421
+ ).toBe(true);
422
+ const retained = await t.query(nested.betterStripe.fixture.ledger, {});
423
+ // Cleanup removes execution history only. The separate receipt remains.
424
+ expect(retained.receipts).toHaveLength(1);
425
+ await expect(
426
+ t.mutation(nested.betterStripe.fixture.control, { id, command: "restart" }),
427
+ ).rejects.toThrow();
428
+ expect(calls).toHaveLength(1);
429
+ expect(
430
+ retained.completions.map((entry: { kind: string }) => entry.kind),
431
+ ).toEqual(["failed", "success"]);
432
+ });
433
+
434
+ it("retries only when explicitly opted in and honors the configured attempt cap", async () => {
435
+ failUntil = 10;
436
+ const { t } = setup();
437
+ const id = await t.mutation(anyApi.host.start, { ...args, retry: true });
438
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
439
+ expect(calls).toHaveLength(2);
440
+ expect(
441
+ await t.query(nested.betterStripe.fixture.status, { id }),
442
+ ).toMatchObject({ type: "failed" });
443
+ });
444
+
445
+ it("does not automatically repeat an unknown provider effect", async () => {
446
+ providerUnknown = true;
447
+ const { t } = setup();
448
+ const id = await t.mutation(anyApi.host.start, args);
449
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
450
+ expect(calls).toHaveLength(1);
451
+ expect(
452
+ await t.query(nested.betterStripe.fixture.status, { id }),
453
+ ).toMatchObject({
454
+ type: "failed",
455
+ error: expect.stringContaining("connection to Stripe"),
456
+ });
457
+ // A failed execution is not a rejected/canceled financial outcome. The
458
+ // operation owner must reconcile the same phase key before any restart.
459
+ expect(commitCalls).toBe(0);
460
+ expect(transport).toHaveLength(1);
461
+ });
462
+
463
+ it("caps provider action concurrency across parallel workflows", async () => {
464
+ providerDelay = 10;
465
+ const { t } = setup();
466
+ const ids = await Promise.all(
467
+ [1, 2, 3, 4].map((n) =>
468
+ t.mutation(anyApi.host.start, {
469
+ ...args,
470
+ operationKey: `operation:${n}:apply:v1`,
471
+ }),
472
+ ),
473
+ );
474
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
475
+ expect(peak).toBe(2);
476
+ expect(calls).toHaveLength(4);
477
+ for (const id of ids)
478
+ expect(
479
+ await t.query(nested.betterStripe.fixture.status, { id }),
480
+ ).toMatchObject({ type: "completed" });
481
+ });
482
+
483
+ it("cancellation cannot undo a provider step already in flight", async () => {
484
+ let release!: () => void;
485
+ providerGate = new Promise<void>((resolve) => {
486
+ release = resolve;
487
+ });
488
+ const { t } = setup();
489
+ const id = await t.mutation(anyApi.host.start, args);
490
+ const drain = t.finishAllScheduledFunctions(vi.runAllTimers);
491
+ await vi.waitFor(() => expect(calls).toHaveLength(1));
492
+ await t.mutation(nested.betterStripe.fixture.control, {
493
+ id,
494
+ command: "cancel",
495
+ });
496
+ release();
497
+ await drain;
498
+ expect(transport).toHaveLength(1);
499
+ expect(
500
+ await t.query(nested.betterStripe.fixture.status, { id }),
501
+ ).toMatchObject({ type: "canceled" });
502
+ expect(commitCalls).toBe(0);
503
+ });
504
+
505
+ it("runs an independent queued provider job without creating a workflow", async () => {
506
+ const { t } = setup();
507
+ const id = await t.mutation(anyApi.host.enqueue, {
508
+ operationKey: args.operationKey,
509
+ stripeAccountId: args.stripeAccountId,
510
+ apiVersion: args.apiVersion,
511
+ });
512
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
513
+ expect(
514
+ await t.query(nested.betterStripe.fixture.queueStatus, { id }),
515
+ ).toMatchObject({ state: "finished" });
516
+ expect(calls).toHaveLength(1);
517
+ expect(await t.query(nested.betterStripe.fixture.ledger, {})).toMatchObject({
518
+ completions: [{ operationKey: args.operationKey, kind: "success" }],
519
+ });
520
+ });
521
+
522
+ it("retains a waiting workflow until reconciliation and exposes reactive status", async () => {
523
+ const { t } = setup();
524
+ const id = await t.mutation(anyApi.host.start, { ...args, wait: true });
525
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
526
+ expect(
527
+ await t.query(nested.betterStripe.fixture.status, { id }),
528
+ ).toMatchObject({ type: "inProgress" });
529
+ expect(
530
+ await t.mutation(nested.betterStripe.fixture.control, {
531
+ id,
532
+ command: "cleanup",
533
+ }),
534
+ ).toBe(false);
535
+ expect(commitCalls).toBe(0);
536
+ await t.mutation(nested.betterStripe.fixture.control, {
537
+ id,
538
+ command: "signal",
539
+ });
540
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
541
+ expect(
542
+ await t.query(nested.betterStripe.fixture.status, { id }),
543
+ ).toMatchObject({ type: "completed" });
544
+ expect(calls).toHaveLength(1);
545
+ expect(await t.query(nested.betterStripe.fixture.ledger, {})).toMatchObject({
546
+ completions: [{ kind: "success" }],
547
+ });
548
+ });
549
+
550
+ it("refuses changed-definition provider arguments during saved-history replay", async () => {
551
+ const { t } = setup();
552
+ const id = await t.mutation(anyApi.host.start, { ...args, wait: true });
553
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
554
+ definitionChanged = true;
555
+ await t.mutation(nested.betterStripe.fixture.control, {
556
+ id,
557
+ command: "signal",
558
+ });
559
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
560
+ expect(
561
+ await t.query(nested.betterStripe.fixture.status, { id }),
562
+ ).toMatchObject({ type: "failed" });
563
+ expect(calls).toHaveLength(1);
564
+ expect(calls[0].apiVersion).toBe(args.apiVersion);
565
+ expect(commitCalls).toBe(0);
566
+ const history = await t.query(nested.betterStripe.fixture.history, { id });
567
+ expect(JSON.stringify(history.steps)).toContain(args.apiVersion);
568
+ });
@@ -0,0 +1,12 @@
1
+ import { WorkflowManager } from "@convex-dev/workflow";
2
+ import { components } from "../_generated/api.js";
3
+
4
+ // Workflow owns its Workpool. Do not enqueue workflow steps in a second pool.
5
+ // Provider writes require phase-specific reconciliation before any replay;
6
+ // throwing from an action does not prove the provider rejected its effect.
7
+ export const executionWorkflow = new WorkflowManager(components.workflow, {
8
+ workpoolOptions: {
9
+ maxParallelism: 2,
10
+ retryActionsByDefault: false,
11
+ },
12
+ });
@@ -1,3 +1,8 @@
1
+ import {
2
+ preparationsTable as balanceFundingPreparations,
3
+ operationsTable as balanceFundingOperations,
4
+ requestsTable as balanceFundingRequests,
5
+ } from "./balanceFunding/schema.js";
1
6
  import {
2
7
  payloadsTable as operationEvidencePayloads,
3
8
  headersTable as operationEvidenceHeaders,
@@ -78,6 +83,9 @@ import { pricesTable, productsTable } from "./products/schema";
78
83
  import { webhookEventsTable } from "./webhooks/schema";
79
84
 
80
85
  export default defineSchema({
86
+ balanceFundingPreparations,
87
+ balanceFundingOperations,
88
+ balanceFundingRequests,
81
89
  operationEvidencePayloads,
82
90
  operationEvidenceHeaders,
83
91
  financialTransferObservations: transferObservationsTable,