@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,534 @@
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
+ } from "convex/server";
11
+ import { getConvexSize, getDocumentSize, v, type Value } from "convex/values";
12
+ import { afterEach, expect, it, vi } from "vitest";
13
+ import { modules, schema } from "../../../../test.js";
14
+ import { query } from "../../../../component/_generated/server.js";
15
+ import type { Doc } from "../../../../component/_generated/dataModel.js";
16
+ import {
17
+ canonical,
18
+ codecFixture,
19
+ VALUE_LIMIT,
20
+ } from "../../../../component/renewalOperations/timingPolicy.fixtures.js";
21
+ import { canonicalJournalEvent } from "../../../../shared/renewalOperationJournal.js";
22
+
23
+ const refs = components.betterStripe.renewalOperations;
24
+ const inspectionRefs = componentsGeneric();
25
+ const call = makeFunctionReference<"action", { operationId: string }, null>(
26
+ "adapterMethods:run",
27
+ );
28
+ const basis = {
29
+ startWallMs: 1700000001000,
30
+ startNsDecimal: "1000000000",
31
+ workEndWallMs: 1700000005000,
32
+ workEndNsDecimal: "5000000000",
33
+ endWallMs: 1700000006000,
34
+ endNsDecimal: "6000000000",
35
+ };
36
+ const methods = [
37
+ "reserveAttempt",
38
+ "bindInitialBasis",
39
+ "appendStageEvent",
40
+ "readAttempt",
41
+ "readStageEvent",
42
+ ] as const;
43
+ const identities = ["runQuery", "runMutation", "getFunctionMetadata"] as const;
44
+ type Physical = {
45
+ operations: Doc<"renewalOperations">[];
46
+ attempts: Doc<"renewalOperationAttempts">[];
47
+ events: Doc<"renewalOperationEvents">[];
48
+ payloads: Doc<"renewalOperationPayloads">[];
49
+ };
50
+ const inspection = {
51
+ physical: query({
52
+ args: {},
53
+ handler: async (ctx): Promise<Physical> => ({
54
+ operations: await ctx.db.query("renewalOperations").take(4),
55
+ attempts: await ctx.db.query("renewalOperationAttempts").take(4),
56
+ events: await ctx.db.query("renewalOperationEvents").take(7),
57
+ payloads: await ctx.db.query("renewalOperationPayloads").take(9),
58
+ }),
59
+ }),
60
+ };
61
+ afterEach(() => vi.unstubAllGlobals());
62
+
63
+ it.each(methods)(
64
+ "ADAPTER-METHOD %s returns original complete committed DATA",
65
+ async (method) => {
66
+ // Entire event/basis recipe precedes constructors and real transactions.
67
+ const event = await canonicalJournalEvent(
68
+ 1,
69
+ canonical({ future: [null, "retained", 1.25] }),
70
+ );
71
+ const h = await codecFixture();
72
+ const progress = { direct: 0, captured: 0, target: 0 };
73
+ const host = {
74
+ run: actionGeneric({
75
+ args: { operationId: v.string() },
76
+ handler: async (ctx, args) => {
77
+ expect(await ctx.meta.getFunctionMetadata()).toEqual({
78
+ name: "adapterMethods:run",
79
+ componentPath: "",
80
+ type: "action",
81
+ visibility: "public",
82
+ });
83
+ const directLoad = await ctx.runQuery(
84
+ refs.queries.loadAuthorizedOperation,
85
+ args,
86
+ );
87
+ assert(
88
+ directLoad &&
89
+ "recordVersion" in directLoad &&
90
+ directLoad.recordVersion === 2 &&
91
+ directLoad.activeAttempt,
92
+ );
93
+ expect(directLoad.recordJSON).toBe(h.recordJSON);
94
+ expect(directLoad.initialBasis).toEqual(bound.initialBasis);
95
+ expect(
96
+ await ctx.runQuery(
97
+ inspectionRefs.betterStripe.adapterMethodsInspection.physical,
98
+ {},
99
+ ),
100
+ ).toEqual(before);
101
+ const journal = await createActionOperationJournal(
102
+ ctx,
103
+ components.betterStripe,
104
+ args.operationId,
105
+ );
106
+ progress.captured++;
107
+ let direct: Value;
108
+ let actual: Value;
109
+ if (method === "reserveAttempt") {
110
+ const input = {
111
+ expectedRevision: 0,
112
+ stage: "attach" as const,
113
+ expectedRequestBinding: h.record.requestBinding,
114
+ recordJSON: h.recordJSON,
115
+ };
116
+ direct = await ctx.runMutation(refs.mutations.reserveAttempt, {
117
+ ...args,
118
+ ...input,
119
+ });
120
+ expect(direct).toEqual({
121
+ disposition: "existing",
122
+ committedRevision: 1,
123
+ reservation,
124
+ });
125
+ progress.direct++;
126
+ actual = await journal.reserveAttempt(input);
127
+ } else if (method === "bindInitialBasis") {
128
+ const input = {
129
+ attemptId: reservation.attemptId,
130
+ policyJSON: canonical(h.record.timingPolicy),
131
+ basisJSON: canonical(basis),
132
+ };
133
+ direct = await ctx.runMutation(refs.mutations.bindInitialBasis, {
134
+ ...args,
135
+ ...input,
136
+ });
137
+ expect(direct).toEqual(bound);
138
+ progress.direct++;
139
+ actual = await journal.bindInitialBasis(input);
140
+ } else if (method === "appendStageEvent") {
141
+ const input = {
142
+ reservation,
143
+ expectedSequence: 0,
144
+ event: {
145
+ sequence: 1 as const,
146
+ binding: event.binding,
147
+ dataJSON: event.json,
148
+ },
149
+ };
150
+ direct = await ctx.runMutation(
151
+ refs.mutations.appendStageEvent,
152
+ input,
153
+ );
154
+ expect(direct).toEqual(committed);
155
+ progress.direct++;
156
+ actual = await journal.appendStageEvent(input);
157
+ } else if (method === "readAttempt") {
158
+ const input = { attemptId: reservation.attemptId };
159
+ direct = await ctx.runQuery(refs.queries.readAttempt, {
160
+ ...args,
161
+ ...input,
162
+ });
163
+ const { reservation: _reservation, ...descriptor } = committed;
164
+ expect(direct).toEqual({
165
+ reservation,
166
+ events: [descriptor],
167
+ });
168
+ progress.direct++;
169
+ actual = await journal.readAttempt(input);
170
+ } else {
171
+ const input = {
172
+ attemptId: reservation.attemptId,
173
+ sequence: 1 as const,
174
+ };
175
+ direct = await ctx.runQuery(refs.queries.readStageEvent, {
176
+ ...args,
177
+ ...input,
178
+ });
179
+ const { reservation: _reservation, ...descriptor } = committed;
180
+ expect(direct).toEqual({ ...descriptor, dataJSON: event.json });
181
+ progress.direct++;
182
+ actual = await journal.readStageEvent(input);
183
+ }
184
+ progress.target++;
185
+ expect(getConvexSize(actual)).toBeLessThanOrEqual(VALUE_LIMIT);
186
+ expect(actual).toEqual(direct);
187
+ return null;
188
+ },
189
+ }),
190
+ };
191
+ const t = convexTest(defineSchema({}), {
192
+ "./_generated/api.ts": async () => ({}),
193
+ "./adapterMethods.ts": async () => host,
194
+ });
195
+ t.registerComponent("betterStripe", schema, {
196
+ ...modules,
197
+ "./component/adapterMethodsInspection.ts": async () => inspection,
198
+ });
199
+ const physical = async (): Promise<Physical> =>
200
+ t.query(
201
+ inspectionRefs.betterStripe.adapterMethodsInspection.physical,
202
+ {},
203
+ );
204
+ expect(await physical()).toEqual({
205
+ operations: [],
206
+ attempts: [],
207
+ events: [],
208
+ payloads: [],
209
+ });
210
+ const created = await t.mutation(refs.mutations.createAuthorizedOperation, {
211
+ authorizationScope: h.record.authorization.scope,
212
+ authorizationRevision: h.record.authorization.revision,
213
+ logicalOperationId: h.record.logicalOperationId,
214
+ recordJSON: h.recordJSON,
215
+ });
216
+ assert(created.status === "created");
217
+ const args = { operationId: created.operationId };
218
+ const acquired = await t.mutation(refs.mutations.reserveAttempt, {
219
+ ...args,
220
+ expectedRevision: 0,
221
+ stage: "attach",
222
+ expectedRequestBinding: h.record.requestBinding,
223
+ recordJSON: h.recordJSON,
224
+ });
225
+ assert(acquired.disposition === "acquired");
226
+ const reservation = acquired.reservation;
227
+ const bound = await t.mutation(refs.mutations.bindInitialBasis, {
228
+ ...args,
229
+ attemptId: reservation.attemptId,
230
+ policyJSON: canonical(h.record.timingPolicy),
231
+ basisJSON: canonical(basis),
232
+ });
233
+ const committed = await t.mutation(refs.mutations.appendStageEvent, {
234
+ reservation,
235
+ expectedSequence: 0,
236
+ event: { sequence: 1, binding: event.binding, dataJSON: event.json },
237
+ });
238
+ expect(committed.reservation).toEqual(reservation);
239
+ const before = await physical();
240
+ expect(before.operations[0].initialBasis).toEqual(bound.initialBasis);
241
+ expect(before.attempts[0].lastSequence).toBe(1);
242
+ expect(before.events).toHaveLength(1);
243
+ expect(before.payloads).toHaveLength(2);
244
+ const source = before.payloads.find(
245
+ (row) => row._id === reservation.payloadId,
246
+ );
247
+ assert(source);
248
+ expect(source.json).toBe(h.recordJSON);
249
+ expect(source.owner).toEqual({ kind: "operation", ...args });
250
+ for (const rows of Object.values(before))
251
+ for (const row of rows)
252
+ expect(getDocumentSize(row)).toBeLessThanOrEqual(VALUE_LIMIT);
253
+ let failed = false;
254
+ try {
255
+ await t.action(call, args);
256
+ expect(progress).toEqual({ direct: 1, captured: 1, target: 1 });
257
+ } catch (error) {
258
+ failed = true;
259
+ throw error;
260
+ } finally {
261
+ try {
262
+ expect(await physical()).toEqual(before);
263
+ expect(h.fetchCalls()).toBe(0);
264
+ console.info(
265
+ "ADAPTER_METHOD_SETTLEMENT",
266
+ JSON.stringify({
267
+ method,
268
+ ...progress,
269
+ physicalEqual: true,
270
+ fetchCalls: 0,
271
+ }),
272
+ );
273
+ } catch (error) {
274
+ if (!failed) throw error;
275
+ console.info("ADAPTER_METHOD_INSPECTION_FAILED");
276
+ }
277
+ }
278
+ },
279
+ );
280
+
281
+ it.each(identities)(
282
+ "ADAPTER-IDENTITY changed %s refuses before RPC",
283
+ async (identity) => {
284
+ const h = await codecFixture();
285
+ let refused = 0;
286
+ const host = {
287
+ run: actionGeneric({
288
+ args: { operationId: v.string() },
289
+ handler: async (ctx, args) => {
290
+ const direct = await ctx.runQuery(
291
+ refs.queries.loadAuthorizedOperation,
292
+ args,
293
+ );
294
+ expect(direct?.recordJSON).toBe(h.recordJSON);
295
+ const journal = await createActionOperationJournal(
296
+ ctx,
297
+ components.betterStripe,
298
+ args.operationId,
299
+ );
300
+ const receiver = identity === "getFunctionMetadata" ? ctx.meta : ctx;
301
+ const original = Object.getOwnPropertyDescriptor(receiver, identity);
302
+ assert(
303
+ original &&
304
+ "value" in original &&
305
+ typeof original.value === "function",
306
+ );
307
+ let replacementCalls = 0;
308
+ Object.defineProperty(receiver, identity, {
309
+ ...original,
310
+ value: () => {
311
+ replacementCalls++;
312
+ throw Error("RETARGETED_METHOD_CALLED");
313
+ },
314
+ });
315
+ try {
316
+ await expect(journal.loadAuthorizedOperation()).rejects.toThrow(
317
+ /^OPERATION_JOURNAL_ACTION_UNBOUND$/,
318
+ );
319
+ refused++;
320
+ expect(replacementCalls).toBe(0);
321
+ } finally {
322
+ Object.defineProperty(receiver, identity, original);
323
+ }
324
+ expect(await journal.loadAuthorizedOperation()).toEqual(direct);
325
+ return null;
326
+ },
327
+ }),
328
+ };
329
+ const t = convexTest(defineSchema({}), {
330
+ "./_generated/api.ts": async () => ({}),
331
+ "./adapterMethods.ts": async () => host,
332
+ });
333
+ t.registerComponent("betterStripe", schema, {
334
+ ...modules,
335
+ "./component/adapterMethodsInspection.ts": async () => inspection,
336
+ });
337
+ const physical = async (): Promise<Physical> =>
338
+ t.query(
339
+ inspectionRefs.betterStripe.adapterMethodsInspection.physical,
340
+ {},
341
+ );
342
+ const created = await t.mutation(refs.mutations.createAuthorizedOperation, {
343
+ authorizationScope: h.record.authorization.scope,
344
+ authorizationRevision: h.record.authorization.revision,
345
+ logicalOperationId: h.record.logicalOperationId,
346
+ recordJSON: h.recordJSON,
347
+ });
348
+ assert(created.status === "created");
349
+ const before = await physical();
350
+ let failed = false;
351
+ try {
352
+ await t.action(call, { operationId: created.operationId });
353
+ expect(refused).toBe(1);
354
+ } catch (error) {
355
+ failed = true;
356
+ throw error;
357
+ } finally {
358
+ try {
359
+ expect(await physical()).toEqual(before);
360
+ expect(h.fetchCalls()).toBe(0);
361
+ } catch (error) {
362
+ if (!failed) throw error;
363
+ console.info("ADAPTER_IDENTITY_INSPECTION_FAILED");
364
+ }
365
+ }
366
+ },
367
+ );
368
+
369
+ it("ADAPTER-WRITE creates reservation, basis and event through one actual Action", async () => {
370
+ const event = await canonicalJournalEvent(
371
+ 1,
372
+ canonical({ future: ["whole", null] }),
373
+ );
374
+ const h = await codecFixture();
375
+ const progress = { direct: 0, reserve: 0, bind: 0, append: 0 };
376
+ const host = {
377
+ run: actionGeneric({
378
+ args: { operationId: v.string() },
379
+ handler: async (ctx, args) => {
380
+ const direct = await ctx.runQuery(
381
+ refs.queries.loadAuthorizedOperation,
382
+ args,
383
+ );
384
+ expect(direct).toEqual({
385
+ recordVersion: 2,
386
+ ...args,
387
+ recordJSON: h.recordJSON,
388
+ revision: 0,
389
+ activeAttempt: null,
390
+ initialBasis: null,
391
+ });
392
+ progress.direct++;
393
+ const journal = await createActionOperationJournal(
394
+ ctx,
395
+ components.betterStripe,
396
+ args.operationId,
397
+ );
398
+ const acquired = await journal.reserveAttempt({
399
+ expectedRevision: 0,
400
+ stage: "attach",
401
+ expectedRequestBinding: h.record.requestBinding,
402
+ recordJSON: h.recordJSON,
403
+ });
404
+ progress.reserve++;
405
+ assert(acquired !== null && acquired.disposition === "acquired");
406
+ expect(acquired.reservation.recordJSON).toBe(h.recordJSON);
407
+ expect(acquired.reservation.operationId).toBe(args.operationId);
408
+ const bound = await journal.bindInitialBasis({
409
+ attemptId: acquired.reservation.attemptId,
410
+ policyJSON: canonical(h.record.timingPolicy),
411
+ basisJSON: canonical(basis),
412
+ });
413
+ progress.bind++;
414
+ assert(bound !== null);
415
+ expect(bound).toEqual({
416
+ status: "bound",
417
+ ...args,
418
+ initialBasis: {
419
+ version: 1,
420
+ attemptId: acquired.reservation.attemptId,
421
+ sourcePayloadId: acquired.reservation.payloadId,
422
+ stage: "attach",
423
+ policyJSON: canonical(h.record.timingPolicy),
424
+ basisJSON: canonical(basis),
425
+ },
426
+ });
427
+ const committed = await journal.appendStageEvent({
428
+ reservation: acquired.reservation,
429
+ expectedSequence: 0,
430
+ event: { sequence: 1, binding: event.binding, dataJSON: event.json },
431
+ });
432
+ progress.append++;
433
+ assert(committed !== null);
434
+ expect(committed.reservation).toEqual(acquired.reservation);
435
+ expect(committed).toMatchObject({
436
+ operationId: args.operationId,
437
+ attemptId: acquired.reservation.attemptId,
438
+ sourcePayloadId: acquired.reservation.payloadId,
439
+ stage: "attach",
440
+ sequence: 1,
441
+ binding: event.binding,
442
+ });
443
+ const loaded = await journal.loadAuthorizedOperation();
444
+ assert(loaded && "recordVersion" in loaded);
445
+ const { recordJSON: _recordJSON, ...summary } = acquired.reservation;
446
+ expect(loaded).toEqual({
447
+ recordVersion: 2,
448
+ ...args,
449
+ recordJSON: h.recordJSON,
450
+ revision: 1,
451
+ activeAttempt: summary,
452
+ initialBasis: bound.initialBasis,
453
+ });
454
+ return null;
455
+ },
456
+ }),
457
+ };
458
+ const t = convexTest(defineSchema({}), {
459
+ "./_generated/api.ts": async () => ({}),
460
+ "./adapterMethods.ts": async () => host,
461
+ });
462
+ t.registerComponent("betterStripe", schema, {
463
+ ...modules,
464
+ "./component/adapterMethodsInspection.ts": async () => inspection,
465
+ });
466
+ const physical = async (): Promise<Physical> =>
467
+ t.query(inspectionRefs.betterStripe.adapterMethodsInspection.physical, {});
468
+ const created = await t.mutation(refs.mutations.createAuthorizedOperation, {
469
+ authorizationScope: h.record.authorization.scope,
470
+ authorizationRevision: h.record.authorization.revision,
471
+ logicalOperationId: h.record.logicalOperationId,
472
+ recordJSON: h.recordJSON,
473
+ });
474
+ assert(created.status === "created");
475
+ const before = await physical();
476
+ let stable = before;
477
+ let failed = false;
478
+ try {
479
+ await t.action(call, { operationId: created.operationId });
480
+ expect(progress).toEqual({ direct: 1, reserve: 1, bind: 1, append: 1 });
481
+ const after = await physical();
482
+ expect({
483
+ operations: after.operations.length,
484
+ attempts: after.attempts.length,
485
+ events: after.events.length,
486
+ payloads: after.payloads.length,
487
+ }).toEqual({ operations: 1, attempts: 1, events: 1, payloads: 2 });
488
+ expect(after.operations[0]).toMatchObject({
489
+ _id: created.operationId,
490
+ state: "RESERVED",
491
+ revision: 1,
492
+ });
493
+ expect(after.attempts[0].lastSequence).toBe(1);
494
+ expect(
495
+ after.payloads.find((row) => row._id === before.payloads[0]._id),
496
+ ).toEqual(before.payloads[0]);
497
+ const added = after.payloads.filter(
498
+ (row) => row._id !== before.payloads[0]._id,
499
+ );
500
+ expect(added).toHaveLength(1);
501
+ expect(added[0]).toEqual({
502
+ _id: after.events[0].payloadId,
503
+ _creationTime: added[0]._creationTime,
504
+ codecVersion: 1,
505
+ json: event.json,
506
+ owner: {
507
+ kind: "event",
508
+ operationId: created.operationId,
509
+ attemptId: after.attempts[0]._id,
510
+ stage: "attach",
511
+ sequence: 1,
512
+ },
513
+ });
514
+ for (const rows of Object.values(after))
515
+ for (const row of rows)
516
+ expect(getDocumentSize(row)).toBeLessThanOrEqual(VALUE_LIMIT);
517
+ stable = after;
518
+ } catch (error) {
519
+ failed = true;
520
+ throw error;
521
+ } finally {
522
+ try {
523
+ expect(await physical()).toEqual(stable);
524
+ expect(h.fetchCalls()).toBe(0);
525
+ console.info(
526
+ "ADAPTER_WRITE_SETTLEMENT",
527
+ JSON.stringify({ ...progress, physicalEqual: true, fetchCalls: 0 }),
528
+ );
529
+ } catch (error) {
530
+ if (!failed) throw error;
531
+ console.info("ADAPTER_WRITE_INSPECTION_FAILED");
532
+ }
533
+ }
534
+ });