Initial curated CertScope source from fe2bbe3ca5c98bf64be26a09c6c58ee805a7f87e
This commit is contained in:
commit
7348faf6c0
65 files changed
+12509
No files matched your search
@@ -0,0 +1,42 @@
|
||||
export const DEADLINE_EXPIRED_CODE = "ETIMEOUT";
|
||||
|
||||
export function createDeadline(budgetMs: number, now = Date.now()) {
|
||||
return now + Math.max(0, budgetMs);
|
||||
}
|
||||
|
||||
export function remainingMs(deadline: number, now = Date.now()) {
|
||||
return Math.max(0, deadline - now);
|
||||
}
|
||||
|
||||
export function timeoutError(message: string) {
|
||||
const error = new Error(message) as Error & { code: string };
|
||||
error.code = DEADLINE_EXPIRED_CODE;
|
||||
return error;
|
||||
}
|
||||
|
||||
export async function withDeadline<T>(
|
||||
operation: Promise<T>,
|
||||
deadline: number,
|
||||
onTimeout: () => void,
|
||||
message: string,
|
||||
): Promise<T> {
|
||||
const remaining = remainingMs(deadline);
|
||||
if (!remaining) {
|
||||
onTimeout();
|
||||
throw timeoutError(message);
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<T>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
onTimeout();
|
||||
reject(timeoutError(message));
|
||||
}, remaining);
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([operation, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user