Line data Source code
1 : /**
2 : * The tab-local pointer to an operation this tab is observing, so a reload
3 : * reattaches to the same `billing_op_id` instead of starting a replacement
4 : * charge. The host supplies the storage (origin-scoped `sessionStorage` in a
5 : * browser); the SDK owns the key, the shape, and the rule for when the
6 : * pointer may go.
7 : *
8 : * The pointer is keyed by scope, so a workspace switch neither reads nor
9 : * clears another workspace's operation, and switching back finds it again.
10 : */
11 : import { z } from 'zod'
12 :
13 : import type { BillingScope } from './billingScope'
14 : import type { BillingOperationState } from './operationState'
15 :
16 : export interface BillingOperationPointerStorage {
17 : getItem: (key: string) => string | null
18 : setItem: (key: string, value: string) => void
19 : removeItem: (key: string) => void
20 : }
21 :
22 2356 : const POINTER_KEY_PREFIX = 'comfy:billing:operation'
23 :
24 : export const OPERATION_POINTER_MAX_AGE_MS = 24 * 60 * 60_000
25 :
26 2356 : const PointerSchema = z.object({
27 : operationId: z.string().min(1),
28 : kind: z.enum(['subscription', 'topup', 'cancel']),
29 : presentation: z.enum(['embedded', 'hosted']),
30 : attemptStartedAt: z.number().finite(),
31 : /** This tab issued the operation and has not yet seen it succeed. */
32 : awaited: z.literal(true).optional(),
33 : /** The end this tab saw it reach, kept only by a store that retains settled pointers. */
34 : settled: z.enum(['succeeded', 'reconciliation_needed']).optional(),
35 : /** The hosted step this page redirected to; the page it returns to reports the return. */
36 : redirect: z
37 : .object({
38 : destination: z.enum(['stripe', 'billing_web']),
39 : step: z.enum([
40 : 'authentication',
41 : 'payment_method',
42 : 'invoice_payment',
43 : 'checkout'
44 : ]),
45 : method_kind: z.enum(['card', 'alipay', 'other']).optional()
46 : })
47 : .optional()
48 : })
49 :
50 : export type BillingOperationPointer = z.infer<typeof PointerSchema>
51 :
52 : type SettledPhase = NonNullable<BillingOperationPointer['settled']>
53 :
54 0 : export function operationPointerKey(scope: BillingScope): string {
55 0 : return `${POINTER_KEY_PREFIX}:${scope.userId}:${scope.workspaceId}`
56 : }
57 :
58 : export interface OperationPointerStore {
59 : read: (scope: BillingScope) => BillingOperationPointer | undefined
60 : write: (scope: BillingScope, pointer: BillingOperationPointer) => void
61 : /** Clears only when the stored pointer names `operationId`, or unconditionally without one. */
62 : clear: (scope: BillingScope, operationId?: string) => void
63 : /**
64 : * What the operation's phase does to the pointer naming it. A client-side
65 : * timeout is this tab giving up, not the server finishing: an operation
66 : * awaiting bank authentication stays pending for hours, so the pointer
67 : * outlives it. A superseded operation belongs to a scope this tab left, and
68 : * its pointer waits under that scope's key for a return. A failure clears
69 : * it, so a reload offers a fresh attempt. A success, or an operation the
70 : * server parked for reconciliation, clears it too, unless the store retains
71 : * settled pointers.
72 : */
73 : settle: (state: BillingOperationState) => void
74 : }
75 :
76 : export interface OperationPointerStoreOptions {
77 : /**
78 : * Keep a settled pointer, marked with how it ended, so a page that is the
79 : * checkout itself can read it back after a reload.
80 : */
81 : readonly retainSettled?: boolean
82 : }
83 :
84 : /** Storage that throws (private mode, quota) reads as empty and writes as a no-op. */
85 0 : function attempt<T>(read: () => T, fallback: T): T {
86 0 : try {
87 0 : return read()
88 : } catch {
89 0 : return fallback
90 : }
91 : }
92 :
93 0 : function decodePointer(
94 : raw: string | null,
95 : now: number
96 : ): BillingOperationPointer | undefined {
97 0 : if (raw === null) return undefined
98 0 : const parsed = PointerSchema.safeParse(attempt(() => JSON.parse(raw), null))
99 0 : if (!parsed.success) return undefined
100 0 : const age = now - parsed.data.attemptStartedAt
101 0 : return age >= 0 && age <= OPERATION_POINTER_MAX_AGE_MS
102 : ? parsed.data
103 : : undefined
104 : }
105 :
106 : /** A success is no longer awaited; an operation still being reconciled is. */
107 0 : function settledPointer(
108 : pointer: BillingOperationPointer,
109 : phase: SettledPhase
110 : ): BillingOperationPointer {
111 0 : if (phase === 'reconciliation_needed') return { ...pointer, settled: phase }
112 0 : const { awaited: _seen, ...rest } = pointer
113 0 : return { ...rest, settled: phase }
114 : }
115 :
116 0 : export function createOperationPointerStore(
117 : storage: BillingOperationPointerStorage,
118 : now: () => number = Date.now,
119 : { retainSettled = false }: OperationPointerStoreOptions = {}
120 : ): OperationPointerStore {
121 0 : const read = (scope: BillingScope) => {
122 0 : const key = operationPointerKey(scope)
123 0 : const pointer = decodePointer(
124 : attempt(() => storage.getItem(key), null),
125 : now()
126 : )
127 0 : if (pointer === undefined) attempt(() => storage.removeItem(key), undefined)
128 0 : return pointer
129 : }
130 :
131 0 : const write = (scope: BillingScope, pointer: BillingOperationPointer) =>
132 : attempt(
133 : () =>
134 : storage.setItem(operationPointerKey(scope), JSON.stringify(pointer)),
135 : undefined
136 : )
137 :
138 0 : const clear = (scope: BillingScope, operationId?: string) => {
139 0 : if (operationId !== undefined && read(scope)?.operationId !== operationId) {
140 0 : return
141 : }
142 0 : attempt(() => storage.removeItem(operationPointerKey(scope)), undefined)
143 : }
144 :
145 0 : const retain = (state: BillingOperationState, phase: SettledPhase) => {
146 0 : const pointer = read(state.scope)
147 0 : if (pointer?.operationId !== state.id) return
148 0 : write(state.scope, settledPointer(pointer, phase))
149 : }
150 :
151 0 : const settle = (state: BillingOperationState) => {
152 0 : switch (state.phase) {
153 : case 'pending':
154 : case 'timed_out':
155 : case 'superseded':
156 0 : return
157 : case 'failed':
158 0 : clear(state.scope, state.id)
159 0 : return
160 : case 'succeeded':
161 : case 'reconciliation_needed':
162 0 : if (retainSettled) retain(state, state.phase)
163 0 : else clear(state.scope, state.id)
164 : }
165 : }
166 :
167 0 : return { read, write, clear, settle }
168 : }
169 :
170 : /** A store for hosts without tab-local storage: nothing is ever recovered. */
171 2356 : export const NO_POINTER_STORE: OperationPointerStore = {
172 : read: () => undefined,
173 : write: () => {},
174 : clear: () => {},
175 : settle: () => {}
176 : }
|