Line data Source code
1 : /**
2 : * A Stripe credit top-up completes in a separate tab, and the balance only
3 : * changes once Stripe's webhook reaches comfy-api. Nothing re-reads the balance
4 : * when the user comes back, so the app keeps showing the pre-purchase amount
5 : * until a manual reload.
6 : *
7 : * Re-fetch when the app tab becomes visible again, retrying on a short schedule
8 : * because the webhook usually lands a beat after the redirect. Gaps between
9 : * attempts, so the run spans ~37s.
10 : */
11 2356 : const RETRY_GAPS_MS = [0, 2_000, 5_000, 10_000, 20_000]
12 :
13 : /** Drop the watch if the user never returns, rather than leaking listeners. */
14 2356 : const WATCH_LIFETIME_MS = 15 * 60_000
15 :
16 : /** Full retry schedules a returning user can trigger; later returns get a single fetch. */
17 2356 : const MAX_SCHEDULED_RUNS = 5
18 :
19 2356 : let stopActiveWatch: (() => void) | null = null
20 :
21 : interface TopupBalanceSource {
22 : current: () => number | null
23 : fetch: () => Promise<number | null>
24 : }
25 :
26 : /**
27 : * Watch for the user returning from a Stripe top-up and refresh the balance.
28 : * Safe to call repeatedly: a new call replaces any watch still pending.
29 : * Returns a function that stops the watch.
30 : */
31 1 : export function watchForTopupBalanceUpdate({
32 : source,
33 : onBalanceIncreased
34 : }: {
35 : source: TopupBalanceSource
36 : onBalanceIncreased?: () => Promise<unknown>
37 : }): () => void {
38 1 : if (typeof window === 'undefined' || typeof document === 'undefined')
39 0 : return () => {}
40 :
41 1 : stopActiveWatch?.()
42 :
43 1 : let baselineMicros: number | null = source.current()
44 :
45 1 : const timeouts = new Set<ReturnType<typeof setTimeout>>()
46 1 : let stopped = false
47 1 : let running = false
48 1 : let runs = 0
49 :
50 1 : const stop = () => {
51 0 : stopped = true
52 0 : document.removeEventListener('visibilitychange', handleReturn)
53 0 : window.removeEventListener('focus', handleReturn)
54 0 : for (const timeout of timeouts) clearTimeout(timeout)
55 0 : timeouts.clear()
56 0 : if (stopActiveWatch === stop) stopActiveWatch = null
57 : }
58 :
59 1 : const wait = (ms: number) =>
60 : new Promise<void>((resolve) => {
61 0 : const timeout = setTimeout(() => {
62 0 : timeouts.delete(timeout)
63 0 : resolve()
64 : }, ms)
65 0 : timeouts.add(timeout)
66 : })
67 :
68 1 : const refresh = async (): Promise<boolean> => {
69 0 : try {
70 0 : const amountMicros = (await source.fetch()) ?? 0
71 0 : if (baselineMicros === null) {
72 0 : baselineMicros = amountMicros
73 0 : return false
74 : }
75 0 : return amountMicros > baselineMicros
76 : } catch (error) {
77 0 : console.warn('[Billing] Top-up balance refresh failed', error)
78 0 : return false
79 : }
80 : }
81 :
82 1 : const refreshDependents = async () => {
83 0 : try {
84 0 : await onBalanceIncreased?.()
85 : } catch (error) {
86 0 : console.warn('[Billing] Top-up dependent refresh failed', error)
87 : }
88 : }
89 :
90 0 : async function onReturn() {
91 0 : if (running || stopped || document.visibilityState !== 'visible') return
92 0 : running = true
93 0 : runs += 1
94 :
95 0 : const gaps = runs > MAX_SCHEDULED_RUNS ? [0] : RETRY_GAPS_MS
96 0 : const isStopped = () => stopped
97 :
98 0 : for (const gap of gaps) {
99 0 : await wait(gap)
100 0 : if (isStopped()) return
101 0 : if (await refresh()) {
102 0 : await refreshDependents()
103 0 : stop()
104 0 : return
105 : }
106 0 : if (isStopped()) return
107 : }
108 :
109 0 : running = false
110 : }
111 :
112 0 : function handleReturn() {
113 0 : void onReturn()
114 : }
115 :
116 1 : document.addEventListener('visibilitychange', handleReturn)
117 1 : window.addEventListener('focus', handleReturn)
118 1 : timeouts.add(setTimeout(stop, WATCH_LIFETIME_MS))
119 :
120 1 : stopActiveWatch = stop
121 1 : return stop
122 : }
|