Files
outline/app/scenes/Document/components/MultiplayerEditor.tsx
T
Tom Moor cca21437f5 Flatten collaborative state of large documents (#14587)
* feat: Flatten collaborative state of large documents

Replace edit history in large collaborative state with fresh state once a
document is idle with no open sessions, and when state is over the maximum
length on save. Each replacement increments a state generation that is part of
the collaboration room name, so old state never merges into the new state.

* fix: Refuse to load state of another generation and lock editor during reset

* Remove excessive tests

* fix: Reset rooms on all instances and check state generation during authentication

* refactor: Schedule state flattening only for changed rooms, from PersistenceExtension

* fix: Refuse API text updates applied to state of an earlier generation
2026-11-29 15:49:34 -05:00

507 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { WebSocketStatus } from "@hocuspocus/provider";
import { throttle } from "es-toolkit/compat";
import { Node as ProsemirrorNode } from "prosemirror-model";
import {
useState,
useLayoutEffect,
useMemo,
useEffect,
useEffectEvent,
useRef,
type Ref,
} from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
import * as Y from "yjs";
import {
DocumentReset,
EditorUpdateError,
} from "@shared/collaboration/CloseEvents";
import { buildDocumentName } from "@shared/collaboration/documentName";
import History from "@shared/editor/extensions/History";
import EDITOR_VERSION from "@shared/editor/version";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import type { Props as EditorProps } from "~/components/Editor";
import { useDocumentContext } from "~/components/DocumentContext";
import Editor from "~/components/Editor";
import type { Editor as SharedEditor } from "~/editor";
import MultiplayerExtension from "~/editor/extensions/Multiplayer";
import { MultiplayerUndo } from "~/editor/extensions/MultiplayerUndo";
import env from "~/env";
import useCurrentUser from "~/hooks/useCurrentUser";
import useIdle from "~/hooks/useIdle";
import usePageVisibility from "~/hooks/usePageVisibility";
import useStores from "~/hooks/useStores";
import type { AwarenessChangeEvent } from "~/types";
import Logger from "~/utils/Logger";
import {
CollaborationProvider,
type ConnectionMessageEvent,
type ConnectionStatusEvent,
} from "~/utils/multiplayer/CollaborationProvider";
import { IndexeddbPersistence } from "~/utils/multiplayer/IndexeddbPersistence";
import { homePath } from "~/utils/routeHelpers";
import { sleep } from "@shared/utils/timers";
type Props = EditorProps & {
id: string;
onSynced?: () => Promise<void>;
ref?: Ref<SharedEditor>;
};
type CollaborativeEditorProps = Props & {
/** The generation of the collaborative state to connect to. */
stateGeneration: number;
/** Called with the current generation when the server resets the state. */
onReset: (stateGeneration: number) => void;
};
/**
* A collaborative editor for a document. It mounts again with a new Y.Doc
* when the server replaces the collaborative state of the document.
*
* @param props the editor props.
* @returns the editor.
*/
function MultiplayerEditor(props: Props) {
const { documents } = useStores();
const [stateGeneration, setStateGeneration] = useState(
() => documents.get(props.id)?.stateGeneration ?? 0
);
return (
<CollaborativeEditor
key={stateGeneration}
{...props}
stateGeneration={stateGeneration}
onReset={setStateGeneration}
/>
);
}
function CollaborativeEditor({
onSynced,
ref,
stateGeneration,
onReset,
...props
}: CollaborativeEditorProps) {
const documentId = props.id;
const history = useHistory();
const { t } = useTranslation();
const currentUser = useCurrentUser();
const retryCount = useRef(0);
const { presence, auth, ui, documents } = useStores();
const documentContext = useDocumentContext();
const [editorVersionBehind, setEditorVersionBehind] = useState(false);
const [isResetting, setResetting] = useState(false);
const [showCursorNames, setShowCursorNames] = useState(false);
const [remoteProvider, setRemoteProvider] = useState<CollaborationProvider>();
const [hasLocalPersistence, setHasLocalPersistence] = useState(true);
const [isLocalSynced, setLocalSynced] = useState(false);
const [isRemoteSynced, setRemoteSynced] = useState(false);
const [ydoc] = useState(() => new Y.Doc());
const token = auth.collaborationToken;
const isIdle = useIdle();
const isVisible = usePageVisibility();
// Provider initialization must be within useLayoutEffect rather than useState
// or useMemo as both of these are ran twice in React StrictMode resulting in
// an orphaned websocket connection.
// see: https://github.com/facebook/react/issues/20090#issuecomment-715926549
useLayoutEffect(() => {
// Tracks whether this effect has been cleaned up so async persistence
// callbacks below do not update state afterwards.
let isActive = true;
const debug = env.ENVIRONMENT === "development";
const name = buildDocumentName(documentId, stateGeneration);
const localProvider =
typeof indexedDB !== "undefined"
? new IndexeddbPersistence(name, ydoc)
: undefined;
if (!localProvider) {
setHasLocalPersistence(false);
}
const provider = new CollaborationProvider({
parameters: {
editorVersion: EDITOR_VERSION,
},
url: `${env.COLLABORATION_URL}/collaboration`,
name,
document: ydoc,
token,
localProvider,
});
const syncScrollPosition = throttle(() => {
provider.setAwarenessField(
"scrollY",
window.scrollY / window.innerHeight
);
}, 250);
const finishObserving = () => {
if (ui.observingUserId) {
ui.setObservingUser(undefined);
}
};
window.addEventListener("click", finishObserving);
window.addEventListener("wheel", finishObserving);
window.addEventListener("scroll", syncScrollPosition, { passive: true });
provider.on("authenticationFailed", ({ reason }: { reason: string }) => {
provider.shouldConnect = false;
// These are followed by their close event, which is handled below.
if (
reason === DocumentReset.reason ||
reason === EditorUpdateError.reason
) {
return;
}
retryCount.current++;
void sleep(retryCount.current * 1000 - 1000).then(() =>
auth
.fetchAuth()
.then(() => {
provider.setConfiguration({ token: auth.collaborationToken });
void provider.connect();
provider.shouldConnect = true;
})
.catch(() => {
history.replace(homePath());
})
);
});
provider.on("awarenessChange", (event: AwarenessChangeEvent) => {
presence.updateFromAwarenessChangeEvent(
documentId,
provider.awareness.clientID,
event
);
event.states.forEach(({ user, scrollY }) => {
if (user) {
if (scrollY !== undefined && user.id === ui.observingUserId) {
window.scrollTo({
top: scrollY * window.innerHeight,
behavior: "smooth",
});
}
}
});
});
const showCursorNames = () => {
setShowCursorNames(true);
setTimeout(() => {
setShowCursorNames(false);
}, 2000);
provider.off("awarenessChange", showCursorNames);
};
provider.on("awarenessChange", showCursorNames);
const syncState = () => {
documentContext.setMultiplayerSyncState(
provider.hasPendingChanges,
provider.hasLocalPersistence
);
};
provider.on("syncStateChange", syncState);
syncState();
localProvider?.whenSynced
.then(() => {
if (!isActive || !localProvider.synced) {
return;
}
if (debug) {
Logger.debug("collaboration", "local synced");
}
// only set local storage to "synced" if it's loaded a non-empty doc
setLocalSynced(!!ydoc.get("default")._start);
})
.catch(() => {
// IndexedDB exists but is unusable, e.g. Firefox private browsing.
if (isActive) {
setHasLocalPersistence(false);
}
});
provider.on("synced", () => {
presence.touch(documentId, currentUser.id, false);
setRemoteSynced(true);
retryCount.current = 0;
});
provider.on("close", (ev: ConnectionMessageEvent) => {
// The local state is not current. Load the current generation, which
// mounts the editor again with a new Y.Doc.
if ("code" in ev.event && ev.event.code === DocumentReset.code) {
provider.shouldConnect = false;
// Edits made to this Y.Doc are discarded, so stop editing until the
// new generation mounts.
setResetting(true);
const handleResetFailed = () => {
if (isActive) {
toast.error(
t("The document could not be loaded – please reload the page")
);
}
};
void documents
.fetch(documentId, { force: true })
.then((document) => {
if (!isActive) {
return;
}
if (document.stateGeneration === stateGeneration) {
handleResetFailed();
return;
}
onReset(document.stateGeneration);
})
.catch(handleResetFailed);
return;
}
if ("code" in ev.event) {
// Note other close code are handled internally by the library
if (ev.event.code === EditorUpdateError.code) {
provider.shouldConnect = false;
}
documentContext.setMultiplayerStatus("disconnected", ev.event.code);
if (ev.event.code === EditorUpdateError.code) {
setEditorVersionBehind(true);
}
}
});
if (debug) {
provider.on("close", (ev: ConnectionMessageEvent) =>
Logger.debug("collaboration", "close", ev)
);
provider.on("message", (ev: ConnectionMessageEvent) =>
Logger.debug("collaboration", "incoming", {
message: ev.message,
})
);
provider.on("outgoingMessage", (ev: ConnectionMessageEvent) =>
Logger.debug("collaboration", "outgoing", {
message: ev.message,
})
);
}
provider.on("status", (ev: ConnectionStatusEvent) => {
if (documentContext.multiplayerStatus !== ev.status) {
documentContext.setMultiplayerStatus(ev.status, undefined);
}
});
setRemoteProvider(provider);
return () => {
isActive = false;
window.removeEventListener("click", finishObserving);
window.removeEventListener("wheel", finishObserving);
window.removeEventListener("scroll", syncScrollPosition);
provider?.destroy();
void localProvider?.destroy();
setRemoteProvider(undefined);
documentContext.setMultiplayerStatus(undefined, undefined);
documentContext.setMultiplayerSyncState(false, true);
};
// `token` is intentionally omitted, it is only read when establishing the
// connection and a refreshed token must not tear down the provider.
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
history,
t,
documentId,
ui,
documentContext,
presence,
ydoc,
currentUser.id,
auth,
documents,
stateGeneration,
onReset,
]);
// Remove the local state of earlier generations, it can not be used again.
useEffect(() => {
if (typeof indexedDB === "undefined") {
return;
}
for (let generation = 0; generation < stateGeneration; generation++) {
indexedDB.deleteDatabase(buildDocumentName(documentId, generation));
}
}, [documentId, stateGeneration]);
const user = useMemo(
() => ({
id: currentUser.id,
name: currentUser.name,
color: currentUser.color,
}),
[currentUser.id, currentUser.color, currentUser.name]
);
const extensions = useMemo(() => {
if (!remoteProvider) {
return props.extensions;
}
// The Yjs undo manager (added by MultiplayerUndo below) is the sole source
// of undo/redo history when collaborating.
return [
...(props.extensions || []).filter(
(extension) => extension !== History && !(extension instanceof History)
),
new MultiplayerExtension({
user,
provider: remoteProvider,
document: ydoc,
}),
MultiplayerUndo,
];
}, [remoteProvider, user, ydoc, props.extensions]);
// Run the callback once per sync, not per identity change.
const onSyncedEvent = useEffectEvent(() => onSynced?.());
useEffect(() => {
if ((!hasLocalPersistence || isLocalSynced) && isRemoteSynced) {
void onSyncedEvent();
}
}, [hasLocalPersistence, isLocalSynced, isRemoteSynced]);
// Disconnect the realtime connection while idle. `isIdle` also checks for
// page visibility and will immediately disconnect when a tab is hidden.
useEffect(() => {
if (!remoteProvider) {
return;
}
if (
isIdle &&
!isVisible &&
remoteProvider.status === WebSocketStatus.Connected
) {
remoteProvider.disconnect();
}
if (
(!isIdle || isVisible) &&
remoteProvider.status === WebSocketStatus.Disconnected
) {
void remoteProvider.connect();
}
}, [remoteProvider, isIdle, isVisible]);
// Certain emoji combinations trigger this error in YJS, while waiting for a fix
// we must prevent the user from continuing to edit as their changes will not
// be persisted. See: https://github.com/yjs/yjs/issues/303
useEffect(() => {
function onUnhandledError(event: ErrorEvent) {
if (event.message.includes("URIError: URI malformed")) {
toast.error(
t(
"Sorry, the last change could not be persisted – please reload the page"
)
);
}
}
window.addEventListener("error", onUnhandledError);
return () => window.removeEventListener("error", onUnhandledError);
}, [t]);
if (!remoteProvider) {
return null;
}
// while the collaborative document is loading, we render a version of the
// document from the last text cache in read-only mode if we have it.
const isLocalReady = !hasLocalPersistence || isLocalSynced;
const showCache =
!isLocalReady && !isRemoteSynced && hasContent(props.defaultValue);
return (
<>
{showCache && (
<Editor
editorStyle={props.editorStyle}
embedsDisabled={props.embedsDisabled}
defaultValue={props.defaultValue}
extensions={props.extensions}
scrollTo={props.scrollTo}
headingPrefix={props.headingPrefix}
cacheOnly
readOnly
ref={ref}
/>
)}
<Editor
{...props}
readOnly={props.readOnly || editorVersionBehind || isResetting}
value={undefined}
defaultValue={undefined}
extensions={extensions}
ref={showCache ? undefined : ref}
style={
showCache
? {
height: 0,
opacity: 0,
}
: undefined
}
className={showCursorNames ? "show-cursor-names" : undefined}
/>
</>
);
}
/**
* Whether the last known content of the document is worth displaying while the
* collaborative document loads. An empty document, such as one that was just
* created, renders identically either way so there is nothing to wait for.
*
* @param value the cached editor content.
* @returns true if the content is non-empty.
*/
function hasContent(value: Props["defaultValue"]): boolean {
if (!value) {
return false;
}
if (typeof value === "string") {
return !!value.trim();
}
if (value instanceof ProsemirrorNode) {
return !!value.textContent.trim();
}
return !ProsemirrorDataHelper.isEmpty(value);
}
export default MultiplayerEditor;