import { describe, expect, test, vi } from 'vitest'; import { AbortError } from '@embedpdf/engine-core/runtime'; import { API_VERSION } from '@embedpdf/engine-core/wire'; import { HttpClient } from '../src/transport/HttpClient'; /** * Transport backpressure + the `X-CloudPDF-Doc` affinity header (see * `cloudpdf/server/deploy/helm/DEPLOY.md`, "Load balancing & doc affinity"). * * Retry is keyed on our 503 codes (`EngineBusy`, `EngineRestarting`) — * both mean nothing happened server-side, so retrying is * method-agnostic-safe. Foreign 503s are returned without a retry. */ type FetchStep = | { status: number; body?: unknown; headers?: Record } | ((url: string, init: RequestInit) => Response); function scriptedFetch(steps: FetchStep[]): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; init: RequestInit }>; } { const calls: Array<{ url: string; init: RequestInit }> = []; const fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => { calls.push({ url: String(url), init: init ?? {} }); const step = steps[Math.min(calls.length - 1, steps.length - 1)]!; if (typeof step === 'function') return step(String(url), init ?? {}); return new Response(step.body === undefined ? null : JSON.stringify(step.body), { status: step.status, headers: { 'content-type': 'application/json', ...(step.headers ?? {}) }, }); }) as unknown as typeof globalThis.fetch; return { fetch, calls }; } const busy503 = (retryAfter = '0'): FetchStep => ({ status: 503, body: { error: { code: 'EngineBusy', message: 'shed' } }, headers: { 'retry-after': retryAfter }, }); function client(fetch: typeof globalThis.fetch, extra: Record = {}): HttpClient { return new HttpClient({ baseUrl: 'https://api.example.test', fetch, ...extra }); } const signal = (): AbortSignal => new AbortController().signal; describe('code-keyed 503 retry', () => { test('EngineBusy then 200 → one retry, result returned', async () => { const { fetch, calls } = scriptedFetch([busy503(), { status: 200, body: { ok: true } }]); const retries: Array<{ code: string; attempt: number }> = []; const http = client(fetch, { onRetry: (i: { code: string; attempt: number }) => retries.push(i), }); const out = await http.getJson('/v1/docs/d1/head', (raw) => raw as { ok: boolean }, signal()); expect(out).toEqual({ ok: true }); expect(calls).toHaveLength(2); expect(retries).toEqual([{ code: 'EngineBusy', attempt: 0, ...retries[0] }]); }); test('EngineRestarting retries too — mutations included (nothing was applied)', async () => { const { fetch, calls } = scriptedFetch([ { status: 503, body: { error: { code: 'EngineRestarting', message: 'respawning' } }, headers: { 'retry-after': '0' }, }, { status: 200, body: { done: 1 } }, ]); const http = client(fetch); const out = await http.postJson( '/v1/docs/d1/x', { a: 1 }, (raw) => raw as { done: number }, signal(), ); expect(out).toEqual({ done: 1 }); expect(calls).toHaveLength(2); // The body was re-sent equivalently on the retry. expect(calls[1]!.init.body).toBe(calls[0]!.init.body); }); test('a FOREIGN 503 (no engine code) keeps old semantics — no retry', async () => { const { fetch, calls } = scriptedFetch([ { status: 503, body: { message: 'proxy says no' } }, { status: 200, body: { never: true } }, ]); const http = client(fetch); await expect(http.getJson('/v1/docs/d1/head', (raw) => raw, signal())).rejects.toThrow(); expect(calls).toHaveLength(1); }); test('exhaustion: after 2 retries the third 503 surfaces as the error', async () => { const { fetch, calls } = scriptedFetch([busy503(), busy503(), busy503()]); const http = client(fetch); await expect(http.getJson('/v1/docs/d1/head', (raw) => raw, signal())).rejects.toThrow(); expect(calls).toHaveLength(3); // 1 + MAX_RETRIES }); test('abort during the wait rejects immediately with AbortError', async () => { const { fetch } = scriptedFetch([busy503('5'), { status: 200, body: {} }]); const http = client(fetch); const ac = new AbortController(); const p = http.getJson('/v1/docs/d1/head', (raw) => raw, ac.signal); p.catch(() => undefined); await new Promise((r) => setTimeout(r, 20)); // inside the hinted wait ac.abort(); await expect(p).rejects.toBeInstanceOf(AbortError); }); test('Retry-After is honored (and capped)', async () => { const { fetch } = scriptedFetch([busy503('1'), { status: 200, body: { ok: 1 } }]); const http = client(fetch); const t0 = Date.now(); await http.getJson('/v1/docs/d1/head', (raw) => raw, signal()); const elapsed = Date.now() - t0; expect(elapsed).toBeGreaterThanOrEqual(850); // 1s hint, −10% jitter, scheduling slack expect(elapsed).toBeLessThan(3_000); }); }); describe("X-CloudPDF-Doc emission (default ON — routing hints are client behavior, using them is the LB operator's call)", () => { test('by DEFAULT: doc paths carry the docId; non-doc paths do not', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); const http = client(fetch); await http.getJson('/v1/docs/docZ/head', (raw) => raw, signal()); expect(new Headers(calls[0]!.init.headers).get('x-cloudpdf-doc')).toBe('docZ'); await http.getJson('/healthz', (raw) => raw, signal()); expect(new Headers(calls[1]!.init.headers).get('x-cloudpdf-doc')).toBeNull(); }); test('docAffinityHeader: false is the escape hatch (stale-CORS server / strict proxy)', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); await client(fetch, { docAffinityHeader: false }).getJson( '/v1/docs/docZ/head', (raw) => raw, signal(), ); expect(new Headers(calls[0]!.init.headers).get('x-cloudpdf-doc')).toBeNull(); }); test('the access bootstrap carries it via its PATH — doc and layer both path-addressed', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); const http = client(fetch); await http.postJson( '/v1/docs/docZ/layers/default/access', { mode: 'any' }, (raw) => raw, signal(), ); expect(new Headers(calls[0]!.init.headers).get('x-cloudpdf-doc')).toBe('docZ'); }); }); describe('one client per open document', () => { test('each keeps its own session and CDN binding, and the engine client its settings', async () => { const { fetch, calls } = scriptedFetch([busy503(), { status: 200, body: {} }]); const retries: string[] = []; const engineClient = client(fetch, { token: 'engine-token', docAffinityHeader: false, onRetry: (info: { code: string }) => retries.push(info.code), }); const first = engineClient.forDocument({ sessionId: 'cloud:first' }); const second = engineClient.forDocument({ sessionId: 'cloud:second', token: 'doc-token' }); await first.postJson('/v1/docs/d1/layers/default/x', {}, (raw) => raw, signal(), { write: { opId: 'op-1' }, }); await second.postJson('/v1/docs/d1/layers/default/x', {}, (raw) => raw, signal(), { write: { opId: 'op-2' }, }); const sent = calls.map((call) => new Headers(call.init.headers)); // The first write was shed once and retried: the engine client's `onRetry` heard it. expect(retries).toEqual(['EngineBusy']); expect(sent.map((headers) => headers.get('x-engine-session-id'))).toEqual([ 'cloud:first', 'cloud:first', 'cloud:second', ]); expect(sent.map((headers) => headers.get('authorization'))).toEqual([ 'Bearer engine-token', 'Bearer engine-token', 'Bearer doc-token', ]); expect(sent.every((headers) => headers.get('x-cloudpdf-doc') === null)).toBe(true); first.setCdnAccess({ cdn: null, docId: 'd1', layerName: 'default' }); expect(first.currentCdnBinding).not.toBeNull(); expect(second.currentCdnBinding).toBeNull(); expect(engineClient.currentCdnBinding).toBeNull(); expect(engineClient.sessionId).toBeNull(); }); }); describe('EmbedPDF-Version', () => { test('every request to the server itself says which version the client speaks', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); const http = client(fetch); await http.getJson('/v1/docs/docZ/head', (raw) => raw, signal()); await http.postJson('/v1/docs/docZ/annotations', {}, (raw) => raw, signal(), { write: { opId: 'op1' }, }); expect(calls.map((call) => new Headers(call.init.headers).get('embedpdf-version'))).toEqual([ API_VERSION, API_VERSION, ]); }); }); describe('reading through a CDN', () => { const textPath = '/v1/docs/d1/layers/default/text/pages/obj:3/data@contentVersion=1'; const binding = { docId: 'd1', layerName: 'default', cdn: { adapter: 'custom-hmac', baseUrlOverrides: { 'layer-page-text': 'https://cdn.example.test' }, authHeader: null, signedQueryParams: { token: 'signed' }, signedCookies: null, signedPathPolicies: null, }, }; test('reads go to the CDN the server offered', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); const http = client(fetch, { token: 't' }); http.setCdnAccess(binding); await http.getBytes(textPath, signal()); expect(calls[0]!.url).toBe(`https://cdn.example.test${textPath}?token=signed`); // A CDN serves cached reads, which never depend on the client's version. expect(new Headers(calls[0]!.init.headers).get('embedpdf-version')).toBeNull(); }); test('cdn: false reads from the server itself, CDN credentials or not', async () => { const { fetch, calls } = scriptedFetch([{ status: 200, body: {} }]); const http = client(fetch, { token: 't', cdn: false }).forDocument({ sessionId: 's' }); http.setCdnAccess(binding); await http.getBytes(textPath, signal()); expect(calls[0]!.url).toBe(`https://api.example.test${textPath}`); expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe('Bearer t'); expect(http.usesCdn).toBe(false); }); });