Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/community/pages/MyStuff.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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}%`;
};

Expand Down
21 changes: 14 additions & 7 deletions src/lib/community/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/lib/community/publish.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' :
Expand Down
3 changes: 2 additions & 1 deletion src/modules/platform-api/response-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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|discard))?$/.test(path);

export const staleCacheTest = (method: string, path: string): CachedPathTest | null => {
const [collection, id, action] = pathSegments(path);
Expand Down
142 changes: 142 additions & 0 deletions src/modules/project-upload/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
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 UploadTransport = Pick<PlatformClient, 'request' | 'upload'>;

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 <T>(send: () => Promise<T>): Promise<T> => {
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, partPath: string, blob: Blob, chunks: number, onProgress: (loaded: number) => void
): Promise<void> => {
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}));
};

const sendProjectUpload = async <T>(
api: UploadTransport, path: string, form: FormData, onProgress?: UploadProgress
): Promise<T> => {
try {
return await api.upload<T>(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 <T>(
api: UploadTransport, projectId: string, form: FormData, onProgress?: UploadProgress
): Promise<T> => {
const projectPath = `/projects/${encodeURIComponent(projectId)}`;
const uploadPath = `${projectPath}/upload`;
const partsPath = `${projectPath}/upload-parts`;
const bytes = payloadBytes(form);
if (bytes < MAX_INLINE_BYTES) return sendProjectUpload<T>(api, uploadPath, 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);
});
const startedPaths: string[] = [];
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<T>(api, uploadPath, form, onProgress);
}
throw error;
}
const offset = stagedBytes;
const partPath = `${partsPath}/${encodeURIComponent(token)}`;
startedPaths.push(partPath);
await stagePart(api, partPath, file, chunks, loaded => {
reportProgress(offset + loaded);
});
completedPaths.push(partPath);
stagedBytes += file.size;
finalForm.delete(field);
finalForm.append(`${field}Token`, token);
}
return await sendProjectUpload<T>(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);
}
};
155 changes: 155 additions & 0 deletions test/unit/modules/project-upload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
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 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<void>>();
const onStart = jest.fn<() => void>();
const api: Pick<PlatformClient, 'request' | 'upload'> = {
request: <T>(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);
}
starts.push(options?.body);
onStart();
return Promise.resolve({token: `token${starts.length.toString()}`} as T);
},
upload: async <T>(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});
await onChunk(path);
} else {
final(form);
}
progress?.(10, 10);
return {ok: true} as T;
}
};
return {api, starts, completed, discarded, chunks, final, onChunk, onStart};
};

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<UploadProgress>();

const saved = uploadProjectForm(api, '123', form, progress);
await jest.advanceTimersByTimeAsync(500);
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]);
});

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<string>(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, discarded} = transport();
final.mockImplementationOnce(() => {
throw Object.assign(new Error('Gateway timed out'), {status: 524});
});
const form = new FormData();
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'
]);
});
});