Line data Source code
1 : import { delay } from 'es-toolkit'
2 :
3 : import type { AutoTopUpActivationOutcome } from '@comfyorg/account-core/billing'
4 : import type { HostedTopupCheckout } from '@comfyorg/ingest-types'
5 :
6 2356 : const READ_ATTEMPTS = 20
7 2356 : const READ_INTERVAL_MS = 1500
8 :
9 0 : function autoTopUpActivationOutcome(
10 : checkout: HostedTopupCheckout
11 : ): AutoTopUpActivationOutcome | undefined {
12 0 : const settings = checkout.auto_top_up
13 0 : if (checkout.auto_top_up_activation === 'failed') return { status: 'failed' }
14 0 : if (checkout.auto_top_up_activation !== 'on' || !settings) return undefined
15 0 : return {
16 : status: 'on',
17 : settings: {
18 : threshold_credits: settings.threshold_credits,
19 : target_credits: settings.target_credits,
20 : monthly_budget_cents: settings.monthly_budget_is_default
21 : ? null
22 : : settings.monthly_budget_cents
23 : }
24 : }
25 : }
26 :
27 : /** Reads the checkout until activation leaves pending; undefined if it never does. Rejects on abort. */
28 0 : export async function readAutoTopUpActivation(
29 : read: (signal: AbortSignal) => Promise<HostedTopupCheckout>,
30 : signal: AbortSignal
31 : ): Promise<AutoTopUpActivationOutcome | undefined> {
32 0 : for (let attempt = 0; attempt < READ_ATTEMPTS; attempt++) {
33 0 : signal.throwIfAborted()
34 0 : const checkout = await read(signal).catch(() => null)
35 0 : signal.throwIfAborted()
36 0 : if (checkout && checkout.auto_top_up_activation !== 'pending') {
37 0 : return autoTopUpActivationOutcome(checkout)
38 : }
39 0 : await delay(READ_INTERVAL_MS, { signal })
40 : }
41 : return undefined
42 : }
|