Refactor build expiration checks

This commit is contained in:
Fedor Indutny
2025-06-10 12:17:07 -07:00
committed by GitHub
parent b0634f9a9d
commit 9a4972d59e
7 changed files with 323 additions and 83 deletions

View File

@@ -34,3 +34,54 @@ export function safeSetTimeout(
return setTimeout(callback, delayMs);
}
// Set timeout for a delay that might be longer than MAX_SAFE_TIMEOUT_DELAY. The
// callback is guaranteed to execute after desired delay.
export class LongTimeout {
#callback: VoidFunction;
#fireTime: number;
#timer: NodeJS.Timeout | undefined;
constructor(callback: VoidFunction, providedDelayMs: number) {
let delayMs = providedDelayMs;
if (delayMs < 0) {
logging.warn('safeSetTimeout: timeout is less than zero');
delayMs = 0;
}
if (Number.isNaN(delayMs)) {
throw new Error('NaN delayMs');
}
if (!Number.isFinite(delayMs)) {
throw new Error('Infinite delayMs');
}
this.#callback = callback;
this.#fireTime = Date.now() + delayMs;
this.#schedule();
}
clear(): void {
if (this.#timer != null) {
clearTimeout(this.#timer);
}
this.#timer = undefined;
}
#schedule(): void {
const remainingMs = this.#fireTime - Date.now();
if (remainingMs <= MAX_SAFE_TIMEOUT_DELAY) {
this.#timer = setTimeout(() => this.#fire(), remainingMs);
return;
}
this.#timer = setTimeout(() => {
this.#schedule();
}, MAX_SAFE_TIMEOUT_DELAY);
}
#fire(): void {
this.clear();
this.#callback();
}
}