Files
outline/server/collaboration/SessionExtension.ts
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

139 lines
3.9 KiB
TypeScript

import { randomUUID } from "node:crypto";
import type {
Extension,
Hocuspocus,
connectedPayload,
onConfigurePayload,
onDisconnectPayload,
} from "@hocuspocus/server";
import { parseDocumentName } from "@shared/collaboration/documentName";
import { toError } from "@shared/utils/error";
import { Second } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import { trace } from "@server/logging/tracing";
import RedisAdapter from "@server/storage/redis";
import { collaborationSessionKey } from "./sessions";
/**
* Records which documents have a collaboration session open on any instance,
* so that background work can wait until nobody has the document open. See
* collaborationSessionExists.
*/
@trace()
export class SessionExtension implements Extension {
async onConfigure({ instance }: onConfigurePayload) {
this.instance = instance;
this.refreshInterval ??= setInterval(
this.handleRefreshInterval,
SessionExtension.refreshInterval
).unref();
}
async connected({ documentName }: connectedPayload) {
const { documentId } = parseDocumentName(documentName) ?? {};
if (documentId) {
await this.add([documentId]);
}
}
/**
* Remove the session when the last connection to the document leaves this
* instance.
*
* @param data the disconnect payload.
* @returns a promise resolving when the session is removed.
*/
async onDisconnect({ documentName, clientsCount }: onDisconnectPayload) {
const { documentId } = parseDocumentName(documentName) ?? {};
if (clientsCount > 0 || !documentId) {
return;
}
// A room of another state generation can be open for the same document.
if (this.loadedDocumentIds(documentName).has(documentId)) {
return;
}
try {
await RedisAdapter.collaborationClient.zrem(
collaborationSessionKey(documentId),
this.instanceId
);
} catch (err) {
Logger.warn("Unable to remove collaboration session", {
documentId,
message: toError(err).message,
});
}
}
async onDestroy() {
clearInterval(this.refreshInterval);
this.refreshInterval = undefined;
}
/** How long a session is recorded without a refresh, in milliseconds. */
private static ttl = 90 * Second.ms;
/** How often the sessions of loaded documents are refreshed, in milliseconds. */
private static refreshInterval = 30 * Second.ms;
/** Identifies this instance in the session records. */
private instanceId = randomUUID();
private instance?: Hocuspocus;
private refreshInterval?: ReturnType<typeof setInterval>;
private handleRefreshInterval = () => {
void this.add(Array.from(this.loadedDocumentIds()));
};
/**
* The IDs of the documents loaded on this instance with connections.
*
* @param exceptName the name of a room to leave out.
* @returns the document IDs.
*/
private loadedDocumentIds(exceptName?: string): Set<string> {
const documentIds = new Set<string>();
for (const [name, document] of this.instance?.documents ?? []) {
const { documentId } = parseDocumentName(name) ?? {};
if (
documentId &&
name !== exceptName &&
document.getConnectionsCount() > 0
) {
documentIds.add(documentId);
}
}
return documentIds;
}
private async add(documentIds: string[]) {
if (!documentIds.length) {
return;
}
const expiresAt = Date.now() + SessionExtension.ttl;
const pipeline = RedisAdapter.collaborationClient.pipeline();
for (const documentId of documentIds) {
const key = collaborationSessionKey(documentId);
pipeline.zadd(key, expiresAt, this.instanceId);
pipeline.zremrangebyscore(key, "-inf", Date.now());
pipeline.pexpire(key, SessionExtension.ttl);
}
try {
await pipeline.exec();
} catch (err) {
Logger.warn("Unable to record collaboration sessions", {
message: toError(err).message,
});
}
}
}