Skip to content

Commit 28c2fe8

Browse files
fix(data-objectstack): a byte upload the storage refuses for good fails at once instead of being re-sent whole three more times (#38407)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoY84428Lgy3xhZTWvnZmD5t)_ Fixes #38270 Clause-②: no Metadata-protocol: none ## 维护者速读 - 在控制台上传文件时,存储服务明确拒收(签名过期 403、令牌过期 401、文件太大 413)现在立刻报错,不再把整个文件再传 3 次、多等约 3.5 秒。 - 只有"暂时失败"才自动重传:断网、408/425/429/502/503/504,沿用仓里唯一一份 `TRANSIENT_STATUS` 定义。取消上传照旧不重传。 - 代价:直传 S3 偶尔遇到 500 时会直接报错,不再自动重传(500 不在那份定义里,是它有意的决定)。 - 无 ## What changes - `ui/packages/data-objectstack/src/upload-adapter.ts`, `uploadWithProgress` (step 2 of the presigned flow, the byte upload): a failure that carries an HTTP status is retried only when the status is in `TRANSIENT_STATUS` from `@object-ui/types` (408, 425, 429, 502, 503, 504), the one definition of "not now" `http-retry.ts` keeps for the whole tree. Any other refusal throws at once. A failure with no HTTP answer (a network error, the XHR `onerror`) is retried as before, and an abort is never retried, as before. No second definition is written. - 500 is not retried. `http-retry.ts` already decides that (a genuine server fault). Cost, accepted in the claim: an S3 `500 InternalError` on a direct presigned upload, which AWS documents as retryable, now fails at once instead of being re-sent. - Rider (accepted in the claim): the byte refusal now goes through the same file's `refusalOf` on both the fetch path (reads `res.text()`) and the XHR path (reads `xhr.responseText`), so it carries the server's error `code` beside its `status` when the answer was the declared envelope, as the presign and completion refusals already did. `uploadFile` / `uploadFiles` map that code to `serverCode`. The local raw PUT answers the envelope (401 `INVALID_TOKEN` for an expired upload token); S3 answers XML, which `refusalOf` leaves as status only. - `ui/packages/types/src/upload.ts`: the `maxRetries` JSDoc says which failures it counts. No type change. - `patch` changeset for `@object-ui/data-objectstack` and `@object-ui/types`. ## Tests - New `ui/packages/data-objectstack/src/upload-retry-38270.test.ts`: a fake storage service answers the byte PUT, and each case runs on both the fetch path (no `onProgress`) and the XHR path (an `onProgress` and a stand-in `XMLHttpRequest`, unstubbed after each test). 8 cases × 2 paths: - 413 `FILE_TOO_LARGE`, 403 and 401 `INVALID_TOKEN`: one byte request, the error carries the status (and the code where the envelope has one). - 500: one byte request. - 503 then 200: two byte requests, upload succeeds. 503 forever with `maxRetries: 3`: four byte requests, then the 503 is thrown. - Network error then 200: two byte requests. - Abort during the retry wait after a 503: `AbortError`, one byte request. <details><summary>Readings at 8ac6117 (base origin/main f42bcc1)</summary> - Premise at f42bcc1: `uploadWithProgress` (upload-adapter.ts 213-247) rethrew only `AbortError` and retried every other failure up to `maxRetries` (default 3), 500 × 2^n ms apart: 0.5 + 1 + 2 = 3.5 s for a refusal that cannot change. `UploadOptions.maxRetries` was already documented as retries "on network failure". - New pins: `Test Files 1 passed (1)`, `Tests 16 passed (16)`. - Request counts, read from the pins: 403 → 1 byte request with the fix, **4** with the gate ablated (`expected 4 to be 1`); 503 then 200 → 2; 503 forever → 4 (1 + `maxRetries`). - Ablation 1, the `TRANSIENT_STATUS` gate line replaced by a no-op: `Tests 8 failed | 8 passed (16)` — 413, 403, 401 and 500 on both paths. Restored after. - Ablation 2, the two `refusalOf` calls put back to the status-only error: `Tests 4 failed | 12 passed (16)` — the 413 and 401 code assertions on both paths. Restored after. - Ablation 3, the loop's `signal.aborted` check removed: `Tests 2 failed | 14 passed (16)` — the abort pin on both paths (`expected 'Error' to be 'AbortError'`, `expected 2 to be 1`). Restored after. - `pnpm --filter @object-ui/data-objectstack test` (under the verify lock): `Test Files 129 passed (129)`, `Tests 1466 passed (1466)`, `VERDICT command-exit 0`. - `pnpm --filter @object-ui/data-objectstack --filter @object-ui/types run type-check`: exit 0 (the package `tsconfig.json` includes `src/**/*`, the new test with it). - `dispatch-gates.mjs --tier`: no path-derived mandate, default tier; 273 changed lines, under 3000. - `overlap-check.mjs` at 8ac6117: `VERDICT clean exit 0`, 0 open PR heads touch the changed files. - Derived gates (`dispatch-gates --commands`, 38): 38 run at 8ac6117, every one exit 0 (each command, its exit code and its verdict line: `/mnt/project-files/card-38270/gates-results-8ac61177.txt`). `dispatch-gates --ran`: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. `pnpm --dir ui exec vitest run scripts/` (under the verify lock) and `check:type-check-debt` included. - PR check-runs at 8ac6117: 45 success, 13 expected skip, 0 unexpected skip, 0 failed, 0 pending; `mergeable_state` clean (`pr-state.mjs`). </details> ## Acceptance notes - None. ## Verification Read first (by risk): 1. `upload-adapter.ts`, the `catch` in `uploadWithProgress`: the `TRANSIENT_STATUS` gate sits after the abort rethrow and before the attempt budget. 2. The two `refusalOf` calls (fetch `!res.ok`, XHR `onload` non-2xx). Two-minute check: `pnpm --dir ui exec vitest run packages/data-objectstack/src/upload-retry-38270.test.ts` passes 16/16; replace the `TRANSIENT_STATUS` gate line with a no-op and 8 go red (a 403 then makes 4 byte requests instead of 1). --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibxgdN9nHqqceW6yq9Q)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibxgdN9nHqqceW6yq9Q <!-- signed: repo:objectstack#3 · os-tesla · session_01L9qibxgdN9nHqqceW6yq9Q --> Co-authored-by: Claude <noreply@anthropic.com>
1 parent a3c71d7 commit 28c2fe8

4 files changed

Lines changed: 269 additions & 4 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/data-objectstack': patch
3+
'@object-ui/types': patch
4+
---
5+
6+
fix(data-objectstack): a byte upload the storage refuses for good fails at once instead of being re-sent whole three more times
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
`createObjectStackUploadAdapter` retried every failure of the byte upload but an abort, so a refusal that cannot change on a resend (403 for an expired signature, 413 for a file too large, 401 `INVALID_TOKEN` for an expired local upload token) sent the whole file three more times and waited about 3.5 s before the same error reached the user. The byte upload is now retried only on a transient failure: no HTTP answer (a network error), or a status in `TRANSIENT_STATUS` from `@object-ui/types` (408, 425, 429, 502, 503, 504). Any other refusal throws at once, on both the fetch and the XHR path, and an abort is still never retried. A 500 is not retried either, as `TRANSIENT_STATUS` already decides, so an occasional S3 `500 InternalError` on a direct upload now fails at once rather than being re-sent.
12+
13+
The refusal now carries the server's error `code` beside its `status` when the answer was the declared error envelope, as the presign and completion refusals already did, so `uploadFile` / `uploadFiles` report it as `serverCode`.
14+
15+
`UploadOptions.maxRetries` in `@object-ui/types` now documents which failures it counts. No type changes.

‎ui/packages/data-objectstack/src/upload-adapter.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* data adapter.
1717
*/
1818
import type { API, UploadAdapter, UploadOptions } from '@object-ui/types';
19+
import { TRANSIENT_STATUS } from '@object-ui/types';
1920

2021
export interface ObjectStackUploadAdapterOptions {
2122
/**
@@ -207,7 +208,9 @@ interface UploadFetchOptions extends UploadOptions {
207208

208209
/**
209210
* Internal helper — performs a single PUT/POST with progress reporting,
210-
* exponential-backoff retry, and abort propagation.
211+
* exponential-backoff retry of a transient failure, and abort propagation.
212+
* A refusal throws `refusalOf`'s error on both paths, so it carries the
213+
* status and, when the answer was the declared envelope, the server's code.
211214
*/
212215
async function uploadWithProgress(
213216
fetchFn: typeof fetch,
@@ -233,12 +236,22 @@ async function uploadWithProgress(
233236
headers: options.headers,
234237
signal: options.signal,
235238
});
236-
if (!res.ok) throw Object.assign(new Error(`Upload failed with status ${res.status}`), { status: res.status });
239+
if (!res.ok) {
240+
const text = await res.text().catch(() => '');
241+
throw refusalOf(`Upload failed with status ${res.status}`, res.status, text);
242+
}
237243
options.onProgress?.(1);
238244
}
239245
return;
240246
} catch (err) {
241247
if ((err as DOMException)?.name === 'AbortError') throw err;
248+
// A refusal with an HTTP answer is retried only when the answer means
249+
// "not now" (`TRANSIENT_STATUS`, the one definition `@object-ui/types`
250+
// keeps); a definitive refusal (403 expired signature, 413 too large)
251+
// cannot succeed on a resend of the same bytes. A failure with no HTTP
252+
// answer (network error) is retried.
253+
const status = (err as { status?: unknown })?.status;
254+
if (typeof status === 'number' && !TRANSIENT_STATUS.has(status)) throw err;
242255
if (attempt >= maxRetries) throw err;
243256
const delay = baseDelay * Math.pow(2, attempt);
244257
attempt++;
@@ -262,7 +275,7 @@ function xhrUpload(url: string, body: Blob, options: UploadFetchOptions): Promis
262275
options.onProgress?.(1);
263276
resolve();
264277
} else {
265-
reject(Object.assign(new Error(`Upload failed with status ${xhr.status}`), { status: xhr.status }));
278+
reject(refusalOf(`Upload failed with status ${xhr.status}`, xhr.status, xhr.responseText ?? ''));
266279
}
267280
};
268281
xhr.onerror = () => reject(new Error('Network error during upload'));
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
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+
});

‎ui/packages/types/src/upload.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,12 @@ export interface UploadOptions {
4545
onProgress?: (ratio: number) => void;
4646
/** External abort signal — cancels the upload (and any retry attempts). */
4747
signal?: AbortSignal;
48-
/** Number of retry attempts on network failure. @default 3 */
48+
/**
49+
* Number of retry attempts on a transient failure: no HTTP answer (a
50+
* network error) or a status in `TRANSIENT_STATUS`. A definitive refusal
51+
* (an expired signature, a file too large) and an abort are never retried.
52+
* @default 3
53+
*/
4954
maxRetries?: number;
5055
/** Initial backoff in ms; exponential. @default 500 */
5156
retryDelayMs?: number;

0 commit comments

Comments
 (0)