|
| 1 | +import { setMaxListeners } from '@libp2p/interface' |
| 2 | +import { anySignal } from 'any-signal' |
| 3 | +import type { AbortOptions } from '@libp2p/interface' |
| 4 | + |
| 5 | +export interface RepeatingTask { |
| 6 | + start(): void |
| 7 | + stop(): void |
| 8 | +} |
| 9 | + |
| 10 | +export interface RepeatingTaskOptions { |
| 11 | + /** |
| 12 | + * How long the task is allowed to run before the passed AbortSignal fires an |
| 13 | + * abort event |
| 14 | + */ |
| 15 | + timeout?: number |
| 16 | + |
| 17 | + /** |
| 18 | + * Whether to schedule the task to run immediately |
| 19 | + */ |
| 20 | + runImmediately?: boolean |
| 21 | +} |
| 22 | + |
| 23 | +export function repeatingTask (fn: (options?: AbortOptions) => void | Promise<void>, interval: number, options?: RepeatingTaskOptions): RepeatingTask { |
| 24 | + let timeout: ReturnType<typeof setTimeout> |
| 25 | + let shutdownController: AbortController |
| 26 | + |
| 27 | + function runTask (): void { |
| 28 | + const opts: AbortOptions = { |
| 29 | + signal: shutdownController.signal |
| 30 | + } |
| 31 | + |
| 32 | + if (options?.timeout != null) { |
| 33 | + const signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)]) |
| 34 | + setMaxListeners(Infinity, signal) |
| 35 | + |
| 36 | + opts.signal = signal |
| 37 | + } |
| 38 | + |
| 39 | + Promise.resolve().then(async () => { |
| 40 | + await fn(opts) |
| 41 | + }) |
| 42 | + .catch(() => {}) |
| 43 | + .finally(() => { |
| 44 | + if (shutdownController.signal.aborted) { |
| 45 | + // task has been cancelled, bail |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + // reschedule |
| 50 | + timeout = setTimeout(runTask, interval) |
| 51 | + }) |
| 52 | + } |
| 53 | + |
| 54 | + let started = false |
| 55 | + |
| 56 | + return { |
| 57 | + start: () => { |
| 58 | + if (started) { |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + started = true |
| 63 | + shutdownController = new AbortController() |
| 64 | + setMaxListeners(Infinity, shutdownController.signal) |
| 65 | + |
| 66 | + // run now |
| 67 | + if (options?.runImmediately === true) { |
| 68 | + queueMicrotask(() => { |
| 69 | + runTask() |
| 70 | + }) |
| 71 | + } else { |
| 72 | + // run later |
| 73 | + timeout = setTimeout(runTask, interval) |
| 74 | + } |
| 75 | + }, |
| 76 | + stop: () => { |
| 77 | + clearTimeout(timeout) |
| 78 | + shutdownController?.abort() |
| 79 | + started = false |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments