Files
vibemake/tests/cad/save.test.js
T
2026-11-05 17:50:35 +08:00

375 lines
18 KiB
JavaScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
globalThis.location = { hostname: 'localhost', href: 'http://localhost/cad/', origin: 'http://localhost' };
const { SaveCoordinator, validateReceipt } = await import('../../js/cad/save.js');
function fixture() {
const logs = [], records = new Map();
let dirty = true, currentRevision = 7, version = 3, uploadNumber = 0;
const snapshot = {
snapshotId: crypto.randomUUID(),
binding: 'binding-a',
bytes: new Uint8Array([1, 2, 3]),
containerFormat: 'solidcraft-container/1',
documentFormat: 'solidcraft/99',
engineBuild: 'build-a',
revision: 7,
};
const bridge = {
getState: async () => ({ dirty: dirty || currentRevision !== snapshot.revision }),
createSnapshot: async ({ snapshotId } = {}) => {
logs.push('capture');
return { ...snapshot, snapshotId: snapshotId || snapshot.snapshotId };
},
acknowledgeSave: async (ack) => {
logs.push(['ack', ack]);
dirty = currentRevision !== snapshot.revision;
},
releaseSnapshot: async (id) => logs.push(['release', id]),
};
const store = {
key: (user, project, session, kind) => JSON.stringify([user, project, session, kind]),
put: async (user, project, session, kind, value) => {
const key = JSON.stringify([user, project, session, kind]);
records.set(key, { key, user, project, session, kind, ...value });
logs.push(['persist', kind]);
},
clearAcknowledged: async (user, project, snapshotId) => {
for (const [key, value] of records) if (value.user === user && value.project === project && value.snapshotId === snapshotId) records.delete(key);
},
remove: async (key) => records.delete(key),
list: async (user, project, kind) => [...records.values()].filter((record) =>
record.user === user && record.project === project && record.kind === kind),
};
const api = {
get: async () => ({ cadProjectCode: 'project-a', version }),
uploadCover: async (cover) => { logs.push(['cover-upload', cover]); return 'https://cdn.example/project-covers/plate.png'; },
setCover: async (projectId, coverUrl) => { logs.push(['cover-patch', projectId, coverUrl]); return { version, coverUrl }; },
assertIdentity() {},
signCalls: [],
commitCalls: [],
signUpload: async (project, request) => {
api.signCalls.push({ project, request });
const uploadCode = 'upload-' + (++uploadNumber);
logs.push('signature');
return { uploadCode, uploadUrl: 'https://oss.example/' + uploadCode, formFields: { key: uploadCode }, expiresAt: 'later' };
},
commit: async (project, uploadCode) => {
api.commitCalls.push({ project, uploadCode });
logs.push('put-document');
if (api.commitHandler) return api.commitHandler(project, uploadCode, api.commitCalls.length);
version = Math.max(version, api.signCalls.at(-1)?.request.expectedVersion + 1 || version);
return { cadProjectCode: project, version, savedAt: '2026-11-03T04:00:00.000Z' };
},
};
const project = { id: 'project-a', version: 3, name: 'Plate' };
const saver = new SaveCoordinator({
api, bridge, store, user: 'owner-a', project, binding: snapshot.binding, session: 'tab-a',
hash: async () => 'digest-a',
uploader: async (signature) => { logs.push(['upload', signature.uploadCode]); },
sleep: async () => {},
});
return {
saver, api, bridge, store, logs, records, snapshot, project,
setRevision: (revision) => { currentRevision = revision; },
dirty: () => dirty,
};
}
function withCover(value = fixture()) {
value.snapshot.cover = { bytes: new Uint8Array([137, 80, 78, 71]), mimeType: 'image/png', width: 640, height: 400 };
return value;
}
test('cover comes from the saved snapshot and is uploaded only after the document ACK', async () => {
const value = withCover(), original = value.snapshot.cover;
value.saver.uploader = async () => { value.setRevision(8); value.snapshot.cover = { bytes: new Uint8Array([99]), mimeType: 'image/png' }; };
await value.saver.save();
const coverUpload = value.logs.find((entry) => entry[0] === 'cover-upload');
assert.equal(coverUpload[1], original);
assert.ok(value.logs.findIndex((entry) => entry[0] === 'ack') < value.logs.indexOf(coverUpload));
assert.equal(value.project.coverUrl, 'https://cdn.example/project-covers/plate.png');
assert.equal(value.dirty(), true, 'later edits must remain unsaved');
assert.equal(value.saver.pendingCover, null);
assert.equal([...value.records.values()].filter((record) => record.kind === 'cover').length, 0);
});
test('failed cover upload preserves a saved native document and retries without a new version', async () => {
const value = withCover(), states = [];
value.saver.onState = (state) => states.push(state);
const upload = value.api.uploadCover;
value.api.uploadCover = async () => { throw Object.assign(new Error('disabled'), { code: 'OSS_DISABLED', status: 503 }); };
const result = await value.saver.save();
assert.equal(result.coverPending, true);
assert.equal(value.project.version, 4);
assert.equal(value.dirty(), false);
assert.equal(value.saver.operation, null);
assert.equal(states.at(-1), 'coverFailed');
assert.equal([...value.records.values()].filter((record) => record.kind === 'cover').length, 1);
value.api.uploadCover = upload;
await value.saver.save();
assert.equal(value.api.signCalls.length, 1);
assert.equal(value.api.commitCalls.length, 1);
assert.equal(value.logs.filter((entry) => entry === 'capture').length, 1);
assert.equal(value.project.version, 4);
assert.equal(states.at(-1), 'saved');
});
test('cover PATCH retries reuse the uploaded URL and a refreshed page can restore that job', async () => {
const value = withCover(), patch = value.api.setCover;
value.api.setCover = async () => { throw new Error('response lost'); };
await value.saver.save();
assert.equal(value.saver.pendingCover.coverUrl, 'https://cdn.example/project-covers/plate.png');
value.saver.pendingCover = null;
await value.saver.restoreCover();
assert.ok(value.saver.pendingCover);
value.api.setCover = patch;
await value.saver.save();
assert.equal(value.logs.filter((entry) => entry[0] === 'cover-upload').length, 1);
assert.equal(value.api.commitCalls.length, 1);
assert.equal(value.saver.pendingCover, null);
});
test('a remote version advancing during cover upload prevents a stale PATCH', async () => {
const value = withCover();
value.api.uploadCover = async () => {
value.api.get = async () => ({ version: 5 });
return 'https://cdn.example/project-covers/old.png';
};
const reply = await value.saver.save();
assert.equal(reply.coverSuperseded, true);
assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false);
assert.equal(value.saver.pendingCover, null);
});
test('disposal during cover upload never patches the project bound to a later session', async () => {
const value = withCover();
value.api.uploadCover = async () => { value.saver.dispose(); return 'https://cdn.example/project-covers/old.png'; };
await assert.rejects(value.saver.save(), { code: 'STALE_BINDING' });
assert.equal(value.dirty(), false, 'the native document was already saved');
assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false);
});
test('unavailable previews preserve an existing cover and still save the native document', async () => {
for (const cover of [null, undefined]) {
const value = fixture();
value.project.coverUrl = 'https://cdn.example/project-covers/previous.png';
value.snapshot.cover = cover;
const reply = await value.saver.save();
assert.equal(reply.coverUnavailable, true, 'an older bridge without cover data must also report the unavailable preview');
assert.equal(value.project.coverUrl, 'https://cdn.example/project-covers/previous.png');
assert.equal(value.dirty(), false);
assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false);
}
});
test('manual save signs, uploads, commits, then ACKs the exact snapshot', async () => {
const value = fixture();
await value.saver.save();
assert.deepEqual(value.api.signCalls[0], {
project: 'project-a',
request: { fileName: 'Plate.sc', sizeBytes: 3, expectedVersion: 3 },
});
assert.ok(value.logs.findIndex((entry) => Array.isArray(entry) && entry[0] === 'persist') < value.logs.indexOf('signature'));
assert.ok(value.logs.indexOf('signature') < value.logs.findIndex((entry) => Array.isArray(entry) && entry[0] === 'upload'));
assert.ok(value.logs.indexOf('put-document') < value.logs.findIndex((entry) => Array.isArray(entry) && entry[0] === 'ack'));
assert.equal(value.dirty(), false);
assert.equal(value.project.version, 4);
assert.equal(value.saver.operation, null);
});
test('editing after snapshot ACK leaves the later revision dirty', async () => {
const value = fixture();
value.saver.uploader = async () => value.setRevision(8);
await value.saver.save();
assert.equal(value.dirty(), true);
});
test('repeated save shares the same in-flight transaction', async () => {
const value = fixture();
let finishUpload;
value.saver.uploader = async () => new Promise((resolve) => { finishUpload = resolve; });
const first = value.saver.save(), second = value.saver.save();
assert.equal(first, second);
await new Promise((resolve) => setImmediate(resolve));
finishUpload();
await first;
assert.equal(value.logs.filter((entry) => entry === 'capture').length, 1);
assert.equal(value.api.signCalls.length, 1);
});
test('lost PUT response retries the same uploadCode without another signature or upload', async () => {
const value = fixture();
let committed = false;
value.api.commitHandler = async (project, uploadCode) => {
if (!committed) {
committed = true;
throw new Error('response lost after commit');
}
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await assert.rejects(value.saver.save(), /response lost/);
const operation = value.saver.operation;
assert.ok(operation.uploadCode);
await value.saver.save();
assert.equal(value.api.signCalls.length, 1);
assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 1);
assert.equal(value.api.commitCalls[0].uploadCode, value.api.commitCalls[1].uploadCode);
assert.equal(value.saver.operation, null);
});
test('lost OSS response confirms the original batch before any new upload', async () => {
const value = fixture();
value.saver.uploader = async (signature) => {
value.logs.push(['upload', signature.uploadCode]);
throw new TypeError('upload response lost');
};
await value.saver.save();
assert.equal(value.api.signCalls.length, 1);
assert.deepEqual(value.api.commitCalls, [{ project: 'project-a', uploadCode: 'upload-1' }]);
assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 1);
assert.equal(value.dirty(), false);
});
test('failed OSS POST renews a batch only after confirmation reports a missing file', async () => {
const value = fixture();
value.saver.uploader = async (signature) => {
value.logs.push(['upload', signature.uploadCode]);
if (signature.uploadCode === 'upload-1') throw Object.assign(new Error('OSS refused'), { code: 'UPLOAD_FAILED' });
};
value.api.commitHandler = async (project, uploadCode, count) => {
if (count === 1) throw Object.assign(new Error('missing'), { code: 'CAD_FILE_MISSING' });
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await value.saver.save();
assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-2']);
assert.deepEqual(value.logs.filter((entry) => typeof entry === 'string' && ['signature', 'put-document'].includes(entry)),
['signature', 'put-document', 'signature', 'put-document']);
});
test('unknown confirmation after a failed upload retains its batch and snapshot for retry', async () => {
const value = fixture();
value.saver.uploader = async (signature) => {
value.logs.push(['upload', signature.uploadCode]);
throw Object.assign(new Error('OSS response denied'), { code: 'CAD_UPLOAD_EXPIRED' });
};
value.api.commitHandler = async (project, uploadCode, count) => {
if (count === 1) throw Object.assign(new Error('OSS unavailable'), { code: 'CAD_OSS_ERROR', status: 502 });
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await assert.rejects(value.saver.save(), { code: 'CAD_OSS_ERROR' });
assert.equal(value.saver.operation.uploadCode, 'upload-1');
assert.equal(value.dirty(), true);
assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'ack'), false);
await value.saver.save();
assert.equal(value.api.signCalls.length, 1);
assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 1);
assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-1']);
});
test('only a backend expiry or size mismatch renews an uploaded batch', async () => {
for (const code of ['CAD_UPLOAD_EXPIRED', 'CAD_FILE_SIZE_MISMATCH']) {
const value = fixture();
value.api.commitHandler = async (project, uploadCode, count) => {
if (count === 1) throw Object.assign(new Error(code), { code, status: 409 });
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await value.saver.save();
assert.equal(value.api.signCalls.length, 2);
assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-2']);
assert.equal(value.project.version, 4);
}
});
test('a confirmed save removes its journal with a valid key', async () => {
const value = fixture(), removed = [];
value.store.remove = async (key) => { assert.equal(typeof key, 'string'); removed.push(key); };
value.saver.onStorageError = (error) => assert.fail(error.message);
await value.saver.save();
assert.deepEqual(removed, [value.store.key('owner-a', 'project-a', 'tab-a', 'operation')]);
});
test('refresh recovery confirms the persisted uploadCode first', async () => {
const value = fixture();
value.api.commitHandler = async (project) => ({
cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z',
});
const journal = {
projectId: 'project-a', user: 'owner-a', binding: 'binding-a', snapshotId: 'journal-snapshot',
bytes: new Uint8Array([1, 2, 3]), digest: 'digest-a',
request: { fileName: 'Plate.sc', sizeBytes: 3, expectedVersion: 3 }, uploadCode: 'original-upload',
};
const opened = { ...journal, journalKey: value.store.key('owner-a', 'project-a', 'old-tab', 'operation') };
value.saver.bridge.createSnapshot = async ({ snapshotId }) => ({ ...value.snapshot, snapshotId });
await value.saver.resume(opened);
assert.deepEqual(value.api.commitCalls[0], { project: 'project-a', uploadCode: 'original-upload' });
assert.equal(value.api.signCalls.length, 0);
assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'ack'), true);
});
test('missing or expired batch requests a new signature and uploads again', async () => {
const value = fixture();
value.api.commitHandler = async (project, uploadCode, count) => {
if (count === 1) throw Object.assign(new Error('missing object'), { code: 'CAD_FILE_MISSING' });
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await value.saver.save();
assert.equal(value.api.signCalls.length, 2);
assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 2);
});
test('version conflict keeps a local draft and blocks overwrite', async () => {
const value = fixture();
value.api.commitHandler = async () => { throw Object.assign(new Error('conflict'), { code: 'CAD_VERSION_CONFLICT', status: 409 }); };
await assert.rejects(value.saver.save(), { code: 'CAD_VERSION_CONFLICT' });
assert.equal(value.saver.conflicted, true);
assert.equal([...value.records.values()].some((record) => record.kind === 'draft' && record.baseVersion === 3), true);
assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'ack'), false);
await assert.rejects(value.saver.save(), { code: 'HEAD_CONFLICT' });
});
test('late reply after account or project disposal never ACKs', async () => {
const value = fixture();
value.api.commitHandler = async (project) => {
value.saver.dispose();
return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' };
};
await assert.rejects(value.saver.save(), { code: 'STALE_BINDING' });
assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'ack'), false);
});
test('snapshot from another document is released before any network request', async () => {
const value = fixture();
value.snapshot.binding = 'old-binding';
await assert.rejects(value.saver.save(), { code: 'STALE_BINDING' });
assert.equal(value.api.signCalls.length, 0);
assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'release'), true);
});
test('invalid format metadata is rejected before creating an upload', async () => {
const value = fixture();
value.snapshot.documentFormat = '';
await assert.rejects(value.saver.save(), { code: 'FORMAT_UNSUPPORTED' });
assert.equal(value.api.signCalls.length, 0);
});
test('empty projects can be saved even when the editor was not dirty', async () => {
const value = fixture();
value.setRevision(0);
await value.saver.save();
assert.equal(value.project.version, 4);
});
test('receipt must identify the project and the exact next version', () => {
const operation = { projectId: 'p', request: { expectedVersion: 1 } };
const valid = { cadProjectCode: 'p', version: 2, savedAt: 'date' };
assert.equal(validateReceipt(valid, operation), valid);
for (const update of [
{ cadProjectCode: 'other' },
{ version: 1 },
{ version: 3 },
{ savedAt: null },
]) assert.throws(() => validateReceipt({ ...valid, ...update }, operation), { code: 'INVALID_RECEIPT' });
});