-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathmanager.ts
More file actions
687 lines (604 loc) · 21.1 KB
/
manager.ts
File metadata and controls
687 lines (604 loc) · 21.1 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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/**
* External dependencies
*/
import * as Y from 'yjs';
import type { Awareness } from 'y-protocols/awareness';
/**
* Internal dependencies
*/
import {
CRDT_RECORD_MAP_KEY,
CRDT_STATE_MAP_KEY,
CRDT_STATE_MAP_SAVED_AT_KEY as SAVED_AT_KEY,
LOCAL_SYNC_MANAGER_ORIGIN,
} from './config';
import {
logPerformanceTiming,
passThru,
yieldToEventLoop,
} from './performance';
import { getProviderCreators } from './providers';
import type {
CollectionHandlers,
CRDTDoc,
EntityID,
ObjectID,
ObjectData,
ObjectType,
ProviderCreator,
RecordHandlers,
SyncConfig,
SyncManager,
SyncManagerUpdateOptions,
SyncUndoManager,
} from './types';
import { createUndoManager } from './undo-manager';
import {
createYjsDoc,
deserializeCrdtDoc,
initializeYjsDoc,
markEntityAsSaved,
serializeCrdtDoc,
} from './utils';
interface CollectionState {
awareness?: Awareness;
handlers: CollectionHandlers;
syncConfig: SyncConfig;
unload: () => void;
ydoc: CRDTDoc;
}
interface EntityState {
awareness?: Awareness;
handlers: RecordHandlers;
objectId: ObjectID;
objectType: ObjectType;
syncConfig: SyncConfig;
unload: () => void;
ydoc: CRDTDoc;
}
/**
* Get the entity ID for the given object type and object ID.
*
* @param {ObjectType} objectType Object type.
* @param {ObjectID|null} objectId Object ID.
*/
function getEntityId(
objectType: ObjectType,
objectId: ObjectID | null
): EntityID {
return `${ objectType }_${ objectId }`;
}
/**
* The sync manager orchestrates the lifecycle of syncing entity records. It
* creates Yjs documents, connects to providers, creates awareness instances,
* and coordinates with the `core-data` store.
*
* @param debug Whether to enable performance and debug logging.
*/
export function createSyncManager( debug = false ): SyncManager {
const debugWrap = debug ? logPerformanceTiming : passThru;
const collectionStates: Map< ObjectType, CollectionState > = new Map();
const entityStates: Map< EntityID, EntityState > = new Map();
/**
* A "sync-aware" undo manager for all synced entities. It is lazily created
* when the first entity is loaded.
*
* IMPORTANT: In Gutenberg, the undo manager is effectively global and manages
* undo/redo state for all entities. If the default WPUndoManager is used,
* changes to entities are recorded in the `editEntityRecord` action:
*
* https://github.com/WordPress/gutenberg/blob/b63451e26e3c91b6bb291a2f9994722e3850417e/packages/core-data/src/actions.js#L428-L442
*
* In contrast, the `SyncUndoManager` only manages undo/redo for entities that
* **are being synced by this sync manager**. The `addRecord` method is still
* called in the code linked above, but it is a no-op. Yjs automatically tracks
* changes to entities via the associated CRDT doc:
*
* https://github.com/WordPress/gutenberg/blob/b63451e26e3c91b6bb291a2f9994722e3850417e/packages/sync/src/undo-manager.ts#L42-L48
*
* This means that if at least one entity is being synced, then undo/redo
* operations will be **restricted to synced entities only.**
*
* We could improve the `SyncUndoManager` to also track non-synced entities by
* delegating to a secondary `WPUndoManager`, but this would add complexity
* since we would need to maintain two separate undo/redo stacks and ensure
* that they retain ordering and integrity.
*
* However, we also anticipate that most entities being edited in Gutenberg
* will be synced entities (e.g. posts, pages, templates, template parts,
* etc.), so this limitation may be temporary.
*/
let undoManager: SyncUndoManager | undefined;
/**
* Log debug messages if debugging is enabled.
*
* @param component The component or context related to the log message
* @param message The debug message
* @param entityId The entity ID related to the log message
* @param context Additional debug context
*/
function log(
component: string,
message: string,
entityId: string,
context: object = {}
): void {
if ( ! debug ) {
return;
}
// eslint-disable-next-line no-console
console.log( `[SyncManager][${ component }]: ${ message }`, {
...context,
entityId,
} );
}
/**
* Load an entity for syncing and manage its lifecycle.
*
* @param {SyncConfig} syncConfig Sync configuration for the object type.
* @param {ObjectType} objectType Object type.
* @param {ObjectID} objectId Object ID.
* @param {ObjectData} record Entity record representing this object type.
* @param {RecordHandlers} handlers Handlers for updating and fetching the record.
*/
async function loadEntity(
syncConfig: SyncConfig,
objectType: ObjectType,
objectId: ObjectID,
record: ObjectData,
handlers: RecordHandlers
): Promise< void > {
const providerCreators = getProviderCreators();
const entityId = getEntityId( objectType, objectId );
if ( 0 === providerCreators.length ) {
log( 'loadEntity', 'no providers, skipping', entityId );
return; // No provider creators, so syncing is effectively disabled.
}
if ( entityStates.has( entityId ) ) {
log( 'loadEntity', 'already loaded', entityId );
return; // Already bootstrapped.
}
if ( false === syncConfig.shouldSync?.( objectType, objectId ) ) {
log( 'loadEntity', 'shouldSync false, skipping', entityId );
return; // Sync config indicates that this entity should not be synced.
}
log( 'loadEntity', 'loading', entityId );
handlers = {
addUndoMeta: debugWrap( handlers.addUndoMeta ),
editRecord: debugWrap( handlers.editRecord ),
getEditedRecord: debugWrap( handlers.getEditedRecord ),
onStatusChange: debugWrap( handlers.onStatusChange ),
persistCRDTDoc: debugWrap( handlers.persistCRDTDoc ),
refetchRecord: debugWrap( handlers.refetchRecord ),
restoreUndoMeta: debugWrap( handlers.restoreUndoMeta ),
};
const ydoc = createYjsDoc( { objectType } );
const recordMap = ydoc.getMap( CRDT_RECORD_MAP_KEY );
const stateMap = ydoc.getMap( CRDT_STATE_MAP_KEY );
const now = Date.now();
// Clean up providers and in-memory state when the entity is unloaded.
const unload = (): void => {
log( 'loadEntity', 'unloading', entityId );
providerResults.forEach( ( result ) => result.destroy() );
handlers.onStatusChange( null );
recordMap.unobserveDeep( onRecordUpdate );
stateMap.unobserve( onStateMapUpdate );
ydoc.destroy();
entityStates.delete( entityId );
};
// If the sync config supports awareness, create it.
const awareness = syncConfig.createAwareness?.( ydoc, objectId );
// When the CRDT document is updated by an UndoManager or a connection (not
// a local origin), update the local store.
const onRecordUpdate = (
_events: Y.YEvent< any >[],
transaction: Y.Transaction
): void => {
if (
transaction.local &&
! ( transaction.origin instanceof Y.UndoManager )
) {
return;
}
void internal.updateEntityRecord( objectType, objectId );
};
const onStateMapUpdate = (
event: Y.YMapEvent< unknown >,
transaction: Y.Transaction
) => {
if ( transaction.local ) {
return;
}
event.keysChanged.forEach( ( key ) => {
switch ( key ) {
case SAVED_AT_KEY:
const newValue = stateMap.get( SAVED_AT_KEY );
if ( 'number' === typeof newValue && newValue > now ) {
// Another peer has saved the record. Refetch it so that we have
// a correct understanding of our own unsaved edits.
log( 'loadEntity', 'refetching record', entityId );
void handlers.refetchRecord().catch( () => {} );
}
break;
}
} );
};
// Lazily create the undo manager when the first entity is loaded.
if ( ! undoManager ) {
undoManager = createUndoManager();
}
const { addUndoMeta, restoreUndoMeta } = handlers;
undoManager.addToScope( recordMap, {
addUndoMeta,
restoreUndoMeta,
} );
const entityState: EntityState = {
awareness,
handlers,
objectId,
objectType,
syncConfig,
unload,
ydoc,
};
entityStates.set( entityId, entityState );
// Create providers for the given entity and its Yjs document.
log( 'loadEntity', 'connecting', entityId );
const providerResults = await Promise.all(
providerCreators.map( async ( create ) => {
const provider = await create( {
objectType,
objectId,
ydoc,
awareness,
} );
// Attach status listener after provider creation.
provider.on( 'status', handlers.onStatusChange );
return provider;
} )
);
// Attach observers.
recordMap.observeDeep( onRecordUpdate );
stateMap.observe( onStateMapUpdate );
// Initialize the Yjs document with the necessary CRDT state.
initializeYjsDoc( ydoc );
// Get and apply the persisted CRDT document, if it exists.
internal.applyPersistedCrdtDoc( objectType, objectId, record );
}
/**
* Load a collection for syncing and manage its lifecycle.
*
* @param {SyncConfig} syncConfig Sync configuration for the object type.
* @param {ObjectType} objectType Object type.
* @param {CollectionHandlers} handlers Handlers for updating the collection.
*/
async function loadCollection(
syncConfig: SyncConfig,
objectType: ObjectType,
handlers: CollectionHandlers
): Promise< void > {
const providerCreators: ProviderCreator[] = getProviderCreators();
const entityId = getEntityId( objectType, null );
if ( 0 === providerCreators.length ) {
log( 'loadCollection', 'no providers, skipping', entityId );
return; // No provider creators, so syncing is effectively disabled.
}
if ( collectionStates.has( objectType ) ) {
log( 'loadCollection', 'already loaded', entityId );
return; // Already loaded.
}
if ( false === syncConfig.shouldSync?.( objectType, null ) ) {
log( 'loadCollection', 'shouldSync false, skipping', entityId );
return; // Sync config indicates that this entity should not be synced.
}
log( 'loadCollection', 'loading', entityId );
const ydoc = createYjsDoc( { collection: true, objectType } );
const stateMap = ydoc.getMap( CRDT_STATE_MAP_KEY );
const now = Date.now();
// Clean up providers and in-memory state when the entity is unloaded.
const unload = (): void => {
log( 'loadCollection', 'unloading', entityId );
providerResults.forEach( ( result ) => result.destroy() );
handlers.onStatusChange( null );
stateMap.unobserve( onStateMapUpdate );
ydoc.destroy();
collectionStates.delete( objectType );
};
const onStateMapUpdate = (
event: Y.YMapEvent< unknown >,
transaction: Y.Transaction
) => {
if ( transaction.local ) {
return;
}
event.keysChanged.forEach( ( key ) => {
switch ( key ) {
case SAVED_AT_KEY:
const newValue = stateMap.get( SAVED_AT_KEY );
if ( 'number' === typeof newValue && newValue > now ) {
// Another peer has mutated the collection. Refetch it so that we
// obtain the updated records.
void handlers.refetchRecords().catch( () => {} );
}
break;
}
} );
};
// If the sync config supports awareness, create it.
const awareness = syncConfig.createAwareness?.( ydoc );
const collectionState: CollectionState = {
awareness,
handlers,
syncConfig,
unload,
ydoc,
};
collectionStates.set( objectType, collectionState );
// Create providers for the given entity and its Yjs document.
log( 'loadCollection', 'connecting', entityId );
const providerResults = await Promise.all(
providerCreators.map( async ( create ) => {
const provider = await create( {
awareness,
objectType,
objectId: null,
ydoc,
} );
// Attach status listener after provider creation.
provider.on( 'status', handlers.onStatusChange );
return provider;
} )
);
// Attach observers.
stateMap.observe( onStateMapUpdate );
// Initialize the Yjs document with the necessary CRDT state.
initializeYjsDoc( ydoc );
}
/**
* Unload an entity, stop syncing, destroy its in-memory state, and trigger an
* update of the collection.
*
* @param {ObjectType} objectType Object type to discard.
* @param {ObjectID} objectId Object ID to discard, or null for collections.
*/
function unloadEntity( objectType: ObjectType, objectId: ObjectID ): void {
const entityId = getEntityId( objectType, objectId );
log( 'unloadEntity', 'unloading', entityId );
entityStates.get( entityId )?.unload();
updateCRDTDoc( objectType, null, {}, origin, { isSave: true } );
}
/**
* Get the awareness instance for the given object type and object ID, if supported.
*
* @template {Awareness} State
* @param {ObjectType} objectType Object type.
* @param {ObjectID} objectId Object ID.
* @return {State | undefined} The awareness instance, or undefined if not supported.
*/
function getAwareness< State extends Awareness >(
objectType: ObjectType,
objectId: ObjectID
): State | undefined {
const entityId = getEntityId( objectType, objectId );
const entityState = entityStates.get( entityId );
if ( ! entityState || ! entityState.awareness ) {
return undefined;
}
return entityState.awareness as State;
}
/**
* Load and inspect the persisted CRDT document. If supported and it exists,
* compare it against the current entity record. If there are differences,
* apply the changes from the entity record.
*
* @param {ObjectType} objectType Object type.
* @param {ObjectID} objectId Object ID.
* @param {ObjectData} record Entity record representing this object type.
*/
function _applyPersistedCrdtDoc(
objectType: ObjectType,
objectId: ObjectID,
record: ObjectData
): void {
const entityId = getEntityId( objectType, objectId );
const entityState = entityStates.get( entityId );
if ( ! entityState ) {
log( 'applyPersistedCrdtDoc', 'no entity state', entityId );
return;
}
const {
handlers,
syncConfig: {
applyChangesToCRDTDoc,
getChangesFromCRDTDoc,
getPersistedCRDTDoc,
},
ydoc: targetDoc,
} = entityState;
// Get the persisted CRDT document, if it exists.
const serialized = getPersistedCRDTDoc?.( record );
const tempDoc = serialized ? deserializeCrdtDoc( serialized ) : null;
if ( ! tempDoc ) {
log( 'applyPersistedCrdtDoc', 'no persisted doc', entityId );
// Apply the current record as changes and request that the CRDT doc be
// persisted with the entity. The persisted CRDT doc can be created by
// calling `syncManager.createPersistedCRDTDoc`.
targetDoc.transact( () => {
applyChangesToCRDTDoc( targetDoc, record );
handlers.persistCRDTDoc();
}, LOCAL_SYNC_MANAGER_ORIGIN );
return;
}
// Apply the persisted document to the current document as a single update.
// This is done even if the persisted document has been invalidated. This
// prevents a newly joining peer (or refreshing user) from re-initializing
// the CRDT document (the "initialization problem").
//
// IMPORTANT: Do not wrap this in a transaction with the local origin. It
// effectively advances the state vector for the current client, which causes
// Yjs to think that another client is using this client ID.
const update = Y.encodeStateAsUpdateV2( tempDoc );
Y.applyUpdateV2( targetDoc, update );
// Compute the differences between the persisted doc and the current
// record. This can happen when:
//
// 1. The server makes updates on save that mutate the entity. Example: On
// initial save, the server adds the "Uncategorized" category to the
// post.
// 2. An "out-of-band" update occurs. Example: a WP-CLI command or direct
// database update mutates the entity.
// 3. Unsaved changes are synced from a peer _before_ this code runs. We
// can't control when (or if) remote changes are synced, so this is a
// race condition.
const invalidations = getChangesFromCRDTDoc( tempDoc, record );
const invalidatedKeys = Object.keys( invalidations );
// Destroy the temporary document to prevent leaks.
tempDoc.destroy();
if ( 0 === invalidatedKeys.length ) {
log( 'applyPersistedCrdtDoc', 'valid persisted doc', entityId );
// The persisted CRDT document is valid. There are no updates to apply.
return;
}
log( 'applyPersistedCrdtDoc', 'invalidated keys', entityId, {
invalidatedKeys,
} );
// Use the invalidated keys to get the updated values from the entity.
const changes = invalidatedKeys.reduce(
( acc, key ) =>
Object.assign( acc, {
[ key ]: record[ key ],
} ),
{}
);
// Apply the changes and request that the updated CRDT doc be persisted with
// the entity. The persisted CRDT doc can be created by calling
// `syncManager.createPersistedCRDTDoc`.
targetDoc.transact( () => {
applyChangesToCRDTDoc( targetDoc, changes );
handlers.persistCRDTDoc();
}, LOCAL_SYNC_MANAGER_ORIGIN );
}
/**
* Update CRDT document with changes from the local store.
*
* @param {ObjectType} objectType Object type.
* @param {ObjectID} objectId Object ID.
* @param {Partial< ObjectData >} changes Updates to make.
* @param {string} origin The source of change.
* @param {SyncManagerUpdateOptions} options Optional flags for the update.
* @param {boolean} options.isSave Whether this update is part of a save operation. Defaults to false.
* @param {boolean} options.isNewUndoLevel Whether to create a new undo level for this change. Defaults to false.
*/
function updateCRDTDoc(
objectType: ObjectType,
objectId: ObjectID | null,
changes: Partial< ObjectData >,
origin: string,
options: SyncManagerUpdateOptions = {}
): void {
const { isSave = false, isNewUndoLevel = false } = options;
const entityId = getEntityId( objectType, objectId );
const entityState = entityStates.get( entityId );
const collectionState = collectionStates.get( objectType );
if ( entityState ) {
const { syncConfig, ydoc } = entityState;
// If this is change should create a new undo level, tell the undo
// manager to stop capturing and create a new undo group.
// We can't do this in the undo manager itself, because addRecord() is
// called after the CRDT changes have been applied, and we want to
// ensure that the undo set is created before the changes are applied.
if ( isNewUndoLevel && undoManager ) {
undoManager.stopCapturing?.();
}
ydoc.transact( () => {
log( 'updateCRDTDoc', 'applying changes', entityId, {
changedKeys: Object.keys( changes ),
} );
syncConfig.applyChangesToCRDTDoc( ydoc, changes );
if ( isSave ) {
markEntityAsSaved( ydoc );
}
}, origin );
}
if ( collectionState && isSave ) {
collectionState.ydoc.transact( () => {
markEntityAsSaved( collectionState.ydoc );
}, origin );
}
}
/**
* Update the entity record in the local store with changes from the CRDT
* document.
*
* @param {ObjectType} objectType Object type of record to update.
* @param {ObjectID} objectId Object ID of record to update.
*/
async function _updateEntityRecord(
objectType: ObjectType,
objectId: ObjectID
): Promise< void > {
const entityId = getEntityId( objectType, objectId );
const entityState = entityStates.get( entityId );
if ( ! entityState ) {
log( 'updateEntityRecord', 'no entity state', entityId );
return;
}
const { handlers, syncConfig, ydoc } = entityState;
// Determine which synced properties have actually changed by comparing
// them against the current edited entity record.
const changes = syncConfig.getChangesFromCRDTDoc(
ydoc,
await handlers.getEditedRecord()
);
const changedKeys = Object.keys( changes );
if ( 0 === changedKeys.length ) {
return;
}
log( 'updateEntityRecord', 'changes', entityId, {
changedKeys,
} );
handlers.editRecord( changes );
}
/* eslint-disable-next-line jsdoc/check-line-alignment */
/**
* Create object meta to persist the CRDT document in the entity record.
*
* @param {ObjectType} objectType Object type.
* @param {ObjectID} objectId Object ID.
* @param {number} [baseVersion=0] Base version from the server.
*/
async function createPersistedCRDTDoc(
objectType: ObjectType,
objectId: ObjectID,
baseVersion: number = 0
): Promise< string | null > {
const entityId = getEntityId( objectType, objectId );
const entityState = entityStates.get( entityId );
if ( ! entityState?.ydoc ) {
return null;
}
// Y.Doc updates are deferred via yieldToEventLoop. Await a promise that
// resolves on the next tick of the event loop so pending updates are flushed
// before we serialize the document.
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );
return serializeCrdtDoc( entityState.ydoc, baseVersion );
}
// Collect internal functions so that they can be wrapped before calling.
const internal = {
applyPersistedCrdtDoc: debugWrap( _applyPersistedCrdtDoc ),
updateEntityRecord: debugWrap( _updateEntityRecord ),
};
// Wrap and return the public API.
return {
createPersistedCRDTDoc: debugWrap( createPersistedCRDTDoc ),
getAwareness,
load: debugWrap( loadEntity ),
loadCollection: debugWrap( loadCollection ),
// Use getter to ensure we always return the current value of `undoManager`.
get undoManager(): SyncUndoManager | undefined {
return undoManager;
},
unload: debugWrap( unloadEntity ),
update: debugWrap( yieldToEventLoop( updateCRDTDoc ) ),
};
}