File size: 3,206 Bytes
338556b
 
 
 
 
 
639b859
 
 
 
 
 
338556b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
 * One read gets one deadline: the request and its body share it, so a stalled server ends in an error.
 * ⚠ About 3x the slowest healthy read: live's product workspace took 14 s on 2026-10-20.
 */
export const READ_DEADLINE_MS = 45000;

/**
 * A full workspace read carries every row's overlay cells, so it gets this longer whole-read deadline.
 * ⚠ Live's product workspace (1.9 MB) took 17 to 39 s on 2026-10-21, too close to READ_DEADLINE_MS.
 */
export const WORKSPACE_DEADLINE_MS = 110000;

/**
 * A whole-table rows read waits this long for the server's first answer, then never times its body.
 * ⚠ A healthy 66.7 MB body takes 10 to 48 s, so only a server that never answers is cut off.
 */
export const FIRST_ANSWER_DEADLINE_MS = 120000;

/** Raised when a read passes its deadline. The request is aborted first. */
export class ReadTimeoutError extends Error {
  constructor(ms: number) {
    super(`The read did not finish within ${ms} ms.`);
    this.name = "ReadTimeoutError";
  }
}

export function isReadTimeout(error: unknown): error is ReadTimeoutError {
  return error instanceof ReadTimeoutError;
}

/**
 * Abort `controller` after `ms`. `expired()` tells a deadline abort from a caller's own abort.
 * ⚠ No `AbortSignal.timeout`: some callers run in plain node and older browsers.
 */
export function armDeadline(controller: AbortController, ms: number = READ_DEADLINE_MS):
  { expired: () => boolean; disarm: () => void } {
  let expired = false;
  const timer = setTimeout(() => {
    expired = true;
    controller.abort();
  }, ms);
  // A node test must not wait for an armed deadline before it exits. Browsers have no unref.
  (timer as { unref?: () => void }).unref?.();
  return { expired: () => expired, disarm: () => clearTimeout(timer) };
}

/**
 * Fetch `url` and read its body with `read`, both under one deadline of `ms`.
 * Rejects with ReadTimeoutError at the deadline. A caller's own `init.signal` still aborts the request.
 */
export async function fetchWithDeadline<T>(
  url: string,
  init: RequestInit,
  read: (res: Response) => Promise<T>,
  ms: number = READ_DEADLINE_MS,
): Promise<{ res: Response; body: T }> {
  const controller = new AbortController();
  const outer = init.signal;
  const forward = () => controller.abort();
  if (outer) {
    if (outer.aborted) controller.abort();
    else outer.addEventListener("abort", forward);
  }
  let timer: ReturnType<typeof setTimeout> | undefined;
  // The rejection must win the race before the abort settles the read as a plain failure.
  const deadline = new Promise<never>((_, reject) => {
    timer = setTimeout(() => {
      reject(new ReadTimeoutError(ms));
      controller.abort();
    }, ms);
    (timer as { unref?: () => void }).unref?.();
  });
  const work = (async () => {
    const res = await fetch(url, { ...init, signal: controller.signal });
    return { res, body: await read(res) };
  })();
  // The loser of the race must not raise an unhandled rejection.
  work.catch(() => undefined);
  deadline.catch(() => undefined);
  try {
    return await Promise.race([work, deadline]);
  } finally {
    clearTimeout(timer);
    outer?.removeEventListener("abort", forward);
  }
}