operation-timeout.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /**
  2. * Embedded Browser operation deadlines.
  3. *
  4. * The inner deadline must always settle before its caller's outer deadline:
  5. * CDP scan (30s) -> tab operation (60s default) -> renderer IPC (275s).
  6. * A hidden long-running action can legally wait for a render slot for 125s and
  7. * then execute for another 125s, so the outer IPC budget leaves a 25s cleanup
  8. * buffer above both bounded phases.
  9. */
  10. export const BROWSER_TIMEOUTS = {
  11. cdpCommand: 30_000,
  12. cdpScan: 30_000,
  13. tabOperation: 60_000,
  14. longTabOperation: 125_000,
  15. ipcHandler: 275_000,
  16. } as const;
  17. export type BrowserOperationInterruptionCode =
  18. | 'ABORTED'
  19. | 'BROWSER_OPERATION_TIMEOUT'
  20. | 'BROWSER_TRANSPORT_CLOSED';
  21. export type BrowserTransportInterruptionError = Error & {
  22. readonly code: BrowserOperationInterruptionCode;
  23. };
  24. /** Create the structured command interruption contract shared by every Browser transport. */
  25. export function browserTransportInterruptionError(
  26. code: BrowserOperationInterruptionCode,
  27. message: string,
  28. ): BrowserTransportInterruptionError {
  29. return Object.assign(new Error(message), { code });
  30. }
  31. export class OperationTimeoutError extends Error {
  32. readonly code = 'BROWSER_OPERATION_TIMEOUT';
  33. constructor(
  34. public readonly label: string,
  35. public readonly timeoutMs: number,
  36. ) {
  37. super(`BROWSER_OPERATION_TIMEOUT: Operation "${label}" exceeded ${timeoutMs}ms`);
  38. this.name = 'OperationTimeoutError';
  39. }
  40. }
  41. export class OperationAbortedError extends Error {
  42. readonly code = 'ABORTED';
  43. constructor(reason?: unknown) {
  44. super('Operation aborted');
  45. this.name = 'AbortError';
  46. if (reason !== undefined) {
  47. (this as Error & { cause?: unknown }).cause = reason;
  48. }
  49. }
  50. }
  51. type TimeoutOperation<T> = Promise<T> | ((signal: AbortSignal) => Promise<T> | T);
  52. export function abortReason(signal: AbortSignal): Error {
  53. return signal.reason instanceof Error ? signal.reason : new OperationAbortedError(signal.reason);
  54. }
  55. export function throwIfAborted(signal?: AbortSignal): void {
  56. if (signal?.aborted) throw abortReason(signal);
  57. }
  58. function errorCode(error: unknown): string | undefined {
  59. if (error && typeof error === 'object' && 'code' in error) {
  60. const code = (error as { code?: unknown }).code;
  61. if (typeof code === 'string') return code;
  62. }
  63. const message = error instanceof Error ? error.message : String(error);
  64. return /^([A-Z][A-Z0-9_]+):/u.exec(message)?.[1];
  65. }
  66. export function browserOperationInterruptionCode(
  67. error: unknown,
  68. ): BrowserOperationInterruptionCode | undefined {
  69. const code = errorCode(error);
  70. if (code === 'ABORTED') return 'ABORTED';
  71. if (code === 'BROWSER_TRANSPORT_CLOSED') return 'BROWSER_TRANSPORT_CLOSED';
  72. if (
  73. code === 'ACTION_TIMEOUT' ||
  74. code === 'BROWSER_OPERATION_TIMEOUT' ||
  75. code === 'BACKGROUND_RENDER_OPERATION_TIMEOUT' ||
  76. code === 'BACKGROUND_RENDER_QUEUE_TIMEOUT'
  77. ) {
  78. return 'BROWSER_OPERATION_TIMEOUT';
  79. }
  80. return undefined;
  81. }
  82. export function isBrowserOperationInterruption(error: unknown): boolean {
  83. return browserOperationInterruptionCode(error) !== undefined;
  84. }
  85. export function browserOperationFailure(error: unknown):
  86. | {
  87. success: false;
  88. code: BrowserOperationInterruptionCode;
  89. error: string;
  90. label?: string;
  91. timeoutMs?: number;
  92. }
  93. | undefined {
  94. const code = browserOperationInterruptionCode(error);
  95. if (!code) return undefined;
  96. const source = error && typeof error === 'object' ? error : {};
  97. const label = 'label' in source && typeof source.label === 'string' ? source.label : undefined;
  98. const timeoutMs =
  99. 'timeoutMs' in source &&
  100. typeof source.timeoutMs === 'number' &&
  101. Number.isFinite(source.timeoutMs)
  102. ? source.timeoutMs
  103. : undefined;
  104. return {
  105. success: false,
  106. code,
  107. error: error instanceof Error ? error.message : String(error),
  108. ...(label ? { label } : {}),
  109. ...(timeoutMs !== undefined ? { timeoutMs } : {}),
  110. };
  111. }
  112. export function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
  113. if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
  114. if (signal.aborted) return Promise.reject(abortReason(signal));
  115. return new Promise((resolve, reject) => {
  116. const onAbort = () => {
  117. clearTimeout(timer);
  118. signal.removeEventListener('abort', onAbort);
  119. reject(abortReason(signal));
  120. };
  121. const timer = setTimeout(() => {
  122. signal.removeEventListener('abort', onAbort);
  123. resolve();
  124. }, ms);
  125. signal.addEventListener('abort', onAbort, { once: true });
  126. });
  127. }
  128. /**
  129. * Runs an operation with a derived AbortSignal and a deterministic deadline.
  130. *
  131. * A timeout rejects the caller and aborts the derived signal so transports
  132. * such as the Utility Browser broker can release their pending request. The
  133. * external abort listener and timer are always removed when the race settles.
  134. */
  135. export async function withTimeout<T>(
  136. operation: TimeoutOperation<T>,
  137. timeoutMs: number,
  138. label: string,
  139. options: { signal?: AbortSignal } = {},
  140. ): Promise<T> {
  141. if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
  142. throw new RangeError(`Invalid timeout for "${label}": ${timeoutMs}`);
  143. }
  144. const controller = new AbortController();
  145. const externalSignal = options.signal;
  146. let rejectExternalAbort: ((error: OperationAbortedError) => void) | undefined;
  147. const externalAbortPromise = new Promise<never>((_resolve, reject) => {
  148. rejectExternalAbort = reject;
  149. });
  150. const onExternalAbort = () => {
  151. const error = new OperationAbortedError(externalSignal?.reason);
  152. rejectExternalAbort?.(error);
  153. controller.abort(error);
  154. };
  155. if (externalSignal?.aborted) {
  156. onExternalAbort();
  157. return externalAbortPromise;
  158. }
  159. externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
  160. let timer: ReturnType<typeof setTimeout> | undefined;
  161. const timeoutPromise = new Promise<never>((_resolve, reject) => {
  162. timer = setTimeout(() => {
  163. const error = new OperationTimeoutError(label, timeoutMs);
  164. // Reject the deadline first so a synchronous transport abort cannot
  165. // replace the structured timeout with a generic abort error.
  166. reject(error);
  167. controller.abort(error);
  168. }, timeoutMs);
  169. timer.unref?.();
  170. });
  171. const operationPromise = Promise.resolve().then(() =>
  172. typeof operation === 'function' ? operation(controller.signal) : operation,
  173. );
  174. try {
  175. return await Promise.race([operationPromise, timeoutPromise, externalAbortPromise]);
  176. } finally {
  177. if (timer) clearTimeout(timer);
  178. externalSignal?.removeEventListener('abort', onExternalAbort);
  179. }
  180. }