feat(studio): a book saved by a newer Studio opens read-only instead of losing what it cannot read

- A book carries schemaRev. The reader that meets a newer one opens the book
  read-only with a reload banner and saves nothing, where it used to drop the
  elements it could not read on the next save.
- The server refuses a save, a restore or a tool edit that would write an older
  revision over a newer book or one newer than itself (409 book_schema_newer),
  on REST and through every book tool alike.
- normalizeBookDocument moves to book-normalize.ts.
- Print waits for photos eagerly and up to 15 s for an export of more than 40
  photos, and skips images without a source.
This commit is contained in:
Maurice
2026-10-23 14:14:54 +02:00
parent 3292a092ae
commit 30382dc366
52 changed files with 1036 additions and 135 deletions
@@ -8,7 +8,14 @@ import { JourneyDomainService } from './journey-domain.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { BookDocument, BookRecord, BookSummary } from '@trek/shared';
import { BOOK_DESIGN_LIMITS, normalizeBookDocument } from '@trek/shared';
import {
BOOK_DESIGN_LIMITS,
BOOK_SCHEMA_NEWER_CODE,
BOOK_SCHEMA_REV,
bookSchemaRev,
normalizeBookDocument,
stampBookSchemaRev,
} from '@trek/shared';
/**
* What an edit of the book hands back to `editBook`: the record's title and
@@ -59,6 +66,15 @@ interface BookEditOptions extends BookWriteOrigin {
*
* The alternative — last write wins — is not a simpler version of this. It is
* the same thing with the failure moved somewhere nobody sees it.
*
* ── Format revisions ─────────────────────────────────────────────────────
*
* A book says which revision of the format wrote it (book-schema-rev.ts in
* @trek/shared). A save from a writer older than the stored book is refused,
* because that writer has already dropped whatever it could not read; so is
* one newer than this server, which would drop the same on the way in. The
* book tools write only books this server reads whole, and stamp what they
* write with its revision.
*/
@Injectable()
export class JourneyBookService {
@@ -166,6 +182,7 @@ export class JourneyBookService {
userId: number,
input: { title: string; document: unknown; baseVersion?: number },
): Promise<{ record: BookRecord } | { conflict: BookRecord }> {
refuseNewerThanServer(bookSchemaRev(input.document));
const document = JSON.stringify(normalizeBookDocument(input.document));
// M1 (rule 11/24) — JB3's existing-link read and JB4's insert are
@@ -187,6 +204,10 @@ export class JourneyBookService {
return { record: (await this.byId(id))! };
}
// An older writer has already lost what it could not read; it does not get to save that loss.
const stored = storedSchemaRev(existing.document);
if (stored > bookSchemaRev(input.document)) throw newerBook(stored);
/*
* The version goes in the WHERE clause rather than being checked first.
* Read-then-write leaves a window between the two in which another save can
@@ -249,11 +270,15 @@ export class JourneyBookService {
if (options.expectedVersion !== undefined && current?.version !== options.expectedVersion) {
throw bookMoved(current);
}
// `current` is the book as this server reads it, which for a newer book is the book minus what it dropped.
if (row) refuseNewerThanServer(storedSchemaRev(row.document));
const next = await edit(current);
// What the edit hands back is checked too: a kept revision from a newer server, put back after a downgrade, would land stripped yet still stamped newer.
refuseNewerThanServer(bookSchemaRev(next.document));
if (current && next.unchanged) {
return { record: current, result: next.result, wrote: false, revisionId: null };
}
const document = JSON.stringify(normalizeBookDocument(next.document));
const document = JSON.stringify(normalizeBookDocument(stampBookSchemaRev(next.document)));
if (!row) {
const id = await this.booksRepo.insertBook(journeyId, next.title, document, userId);
return { record: await this.written(id), result: next.result, wrote: true, revisionId: null };
@@ -341,6 +366,31 @@ function bookMoved(current: BookRecord | null): DomainError {
});
}
/**
* The book was written by a newer revision of the format than the writer (or
* this server) knows. 409 like a moved book, with the code the Studio reads to
* open the book read-only and ask for a reload; no `current`, because there is
* nothing here an older writer could safely take.
*/
function newerBook(schemaRev: number): DomainError {
return new DomainError(409, 'Book was saved by a newer version of TREK Studio', {
code: BOOK_SCHEMA_NEWER_CODE,
details: { code: BOOK_SCHEMA_NEWER_CODE, schemaRev },
mcpMessage:
'This book was saved by a newer version of TREK than this server runs. Changing it here would drop what that version added, so it stays as it is.',
});
}
/** Refuse a book written by a revision this server cannot read whole. */
function refuseNewerThanServer(schemaRev: number): void {
if (schemaRev > BOOK_SCHEMA_REV) throw newerBook(schemaRev);
}
/** The revision a stored row's document says it was written by; broken JSON reads as 1, like its document. */
function storedSchemaRev(raw: string): number {
return bookSchemaRev(safeParse(raw));
}
/** JSON that will not parse is an empty document, never an exception. */
function safeParse(raw: string): unknown {
try {
+63 -1
View File
@@ -9,14 +9,18 @@
* viewer's write is refused with the tool's own words, and an operation the
* engine refuses with the operation it names; a REST save and an MCP write
* send the same event to the same users, REST leaving out the tab that saved
* and MCP none; and the tools are gone while the Journey addon is off.
* and MCP none; the tools are gone while the Journey addon is off; and a book
* a newer Studio wrote is refused with 409 and its code over both, even when
* its document holds what this build cannot parse.
*/
import { ADDON_IDS } from '../../src/addons';
import { buildApp } from '../../src/bootstrap';
import { JourneyBooks } from '../../src/db/entities/JourneyBooks.entity';
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { authCookie } from '../helpers/auth';
import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';
import { findRow, updateRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeUser } from '../helpers/factories/users';
import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';
@@ -198,4 +202,62 @@ describe('Studio book over MCP and REST', () => {
expect(names.filter((name) => BOOK_TOOLS.includes(name))).toEqual([]);
expect(names.length).toBeGreaterThan(0);
});
it('JBE2E-005: a book a newer Studio saved refuses a REST save with 409 and its code, and an MCP write in its words', async () => {
const { owner, journey, inner } = await journeyWithBook();
const before = await request(app.getHttpServer())
.get(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id));
const row = await findRow(orm, JourneyBooks, { journey: journey.id });
const newer = JSON.stringify({ ...JSON.parse(String(row?.document)), schemaRev: 2 });
await updateRows(orm, JourneyBooks, { journey: journey.id }, { document: newer });
const saved = await request(app.getHttpServer())
.put(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id))
.send({ title: before.body.book.title, document: before.body.book.document, baseVersion: 1 });
expect(saved.status).toBe(409);
expect(saved.body).toEqual({
error: 'Book was saved by a newer version of TREK Studio',
code: 'book_schema_newer',
schemaRev: 2,
});
const tool = await callTool(owner.id, 'edit_book_page', {
journeyId: journey.id,
spreadId: inner,
ops: [{ op: 'background', color: '#202020' }],
});
expect(tool).toEqual({
error:
'This book was saved by a newer version of TREK than this server runs. Changing it here would drop what that version added, so it stays as it is.',
});
expect(sent()).toEqual([]);
const after = await findRow(orm, JourneyBooks, { journey: journey.id });
expect([after?.version, after?.document]).toEqual([1, newer]);
});
it('JBE2E-006: a save of a book a newer Studio wrote, with a kind this one cannot read, is a 409 with its code, not a 400', async () => {
const { owner, journey } = await journeyWithBook();
const before = await request(app.getHttpServer())
.get(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id));
const document = before.body.book.document as { spreads: Array<{ elements: unknown[] }> };
const frame = { x: 10, y: 10, w: 40, h: 40 };
document.spreads[0]?.elements.push({ id: 'from-later', kind: 'sticker', frame, stickerId: 'lemon' });
const saved = await request(app.getHttpServer())
.put(`/api/journeys/${journey.id}/book`)
.set('Cookie', authCookie(owner.id))
.send({ title: before.body.book.title, document: { ...document, schemaRev: 2 }, baseVersion: 1 });
expect(saved.status).toBe(409);
expect(saved.body).toEqual({
error: 'Book was saved by a newer version of TREK Studio',
code: 'book_schema_newer',
schemaRev: 2,
});
expect(sent()).toEqual([]);
const after = await findRow(orm, JourneyBooks, { journey: journey.id });
expect(after?.version).toBe(1);
});
});
@@ -620,6 +620,116 @@ describe('editBook', () => {
});
});
// -- Format revisions ---------------------------------------------------------
/*
* A book written by a newer revision of the format than the writer knows. The
* older writer has already dropped what it could not read, so its save, from
* an old tab or a replayed offline copy, must not land; nor may the book tools
* of a server that cannot read the book whole.
*/
describe('format revisions', () => {
/** A journey whose stored book says it was written by revision `schemaRev`. */
async function storedAt(schemaRev: number) {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
await insertRow(await sharedTestOrm(testDb), JourneyBooks, {
journey: journey.id,
title: 'T',
document: JSON.stringify({ ...doc('newer'), schemaRev }),
version: 1,
});
return { user, journey };
}
const refusalOf = (thrown: unknown) =>
thrown instanceof DomainError ? [thrown.getStatus(), thrown.code, thrown.toBody().code] : thrown;
it('JBOOK-011: refuses a save from a writer older than the stored book with 409 and the code, writing and sending nothing', async () => {
const { user, journey } = await storedAt(2);
const rec = await recordSends();
try {
const thrown = await catchDomainError(() =>
books.saveBook(journey.id, user.id, { title: 'T', document: doc('older'), baseVersion: 1 }),
);
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect(thrown instanceof DomainError && thrown.toBody()).toMatchObject({
error: 'Book was saved by a newer version of TREK Studio',
schemaRev: 2,
});
expect(rec.sent).toEqual([]);
const stored = await books.getBook(journey.id, user.id);
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', 2]);
} finally {
rec.restore();
}
});
it('JBOOK-012: refuses a document newer than this server reads, first save and later save alike', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const ahead = { ...doc('ahead'), schemaRev: 9 };
const first = await catchDomainError(() => books.saveBook(journey.id, user.id, { title: 'T', document: ahead }));
expect(refusalOf(first)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect(await books.getBook(journey.id, user.id)).toBeNull();
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('one') });
const later = await catchDomainError(() =>
books.saveBook(journey.id, user.id, { title: 'T', document: ahead, baseVersion: 1 }),
);
expect(refusalOf(later)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect((await books.getBook(journey.id, user.id))?.document.title).toBe('one');
});
it('JBOOK-013: a save at the stored revision or above it lands as before, and a book of today stores no revision', async () => {
const { user, journey } = await storedAt(1);
const same = await books.saveBook(journey.id, user.id, {
title: 'T',
document: { ...doc('same'), schemaRev: 1 },
baseVersion: 1,
});
expect(same && 'record' in same && same.record.version).toBe(2);
const plain = await books.saveBook(journey.id, user.id, { title: 'T', document: doc('plain'), baseVersion: 2 });
expect(plain && 'record' in plain && plain.record.version).toBe(3);
const row = await findRow(await sharedTestOrm(testDb), JourneyBooks, { journey: journey.id });
expect(JSON.parse(String(row?.document))).not.toHaveProperty('schemaRev');
});
it('JBOOK-014: the book tools leave a book this server cannot read whole alone, before any edit runs', async () => {
const { user, journey } = await storedAt(2);
const rec = await recordSends();
try {
const edit = vi.fn(() => ({ title: 'T', document: normalizeBookDocument(doc('tool')), result: null }));
const thrown = await catchDomainError(() => books.editBook(journey.id, user.id, edit));
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect(thrown instanceof DomainError && thrown.mcpMessage).toMatch(/newer version of TREK/);
expect(edit).not.toHaveBeenCalled();
expect(rec.sent).toEqual([]);
expect((await books.getBook(journey.id, user.id))?.document.title).toBe('newer');
} finally {
rec.restore();
}
});
it('JBOOK-015: an edit that hands back a document newer than this server reads is refused, the stored book untouched', async () => {
const { user, journey } = await storedAt(1);
const rec = await recordSends();
try {
const ahead = normalizeBookDocument({ ...doc('ahead'), schemaRev: 2 });
const thrown = await catchDomainError(() =>
books.editBook(journey.id, user.id, () => ({ title: 'T', document: ahead, result: null })),
);
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
expect(rec.sent).toEqual([]);
const stored = await books.getBook(journey.id, user.id);
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', 1]);
} finally {
rec.restore();
}
});
});
// -- Deleting -----------------------------------------------------------------
describe('deleting', () => {
@@ -15,7 +15,7 @@
* stale version, and forgets the draft; a journey without a book gets a new
* one and no revision; restoring the revision puts the book back only at the
* version the apply left, and never writes a revision that does not read
* back; five revisions are kept.
* back or that a newer TREK kept; five revisions are kept.
*/
import { JourneyBookRevisions } from '../../../../src/db/entities/JourneyBookRevisions.entity';
import { JourneyEntryPhotos } from '../../../../src/db/entities/JourneyEntryPhotos.entity';
@@ -321,6 +321,25 @@ describe('taking a design back', () => {
expect(told()).toEqual([]);
});
it('JBDSN-011: a revision kept by a newer TREK is refused, never put back stripped of what this one cannot read', async () => {
const { journey, owner } = await crew();
const answer = await designs.design(journey.id, owner.id);
const applied = await designs.apply(journey.id, owner.id, { designId: answer.design_id });
const revisionId = applied.revision_id ?? 0;
const kept = await findRow(orm, JourneyBookRevisions, { id: revisionId });
const newer = JSON.stringify({ ...JSON.parse(String(kept?.document)), schemaRev: 2 });
await updateRows(orm, JourneyBookRevisions, { id: revisionId }, { document: newer });
t.realtime.reset();
const back = { revisionId, expectedVersion: applied.version };
expect(await refusal(() => designs.restoreRevision(journey.id, owner.id, back))).toEqual({
status: 409,
code: 'book_schema_newer',
});
expect(await version(journey.id, owner.id)).toBe(applied.version);
expect(told()).toEqual([]);
});
it('JBDSN-009: a journey keeps its newest five revisions', async () => {
const { journey, owner } = await crew();
const books = t.get(JourneyBookService);