@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,531 @@
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
+ createActionOperationJournal,
7
+ createClassActionOperationJournal,
8
+ consumeClassReservation,
9
+ } from "../operationJournal.js";
10
+ import { convexTest } from "convex-test";
11
+ import {
12
+ actionGeneric,
13
+ componentsGeneric,
14
+ defineSchema,
15
+ makeFunctionReference,
16
+ type FunctionReturnType,
17
+ } from "convex/server";
18
+ import { getConvexSize, getDocumentSize, v } from "convex/values";
19
+ import { afterEach, expect, it, vi } from "vitest";
20
+ import { modules, schema } from "../../../../../test.js";
21
+ import { query } from "../../../../../component/_generated/server.js";
22
+ import type { Doc } from "../../../../../component/_generated/dataModel.js";
23
+ import {
24
+ canonical,
25
+ codecFixture,
26
+ VALUE_LIMIT,
27
+ } from "../../../../../component/renewalOperations/timingPolicy.fixtures.js";
28
+
29
+ const refs = components.betterStripe.renewalOperations;
30
+ const nested = componentsGeneric();
31
+ const cases = [
32
+ "once",
33
+ "copies",
34
+ "duplicate",
35
+ "foreign-op",
36
+ "foreign-root",
37
+ "invalid-expected",
38
+ "extra-arity",
39
+ "generic-data",
40
+ "conflict",
41
+ "rejected",
42
+ "retarget",
43
+ ] as const;
44
+ type Mode = (typeof cases)[number];
45
+ type Reserved = FunctionReturnType<typeof refs.mutations.reserveAttempt>;
46
+ const route = makeFunctionReference<
47
+ "action",
48
+ { operationId: string; foreignId: string; mode: Mode },
49
+ null
50
+ >("winningCall:run");
51
+ type Physical = {
52
+ operations: Doc<"renewalOperations">[];
53
+ attempts: Doc<"renewalOperationAttempts">[];
54
+ events: Doc<"renewalOperationEvents">[];
55
+ payloads: Doc<"renewalOperationPayloads">[];
56
+ };
57
+ const inspection = {
58
+ physical: query({
59
+ args: {},
60
+ handler: async (ctx): Promise<Physical> => ({
61
+ operations: await ctx.db.query("renewalOperations").take(4),
62
+ attempts: await ctx.db.query("renewalOperationAttempts").take(4),
63
+ events: await ctx.db.query("renewalOperationEvents").take(4),
64
+ payloads: await ctx.db.query("renewalOperationPayloads").take(5),
65
+ }),
66
+ }),
67
+ };
68
+ const callError = /^CLASS_JOURNAL_CALL_UNBOUND$/;
69
+ afterEach(() => vi.unstubAllGlobals());
70
+
71
+ it.each(cases)(
72
+ "WINNING-CALL %s preserves actual-call identity and one-use ordering",
73
+ async (mode) => {
74
+ const h = await codecFixture();
75
+ const foreignLogical = h.record.logicalOperationId + "-winning-foreign";
76
+ const foreignJSON = canonical({
77
+ ...h.record,
78
+ logicalOperationId: foreignLogical,
79
+ });
80
+ const roots = [
81
+ new BetterStripe(components.betterStripe, {
82
+ STRIPE_SECRET_KEY: "sk_test_invalid_winning_fixture",
83
+ }),
84
+ new BetterStripe(components.betterStripe, {
85
+ STRIPE_SECRET_KEY: "sk_test_invalid_winning_fixture",
86
+ }),
87
+ ];
88
+ expect(roots[0]).not.toBe(roots[1]);
89
+ let selectorReads = 0;
90
+ const descriptors = roots.map((sdk) => {
91
+ const descriptor = Object.getOwnPropertyDescriptor(sdk, "_apiKey");
92
+ assert(descriptor && "value" in descriptor && descriptor.configurable);
93
+ Object.defineProperty(sdk, "_apiKey", {
94
+ configurable: true,
95
+ enumerable: descriptor.enumerable,
96
+ get() {
97
+ selectorReads++;
98
+ throw Error("WINNING_SELECTOR_TOUCHED");
99
+ },
100
+ });
101
+ return descriptor;
102
+ });
103
+ try {
104
+ let stable: Physical | null = null;
105
+ const progress = { entry: 0, binding: 0, reserve: 0, consume: 0 };
106
+ const host = {
107
+ run: actionGeneric({
108
+ args: {
109
+ operationId: v.string(),
110
+ foreignId: v.string(),
111
+ mode: v.string(),
112
+ },
113
+ handler: async (ctx, args): Promise<null> => {
114
+ progress.entry++;
115
+ expect(args.mode).toBe(mode);
116
+ expect(await ctx.meta.getFunctionMetadata()).toEqual({
117
+ name: "winningCall:run",
118
+ componentPath: "",
119
+ type: "action",
120
+ visibility: "public",
121
+ });
122
+ const input = {
123
+ expectedRevision: 0,
124
+ stage: "attach" as const,
125
+ expectedRequestBinding: h.record.requestBinding,
126
+ recordJSON: h.recordJSON,
127
+ };
128
+ expect(getConvexSize(input)).toBeLessThanOrEqual(VALUE_LIMIT);
129
+ const direct = await ctx.runQuery(
130
+ refs.queries.loadAuthorizedOperation,
131
+ { operationId: args.operationId },
132
+ );
133
+ expect(direct).toEqual({
134
+ recordVersion: 2,
135
+ operationId: args.operationId,
136
+ recordJSON: h.recordJSON,
137
+ revision: 0,
138
+ activeAttempt: null,
139
+ initialBasis: null,
140
+ });
141
+ expect(
142
+ await ctx.runQuery(
143
+ nested.betterStripe.winningInspection.physical,
144
+ {},
145
+ ),
146
+ ).toEqual(before);
147
+ await expect(
148
+ captureMaintainedActionSelection(roots[0], {
149
+ actualActionCtx: ctx,
150
+ operationId: args.operationId,
151
+ }),
152
+ ).rejects.toThrow(/^CLASS_ACTION_PROFILE_UNBOUND$/);
153
+ const journal = await createClassActionOperationJournal(roots[0], {
154
+ actualActionCtx: ctx,
155
+ operationId: args.operationId,
156
+ });
157
+ expect(await journal.loadAuthorizedOperation()).toEqual(direct);
158
+ progress.binding++;
159
+ async function observe(reply: Reserved) {
160
+ assert(reply.disposition !== "conflict");
161
+ const reservation = reply.reservation;
162
+ expect(reservation.operationId).toBe(args.operationId);
163
+ expect(reservation.recordJSON).toBe(h.recordJSON);
164
+ const manifest = await ctx.runQuery(refs.queries.readAttempt, {
165
+ operationId: args.operationId,
166
+ attemptId: reservation.attemptId,
167
+ });
168
+ expect(manifest).toEqual({ reservation, events: [] });
169
+ const after: Physical = await ctx.runQuery(
170
+ nested.betterStripe.winningInspection.physical,
171
+ {},
172
+ );
173
+ const primary = before.operations.find(
174
+ (row) => row._id === args.operationId,
175
+ );
176
+ assert(primary);
177
+ expect(after.operations).toHaveLength(2);
178
+ expect(
179
+ after.operations.find((row) => row._id === args.operationId),
180
+ ).toEqual({
181
+ ...primary,
182
+ state: "RESERVED",
183
+ revision: 1,
184
+ activeAttemptId: reservation.attemptId,
185
+ });
186
+ expect(
187
+ after.operations.find((row) => row._id === args.foreignId),
188
+ ).toEqual(
189
+ before.operations.find((row) => row._id === args.foreignId),
190
+ );
191
+ expect(after.attempts).toHaveLength(1);
192
+ const {
193
+ attemptId,
194
+ recordJSON: _recordJSON,
195
+ ...fields
196
+ } = reservation;
197
+ expect(after.attempts[0]).toEqual({
198
+ ...fields,
199
+ _id: attemptId,
200
+ _creationTime: after.attempts[0]._creationTime,
201
+ lastSequence: 0,
202
+ });
203
+ expect(after.events).toEqual([]);
204
+ expect(after.payloads).toEqual(before.payloads);
205
+ expect(getConvexSize(reply)).toBeLessThanOrEqual(VALUE_LIMIT);
206
+ stable = after;
207
+ }
208
+ if (mode === "generic-data") {
209
+ const data = await createActionOperationJournal(
210
+ ctx,
211
+ components.betterStripe,
212
+ args.operationId,
213
+ );
214
+ expect(
215
+ Object.prototype.hasOwnProperty.call(
216
+ data,
217
+ "reserveFreshAttempt",
218
+ ),
219
+ ).toBe(false);
220
+ const raw = await data.reserveAttempt(input);
221
+ assert(raw.disposition === "acquired");
222
+ await observe(raw);
223
+ const existing = await journal.reserveFreshAttempt(input);
224
+ progress.reserve++;
225
+ expect(existing).toEqual({
226
+ result: {
227
+ disposition: "existing",
228
+ committedRevision: 1,
229
+ reservation: raw.reservation,
230
+ },
231
+ call: null,
232
+ });
233
+ expect(() => consumeClassReservation(raw, journal)).toThrow(
234
+ callError,
235
+ );
236
+ expect(() =>
237
+ consumeClassReservation(raw.reservation, journal),
238
+ ).toThrow(callError);
239
+ return null;
240
+ }
241
+ if (mode === "conflict") {
242
+ const fresh = await journal.reserveFreshAttempt({
243
+ ...input,
244
+ expectedRequestBinding: "different-request-binding",
245
+ });
246
+ progress.reserve++;
247
+ expect(fresh).toEqual({
248
+ result: { disposition: "conflict", reason: "identity_changed" },
249
+ call: null,
250
+ });
251
+ expect(
252
+ await ctx.runQuery(
253
+ nested.betterStripe.winningInspection.physical,
254
+ {},
255
+ ),
256
+ ).toEqual(before);
257
+ return null;
258
+ }
259
+ if (mode === "rejected") {
260
+ await expect(
261
+ journal.reserveFreshAttempt({ ...input, recordJSON: "{}" }),
262
+ ).rejects.toThrow(/^RENEWAL_JOURNAL_JSON_STOP$/);
263
+ progress.reserve++;
264
+ expect(
265
+ await ctx.runQuery(
266
+ nested.betterStripe.winningInspection.physical,
267
+ {},
268
+ ),
269
+ ).toEqual(before);
270
+ return null;
271
+ }
272
+ const fresh = await journal.reserveFreshAttempt(input);
273
+ progress.reserve++;
274
+ assert(fresh.result.disposition === "acquired");
275
+ await observe(fresh.result);
276
+ // The exact real CAS/data/physical transition precedes missing-handle RED.
277
+ expect(fresh.call).not.toBeNull();
278
+ assert(fresh.call !== null);
279
+ const winningCall = fresh.call;
280
+ expect(Object.isFrozen(winningCall)).toBe(true);
281
+ const reservation = fresh.result.reservation;
282
+ if (mode === "foreign-op" || mode === "foreign-root") {
283
+ const foreign = await createClassActionOperationJournal(
284
+ mode === "foreign-root" ? roots[1] : roots[0],
285
+ {
286
+ actualActionCtx: ctx,
287
+ operationId:
288
+ mode === "foreign-root" ? args.operationId : args.foreignId,
289
+ },
290
+ );
291
+ expect(() =>
292
+ consumeClassReservation(winningCall, foreign),
293
+ ).toThrow(callError);
294
+ expect(() =>
295
+ consumeClassReservation(winningCall, journal),
296
+ ).toThrow(callError);
297
+ } else if (mode === "invalid-expected") {
298
+ let traps = 0;
299
+ const invalid = Proxy.revocable(journal, {
300
+ get() {
301
+ traps++;
302
+ throw Error("EXPECTED_REFLECTED");
303
+ },
304
+ });
305
+ invalid.revoke();
306
+ expect(() =>
307
+ consumeClassReservation(winningCall, invalid.proxy),
308
+ ).toThrow(callError);
309
+ expect(() =>
310
+ consumeClassReservation(winningCall, journal),
311
+ ).toThrow(callError);
312
+ expect(traps).toBe(0);
313
+ } else if (mode === "extra-arity") {
314
+ expect(() =>
315
+ Reflect.apply(consumeClassReservation, undefined, [
316
+ winningCall,
317
+ journal,
318
+ {},
319
+ ]),
320
+ ).toThrow(callError);
321
+ expect(() =>
322
+ consumeClassReservation(winningCall, journal),
323
+ ).toThrow(callError);
324
+ } else if (mode === "retarget") {
325
+ const descriptor = Object.getOwnPropertyDescriptor(
326
+ ctx,
327
+ "runQuery",
328
+ );
329
+ assert(descriptor && "value" in descriptor);
330
+ let invoked = 0;
331
+ Object.defineProperty(ctx, "runQuery", {
332
+ ...descriptor,
333
+ value: () => {
334
+ invoked++;
335
+ throw Error("RETARGETED_RPC_CALLED");
336
+ },
337
+ });
338
+ try {
339
+ expect(() =>
340
+ consumeClassReservation(winningCall, journal),
341
+ ).toThrow(callError);
342
+ } finally {
343
+ Object.defineProperty(ctx, "runQuery", descriptor);
344
+ }
345
+ expect(invoked).toBe(0);
346
+ expect(() =>
347
+ consumeClassReservation(winningCall, journal),
348
+ ).toThrow(callError);
349
+ await expect(journal.loadAuthorizedOperation()).rejects.toThrow(
350
+ /^CLASS_ACTION_JOURNAL_UNBOUND$/,
351
+ );
352
+ } else {
353
+ if (mode === "copies") {
354
+ let traps = 0;
355
+ const proxy = new Proxy(winningCall, {
356
+ get() {
357
+ traps++;
358
+ throw Error("CALL_REFLECTED");
359
+ },
360
+ getPrototypeOf() {
361
+ traps++;
362
+ throw Error("CALL_PROTO_REFLECTED");
363
+ },
364
+ });
365
+ for (const invalid of [
366
+ fresh.result,
367
+ reservation,
368
+ { ...winningCall },
369
+ JSON.parse(JSON.stringify(winningCall)),
370
+ Object.create(Object.getPrototypeOf(winningCall)),
371
+ proxy,
372
+ ])
373
+ expect(() =>
374
+ consumeClassReservation(invalid, journal),
375
+ ).toThrow(callError);
376
+ expect(traps).toBe(0);
377
+ }
378
+ if (mode === "duplicate") {
379
+ const duplicate = await journal.reserveFreshAttempt(input);
380
+ progress.reserve++;
381
+ expect(duplicate).toEqual({
382
+ result: {
383
+ disposition: "existing",
384
+ committedRevision: 1,
385
+ reservation,
386
+ },
387
+ call: null,
388
+ });
389
+ const queried = await journal.readAttempt({
390
+ attemptId: reservation.attemptId,
391
+ });
392
+ assert(queried);
393
+ expect(() =>
394
+ consumeClassReservation(queried.reservation, journal),
395
+ ).toThrow(callError);
396
+ }
397
+ const consumed = consumeClassReservation(winningCall, journal);
398
+ progress.consume++;
399
+ expect(consumed.reservation).toBe(reservation);
400
+ expect(typeof consumed.tag).toBe("object");
401
+ expect(Object.isFrozen(consumed)).toBe(true);
402
+ expect(() =>
403
+ consumeClassReservation(winningCall, journal),
404
+ ).toThrow(callError);
405
+ }
406
+ expect(selectorReads).toBe(0);
407
+ await expect(
408
+ captureMaintainedActionSelection(roots[0], {
409
+ actualActionCtx: ctx,
410
+ operationId: args.operationId,
411
+ }),
412
+ ).rejects.toThrow(/^CLASS_ACTION_PROFILE_UNBOUND$/);
413
+ return null;
414
+ },
415
+ }),
416
+ };
417
+ const t = convexTest(defineSchema({}), {
418
+ "./_generated/api.ts": async () => ({}),
419
+ "./winningCall.ts": async () => host,
420
+ });
421
+ expect(
422
+ Object.prototype.hasOwnProperty.call(
423
+ modules,
424
+ "./component/winningInspection.ts",
425
+ ),
426
+ ).toBe(false);
427
+ t.registerComponent("betterStripe", schema, {
428
+ ...modules,
429
+ "./component/winningInspection.ts": async () => inspection,
430
+ });
431
+ const physical = async (): Promise<Physical> =>
432
+ t.query(nested.betterStripe.winningInspection.physical, {});
433
+ expect(await physical()).toEqual({
434
+ operations: [],
435
+ attempts: [],
436
+ events: [],
437
+ payloads: [],
438
+ });
439
+ const create = {
440
+ authorizationScope: h.record.authorization.scope,
441
+ authorizationRevision: h.record.authorization.revision,
442
+ logicalOperationId: h.record.logicalOperationId,
443
+ recordJSON: h.recordJSON,
444
+ };
445
+ const primary = await t.mutation(
446
+ refs.mutations.createAuthorizedOperation,
447
+ create,
448
+ );
449
+ const foreign = await t.mutation(
450
+ refs.mutations.createAuthorizedOperation,
451
+ {
452
+ ...create,
453
+ logicalOperationId: foreignLogical,
454
+ recordJSON: foreignJSON,
455
+ },
456
+ );
457
+ assert(primary.status === "created" && foreign.status === "created");
458
+ const before = await physical();
459
+ expect(before.operations).toHaveLength(2);
460
+ expect(before.attempts).toEqual([]);
461
+ expect(before.events).toEqual([]);
462
+ expect(before.payloads).toHaveLength(2);
463
+ for (const operation of before.operations) {
464
+ const recordJSON =
465
+ operation._id === primary.operationId ? h.recordJSON : foreignJSON;
466
+ expect(
467
+ await t.query(refs.queries.loadAuthorizedOperation, {
468
+ operationId: operation._id,
469
+ }),
470
+ ).toEqual({
471
+ recordVersion: 2,
472
+ operationId: operation._id,
473
+ recordJSON,
474
+ revision: 0,
475
+ activeAttempt: null,
476
+ initialBasis: null,
477
+ });
478
+ const payload = before.payloads.find(
479
+ (row) => row._id === operation.payloadId,
480
+ );
481
+ assert(payload);
482
+ expect(payload.json).toBe(recordJSON);
483
+ expect(payload.owner).toEqual({
484
+ kind: "operation",
485
+ operationId: operation._id,
486
+ });
487
+ }
488
+ stable = before;
489
+ let failed = false;
490
+ try {
491
+ await t.action(route, {
492
+ operationId: primary.operationId,
493
+ foreignId: foreign.operationId,
494
+ mode,
495
+ });
496
+ expect(progress.entry).toBe(1);
497
+ expect(progress.binding).toBe(1);
498
+ } catch (error) {
499
+ failed = true;
500
+ throw error;
501
+ } finally {
502
+ try {
503
+ const after = await physical();
504
+ expect(after).toEqual(stable);
505
+ for (const rows of Object.values(after))
506
+ for (const row of rows)
507
+ expect(getDocumentSize(row)).toBeLessThanOrEqual(VALUE_LIMIT);
508
+ expect(selectorReads).toBe(0);
509
+ expect(h.fetchCalls()).toBe(0);
510
+ console.info(
511
+ "WINNING_CALL_SETTLEMENT",
512
+ JSON.stringify({
513
+ mode,
514
+ ...progress,
515
+ physicalEqual: true,
516
+ selectorReads,
517
+ fetchCalls: 0,
518
+ }),
519
+ );
520
+ } catch (error) {
521
+ if (!failed) throw error;
522
+ console.info("WINNING_CALL_INSPECTION_FAILED");
523
+ }
524
+ }
525
+ } finally {
526
+ roots.forEach((sdk, index) =>
527
+ Object.defineProperty(sdk, "_apiKey", descriptors[index]),
528
+ );
529
+ }
530
+ },
531
+ );