Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/core-data/src/private-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import apiFetch from '@wordpress/api-fetch';
* Internal dependencies
*/
import { STORE_NAME } from './name';
import { getSyncManager, hasSyncManager } from './sync';

/**
* Returns an action object used in signalling that the registered post meta
Expand Down Expand Up @@ -163,6 +164,7 @@ export function receiveEditorAssets( assets ) {

/**
* Returns an action object used to set whether collaboration is supported.
* When set to false, also disconnects all sync entities.
*
* @param {boolean} supported Whether collaboration is supported.
*
Expand All @@ -172,6 +174,9 @@ export const setCollaborationSupported =
( supported ) =>
( { dispatch } ) => {
dispatch( { type: 'SET_COLLABORATION_SUPPORTED', supported } );
if ( ! supported && hasSyncManager() ) {
getSyncManager().unloadAll();
}
};

/**
Expand Down
9 changes: 9 additions & 0 deletions packages/core-data/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,12 @@ export function getSyncManager(): SyncManager | undefined {

return syncManager;
}

/**
* Return whether a sync manager has already been created. Use this when you
* only want to interact with an existing sync manager (e.g. to tear it down),
* without `getSyncManager()` bootstrapping one if none exists.
*/
export function hasSyncManager(): boolean {
return Boolean( syncManager );
}
85 changes: 78 additions & 7 deletions packages/sync/src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import type {
ObjectData,
ObjectType,
ProviderCreator,
ProviderCreatorResult,
RecordHandlers,
SyncConfig,
SyncManager,
Expand Down Expand Up @@ -192,13 +193,23 @@ export function createSyncManager( debug = false ): SyncManager {
const stateMap = ydoc.getMap( CRDT_STATE_MAP_KEY );
const now = Date.now();

// Track whether observers have been attached to the maps.
let hasObserversAttached = false;
// Track whether unload ran (possibly while we were awaiting provider
// creation), so the post-await code can destroy any providers that
// were created after unload and bail out.
let isEntityUnloaded = false;

// Clean up providers and in-memory state when the entity is unloaded.
const unload = (): void => {
log( 'loadEntity', 'unloading', entityId );
providerResults.forEach( ( result ) => result.destroy() );
isEntityUnloaded = true;
providerResults?.forEach( ( result ) => result.destroy() );
handlers.onStatusChange( null );
recordMap.unobserveDeep( onRecordUpdate );
stateMap.unobserve( onStateMapUpdate );
if ( hasObserversAttached ) {
recordMap.unobserveDeep( onRecordUpdate );
stateMap.unobserve( onStateMapUpdate );
}
ydoc.destroy();
entityStates.delete( entityId );
};
Expand Down Expand Up @@ -256,6 +267,10 @@ export function createSyncManager( debug = false ): SyncManager {
restoreUndoMeta,
} );

// Declare with let before using it in unload closure.
// eslint-disable-next-line prefer-const
let providerResults: ProviderCreatorResult[];

const entityState: EntityState = {
awareness,
handlers,
Expand All @@ -270,7 +285,7 @@ export function createSyncManager( debug = false ): SyncManager {

// Create providers for the given entity and its Yjs document.
log( 'loadEntity', 'connecting', entityId );
const providerResults = await Promise.all(
providerResults = await Promise.all(
providerCreators.map( async ( create ) => {
const provider = await create( {
objectType,
Expand All @@ -286,6 +301,15 @@ export function createSyncManager( debug = false ): SyncManager {
} )
);

// If unload() or unloadAll() ran while we were awaiting provider
// creation, destroy the just-created providers and bail out before
// attempting to use the connection
if ( isEntityUnloaded ) {
log( 'loadEntity', 'unloaded during connect, aborting', entityId );
providerResults.forEach( ( result ) => result.destroy() );
return;
}

// Initialize the Yjs document with the necessary CRDT state.
initializeYjsDoc( ydoc );

Expand All @@ -299,6 +323,7 @@ export function createSyncManager( debug = false ): SyncManager {
// Attach observers.
recordMap.observeDeep( onRecordUpdate );
stateMap.observe( onStateMapUpdate );
hasObserversAttached = true;
}

/**
Expand Down Expand Up @@ -337,12 +362,22 @@ export function createSyncManager( debug = false ): SyncManager {
const stateMap = ydoc.getMap( CRDT_STATE_MAP_KEY );
const now = Date.now();

// Track whether observers have been attached to the maps.
let hasObserversAttached = false;
// Track whether unload ran (possibly while we were awaiting provider
// creation), so the post-await code can destroy any providers that
// were created after unload and bail out.
let isCollectionUnloaded = false;

// Clean up providers and in-memory state when the entity is unloaded.
const unload = (): void => {
log( 'loadCollection', 'unloading', entityId );
providerResults.forEach( ( result ) => result.destroy() );
isCollectionUnloaded = true;
providerResults?.forEach( ( result ) => result.destroy() );
handlers.onStatusChange( null );
stateMap.unobserve( onStateMapUpdate );
if ( hasObserversAttached ) {
stateMap.unobserve( onStateMapUpdate );
}
ydoc.destroy();
collectionStates.delete( objectType );
};
Expand Down Expand Up @@ -372,6 +407,10 @@ export function createSyncManager( debug = false ): SyncManager {
// If the sync config supports awareness, create it.
const awareness = syncConfig.createAwareness?.( ydoc );

// Declare with let before using it in unload closure.
// eslint-disable-next-line prefer-const
let providerResults: ProviderCreatorResult[];

const collectionState: CollectionState = {
awareness,
handlers,
Expand All @@ -384,7 +423,7 @@ export function createSyncManager( debug = false ): SyncManager {

// Create providers for the given entity and its Yjs document.
log( 'loadCollection', 'connecting', entityId );
const providerResults = await Promise.all(
providerResults = await Promise.all(
providerCreators.map( async ( create ) => {
const provider = await create( {
awareness,
Expand All @@ -400,8 +439,22 @@ export function createSyncManager( debug = false ): SyncManager {
} )
);

// If unload() or unloadAll() ran while we were awaiting provider
// creation, destroy the just-created providers and bail out before
// attempting to use the connection
if ( isCollectionUnloaded ) {
log(
'loadCollection',
'unloaded during connect, aborting',
entityId
);
providerResults.forEach( ( result ) => result.destroy() );
return;
}

// Attach observers.
stateMap.observe( onStateMapUpdate );
hasObserversAttached = true;

// Initialize the Yjs document with the necessary CRDT state.
initializeYjsDoc( ydoc );
Expand All @@ -421,6 +474,23 @@ export function createSyncManager( debug = false ): SyncManager {
updateCRDTDoc( objectType, null, {}, origin, { isSave: true } );
}

/**
* Unload all loaded entities, stopping all syncing.
*/
function unloadAll(): void {
log( 'unloadAll', 'unloading all entities', 'all' );

for ( const [ , entityState ] of [ ...entityStates ] ) {
entityState.unload();
}
entityStates.clear();

for ( const [ , collectionState ] of [ ...collectionStates ] ) {
collectionState.unload();
}
collectionStates.clear();
}

/**
* Get the awareness instance for the given object type and object ID, if supported.
*
Expand Down Expand Up @@ -683,6 +753,7 @@ export function createSyncManager( debug = false ): SyncManager {
return undoManager;
},
unload: debugWrap( unloadEntity ),
unloadAll: debugWrap( unloadAll ),
update: debugWrap( yieldToEventLoop( updateCRDTDoc ) ),
};
}
66 changes: 66 additions & 0 deletions packages/sync/src/test/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,72 @@ describe( 'SyncManager', () => {

expect( mockSyncConfig.applyChangesToCRDTDoc ).toHaveBeenCalled();
} );

it( 'destroys providers and skips initialization when unload runs during load', async () => {
// Hold provider creation open so we can interrupt the load between
// `entityStates.set(...)` and the provider creation resolving.
let resolveProvider: (
result: ProviderCreatorResult
) => void = () => {};
const providerPromise = new Promise< ProviderCreatorResult >(
( resolve ) => {
resolveProvider = resolve;
}
);
mockProviderCreator.mockImplementation( () => providerPromise );

const manager = createSyncManager();

// Start the load but do not await it. The async function will run up
// to the `await Promise.all(...)` and then suspend.
const loadPromise = manager.load(
mockSyncConfig,
'post',
'123',
mockRecord,
mockHandlers
);

// Yield so loadEntity reaches its await point.
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );

// At this point providerResults is still unassigned. Trigger unload.
manager.unload( 'post', '123' );

// Now resolve provider creation and let the load promise finish.
resolveProvider( mockProviderResult );
await loadPromise;

// The provider that was created after unload should still be
// destroyed by the post-await guard.
expect( mockProviderResult.destroy ).toHaveBeenCalledTimes( 1 );

// Initialization and persistence work should have been skipped: no
// changes applied to the (now-destroyed) ydoc, no persistCRDTDoc.
expect(
mockSyncConfig.applyChangesToCRDTDoc
).not.toHaveBeenCalled();
expect( mockHandlers.persistCRDTDoc ).not.toHaveBeenCalled();

// The entity is fully torn down, so a fresh load should succeed.
mockProviderCreator.mockImplementation( () =>
Promise.resolve( mockProviderResult )
);
jest.clearAllMocks();

await manager.load(
mockSyncConfig,
'post',
'123',
mockRecord,
mockHandlers
);

expect( mockProviderCreator ).toHaveBeenCalledTimes( 1 );
expect(
mockSyncConfig.applyChangesToCRDTDoc
).toHaveBeenCalledTimes( 1 );
} );
} );

describe( 'update', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/sync/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ export interface SyncManager {
// undoManager is undefined until the first entity is loaded.
undoManager: SyncUndoManager | undefined;
unload: ( objectType: ObjectType, objectId: ObjectID ) => void;
unloadAll: () => void;
update: (
objectType: ObjectType,
objectId: ObjectID | null,
Expand Down
Loading