Line data Source code
1 : /**
2 : * The operation lifecycle every billing command sits on: adopt a
3 : * `billing_op_id`, observe it to a terminal state, and reattach to it after a
4 : * reload, a focus, or a return to the workspace — without ever creating a
5 : * replacement operation. Commands issue the request; this owns everything
6 : * that happens to the id afterwards.
7 : *
8 : * Framework-free by construction. Nothing here opens a URL, drives a
9 : * payment-provider challenge, or listens to a document: a host renders the
10 : * state (`actionUrl`, `challenge`), performs those effects itself, and
11 : * reports back through `reportChallenge*` and `wake`.
12 : *
13 : * Behavior is ported from the cloud app's `billingOperationStore` — the
14 : * cadence, the budgets, the parked-on-customer rules, the challenge echo
15 : * suppression — and from the pending-checkout pointer's terminal rule; the
16 : * wiring onto the scope source, the scope tracker, and the generated
17 : * contract is new.
18 : */
19 :
20 : import {
21 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT,
22 : BILLING_OPERATION_TELEMETRY_EVENT
23 : } from '#/telemetry'
24 : import type {
25 : BillingFailure,
26 : BillingResult,
27 : BillingTransport
28 : } from './billingContracts'
29 : import type {
30 : BillingScope,
31 : BillingScopeContext,
32 : BillingScopeSource
33 : } from './billingScope'
34 : import { createBillingScopeTracker } from './billingScope'
35 : import type {
36 : BillingOperationPointer,
37 : BillingOperationPointerStorage,
38 : OperationPointerStore
39 : } from './operationPointer'
40 : import {
41 : NO_POINTER_STORE,
42 : createOperationPointerStore
43 : } from './operationPointer'
44 : import {
45 : hasExhaustedPollBudget,
46 : isWaitingOnCustomerWithoutAction,
47 : nextPollDelayMs
48 : } from './operationPolicy'
49 : import type {
50 : BillingDeclineReason,
51 : BillingOpStatus,
52 : BillingOperationEvent,
53 : BillingOperationKind,
54 : BillingOperationState,
55 : BillingPresentation,
56 : BillingPresentationState,
57 : HostedBillingDestination,
58 : PendingBillingOperation
59 : } from './operationState'
60 : import {
61 : BillingOpStatusSchema,
62 : isGrantLanding,
63 : isTerminal,
64 : reduceBillingOperation,
65 : validateActionUrl
66 : } from './operationState'
67 : import type { PaymentFrictionSignal } from './paymentFriction'
68 : import type {
69 : CheckoutHostedStep,
70 : CheckoutRedirectNavigation
71 : } from './telemetry/checkoutRedirectEvent'
72 : import type { CheckoutMethodKind } from './telemetry/checkoutJourney'
73 : import { paymentFrictionBetween } from './paymentFriction'
74 : import { selectBillingPresentation } from './presentation'
75 : import { readValidatedBillingResponse } from './sharedRead'
76 : import type { BillingStatusData, BillingStatusReader } from './status'
77 :
78 : /** Settled, but a later read may still change what the operation reports. */
79 0 : function isStillSettling(state: BillingOperationState): boolean {
80 0 : return state.phase === 'reconciliation_needed' || isGrantLanding(state)
81 : }
82 :
83 0 : export function operationRoute(operationId: string): string {
84 0 : return `/billing/ops/${encodeURIComponent(operationId)}`
85 : }
86 :
87 : /** What a command learned from the backend when it issued the operation. */
88 : export interface IssuedBillingOperation {
89 : readonly operationId: string
90 : /** A hosted continuation the response already carried (`payment_method_url`, `action_url`). */
91 : readonly actionUrl?: string
92 : /** An in-page challenge the response already carried. */
93 : readonly clientSecret?: string
94 : }
95 :
96 : export type BillingOperationFailureCategory =
97 : | 'provider_decline'
98 : | 'api_rejected'
99 : | 'poll_timeout'
100 : | 'reconciliation_needed'
101 : | 'stale_operation'
102 :
103 : type HostedStepEventName =
104 : | typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.redirectStarted
105 : | typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned
106 :
107 : type BillingOperationTelemetryEventName = Exclude<
108 : | (typeof BILLING_OPERATION_TELEMETRY_EVENT)[keyof typeof BILLING_OPERATION_TELEMETRY_EVENT]
109 : | (typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT)[keyof typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT],
110 : HostedStepEventName
111 : >
112 :
113 : /** A hosted step this tab handed the customer to. */
114 : interface HostedStepVisit {
115 : readonly destination: HostedBillingDestination
116 : readonly step: CheckoutHostedStep
117 : readonly navigation: CheckoutRedirectNavigation
118 : readonly method_kind?: CheckoutMethodKind
119 : }
120 :
121 : interface BillingOperationTelemetryBase {
122 : readonly billing_op_id: string
123 : readonly operation_type: BillingOperationKind
124 : readonly presentation: BillingPresentation
125 : /** True when this tab reattached to an operation it did not issue. */
126 : readonly resumed: boolean
127 : }
128 :
129 : export type BillingOperationTelemetryEvent = BillingOperationTelemetryBase &
130 : (
131 : | {
132 : readonly name: BillingOperationTelemetryEventName
133 : readonly failure_category?: BillingOperationFailureCategory
134 : readonly decline_reason?: BillingDeclineReason
135 : /** From the attempt's start, so a resumed operation reports its whole life. */
136 : readonly duration_ms?: number
137 : }
138 : | (HostedStepVisit & { readonly name: HostedStepEventName })
139 : )
140 :
141 : export type PresentationSwitchOutcome =
142 : | 'switched'
143 : | 'unchanged'
144 : /** The server has offered no hosted continuation yet. */
145 : | 'no_hosted_url'
146 : /** The host cannot drive a challenge, or none has been issued for this operation. */
147 : | 'embedded_unavailable'
148 : | 'not_pending'
149 : | 'unknown_operation'
150 :
151 : export interface BillingOperationLifecycleOptions {
152 : readonly transport: BillingTransport
153 : /** Where the core learns which user, workspace, and role it runs as. */
154 : readonly scopeSource: BillingScopeSource
155 : /** The Phase 2 status reader; consulted before every start and recovery. */
156 : readonly statusReader: BillingStatusReader
157 : /** Tab-local storage for the operation pointer; absent means nothing survives a reload. */
158 : readonly pointerStorage?: BillingOperationPointerStorage
159 : /**
160 : * Keep the pointer of an operation that succeeded or needs reconciliation,
161 : * for a host whose page is the checkout itself: a revisit reads it back
162 : * through `recover({ includeSettled: true })`. A plain `recover` never
163 : * sees it, so every other caller recovers exactly what it did before.
164 : */
165 : readonly retainSettledPointer?: boolean
166 : /** Whether the host can drive an in-page challenge right now. Absent routes everything hosted. */
167 : readonly embeddedCheckoutAvailable?: () => boolean
168 : /** Which origin serves a hosted page right now. Absent keeps every hosted operation on the provider page. */
169 : readonly hostedDestination?: () => HostedBillingDestination
170 : readonly onTelemetry?: (event: BillingOperationTelemetryEvent) => void
171 : readonly now?: () => number
172 : }
173 :
174 : export interface BillingRecoverOptions {
175 : /**
176 : * Also read back the operation a retained pointer says already settled, so
177 : * the checkout that issued it can show it finished. Only a lifecycle with
178 : * `retainSettledPointer` keeps one.
179 : */
180 : readonly includeSettled?: boolean
181 : }
182 :
183 : export interface BillingOperationLifecycle {
184 : /**
185 : * Runs a command on the lifecycle: single-flight per kind, the backend's
186 : * pending operation adopted instead of a second one issued, and the
187 : * issued id observed from the moment it exists. Resolves once the
188 : * operation is adopted, not once it settles — see `settled`.
189 : */
190 : begin: (
191 : kind: BillingOperationKind,
192 : issue: (
193 : scope: BillingScope
194 : ) => Promise<BillingResult<IssuedBillingOperation>>
195 : ) => Promise<BillingResult<BillingOperationState>>
196 : /**
197 : * Reattaches to whatever this scope is already waiting on: the backend's
198 : * pending operation first, then the tab-local pointer. Resolves undefined
199 : * when there is nothing to recover.
200 : */
201 : recover: (
202 : options?: BillingRecoverOptions
203 : ) => Promise<BillingResult<BillingOperationState | undefined>>
204 : /** The host became visible or focused: poll every pending operation now. */
205 : wake: () => void
206 : /** Moves the operation between presentations under the same id. */
207 : switchPresentation: (
208 : operationId: string,
209 : presentation: BillingPresentation
210 : ) => PresentationSwitchOutcome
211 : /**
212 : * The host opened the operation's hosted step. A redirect is remembered in
213 : * the pointer, so the page it returns to reports the return; a new tab
214 : * reports it on the next wake.
215 : */
216 : reportHostedStepOpened: (
217 : operationId: string,
218 : navigation: CheckoutRedirectNavigation,
219 : methodKind?: CheckoutMethodKind
220 : ) => void
221 : /** The host began driving the operation's challenge; polling pauses until it settles. */
222 : reportChallengeStarted: (operationId: string) => void
223 : reportChallengeSettled: (
224 : operationId: string,
225 : outcome: 'completed' | 'failed'
226 : ) => void
227 : get: (operationId: string) => BillingOperationState | undefined
228 : getSnapshot: () => readonly BillingOperationState[]
229 : subscribe: (listener: (state: BillingOperationState) => void) => () => void
230 : /** Resolves with the terminal state; undefined for an id this lifecycle never adopted. */
231 : settled: (operationId: string) => Promise<BillingOperationState> | undefined
232 : dispose: () => void
233 : }
234 :
235 2356 : const NOT_AUTHENTICATED = {
236 : status: 'error',
237 : code: 'NOT_AUTHENTICATED'
238 : } as const satisfies BillingFailure
239 :
240 2356 : const SUPERSEDED = {
241 : status: 'error',
242 : code: 'SUPERSEDED'
243 : } as const satisfies BillingFailure
244 :
245 2356 : const OPERATION_ALREADY_PENDING = {
246 : status: 'error',
247 : code: 'OPERATION_ALREADY_PENDING'
248 : } as const satisfies BillingFailure
249 :
250 : /** A command attempt still settling, kept with the scope that issued it. */
251 : interface InFlightCommand {
252 : readonly context: BillingScopeContext
253 : readonly promise: Promise<BillingResult<BillingOperationState>>
254 : }
255 :
256 : interface OperationRecord {
257 : state: BillingOperationState
258 : readonly context: BillingScopeContext
259 : readonly resumed: boolean
260 : /** The end this tab already reported, kept on every pointer rewrite; a revisit says nothing new. */
261 : readonly reportedAs: BillingOperationPointer['settled']
262 : delayMs: number | undefined
263 : /** When the operation last became blocked on the customer with no action here. */
264 : waitingWithoutActionSince: number | undefined
265 : timer: ReturnType<typeof setTimeout> | undefined
266 : inFlightPoll: Promise<void> | undefined
267 : /** A hosted step this tab opened in a new tab; the next wake is the customer back. */
268 : awaitingReturn: HostedStepVisit | undefined
269 : readonly settled: Promise<BillingOperationState>
270 : resolveSettled: (state: BillingOperationState) => void
271 : }
272 :
273 : interface AdoptInput {
274 : readonly id: string
275 : readonly kind: BillingOperationKind
276 : readonly context: BillingScopeContext
277 : readonly presentation: BillingPresentation
278 : readonly actionUrl?: string
279 : readonly clientSecret?: string
280 : readonly attemptStartedAt: number
281 : readonly resumed: boolean
282 : readonly awaitedHere: boolean
283 : /** A status already read for this operation; observed from it instead of polled again. */
284 : readonly initialStatus?: BillingOpStatus
285 : /** The hosted step a redirect left this page for; adopting it is the return. */
286 : readonly returnedFrom?: BillingOperationPointer['redirect']
287 : readonly reportedAs?: BillingOperationPointer['settled']
288 : }
289 :
290 : type ResumedAttempt = Pick<
291 : AdoptInput,
292 : | 'presentation'
293 : | 'attemptStartedAt'
294 : | 'resumed'
295 : | 'awaitedHere'
296 : | 'returnedFrom'
297 : | 'reportedAs'
298 : >
299 :
300 : /** The attempt a pointer remembers, picked up again by this tab. */
301 0 : function resumedFrom(pointer: BillingOperationPointer): ResumedAttempt {
302 0 : return {
303 : presentation: pointer.presentation,
304 : attemptStartedAt: pointer.attemptStartedAt,
305 : resumed: true,
306 : awaitedHere: pointer.awaited === true,
307 : ...(pointer.settled === undefined ? {} : { reportedAs: pointer.settled }),
308 : ...(pointer.redirect === undefined
309 : ? {}
310 : : { returnedFrom: pointer.redirect })
311 : }
312 : }
313 :
314 : interface ServerPendingOperation {
315 : readonly id: string
316 : readonly kind: BillingOperationKind
317 : readonly actionUrl?: string
318 : readonly clientSecret?: string
319 : }
320 :
321 0 : function continuationOf(issued: {
322 : readonly actionUrl?: string | undefined
323 : readonly clientSecret?: string | undefined
324 : }): Pick<AdoptInput, 'actionUrl' | 'clientSecret'> {
325 0 : return {
326 : ...(issued.actionUrl === undefined ? {} : { actionUrl: issued.actionUrl }),
327 : ...(issued.clientSecret === undefined
328 : ? {}
329 : : { clientSecret: issued.clientSecret })
330 : }
331 : }
332 :
333 0 : function pendingFromStatus(
334 : status: BillingStatusData
335 : ): ServerPendingOperation | undefined {
336 0 : if (status.pending_billing_op_id === undefined) return undefined
337 0 : return {
338 : id: status.pending_billing_op_id,
339 : kind: status.pending_billing_op_type === 'topup' ? 'topup' : 'subscription',
340 : ...continuationOf({
341 : actionUrl: status.action_url,
342 : clientSecret: status.payment_intent_client_secret
343 : })
344 : }
345 : }
346 :
347 0 : function initialPendingState(
348 : input: AdoptInput,
349 : observedAt: number,
350 : presentation: BillingPresentationState
351 : ): PendingBillingOperation {
352 0 : const actionUrl = validateActionUrl(input.actionUrl)
353 0 : const challenge =
354 : input.clientSecret === undefined || input.presentation !== 'embedded'
355 : ? undefined
356 : : { clientSecret: input.clientSecret, status: 'required' as const }
357 0 : return {
358 : id: input.id,
359 : kind: input.kind,
360 : scope: input.context.scope,
361 : ...presentation,
362 : observedAt,
363 : attemptStartedAt: input.attemptStartedAt,
364 : ...(input.awaitedHere ? { awaitedHere: true } : {}),
365 : phase: 'pending',
366 : ...(actionUrl === undefined ? {} : { actionUrl }),
367 : ...(challenge === undefined ? {} : { challenge }),
368 : customerActionSeen:
369 : actionUrl !== undefined || input.clientSecret !== undefined
370 : }
371 : }
372 :
373 0 : export function failureCategoryFor(
374 : state: Exclude<BillingOperationState, PendingBillingOperation>
375 : ): BillingOperationFailureCategory | undefined {
376 0 : switch (state.phase) {
377 : case 'succeeded':
378 0 : return undefined
379 : case 'failed':
380 0 : return state.kind === 'cancel' ? 'api_rejected' : 'provider_decline'
381 : case 'timed_out':
382 0 : return 'poll_timeout'
383 : case 'reconciliation_needed':
384 0 : return 'reconciliation_needed'
385 : case 'superseded':
386 0 : return 'stale_operation'
387 : }
388 : }
389 :
390 2356 : const FRICTION_EVENT_NAME = {
391 : challenge_required:
392 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeRequired,
393 : challenge_completed:
394 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeCompleted,
395 : challenge_failed: BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeFailed
396 : } as const satisfies Record<PaymentFrictionSignal['stage'], string>
397 :
398 : /** What the hosted page asks of the customer, from what the server waits on. */
399 0 : function hostedStepOf(state: PendingBillingOperation): CheckoutHostedStep {
400 0 : if (
401 : state.authenticationState === 'requires_action' ||
402 : (state.presentation === 'embedded' && state.challenge !== undefined)
403 : ) {
404 0 : return 'authentication'
405 : }
406 0 : if (state.serverPhase === 'awaiting_payment_method') return 'payment_method'
407 0 : if (state.serverPhase === 'awaiting_invoice_payment') return 'invoice_payment'
408 0 : return 'checkout'
409 : }
410 :
411 : /** The pause is this tab's own challenge on screen; a hosted page never pauses. */
412 0 : function isDrivingChallenge(state: PendingBillingOperation): boolean {
413 0 : return (
414 : state.presentation === 'embedded' &&
415 : state.challenge?.status === 'in_progress'
416 : )
417 : }
418 :
419 0 : export function createBillingOperationLifecycle(
420 : options: BillingOperationLifecycleOptions
421 : ): BillingOperationLifecycle {
422 0 : const {
423 : transport,
424 : scopeSource,
425 : statusReader,
426 : embeddedCheckoutAvailable = () => false,
427 : hostedDestination = () => 'stripe',
428 : onTelemetry,
429 : now = Date.now
430 : } = options
431 0 : const pointers: OperationPointerStore =
432 : options.pointerStorage === undefined
433 : ? NO_POINTER_STORE
434 : : createOperationPointerStore(options.pointerStorage, now, {
435 : retainSettled: options.retainSettledPointer === true
436 : })
437 :
438 0 : const operations = new Map<string, OperationRecord>()
439 0 : const inFlightCommands = new Map<BillingOperationKind, InFlightCommand>()
440 0 : const listeners = new Set<(state: BillingOperationState) => void>()
441 0 : const lifetime = { disposed: false }
442 :
443 : // Role is part of the scope, so a demotion mid-payment supersedes the
444 : // operation and this tab stops observing it. The pointer key omits role on
445 : // purpose: the charge still belongs to (user, workspace), so `recover` finds
446 : // it again under the new role. Keying the pointer by role would strand it.
447 0 : const scopeTracker = createBillingScopeTracker(scopeSource, () => {
448 0 : for (const record of operations.values()) {
449 0 : dispatch(record, { type: 'superseded' })
450 : }
451 : })
452 :
453 0 : function isLive(context: BillingScopeContext): boolean {
454 0 : return !lifetime.disposed && scopeTracker.isCurrent(context)
455 : }
456 :
457 0 : function publish(record: OperationRecord) {
458 0 : for (const listener of Array.from(listeners)) listener(record.state)
459 : }
460 :
461 0 : function stopTimer(record: OperationRecord) {
462 0 : if (record.timer === undefined) return
463 0 : clearTimeout(record.timer)
464 0 : record.timer = undefined
465 : }
466 :
467 0 : function report(
468 : record: OperationRecord,
469 : event: BillingOperationTelemetryEvent
470 : ) {
471 0 : if (record.reportedAs === undefined) onTelemetry?.(event)
472 : }
473 :
474 0 : function emitTerminalTelemetry(record: OperationRecord) {
475 0 : const state = record.state
476 0 : if (!isTerminal(state)) return
477 0 : const category = failureCategoryFor(state)
478 0 : report(record, {
479 : name:
480 : state.phase === 'succeeded'
481 : ? BILLING_OPERATION_TELEMETRY_EVENT.succeeded
482 : : state.phase === 'timed_out'
483 : ? BILLING_OPERATION_TELEMETRY_EVENT.timeout
484 : : BILLING_OPERATION_TELEMETRY_EVENT.failed,
485 : billing_op_id: state.id,
486 : operation_type: state.kind,
487 : presentation: state.presentation,
488 : resumed: record.resumed,
489 : ...(category === undefined ? {} : { failure_category: category }),
490 : ...(state.phase === 'failed'
491 : ? { decline_reason: state.declineReason }
492 : : {}),
493 : duration_ms: now() - state.attemptStartedAt
494 : })
495 : }
496 :
497 0 : function emitFrictionTelemetry(
498 : record: OperationRecord,
499 : before: BillingOperationState | undefined
500 : ) {
501 0 : const state = record.state
502 0 : for (const signal of paymentFrictionBetween(before, state)) {
503 0 : report(record, {
504 : name: FRICTION_EVENT_NAME[signal.stage],
505 : billing_op_id: state.id,
506 : operation_type: state.kind,
507 : presentation: state.presentation,
508 : resumed: record.resumed,
509 : ...('declineReason' in signal && signal.declineReason !== undefined
510 : ? { decline_reason: signal.declineReason }
511 : : {})
512 : })
513 : }
514 : }
515 :
516 0 : function dispatch(record: OperationRecord, event: BillingOperationEvent) {
517 0 : const before = record.state
518 0 : const next = reduceBillingOperation(before, event)
519 0 : if (next === before) return
520 0 : record.state = next
521 0 : emitFrictionTelemetry(record, before)
522 0 : if (isTerminal(next)) {
523 0 : stopTimer(record)
524 0 : pointers.settle(next)
525 0 : emitTerminalTelemetry(record)
526 0 : record.resolveSettled(next)
527 : }
528 0 : publish(record)
529 : }
530 :
531 0 : function schedule(record: OperationRecord) {
532 0 : if (record.state.phase !== 'pending') return
533 0 : stopTimer(record)
534 0 : record.waitingWithoutActionSince = isWaitingOnCustomerWithoutAction(
535 : record.state
536 : )
537 : ? (record.waitingWithoutActionSince ?? now())
538 : : undefined
539 0 : const delayMs = nextPollDelayMs(
540 : record.state,
541 : record.delayMs,
542 : record.waitingWithoutActionSince === undefined
543 : ? 0
544 : : now() - record.waitingWithoutActionSince
545 : )
546 0 : record.delayMs = delayMs
547 0 : record.timer = setTimeout(() => void poll(record), delayMs)
548 : }
549 :
550 : // One request per record at a time: a wake arriving mid-poll joins the
551 : // poll in flight instead of doubling the request rate. The request is
552 : // bound to the record, not the id, so an id re-adopted after supersession
553 : // starts its own observation instead of joining a poll that can no longer
554 : // schedule it.
555 0 : function poll(record: OperationRecord): Promise<void> {
556 0 : if (record.inFlightPoll !== undefined) return record.inFlightPoll
557 0 : const request = pollOnce(record).finally(() => {
558 0 : record.inFlightPoll = undefined
559 : })
560 0 : record.inFlightPoll = request
561 0 : return request
562 : }
563 :
564 0 : function savedRedirect(scope: BillingScope, operationId: string) {
565 0 : const saved = pointers.read(scope)
566 0 : return saved?.operationId === operationId ? saved.redirect : undefined
567 : }
568 :
569 0 : function writePointer(
570 : record: OperationRecord,
571 : redirect?: BillingOperationPointer['redirect']
572 : ) {
573 0 : const { state, reportedAs } = record
574 0 : pointers.write(record.context.scope, {
575 : operationId: state.id,
576 : kind: state.kind,
577 : presentation: state.presentation,
578 : attemptStartedAt: state.attemptStartedAt,
579 : ...(state.awaitedHere ? { awaited: true } : {}),
580 : ...(redirect === undefined ? {} : { redirect }),
581 : ...(reportedAs === undefined ? {} : { settled: reportedAs })
582 : })
583 : }
584 :
585 0 : function emitHostedStepTelemetry(
586 : record: OperationRecord,
587 : name: HostedStepEventName,
588 : visit: HostedStepVisit
589 : ) {
590 0 : report(record, {
591 : name,
592 : billing_op_id: record.state.id,
593 : operation_type: record.state.kind,
594 : presentation: record.state.presentation,
595 : resumed: record.resumed,
596 : ...visit
597 : })
598 : }
599 :
600 0 : function readOperation(operationId: string) {
601 0 : return readValidatedBillingResponse(
602 : transport,
603 : { method: 'GET', route: operationRoute(operationId) },
604 : (body) => BillingOpStatusSchema.safeParse(body)
605 : )
606 : }
607 :
608 0 : function continueOrExpire(record: OperationRecord) {
609 0 : if (record.state.phase !== 'pending') return
610 0 : if (hasExhaustedPollBudget(record.state, now())) {
611 0 : dispatch(record, { type: 'timed_out' })
612 0 : return
613 : }
614 0 : schedule(record)
615 : }
616 :
617 0 : async function pollOnce(record: OperationRecord) {
618 0 : const state = record.state
619 0 : if (state.phase !== 'pending') return
620 0 : stopTimer(record)
621 0 : if (isDrivingChallenge(state)) return
622 0 : if (!scopeTracker.isCurrent(record.context)) {
623 0 : dispatch(record, { type: 'superseded' })
624 0 : return
625 : }
626 0 : if (hasExhaustedPollBudget(state, now())) {
627 0 : dispatch(record, { type: 'timed_out' })
628 0 : return
629 : }
630 :
631 0 : const response = await readOperation(state.id)
632 :
633 0 : if (record.state.phase !== 'pending') return
634 0 : if (!isLive(record.context)) {
635 0 : dispatch(record, { type: 'superseded' })
636 0 : return
637 : }
638 0 : applyPollResponse(record, response)
639 : }
640 :
641 0 : function applyPollResponse(
642 : record: OperationRecord,
643 : response: Awaited<ReturnType<typeof readOperation>>
644 : ) {
645 0 : if (response.status === 'ok') {
646 0 : dispatch(record, { type: 'status_polled', status: response.value.data })
647 0 : continueOrExpire(record)
648 0 : return
649 : }
650 0 : if (
651 : response.code === 'SUPERSEDED' ||
652 : response.code === 'ACCESS_DENIED' ||
653 : response.code === 'NOT_AUTHENTICATED'
654 : ) {
655 0 : dispatch(record, { type: 'superseded' })
656 0 : } else if (response.code === 'NOT_FOUND') {
657 0 : dispatch(record, { type: 'lost' })
658 : } else {
659 0 : continueOrExpire(record)
660 : }
661 : }
662 :
663 : /** Read at every adoption, so an operation recovered from the pointer lands on today's destination. */
664 0 : function destinationFor(
665 : presentation: BillingPresentation
666 : ): BillingPresentationState {
667 0 : return presentation === 'hosted'
668 : ? { presentation, hostedDestination: hostedDestination() }
669 : : { presentation }
670 : }
671 :
672 : /**
673 : * An id is observed afresh once this tab has stopped learning anything new
674 : * about it: its poll budget ran out or it left the scope. One the server
675 : * parked for reconciliation, or a success whose credits were still landing,
676 : * is observed afresh only for a caller reading settled operations, since
677 : * the server may since have settled it or recorded the grant.
678 : */
679 0 : function adopt(input: AdoptInput, includeSettled = false): OperationRecord {
680 0 : const existing = operations.get(input.id)
681 0 : if (
682 : existing !== undefined &&
683 : existing.state.phase !== 'timed_out' &&
684 : existing.state.phase !== 'superseded' &&
685 : !(includeSettled && isStillSettling(existing.state))
686 : ) {
687 0 : return existing
688 : }
689 :
690 0 : const state = initialPendingState(
691 : input,
692 : now(),
693 : destinationFor(input.presentation)
694 : )
695 :
696 0 : let resolveSettled: (state: BillingOperationState) => void = () => {}
697 0 : const settled = new Promise<BillingOperationState>((resolve) => {
698 0 : resolveSettled = resolve
699 : })
700 0 : const record: OperationRecord = {
701 : state,
702 : context: input.context,
703 : resumed: input.resumed,
704 : reportedAs: input.reportedAs,
705 : delayMs: undefined,
706 : waitingWithoutActionSince: undefined,
707 : timer: undefined,
708 : inFlightPoll: undefined,
709 : awaitingReturn: undefined,
710 : settled,
711 : resolveSettled
712 : }
713 0 : operations.set(input.id, record)
714 0 : writePointer(record)
715 0 : report(record, {
716 : name: BILLING_OPERATION_TELEMETRY_EVENT.started,
717 : billing_op_id: input.id,
718 : operation_type: input.kind,
719 : presentation: input.presentation,
720 : resumed: input.resumed
721 : })
722 0 : emitFrictionTelemetry(record, undefined)
723 0 : if (input.returnedFrom !== undefined) {
724 0 : emitHostedStepTelemetry(
725 : record,
726 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned,
727 : {
728 : ...input.returnedFrom,
729 : navigation: 'redirect'
730 : }
731 : )
732 : }
733 0 : startObserving(record, input, state)
734 0 : return record
735 : }
736 :
737 : // A resumed operation without a served link is announced by its first
738 : // status, never before it: the status read names it but not what it waits
739 : // on, and a checkout parked on a card must not be announced as processing
740 : // for the length of a poll. A served link already says what it waits on.
741 0 : function startObserving(
742 : record: OperationRecord,
743 : input: AdoptInput,
744 : state: PendingBillingOperation
745 : ) {
746 0 : if (input.initialStatus !== undefined) {
747 0 : dispatch(record, { type: 'status_polled', status: input.initialStatus })
748 0 : continueOrExpire(record)
749 0 : return
750 : }
751 0 : if (!input.resumed || state.actionUrl !== undefined) publish(record)
752 0 : void poll(record)
753 : }
754 :
755 0 : function routeFor(
756 : rail: BillingStatusData['billing_rail'],
757 : issued: { readonly actionUrl?: string; readonly clientSecret?: string }
758 : ): BillingPresentation {
759 0 : return selectBillingPresentation({
760 : embeddedCheckoutAvailable: embeddedCheckoutAvailable(),
761 : billingRail: rail,
762 : ...(issued.actionUrl === undefined
763 : ? {}
764 : : { hostedUrl: issued.actionUrl }),
765 : ...(issued.clientSecret === undefined
766 : ? {}
767 : : { clientSecret: issued.clientSecret })
768 : })
769 : }
770 :
771 0 : async function beginOnce(
772 : kind: BillingOperationKind,
773 : context: BillingScopeContext,
774 : issue: (
775 : scope: BillingScope
776 : ) => Promise<BillingResult<IssuedBillingOperation>>
777 : ): Promise<BillingResult<BillingOperationState>> {
778 : // The backend's word on what is already pending comes first: a second
779 : // charge attempt is never issued over one the server is still settling.
780 0 : const status = await statusReader.read()
781 : // A scope change outranks a failed read, as in recover().
782 0 : if (!isLive(context)) return SUPERSEDED
783 0 : if (status.status === 'error') return status
784 :
785 0 : const rail = status.value.status.billing_rail
786 0 : const parked = await resubmitTarget(
787 : pendingFromStatus(status.value.status),
788 : kind
789 : )
790 0 : if (!isLive(context)) return SUPERSEDED
791 0 : if (parked === 'refused') return OPERATION_ALREADY_PENDING
792 :
793 0 : const attemptStartedAt = now()
794 0 : const issued = await issue(context.scope)
795 0 : if (!isLive(context)) {
796 0 : return leftScope(context, kind, rail, issued, attemptStartedAt)
797 : }
798 0 : if (issued.status === 'error') return issued
799 :
800 0 : const resumed =
801 : parked === undefined ? undefined : resumeParked(parked, issued.value)
802 0 : if (resumed !== undefined) return { status: 'ok', value: resumed }
803 :
804 : const record = adopt({
805 : id: issued.value.operationId,
806 : kind,
807 : context,
808 : presentation: routeFor(rail, issued.value),
809 : ...continuationOf(issued.value),
810 : attemptStartedAt,
811 : resumed: false,
812 : awaitedHere: true
813 : })
814 0 : return { status: 'ok', value: record.state }
815 : }
816 :
817 : // The operation exists server-side under the scope this tab just left; the
818 : // pointer waits there so a return recovers it rather than reissuing.
819 0 : function leftScope(
820 : context: BillingScopeContext,
821 : kind: BillingOperationKind,
822 : rail: BillingStatusData['billing_rail'],
823 : issued: BillingResult<IssuedBillingOperation>,
824 : attemptStartedAt: number
825 : ): typeof SUPERSEDED {
826 0 : if (issued.status === 'ok') {
827 0 : pointers.write(context.scope, {
828 : operationId: issued.value.operationId,
829 : kind,
830 : presentation: routeFor(rail, issued.value),
831 : attemptStartedAt,
832 : awaited: true
833 : })
834 : }
835 0 : return SUPERSEDED
836 : }
837 :
838 : /**
839 : * Declines rather than joins an operation of this kind the server already
840 : * has pending, because the status names no plan: this caller asked for one
841 : * outcome and the parked attempt settles another, so reporting that one as
842 : * this command's result would tell the customer they bought something they
843 : * did not choose. recover() is where a deliberate return to it belongs.
844 : *
845 : * The exception is a checkout this tab watches parked on a card. The server
846 : * keeps no link back to it, and a resubmit is how it resumes that checkout
847 : * or replaces it, so the command goes through with that record in hand.
848 : */
849 0 : async function resubmitTarget(
850 : pending: ServerPendingOperation | undefined,
851 : kind: BillingOperationKind
852 : ): Promise<OperationRecord | 'refused' | undefined> {
853 0 : if (pending?.kind !== kind) return undefined
854 0 : const record = operations.get(pending.id)
855 0 : if (
856 : record?.state.phase === 'pending' &&
857 : record.state.serverPhase === undefined
858 : ) {
859 0 : const read = await readOperation(pending.id)
860 0 : if (read.status === 'ok') {
861 0 : dispatch(record, { type: 'status_polled', status: read.value.data })
862 : }
863 : }
864 0 : return record?.state.phase === 'pending' &&
865 : record.state.serverPhase === 'awaiting_payment_method'
866 : ? record
867 : : 'refused'
868 : }
869 :
870 : /**
871 : * The same id is the parked checkout resumed, with the fresh hosted step the
872 : * server minted for it; another id replaced it, so this tab stops watching.
873 : */
874 0 : function resumeParked(
875 : parked: OperationRecord,
876 : issued: IssuedBillingOperation
877 : ): BillingOperationState | undefined {
878 0 : if (parked.state.id !== issued.operationId) {
879 0 : dispatch(parked, { type: 'superseded' })
880 0 : return undefined
881 : }
882 0 : if (issued.actionUrl !== undefined) {
883 0 : dispatch(parked, { type: 'action_reissued', actionUrl: issued.actionUrl })
884 : }
885 0 : return parked.state
886 : }
887 :
888 0 : function begin(
889 : kind: BillingOperationKind,
890 : issue: (
891 : scope: BillingScope
892 : ) => Promise<BillingResult<IssuedBillingOperation>>
893 : ): Promise<BillingResult<BillingOperationState>> {
894 0 : if (lifetime.disposed) return Promise.resolve(SUPERSEDED)
895 0 : const context = scopeTracker.capture()
896 0 : if (context === undefined) return Promise.resolve(NOT_AUTHENTICATED)
897 :
898 : // Single-flight holds only within a scope: an attempt the scope change
899 : // already doomed to SUPERSEDED must not stand in for this caller's.
900 0 : const inFlight = inFlightCommands.get(kind)
901 0 : if (inFlight !== undefined && isLive(inFlight.context)) {
902 0 : return inFlight.promise
903 : }
904 0 : const attempt = beginOnce(kind, context, issue).finally(() => {
905 0 : if (inFlightCommands.get(kind)?.promise === attempt) {
906 0 : inFlightCommands.delete(kind)
907 : }
908 : })
909 0 : inFlightCommands.set(kind, { context, promise: attempt })
910 0 : return attempt
911 : }
912 :
913 0 : function fromPointer(
914 : pointer: BillingOperationPointer,
915 : context: BillingScopeContext
916 : ): AdoptInput {
917 0 : return {
918 : id: pointer.operationId,
919 : kind: pointer.kind,
920 : context,
921 : ...resumedFrom(pointer)
922 : }
923 : }
924 :
925 : // Unreachable is not "nothing pending": the pointer is the only evidence
926 : // left, and observing it costs a poll while reissuing could cost a charge.
927 0 : function recoverFromPointer(
928 : failure: BillingFailure,
929 : pointer: BillingOperationPointer | undefined,
930 : context: BillingScopeContext,
931 : includeSettled: boolean
932 : ): BillingResult<BillingOperationState | undefined> {
933 0 : if (failure.code !== 'REQUEST_FAILED' || pointer === undefined) {
934 0 : return failure
935 : }
936 : const record = adopt(fromPointer(pointer, context), includeSettled)
937 0 : return { status: 'ok', value: record.state }
938 : }
939 :
940 0 : function resumeServerPending(
941 : pending: ServerPendingOperation,
942 : rail: BillingStatusData['billing_rail'],
943 : pointer: BillingOperationPointer | undefined,
944 : context: BillingScopeContext,
945 : includeSettled: boolean
946 : ): BillingResult<BillingOperationState> {
947 0 : const known = pointer?.operationId === pending.id ? pointer : undefined
948 : const record = adopt(
949 : {
950 : ...pending,
951 : context,
952 : ...(known === undefined
953 : ? {
954 : presentation: routeFor(rail, pending),
955 : attemptStartedAt: now(),
956 : resumed: true,
957 : awaitedHere: false
958 : }
959 : : resumedFrom(known))
960 : },
961 : includeSettled
962 : )
963 0 : return { status: 'ok', value: record.state }
964 : }
965 :
966 : // The server reports nothing pending, so the pointed-at operation has
967 : // either settled since this tab last saw it or never belonged to this
968 : // scope. One read decides which; a stale pointer is dropped, never
969 : // re-observed on a schedule.
970 0 : async function probePointer(
971 : pointer: BillingOperationPointer,
972 : context: BillingScopeContext,
973 : includeSettled: boolean
974 : ): Promise<BillingResult<BillingOperationState | undefined>> {
975 0 : const probe = await readOperation(pointer.operationId)
976 0 : if (!isLive(context)) return SUPERSEDED
977 0 : if (probe.status === 'error') {
978 0 : if (probe.code !== 'NOT_FOUND') return probe
979 0 : pointers.clear(context.scope, pointer.operationId)
980 0 : return { status: 'ok', value: undefined }
981 : }
982 : const record = adopt(
983 : { ...fromPointer(pointer, context), initialStatus: probe.value.data },
984 : includeSettled
985 : )
986 0 : return { status: 'ok', value: record.state }
987 : }
988 :
989 : /** A settled pointer answers only a caller that asked for it. */
990 0 : function readPointer(
991 : scope: BillingScope,
992 : includeSettled: boolean
993 : ): BillingOperationPointer | undefined {
994 0 : const pointer = pointers.read(scope)
995 0 : return pointer?.settled === undefined || includeSettled
996 : ? pointer
997 : : undefined
998 : }
999 :
1000 0 : async function recover({
1001 : includeSettled = false
1002 : }: BillingRecoverOptions = {}): Promise<
1003 : BillingResult<BillingOperationState | undefined>
1004 : > {
1005 0 : if (lifetime.disposed) return SUPERSEDED
1006 0 : const context = scopeTracker.capture()
1007 0 : if (context === undefined) return NOT_AUTHENTICATED
1008 :
1009 0 : const status = await statusReader.read()
1010 0 : if (!isLive(context)) return SUPERSEDED
1011 0 : const pointer = readPointer(context.scope, includeSettled)
1012 0 : if (status.status === 'error') {
1013 0 : return recoverFromPointer(status, pointer, context, includeSettled)
1014 : }
1015 :
1016 0 : const pending = pendingFromStatus(status.value.status)
1017 0 : if (pending !== undefined) {
1018 0 : return resumeServerPending(
1019 : pending,
1020 : status.value.status.billing_rail,
1021 : pointer,
1022 : context,
1023 : includeSettled
1024 : )
1025 : }
1026 0 : if (pointer === undefined) return { status: 'ok', value: undefined }
1027 0 : return probePointer(pointer, context, includeSettled)
1028 : }
1029 :
1030 0 : function wake() {
1031 0 : for (const record of operations.values()) {
1032 0 : reportReturnFromNewTab(record)
1033 0 : if (record.state.phase !== 'pending') continue
1034 0 : if (isDrivingChallenge(record.state)) continue
1035 0 : void poll(record)
1036 : }
1037 : }
1038 :
1039 0 : function refusedSwitch(
1040 : state: PendingBillingOperation,
1041 : presentation: BillingPresentation
1042 : ): PresentationSwitchOutcome | undefined {
1043 0 : if (state.presentation === presentation) return 'unchanged'
1044 0 : if (presentation === 'hosted') {
1045 0 : return state.actionUrl === undefined ? 'no_hosted_url' : undefined
1046 : }
1047 0 : return !embeddedCheckoutAvailable() || state.challenge === undefined
1048 : ? 'embedded_unavailable'
1049 : : undefined
1050 : }
1051 :
1052 0 : function switchEvent(
1053 : presentation: BillingPresentation
1054 : ): BillingOperationEvent {
1055 0 : return presentation === 'hosted'
1056 : ? {
1057 : type: 'presentation_switched',
1058 : presentation,
1059 : hostedDestination: hostedDestination()
1060 : }
1061 : : { type: 'presentation_switched', presentation }
1062 : }
1063 :
1064 0 : function switchPresentation(
1065 : operationId: string,
1066 : presentation: BillingPresentation
1067 : ): PresentationSwitchOutcome {
1068 0 : const record = operations.get(operationId)
1069 0 : if (record === undefined) return 'unknown_operation'
1070 0 : const state = record.state
1071 0 : if (state.phase !== 'pending') return 'not_pending'
1072 0 : const refusal = refusedSwitch(state, presentation)
1073 0 : if (refusal !== undefined) return refusal
1074 0 : dispatch(record, switchEvent(presentation))
1075 0 : writePointer(record, savedRedirect(record.context.scope, operationId))
1076 0 : record.delayMs = undefined
1077 0 : schedule(record)
1078 0 : return 'switched'
1079 : }
1080 :
1081 0 : function reportReturnFromNewTab(record: OperationRecord) {
1082 0 : const visit = record.awaitingReturn
1083 0 : if (visit === undefined) return
1084 0 : record.awaitingReturn = undefined
1085 0 : emitHostedStepTelemetry(
1086 : record,
1087 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned,
1088 : visit
1089 : )
1090 : }
1091 :
1092 0 : function reportHostedStepOpened(
1093 : operationId: string,
1094 : navigation: CheckoutRedirectNavigation,
1095 : methodKind?: CheckoutMethodKind
1096 : ) {
1097 0 : const record = operations.get(operationId)
1098 0 : if (record === undefined || record.state.phase !== 'pending') return
1099 0 : const state = record.state
1100 0 : const redirect = {
1101 : destination:
1102 : state.presentation === 'hosted' ? state.hostedDestination : 'stripe',
1103 : step: hostedStepOf(state),
1104 : ...(methodKind === undefined ? {} : { method_kind: methodKind })
1105 : } as const
1106 0 : const visit = { ...redirect, navigation }
1107 0 : if (navigation === 'redirect') {
1108 0 : writePointer(record, redirect)
1109 : } else {
1110 0 : record.awaitingReturn = visit
1111 : }
1112 0 : emitHostedStepTelemetry(
1113 : record,
1114 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.redirectStarted,
1115 : visit
1116 : )
1117 : }
1118 :
1119 0 : function reportChallengeStarted(operationId: string) {
1120 0 : const record = operations.get(operationId)
1121 0 : if (record === undefined) return
1122 0 : dispatch(record, { type: 'challenge_started' })
1123 0 : if (record.state.phase === 'pending' && isDrivingChallenge(record.state)) {
1124 0 : stopTimer(record)
1125 : }
1126 : }
1127 :
1128 0 : function reportChallengeSettled(
1129 : operationId: string,
1130 : outcome: 'completed' | 'failed'
1131 : ) {
1132 0 : const record = operations.get(operationId)
1133 0 : if (record === undefined || record.state.phase !== 'pending') return
1134 0 : dispatch(record, { type: 'challenge_settled', outcome })
1135 0 : record.delayMs = undefined
1136 : // A completed challenge is read back at once; a failed one is not a
1137 : // verdict on the payment — the server may have seen it succeed — so the
1138 : // operation stays observed on the parked cadence rather than stopping.
1139 0 : if (outcome === 'completed') void poll(record)
1140 0 : else schedule(record)
1141 : }
1142 :
1143 0 : return {
1144 : begin,
1145 : recover,
1146 : wake,
1147 : switchPresentation,
1148 : reportHostedStepOpened,
1149 : reportChallengeStarted,
1150 : reportChallengeSettled,
1151 : get: (operationId) => operations.get(operationId)?.state,
1152 : getSnapshot: () => [...operations.values()].map((record) => record.state),
1153 : subscribe: (listener) => {
1154 0 : listeners.add(listener)
1155 0 : return () => listeners.delete(listener)
1156 : },
1157 : settled: (operationId) => operations.get(operationId)?.settled,
1158 : dispose: () => {
1159 0 : lifetime.disposed = true
1160 : // Every pending settlement resolves so no awaiting host hangs; this is
1161 : // the tab giving up observation, not an outcome, so no telemetry.
1162 0 : for (const record of operations.values()) {
1163 0 : stopTimer(record)
1164 0 : const next = reduceBillingOperation(record.state, {
1165 : type: 'superseded'
1166 : })
1167 0 : if (next === record.state) continue
1168 0 : record.state = next
1169 0 : record.resolveSettled(next)
1170 : }
1171 0 : operations.clear()
1172 0 : inFlightCommands.clear()
1173 0 : listeners.clear()
1174 0 : scopeTracker.dispose()
1175 : }
1176 : }
1177 : }
|