Files
apophis-fastify/src/extension/timeout.ts
T

40 lines
975 B
TypeScript
Raw Normal View History

/**
* Hook Timeout Utility
*
* Wraps async operations with a timeout to prevent indefinite hangs.
*/
class HookTimeoutError extends Error {
constructor(extensionName: string, hookName: string, timeoutMs: number) {
super(
`Extension '${extensionName}' ${hookName} timed out after ${timeoutMs}ms. ` +
`Consider increasing hookTimeoutMs or investigating the extension for blocking operations.`
)
this.name = 'HookTimeoutError'
}
}
/**
* Wrap a promise with a timeout.
* @returns Promise that rejects with HookTimeoutError if deadline exceeded
*/
export function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
extensionName: string,
hookName: string
): Promise<T> {
if (timeoutMs <= 0) {
return promise
}
return Promise.race([
promise,
new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new HookTimeoutError(extensionName, hookName, timeoutMs))
}, timeoutMs)
}),
])
}