From e5cdb22cc9a65ee2387a431bedc009ad5ff4afd5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 25 Nov 2026 21:55:59 -0500 Subject: [PATCH] fix: Restored revisions via API are overwritten on next edit (#14714) * fix: Restore collaborative state when restoring a revision via the API * fix: Normalize restored content and do not fail on collaboration notify errors * fix: Read state under a row lock when restoring a revision --- server/commands/documentRestorer.ts | 16 +- server/models/Document.ts | 17 +- server/models/helpers/DocumentHelper.tsx | 55 +++--- server/routes/api/documents/documents.test.ts | 170 ++++++++++++++++++ 4 files changed, 233 insertions(+), 25 deletions(-) diff --git a/server/commands/documentRestorer.ts b/server/commands/documentRestorer.ts index ee9f832462..5772163958 100644 --- a/server/commands/documentRestorer.ts +++ b/server/commands/documentRestorer.ts @@ -1,7 +1,7 @@ import { traceFunction } from "@server/logging/tracing"; import { ParamRequiredError, ValidationError } from "@server/errors"; -import { Collection, Revision } from "@server/models"; -import type { Document } from "@server/models"; +import { Transaction } from "sequelize"; +import { Collection, Document, Revision } from "@server/models"; import { authorize } from "@server/policies"; import type { Context } from "@server/types"; @@ -47,6 +47,18 @@ async function documentRestorer( }); authorize(document, "restore", revision); + // read the state under a row lock, so the collaboration server cannot + // create it from the pre-restore content before this commits + const { state } = await Document.unscoped().findOne({ + attributes: ["id", "state"], + where: { id: document.id }, + transaction, + lock: Transaction.LOCK.NO_KEY_UPDATE, + paranoid: false, + rejectOnEmpty: true, + }); + document.state = state; + await document.restoreFromRevision(revision); await document.saveWithCtx(ctx, undefined, { name: "restore" }); return document; diff --git a/server/models/Document.ts b/server/models/Document.ts index 58007cce0d..b6f24b061b 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -52,11 +52,14 @@ import type { SourceMetadata, } from "@shared/types"; import { DocumentPreferenceDefaults } from "@shared/constants"; +import { withTrailingNode } from "@shared/editor/lib/trailingNode"; +import { toError } from "@shared/utils/error"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { UrlHelper } from "@shared/utils/UrlHelper"; import slugify from "@server/utils/slugify"; import { DeprecationValidation, DocumentValidation } from "@shared/validations"; import { InvalidRequestError, ValidationError } from "@server/errors"; +import Logger from "@server/logging/Logger"; import { afterCommit } from "@server/storage/transaction"; import { CacheHelper } from "@server/utils/CacheHelper"; import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper"; @@ -696,7 +699,14 @@ class Document extends ArchivableModel< if (model.changed("state") && ctx.auth?.user?.id) { const actorId = ctx.auth.user.id; const notify = async () => { - await APIUpdateExtension.notifyUpdate(model.id, actorId); + try { + await APIUpdateExtension.notifyUpdate(model.id, actorId); + } catch (err) { + // the change is committed, so a failed notification must not fail the request + Logger.error("Failed to notify collaboration server", toError(err), { + documentId: model.id, + }); + } }; void afterCommit(ctx.transaction, notify); @@ -1181,10 +1191,13 @@ class Document extends ArchivableModel< throw new Error("Revision does not belong to this document"); } - this.content = revision.content; + // match the editor's normalized form so open editors do not repair it + const doc = withTrailingNode(DocumentHelper.toProsemirror(revision)); + this.content = doc.toJSON(); this.text = await DocumentHelper.toMarkdown(revision, { includeTitle: false, }); + DocumentHelper.applyToState(this, doc); this.title = revision.title; this.icon = revision.icon; this.color = revision.color; diff --git a/server/models/helpers/DocumentHelper.tsx b/server/models/helpers/DocumentHelper.tsx index bb4abc086c..316f942362 100644 --- a/server/models/helpers/DocumentHelper.tsx +++ b/server/models/helpers/DocumentHelper.tsx @@ -737,31 +737,44 @@ export class DocumentHelper { // own repairs back in response to this change. doc = withTrailingNode(doc); document.content = doc.toJSON(); - - if (document.state) { - const ydoc = new Y.Doc(); - Y.applyUpdate(ydoc, document.state); - const type = ydoc.get("default", Y.XmlFragment) as Y.XmlFragment; - - if (!type.doc) { - throw new Error("type.doc not found"); - } - - // apply new document to existing ydoc - updateYFragment(type.doc, type, doc, { - mapping: new Map(), - isOMark: new Map(), - }); - - const state = Y.encodeStateAsUpdate(ydoc); - - document.state = Buffer.from(state); - document.changed("state", true); - } + DocumentHelper.applyToState(document, doc); return document; } + /** + * Updates the collaborative state of a document to match the given content. + * Documents without state are not changed, as state is derived from content + * when they are first opened. + * + * @param document The document to update. + * @param doc The new content of the document. + */ + static applyToState(document: Document, doc: Node) { + if (!document.state) { + return; + } + + const ydoc = new Y.Doc(); + Y.applyUpdate(ydoc, document.state); + const type = ydoc.get("default", Y.XmlFragment) as Y.XmlFragment; + + if (!type.doc) { + throw new Error("type.doc not found"); + } + + // apply new document to existing ydoc + updateYFragment(type.doc, type, doc, { + mapping: new Map(), + isOMark: new Map(), + }); + + const state = Y.encodeStateAsUpdate(ydoc); + + document.state = Buffer.from(state); + document.changed("state", true); + } + /** * Attempt a surgical patch on a single affected top-level block. For * textblocks this does an inline replacement. For container nodes (lists, diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 34b55867a8..a157fb8441 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -4,6 +4,8 @@ import path from "node:path"; import { faker } from "@faker-js/faker"; import { addMinutes, subDays } from "date-fns"; import FormData from "form-data"; +import { yDocToProsemirrorJSON } from "y-prosemirror"; +import * as Y from "yjs"; import { CollectionPermission, DocumentPermission, @@ -16,6 +18,7 @@ import { } from "@shared/types"; import { TextHelper } from "@shared/utils/TextHelper"; import { DeprecationValidation, DocumentValidation } from "@shared/validations"; +import { APIUpdateExtension } from "@server/collaboration/APIUpdateExtension"; import { createContext } from "@server/context"; import { parser } from "@server/editor"; import type { Group, User } from "@server/models"; @@ -35,7 +38,9 @@ import { import { RelationshipType } from "@server/models/Relationship"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import HTMLHelper from "@server/models/helpers/HTMLHelper"; +import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import DocumentImportTask from "@server/queues/tasks/DocumentImportTask"; +import { sequelize } from "@server/storage/database"; import FileStorage from "@server/storage/files"; import { buildShare, @@ -6201,6 +6206,171 @@ describe("#documents.restore", () => { expect(body.data.data).toEqual(previous); }); + it("should restore the collaborative state to a previous version", async () => { + const notifyUpdateSpy = vi + .spyOn(APIUpdateExtension, "notifyUpdate") + .mockResolvedValue(undefined); + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + text: "original", + }); + const revision = await Revision.createFromDocument( + createContext({ user }), + document + ); + + // simulate an edit made in the collaborative editor + const updated = parser.parse("updated")?.toJSON(); + document.content = updated; + document.state = Buffer.from( + Y.encodeStateAsUpdate(ProsemirrorHelper.toYDoc(updated)) + ); + await document.save(); + + const res = await server.post("/api/documents.restore", user, { + body: { + id: document.id, + revisionId: revision.id, + }, + }); + expect(res.status).toEqual(200); + expect(notifyUpdateSpy).toHaveBeenCalledWith(document.id, user.id); + notifyUpdateSpy.mockRestore(); + + const reloaded = await Document.findByPk(document.id, { + includeState: true, + rejectOnEmpty: true, + }); + const ydoc = new Y.Doc(); + Y.applyUpdate(ydoc, DocumentHelper.toState(reloaded)); + expect(yDocToProsemirrorJSON(ydoc, "default")).toEqual(revision.content); + }); + + it("should wait for the collaboration server to create the initial state", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + text: "original", + }); + const revision = await Revision.createFromDocument( + createContext({ user }), + document + ); + document.content = parser.parse("updated")?.toJSON(); + await document.save(); + expect(document.state).toBeFalsy(); + + // hold the row lock that the collaboration server takes on first load + let restored = false; + let request: ReturnType | undefined; + await sequelize.transaction(async (transaction) => { + await Document.unscoped().findOne({ + where: { id: document.id }, + attributes: ["id"], + transaction, + lock: transaction.LOCK.NO_KEY_UPDATE, + }); + request = server.post("/api/documents.restore", user, { + body: { + id: document.id, + revisionId: revision.id, + }, + }); + void request.then(() => { + restored = true; + }); + await new Promise((resolve) => setTimeout(resolve, 250)); + expect(restored).toEqual(false); + + await Document.unscoped().update( + { + state: Buffer.from( + Y.encodeStateAsUpdate(ProsemirrorHelper.toYDoc("updated")) + ), + }, + { where: { id: document.id }, transaction } + ); + }); + + const res = await request; + expect(res?.status).toEqual(200); + + const reloaded = await Document.findByPk(document.id, { + includeState: true, + rejectOnEmpty: true, + }); + const ydoc = new Y.Doc(); + Y.applyUpdate(ydoc, DocumentHelper.toState(reloaded)); + expect(yDocToProsemirrorJSON(ydoc, "default")).toEqual(revision.content); + }); + + it("should add the trailing paragraph when restoring a revision", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + content: parser.parse("- item")?.toJSON(), + }); + const revision = await Revision.createFromDocument( + createContext({ user }), + document + ); + document.state = Buffer.from( + Y.encodeStateAsUpdate(ProsemirrorHelper.toYDoc("updated")) + ); + await document.save(); + + const res = await server.post("/api/documents.restore", user, { + body: { + id: document.id, + revisionId: revision.id, + }, + }); + expect(res.status).toEqual(200); + + const reloaded = await Document.findByPk(document.id, { + includeState: true, + rejectOnEmpty: true, + }); + const ydoc = new Y.Doc(); + Y.applyUpdate(ydoc, DocumentHelper.toState(reloaded)); + const state = yDocToProsemirrorJSON(ydoc, "default"); + expect(state.content?.at(-1)?.type).toEqual("paragraph"); + expect(reloaded.content?.content?.at(-1)?.type).toEqual("paragraph"); + }); + + it("should restore a revision when the collaboration server cannot be notified", async () => { + const notifyUpdateSpy = vi + .spyOn(APIUpdateExtension, "notifyUpdate") + .mockRejectedValue(new Error("Redis unavailable")); + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const revision = await Revision.createFromDocument( + createContext({ user }), + document + ); + document.state = Buffer.from( + Y.encodeStateAsUpdate(ProsemirrorHelper.toYDoc("updated")) + ); + await document.save(); + + const res = await server.post("/api/documents.restore", user, { + body: { + id: document.id, + revisionId: revision.id, + }, + }); + expect(res.status).toEqual(200); + expect(notifyUpdateSpy).toHaveBeenCalled(); + notifyUpdateSpy.mockRestore(); + }); + it("should not allow restoring a revision in another document", async () => { const user = await buildUser(); const document = await buildDocument({