diff --git a/packages/core/postgrest-js/src/PostgrestBuilder.ts b/packages/core/postgrest-js/src/PostgrestBuilder.ts index 82b430d752a..580c78c6f78 100644 --- a/packages/core/postgrest-js/src/PostgrestBuilder.ts +++ b/packages/core/postgrest-js/src/PostgrestBuilder.ts @@ -5,10 +5,66 @@ import type { MergePartialResult, IsValidResultOverride, } from './types/types' -import { ClientServerOptions, Fetch } from './types/common/common' +import { + ClientServerOptions, + Fetch, + DEFAULT_MAX_RETRIES, + getRetryDelay, + RETRYABLE_STATUS_CODES, + RETRYABLE_METHODS, +} from './types/common/common' import PostgrestError from './PostgrestError' import { ContainsNull } from './select-query-parser/types' +/** + * Sleep for a given number of milliseconds. + * If an AbortSignal is provided, the sleep resolves early when the signal is aborted. + */ +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal?.aborted) { + resolve() + return + } + const id = setTimeout(() => { + signal?.removeEventListener('abort', onAbort) + resolve() + }, ms) + function onAbort() { + clearTimeout(id) + resolve() + } + signal?.addEventListener('abort', onAbort) + }) +} + +/** + * Check if a request should be retried based on method and status code. + */ +function shouldRetry( + method: string, + status: number, + attemptCount: number, + retryEnabled: boolean +): boolean { + // Don't retry if retries are disabled or we've exhausted attempts + if (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) { + return false + } + + // Only retry idempotent methods (GET, HEAD, OPTIONS) + if (!RETRYABLE_METHODS.includes(method as (typeof RETRYABLE_METHODS)[number])) { + return false + } + + // Only retry on specific status codes (520 - Cloudflare errors) + if (!RETRYABLE_STATUS_CODES.includes(status as (typeof RETRYABLE_STATUS_CODES)[number])) { + return false + } + + return true +} + export default abstract class PostgrestBuilder< ClientOptions extends ClientServerOptions, Result, @@ -29,6 +85,9 @@ export default abstract class PostgrestBuilder< protected isMaybeSingle: boolean protected urlLengthLimit: number + // Retry configuration - enabled by default + protected retryEnabled: boolean = true + /** * Creates a builder configured for a specific PostgREST request. * @@ -65,6 +124,8 @@ export default abstract class PostgrestBuilder< fetch?: Fetch isMaybeSingle?: boolean urlLengthLimit?: number + // Retry option + retry?: boolean }) { this.method = builder.method this.url = builder.url @@ -75,6 +136,7 @@ export default abstract class PostgrestBuilder< this.signal = builder.signal this.isMaybeSingle = builder.isMaybeSingle ?? false this.urlLengthLimit = builder.urlLengthLimit ?? 8000 + this.retryEnabled = builder.retry ?? true if (builder.fetch) { this.fetch = builder.fetch @@ -107,9 +169,31 @@ export default abstract class PostgrestBuilder< return this } - /** * + /** * @category Database + * + * Configure retry behavior for this request. + * + * By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS) + * that fail with network errors or specific HTTP status codes (503, 520). + * Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts. + * + * @param enabled - Whether to enable retries for this request + * + * @example + * ```ts + * // Disable retries for a specific query + * const { data, error } = await supabase + * .from('users') + * .select() + * .retry(false) + * ``` */ + retry(enabled: boolean): this { + this.retryEnabled = enabled + return this + } + then< TResult1 = ThrowOnError extends true ? PostgrestResponseSuccess @@ -141,101 +225,74 @@ export default abstract class PostgrestBuilder< // NOTE: Invoke w/o `this` to avoid illegal invocation error. // https://github.com/supabase/postgrest-js/pull/247 const _fetch = this.fetch - let res = _fetch(this.url.toString(), { - method: this.method, - headers: this.headers, - body: JSON.stringify(this.body), - signal: this.signal, - }).then(async (res) => { - let error = null - let data = null - let count: number | null = null - let status = res.status - let statusText = res.statusText - - if (res.ok) { - if (this.method !== 'HEAD') { - const body = await res.text() - if (body === '') { - // Prefer: return=minimal - } else if (this.headers.get('Accept') === 'text/csv') { - data = body - } else if ( - this.headers.get('Accept') && - this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text') - ) { - data = body - } else { - data = JSON.parse(body) - } - } - const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/) - const contentRange = res.headers.get('content-range')?.split('/') - if (countHeader && contentRange && contentRange.length > 1) { - count = parseInt(contentRange[1]) - } + // Execute fetch with retry logic + const executeWithRetry = async (): Promise<{ + error: any + data: any + count: number | null + status: number + statusText: string + }> => { + let attemptCount = 0 - // Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods. - if (this.isMaybeSingle && Array.isArray(data)) { - if (data.length > 1) { - error = { - // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 - code: 'PGRST116', - details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, - hint: null, - message: 'JSON object requested, multiple (or no) rows returned', - } - data = null - count = null - status = 406 - statusText = 'Not Acceptable' - } else if (data.length === 1) { - data = data[0] - } else { - data = null - } + while (true) { + const requestHeaders = new Headers(this.headers) + if (attemptCount > 0) { + requestHeaders.set('X-Retry-Count', String(attemptCount)) } - } else { - const body = await res.text() + // Only wrap the fetch call itself — processResponse errors must never trigger retries + let res: Response try { - error = JSON.parse(body) - - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (Array.isArray(error) && res.status === 404) { - data = [] - error = null - status = 200 - statusText = 'OK' + res = await _fetch(this.url.toString(), { + method: this.method, + headers: requestHeaders, + body: JSON.stringify(this.body), + signal: this.signal, + }) + } catch (fetchError: any) { + // Never retry aborted requests + if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') { + throw fetchError + } + + // Don't retry network errors for non-idempotent methods + if (!RETRYABLE_METHODS.includes(this.method as (typeof RETRYABLE_METHODS)[number])) { + throw fetchError } - } catch { - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (res.status === 404 && body === '') { - status = 204 - statusText = 'No Content' - } else { - error = { - message: body, - } + + // Check if we should retry network errors + if (this.retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) { + const delay = getRetryDelay(attemptCount) + attemptCount++ + await sleep(delay, this.signal) + continue } + + // Exhausted retries or retries disabled, throw the last error + throw fetchError } - if (error && this.shouldThrowOnError) { - throw new PostgrestError(error) + // Check if we should retry this HTTP response + if (shouldRetry(this.method, res.status, attemptCount, this.retryEnabled)) { + const retryAfterHeader = res.headers?.get('Retry-After') ?? null + const delay = + retryAfterHeader !== null + ? Math.max(0, parseInt(retryAfterHeader, 10) || 0) * 1000 + : getRetryDelay(attemptCount) + await res.text() + attemptCount++ + await sleep(delay, this.signal) + continue } - } - const postgrestResponse = { - error, - data, - count, - status, - statusText, + return await this.processResponse(res) } + } + + let res = executeWithRetry() - return postgrestResponse - }) if (!this.shouldThrowOnError) { res = res.catch((fetchError) => { // Build detailed error information including cause if available @@ -307,6 +364,104 @@ export default abstract class PostgrestBuilder< return res.then(onfulfilled, onrejected) } + /** + * Process a fetch response and return the standardized postgrest response. + */ + private async processResponse(res: Response): Promise<{ + error: any + data: any + count: number | null + status: number + statusText: string + }> { + let error = null + let data = null + let count: number | null = null + let status = res.status + let statusText = res.statusText + + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text() + if (body === '') { + // Prefer: return=minimal + } else if (this.headers.get('Accept') === 'text/csv') { + data = body + } else if ( + this.headers.get('Accept') && + this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text') + ) { + data = body + } else { + data = JSON.parse(body) + } + } + + const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/) + const contentRange = res.headers.get('content-range')?.split('/') + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]) + } + + // Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods. + if (this.isMaybeSingle && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + } + data = null + count = null + status = 406 + statusText = 'Not Acceptable' + } else if (data.length === 1) { + data = data[0] + } else { + data = null + } + } + } else { + const body = await res.text() + + try { + error = JSON.parse(body) + + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = [] + error = null + status = 200 + statusText = 'OK' + } + } catch { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204 + statusText = 'No Content' + } else { + error = { + message: body, + } + } + } + + if (error && this.shouldThrowOnError) { + throw new PostgrestError(error) + } + } + + return { + error, + data, + count, + status, + statusText, + } + } + /** * Override the type of the returned `data`. * diff --git a/packages/core/postgrest-js/src/PostgrestClient.ts b/packages/core/postgrest-js/src/PostgrestClient.ts index 9af34bba17c..41c49f04dc6 100644 --- a/packages/core/postgrest-js/src/PostgrestClient.ts +++ b/packages/core/postgrest-js/src/PostgrestClient.ts @@ -40,6 +40,9 @@ export default class PostgrestClient< fetch?: Fetch urlLengthLimit: number + // Retry configuration - enabled by default + retry?: boolean + // TODO: Add back shouldThrowOnError once we figure out the typings /** * Creates a PostgREST client. @@ -51,6 +54,10 @@ export default class PostgrestClient< * @param options.fetch - Custom fetch * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs. * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000. + * @param options.retry - Enable or disable automatic retries for transient errors. + * When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network + * errors or HTTP 503/520 responses will be automatically retried up to 3 times + * with exponential backoff (1s, 2s, 4s). Defaults to `true`. * @example * ```ts * import { PostgrestClient } from '@supabase/postgrest-js' @@ -86,6 +93,7 @@ export default class PostgrestClient< * headers: { apikey: 'public-anon-key' }, * schema: 'public', * timeout: 30000, // 30 second timeout + * retry: false, // Disable automatic retries * }) * ``` */ @@ -97,12 +105,14 @@ export default class PostgrestClient< fetch, timeout, urlLengthLimit = 8000, + retry, }: { headers?: HeadersInit schema?: SchemaName fetch?: Fetch timeout?: number urlLengthLimit?: number + retry?: boolean } = {} ) { this.url = url @@ -151,6 +161,7 @@ export default class PostgrestClient< } else { this.fetch = originalFetch } + this.retry = retry } from< TableName extends string & keyof Schema['Tables'], @@ -179,6 +190,7 @@ export default class PostgrestClient< schema: this.schemaName, fetch: this.fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -204,6 +216,7 @@ export default class PostgrestClient< schema, fetch: this.fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -442,6 +455,7 @@ export default class PostgrestClient< body, fetch: this.fetch ?? fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } } diff --git a/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts b/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts index 34178cfe833..0b67faf2c79 100644 --- a/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts +++ b/packages/core/postgrest-js/src/PostgrestQueryBuilder.ts @@ -22,18 +22,34 @@ export default class PostgrestQueryBuilder< fetch?: Fetch urlLengthLimit: number + /** + * Enable or disable automatic retries for transient errors. + * When enabled, idempotent requests (GET/HEAD/OPTIONS) that fail with network + * errors or HTTP 503/520 responses are automatically retried with exponential + * backoff (1s, 2s, 4s, up to 3 attempts). Defaults to `true` when not specified. + */ + retry?: boolean + /** * Creates a query builder scoped to a Postgres table or view. * * @category Database * + * @param url - The URL for the query + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to use + * @param options.fetch - Custom fetch implementation + * @param options.urlLengthLimit - Maximum URL length before warning + * @param options.retry - Enable automatic retries for transient errors (default: true) + * * @example Creating a Postgrest query builder * ```ts * import { PostgrestQueryBuilder } from '@supabase/postgrest-js' * * const query = new PostgrestQueryBuilder( * new URL('https://xyzcompany.supabase.co/rest/v1/users'), - * { headers: { apikey: 'public-anon-key' } } + * { headers: { apikey: 'public-anon-key' }, retry: true } * ) * ``` */ @@ -44,11 +60,13 @@ export default class PostgrestQueryBuilder< schema, fetch, urlLengthLimit = 8000, + retry, }: { headers?: HeadersInit schema?: string fetch?: Fetch urlLengthLimit?: number + retry?: boolean } ) { this.url = url @@ -56,6 +74,7 @@ export default class PostgrestQueryBuilder< this.schema = schema this.fetch = fetch this.urlLengthLimit = urlLengthLimit + this.retry = retry } /** @@ -904,6 +923,7 @@ export default class PostgrestQueryBuilder< schema: this.schema, fetch: this.fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -1092,6 +1112,7 @@ export default class PostgrestQueryBuilder< body: values, fetch: this.fetch ?? fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -1389,6 +1410,7 @@ export default class PostgrestQueryBuilder< body: values, fetch: this.fetch ?? fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -1562,6 +1584,7 @@ export default class PostgrestQueryBuilder< body: values, fetch: this.fetch ?? fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } @@ -1710,6 +1733,7 @@ export default class PostgrestQueryBuilder< schema: this.schema, fetch: this.fetch ?? fetch, urlLengthLimit: this.urlLengthLimit, + retry: this.retry, }) } } diff --git a/packages/core/postgrest-js/src/types/common/common.ts b/packages/core/postgrest-js/src/types/common/common.ts index 9ad962ef5e2..f67ec9e98e9 100644 --- a/packages/core/postgrest-js/src/types/common/common.ts +++ b/packages/core/postgrest-js/src/types/common/common.ts @@ -2,6 +2,33 @@ export type Fetch = typeof fetch +/** + * Default number of retry attempts. + */ +export const DEFAULT_MAX_RETRIES = 3 + +/** + * Default exponential backoff delay function. + * Delays: 1s, 2s, 4s, 8s, ... (max 30s) + * + * @param attemptIndex - Zero-based index of the retry attempt + * @returns Delay in milliseconds before the next retry + */ +export const getRetryDelay = (attemptIndex: number): number => + Math.min(1000 * 2 ** attemptIndex, 30000) + +/** + * Status codes that are safe to retry. + * 520 = Cloudflare timeout/connection errors (transient) + * 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header) + */ +export const RETRYABLE_STATUS_CODES = [520, 503] as const + +/** + * HTTP methods that are safe to retry (idempotent operations). + */ +export const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'] as const + export type GenericRelationship = { foreignKeyName: string columns: string[] diff --git a/packages/core/postgrest-js/test/basic.test.ts b/packages/core/postgrest-js/test/basic.test.ts index 359e22dd7ce..58bcdeb4ce5 100644 --- a/packages/core/postgrest-js/test/basic.test.ts +++ b/packages/core/postgrest-js/test/basic.test.ts @@ -894,6 +894,16 @@ describe('basic insert, update, delete', () => { } `) }) + + afterAll(async () => { + // Restore message id 3 — the upsert test changes it to 'foo' and the delete test removes it + await postgrest.from('messages').upsert({ + id: 3, + message: 'Some message on channel without details', + username: 'supabot', + channel_id: 3, + }) + }) }) test('throwOnError throws errors instead of returning them', async () => { @@ -1329,6 +1339,13 @@ describe("insert, update, delete with count: 'exact'", () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 1, "data": null, @@ -1362,8 +1379,8 @@ describe("insert, update, delete with count: 'exact'", () => { }, ], "error": null, - "status": 201, - "statusText": "Created", + "status": 200, + "statusText": "OK", } `) @@ -1754,6 +1771,16 @@ describe("insert, update, delete with count: 'exact'", () => { } `) }) + + afterAll(async () => { + // Restore message id 3 — the upsert test changes it to 'foo' and the delete test removes it + await postgrest.from('messages').upsert({ + id: 3, + message: 'Some message on channel without details', + username: 'supabot', + channel_id: 3, + }) + }) }) test('insert includes columns param', async () => { @@ -1849,6 +1876,9 @@ test('!left join on one to many relation', async () => { { "username": "supabot", }, + { + "username": "supabot", + }, ], }, "error": null, diff --git a/packages/core/postgrest-js/test/embeded_functions_join.test.ts b/packages/core/postgrest-js/test/embeded_functions_join.test.ts index 33220716282..bd37371f33d 100644 --- a/packages/core/postgrest-js/test/embeded_functions_join.test.ts +++ b/packages/core/postgrest-js/test/embeded_functions_join.test.ts @@ -47,6 +47,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], "id": 3, }, @@ -111,6 +118,10 @@ describe('embeded functions select', () => { "id": 4, "message": "Some message on channel without details", }, + { + "id": 3, + "message": "Some message on channel without details", + }, ], "id": 3, }, @@ -167,6 +178,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], "username": "supabot", }, @@ -235,6 +253,10 @@ describe('embeded functions select', () => { "id": 4, "message": "Some message on channel without details", }, + { + "id": 3, + "message": "Some message on channel without details", + }, ], "username": "supabot", }, @@ -303,6 +325,11 @@ describe('embeded functions select', () => { "id": 4, "message": "Some message on channel without details", }, + { + "blurb_message": "Som", + "id": 3, + "message": "Some message on channel without details", + }, ], "username": "supabot", }, @@ -613,6 +640,14 @@ describe('embeded functions select', () => { "id": 4, "message": "Some message on channel without details", }, + { + "channels": { + "id": 3, + "slug": "other", + }, + "id": 3, + "message": "Some message on channel without details", + }, ], "id": 3, }, @@ -673,6 +708,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], "username": "supabot", }, @@ -750,6 +792,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], "username": "supabot", }, @@ -809,6 +858,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 2, "data": null, @@ -886,6 +942,13 @@ describe('embeded functions select', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 2, "data": null, @@ -967,6 +1030,11 @@ describe('embeded functions select', () => { "id": 4, "message": "Some message on channel without details", }, + { + "blurb_message": "Som", + "id": 3, + "message": "Some message on channel without details", + }, ], "username": "supabot", }, @@ -1061,6 +1129,13 @@ describe('embeded functions select', () => { "username": "supabot", }, }, + { + "id": 3, + "user": { + "status": "ONLINE", + "username": "supabot", + }, + }, ], "error": null, "status": 200, diff --git a/packages/core/postgrest-js/test/filters.test.ts b/packages/core/postgrest-js/test/filters.test.ts index 5fcb9e69ec6..9d29e81ee76 100644 --- a/packages/core/postgrest-js/test/filters.test.ts +++ b/packages/core/postgrest-js/test/filters.test.ts @@ -109,6 +109,9 @@ test('gt', async () => { { "id": 4, }, + { + "id": 3, + }, ], "error": null, "status": 200, @@ -132,6 +135,9 @@ test('gte', async () => { { "id": 4, }, + { + "id": 3, + }, ], "error": null, "status": 200, diff --git a/packages/core/postgrest-js/test/relationships-aggregate-operations.test.ts b/packages/core/postgrest-js/test/relationships-aggregate-operations.test.ts index dd03f832c61..1356e963e83 100644 --- a/packages/core/postgrest-js/test/relationships-aggregate-operations.test.ts +++ b/packages/core/postgrest-js/test/relationships-aggregate-operations.test.ts @@ -14,7 +14,7 @@ test('select with aggregate count function', async () => { "data": { "messages": [ { - "count": 3, + "count": 4, }, ], "username": "supabot", @@ -50,7 +50,7 @@ test('select with aggregate count on a column function', async () => { "data": { "messages": [ { - "count": 3, + "count": 4, }, ], "username": "supabot", @@ -86,7 +86,7 @@ test('select with aggregate count function and alias', async () => { "data": { "messages": [ { - "message_count": 3, + "message_count": 4, }, ], "username": "supabot", @@ -136,6 +136,11 @@ test('select with aggregate nested count function', async () => { "count": 1, }, }, + { + "channels": { + "count": 1, + }, + }, ], "username": "supabot", }, @@ -186,6 +191,11 @@ test('select with aggregate nested count function and alias', async () => { "channel_count": 1, }, }, + { + "channels": { + "channel_count": 1, + }, + }, ], "username": "supabot", }, @@ -218,7 +228,7 @@ test('select with aggregate sum function', async () => { "data": { "messages": [ { - "sum": 7, + "sum": 10, }, ], "username": "supabot", @@ -254,7 +264,7 @@ test('select with aggregate aliased sum function', async () => { "data": { "messages": [ { - "sum_id": 7, + "sum_id": 10, }, ], "username": "supabot", @@ -304,6 +314,11 @@ test('select with aggregate sum function on nested relation', async () => { "sum": 3, }, }, + { + "channels": { + "sum": 3, + }, + }, ], "username": "supabot", }, diff --git a/packages/core/postgrest-js/test/relationships-join-operations.test.ts b/packages/core/postgrest-js/test/relationships-join-operations.test.ts index 95bc60951a4..81cd49b88be 100644 --- a/packages/core/postgrest-js/test/relationships-join-operations.test.ts +++ b/packages/core/postgrest-js/test/relationships-join-operations.test.ts @@ -208,6 +208,13 @@ test('!left oneToMany', async () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], }, "error": null, diff --git a/packages/core/postgrest-js/test/relationships-spread-operations.test.ts b/packages/core/postgrest-js/test/relationships-spread-operations.test.ts index a3cb75e425d..3eee4fe7aac 100644 --- a/packages/core/postgrest-js/test/relationships-spread-operations.test.ts +++ b/packages/core/postgrest-js/test/relationships-spread-operations.test.ts @@ -35,6 +35,12 @@ test('select with aggregate count and spread', async () => { "details": null, }, }, + { + "channels": { + "count": 1, + "details": null, + }, + }, ], "username": "supabot", }, @@ -89,6 +95,12 @@ test('spread resource with single column in select query', async () => { "details": null, }, }, + { + "channels": { + "count": 1, + "details": null, + }, + }, ], "username": "supabot", }, @@ -146,6 +158,13 @@ test('spread resource with all columns in select query', async () => { "id": null, }, }, + { + "channels": { + "count": 1, + "details": null, + "id": null, + }, + }, ], "username": "supabot", }, @@ -201,6 +220,12 @@ test('select with aggregate sum and spread', async () => { "sum": 3, }, }, + { + "channels": { + "details": null, + "sum": 3, + }, + }, ], "username": "supabot", }, @@ -260,6 +285,13 @@ test('select with aggregate sum and spread on nested relation', async () => { "sum": 3, }, }, + { + "channels": { + "details": null, + "details_sum": null, + "sum": 3, + }, + }, ], "username": "supabot", }, diff --git a/packages/core/postgrest-js/test/relationships.test.ts b/packages/core/postgrest-js/test/relationships.test.ts index 2740e58aa93..6bccbbc3303 100644 --- a/packages/core/postgrest-js/test/relationships.test.ts +++ b/packages/core/postgrest-js/test/relationships.test.ts @@ -44,6 +44,10 @@ test('nested query with selective fields', async () => { "id": 4, "message": "Some message on channel without details", }, + { + "id": 3, + "message": "Some message on channel without details", + }, ], "username": "supabot", }, @@ -102,6 +106,14 @@ test('nested query with multiple levels and selective fields', async () => { "id": 4, "message": "Some message on channel without details", }, + { + "channels": { + "id": 3, + "slug": "other", + }, + "id": 3, + "message": "Some message on channel without details", + }, ], "username": "supabot", }, @@ -149,6 +161,9 @@ test('query with multiple one-to-many relationships', async () => { { "id": 4, }, + { + "id": 3, + }, ], "user_profiles": [ { @@ -229,6 +244,13 @@ test('one-to-many relationship', async () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], }, "error": null, @@ -271,6 +293,9 @@ test('one-to-many relationship with selective columns', async () => { { "data": null, }, + { + "data": null, + }, ], }, "error": null, diff --git a/packages/core/postgrest-js/test/resource-embedding.test.ts b/packages/core/postgrest-js/test/resource-embedding.test.ts index 554442a9548..fb4484bd258 100644 --- a/packages/core/postgrest-js/test/resource-embedding.test.ts +++ b/packages/core/postgrest-js/test/resource-embedding.test.ts @@ -36,6 +36,13 @@ test('embedded select', async () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], }, { @@ -110,6 +117,14 @@ test('embedded select with computed field explicit selection', async () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "blurb_message": "Som", + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, ], }, { @@ -365,6 +380,13 @@ describe('embedded transforms', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 2, "data": null, @@ -439,6 +461,13 @@ describe('embedded transforms', () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 2, "data": null, diff --git a/packages/core/postgrest-js/test/retry.test.ts b/packages/core/postgrest-js/test/retry.test.ts new file mode 100644 index 00000000000..7164d1b1d89 --- /dev/null +++ b/packages/core/postgrest-js/test/retry.test.ts @@ -0,0 +1,488 @@ +import PostgrestClient from '../src/PostgrestClient' + +describe('Automatic Retries', () => { + let fetchMock: jest.Mock + + beforeEach(() => { + fetchMock = jest.fn() + jest.useFakeTimers() + }) + + afterEach(() => { + jest.useRealTimers() + jest.restoreAllMocks() + }) + + /** + * Helper to run async code with fake timers + */ + async function runWithTimers(promise: PromiseLike): Promise { + let result: T | undefined + let error: Error | undefined + let resolved = false + + promise.then( + (r) => { + result = r + resolved = true + }, + (e) => { + error = e + resolved = true + } + ) + + // Keep advancing timers until promise resolves + while (!resolved) { + await jest.advanceTimersByTimeAsync(100) + } + + if (error) throw error + return result as T + } + + describe('default retry behavior', () => { + it('should retry GET requests on 520 errors by default', async () => { + // First two calls return 520, third succeeds + fetchMock + .mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + .mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve(JSON.stringify([{ id: 1, name: 'test' }])), + headers: new Headers(), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).toBeNull() + expect(result.data).toEqual([{ id: 1, name: 'test' }]) + expect(fetchMock).toHaveBeenCalledTimes(3) + + // Verify X-Retry-Count header was sent on retries + const [, firstRetryCall] = fetchMock.mock.calls + const firstRetryHeaders = firstRetryCall[1].headers as Headers + expect(firstRetryHeaders.get('X-Retry-Count')).toBe('1') + + const [, , secondRetryCall] = fetchMock.mock.calls + const secondRetryHeaders = secondRetryCall[1].headers as Headers + expect(secondRetryHeaders.get('X-Retry-Count')).toBe('2') + }) + + it('should NOT retry POST requests even on 520 errors', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').insert({ name: 'test' })) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + + it('should NOT retry on non-520 errors', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 500, + statusText: 'Internal Server Error', + text: () => Promise.resolve('Server error'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + + it('should stop retrying after max retries (default 3)', async () => { + // All calls return 520 + fetchMock.mockResolvedValue({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(4) // 1 initial + 3 retries + }) + }) + + describe('disabling retries', () => { + it('should not retry when retry is set to false globally', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { + fetch: fetchMock, + retry: false, + }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + + it('should not retry when retry is set to false per-request', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select().retry(false)) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + + it('per-request retry(false) should override global retry(true)', async () => { + fetchMock.mockResolvedValue({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + // Global: retries enabled (default) + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select().retry(false)) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries due to per-request override + }) + + it('per-request retry(true) should override global retry(false)', async () => { + fetchMock + .mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve(JSON.stringify([{ id: 1 }])), + headers: new Headers(), + }) + + // Global: retries disabled + const client = new PostgrestClient('http://localhost:3000', { + fetch: fetchMock, + retry: false, + }) + const result = await runWithTimers(client.from('users').select().retry(true)) + + expect(result.error).toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(2) // Retried once due to per-request override + }) + }) + + describe('exponential backoff', () => { + it('should use exponential backoff delays', async () => { + let delaysSeen: number[] = [] + const originalSleep = globalThis.setTimeout + jest.spyOn(globalThis, 'setTimeout').mockImplementation((fn, delay) => { + delaysSeen.push(delay as number) + return originalSleep(fn, 0) // Run immediately for testing + }) + + // All calls return 520 to trigger retries + fetchMock.mockResolvedValue({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + await runWithTimers(client.from('users').select()) + + // Verify exponential backoff: 1000ms, 2000ms, 4000ms + expect(delaysSeen).toContain(1000) // First retry + expect(delaysSeen).toContain(2000) // Second retry + expect(delaysSeen).toContain(4000) // Third retry + }) + }) + + describe('retry with RPC', () => { + it('should retry GET RPC calls on 520 errors', async () => { + fetchMock + .mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve(JSON.stringify({ result: 42 })), + headers: new Headers(), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.rpc('my_function', {}, { get: true })) + + expect(result.error).toBeNull() + expect(result.data).toEqual({ result: 42 }) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) + + it('should NOT retry POST RPC calls', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.rpc('my_function', { arg: 1 })) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + }) + + describe('network errors', () => { + it('should retry on network errors for GET requests', async () => { + fetchMock.mockRejectedValueOnce(new Error('Network error')).mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve(JSON.stringify([{ id: 1 }])), + headers: new Headers(), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).toBeNull() + expect(result.data).toEqual([{ id: 1 }]) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) + + it('should NOT retry on network errors for POST requests', async () => { + fetchMock.mockRejectedValueOnce(new Error('Network error')) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').insert({ name: 'test' })) + + expect(result.error).not.toBeNull() + expect(result.error?.message).toContain('Network error') + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + + it('should not retry network errors when retry is disabled', async () => { + fetchMock.mockRejectedValueOnce(new Error('Network error')) + + const client = new PostgrestClient('http://localhost:3000', { + fetch: fetchMock, + retry: false, + }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + }) + + describe('503 / PGRST002 (schema cache not ready)', () => { + it('should retry on 503 with Retry-After header and succeed', async () => { + const pgrst002Body = JSON.stringify({ + code: 'PGRST002', + details: null, + hint: null, + message: 'Could not query the database for the schema cache. Retrying.', + }) + + fetchMock + .mockResolvedValueOnce({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + headers: new Headers({ 'Retry-After': '0', 'Content-Type': 'application/json' }), + text: () => Promise.resolve(pgrst002Body), + body: { cancel: jest.fn().mockResolvedValue(undefined) }, + }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + headers: new Headers(), + text: () => Promise.resolve(JSON.stringify([{ id: 1 }])), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).toBeNull() + expect(result.data).toEqual([{ id: 1 }]) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) + + it('should surface the error if retry also returns 503', async () => { + const pgrst002Body = JSON.stringify({ + code: 'PGRST002', + details: null, + hint: null, + message: 'Could not query the database for the schema cache. Retrying.', + }) + const mockBody = { cancel: jest.fn().mockResolvedValue(undefined) } + + fetchMock.mockResolvedValue({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + headers: new Headers({ 'Retry-After': '0', 'Content-Type': 'application/json' }), + text: () => Promise.resolve(pgrst002Body), + body: mockBody, + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(result.error?.code).toBe('PGRST002') + expect(result.status).toBe(503) + expect(fetchMock).toHaveBeenCalledTimes(4) // 1 original + 3 retries + }) + + it('should drain the response body before retrying', async () => { + const textMock = jest.fn().mockResolvedValue( + JSON.stringify({ + code: 'PGRST002', + details: null, + hint: null, + message: 'err', + }) + ) + + fetchMock + .mockResolvedValueOnce({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + headers: new Headers({ 'Retry-After': '0', 'Content-Type': 'application/json' }), + text: textMock, + }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + headers: new Headers(), + text: () => Promise.resolve('[]'), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + await runWithTimers(client.from('users').select()) + + // text() is called once to drain body before retry, once by processResponse for the retry + expect(textMock).toHaveBeenCalledTimes(1) + }) + }) + + describe('AbortError handling', () => { + it('should rethrow AbortError immediately without retrying', async () => { + const abortError = new Error('The operation was aborted') + abortError.name = 'AbortError' + + fetchMock.mockRejectedValue(abortError) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + const result = await runWithTimers(client.from('users').select()) + + expect(result.error).not.toBeNull() + expect(result.error?.message).toContain('AbortError') + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries + }) + }) + + describe('shouldThrowOnError interaction', () => { + it('should NOT retry a non-retryable error with throwOnError()', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 400, + statusText: 'Bad Request', + text: () => + Promise.resolve( + JSON.stringify({ code: 'PGRST000', message: 'bad input', hint: null, details: null }) + ), + headers: new Headers(), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + await expect(runWithTimers(client.from('users').select().throwOnError())).rejects.toThrow( + 'bad input' + ) + + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries for application-level errors + }) + + it('should NOT retry a retryable status code after exhaustion when using throwOnError()', async () => { + fetchMock.mockResolvedValue({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + headers: new Headers(), + }) + + const client = new PostgrestClient('http://localhost:3000', { fetch: fetchMock }) + await expect(runWithTimers(client.from('users').select().throwOnError())).rejects.toThrow() + + expect(fetchMock).toHaveBeenCalledTimes(4) // 1 initial + 3 retries, then throws + }) + }) + + describe('schema switching', () => { + it('should preserve retry setting when switching schemas', async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 520, + statusText: 'Origin Error', + text: () => Promise.resolve('Cloudflare timeout'), + }) + + const client = new PostgrestClient('http://localhost:3000', { + fetch: fetchMock, + retry: false, + }) + const result = await runWithTimers(client.schema('other_schema').from('users').select()) + + expect(result.error).not.toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) // No retries - setting preserved + }) + }) +}) diff --git a/packages/core/postgrest-js/test/transforms.test.ts b/packages/core/postgrest-js/test/transforms.test.ts index afc08aca54c..d95d6957069 100644 --- a/packages/core/postgrest-js/test/transforms.test.ts +++ b/packages/core/postgrest-js/test/transforms.test.ts @@ -78,6 +78,13 @@ test('order on multiple columns', async () => { "message": "Some message on channel without details", "username": "supabot", }, + { + "channel_id": 3, + "data": null, + "id": 3, + "message": "Some message on channel without details", + "username": "supabot", + }, { "channel_id": 2, "data": null, @@ -236,6 +243,9 @@ test('maybeSingle', async () => { "statusText": "Not Acceptable", } `) + + // Clean up inserted users so they don't leak into other test files + await postgrest.from('users').delete().in('username', ['a', 'b']) }) test('select on insert', async () => { @@ -286,9 +296,7 @@ test('csv', async () => { kiwicopple,,"[25,35)",OFFLINE,"'bat' 'cat'" awailas,,"[25,35)",ONLINE,"'bat' 'rat'" jsonuser,"{""foo"": {""bar"": {""nested"": ""value""}, ""baz"": ""string value""}}","[20,30)",ONLINE,"'json' 'test'" - dragarcia,,"[20,30)",ONLINE,"'fat' 'rat'" - a,,,ONLINE, - b,,,ONLINE,", + dragarcia,,"[20,30)",ONLINE,"'fat' 'rat'"", "error": null, "status": 200, "statusText": "OK", diff --git a/packages/core/supabase-js/src/cors.ts b/packages/core/supabase-js/src/cors.ts index 2427e7f9b0d..54278ee0681 100644 --- a/packages/core/supabase-js/src/cors.ts +++ b/packages/core/supabase-js/src/cors.ts @@ -33,8 +33,15 @@ * - x-client-info: Library version information * - apikey: Project API key * - content-type: Standard HTTP content type + * - x-retry-count: Retry attempt number sent by postgrest-js on retried requests */ -const SUPABASE_HEADERS = ['authorization', 'x-client-info', 'apikey', 'content-type'].join(', ') +const SUPABASE_HEADERS = [ + 'authorization', + 'x-client-info', + 'apikey', + 'content-type', + 'x-retry-count', +].join(', ') /** * All HTTP methods used by the Supabase SDK diff --git a/packages/core/supabase-js/src/lib/rest/types/common/common.ts b/packages/core/supabase-js/src/lib/rest/types/common/common.ts index 8e38dd23136..a932dc43f66 100644 --- a/packages/core/supabase-js/src/lib/rest/types/common/common.ts +++ b/packages/core/supabase-js/src/lib/rest/types/common/common.ts @@ -12,6 +12,33 @@ export type Fetch = typeof fetch +/** + * Default number of retry attempts. + */ +export const DEFAULT_MAX_RETRIES = 3 + +/** + * Default exponential backoff delay function. + * Delays: 1s, 2s, 4s, 8s, ... (max 30s) + * + * @param attemptIndex - Zero-based index of the retry attempt + * @returns Delay in milliseconds before the next retry + */ +export const getRetryDelay = (attemptIndex: number): number => + Math.min(1000 * 2 ** attemptIndex, 30000) + +/** + * Status codes that are safe to retry. + * 520 = Cloudflare timeout/connection errors (transient) + * 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header) + */ +export const RETRYABLE_STATUS_CODES = [520, 503] as const + +/** + * HTTP methods that are safe to retry (idempotent operations). + */ +export const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'] as const + export type GenericRelationship = { foreignKeyName: string columns: string[] diff --git a/packages/core/supabase-js/test/unit/SupabaseClient.test.ts b/packages/core/supabase-js/test/unit/SupabaseClient.test.ts index fe35dcf40f4..1dbb997f8f3 100644 --- a/packages/core/supabase-js/test/unit/SupabaseClient.test.ts +++ b/packages/core/supabase-js/test/unit/SupabaseClient.test.ts @@ -385,6 +385,10 @@ describe('SupabaseClient', () => { const expectedToken = 'test-fetch-token' const mockFetch = jest.fn().mockResolvedValue({ ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve('{}'), + headers: new Headers(), json: () => Promise.resolve({}), }) @@ -408,7 +412,14 @@ describe('SupabaseClient', () => { const expectedToken = 'test-multi-service-token' const mockFetch = jest .fn() - .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) }) // rest + .mockResolvedValueOnce({ + ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve('{}'), + headers: new Headers(), + json: () => Promise.resolve({}), + }) // rest .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ data: [] }) }) // storage .mockResolvedValueOnce({ ok: true, @@ -438,6 +449,10 @@ describe('SupabaseClient', () => { test('should use supabaseKey fallback in fetchWithAuth', async () => { const mockFetch = jest.fn().mockResolvedValue({ ok: true, + status: 200, + statusText: 'OK', + text: () => Promise.resolve('{}'), + headers: new Headers(), json: () => Promise.resolve({}), }) diff --git a/packages/core/supabase-js/test/unit/cors.test.ts b/packages/core/supabase-js/test/unit/cors.test.ts index bcb1fc4c483..3a923c824cb 100644 --- a/packages/core/supabase-js/test/unit/cors.test.ts +++ b/packages/core/supabase-js/test/unit/cors.test.ts @@ -21,6 +21,7 @@ describe('CORS Module', () => { expect(allowedHeaders).toContain('x-client-info') expect(allowedHeaders).toContain('apikey') expect(allowedHeaders).toContain('content-type') + expect(allowedHeaders).toContain('x-retry-count') }) it('should include all HTTP methods including OPTIONS', () => {