|
| 1 | +import type { WorkItemDetail } from '~~/shared/types/work-item' |
| 2 | + |
| 3 | +const POLL_INTERVAL = 20_000 |
| 4 | +const MAX_STALE_ROUNDS = 3 |
| 5 | + |
| 6 | +export function useWorkItemPolling( |
| 7 | + workItem: Ref<WorkItemDetail | null | undefined>, |
| 8 | + fetchUrl: Ref<string>, |
| 9 | +) { |
| 10 | + const requestFetch = useRequestFetch() |
| 11 | + |
| 12 | + let timer: ReturnType<typeof setInterval> | null = null |
| 13 | + let staleCount = 0 |
| 14 | + let lastFingerprint = '' |
| 15 | + |
| 16 | + const polling = ref(false) |
| 17 | + |
| 18 | + const needsPolling = computed(() => { |
| 19 | + const wi = workItem.value |
| 20 | + if (!wi) return false |
| 21 | + return wi.ciStatus === 'PENDING' |
| 22 | + }) |
| 23 | + |
| 24 | + function fingerprint(): string { |
| 25 | + const wi = workItem.value |
| 26 | + if (!wi) return '' |
| 27 | + return `${wi.state}|${wi.ciStatus}|${wi.updatedAt}` |
| 28 | + } |
| 29 | + |
| 30 | + async function tick() { |
| 31 | + try { |
| 32 | + const fresh = await requestFetch<WorkItemDetail>(fetchUrl.value) |
| 33 | + if (!fresh || !workItem.value) return |
| 34 | + Object.assign(workItem.value, fresh) |
| 35 | + } |
| 36 | + catch { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + const current = fingerprint() |
| 41 | + if (current === lastFingerprint) { |
| 42 | + staleCount++ |
| 43 | + } |
| 44 | + else { |
| 45 | + staleCount = 0 |
| 46 | + lastFingerprint = current |
| 47 | + } |
| 48 | + |
| 49 | + if (staleCount >= MAX_STALE_ROUNDS || !needsPolling.value) { |
| 50 | + stop() |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + function start() { |
| 55 | + if (timer) return |
| 56 | + staleCount = 0 |
| 57 | + lastFingerprint = fingerprint() |
| 58 | + polling.value = true |
| 59 | + timer = setInterval(tick, POLL_INTERVAL) |
| 60 | + } |
| 61 | + |
| 62 | + function stop() { |
| 63 | + if (!timer) return |
| 64 | + clearInterval(timer) |
| 65 | + timer = null |
| 66 | + polling.value = false |
| 67 | + } |
| 68 | + |
| 69 | + watch(needsPolling, (should) => { |
| 70 | + if (import.meta.client && should) { |
| 71 | + start() |
| 72 | + } |
| 73 | + else { |
| 74 | + stop() |
| 75 | + } |
| 76 | + }, { immediate: true }) |
| 77 | + |
| 78 | + async function trigger() { |
| 79 | + if (import.meta.client) { |
| 80 | + start() |
| 81 | + await tick() |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + onScopeDispose(stop) |
| 86 | + |
| 87 | + return { |
| 88 | + polling: readonly(polling), |
| 89 | + trigger, |
| 90 | + } |
| 91 | +} |
0 commit comments