diff --git a/packages/worker/src/dr/backup-s3.node.test.ts b/packages/worker/src/dr/backup-s3.node.test.ts new file mode 100644 index 0000000000..878efe6d1e --- /dev/null +++ b/packages/worker/src/dr/backup-s3.node.test.ts @@ -0,0 +1,157 @@ +import { expect, test, vi } from 'vitest' +import { + createDrBackupS3Client, + DrBackupPreconditionFailedError, + isTransientDrBackupHttpStatus, + readDrBackupS3Config, +} from './backup-s3.ts' + +const config = { + accountId: 'acct', + bucketName: 'backups', + accessKeyId: 'key', + secretAccessKey: 'secret', +} + +function jsonResponse( + status: number, + body = '', + headers: Record = {}, +) { + return new Response(body, { status, headers }) +} + +test('isTransientDrBackupHttpStatus matches platform blips only', () => { + expect(isTransientDrBackupHttpStatus(429)).toBe(true) + expect(isTransientDrBackupHttpStatus(500)).toBe(true) + expect(isTransientDrBackupHttpStatus(502)).toBe(true) + expect(isTransientDrBackupHttpStatus(503)).toBe(true) + expect(isTransientDrBackupHttpStatus(504)).toBe(true) + expect(isTransientDrBackupHttpStatus(400)).toBe(false) + expect(isTransientDrBackupHttpStatus(403)).toBe(false) + expect(isTransientDrBackupHttpStatus(404)).toBe(false) + expect(isTransientDrBackupHttpStatus(412)).toBe(false) + expect(isTransientDrBackupHttpStatus(200)).toBe(false) +}) + +test('put retries transient HTTP 500 then succeeds', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(jsonResponse(500, 'blip')) + .mockResolvedValueOnce(jsonResponse(200, '', { etag: '"etag-1"' })) + + const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, { + maxAttempts: 3, + baseDelayMs: 1, + }) + await expect( + client.put('staging/day/exporter/progress.json', '{}', { + contentType: 'application/json', + ifMatch: '"prev"', + }), + ).resolves.toEqual({ etag: '"etag-1"' }) + expect(fetchImpl).toHaveBeenCalledTimes(2) + const secondInit = fetchImpl.mock.calls[1]?.[0] as Request + expect(secondInit.method).toBe('PUT') + expect(secondInit.headers.get('If-Match')).toBe('"prev"') +}) + +test('put does not retry precondition failures', async () => { + const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(412, 'conflict')) + const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, { + maxAttempts: 4, + baseDelayMs: 1, + }) + await expect( + client.put('staging/day/exporter/progress.json', '{}', { + ifMatch: '"prev"', + }), + ).rejects.toBeInstanceOf(DrBackupPreconditionFailedError) + expect(fetchImpl).toHaveBeenCalledTimes(1) +}) + +test('put retries transport errors then surfaces exhausted failures', async () => { + const fetchImpl = vi + .fn() + .mockRejectedValueOnce(new TypeError('network down')) + .mockResolvedValueOnce(jsonResponse(500, 'still bad')) + .mockResolvedValueOnce(jsonResponse(500, 'still bad')) + + const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, { + maxAttempts: 3, + baseDelayMs: 1, + }) + await expect(client.put('key', 'body')).rejects.toThrow( + 'DR backup PUT failed for key: HTTP 500', + ) + expect(fetchImpl).toHaveBeenCalledTimes(3) +}) + +test('head, getText, and getBytes retry transient 503 responses', async () => { + const headFetch = vi + .fn() + .mockResolvedValueOnce(jsonResponse(503)) + .mockResolvedValueOnce(jsonResponse(200, '', { etag: '"h"' })) + const headClient = createDrBackupS3Client(config, headFetch as typeof fetch, { + maxAttempts: 2, + baseDelayMs: 1, + }) + await expect(headClient.head('blob')).resolves.toEqual({ + exists: true, + status: 200, + etag: '"h"', + }) + expect(headFetch).toHaveBeenCalledTimes(2) + + const getFetch = vi + .fn() + .mockResolvedValueOnce(jsonResponse(503, 'busy')) + .mockResolvedValueOnce(jsonResponse(200, '{"ok":true}', { etag: '"g"' })) + const getClient = createDrBackupS3Client(config, getFetch as typeof fetch, { + maxAttempts: 2, + baseDelayMs: 1, + }) + await expect(getClient.getText('progress.json')).resolves.toEqual({ + text: '{"ok":true}', + etag: '"g"', + }) + expect(getFetch).toHaveBeenCalledTimes(2) + + const bytesFetch = vi + .fn() + .mockResolvedValueOnce(jsonResponse(503, 'busy')) + .mockResolvedValueOnce(jsonResponse(200, 'abc', { etag: '"b"' })) + const bytesClient = createDrBackupS3Client( + config, + bytesFetch as typeof fetch, + { maxAttempts: 2, baseDelayMs: 1 }, + ) + await expect(bytesClient.getBytes('blob.bin')).resolves.toEqual( + new Uint8Array([97, 98, 99]), + ) + expect(bytesFetch).toHaveBeenCalledTimes(2) +}) + +test('readDrBackupS3Config requires all fields', () => { + expect( + readDrBackupS3Config({ + DR_BACKUP_ACCOUNT_ID: 'a', + DR_BACKUP_BUCKET_NAME: 'b', + DR_BACKUP_ACCESS_KEY_ID: 'c', + DR_BACKUP_SECRET_ACCESS_KEY: 'd', + }), + ).toEqual({ + accountId: 'a', + bucketName: 'b', + accessKeyId: 'c', + secretAccessKey: 'd', + }) + expect( + readDrBackupS3Config({ + DR_BACKUP_ACCOUNT_ID: 'a', + DR_BACKUP_BUCKET_NAME: '', + DR_BACKUP_ACCESS_KEY_ID: 'c', + DR_BACKUP_SECRET_ACCESS_KEY: 'd', + }), + ).toBeNull() +}) diff --git a/packages/worker/src/dr/backup-s3.ts b/packages/worker/src/dr/backup-s3.ts index 35e75b9422..0ca71b4a45 100644 --- a/packages/worker/src/dr/backup-s3.ts +++ b/packages/worker/src/dr/backup-s3.ts @@ -42,6 +42,28 @@ export type DrBackupS3Client = { ) => Promise<{ etag: string | null }> } +/** R2/S3 platform blips observed on PutObject (and siblings) during cron ticks. */ +export const drBackupS3RetryMaxAttempts = 4 +export const drBackupS3RetryBaseDelayMs = 150 + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +/** + * Transient R2/S3 HTTP statuses worth retrying. 412 stays non-retryable so + * conditional progress.json ownership conflicts surface immediately. + */ +export function isTransientDrBackupHttpStatus(status: number) { + return ( + status === 429 || + status === 500 || + status === 502 || + status === 503 || + status === 504 + ) +} + function objectUrl(config: DrBackupS3Config, key: string) { const encodedKey = key .split('/') @@ -55,9 +77,21 @@ function readEtag(response: Response): string | null { return etag && etag.length > 0 ? etag : null } +async function drainResponseBody(response: Response) { + try { + await response.arrayBuffer() + } catch { + // Best-effort: free the connection before the next attempt. + } +} + export function createDrBackupS3Client( config: DrBackupS3Config, fetchImpl: typeof fetch = fetch, + options?: { + maxAttempts?: number + baseDelayMs?: number + }, ): DrBackupS3Client { const aws = new AwsClient({ accessKeyId: config.accessKeyId, @@ -65,15 +99,43 @@ export function createDrBackupS3Client( service: 's3', region: 'auto', }) + const maxAttempts = options?.maxAttempts ?? drBackupS3RetryMaxAttempts + const baseDelayMs = options?.baseDelayMs ?? drBackupS3RetryBaseDelayMs async function signedFetch(key: string, init?: RequestInit) { const request = await aws.sign(objectUrl(config, key), init) return fetchImpl(request) } + /** + * Retry transport / platform blips. Conditional headers are preserved on + * each attempt: a phantom success that still 412s on retry is handled by + * callers as `DrBackupPreconditionFailedError` (safe skip / resume). + */ + async function signedFetchWithRetry(key: string, init?: RequestInit) { + let lastError: unknown + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const response = await signedFetch(key, init) + if ( + !isTransientDrBackupHttpStatus(response.status) || + attempt === maxAttempts + ) { + return response + } + await drainResponseBody(response) + } catch (error) { + lastError = error + if (attempt === maxAttempts) throw error + } + await sleep(baseDelayMs * 2 ** (attempt - 1)) + } + throw lastError ?? new Error('DR backup request failed after retries') + } + return { async head(key) { - const response = await signedFetch(key, { method: 'HEAD' }) + const response = await signedFetchWithRetry(key, { method: 'HEAD' }) if (response.status === 404) { return { exists: false, status: response.status, etag: null } } @@ -89,7 +151,7 @@ export function createDrBackupS3Client( } }, async getText(key) { - const response = await signedFetch(key, { method: 'GET' }) + const response = await signedFetchWithRetry(key, { method: 'GET' }) if (response.status === 404) return null if (!response.ok) { throw new Error( @@ -102,7 +164,7 @@ export function createDrBackupS3Client( } }, async getBytes(key) { - const response = await signedFetch(key, { method: 'GET' }) + const response = await signedFetchWithRetry(key, { method: 'GET' }) if (response.status === 404) return null if (!response.ok) { throw new Error( @@ -121,7 +183,7 @@ export function createDrBackupS3Client( if (options.ifNoneMatch) { headers['If-None-Match'] = options.ifNoneMatch } - const response = await signedFetch(key, { + const response = await signedFetchWithRetry(key, { method: 'PUT', headers, body: body as BodyInit,