@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
@@ -0,0 +1,500 @@
1
+ import assert from "node:assert/strict";
2
+ import { components } from "../../../../../example/convex/_generated/api.js";
3
+ import { createActionOperationJournal } from "./operationJournal.js";
4
+ import { convexTest } from "convex-test";
5
+ import {
6
+ actionGeneric,
7
+ componentsGeneric,
8
+ defineSchema,
9
+ makeFunctionReference,
10
+ type FunctionReturnType,
11
+ } from "convex/server";
12
+ import { getConvexSize, getDocumentSize, v } from "convex/values";
13
+ import { afterEach, expect, it, vi } from "vitest";
14
+ import { modules, schema } from "../../../../test.js";
15
+ import { query } from "../../../../component/_generated/server.js";
16
+ import type { Doc } from "../../../../component/_generated/dataModel.js";
17
+ import {
18
+ prepareV2AcknowledgementScenario,
19
+ canonical,
20
+ VALUE_LIMIT,
21
+ } from "../../../../component/renewalOperations/acknowledgement.fixtures.js";
22
+ import { canonicalJournalEvent } from "../../../../shared/renewalOperationJournal.js";
23
+
24
+ const refs = components.betterStripe.renewalOperations;
25
+ const nested = componentsGeneric();
26
+ type Retained = FunctionReturnType<
27
+ typeof refs.mutations.retainProviderAcknowledgement
28
+ >;
29
+ type Read = FunctionReturnType<typeof refs.queries.readProviderAcknowledgement>;
30
+ const target = makeFunctionReference<
31
+ "action",
32
+ { operationId: string },
33
+ { retained: Retained | null; read: Read }
34
+ >("adapterAcknowledgement:run");
35
+ const scenarios = ["retain-duplicate", "read", "retain-first"] as const;
36
+ type Physical = {
37
+ operations: Doc<"renewalOperations">[];
38
+ attempts: Doc<"renewalOperationAttempts">[];
39
+ events: Doc<"renewalOperationEvents">[];
40
+ payloads: Doc<"renewalOperationPayloads">[];
41
+ };
42
+ const inspection = {
43
+ physical: query({
44
+ args: {},
45
+ handler: async (ctx): Promise<Physical> => ({
46
+ operations: await ctx.db.query("renewalOperations").take(3),
47
+ attempts: await ctx.db.query("renewalOperationAttempts").take(3),
48
+ events: await ctx.db.query("renewalOperationEvents").take(4),
49
+ payloads: await ctx.db.query("renewalOperationPayloads").take(6),
50
+ }),
51
+ }),
52
+ };
53
+ afterEach(() => vi.unstubAllGlobals());
54
+
55
+ it.each(scenarios)(
56
+ "ADAPTER-ACK %s preserves complete owned C3 DATA",
57
+ async (scenario) => {
58
+ const basis = {
59
+ startWallMs: 1700000001000,
60
+ startNsDecimal: "1000000000",
61
+ workEndWallMs: 1700000005000,
62
+ workEndNsDecimal: "5000000000",
63
+ endWallMs: 1700000006000,
64
+ endNsDecimal: "6000000000",
65
+ };
66
+ // Maintained offline pure C3/whole-output/capture fixture, not runtime custody.
67
+ // Its DB rows/IDs are never copied into the fresh mounted operation below.
68
+ const h = await prepareV2AcknowledgementScenario();
69
+ expect(h.shouldRetain).toBe(true);
70
+ expect(h.scenario).toBe("clean");
71
+ const recordJSON = h.acquired.reservation.recordJSON;
72
+ const declared = JSON.parse(recordJSON);
73
+ expect(declared.schemaVersion).toBe(2);
74
+ expect(declared.attachRequest).toEqual(h.raw.attachRequest);
75
+ expect(declared.dispatch).toEqual(h.raw.actualDispatch);
76
+ expect(Object.keys(declared.dispatch)).toHaveLength(7);
77
+ expect(canonical(h.receipt)).toBe(h.receiptJSON);
78
+ const declaredEvents: Awaited<ReturnType<typeof canonicalJournalEvent>>[] =
79
+ [];
80
+ for (const committed of h.commits) {
81
+ const payload = h.before.payloads.find(
82
+ (row) => row._id === committed.payloadId,
83
+ );
84
+ assert(payload);
85
+ const event = await canonicalJournalEvent(
86
+ committed.sequence,
87
+ payload.json,
88
+ );
89
+ expect(event.binding).toBe(committed.binding);
90
+ expect(event.json).toBe(payload.json);
91
+ declaredEvents.push(event);
92
+ }
93
+ expect(declaredEvents.map((event) => event.sequence)).toEqual([1, 2]);
94
+ const progress = { direct: 0, capture: 0, target: 0 };
95
+ const host = {
96
+ run: actionGeneric({
97
+ args: { operationId: v.string() },
98
+ handler: async (
99
+ ctx,
100
+ args,
101
+ ): Promise<FunctionReturnType<typeof target>> => {
102
+ expect(await ctx.meta.getFunctionMetadata()).toEqual({
103
+ name: "adapterAcknowledgement:run",
104
+ componentPath: "",
105
+ type: "action",
106
+ visibility: "public",
107
+ });
108
+ const loaded = await ctx.runQuery(
109
+ refs.queries.loadAuthorizedOperation,
110
+ args,
111
+ );
112
+ assert(
113
+ loaded && "recordVersion" in loaded && loaded.recordVersion === 2,
114
+ );
115
+ expect(loaded.recordJSON).toBe(recordJSON);
116
+ expect(loaded.initialBasis).toEqual(bound.initialBasis);
117
+ expect(
118
+ await ctx.runQuery(
119
+ nested.betterStripe.adapterAcknowledgementInspection.physical,
120
+ {},
121
+ ),
122
+ ).toEqual(before);
123
+ const direct = await ctx.runQuery(
124
+ refs.queries.readProviderAcknowledgement,
125
+ args,
126
+ );
127
+ expect(direct).toEqual(
128
+ scenario === "retain-first"
129
+ ? null
130
+ : { retention: originalRetained, receiptJSON: h.receiptJSON },
131
+ );
132
+ progress.direct++;
133
+ const journal = await createActionOperationJournal(
134
+ ctx,
135
+ components.betterStripe,
136
+ args.operationId,
137
+ );
138
+ progress.capture++;
139
+ if (scenario === "read") {
140
+ const read = await journal.readProviderAcknowledgement();
141
+ progress.target++;
142
+ expect(read).toEqual(direct);
143
+ return { retained: originalRetained, read };
144
+ }
145
+ const retained = await journal.retainProviderAcknowledgement({
146
+ attemptId: reservation.attemptId,
147
+ expectedSequence: 2,
148
+ receiptJSON: h.receiptJSON,
149
+ });
150
+ progress.target++;
151
+ if (scenario === "retain-duplicate")
152
+ expect(retained).toEqual(originalRetained);
153
+ else expect(retained).toMatchObject({ status: "retained", ...args });
154
+ assert(retained !== null);
155
+ const read = await ctx.runQuery(
156
+ refs.queries.readProviderAcknowledgement,
157
+ args,
158
+ );
159
+ expect(read).toEqual({
160
+ retention: retained,
161
+ receiptJSON: h.receiptJSON,
162
+ });
163
+ return { retained, read };
164
+ },
165
+ }),
166
+ };
167
+ const t = convexTest(defineSchema({}), {
168
+ "./_generated/api.ts": async () => ({}),
169
+ "./adapterAcknowledgement.ts": async () => host,
170
+ });
171
+ t.registerComponent("betterStripe", schema, {
172
+ ...modules,
173
+ "./component/adapterAcknowledgementInspection.ts": async () => inspection,
174
+ });
175
+ const physical = async (): Promise<Physical> =>
176
+ t.query(
177
+ nested.betterStripe.adapterAcknowledgementInspection.physical,
178
+ {},
179
+ );
180
+ expect(await physical()).toEqual({
181
+ operations: [],
182
+ attempts: [],
183
+ events: [],
184
+ payloads: [],
185
+ });
186
+ const sourceOperation = h.before.operations[0];
187
+ const created = await t.mutation(refs.mutations.createAuthorizedOperation, {
188
+ authorizationScope: sourceOperation.authorizationScope,
189
+ logicalOperationId: sourceOperation.logicalOperationId,
190
+ authorizationRevision: sourceOperation.authorizationRevision,
191
+ recordJSON,
192
+ });
193
+ assert(created.status === "created");
194
+ const args = { operationId: created.operationId };
195
+ const acquired = await t.mutation(refs.mutations.reserveAttempt, {
196
+ ...args,
197
+ expectedRevision: 0,
198
+ stage: "attach",
199
+ expectedRequestBinding: h.acquired.reservation.requestBinding,
200
+ recordJSON,
201
+ });
202
+ assert(acquired.disposition === "acquired");
203
+ const reservation = acquired.reservation;
204
+ expect(reservation.recordJSON).toBe(recordJSON);
205
+ const bound = await t.mutation(refs.mutations.bindInitialBasis, {
206
+ ...args,
207
+ attemptId: reservation.attemptId,
208
+ policyJSON: canonical(declared.timingPolicy),
209
+ basisJSON: canonical(basis),
210
+ });
211
+ const commits: FunctionReturnType<
212
+ typeof refs.mutations.appendStageEvent
213
+ >[] = [];
214
+ for (const event of declaredEvents) {
215
+ const committed = await t.mutation(refs.mutations.appendStageEvent, {
216
+ reservation,
217
+ expectedSequence: event.sequence - 1,
218
+ event: {
219
+ sequence: event.sequence,
220
+ binding: event.binding,
221
+ dataJSON: event.json,
222
+ },
223
+ });
224
+ expect(committed.reservation).toEqual(reservation);
225
+ commits.push(committed);
226
+ }
227
+ const owned = await physical();
228
+ expect({
229
+ operations: owned.operations.length,
230
+ attempts: owned.attempts.length,
231
+ events: owned.events.length,
232
+ payloads: owned.payloads.length,
233
+ }).toEqual({ operations: 1, attempts: 1, events: 2, payloads: 3 });
234
+ expect(owned.operations[0].initialBasis).toEqual(bound.initialBasis);
235
+ expect(owned.attempts[0].lastSequence).toBe(2);
236
+ expect(owned.operations[0].knownAcknowledgement).toBeUndefined();
237
+ const source = owned.payloads.find(
238
+ (row) => row._id === reservation.payloadId,
239
+ );
240
+ assert(source);
241
+ expect(source.json).toBe(recordJSON);
242
+ expect(source.owner).toEqual({ kind: "operation", ...args });
243
+ for (let index = 0; index < commits.length; index++) {
244
+ const commit = commits[index];
245
+ const row = owned.events.find((event) => event._id === commit.eventId);
246
+ assert(row);
247
+ expect(row).toEqual({
248
+ _id: commit.eventId,
249
+ _creationTime: row._creationTime,
250
+ operationId: created.operationId,
251
+ attemptId: reservation.attemptId,
252
+ sourcePayloadId: reservation.payloadId,
253
+ stage: "attach",
254
+ sequence: commit.sequence,
255
+ binding: commit.binding,
256
+ payloadId: commit.payloadId,
257
+ });
258
+ const payload = owned.payloads.find(
259
+ (row) => row._id === commit.payloadId,
260
+ );
261
+ assert(payload);
262
+ expect(payload).toEqual({
263
+ _id: commit.payloadId,
264
+ _creationTime: payload._creationTime,
265
+ codecVersion: 1,
266
+ json: declaredEvents[index].json,
267
+ owner: {
268
+ kind: "event",
269
+ ...args,
270
+ attemptId: reservation.attemptId,
271
+ stage: "attach",
272
+ sequence: commit.sequence,
273
+ },
274
+ });
275
+ }
276
+ const retainArgs = {
277
+ ...args,
278
+ attemptId: reservation.attemptId,
279
+ expectedSequence: 2 as const,
280
+ receiptJSON: h.receiptJSON,
281
+ };
282
+ expect(getConvexSize(retainArgs)).toBeLessThanOrEqual(VALUE_LIMIT);
283
+ const originalRetained: Retained | null =
284
+ scenario === "retain-first"
285
+ ? null
286
+ : await t.mutation(
287
+ refs.mutations.retainProviderAcknowledgement,
288
+ retainArgs,
289
+ );
290
+ const before = await physical();
291
+ let stable = before;
292
+ let failed = false;
293
+ try {
294
+ const result = await t.action(target, args);
295
+ expect(progress).toEqual({ direct: 1, capture: 1, target: 1 });
296
+ assert(result.retained !== null);
297
+ const retained = result.retained;
298
+ const known = {
299
+ schemaVersion: 1,
300
+ stage: "attach",
301
+ attemptId: reservation.attemptId,
302
+ sourcePayloadId: reservation.payloadId,
303
+ dispatchEventId: commits[0].eventId,
304
+ dispatchPayloadId: commits[0].payloadId,
305
+ responseEventId: commits[1].eventId,
306
+ responsePayloadId: commits[1].payloadId,
307
+ receiptPayloadId: retained.receiptPayloadId,
308
+ receiptBinding: h.receipt.binding,
309
+ };
310
+ expect(retained).toEqual({ status: "retained", ...args, ...known });
311
+ expect(result.read).toEqual({
312
+ retention: retained,
313
+ receiptJSON: h.receiptJSON,
314
+ });
315
+ const after = await physical();
316
+ expect({
317
+ operations: after.operations.length,
318
+ attempts: after.attempts.length,
319
+ events: after.events.length,
320
+ payloads: after.payloads.length,
321
+ }).toEqual({ operations: 1, attempts: 1, events: 2, payloads: 4 });
322
+ expect(after.operations).toEqual([
323
+ { ...owned.operations[0], knownAcknowledgement: known },
324
+ ]);
325
+ expect(after.attempts).toEqual(owned.attempts);
326
+ expect(after.events).toEqual(owned.events);
327
+ for (const original of owned.payloads)
328
+ expect(after.payloads.find((row) => row._id === original._id)).toEqual(
329
+ original,
330
+ );
331
+ const receiptPayload = after.payloads.find(
332
+ (row) => row._id === retained.receiptPayloadId,
333
+ );
334
+ assert(receiptPayload);
335
+ expect(receiptPayload).toEqual({
336
+ _id: retained.receiptPayloadId,
337
+ _creationTime: receiptPayload._creationTime,
338
+ codecVersion: 1,
339
+ json: h.receiptJSON,
340
+ owner: {
341
+ kind: "receipt",
342
+ ...args,
343
+ attemptId: reservation.attemptId,
344
+ stage: "attach",
345
+ },
346
+ });
347
+ expect(after.events.some((row) => row.sequence === 3)).toBe(false);
348
+ if (scenario !== "retain-first") expect(after).toEqual(before);
349
+ for (const rows of Object.values(after))
350
+ for (const row of rows)
351
+ expect(getDocumentSize(row)).toBeLessThanOrEqual(VALUE_LIMIT);
352
+ expect(getConvexSize(result)).toBeLessThanOrEqual(VALUE_LIMIT);
353
+ stable = after;
354
+ } catch (error) {
355
+ failed = true;
356
+ throw error;
357
+ } finally {
358
+ try {
359
+ expect(await physical()).toEqual(stable);
360
+ expect(h.fetchCalls()).toBe(0);
361
+ console.info(
362
+ "ADAPTER_ACK_SETTLEMENT",
363
+ JSON.stringify({
364
+ scenario,
365
+ ...progress,
366
+ physicalEqual: true,
367
+ fetchCalls: 0,
368
+ }),
369
+ );
370
+ } catch (error) {
371
+ if (!failed) throw error;
372
+ console.info("ADAPTER_ACK_INSPECTION_FAILED");
373
+ }
374
+ }
375
+ },
376
+ );
377
+
378
+ it.each(["extra-operation", "foreign-reservation"] as const)(
379
+ "ADAPTER-SCOPE %s refuses without modifying either real operation",
380
+ async (mode) => {
381
+ const h = await prepareV2AcknowledgementScenario();
382
+ const original = JSON.parse(h.acquired.reservation.recordJSON);
383
+ const foreignJSON = canonical({
384
+ ...original,
385
+ logicalOperationId: original.logicalOperationId + "-foreign",
386
+ });
387
+ const host = {
388
+ run: actionGeneric({
389
+ args: { operationId: v.string() },
390
+ handler: async (
391
+ ctx,
392
+ args,
393
+ ): Promise<FunctionReturnType<typeof target>> => {
394
+ const direct = await ctx.runQuery(
395
+ refs.queries.loadAuthorizedOperation,
396
+ args,
397
+ );
398
+ expect(direct?.recordJSON).toBe(h.acquired.reservation.recordJSON);
399
+ expect(
400
+ (
401
+ await ctx.runQuery(refs.queries.loadAuthorizedOperation, {
402
+ operationId: foreignOperationId,
403
+ })
404
+ )?.recordJSON,
405
+ ).toBe(foreignJSON);
406
+ const journal = await createActionOperationJournal(
407
+ ctx,
408
+ components.betterStripe,
409
+ args.operationId,
410
+ );
411
+ if (mode === "extra-operation") {
412
+ const input = {
413
+ operationId: foreignOperationId,
414
+ expectedRevision: 0,
415
+ stage: "attach" as const,
416
+ expectedRequestBinding: original.requestBinding,
417
+ recordJSON: foreignJSON,
418
+ };
419
+ await expect(journal.reserveAttempt(input)).rejects.toThrow(
420
+ /^OPERATION_JOURNAL_ACTION_UNBOUND$/,
421
+ );
422
+ } else {
423
+ const input = {
424
+ reservation,
425
+ expectedSequence: 0,
426
+ event: {
427
+ sequence: 1 as const,
428
+ binding: event.binding,
429
+ dataJSON: event.json,
430
+ },
431
+ };
432
+ await expect(journal.appendStageEvent(input)).rejects.toThrow(
433
+ /^OPERATION_JOURNAL_ACTION_UNBOUND$/,
434
+ );
435
+ }
436
+ return { retained: null, read: null };
437
+ },
438
+ }),
439
+ };
440
+ const t = convexTest(defineSchema({}), {
441
+ "./_generated/api.ts": async () => ({}),
442
+ "./adapterAcknowledgement.ts": async () => host,
443
+ });
444
+ t.registerComponent("betterStripe", schema, {
445
+ ...modules,
446
+ "./component/adapterAcknowledgementInspection.ts": async () => inspection,
447
+ });
448
+ const physical = async (): Promise<Physical> =>
449
+ t.query(
450
+ nested.betterStripe.adapterAcknowledgementInspection.physical,
451
+ {},
452
+ );
453
+ const createInput = {
454
+ authorizationScope: original.authorization.scope,
455
+ authorizationRevision: original.authorization.revision,
456
+ logicalOperationId: original.logicalOperationId,
457
+ recordJSON: h.acquired.reservation.recordJSON,
458
+ };
459
+ const created = await t.mutation(
460
+ refs.mutations.createAuthorizedOperation,
461
+ createInput,
462
+ );
463
+ const foreign = await t.mutation(refs.mutations.createAuthorizedOperation, {
464
+ ...createInput,
465
+ logicalOperationId: original.logicalOperationId + "-foreign",
466
+ recordJSON: foreignJSON,
467
+ });
468
+ assert(created.status === "created" && foreign.status === "created");
469
+ const foreignOperationId = foreign.operationId;
470
+ const acquired = await t.mutation(refs.mutations.reserveAttempt, {
471
+ operationId: foreignOperationId,
472
+ expectedRevision: 0,
473
+ stage: "attach",
474
+ expectedRequestBinding: original.requestBinding,
475
+ recordJSON: foreignJSON,
476
+ });
477
+ assert(acquired.disposition === "acquired");
478
+ const reservation = acquired.reservation;
479
+ const event = await canonicalJournalEvent(
480
+ 1,
481
+ canonical({ independent: "scope-refusal" }),
482
+ );
483
+ const before = await physical();
484
+ let failed = false;
485
+ try {
486
+ await t.action(target, { operationId: created.operationId });
487
+ } catch (error) {
488
+ failed = true;
489
+ throw error;
490
+ } finally {
491
+ try {
492
+ expect(await physical()).toEqual(before);
493
+ expect(h.fetchCalls()).toBe(0);
494
+ } catch (error) {
495
+ if (!failed) throw error;
496
+ console.info("ADAPTER_SCOPE_INSPECTION_FAILED");
497
+ }
498
+ }
499
+ },
500
+ );