-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.ts
More file actions
594 lines (546 loc) · 19.6 KB
/
session.ts
File metadata and controls
594 lines (546 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { EventEmitter } from "events";
import { PatchGraph } from "./patch-graph";
import { rebaseDraft } from "./working-copy";
import { decodePatchId, encodePatchId } from "./patch-id";
import { makeClientId } from "./client-id";
import type {
DocCodec,
Document,
PatchEnvelope,
PatchStore,
FileAdapter,
PresenceAdapter,
PatchGraphValueOptions,
CursorSnapshot,
CursorPresence,
} from "./types";
export type SessionOptions = {
// Codec used to convert between strings and document instances and to make/apply patches.
codec: DocCodec;
// Persistence/transport adapter for loading initial history and appending patches.
patchStore: PatchStore;
// Optional clock override (defaults to Date.now) for deterministic testing.
clock?: () => number;
// Optional local user id, propagated on emitted patches/presence.
userId?: number;
// Optional per-client identifier for PatchId generation. Must be stable for the life
// of the Session instance. When omitted, a default is generated.
clientId?: string;
// Optional override for clientId generation (useful for tests).
clientIdFactory?: () => string;
// Optional document identifier for presence scoping (e.g., path or id).
docId?: string;
// Optional file adapter to mirror the current doc to disk and watch for external edits.
fileAdapter?: FileAdapter;
// Optional presence adapter to publish/receive lightweight presence state.
presenceAdapter?: PresenceAdapter;
};
let didWarnWeakClientIdEntropy = false;
/**
* Session orchestrates a local Document against a PatchGraph and a PatchStore.
* It handles local commits, remote patches, and basic undo/redo of local changes.
*/
export class Session extends EventEmitter {
private readonly codec: DocCodec;
private readonly patchStore: PatchStore;
private readonly clock: () => number;
private readonly graph: PatchGraph;
private readonly fileAdapter?: FileAdapter;
private readonly presenceAdapter?: PresenceAdapter;
private readonly docId?: string;
private doc?: Document; // live doc (committed + staged)
private committedDoc?: Document; // graph-derived doc without staged edits
private lastTimeMs: number = 0;
private userId: number;
private maxVersion: number = 0;
private readonly clientId: string;
private localTimes: string[] = [];
private undoPtr = 0;
private unsubscribe?: () => void;
private fileUnsubscribe?: () => void;
private pendingWrite?: Promise<void>;
private dirtyDoc?: Document;
private writingDoc?: Document;
private persistedContent?: string;
private suppressFileChanges = 0;
private hasMoreHistory = false;
private cursorTtlMs = 60_000;
private cursorStates: Map<string, CursorSnapshot> = new Map();
private cursorPruneTimer?: NodeJS.Timeout;
private workingCopy?: { base: Document; draft: Document };
private ensureInitialized(): void {
if (!this.doc) {
throw new Error("session not initialized");
}
}
// Build session state and wire adapters.
constructor(opts: SessionOptions) {
super();
this.codec = opts.codec;
this.patchStore = opts.patchStore;
this.clock = opts.clock ?? (() => Date.now());
this.userId = opts.userId ?? 0;
this.docId = opts.docId;
this.fileAdapter = opts.fileAdapter;
this.presenceAdapter = opts.presenceAdapter;
this.graph = new PatchGraph({ codec: this.codec });
const factory = opts.clientIdFactory ?? makeClientId;
this.clientId = opts.clientId ?? factory();
}
// Load initial history, seed state, and subscribe to adapters.
async init(): Promise<void> {
const { patches, hasMore } = await this.patchStore.loadInitial();
this.hasMoreHistory = !!hasMore;
this.graph.add(patches);
this.lastTimeMs = this.computeLastTimeMs();
this.maxVersion = this.computeMaxVersion();
this.committedDoc = this.graph.value();
this.doc = this.committedDoc;
if (this.fileAdapter && this.doc) {
// Track current doc string so we can skip redundant writes.
this.persistedContent = this.codec.toString(this.doc);
}
this.emit("change", this.doc);
this.unsubscribe = this.patchStore.subscribe((env) => {
this.applyRemote(env);
});
if (this.presenceAdapter) {
this.presenceAdapter.subscribe((state, clientId) => {
if (this.isCursorPresence(state)) {
this.ingestCursorState({ ...state, clientId });
this.emit("cursors", this.cursors());
} else {
this.emit("presence", state, clientId);
}
});
}
if (this.fileAdapter?.watch) {
this.fileUnsubscribe = this.fileAdapter.watch(async () => {
await this.handleFileChange();
});
}
}
// Tear down subscriptions and presence when done.
close(): void {
this.unsubscribe?.();
this.fileUnsubscribe?.();
this.presenceAdapter?.publish(undefined);
if (this.cursorPruneTimer) {
clearTimeout(this.cursorPruneTimer);
}
this.cursorStates.clear();
this.removeAllListeners();
}
// True if initial load included all history.
hasFullHistory(): boolean {
this.ensureInitialized();
return !this.hasMoreHistory;
}
// Mark that full history is now present (e.g., after incremental backfill).
markFullHistory(): void {
this.ensureInitialized();
this.hasMoreHistory = false;
}
// Return patch ids (versions) in ascending order.
versions(opts: { start?: string; end?: string } = {}): string[] {
this.ensureInitialized();
return this.graph.versions(opts);
}
// Return the current head logical times.
getHeads(): string[] {
this.ensureInitialized();
return this.graph.getHeads();
}
// Compute the document at a specific version or with exclusions.
value(opts: PatchGraphValueOptions = {}): Document {
this.ensureInitialized();
return this.graph.value(opts);
}
// Return a sorted list of patches in the session, optionally filtered.
history(
opts: { start?: string; end?: string; includeSnapshots?: boolean } = {},
): PatchEnvelope[] {
this.ensureInitialized();
return this.graph.history(opts).map((p) => ({ ...p }));
}
// Fetch a specific patch by logical time.
getPatch(time: string): PatchEnvelope {
this.ensureInitialized();
return { ...this.graph.getPatch(time) };
}
// Render a readable history summary for debugging/REPL use.
summarizeHistory(
opts: {
includeSnapshots?: boolean;
trunc?: number | null;
milliseconds?: boolean;
log?: (text: string) => void;
formatDoc?: (doc: Document) => string;
} = {},
): string {
this.ensureInitialized();
const { includeSnapshots = true, trunc = 80, milliseconds = false, log, formatDoc } = opts;
const truncMiddle = (s: string, n: number | null): string => {
if (n == null || n <= 0 || s.length <= n) return s;
if (n <= 3) return s.slice(0, n);
const half = Math.floor((n - 3) / 2);
return `${s.slice(0, half)}...${s.slice(s.length - half)}`;
};
const patches = this.history({ includeSnapshots });
const lines: string[] = [];
const emit = (text: string) => {
lines.push(text);
log?.(text);
};
patches.forEach((p, idx) => {
const wall = milliseconds
? String(p.wall ?? decodePatchId(p.time).timeMs)
: new Date(p.wall ?? decodePatchId(p.time).timeMs).toISOString();
const parents = p.parents && p.parents.length > 0 ? ` parents=[${p.parents.join(",")}]` : "";
const patchStr = p.isSnapshot
? `(snapshot len=${p.snapshot?.length ?? 0})`
: `(patch ${truncMiddle(JSON.stringify(p.patch), trunc)})`;
emit(
`${(idx + 1).toString().padStart(3, "0")} t=${p.time} v=${p.version ?? "-"} user=${p.userId ?? "-"} wall=${wall}${parents} ${patchStr}`,
);
const doc = this.graph.value({ time: p.time });
const docStr = formatDoc
? formatDoc(doc)
: truncMiddle(this.codec.toString(doc).trim(), trunc);
const label = p.isSnapshot
? "(SNAPSHOT)"
: (p.parents?.length ?? 0) > 1
? "(MERGE) "
: " ";
emit(`${label} ${JSON.stringify(docStr)}`);
});
const currentDoc = this.codec.toString(this.getDocument()).trim();
emit(`\nCurrent: ${JSON.stringify(truncMiddle(currentDoc, trunc))}`);
return lines.join("\n");
}
// Return the current document or throw if not initialized.
getDocument(): Document {
this.ensureInitialized();
return this.doc!;
}
// Return the committed document (graph value without staged edits).
getCommittedDocument(): Document {
this.ensureInitialized();
return this.committedDoc ?? this.doc!;
}
// Apply local change as a patch, persist, and publish presence.
commit(
nextDoc: Document,
opts: { file?: boolean; source?: string; meta?: PatchEnvelope["meta"] } = {},
): PatchEnvelope {
if (!this.committedDoc) {
throw new Error("session not initialized");
}
const base = this.workingCopy?.base ?? this.committedDoc;
const patch = this.codec.makePatch(base, nextDoc);
const timeMs = this.nextTimeMs();
const time = encodePatchId(timeMs, this.clientId);
const nextVersion = Math.max(this.maxVersion + 1, this.graph.versions().length + 1);
const envelope: PatchEnvelope = {
time,
wall: this.clock(),
patch,
parents: this.graph.getHeads(),
userId: this.userId,
version: nextVersion,
file: opts.file,
source: opts.source,
meta: opts.meta,
};
this.graph.add([envelope]);
this.maxVersion = Math.max(this.maxVersion, nextVersion);
this.committedDoc = nextDoc;
this.doc = nextDoc;
this.workingCopy = undefined;
// Reset undo future and record this local change.
this.localTimes = this.localTimes.slice(0, this.undoPtr);
this.localTimes.push(time);
this.undoPtr = this.localTimes.length;
this.syncDoc();
this.patchStore.append(envelope);
// Optionally publish presence after commit
this.presenceAdapter?.publish({ userId: this.userId, time });
return envelope;
}
// Merge a remote patch and refresh the current document.
applyRemote(env: PatchEnvelope): void {
this.graph.add([env]);
this.lastTimeMs = Math.max(this.lastTimeMs, decodePatchId(env.time).timeMs);
if (env.version != null) {
this.maxVersion = Math.max(this.maxVersion, env.version);
} else {
this.maxVersion = Math.max(this.maxVersion, this.graph.versions().length);
}
this.syncDoc();
this.emit("patch", env);
}
// Step the undo pointer backward and recompute the doc.
undo(): Document {
if (this.undoPtr > 0) {
this.undoPtr -= 1;
this.syncDoc();
this.emit("undo", this.doc);
this.presenceAdapter?.publish({ userId: this.userId, undoPtr: this.undoPtr });
}
return this.getDocument();
}
// Step the undo pointer forward and recompute the doc.
redo(): Document {
if (this.undoPtr < this.localTimes.length) {
this.undoPtr += 1;
this.syncDoc();
this.emit("redo", this.doc);
this.presenceAdapter?.publish({ userId: this.userId, undoPtr: this.undoPtr });
}
return this.getDocument();
}
// Return undo pointer and local history for callers that need to mirror undo UI.
undoState(): { undoPtr: number; localTimes: string[] } {
return {
undoPtr: this.undoPtr,
localTimes: [...this.localTimes],
};
}
// Reset undo pointer to the top (exit undo mode). If we are in an undone
// state, commit a new patch that preserves the current view so redo history
// is cleared without losing the undone changes.
resetUndo(): void {
this.ensureInitialized();
const targetDoc = this.getDocument();
const fullDoc = this.graph.value(); // state with all local patches applied
if (!targetDoc.isEqual(fullDoc)) {
// Temporarily treat the full graph value as the base for the commit so
// we create a patch from fullDoc -> targetDoc.
const prevCommitted = this.committedDoc;
this.committedDoc = fullDoc;
try {
this.commit(targetDoc, { source: "undo-reset" });
// commit() already updated committedDoc/doc/undoPtr and published presence.
} catch (err) {
this.committedDoc = prevCommitted ?? this.committedDoc;
throw err;
}
} else {
// Nothing to preserve; just exit undo mode.
this.undoPtr = this.localTimes.length;
this.syncDoc();
this.presenceAdapter?.publish({ userId: this.userId, undoPtr: this.undoPtr });
}
}
// Record a staged working copy of the document. Does not append to history.
setWorkingCopy(draft: Document): void {
this.ensureInitialized();
const base = this.committedDoc ?? this.doc!;
this.workingCopy = { base, draft };
this.doc = draft;
this.emit("change", this.doc);
}
// Clear any staged working copy and return to the committed version.
clearWorkingCopy(): void {
this.ensureInitialized();
this.workingCopy = undefined;
this.doc = this.committedDoc;
this.emit("change", this.doc!);
}
// Publish a cursor update for this session/user.
updateCursors(locs: unknown): void {
this.ensureInitialized();
if (!this.presenceAdapter) return;
const time = this.clock();
const payload: CursorPresence = {
type: "cursor",
time,
locs,
userId: this.userId,
docId: this.docId,
};
this.ingestCursorState({ ...payload, clientId: this.localCursorId() });
this.emit("cursors", this.cursors());
this.presenceAdapter.publish(payload);
}
// Return recent cursor states, filtered by TTL.
cursors(opts: { ttlMs?: number } = {}): CursorSnapshot[] {
this.ensureInitialized();
this.pruneCursors(opts.ttlMs ?? this.cursorTtlMs);
return Array.from(this.cursorStates.values());
}
// Recompute the current document (respecting undo/redo), rebase any staged working copy,
// emit change, and enqueue a file write if needed.
private syncDoc(): void {
const without = this.withoutTimes();
const baseDoc = this.graph.value({ withoutTimes: without });
this.committedDoc = baseDoc;
let liveDoc = baseDoc;
if (this.workingCopy) {
liveDoc = rebaseDraft({
base: this.workingCopy.base as Document,
draft: this.workingCopy.draft as Document,
updatedBase: baseDoc,
}) as Document;
this.workingCopy = { base: baseDoc, draft: liveDoc };
}
this.doc = liveDoc;
this.emit("change", this.doc);
// If a file adapter is present, keep it in sync
if (this.fileAdapter && this.doc) {
this.queueFileWriteDoc(liveDoc);
}
}
// List local patch times that should be excluded (undo region).
private withoutTimes(): string[] {
if (this.undoPtr >= this.localTimes.length) return [];
return this.localTimes.slice(this.undoPtr);
}
// Detect and store cursor presence payloads.
private ingestCursorState(state: CursorPresence & { clientId?: string }): void {
if (this.docId && state.docId && state.docId !== this.docId) {
return;
}
const clientId = this.cursorKey(state);
this.cursorStates.set(clientId, { ...state, clientId });
this.pruneCursors();
this.emit("cursors", this.cursors());
}
private isCursorPresence(state: unknown): state is CursorPresence {
if (!state || typeof state !== "object") return false;
const obj = state as Record<string, unknown>;
return obj.type === "cursor" && typeof obj.time === "number" && "locs" in obj;
}
private localCursorId(): string {
return `local-${this.userId ?? "anon"}`;
}
private cursorKey(state: CursorPresence & { clientId?: string }): string {
if (state.userId != null) {
return `user-${state.userId}`;
}
return state.clientId ?? this.localCursorId();
}
private pruneCursors(ttlMs: number = this.cursorTtlMs): void {
const now = this.clock();
for (const [id, c] of Array.from(this.cursorStates.entries())) {
if (ttlMs && now - c.time > ttlMs) {
this.cursorStates.delete(id);
}
}
if (this.cursorPruneTimer) {
clearTimeout(this.cursorPruneTimer);
}
if (ttlMs) {
this.cursorPruneTimer = setTimeout(() => this.pruneCursors(ttlMs), ttlMs);
this.cursorPruneTimer.unref?.();
}
}
// Compute the latest logical time from the graph.
private computeLastTimeMs(): number {
const versions = this.graph.versions();
if (versions.length === 0) return 0;
let best = 0;
for (const id of versions) {
best = Math.max(best, decodePatchId(id).timeMs);
}
return best;
}
// Produce the next monotonic logical time (milliseconds since epoch, but monotone per client).
private nextTimeMs(): number {
const base = Math.max(this.clock(), this.lastTimeMs + 1);
this.lastTimeMs = base;
return base;
}
// Compute the maximum version seen in the current graph.
private computeMaxVersion(): number {
let max = 0;
this.graph.history().forEach((p) => {
if (p.version != null) {
max = Math.max(max, p.version);
}
});
if (max === 0) {
max = this.graph.versions().length;
}
return max;
}
// React to filesystem changes by ingesting external content.
private async handleFileChange(): Promise<void> {
if (!this.doc || !this.fileAdapter) return;
if (this.suppressFileChanges > 0) {
this.suppressFileChanges -= 1;
return;
}
try {
const text = await this.fileAdapter.read();
const newDoc = this.codec.fromString(text);
if (this.doc.isEqual(newDoc)) return;
this.persistedContent = text;
await this.applyExternalDoc(newDoc);
} catch {
// ignore file read errors
}
}
// Convert external doc changes into a patch and append it.
private async applyExternalDoc(newDoc: Document): Promise<void> {
if (!this.doc) return;
const patch = this.doc.makePatch(newDoc);
const timeMs = this.nextTimeMs();
const time = encodePatchId(timeMs, this.clientId);
const nextVersion = Math.max(this.maxVersion + 1, this.graph.versions().length + 1);
const envelope: PatchEnvelope = {
time,
wall: this.clock(),
patch,
parents: this.graph.getHeads(),
userId: this.userId,
version: nextVersion,
file: true,
};
this.graph.add([envelope]);
this.maxVersion = Math.max(this.maxVersion, nextVersion);
this.doc = newDoc;
this.localTimes = this.localTimes.slice(0, this.undoPtr);
this.localTimes.push(time);
this.undoPtr = this.localTimes.length;
this.patchStore.append(envelope);
this.syncDoc();
}
// Record desired content and start a write flush if idle.
private queueFileWriteDoc(doc: Document): void {
if (!this.fileAdapter) return;
if (this.writingDoc && this.writingDoc.isEqual(doc)) return;
if (this.dirtyDoc && this.dirtyDoc.isEqual(doc)) return;
this.dirtyDoc = doc;
if (this.pendingWrite) return;
this.pendingWrite = this.flushFileQueue();
}
// Sequentially write queued content to the file adapter with base hints.
private async flushFileQueue(): Promise<void> {
while (this.dirtyDoc !== undefined) {
const doc = this.dirtyDoc;
this.dirtyDoc = undefined;
this.writingDoc = doc;
const content = this.codec.toString(doc);
if (this.persistedContent === content) {
this.writingDoc = undefined;
continue;
}
this.suppressFileChanges += 1;
try {
const hasBase = this.persistedContent !== undefined;
await this.fileAdapter!.write(
content,
hasBase ? { base: this.persistedContent } : undefined,
);
this.persistedContent = content;
} catch (err) {
this.emit("file-error", err);
} finally {
this.suppressFileChanges = Math.max(0, this.suppressFileChanges - 1);
this.writingDoc = undefined;
}
}
this.pendingWrite = undefined;
}
}