From a7eea557d5aef0c9b83d42b5b0b239eecd5f871a Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:19:37 +0000 Subject: [PATCH 1/3] Upload large project saves in chunks --- package.json | 2 +- src/community/pages/MyStuff.jsx | 2 +- src/lib/community/api.js | 21 +++-- src/lib/community/publish.js | 2 +- src/modules/platform-api/response-cache.ts | 3 +- src/modules/project-upload/index.ts | 92 ++++++++++++++++++++++ test/unit/modules/project-upload.test.ts | 89 +++++++++++++++++++++ 7 files changed, 200 insertions(+), 11 deletions(-) create mode 100644 src/modules/project-upload/index.ts create mode 100644 test/unit/modules/project-upload.test.ts diff --git a/package.json b/package.json index feae27a36ed..33ea0007957 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "scratch-gui", - "version": "3.16.1", + "version": "3.16.2", "private": true, "description": "MistWarp editor, player, and community site", "author": "MistWarp contributors", diff --git a/src/community/pages/MyStuff.jsx b/src/community/pages/MyStuff.jsx index be94e4a969a..6a92ef84c37 100644 --- a/src/community/pages/MyStuff.jsx +++ b/src/community/pages/MyStuff.jsx @@ -42,7 +42,7 @@ const uploadErrorTarget = (agreementAccepted, error) => { const uploadProgressLabel = (loaded, total) => { if (!(total > 0)) return 'Uploading…'; - const percent = Math.min(100, Math.max(0, Math.round((loaded / total) * 100))); + const percent = Math.min(100, Math.max(0, Math.floor((loaded / total) * 100))); return percent >= 100 ? 'Processing on server…' : `Uploading ${percent}%`; }; diff --git a/src/lib/community/api.js b/src/lib/community/api.js index 0e5c9ae8555..2e007c3ef70 100644 --- a/src/lib/community/api.js +++ b/src/lib/community/api.js @@ -9,6 +9,7 @@ import { } from '../../community/api-errors.js'; import {reportActionableError} from '../error-reporter.js'; import {createPlatformApi, staleCacheTest} from '../../modules/platform-api'; +import {uploadProjectForm} from '../../modules/project-upload'; import {session as sessionStore} from '../../modules/storage'; const API_BASE = process.env.MW_API_BASE || 'https://api.mistwarp.org/v1'; @@ -64,6 +65,17 @@ const logout = () => platformApi.logout(); const uploadXhr = (path, form, onUploadProgress) => platformApi.upload(path, form, onUploadProgress); +const uploadWithSessionRefresh = async (path, form, onUploadProgress) => { + try { + return await uploadXhr(path, form, onUploadProgress); + } catch (e) { + if (e.status !== 401) throw e; + storeSession(null); + if (!(await refreshSession())) throw e; + return uploadXhr(path, form, onUploadProgress); + } +}; + const createProject = payload => request('/projects', {method: 'POST', body: payload}); const getCustomExtensionUrls = project => { @@ -217,14 +229,9 @@ const uploadProject = async (id, sb3Blob, thumbnailBlob, onUploadProgress, { if (thumbnailBlob) { form.append('thumbnail', thumbnailBlob, 'thumb.png'); } - const path = `/projects/${id}/upload`; try { - return await uploadXhr(path, form, onUploadProgress); - } catch (e) { - if (e.status !== 401) throw e; - storeSession(null); - if (!(await refreshSession())) throw e; - return uploadXhr(path, form, onUploadProgress); + return await uploadProjectForm({request: platformApi.request, upload: uploadWithSessionRefresh}, + id, form, onUploadProgress); } finally { clearApiCache(); clearContentCache(); diff --git a/src/lib/community/publish.js b/src/lib/community/publish.js index 467ee80eb5c..51965ba5d79 100644 --- a/src/lib/community/publish.js +++ b/src/lib/community/publish.js @@ -340,7 +340,7 @@ const publishWorkspace = async ({ const expectedEdited = platformProject.edited; onProgress({phase: 'upload', message: 'Uploading project'}); const upload = () => uploadProject(uploadId, sb3Blob, thumbnail, (loaded, total) => { - const percent = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : null; + const percent = total > 0 ? Math.min(100, Math.floor((loaded / total) * 100)) : null; onProgress({ phase: 'upload', message: percent !== null && percent >= 100 ? 'Processing on server' : diff --git a/src/modules/platform-api/response-cache.ts b/src/modules/platform-api/response-cache.ts index 3cfa28a08c6..95cb04ea0c2 100644 --- a/src/modules/platform-api/response-cache.ts +++ b/src/modules/platform-api/response-cache.ts @@ -20,7 +20,8 @@ const isCacheEntry = (value: unknown): value is CacheEntry => const pathSegments = (path: string): string[] => (path.split('?')[0] ?? '').split('/').filter(Boolean); export const isCacheNeutral = (path: string): boolean => - path.endsWith('/view') || path.endsWith('/live') || path === '/errors'; + path.endsWith('/view') || path.endsWith('/live') || path === '/errors' || + /^\/projects\/[^/]+\/upload-parts(?:\/[^/]+\/complete)?$/.test(path); export const staleCacheTest = (method: string, path: string): CachedPathTest | null => { const [collection, id, action] = pathSegments(path); diff --git a/src/modules/project-upload/index.ts b/src/modules/project-upload/index.ts new file mode 100644 index 00000000000..b5382025baf --- /dev/null +++ b/src/modules/project-upload/index.ts @@ -0,0 +1,92 @@ +import type {ApiError, PlatformClient, UploadProgress} from '../platform-api'; + +const MAX_INLINE_BYTES = 90_000_000; +const CHUNK_BYTES = 8 * 1024 * 1024; +const ARCHIVE_FIELDS = ['project', 'workspace', 'mergeTree'] as const; + +type ArchiveField = typeof ARCHIVE_FIELDS[number]; +type UploadTransport = Pick; + +const payloadBytes = (form: FormData): number => Array.from(form.values()).reduce( + (total, value) => total + (typeof value === 'string' ? new Blob([value]).size : value.size), 0 +); + +const retryPart = async (send: () => Promise): Promise => { + for (let attempt = 0; ; attempt++) { + try { + return await send(); + } catch (cause) { + const error = cause as ApiError; + const retryable = (error.status ?? 0) >= 500 || + ['network', 'timeout', 'upload_stalled', 'upload_processing_timeout'].includes(error.code ?? ''); + if (!retryable || attempt === 2) { + if (error.code === 'upload_processing_timeout') error.code = 'upload_stalled'; + throw error; + } + await new Promise(resolve => setTimeout(resolve, 500 * (attempt + 1))); + } + } +}; + +const stagePart = async ( + api: UploadTransport, path: string, kind: ArchiveField, blob: Blob, onProgress: (loaded: number) => void +): Promise => { + const chunks = Math.ceil(blob.size / CHUNK_BYTES); + const {token} = await api.request<{token: string}>(path, { + method: 'POST', body: {kind, size: blob.size, chunks}, timeoutMs: 30_000 + }); + const partPath = `${path}/${encodeURIComponent(token)}`; + for (let index = 0; index < chunks; index++) { + const offset = index * CHUNK_BYTES; + const chunk = blob.slice(offset, offset + CHUNK_BYTES); + const form = new FormData(); + form.append('index', String(index)); + form.append('chunk', chunk, 'chunk.bin'); + await retryPart(() => api.upload(`${partPath}/chunk`, form, (loaded, total) => { + const fraction = total > 0 ? Math.min(1, loaded / total) : 0; + onProgress(offset + Math.floor(fraction * chunk.size)); + })); + onProgress(offset + chunk.size); + } + await retryPart(() => api.request(`${partPath}/complete`, {method: 'POST', timeoutMs: 120_000})); + return token; +}; + +export const uploadProjectForm = async ( + api: UploadTransport, projectId: string, form: FormData, onProgress?: UploadProgress +): Promise => { + const projectPath = `/projects/${encodeURIComponent(projectId)}`; + const bytes = payloadBytes(form); + if (bytes < MAX_INLINE_BYTES) return api.upload(`${projectPath}/upload`, form, onProgress); + + const stages = ARCHIVE_FIELDS.flatMap(field => { + const file = form.get(field); + return typeof file !== 'string' && file?.size ? [{field, file}] : []; + }); + const totalStagedBytes = stages.reduce((sum, {file}) => sum + file.size, 0); + const finalBytes = Math.max(1, bytes - totalStagedBytes); + const totalBytes = totalStagedBytes + finalBytes; + let stagedBytes = 0; + let reportedBytes = 0; + const finalForm = new FormData(); + const reportProgress = (loaded: number): void => { + reportedBytes = Math.max(reportedBytes, loaded); + onProgress?.(reportedBytes, totalBytes); + }; + form.forEach((value, field) => { + finalForm.append(field, value); + }); + for (const {field, file} of stages) { + const offset = stagedBytes; + const token = await stagePart(api, `${projectPath}/upload-parts`, field, file, loaded => { + reportProgress(offset + loaded); + }); + stagedBytes += file.size; + finalForm.delete(field); + finalForm.append(`${field}Token`, token); + } + return api.upload(`${projectPath}/upload`, finalForm, (loaded, total) => { + const fraction = total > 0 ? Math.min(1, loaded / total) : 0; + reportProgress(stagedBytes + Math.floor(fraction * finalBytes)); + }); +}; diff --git a/test/unit/modules/project-upload.test.ts b/test/unit/modules/project-upload.test.ts new file mode 100644 index 00000000000..af807c46124 --- /dev/null +++ b/test/unit/modules/project-upload.test.ts @@ -0,0 +1,89 @@ +import {afterEach, describe, expect, it, jest} from '@jest/globals'; +import type {PlatformClient, RequestOptions, UploadProgress} from '../../../src/modules/platform-api'; +import {uploadProjectForm} from '../../../src/modules/project-upload'; + +const chunkBytes = 8 * 1024 * 1024; +const archive = (size: number): Blob => new Blob([new Uint8Array(size)]); + +const transport = () => { + const starts: unknown[] = []; + const completed: string[] = []; + const chunks: {path: string; index: string; bytes: number}[] = []; + const final = jest.fn<(form: FormData) => void>(); + const onChunk = jest.fn<() => void>(); + const api: Pick = { + request: (path: string, options?: RequestOptions) => { + if (path.endsWith('/complete')) { + completed.push(path); + return Promise.resolve({ok: true} as T); + } + starts.push(options?.body); + return Promise.resolve({token: `token${starts.length.toString()}`} as T); + }, + upload: (path: string, form: FormData, progress?: UploadProgress) => { + if (path.endsWith('/chunk')) { + const data = form.get('chunk') as File; + chunks.push({path, index: form.get('index') as string, bytes: data.size}); + onChunk(); + } else { + final(form); + } + progress?.(10, 10); + return Promise.resolve({ok: true} as T); + } + }; + return {api, starts, completed, chunks, final, onChunk}; +}; + +describe('uploadProjectForm', () => { + afterEach(() => { + jest.useRealTimers(); + }); + + it('sends a small save in one request', async () => { + const {api, starts, final} = transport(); + const form = new FormData(); + form.append('project', new Blob(['sb3']), 'project.sb3'); + await expect(uploadProjectForm(api, '123', form)).resolves.toEqual({ok: true}); + expect(starts).toEqual([]); + expect(final).toHaveBeenCalledWith(form); + }); + + it('stages large saves and retries a chunk after a dropped response', async () => { + jest.useFakeTimers(); + const {api, starts, completed, chunks, final, onChunk} = transport(); + onChunk.mockImplementationOnce(() => { + throw Object.assign(new Error('Connection dropped'), {code: 'network'}); + }); + const form = new FormData(); + form.append('project', archive(50_000_000)); + form.append('workspace', archive(51_000_000)); + form.append('mergeTree', new Blob(['tree'])); + form.append('thumbnail', new Blob(['thumb'])); + form.append('expectedHead', 'previous-head'); + const progress = jest.fn(); + + const saved = uploadProjectForm(api, '123', form, progress); + await jest.runAllTimersAsync(); + await expect(saved).resolves.toEqual({ok: true}); + + expect(starts).toEqual([ + {kind: 'project', size: 50_000_000, chunks: 6}, + {kind: 'workspace', size: 51_000_000, chunks: 7}, + {kind: 'mergeTree', size: 4, chunks: 1} + ]); + expect(chunks[0]).toEqual(chunks[1]); + expect(chunks[2]?.index).toBe('1'); + expect(chunks.slice(1).reduce((total, chunk) => total + chunk.bytes, 0)).toBe(101_000_004); + expect(chunks.every(chunk => chunk.bytes <= chunkBytes)).toBe(true); + expect(completed).toEqual(['1', '2', '3'].map(i => `/projects/123/upload-parts/token${i}/complete`)); + expect(Array.from(final.mock.calls[0]?.[0].keys() ?? [])).toEqual([ + 'thumbnail', 'expectedHead', 'projectToken', 'workspaceToken', 'mergeTreeToken' + ]); + expect(final.mock.calls[0]?.[0].get('projectToken')).toBe('token1'); + expect(final.mock.calls[0]?.[0].get('expectedHead')).toBe('previous-head'); + expect(progress.mock.calls.slice(0, -1).every(([loaded, total]) => loaded < total)).toBe(true); + const last = progress.mock.calls.at(-1); + expect(last?.[0]).toBe(last?.[1]); + }); +}); From 0b2ca396ce980731e496137b39c733da2886d688 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:30:07 +0000 Subject: [PATCH 2/3] Keep staged saves available across retries --- src/modules/project-upload/index.ts | 79 ++++++++++++++++++------ test/unit/modules/project-upload.test.ts | 55 +++++++++++++++-- 2 files changed, 109 insertions(+), 25 deletions(-) diff --git a/src/modules/project-upload/index.ts b/src/modules/project-upload/index.ts index b5382025baf..e1441dbac8c 100644 --- a/src/modules/project-upload/index.ts +++ b/src/modules/project-upload/index.ts @@ -2,9 +2,9 @@ import type {ApiError, PlatformClient, UploadProgress} from '../platform-api'; const MAX_INLINE_BYTES = 90_000_000; const CHUNK_BYTES = 8 * 1024 * 1024; +const KEEPALIVE_MS = 4 * 60 * 1000; const ARCHIVE_FIELDS = ['project', 'workspace', 'mergeTree'] as const; -type ArchiveField = typeof ARCHIVE_FIELDS[number]; type UploadTransport = Pick; const payloadBytes = (form: FormData): number => Array.from(form.values()).reduce( @@ -29,13 +29,8 @@ const retryPart = async (send: () => Promise): Promise => { }; const stagePart = async ( - api: UploadTransport, path: string, kind: ArchiveField, blob: Blob, onProgress: (loaded: number) => void -): Promise => { - const chunks = Math.ceil(blob.size / CHUNK_BYTES); - const {token} = await api.request<{token: string}>(path, { - method: 'POST', body: {kind, size: blob.size, chunks}, timeoutMs: 30_000 - }); - const partPath = `${path}/${encodeURIComponent(token)}`; + api: UploadTransport, partPath: string, blob: Blob, chunks: number, onProgress: (loaded: number) => void +): Promise => { for (let index = 0; index < chunks; index++) { const offset = index * CHUNK_BYTES; const chunk = blob.slice(offset, offset + CHUNK_BYTES); @@ -49,15 +44,37 @@ const stagePart = async ( onProgress(offset + chunk.size); } await retryPart(() => api.request(`${partPath}/complete`, {method: 'POST', timeoutMs: 120_000})); - return token; +}; + +const sendProjectUpload = async ( + api: UploadTransport, path: string, form: FormData, onProgress?: UploadProgress +): Promise => { + try { + return await api.upload(path, form, onProgress); + } catch (cause) { + const error = cause as ApiError; + const status = error.status ?? 0; + if (error.code === 'network' || [502, 503, 504].includes(status) || (status >= 520 && status <= 527)) { + error.code = 'upload_processing_timeout'; + error.message = 'The server may still be saving your project. Check My Stuff before retrying.'; + } + throw error; + } +}; + +const acceptsInlineOnly = (cause: unknown): boolean => { + const error = cause as ApiError; + return error.status === 404 || (error.status === 400 && error.serverMessage === 'invalid upload part'); }; export const uploadProjectForm = async ( api: UploadTransport, projectId: string, form: FormData, onProgress?: UploadProgress ): Promise => { const projectPath = `/projects/${encodeURIComponent(projectId)}`; + const uploadPath = `${projectPath}/upload`; + const partsPath = `${projectPath}/upload-parts`; const bytes = payloadBytes(form); - if (bytes < MAX_INLINE_BYTES) return api.upload(`${projectPath}/upload`, form, onProgress); + if (bytes < MAX_INLINE_BYTES) return sendProjectUpload(api, uploadPath, form, onProgress); const stages = ARCHIVE_FIELDS.flatMap(field => { const file = form.get(field); @@ -76,16 +93,40 @@ export const uploadProjectForm = async ( form.forEach((value, field) => { finalForm.append(field, value); }); - for (const {field, file} of stages) { - const offset = stagedBytes; - const token = await stagePart(api, `${projectPath}/upload-parts`, field, file, loaded => { - reportProgress(offset + loaded); - }); - stagedBytes += file.size; - finalForm.delete(field); - finalForm.append(`${field}Token`, token); + const completedPaths: string[] = []; + const keepalive = setInterval(() => { + for (const path of completedPaths) { + void api.request(`${path}/complete`, {method: 'POST', timeoutMs: 30_000}).catch(() => undefined); + } + }, KEEPALIVE_MS); + try { + for (const {field, file} of stages) { + const chunks = Math.ceil(file.size / CHUNK_BYTES); + let token; + try { + ({token} = await api.request<{token: string}>(partsPath, { + method: 'POST', body: {kind: field, size: file.size, chunks}, timeoutMs: 30_000 + })); + } catch (error) { + if (field === 'project' && acceptsInlineOnly(error)) { + return await sendProjectUpload(api, uploadPath, form, onProgress); + } + throw error; + } + const offset = stagedBytes; + const partPath = `${partsPath}/${encodeURIComponent(token)}`; + await stagePart(api, partPath, file, chunks, loaded => { + reportProgress(offset + loaded); + }); + completedPaths.push(partPath); + stagedBytes += file.size; + finalForm.delete(field); + finalForm.append(`${field}Token`, token); + } + } finally { + clearInterval(keepalive); } - return api.upload(`${projectPath}/upload`, finalForm, (loaded, total) => { + return sendProjectUpload(api, uploadPath, finalForm, (loaded, total) => { const fraction = total > 0 ? Math.min(1, loaded / total) : 0; reportProgress(stagedBytes + Math.floor(fraction * finalBytes)); }); diff --git a/test/unit/modules/project-upload.test.ts b/test/unit/modules/project-upload.test.ts index af807c46124..0e73fab3486 100644 --- a/test/unit/modules/project-upload.test.ts +++ b/test/unit/modules/project-upload.test.ts @@ -10,7 +10,8 @@ const transport = () => { const completed: string[] = []; const chunks: {path: string; index: string; bytes: number}[] = []; const final = jest.fn<(form: FormData) => void>(); - const onChunk = jest.fn<() => void>(); + const onChunk = jest.fn<(path: string) => void | Promise>(); + const onStart = jest.fn<() => void>(); const api: Pick = { request: (path: string, options?: RequestOptions) => { if (path.endsWith('/complete')) { @@ -18,21 +19,22 @@ const transport = () => { return Promise.resolve({ok: true} as T); } starts.push(options?.body); + onStart(); return Promise.resolve({token: `token${starts.length.toString()}`} as T); }, - upload: (path: string, form: FormData, progress?: UploadProgress) => { + upload: async (path: string, form: FormData, progress?: UploadProgress) => { if (path.endsWith('/chunk')) { const data = form.get('chunk') as File; chunks.push({path, index: form.get('index') as string, bytes: data.size}); - onChunk(); + await onChunk(path); } else { final(form); } progress?.(10, 10); - return Promise.resolve({ok: true} as T); + return {ok: true} as T; } }; - return {api, starts, completed, chunks, final, onChunk}; + return {api, starts, completed, chunks, final, onChunk, onStart}; }; describe('uploadProjectForm', () => { @@ -64,7 +66,7 @@ describe('uploadProjectForm', () => { const progress = jest.fn(); const saved = uploadProjectForm(api, '123', form, progress); - await jest.runAllTimersAsync(); + await jest.advanceTimersByTimeAsync(500); await expect(saved).resolves.toEqual({ok: true}); expect(starts).toEqual([ @@ -86,4 +88,45 @@ describe('uploadProjectForm', () => { const last = progress.mock.calls.at(-1); expect(last?.[0]).toBe(last?.[1]); }); + + it('renews already completed parts during a slow workspace upload', async () => { + jest.useFakeTimers(); + const {api, completed, onChunk} = transport(); + let finishWorkspace: (() => void) | undefined; + onChunk.mockImplementation(path => { + if (!path.includes('/token2/')) return; + return new Promise(resolve => { + finishWorkspace = resolve; + }); + }); + const form = new FormData(); + form.append('project', archive(90_000_000)); + form.append('workspace', new Blob(['workspace'])); + const saved = uploadProjectForm(api, '123', form); + await jest.advanceTimersByTimeAsync(16 * 60 * 1000); + expect(completed).toEqual(Array(5).fill('/projects/123/upload-parts/token1/complete')); + finishWorkspace?.(); + await expect(saved).resolves.toEqual({ok: true}); + }); + + it('keeps inline uploads working when the server has no project staging', async () => { + const {api, final, onStart} = transport(); + onStart.mockImplementationOnce(() => { + throw Object.assign(new Error('Invalid upload part'), {status: 400, serverMessage: 'invalid upload part'}); + }); + const form = new FormData(); + form.append('project', archive(95_000_000)); + await expect(uploadProjectForm(api, '123', form)).resolves.toEqual({ok: true}); + expect(final).toHaveBeenCalledWith(form); + }); + + it('reports an uncertain final save so callers keep the draft', async () => { + const {api, final} = transport(); + final.mockImplementationOnce(() => { + throw Object.assign(new Error('Gateway timed out'), {status: 524}); + }); + const form = new FormData(); + form.append('project', new Blob(['sb3'])); + await expect(uploadProjectForm(api, '123', form)).rejects.toMatchObject({code: 'upload_processing_timeout'}); + }); }); From 49306376d52264a96496a25b2d3a07aa9da46fa5 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:39:11 +0000 Subject: [PATCH 3/3] Release staged files after a refused save --- src/modules/platform-api/response-cache.ts | 2 +- src/modules/project-upload/index.ts | 17 ++++++++++--- test/unit/modules/project-upload.test.ts | 29 +++++++++++++++++++--- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/src/modules/platform-api/response-cache.ts b/src/modules/platform-api/response-cache.ts index 95cb04ea0c2..ec1b32d7c60 100644 --- a/src/modules/platform-api/response-cache.ts +++ b/src/modules/platform-api/response-cache.ts @@ -21,7 +21,7 @@ const pathSegments = (path: string): string[] => (path.split('?')[0] ?? '').spli export const isCacheNeutral = (path: string): boolean => path.endsWith('/view') || path.endsWith('/live') || path === '/errors' || - /^\/projects\/[^/]+\/upload-parts(?:\/[^/]+\/complete)?$/.test(path); + /^\/projects\/[^/]+\/upload-parts(?:\/[^/]+\/(?:complete|discard))?$/.test(path); export const staleCacheTest = (method: string, path: string): CachedPathTest | null => { const [collection, id, action] = pathSegments(path); diff --git a/src/modules/project-upload/index.ts b/src/modules/project-upload/index.ts index e1441dbac8c..150cd77dd6e 100644 --- a/src/modules/project-upload/index.ts +++ b/src/modules/project-upload/index.ts @@ -93,6 +93,7 @@ export const uploadProjectForm = async ( form.forEach((value, field) => { finalForm.append(field, value); }); + const startedPaths: string[] = []; const completedPaths: string[] = []; const keepalive = setInterval(() => { for (const path of completedPaths) { @@ -115,6 +116,7 @@ export const uploadProjectForm = async ( } const offset = stagedBytes; const partPath = `${partsPath}/${encodeURIComponent(token)}`; + startedPaths.push(partPath); await stagePart(api, partPath, file, chunks, loaded => { reportProgress(offset + loaded); }); @@ -123,11 +125,18 @@ export const uploadProjectForm = async ( finalForm.delete(field); finalForm.append(`${field}Token`, token); } + return await sendProjectUpload(api, uploadPath, finalForm, (loaded, total) => { + const fraction = total > 0 ? Math.min(1, loaded / total) : 0; + reportProgress(stagedBytes + Math.floor(fraction * finalBytes)); + }); + } catch (cause) { + const error = cause as ApiError; + if (error.code !== 'upload_processing_timeout') { + await Promise.all(startedPaths.map(path => + api.request(`${path}/discard`, {method: 'POST', timeoutMs: 5_000}).catch(() => undefined))); + } + throw error; } finally { clearInterval(keepalive); } - return sendProjectUpload(api, uploadPath, finalForm, (loaded, total) => { - const fraction = total > 0 ? Math.min(1, loaded / total) : 0; - reportProgress(stagedBytes + Math.floor(fraction * finalBytes)); - }); }; diff --git a/test/unit/modules/project-upload.test.ts b/test/unit/modules/project-upload.test.ts index 0e73fab3486..8c36a9e4909 100644 --- a/test/unit/modules/project-upload.test.ts +++ b/test/unit/modules/project-upload.test.ts @@ -8,12 +8,17 @@ const archive = (size: number): Blob => new Blob([new Uint8Array(size)]); const transport = () => { const starts: unknown[] = []; const completed: string[] = []; + const discarded: string[] = []; const chunks: {path: string; index: string; bytes: number}[] = []; const final = jest.fn<(form: FormData) => void>(); const onChunk = jest.fn<(path: string) => void | Promise>(); const onStart = jest.fn<() => void>(); const api: Pick = { request: (path: string, options?: RequestOptions) => { + if (path.endsWith('/discard')) { + discarded.push(path); + return Promise.resolve({ok: true} as T); + } if (path.endsWith('/complete')) { completed.push(path); return Promise.resolve({ok: true} as T); @@ -34,7 +39,7 @@ const transport = () => { return {ok: true} as T; } }; - return {api, starts, completed, chunks, final, onChunk, onStart}; + return {api, starts, completed, discarded, chunks, final, onChunk, onStart}; }; describe('uploadProjectForm', () => { @@ -121,12 +126,30 @@ describe('uploadProjectForm', () => { }); it('reports an uncertain final save so callers keep the draft', async () => { - const {api, final} = transport(); + const {api, final, discarded} = transport(); final.mockImplementationOnce(() => { throw Object.assign(new Error('Gateway timed out'), {status: 524}); }); const form = new FormData(); - form.append('project', new Blob(['sb3'])); + form.append('project', archive(90_000_000)); await expect(uploadProjectForm(api, '123', form)).rejects.toMatchObject({code: 'upload_processing_timeout'}); + expect(discarded).toEqual([]); + }); + + it('releases the staged archives before allowing a retry after a definite refusal', async () => { + const {api, final, discarded} = transport(); + const refusal = Object.assign(new Error('Missing worktree assets'), { + status: 409, code: 'worktree_assets_unavailable' + }); + final.mockImplementationOnce(() => { + throw refusal; + }); + const form = new FormData(); + form.append('project', archive(90_000_000)); + form.append('workspace', new Blob(['workspace'])); + await expect(uploadProjectForm(api, '123', form)).rejects.toBe(refusal); + expect(discarded).toEqual([ + '/projects/123/upload-parts/token1/discard', '/projects/123/upload-parts/token2/discard' + ]); }); });