File size: 3,125 Bytes
61ca2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import axios from 'axios'

export type TaskStatus = {
  task_id: string
  user_id?: string | null
  type?: string
  status?: string
  progress?: number
  stage?: string
  message?: string | null
  error?: string | null
  created_at?: string | null
  started_at?: string | null
  finished_at?: string | null
  file_path?: string | null
  params?: any
  result?: any
}

export type PollOptions = {
  intervalMs?: number
  timeoutMs?: number
  backoffMinMs?: number
  backoffMaxMs?: number
  onUpdate?: (st: TaskStatus) => void
  signal?: AbortSignal
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))

const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v))

const parseRetryAfterMs = (raw: any) => {
  const s = Number(raw)
  if (!Number.isFinite(s) || s <= 0) return null
  return Math.max(0, Math.floor(s * 1000))
}

export const startTaskPolling = (taskId: string, options: PollOptions = {}) => {
  const controller = new AbortController()

  if (options.signal) {
    if (options.signal.aborted) {
      controller.abort()
    } else {
      options.signal.addEventListener('abort', () => controller.abort(), { once: true })
    }
  }

  const intervalMs = Math.max(200, Number(options.intervalMs || 1000))
  const timeoutMs = Math.max(1000, Number(options.timeoutMs || 10 * 60 * 1000))
  const backoffMinMs = Math.max(200, Number(options.backoffMinMs || 3000))
  const backoffMaxMs = Math.max(backoffMinMs, Number(options.backoffMaxMs || 10000))

  const cancel = () => controller.abort()

  const promise = (async () => {
    const t0 = Date.now()
    let backoffPow = 0

    while (true) {
      if (controller.signal.aborted) {
        throw new Error('已取消')
      }

      if (Date.now() - t0 > timeoutMs) {
        throw new Error('轮询超时')
      }

      try {
        const res = await axios.get<TaskStatus>(`/api/v2/tasks/${taskId}`, { signal: controller.signal as any })
        const st = res.data
        options.onUpdate?.(st)

        backoffPow = 0

        const status = String(st?.status || '').toLowerCase()
        if (status === 'completed' || status === 'failed' || status === 'canceled' || status === 'cancelled') {
          return st
        }

        await sleep(intervalMs)
        continue
      } catch (err: any) {
        if (controller.signal.aborted) {
          throw new Error('已取消')
        }

        const statusCode = err?.response?.status
        const retryAfter = parseRetryAfterMs(err?.response?.headers?.['retry-after'])

        if (statusCode === 429) {
          const wait = retryAfter ?? clamp(backoffMinMs * Math.pow(2, backoffPow), backoffMinMs, backoffMaxMs)
          backoffPow = Math.min(backoffPow + 1, 10)
          await sleep(wait)
          continue
        }

        const wait = clamp(backoffMinMs * Math.pow(2, backoffPow), backoffMinMs, backoffMaxMs)
        backoffPow = Math.min(backoffPow + 1, 10)
        await sleep(wait)
      }
    }
  })()

  return { promise, cancel }
}