|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * objectstack#38270 — the byte upload is retried only on a transient failure. |
| 11 | + * |
| 12 | + * `createObjectStackUploadAdapter` sends the file's bytes in step 2 of the |
| 13 | + * presigned flow, on the fetch path (no `onProgress`) or the XHR path (an |
| 14 | + * `onProgress` and an `XMLHttpRequest`). Both used to retry every failure but |
| 15 | + * an abort, so a storage refusal that cannot change on a resend — 403 (an |
| 16 | + * expired signature), 413 (too large), 401 `INVALID_TOKEN` (an expired local |
| 17 | + * upload token) — sent the whole file three more times before the same error |
| 18 | + * reached the user. |
| 19 | + * |
| 20 | + * Now a refusal is retried only when its status is in `TRANSIENT_STATUS` |
| 21 | + * (`@object-ui/types`, the one definition of "not now"); a failure with no HTTP |
| 22 | + * answer is retried as before, and an abort never is. The refusal carries its |
| 23 | + * status and, when the answer was the declared envelope, the server's code. |
| 24 | + */ |
| 25 | + |
| 26 | +import { describe, it, expect, vi, afterEach } from 'vitest'; |
| 27 | +import { createObjectStackUploadAdapter } from './upload-adapter'; |
| 28 | + |
| 29 | +const BASE = 'http://fake-38270.test'; |
| 30 | +const STORAGE = `${BASE}/api/v1/storage`; |
| 31 | +const PUT_URL = `${STORAGE}/_local/raw/tok-1`; |
| 32 | + |
| 33 | +function json(body: unknown, status = 200): Response { |
| 34 | + return new Response(JSON.stringify(body), { |
| 35 | + status, |
| 36 | + headers: { 'Content-Type': 'application/json' }, |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +/** One byte-PUT answer: a status (with an optional envelope code), or a thrown network error. */ |
| 41 | +type PutAnswer = { status: number; code?: string } | 'network-error'; |
| 42 | + |
| 43 | +function envelope(answer: { status: number; code?: string }): string { |
| 44 | + return JSON.stringify({ success: false, error: { code: answer.code ?? 'REFUSED', message: 'refused' } }); |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * A fake storage service: presign and complete always succeed; each byte PUT |
| 49 | + * takes the next answer from `puts` (the last one repeats). `putCount` is how |
| 50 | + * many byte requests reached it. |
| 51 | + */ |
| 52 | +function fakeStorage(puts: PutAnswer[]) { |
| 53 | + let putCount = 0; |
| 54 | + const nextPut = (): PutAnswer => puts[Math.min(putCount++, puts.length - 1)]; |
| 55 | + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => { |
| 56 | + const url = String(input); |
| 57 | + const method = init?.method ?? 'GET'; |
| 58 | + if (url === `${STORAGE}/upload/presigned` && method === 'POST') { |
| 59 | + return json({ success: true, data: { uploadUrl: PUT_URL, fileId: 'file_1' } }); |
| 60 | + } |
| 61 | + if (url === PUT_URL && method === 'PUT') { |
| 62 | + const answer = nextPut(); |
| 63 | + if (answer === 'network-error') throw new TypeError('Failed to fetch'); |
| 64 | + if (answer.status >= 200 && answer.status < 300) return new Response(null, { status: answer.status }); |
| 65 | + return new Response(envelope(answer), { status: answer.status, headers: { 'Content-Type': 'application/json' } }); |
| 66 | + } |
| 67 | + if (url === `${STORAGE}/upload/complete` && method === 'POST') { |
| 68 | + return json({ success: true, data: {} }); |
| 69 | + } |
| 70 | + return json({ success: false, error: { code: 'ENDPOINT_NOT_FOUND' } }, 404); |
| 71 | + }) as typeof fetch; |
| 72 | + return { fetchImpl, nextPut, putCount: () => putCount }; |
| 73 | +} |
| 74 | + |
| 75 | +/** |
| 76 | + * A stand-in `XMLHttpRequest` that answers each `send` from the same fake |
| 77 | + * storage's byte-PUT answers, so the XHR path is driven the way the fetch path |
| 78 | + * is. A network error fires `onerror`, as a browser does. |
| 79 | + */ |
| 80 | +function fakeXhrClass(storage: ReturnType<typeof fakeStorage>) { |
| 81 | + return class FakeXhr { |
| 82 | + status = 0; |
| 83 | + responseText = ''; |
| 84 | + upload: { onprogress: ((e: { lengthComputable: boolean; loaded: number; total: number }) => void) | null } = { |
| 85 | + onprogress: null, |
| 86 | + }; |
| 87 | + onload: (() => void) | null = null; |
| 88 | + onerror: (() => void) | null = null; |
| 89 | + onabort: (() => void) | null = null; |
| 90 | + private url = ''; |
| 91 | + open(_method: string, url: string) { |
| 92 | + this.url = url; |
| 93 | + } |
| 94 | + setRequestHeader() {} |
| 95 | + abort() { |
| 96 | + queueMicrotask(() => this.onabort?.()); |
| 97 | + } |
| 98 | + send() { |
| 99 | + if (this.url !== PUT_URL) throw new Error(`unexpected XHR to ${this.url}`); |
| 100 | + const answer = storage.nextPut(); |
| 101 | + queueMicrotask(() => { |
| 102 | + if (answer === 'network-error') { |
| 103 | + this.onerror?.(); |
| 104 | + return; |
| 105 | + } |
| 106 | + this.status = answer.status; |
| 107 | + if (answer.status < 200 || answer.status >= 300) this.responseText = envelope(answer); |
| 108 | + this.onload?.(); |
| 109 | + }); |
| 110 | + } |
| 111 | + }; |
| 112 | +} |
| 113 | + |
| 114 | +const file = () => new File(['hello'], 'hello.txt', { type: 'text/plain' }); |
| 115 | + |
| 116 | +afterEach(() => { |
| 117 | + vi.unstubAllGlobals(); |
| 118 | +}); |
| 119 | + |
| 120 | +/** Both byte-upload paths, driven through the same fake storage. */ |
| 121 | +const paths = [ |
| 122 | + { |
| 123 | + name: 'fetch path', |
| 124 | + setup(_storage: ReturnType<typeof fakeStorage>) { |
| 125 | + // No `onProgress`: the adapter sends the bytes through the injected fetch. |
| 126 | + return {}; |
| 127 | + }, |
| 128 | + }, |
| 129 | + { |
| 130 | + name: 'XHR path', |
| 131 | + setup(storage: ReturnType<typeof fakeStorage>) { |
| 132 | + vi.stubGlobal('XMLHttpRequest', fakeXhrClass(storage)); |
| 133 | + return { onProgress: () => {} }; |
| 134 | + }, |
| 135 | + }, |
| 136 | +] as const; |
| 137 | + |
| 138 | +describe.each(paths)('byte upload retry — $name', (path) => { |
| 139 | + it('a 413 refusal makes one byte request and throws its status and code at once', async () => { |
| 140 | + const storage = fakeStorage([{ status: 413, code: 'FILE_TOO_LARGE' }]); |
| 141 | + const opts = path.setup(storage); |
| 142 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 143 | + |
| 144 | + const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e); |
| 145 | + |
| 146 | + expect(storage.putCount()).toBe(1); |
| 147 | + expect(err).toMatchObject({ status: 413, code: 'FILE_TOO_LARGE' }); |
| 148 | + }); |
| 149 | + |
| 150 | + it('a 403 refusal (expired signature) makes one byte request', async () => { |
| 151 | + const storage = fakeStorage([{ status: 403 }]); |
| 152 | + const opts = path.setup(storage); |
| 153 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 154 | + |
| 155 | + const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e); |
| 156 | + |
| 157 | + expect(storage.putCount()).toBe(1); |
| 158 | + expect(err).toMatchObject({ status: 403 }); |
| 159 | + }); |
| 160 | + |
| 161 | + it('a 401 INVALID_TOKEN (expired local upload token) makes one byte request', async () => { |
| 162 | + const storage = fakeStorage([{ status: 401, code: 'INVALID_TOKEN' }]); |
| 163 | + const opts = path.setup(storage); |
| 164 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 165 | + |
| 166 | + const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e); |
| 167 | + |
| 168 | + expect(storage.putCount()).toBe(1); |
| 169 | + expect(err).toMatchObject({ status: 401, code: 'INVALID_TOKEN' }); |
| 170 | + }); |
| 171 | + |
| 172 | + it('a 500 is not retried (TRANSIENT_STATUS leaves it out)', async () => { |
| 173 | + const storage = fakeStorage([{ status: 500 }]); |
| 174 | + const opts = path.setup(storage); |
| 175 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 176 | + |
| 177 | + const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e); |
| 178 | + |
| 179 | + expect(storage.putCount()).toBe(1); |
| 180 | + expect(err).toMatchObject({ status: 500 }); |
| 181 | + }); |
| 182 | + |
| 183 | + it('a 503 is retried, and the upload succeeds on the next attempt', async () => { |
| 184 | + const storage = fakeStorage([{ status: 503 }, { status: 200 }]); |
| 185 | + const opts = path.setup(storage); |
| 186 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 187 | + |
| 188 | + const result = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }); |
| 189 | + |
| 190 | + expect(storage.putCount()).toBe(2); |
| 191 | + expect(result.meta).toMatchObject({ fileId: 'file_1' }); |
| 192 | + }); |
| 193 | + |
| 194 | + it('a 503 that never clears is sent 1 + maxRetries times, then throws its status', async () => { |
| 195 | + const storage = fakeStorage([{ status: 503 }]); |
| 196 | + const opts = path.setup(storage); |
| 197 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 198 | + |
| 199 | + const err = await adapter.upload(file(), { ...opts, maxRetries: 3, retryDelayMs: 1 }).catch((e: unknown) => e); |
| 200 | + |
| 201 | + expect(storage.putCount()).toBe(4); |
| 202 | + expect(err).toMatchObject({ status: 503 }); |
| 203 | + }); |
| 204 | + |
| 205 | + it('a network error (no HTTP answer) is still retried', async () => { |
| 206 | + const storage = fakeStorage(['network-error', { status: 200 }]); |
| 207 | + const opts = path.setup(storage); |
| 208 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 209 | + |
| 210 | + await adapter.upload(file(), { ...opts, retryDelayMs: 1 }); |
| 211 | + |
| 212 | + expect(storage.putCount()).toBe(2); |
| 213 | + }); |
| 214 | + |
| 215 | + it('an abort during a retry wait is not retried', async () => { |
| 216 | + const storage = fakeStorage([{ status: 503 }]); |
| 217 | + const opts = path.setup(storage); |
| 218 | + const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl }); |
| 219 | + const controller = new AbortController(); |
| 220 | + |
| 221 | + const pending = adapter |
| 222 | + .upload(file(), { ...opts, signal: controller.signal, retryDelayMs: 50 }) |
| 223 | + .catch((e: unknown) => e); |
| 224 | + // The first byte request answers 503; abort while the adapter waits to retry. |
| 225 | + await vi.waitFor(() => expect(storage.putCount()).toBe(1)); |
| 226 | + controller.abort(); |
| 227 | + const err = await pending; |
| 228 | + |
| 229 | + expect((err as DOMException).name).toBe('AbortError'); |
| 230 | + expect(storage.putCount()).toBe(1); |
| 231 | + }); |
| 232 | +}); |
0 commit comments