(
fetchFn: ConnectionEffectFetch | undefined,
input: string | URL,
init: ProxiedFetchInit = {},
)
| 32 | } |
| 33 | |
| 34 | export async function fetchForConnectionEffect( |
| 35 | fetchFn: ConnectionEffectFetch | undefined, |
| 36 | input: string | URL, |
| 37 | init: ProxiedFetchInit = {}, |
| 38 | ): Promise<ConnectionEffectResponse> { |
| 39 | const { timeoutMs = 15_000, signal, ...requestInit } = init; |
| 40 | const controller = new AbortController(); |
| 41 | let timedOut = false; |
| 42 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 43 | |
| 44 | const abortFromCaller = () => { |
| 45 | if (isTimeoutReason(signal?.reason)) timedOut = true; |
| 46 | controller.abort(signal?.reason); |
| 47 | }; |
| 48 | if (signal) { |
| 49 | if (signal.aborted) abortFromCaller(); |
| 50 | else signal.addEventListener('abort', abortFromCaller, { once: true }); |
| 51 | } |
| 52 | if (timeoutMs > 0) { |
| 53 | timer = setTimeout(() => { |
| 54 | timedOut = true; |
| 55 | controller.abort(new ConnectionEffectFetchError('timeout')); |
| 56 | }, timeoutMs); |
| 57 | } |
| 58 | |
| 59 | try { |
| 60 | // Own the timeout above both transports so it remains active until the |
| 61 | // response body is consumed or cancelled. proxiedFetch's native timeout |
| 62 | // ends at headers because it also serves streaming callers. |
| 63 | const response = fetchFn |
| 64 | ? await fetchFn(input, { |
| 65 | ...requestInit, |
| 66 | signal: controller.signal, |
| 67 | } as RequestInit) |
| 68 | : await proxiedFetch(input.toString(), { |
| 69 | ...requestInit, |
| 70 | signal: controller.signal, |
| 71 | timeoutMs: 0, |
| 72 | }); |
| 73 | return manageConnectionEffectResponse(response, { |
| 74 | didTimeOut: () => timedOut, |
| 75 | finish: () => { |
| 76 | if (timer) clearTimeout(timer); |
| 77 | signal?.removeEventListener('abort', abortFromCaller); |
| 78 | }, |
| 79 | }); |
| 80 | } catch (error) { |
| 81 | if (timer) clearTimeout(timer); |
| 82 | signal?.removeEventListener('abort', abortFromCaller); |
| 83 | throw connectionEffectFetchFailure(error, timedOut); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | function manageConnectionEffectResponse( |
| 88 | response: Response, |
no test coverage detected