Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

fetch.ts

564 lines16.9 KB

1import {
2 CHUNK_LAST_OFFSET_HEADER,
3 CHUNK_UP_TO_DATE_HEADER,
4 EXPIRED_HANDLE_QUERY_PARAM,
5 LIVE_CACHE_BUSTER_HEADER,
6 LIVE_QUERY_PARAM,
7 OFFSET_QUERY_PARAM,
8 SHAPE_SCHEMA_HEADER,
9 SHAPE_HANDLE_HEADER,
10 SHAPE_HANDLE_QUERY_PARAM,
11 SNAPSHOT_HEADER,
12 SUBSET_PARAM_LIMIT,
13 SUBSET_PARAM_OFFSET,
14 SUBSET_PARAM_ORDER_BY,
15 SUBSET_PARAM_WHERE,
16 SUBSET_PARAM_WHERE_PARAMS,
17} from './constants'
18import {
19 FetchError,
20 FetchBackoffAbortError,
21 MissingHeadersError,
22} from './error'
23​
24// Some specific 4xx and 5xx HTTP status codes that we definitely
25// want to retry
26const HTTP_RETRY_STATUS_CODES = [429]
27​
28export interface BackoffOptions {
29 /**
30 * Initial delay before retrying in milliseconds
31 */
32 initialDelay: number
33 /**
34 * Maximum retry delay in milliseconds
35 * After reaching this, delay stays constant (e.g., retry every 60s)
36 */
37 maxDelay: number
38 multiplier: number
39 onFailedAttempt?: () => void
40 debug?: boolean
41 /**
42 * Maximum number of retry attempts before giving up.
43 * Set to Infinity (default) for indefinite retries - needed for offline scenarios
44 * where clients may go offline and come back later.
45 */
46 maxRetries?: number
48​
49export const BackoffDefaults = {
50 initialDelay: 1_000,
51 maxDelay: 32_000,
52 multiplier: 2,
53 maxRetries: Infinity, // Retry forever - clients may go offline and come back
55​
56/**
57 * Parse Retry-After header value and return delay in milliseconds
58 * Supports both delta-seconds format and HTTP-date format
59 * Returns 0 if header is not present or invalid
60 */
61export function parseRetryAfterHeader(retryAfter: string | undefined): number {
62 if (!retryAfter) return 0
63​
64 // Try parsing as seconds (delta-seconds format)
65 const retryAfterSec = Number(retryAfter)
66 if (Number.isFinite(retryAfterSec) && retryAfterSec > 0) {
67 return retryAfterSec * 1000
68 }
69​
70 // Try parsing as HTTP-date
71 const retryDate = Date.parse(retryAfter)
72 if (!isNaN(retryDate)) {
73 // Handle clock skew: clamp to non-negative, cap at reasonable max
74 const deltaMs = retryDate - Date.now()
75 return Math.max(0, Math.min(deltaMs, 3600_000)) // Cap at 1 hour
76 }
77​
78 return 0
80​
81async function abortableSleep(
82 waitMs: number,
83 signal?: AbortSignal
84): Promise<void> {
85 if (waitMs <= 0) return
86 if (signal?.aborted) throw new FetchBackoffAbortError()
87​
88 await new Promise<void>((resolve, reject) => {
89 let settled = false
90 const done = (err?: Error) => {
91 if (settled) return
92 settled = true
93 clearTimeout(timer)
94 signal?.removeEventListener(`abort`, onAbort)
95 err ? reject(err) : resolve()
96 }
97 const onAbort = () => done(new FetchBackoffAbortError())
98 const timer = setTimeout(() => done(), waitMs)
99 signal?.addEventListener(`abort`, onAbort, { once: true })
100 if (signal?.aborted) onAbort()
101 })
103​
104export function createFetchWithBackoff(
105 fetchClient: typeof fetch,
106 backoffOptions: BackoffOptions = BackoffDefaults
107): typeof fetch {
108 const {
109 initialDelay,
110 maxDelay,
111 multiplier,
112 debug = false,
113 onFailedAttempt,
114 maxRetries = Infinity,
115 } = backoffOptions
116 return async (...args: Parameters<typeof fetch>): Promise<Response> => {
117 const url = args[0]
118 const options = args[1]
119​
120 let delay = initialDelay
121 let attempt = 0
122​
123 while (true) {
124 try {
125 const result = await fetchClient(...args)
126 if (result.ok) {
127 return result
128 }
129​
130 const err = await FetchError.fromResponse(result, url.toString())
131​
132 throw err
133 } catch (e) {
134 onFailedAttempt?.()
135 if (options?.signal?.aborted) {
136 throw new FetchBackoffAbortError()
137 } else if (
138 e instanceof FetchError &&
139 !HTTP_RETRY_STATUS_CODES.includes(e.status) &&
140 e.status >= 400 &&
141 e.status < 500
142 ) {
143 // Any client errors cannot be backed off on, leave it to the caller to handle.
144 throw e
145 } else {
146 // Check max retries
147 attempt++
148 if (attempt > maxRetries) {
149 if (debug) {
150 console.log(
151 `Max retries reached (${attempt}/${maxRetries}), giving up`
152 )
153 }
154 throw e
155 }
156​
157 // Calculate wait time honoring server-driven backoff as a floor
158 // Precedence: max(serverMinimum, min(clientMaxDelay, backoffWithJitter))
159​
160 // 1. Parse server-provided Retry-After (if present)
161 const serverMinimumMs =
162 e instanceof FetchError && e.headers
163 ? parseRetryAfterHeader(e.headers[`retry-after`])
164 : 0
165​
166 // 2. Calculate client backoff with full jitter strategy
167 // Full jitter: random_between(0, min(cap, exponential_backoff))
168 // See: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
169 const jitter = Math.random() * delay // random value between 0 and current delay
170 const clientBackoffMs = Math.min(jitter, maxDelay) // cap at maxDelay
171​
172 // 3. Server minimum is the floor, client cap is the ceiling
173 const waitMs = Math.max(serverMinimumMs, clientBackoffMs)
174​
175 if (debug) {
176 const source = serverMinimumMs > 0 ? `server+client` : `client`
177 console.log(
178 `Retry attempt #${attempt} after ${waitMs}ms (${source}, serverMin=${serverMinimumMs}ms, clientBackoff=${clientBackoffMs}ms)`
179 )
180 }
181​
182 // Wait for the calculated duration, but let stream-level aborts
183 // interrupt the backoff immediately (e.g. system wake reconnects).
184 await abortableSleep(waitMs, options?.signal ?? undefined)
185​
186 // Increase the delay for the next attempt (capped at maxDelay)
187 delay = Math.min(delay * multiplier, maxDelay)
188 }
189 }
190 }
191 }
193​
194const NO_BODY_STATUS_CODES = [201, 204, 205]
195​
196export async function consumeResponseBody(
197 res: Response,
198 url: string,
199 signal?: AbortSignal
200): Promise<Response> {
201 try {
202 if (res.status < 200 || NO_BODY_STATUS_CODES.includes(res.status)) {
203 return res
204 }
205​
206 const text = await res.text()
207 return new Response(text, res)
208 } catch (err) {
209 if (signal?.aborted) {
210 throw new FetchBackoffAbortError()
211 }
212​
213 throw new FetchError(
214 res.status,
215 undefined,
216 undefined,
217 Object.fromEntries([...res.headers.entries()]),
218 url,
219 err instanceof Error
220 ? err.message
221 : typeof err === `string`
222 ? err
223 : `failed to read body`
224 )
225 }
227​
228// Ensure body can actually be read in its entirety
229export function createFetchWithConsumedMessages(fetchClient: typeof fetch) {
230 return async (...args: Parameters<typeof fetch>): Promise<Response> => {
231 const url = args[0]
232 const res = await fetchClient(...args)
233 return consumeResponseBody(
234 res,
235 url.toString(),
236 args[1]?.signal ?? undefined
237 )
238 }
240​
241interface ChunkPrefetchOptions {
242 maxChunksToPrefetch: number
244​
245const ChunkPrefetchDefaults = {
246 maxChunksToPrefetch: 2,
248​
249/**
250 * Creates a fetch client that prefetches subsequent log chunks for
251 * consumption by the shape stream without waiting for the chunk bodies
252 * themselves to be loaded.
253 *
254 * @param fetchClient the client to wrap
255 * @param prefetchOptions options to configure prefetching
256 * @returns wrapped client with prefetch capabilities
257 */
258export function createFetchWithChunkBuffer(
259 fetchClient: typeof fetch,
260 prefetchOptions: ChunkPrefetchOptions = ChunkPrefetchDefaults
261): typeof fetch {
262 const { maxChunksToPrefetch } = prefetchOptions
263​
264 let prefetchQueue: PrefetchQueue | undefined
265​
266 const prefetchClient = async (...args: Parameters<typeof fetchClient>) => {
267 const url = args[0].toString()
268 const method = getRequestMethod(args[0], args[1])
269​
270 // Prefetch is only valid for GET requests. The prefetch queue matches
271 // requests by URL alone and ignores HTTP method/body, so a POST request
272 // with the same URL would incorrectly consume the prefetched stream
273 // response instead of making its own request.
274 if (method !== `GET`) {
275 prefetchQueue?.abort()
276 prefetchQueue = undefined
277 return fetchClient(...args)
278 }
279​
280 // try to consume from the prefetch queue first, and if request is
281 // not present abort the prefetch queue as it must no longer be valid
282 const prefetchedRequest = prefetchQueue?.consume(...args)
283 if (prefetchedRequest) {
284 return prefetchedRequest
285 }
286​
287 // Clear the prefetch queue after aborting to prevent returning
288 // stale/aborted requests on future calls with the same URL
289 prefetchQueue?.abort()
290 prefetchQueue = undefined
291​
292 // perform request and fire off prefetch queue if request is eligible
293 const response = await fetchClient(...args)
294 const nextUrl = getNextChunkUrl(url, response)
295 if (nextUrl) {
296 prefetchQueue = new PrefetchQueue({
297 fetchClient,
298 maxPrefetchedRequests: maxChunksToPrefetch,
299 url: nextUrl,
300 requestInit: args[1],
301 })
302 }
303​
304 return response
305 }
306​
307 return prefetchClient
309​
310export const requiredElectricResponseHeaders = [
311 CHUNK_LAST_OFFSET_HEADER,
312 SHAPE_HANDLE_HEADER,
314​
315export const requiredLiveResponseHeaders = [LIVE_CACHE_BUSTER_HEADER]
316​
317export const requiredNonLiveResponseHeaders = [SHAPE_SCHEMA_HEADER]
318​
319export function createFetchWithResponseHeadersCheck(
320 fetchClient: typeof fetch
321): typeof fetch {
322 return async (...args: Parameters<typeof fetchClient>) => {
323 const response = await fetchClient(...args)
324​
325 if (response.ok) {
326 // Check that the necessary Electric headers are present on the response
327 const headers = response.headers
328 const missingHeaders: Array<string> = []
329​
330 const addMissingHeaders = (requiredHeaders: Array<string>) =>
331 missingHeaders.push(...requiredHeaders.filter((h) => !headers.has(h)))
332​
333 const input = args[0]
334 const urlString = input.toString()
335 const url = new URL(urlString)
336​
337 // Snapshot responses (subset params) return a JSON object and do not include Electric chunk headers
338 const isSnapshotRequest = [
339 SUBSET_PARAM_WHERE,
340 SUBSET_PARAM_WHERE_PARAMS,
341 SUBSET_PARAM_LIMIT,
342 SUBSET_PARAM_OFFSET,
343 SUBSET_PARAM_ORDER_BY,
344 ].some((p) => url.searchParams.has(p))
345 if (isSnapshotRequest) {
346 return response
347 }
348​
349 addMissingHeaders(requiredElectricResponseHeaders)
350 if (url.searchParams.get(LIVE_QUERY_PARAM) === `true`) {
351 addMissingHeaders(requiredLiveResponseHeaders)
352 }
353​
354 if (
355 !url.searchParams.has(LIVE_QUERY_PARAM) ||
356 url.searchParams.get(LIVE_QUERY_PARAM) === `false`
357 ) {
358 addMissingHeaders(requiredNonLiveResponseHeaders)
359 }
360​
361 if (missingHeaders.length > 0) {
362 throw new MissingHeadersError(urlString, missingHeaders)
363 }
364 }
365​
366 return response
367 }
369​
370class PrefetchQueue {
371 readonly #fetchClient: typeof fetch
372 readonly #maxPrefetchedRequests: number
373 readonly #prefetchQueue = new Map<
374 string,
375 [Promise<Response>, AbortController]
376 >()
377 #queueHeadUrl: string | void
378 #queueTailUrl: string | void
379​
380 constructor(options: {
381 url: Parameters<typeof fetch>[0]
382 requestInit: Parameters<typeof fetch>[1]
383 maxPrefetchedRequests: number
384 fetchClient?: typeof fetch
385 }) {
386 this.#fetchClient =
387 options.fetchClient ??
388 ((...args: Parameters<typeof fetch>) => fetch(...args))
389 this.#maxPrefetchedRequests = options.maxPrefetchedRequests
390 this.#queueHeadUrl = options.url.toString()
391 this.#queueTailUrl = this.#queueHeadUrl
392 this.#prefetch(options.url, options.requestInit)
393 }
394​
395 abort(): void {
396 this.#prefetchQueue.forEach(([_, aborter]) => aborter.abort())
397 this.#prefetchQueue.clear()
398 }
399​
400 consume(...args: Parameters<typeof fetch>): Promise<Response> | void {
401 const url = args[0].toString()
402​
403 const entry = this.#prefetchQueue.get(url)
404 // only consume if request is in queue and is the queue "head"
405 // if request is in the queue but not the head, the queue is being
406 // consumed out of order and should be restarted
407 if (!entry || url !== this.#queueHeadUrl) return
408​
409 const [request, aborter] = entry
410 // Don't return aborted requests - they will reject with AbortError
411 if (aborter.signal.aborted) {
412 this.#prefetchQueue.delete(url)
413 return
414 }
415 this.#prefetchQueue.delete(url)
416​
417 // fire off new prefetch since request has been consumed
418 request
419 .then((response) => {
420 const nextUrl = getNextChunkUrl(url, response)
421 this.#queueHeadUrl = nextUrl
422 if (
423 this.#queueTailUrl &&
424 !this.#prefetchQueue.has(this.#queueTailUrl)
425 ) {
426 this.#prefetch(this.#queueTailUrl, args[1])
427 }
428 })
429 .catch(() => {})
430​
431 return request
432 }
433​
434 #prefetch(...args: Parameters<typeof fetch>): void {
435 const url = args[0].toString()
436​
437 // only prefetch when queue is not full
438 if (this.#prefetchQueue.size >= this.#maxPrefetchedRequests) return
439​
440 // initialize aborter per request, to avoid aborting consumed requests that
441 // are still streaming their bodies to the consumer
442 const aborter = new AbortController()
443​
444 try {
445 const { signal, cleanup } = chainAborter(aborter, args[1]?.signal)
446 const request = this.#fetchClient(url, { ...(args[1] ?? {}), signal })
447 this.#prefetchQueue.set(url, [request, aborter])
448 request
449 .then((response) => {
450 // only keep prefetching if response chain is uninterrupted
451 if (!response.ok || aborter.signal.aborted) return
452​
453 const nextUrl = getNextChunkUrl(url, response)
454​
455 // only prefetch when there is a next URL
456 if (!nextUrl || nextUrl === url) {
457 this.#queueTailUrl = undefined
458 return
459 }
460​
461 this.#queueTailUrl = nextUrl
462 return this.#prefetch(nextUrl, args[1])
463 })
464 .catch(() => {})
465 .finally(cleanup)
466 } catch (_) {
467 // ignore prefetch errors
468 }
469 }
471​
472/**
473 * Generate the next chunk's URL if the url and response are valid
474 */
475function getNextChunkUrl(url: string, res: Response): string | void {
476 const shapeHandle = res.headers.get(SHAPE_HANDLE_HEADER)
477 const lastOffset = res.headers.get(CHUNK_LAST_OFFSET_HEADER)
478 const isUpToDate = res.headers.has(CHUNK_UP_TO_DATE_HEADER)
479 const isSnapshot = res.headers.get(SNAPSHOT_HEADER) === `true`
480​
481 // only prefetch if shape handle and offset for next chunk are available, and
482 // response is not already up-to-date
483 // snapshot (subset) responses are one-shot and must never be prefetched:
484 // there is no "next chunk" URL for them, only a repeat of the same request
485 if (!shapeHandle || !lastOffset || isUpToDate || isSnapshot) return
486​
487 const nextUrl = new URL(url)
488​
489 // don't prefetch live requests, rushing them will only
490 // potentially miss more recent data
491 if (nextUrl.searchParams.has(LIVE_QUERY_PARAM)) return
492​
493 // don't prefetch if the response handle is the expired handle from the request
494 // this can happen when a proxy serves a stale cached response despite the
495 // expired_handle cache buster parameter
496 const expiredHandle = nextUrl.searchParams.get(EXPIRED_HANDLE_QUERY_PARAM)
497 if (expiredHandle && shapeHandle === expiredHandle) {
498 console.warn(
499 `[Electric] Received stale cached response with expired shape handle. ` +
500 `This should not happen and indicates a proxy/CDN caching misconfiguration. ` +
501 `The response contained handle "${shapeHandle}" which was previously marked as expired. ` +
502 `Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. ` +
503 `Skipping prefetch to prevent infinite 409 loop.`
504 )
505 return
506 }
507​
508 nextUrl.searchParams.set(SHAPE_HANDLE_QUERY_PARAM, shapeHandle)
509 nextUrl.searchParams.set(OFFSET_QUERY_PARAM, lastOffset)
510 nextUrl.searchParams.sort()
511 return nextUrl.toString()
513​
514/**
515 * Chains an abort controller on an optional source signal's
516 * aborted state - if the source signal is aborted, the provided abort
517 * controller will also abort
518 */
519function chainAborter(
520 aborter: AbortController,
521 sourceSignal?: AbortSignal | null
522): {
523 signal: AbortSignal
524 cleanup: () => void
525} {
526 let cleanup = noop
527 if (!sourceSignal) {
528 // no-op, nothing to chain to
529 } else if (sourceSignal.aborted) {
530 // source signal is already aborted, abort immediately
531 aborter.abort()
532 } else {
533 // chain to source signal abort event, and add callback to unlink
534 // the aborter to avoid memory leaks
535 const abortParent = () => aborter.abort()
536 sourceSignal.addEventListener(`abort`, abortParent, {
537 once: true,
538 signal: aborter.signal,
539 })
540 cleanup = () => sourceSignal.removeEventListener(`abort`, abortParent)
541 }
542​
543 return {
544 signal: aborter.signal,
545 cleanup,
546 }
548​
549function noop() {}
550​
551function getRequestMethod(
552 input: Parameters<typeof fetch>[0],
553 init?: Parameters<typeof fetch>[1]
554): string {
555 if (init?.method) {
556 return init.method.toUpperCase()
557 }
558​
559 if (typeof Request !== `undefined` && input instanceof Request) {
560 return input.method.toUpperCase()
561 }
562​
563 return `GET`