Line data Source code
1 : import { useTimeoutFn } from '@vueuse/core'
2 : import { ref, watch } from 'vue'
3 :
4 : import { useQueueStore } from '@/stores/queueStore'
5 :
6 2355 : const BASE_INTERVAL_MS = 8_000
7 2355 : const MAX_INTERVAL_MS = 32_000
8 2355 : const BACKOFF_MULTIPLIER = 1.5
9 :
10 2355 : export function useQueuePolling() {
11 2355 : const queueStore = useQueueStore()
12 2355 : const delay = ref(BASE_INTERVAL_MS)
13 :
14 2355 : const { start, stop } = useTimeoutFn(
15 : () => {
16 0 : if (queueStore.activeJobsCount !== 1 || queueStore.isLoading) return
17 0 : delay.value = Math.min(delay.value * BACKOFF_MULTIPLIER, MAX_INTERVAL_MS)
18 0 : void queueStore.update()
19 : },
20 : delay,
21 : { immediate: false }
22 : )
23 :
24 4986 : function scheduleNextPoll() {
25 4986 : if (queueStore.activeJobsCount === 1 && !queueStore.isLoading) start()
26 4927 : else stop()
27 : }
28 :
29 2355 : watch(
30 : () => queueStore.activeJobsCount,
31 : () => {
32 2405 : delay.value = BASE_INTERVAL_MS
33 2405 : scheduleNextPoll()
34 : },
35 : { immediate: true }
36 : )
37 :
38 : // Reschedule after any update completes (whether from polling or
39 : // WebSocket events) to avoid redundant requests.
40 2355 : watch(
41 : () => queueStore.isLoading,
42 : (loading, wasLoading) => {
43 5199 : if (wasLoading && !loading) scheduleNextPoll()
44 : },
45 : { flush: 'sync' }
46 : )
47 : }
|