294 lines
12 KiB
JavaScript
294 lines
12 KiB
JavaScript
import { cadError, sha256, uploadSource, MAX_COVER_BYTES, projectCoverUrl } from './api.js';
|
|
import { filename, CAD } from './config.js';
|
|
|
|
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
const isRetryableBatchError = (error) => ['CAD_FILE_MISSING', 'CAD_FILE_SIZE_MISMATCH', 'CAD_UPLOAD_EXPIRED'].includes(error?.code);
|
|
|
|
export function validateReceipt(reply, operation) {
|
|
const expectedVersion = operation.request.expectedVersion;
|
|
if (!reply || reply.cadProjectCode !== operation.projectId || !Number.isSafeInteger(reply.version)
|
|
|| reply.version !== expectedVersion + 1 || typeof reply.savedAt !== 'string' || !reply.savedAt) {
|
|
throw cadError('INVALID_RECEIPT');
|
|
}
|
|
return reply;
|
|
}
|
|
|
|
export class SaveCoordinator {
|
|
constructor({ api, bridge, store, user, project, binding, session, onState = () => {}, onStorageError = () => {},
|
|
uploader = uploadSource, hash = sha256, sleep = delay }) {
|
|
Object.assign(this, { api, bridge, store, user, project, binding, session, onState, onStorageError, uploader, hash, sleep });
|
|
this.active = null;
|
|
this.operation = null;
|
|
this.closed = false;
|
|
this.conflicted = false;
|
|
this.pendingCover = null;
|
|
this.coverUnavailable = false;
|
|
}
|
|
|
|
assertCurrent() {
|
|
this.api.assertIdentity();
|
|
if (this.closed) throw cadError('STALE_BINDING');
|
|
}
|
|
|
|
dispose() {
|
|
this.closed = true;
|
|
}
|
|
|
|
async persist() {
|
|
if (!this.operation) return;
|
|
const { signature, snapshot, ...journal } = this.operation;
|
|
try {
|
|
await this.store.put(this.user, this.project.id, this.session, 'operation', {
|
|
...journal,
|
|
journalKey: this.store.key(this.user, this.project.id, this.session, 'operation'),
|
|
});
|
|
} catch (error) {
|
|
this.onStorageError(error);
|
|
}
|
|
}
|
|
|
|
save() {
|
|
if (this.active) return this.active;
|
|
this.active = this.run().finally(() => { this.active = null; });
|
|
return this.active;
|
|
}
|
|
|
|
async run() {
|
|
this.assertCurrent();
|
|
if (this.conflicted) throw cadError('HEAD_CONFLICT');
|
|
// Retrying a failed cover must not upload the native file or increment its version again.
|
|
if (!this.operation && this.pendingCover && !(await this.bridge.getState()).dirty) return this.finishCover();
|
|
if (!this.operation) {
|
|
this.onState('preparing');
|
|
const snapshot = await this.bridge.createSnapshot({ includeCover: true });
|
|
if (snapshot.binding !== this.binding) {
|
|
await this.bridge.releaseSnapshot(snapshot.snapshotId);
|
|
throw cadError('STALE_BINDING');
|
|
}
|
|
const sizeBytes = snapshot.bytes?.byteLength;
|
|
if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= 0 || sizeBytes > CAD.maxSourceBytes) {
|
|
await this.bridge.releaseSnapshot(snapshot.snapshotId);
|
|
throw cadError('SOURCE_TOO_LARGE');
|
|
}
|
|
if (typeof snapshot.containerFormat !== 'string' || !snapshot.containerFormat
|
|
|| typeof snapshot.documentFormat !== 'string' || !snapshot.documentFormat) {
|
|
await this.bridge.releaseSnapshot(snapshot.snapshotId);
|
|
throw cadError('FORMAT_UNSUPPORTED');
|
|
}
|
|
const request = {
|
|
fileName: filename(this.project.name),
|
|
sizeBytes,
|
|
expectedVersion: this.project.version ?? this.project.headVersion ?? 0,
|
|
};
|
|
this.operation = {
|
|
projectId: this.project.id,
|
|
user: this.user,
|
|
binding: this.binding,
|
|
snapshotId: snapshot.snapshotId,
|
|
snapshot,
|
|
bytes: snapshot.bytes,
|
|
cover: snapshot.cover,
|
|
digest: await this.hash(snapshot.bytes),
|
|
request,
|
|
uploadCode: null,
|
|
};
|
|
await this.persist();
|
|
}
|
|
|
|
const operation = this.operation;
|
|
try {
|
|
this.assertCurrent();
|
|
let reply = null;
|
|
if (operation.uploadCode) {
|
|
this.onState('verifying');
|
|
try {
|
|
reply = await this.api.commit(operation.projectId, operation.uploadCode);
|
|
} catch (error) {
|
|
if (!isRetryableBatchError(error)) throw error;
|
|
}
|
|
}
|
|
|
|
if (!reply) {
|
|
let lastBatchError;
|
|
for (let attempt = 0; attempt < 3 && !reply; attempt++) {
|
|
this.assertCurrent();
|
|
const signature = await this.api.signUpload(operation.projectId, operation.request);
|
|
this.assertCurrent();
|
|
if (!signature?.uploadCode) throw cadError('BAD_RESPONSE');
|
|
operation.uploadCode = signature.uploadCode;
|
|
await this.persist();
|
|
this.onState('uploading');
|
|
try {
|
|
await this.uploader(signature, operation.bytes, operation.request.fileName);
|
|
} catch {
|
|
// OSS may have accepted the bytes even when its response was lost or refused.
|
|
// Only confirmation can decide whether this batch needs another upload.
|
|
}
|
|
this.assertCurrent();
|
|
this.onState('verifying');
|
|
try {
|
|
reply = await this.api.commit(operation.projectId, operation.uploadCode);
|
|
} catch (error) {
|
|
if (!isRetryableBatchError(error)) throw error;
|
|
lastBatchError = error;
|
|
}
|
|
}
|
|
if (!reply) throw lastBatchError || cadError('CAD_UPLOAD_EXPIRED');
|
|
}
|
|
|
|
this.assertCurrent();
|
|
validateReceipt(reply, operation);
|
|
await this.bridge.acknowledgeSave({ binding: this.binding, snapshotId: operation.snapshotId });
|
|
this.assertCurrent();
|
|
this.project.version = reply.version;
|
|
this.project.headVersion = reply.version;
|
|
this.project.savedAt = reply.savedAt;
|
|
this.project.lastSavedAt = reply.savedAt;
|
|
try {
|
|
await this.store.clearAcknowledged(this.user, operation.projectId, operation.snapshotId,
|
|
{ binding: this.binding, revision: operation.snapshot.revision });
|
|
await this.store.remove(operation.journalKey || this.store.key(this.user, operation.projectId, this.session, 'operation'),
|
|
operation.snapshotId);
|
|
} catch (error) {
|
|
this.onStorageError(error);
|
|
}
|
|
await this.bridge.releaseSnapshot(operation.snapshotId);
|
|
this.operation = null;
|
|
if (this.pendingCover) await this.clearCover(this.pendingCover);
|
|
this.coverUnavailable = !operation.cover;
|
|
if (operation.cover) {
|
|
this.pendingCover = {
|
|
user: this.user, projectId: operation.projectId, snapshotId: operation.snapshotId,
|
|
version: reply.version, savedAt: reply.savedAt, cover: operation.cover,
|
|
};
|
|
await this.persistCover();
|
|
return this.finishCover();
|
|
}
|
|
this.onState(this.coverUnavailable ? 'coverUnavailable' : 'saved');
|
|
return { ...reply, ...(this.coverUnavailable ? { coverUnavailable: true } : {}) };
|
|
} catch (error) {
|
|
const conflict = ['HEAD_CONFLICT', 'CAD_VERSION_CONFLICT'].includes(error?.code);
|
|
if (conflict) {
|
|
this.conflicted = true;
|
|
await this.forget(operation);
|
|
}
|
|
if (!this.closed && !['STALE_IDENTITY', 'STALE_BINDING'].includes(error?.code)) {
|
|
this.onState(conflict ? 'conflict' : error.status === 401 ? 'expired'
|
|
: [404, 410].includes(error.status) ? 'unavailable'
|
|
: globalThis.navigator?.onLine === false ? 'offline' : 'failed', error);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async persistCover() {
|
|
if (!this.pendingCover) return;
|
|
try {
|
|
await this.store.put(this.user, this.project.id, this.session, 'cover', this.pendingCover);
|
|
} catch (error) { this.onStorageError(error); }
|
|
}
|
|
|
|
async restoreCover() {
|
|
try {
|
|
const records = await this.store.list(this.user, this.project.id, 'cover');
|
|
this.assertCurrent();
|
|
const pending = records.find((record) => record.user === this.user && record.projectId === this.project.id
|
|
&& record.version === this.project.version && record.cover?.bytes instanceof Uint8Array
|
|
&& record.cover.bytes.byteLength > 0 && record.cover.bytes.byteLength <= MAX_COVER_BYTES);
|
|
if (pending) {
|
|
this.pendingCover = pending;
|
|
this.onState('coverFailed');
|
|
}
|
|
} catch (error) {
|
|
if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) throw error;
|
|
this.onStorageError(error);
|
|
}
|
|
}
|
|
|
|
async clearCover(pending) {
|
|
try {
|
|
await this.store.remove(pending.key || this.store.key(this.user, this.project.id, this.session, 'cover'), pending.snapshotId);
|
|
} catch (error) { this.onStorageError(error); }
|
|
if (this.pendingCover === pending) this.pendingCover = null;
|
|
}
|
|
|
|
async finishCover() {
|
|
const pending = this.pendingCover;
|
|
if (!pending) throw cadError('BAD_COVER');
|
|
const receipt = { cadProjectCode: pending.projectId, version: pending.version, savedAt: pending.savedAt };
|
|
try {
|
|
this.assertCurrent();
|
|
this.onState('coverUploading');
|
|
// PATCH has no version precondition. These checks avoid known stale publications;
|
|
// atomic cross-client protection would require a backend conditional update.
|
|
const current = await this.api.get(pending.projectId);
|
|
this.assertCurrent();
|
|
if (current.version !== pending.version) {
|
|
await this.clearCover(pending);
|
|
this.onState('saved');
|
|
return { ...receipt, coverSuperseded: true };
|
|
}
|
|
if (!pending.coverUrl) {
|
|
const coverUrl = await this.api.uploadCover(pending.cover);
|
|
this.assertCurrent();
|
|
if (!projectCoverUrl(coverUrl)) throw cadError('BAD_RESPONSE');
|
|
pending.coverUrl = coverUrl;
|
|
await this.persistCover();
|
|
}
|
|
const latest = await this.api.get(pending.projectId);
|
|
this.assertCurrent();
|
|
if (latest.version !== pending.version) {
|
|
await this.clearCover(pending);
|
|
this.onState('saved');
|
|
return { ...receipt, coverSuperseded: true };
|
|
}
|
|
const updated = await this.api.setCover(pending.projectId, pending.coverUrl);
|
|
this.assertCurrent();
|
|
this.project.coverUrl = updated.coverUrl;
|
|
this.coverUnavailable = false;
|
|
await this.clearCover(pending);
|
|
this.onState('saved');
|
|
return receipt;
|
|
} catch (error) {
|
|
if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) throw error;
|
|
this.onState('coverFailed', error);
|
|
return { ...receipt, coverPending: true };
|
|
}
|
|
}
|
|
|
|
async forget(operation) {
|
|
try {
|
|
await this.store.put(this.user, operation.projectId, this.session, 'draft', {
|
|
bytes: operation.bytes,
|
|
digest: operation.digest,
|
|
snapshotId: operation.snapshotId,
|
|
baseVersion: operation.request.expectedVersion,
|
|
binding: this.binding,
|
|
revision: operation.snapshot?.revision,
|
|
});
|
|
await this.store.remove(operation.journalKey || this.store.key(this.user, operation.projectId, this.session, 'operation'),
|
|
operation.snapshotId);
|
|
} catch (error) {
|
|
this.onStorageError(error);
|
|
}
|
|
await this.bridge.releaseSnapshot(operation.snapshotId);
|
|
this.operation = null;
|
|
}
|
|
|
|
async resume(journal) {
|
|
this.assertCurrent();
|
|
if (journal.user !== this.user || journal.projectId !== this.project.id
|
|
|| !(journal.bytes instanceof Uint8Array) || journal.bytes.byteLength !== journal.request.sizeBytes
|
|
|| (journal.digest && await this.hash(journal.bytes) !== journal.digest)) throw cadError('BAD_DESIGN');
|
|
const snapshot = await this.bridge.createSnapshot({ snapshotId: journal.snapshotId });
|
|
this.assertCurrent();
|
|
if (snapshot.binding !== this.binding) {
|
|
await this.bridge.releaseSnapshot(snapshot.snapshotId);
|
|
throw cadError('STALE_BINDING');
|
|
}
|
|
this.operation = { ...journal, snapshot, binding: this.binding, bytes: journal.bytes };
|
|
await this.persist();
|
|
return this.save();
|
|
}
|
|
}
|