diff --git a/package-lock.json b/package-lock.json index 41a5f2f7f33270..1909925e760bd0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17735,7 +17735,8 @@ "@wordpress/url": "file:packages/url", "equivalent-key-map": "^0.2.2", "lodash": "^4.17.19", - "rememo": "^3.0.0" + "rememo": "^3.0.0", + "uuid": "^8.3.0" } }, "@wordpress/create-block": { diff --git a/packages/core-data/package.json b/packages/core-data/package.json index fb16c6212c62a6..47ddfbab6de835 100644 --- a/packages/core-data/package.json +++ b/packages/core-data/package.json @@ -38,7 +38,8 @@ "@wordpress/url": "file:../url", "equivalent-key-map": "^0.2.2", "lodash": "^4.17.19", - "rememo": "^3.0.0" + "rememo": "^3.0.0", + "uuid": "^8.3.0" }, "publishConfig": { "access": "public" diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index c72bfdf97a6ed1..31163cae4dcbf4 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -2,6 +2,7 @@ * External dependencies */ import { castArray, get, isEqual, find } from 'lodash'; +import { v4 as uuid } from 'uuid'; /** * WordPress dependencies @@ -15,6 +16,10 @@ import { addQueryArgs } from '@wordpress/url'; */ import { receiveItems, removeItems, receiveQueriedItems } from './queried-data'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; +import { + __unstableAcquireStoreLock, + __unstableReleaseStoreLock, +} from './locks'; /** * Returns an action object used in signalling that authors have been received. @@ -162,39 +167,48 @@ export function* deleteEntityRecord( kind, name, recordId, query ) { return; } - yield { - type: 'DELETE_ENTITY_RECORD_START', - kind, - name, - recordId, - }; - + const lock = yield* __unstableAcquireStoreLock( + 'core', + [ 'entities', 'data', kind, name, recordId ], + { exclusive: true } + ); try { - let path = `${ entity.baseURL }/${ recordId }`; + yield { + type: 'DELETE_ENTITY_RECORD_START', + kind, + name, + recordId, + }; - if ( query ) { - path = addQueryArgs( path, query ); - } + try { + let path = `${ entity.baseURL }/${ recordId }`; - deletedRecord = yield apiFetch( { - path, - method: 'DELETE', - } ); + if ( query ) { + path = addQueryArgs( path, query ); + } - yield removeItems( kind, name, recordId, true ); - } catch ( _error ) { - error = _error; - } + deletedRecord = yield apiFetch( { + path, + method: 'DELETE', + } ); - yield { - type: 'DELETE_ENTITY_RECORD_FINISH', - kind, - name, - recordId, - error, - }; + yield removeItems( kind, name, recordId, true ); + } catch ( _error ) { + error = _error; + } - return deletedRecord; + yield { + type: 'DELETE_ENTITY_RECORD_FINISH', + kind, + name, + recordId, + error, + }; + + return deletedRecord; + } finally { + yield* __unstableReleaseStoreLock( lock ); + } } /** @@ -334,232 +348,257 @@ export function* saveEntityRecord( const entityIdKey = entity.key || DEFAULT_ENTITY_KEY; const recordId = record[ entityIdKey ]; - // Evaluate optimized edits. - // (Function edits that should be evaluated on save to avoid expensive computations on every edit.) - for ( const [ key, value ] of Object.entries( record ) ) { - if ( typeof value === 'function' ) { - const evaluatedValue = value( - yield controls.select( - 'core', - 'getEditedEntityRecord', + const lock = yield* __unstableAcquireStoreLock( + 'core', + [ 'entities', 'data', kind, name, recordId || uuid() ], + { exclusive: true } + ); + try { + // Evaluate optimized edits. + // (Function edits that should be evaluated on save to avoid expensive computations on every edit.) + for ( const [ key, value ] of Object.entries( record ) ) { + if ( typeof value === 'function' ) { + const evaluatedValue = value( + yield controls.select( + 'core', + 'getEditedEntityRecord', + kind, + name, + recordId + ) + ); + yield editEntityRecord( kind, name, - recordId - ) - ); - yield editEntityRecord( - kind, - name, - recordId, - { - [ key ]: evaluatedValue, - }, - { undoIgnore: true } - ); - record[ key ] = evaluatedValue; + recordId, + { + [ key ]: evaluatedValue, + }, + { undoIgnore: true } + ); + record[ key ] = evaluatedValue; + } } - } - yield { - type: 'SAVE_ENTITY_RECORD_START', - kind, - name, - recordId, - isAutosave, - }; - let updatedRecord; - let error; - let persistedEntity; - let currentEdits; - try { - const path = `${ entity.baseURL }${ recordId ? '/' + recordId : '' }`; - const persistedRecord = yield controls.select( - 'core', - 'getRawEntityRecord', + yield { + type: 'SAVE_ENTITY_RECORD_START', kind, name, - recordId - ); - - if ( isAutosave ) { - // Most of this autosave logic is very specific to posts. - // This is fine for now as it is the only supported autosave, - // but ideally this should all be handled in the back end, - // so the client just sends and receives objects. - const currentUser = yield controls.select( - 'core', - 'getCurrentUser' - ); - const currentUserId = currentUser ? currentUser.id : undefined; - const autosavePost = yield controls.select( + recordId, + isAutosave, + }; + let updatedRecord; + let error; + let persistedEntity; + let currentEdits; + try { + const path = `${ entity.baseURL }${ + recordId ? '/' + recordId : '' + }`; + const persistedRecord = yield controls.select( 'core', - 'getAutosave', - persistedRecord.type, - persistedRecord.id, - currentUserId + 'getRawEntityRecord', + kind, + name, + recordId ); - // Autosaves need all expected fields to be present. - // So we fallback to the previous autosave and then - // to the actual persisted entity if the edits don't - // have a value. - let data = { ...persistedRecord, ...autosavePost, ...record }; - data = Object.keys( data ).reduce( - ( acc, key ) => { - if ( [ 'title', 'excerpt', 'content' ].includes( key ) ) { - // Edits should be the "raw" attribute values. - acc[ key ] = get( data[ key ], 'raw', data[ key ] ); + + if ( isAutosave ) { + // Most of this autosave logic is very specific to posts. + // This is fine for now as it is the only supported autosave, + // but ideally this should all be handled in the back end, + // so the client just sends and receives objects. + const currentUser = yield controls.select( + 'core', + 'getCurrentUser' + ); + const currentUserId = currentUser ? currentUser.id : undefined; + const autosavePost = yield controls.select( + 'core', + 'getAutosave', + persistedRecord.type, + persistedRecord.id, + currentUserId + ); + // Autosaves need all expected fields to be present. + // So we fallback to the previous autosave and then + // to the actual persisted entity if the edits don't + // have a value. + let data = { ...persistedRecord, ...autosavePost, ...record }; + data = Object.keys( data ).reduce( + ( acc, key ) => { + if ( + [ 'title', 'excerpt', 'content' ].includes( key ) + ) { + // Edits should be the "raw" attribute values. + acc[ key ] = get( data[ key ], 'raw', data[ key ] ); + } + return acc; + }, + { + status: + data.status === 'auto-draft' + ? 'draft' + : data.status, } - return acc; - }, - { status: data.status === 'auto-draft' ? 'draft' : data.status } - ); - updatedRecord = yield apiFetch( { - path: `${ path }/autosaves`, - method: 'POST', - data, - } ); - // An autosave may be processed by the server as a regular save - // when its update is requested by the author and the post had - // draft or auto-draft status. - if ( persistedRecord.id === updatedRecord.id ) { - let newRecord = { - ...persistedRecord, - ...data, - ...updatedRecord, - }; - newRecord = Object.keys( newRecord ).reduce( ( acc, key ) => { - // These properties are persisted in autosaves. - if ( [ 'title', 'excerpt', 'content' ].includes( key ) ) { - // Edits should be the "raw" attribute values. - acc[ key ] = get( - newRecord[ key ], - 'raw', - newRecord[ key ] - ); - } else if ( key === 'status' ) { - // Status is only persisted in autosaves when going from - // "auto-draft" to "draft". - acc[ key ] = - persistedRecord.status === 'auto-draft' && - newRecord.status === 'draft' - ? newRecord.status - : persistedRecord.status; - } else { - // These properties are not persisted in autosaves. - acc[ key ] = get( - persistedRecord[ key ], - 'raw', - persistedRecord[ key ] - ); + ); + updatedRecord = yield apiFetch( { + path: `${ path }/autosaves`, + method: 'POST', + data, + } ); + // An autosave may be processed by the server as a regular save + // when its update is requested by the author and the post had + // draft or auto-draft status. + if ( persistedRecord.id === updatedRecord.id ) { + let newRecord = { + ...persistedRecord, + ...data, + ...updatedRecord, + }; + newRecord = Object.keys( newRecord ).reduce( + ( acc, key ) => { + // These properties are persisted in autosaves. + if ( + [ 'title', 'excerpt', 'content' ].includes( + key + ) + ) { + // Edits should be the "raw" attribute values. + acc[ key ] = get( + newRecord[ key ], + 'raw', + newRecord[ key ] + ); + } else if ( key === 'status' ) { + // Status is only persisted in autosaves when going from + // "auto-draft" to "draft". + acc[ key ] = + persistedRecord.status === 'auto-draft' && + newRecord.status === 'draft' + ? newRecord.status + : persistedRecord.status; + } else { + // These properties are not persisted in autosaves. + acc[ key ] = get( + persistedRecord[ key ], + 'raw', + persistedRecord[ key ] + ); + } + return acc; + }, + {} + ); + yield receiveEntityRecords( + kind, + name, + newRecord, + undefined, + true + ); + } else { + yield receiveAutosaves( persistedRecord.id, updatedRecord ); + } + } else { + // Auto drafts should be converted to drafts on explicit saves and we should not respect their default title, + // but some plugins break with this behavior so we can't filter it on the server. + let data = record; + if ( + kind === 'postType' && + persistedRecord && + persistedRecord.status === 'auto-draft' + ) { + if ( ! data.status ) { + data = { ...data, status: 'draft' }; } - return acc; - }, {} ); + if ( ! data.title || data.title === 'Auto Draft' ) { + data = { ...data, title: '' }; + } + } + + // Get the full local version of the record before the update, + // to merge it with the edits and then propagate it to subscribers + persistedEntity = yield controls.select( + 'core', + '__experimentalGetEntityRecordNoResolver', + kind, + name, + recordId + ); + currentEdits = yield controls.select( + 'core', + 'getEntityRecordEdits', + kind, + name, + recordId + ); + yield receiveEntityRecords( + kind, + name, + { ...persistedEntity, ...data }, + undefined, + // This must be false or it will trigger a GET request in parallel to the PUT/POST below + false + ); + + updatedRecord = yield apiFetch( { + path, + method: recordId ? 'PUT' : 'POST', + data, + } ); yield receiveEntityRecords( kind, name, - newRecord, + updatedRecord, undefined, true ); - } else { - yield receiveAutosaves( persistedRecord.id, updatedRecord ); - } - } else { - // Auto drafts should be converted to drafts on explicit saves and we should not respect their default title, - // but some plugins break with this behavior so we can't filter it on the server. - let data = record; - if ( - kind === 'postType' && - persistedRecord && - persistedRecord.status === 'auto-draft' - ) { - if ( ! data.status ) { - data = { ...data, status: 'draft' }; - } - if ( ! data.title || data.title === 'Auto Draft' ) { - data = { ...data, title: '' }; - } } + } catch ( _error ) { + error = _error; - // Get the full local version of the record before the update, - // to merge it with the edits and then propagate it to subscribers - persistedEntity = yield controls.select( - 'core', - '__experimentalGetEntityRecordNoResolver', - kind, - name, - recordId - ); - currentEdits = yield controls.select( - 'core', - 'getEntityRecordEdits', - kind, - name, - recordId - ); - yield receiveEntityRecords( - kind, - name, - { ...persistedEntity, ...data }, - undefined, - // This must be false or it will trigger a GET request in parallel to the PUT/POST below - false - ); - - updatedRecord = yield apiFetch( { - path, - method: recordId ? 'PUT' : 'POST', - data, - } ); - yield receiveEntityRecords( - kind, - name, - updatedRecord, - undefined, - true - ); - } - } catch ( _error ) { - error = _error; - - // If we got to the point in the try block where we made an optimistic update, - // we need to roll it back here. - if ( persistedEntity && currentEdits ) { - yield receiveEntityRecords( - kind, - name, - persistedEntity, - undefined, - true - ); - yield editEntityRecord( - kind, - name, - recordId, - { - ...currentEdits, - ...( yield controls.select( - 'core', - 'getEntityRecordEdits', - kind, - name, - recordId - ) ), - }, - { undoIgnore: true } - ); + // If we got to the point in the try block where we made an optimistic update, + // we need to roll it back here. + if ( persistedEntity && currentEdits ) { + yield receiveEntityRecords( + kind, + name, + persistedEntity, + undefined, + true + ); + yield editEntityRecord( + kind, + name, + recordId, + { + ...currentEdits, + ...( yield controls.select( + 'core', + 'getEntityRecordEdits', + kind, + name, + recordId + ) ), + }, + { undoIgnore: true } + ); + } } + yield { + type: 'SAVE_ENTITY_RECORD_FINISH', + kind, + name, + recordId, + error, + isAutosave, + }; + + return updatedRecord; + } finally { + yield* __unstableReleaseStoreLock( lock ); } - yield { - type: 'SAVE_ENTITY_RECORD_FINISH', - kind, - name, - recordId, - error, - isAutosave, - }; - - return updatedRecord; } /** diff --git a/packages/core-data/src/index.js b/packages/core-data/src/index.js index 06a74cbab4209d..8f74ce30c076c1 100644 --- a/packages/core-data/src/index.js +++ b/packages/core-data/src/index.js @@ -11,6 +11,8 @@ import reducer from './reducer'; import * as selectors from './selectors'; import * as actions from './actions'; import * as resolvers from './resolvers'; +import * as locksSelectors from './locks/selectors'; +import * as locksActions from './locks/actions'; import { defaultEntities, getMethodName } from './entities'; import { REDUCER_KEY } from './name'; @@ -57,8 +59,8 @@ const entityActions = defaultEntities.reduce( ( result, entity ) => { registerStore( REDUCER_KEY, { reducer, controls, - actions: { ...actions, ...entityActions }, - selectors: { ...selectors, ...entitySelectors }, + actions: { ...actions, ...entityActions, ...locksActions }, + selectors: { ...selectors, ...entitySelectors, ...locksSelectors }, resolvers: { ...resolvers, ...entityResolvers }, } ); diff --git a/packages/core-data/src/locks/README.md b/packages/core-data/src/locks/README.md new file mode 100644 index 00000000000000..2dc2c65f053958 --- /dev/null +++ b/packages/core-data/src/locks/README.md @@ -0,0 +1,108 @@ +# Store locks + +Operations mutating the store (resolvers, saveEntityRecord) interfere with each other by changing the state used by other "concurrent" operations. My solution is to enable these operations to lock parts of the state tree that are expected to remain constant for the duration of the operation. For example `saveEntityRecord("postType", "book", 3)` would acquire a lock on a book with id=3 and nothing else. + +More generally, interfering store operations should run sequentially. Each operation acquires a lock scoped to its state dependencies. If a lock cannot be acquired, the operation is delayed until a lock can be acquired. Locks are either exclusive or shared. If all operations request a shared lock, everything is executed concurrently. If any operation requests an exclusive lock, is it run only after all other locks (shared or exclusive) acting on the same scope are released. + +The most complex part of this PR is the concept of lock scope. Locks are stored in a tree. Each node in the tree looks like this: + +```jsx +{ + "locks": [], + "children": {} +} +``` + +Locks are stored like this: + +```jsx +{ + "locks": [ { "exclusive": false, /* data */ } ], + "children": {} +} +``` + +A more complete, but still simplified, tree looks like this: + +```jsx +{ + "locks": [], + "children": { + "book": { + "locks": [], + "children": { + 1: { + "locks": [], + "children": {} + }, + 2: { + "locks": [], + "children": {} + } + } + } + } +} +``` + +Let's imagine we want to fetch a list of books. One way to control concurrency would be to acquire a shared lock on `book`. The lock will be granted once there are **no exclusive locks** on: +* `book` itself +* All its parents (`root`) +* All its descendants (`book > 1`, `book > 2`) + +In the case above we're good to grab the lock, let's do it then: + +```jsx +{ + "locks": [], + "children": { + "book": { + "locks": [ { "exclusive": false, /* data */ } ], + "children": { + 1: { + "locks": [], + "children": {} + }, + 2: { + "locks": [], + "children": {} + } + } + } + } +} +``` + +Let's imagine that another fetch was triggered to get a filtered list of entities. By checking the criteria above, it's okay to grab a shared lock on books so now we have two: +```jsx +/* ... */ + "book": { + "locks": [ { "exclusive": false, /* data */ }, { "exclusive": false, /* data */ } ], + } +/* ... */ +``` + +While these are running, the user triggered an update of book id=1. Now an update operation requests an exclusive lock. It will be able to acquire one once there are **no locks at all** on: +* `book > 1` itself +* All its parents (`root`, `book`) +* All its descendants (an empty list in this case) + +Since there are two shared locks on `book`, the operation is delayed until both of them are released. Once that happens, an exclusive lock is granted on a specific book: + +```jsx +/* ... */ + "book": { + "locks": [], + "children": { + 1: { + "locks": [ { "exclusive": true, /* data */ } ], + "children": {} + }, + }, + }, +/* ... */ +``` + +If any fetch operation is triggered now, it will attempt to acquire a shared lock on `book`. Since one of `book` descendants holds an exclusive lock, fetch must wait until that lock is released. + +This structure makes it quite easy to control concurrent reads/writes with, as I believe, any granularity. For example, if we wanted to make sure two fetch operations may run only if their `query` is different, each could acquire two locks: a shared lock on `book` to prevent clashing with writes, and an exclusive lock on an unrelated branch such as `fetchByQuery > [query]`. diff --git a/packages/core-data/src/locks/actions.js b/packages/core-data/src/locks/actions.js new file mode 100644 index 00000000000000..2af5f4f8463b1b --- /dev/null +++ b/packages/core-data/src/locks/actions.js @@ -0,0 +1,64 @@ +/** + * WordPress dependencies + */ +import { awaitPromise } from '@wordpress/data-controls'; +import { controls } from '@wordpress/data'; + +export function* __unstableAcquireStoreLock( store, path, { exclusive } ) { + const promise = yield* __unstableEnqueueLockRequest( store, path, { + exclusive, + } ); + yield* __unstableProcessPendingLockRequests(); + return yield awaitPromise( promise ); +} + +export function* __unstableEnqueueLockRequest( store, path, { exclusive } ) { + let notifyAcquired; + const promise = new Promise( ( resolve ) => { + notifyAcquired = resolve; + } ); + yield { + type: 'ENQUEUE_LOCK_REQUEST', + request: { store, path, exclusive, notifyAcquired }, + }; + return promise; +} + +export function* __unstableReleaseStoreLock( lock ) { + yield { + type: 'RELEASE_LOCK', + lock, + }; + yield* __unstableProcessPendingLockRequests(); +} + +export function* __unstableProcessPendingLockRequests() { + yield { + type: 'PROCESS_PENDING_LOCK_REQUESTS', + }; + const lockRequests = yield controls.select( + 'core', + '__unstableGetPendingLockRequests' + ); + for ( const request of lockRequests ) { + const { store, path, exclusive, notifyAcquired } = request; + const isAvailable = yield controls.select( + 'core', + '__unstableIsLockAvailable', + store, + path, + { + exclusive, + } + ); + if ( isAvailable ) { + const lock = { store, path, exclusive }; + yield { + type: 'GRANT_LOCK_REQUEST', + lock, + request, + }; + notifyAcquired( lock ); + } + } +} diff --git a/packages/core-data/src/locks/index.js b/packages/core-data/src/locks/index.js new file mode 100644 index 00000000000000..57e124e445d87d --- /dev/null +++ b/packages/core-data/src/locks/index.js @@ -0,0 +1,3 @@ +export * from './actions'; +export * from './selectors'; +export { default as reducer } from './reducer'; diff --git a/packages/core-data/src/locks/reducer.js b/packages/core-data/src/locks/reducer.js new file mode 100644 index 00000000000000..6a29de6a3ffaba --- /dev/null +++ b/packages/core-data/src/locks/reducer.js @@ -0,0 +1,64 @@ +/** + * Internal dependencies + */ +import { getNode, deepCopyLocksTreePath } from './utils'; + +const DEFAULT_STATE = { + requests: [], + tree: { + locks: [], + children: {}, + }, +}; + +/** + * Reducer returning locks. + * + * @param {Object} state Current state. + * @param {Object} action Dispatched action. + * + * @return {Object} Updated state. + */ +export function locks( state = DEFAULT_STATE, action ) { + switch ( action.type ) { + case 'ENQUEUE_LOCK_REQUEST': { + const { request } = action; + return { + ...state, + requests: [ request, ...state.requests ], + }; + } + case 'GRANT_LOCK_REQUEST': { + const { lock, request } = action; + const { store, path } = request; + const storePath = [ store, ...path ]; + + const newTree = deepCopyLocksTreePath( state.tree, storePath ); + const node = getNode( newTree, storePath ); + node.locks = [ ...node.locks, lock ]; + + return { + ...state, + requests: state.requests.filter( ( r ) => r !== request ), + tree: newTree, + }; + } + case 'RELEASE_LOCK': { + const { lock } = action; + const storePath = [ lock.store, ...lock.path ]; + + const newTree = deepCopyLocksTreePath( state.tree, storePath ); + const node = getNode( newTree, storePath ); + node.locks = node.locks.filter( ( l ) => l !== lock ); + + return { + ...state, + tree: newTree, + }; + } + } + + return state; +} + +export default locks; diff --git a/packages/core-data/src/locks/selectors.js b/packages/core-data/src/locks/selectors.js new file mode 100644 index 00000000000000..233b36985a5c54 --- /dev/null +++ b/packages/core-data/src/locks/selectors.js @@ -0,0 +1,41 @@ +/** + * Internal dependencies + */ +import { + iterateDescendants, + iteratePath, + hasConflictingLock, + getNode, +} from './utils'; + +export function __unstableGetPendingLockRequests( state ) { + return state.locks.requests; +} + +export function __unstableIsLockAvailable( state, store, path, { exclusive } ) { + const storePath = [ store, ...path ]; + const locks = state.locks.tree; + + // Validate all parents and the node itself + for ( const node of iteratePath( locks, storePath ) ) { + if ( hasConflictingLock( { exclusive }, node.locks ) ) { + return false; + } + } + + // iteratePath terminates early if path is unreachable, let's + // re-fetch the node and check it exists in the tree. + const node = getNode( locks, storePath ); + if ( ! node ) { + return true; + } + + // Validate all nested nodes + for ( const descendant of iterateDescendants( node ) ) { + if ( hasConflictingLock( { exclusive }, descendant.locks ) ) { + return false; + } + } + + return true; +} diff --git a/packages/core-data/src/locks/test/actions.js b/packages/core-data/src/locks/test/actions.js new file mode 100644 index 00000000000000..f3d2cbdb1b44a1 --- /dev/null +++ b/packages/core-data/src/locks/test/actions.js @@ -0,0 +1,307 @@ +/** + * Internal dependencies + */ +import { + __unstableAcquireStoreLock, + __unstableEnqueueLockRequest, + __unstableReleaseStoreLock, + __unstableProcessPendingLockRequests, +} from '../actions'; + +const store = 'test'; +const path = [ 'blue', 'bird' ]; + +describe( '__unstableEnqueueLockRequest', () => { + it( 'Enqueues a lock request', async () => { + const fulfillment = __unstableEnqueueLockRequest( store, path, { + exclusive: true, + } ); + + // Start + expect( fulfillment.next().value ).toMatchObject( { + type: 'ENQUEUE_LOCK_REQUEST', + request: { + store, + path, + exclusive: true, + notifyAcquired: expect.any( Function ), + }, + } ); + + // Should return a promise + expect( fulfillment.next() ).toMatchObject( { + done: true, + value: expect.any( Promise ), + } ); + } ); + + it( 'Returns a promise fulfilled only after calling notifyAcquired', async () => { + const fulfillment = __unstableEnqueueLockRequest( store, path, { + exclusive: true, + } ); + const { request } = fulfillment.next().value; + const promise = fulfillment.next().value; + const fulfilled = jest.fn(); + promise.then( fulfilled ); + // Fulfilled should not be called until notifyAcquired is called + await sleep( 1 ); + expect( fulfilled ).not.toBeCalled(); + const lock = {}; + request.notifyAcquired( lock ); + expect( fulfilled ).not.toBeCalled(); + + // Promises are resolved only the next tick, so let's wait a little: + await sleep( 1 ); + expect( fulfilled ).toBeCalledTimes( 1 ); + + // Calling notifyAcquired again shouldn't have any effect: + request.notifyAcquired( lock ); + await sleep( 1 ); + expect( fulfilled ).toBeCalledTimes( 1 ); + } ); +} ); + +describe( '__unstableProcessPendingLockRequests', () => { + const exclusive = true; + const lock = { store, path, exclusive }; + + let notifyAcquired; + let request; + + beforeEach( () => { + notifyAcquired = jest.fn(); + request = { store, path, exclusive, notifyAcquired }; + } ); + + it( 'Grants a lock request that may be granted', async () => { + const fulfillment = __unstableProcessPendingLockRequests(); + + // Start + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + + // Get pending lock requests + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Find one and check if the request may be granted + expect( fulfillment.next( [ request ] ).value.type ).toBe( + '@@data/SELECT' + ); + + // It may, grant it + expect( fulfillment.next( true ).value.type ).toBe( + 'GRANT_LOCK_REQUEST' + ); + + // Ensure the promise isn't fulfilled until after GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).not.toBeCalled(); + + // All requests processed, return + expect( fulfillment.next() ).toMatchObject( { + done: true, + value: undefined, + } ); + + // Ensure the promise is fulfilled once GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).toBeCalledWith( lock ); + expect( notifyAcquired ).toBeCalledTimes( 1 ); + + // All requests processed, return + expect( fulfillment.next() ).toMatchObject( { + done: true, + value: undefined, + } ); + } ); + + it( 'Does not grants a lock request that may not be granted', async () => { + const fulfillment = __unstableProcessPendingLockRequests(); + + // Start + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + + // Get pending lock requests + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Find one and check if the request may be granted + expect( fulfillment.next( [ request ] ).value.type ).toBe( + '@@data/SELECT' + ); + + // It may not, let's finish + expect( fulfillment.next( false ) ).toMatchObject( { + done: true, + value: undefined, + } ); + } ); + + it( 'Handles multiple lock requests', async () => { + const fulfillment = __unstableProcessPendingLockRequests(); + + // Start + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + + // Get pending lock requests + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Find one and check if the request may be granted + expect( fulfillment.next( [ request, request ] ).value.type ).toBe( + '@@data/SELECT' + ); + + // It may not, continue - check if the next one may be granted + expect( fulfillment.next( false ).value.type ).toBe( '@@data/SELECT' ); + // It may, grant it + expect( fulfillment.next( true ).value.type ).toBe( + 'GRANT_LOCK_REQUEST' + ); + + // Ensure the promise isn't fulfilled until after GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).not.toBeCalled(); + + // All requests processed, return + expect( fulfillment.next() ).toMatchObject( { + done: true, + value: undefined, + } ); + + // Ensure the promise is fulfilled once GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).toBeCalledWith( lock ); + expect( notifyAcquired ).toBeCalledTimes( 1 ); + + // All requests processed, return + expect( fulfillment.next() ).toMatchObject( { + done: true, + value: undefined, + } ); + } ); +} ); + +describe( '__unstableAcquireStoreLock', () => { + const exclusive = true; + const lock = { store, path, exclusive }; + + let notifyAcquired; + let request; + + beforeEach( () => { + notifyAcquired = jest.fn(); + request = { store, path, exclusive, notifyAcquired }; + } ); + + it( 'Enqueues a lock request and attempts to fulfill it', async () => { + const fulfillment = __unstableAcquireStoreLock( store, path, { + exclusive, + } ); + + // Start + expect( fulfillment.next().value.type ).toBe( 'ENQUEUE_LOCK_REQUEST' ); + + // Get pending lock requests + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Check if lock may be granted + expect( fulfillment.next( [ request ] ).value.type ).toBe( + '@@data/SELECT' + ); + + // Grant lock request + expect( fulfillment.next( true ).value.type ).toBe( + 'GRANT_LOCK_REQUEST' + ); + + // Ensure the promise isn't fulfilled until after GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).not.toBeCalled(); + + // Await for lock promise fulfillment + expect( fulfillment.next( 'promise' ).value.type ).toBe( + 'AWAIT_PROMISE' + ); + + // Ensure the promise is fulfilled once GRANT_LOCK_REQUEST finishes + expect( notifyAcquired ).toBeCalledWith( lock ); + + // Return lock + expect( fulfillment.next( lock ) ).toMatchObject( { + done: true, + value: lock, + } ); + } ); + + it( 'Enqueues a lock request and waits until fultillment it when not available', async () => { + const fulfillment = __unstableAcquireStoreLock( store, path, { + exclusive, + } ); + + // Start + expect( fulfillment.next().value.type ).toBe( 'ENQUEUE_LOCK_REQUEST' ); + + // Get pending lock requests + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Check if lock may be granted + expect( fulfillment.next( [ request ] ).value.type ).toBe( + '@@data/SELECT' + ); + + // Await until lock request is granted + expect( fulfillment.next( false ).value.type ).toBe( 'AWAIT_PROMISE' ); + + // Ensure the promise isn't fulfilled at this point... + expect( notifyAcquired ).not.toBeCalled(); + + await sleep( 1000 ); + + // ...or even a second lateer + expect( notifyAcquired ).not.toBeCalled(); + + // Let's assume the promise was fulfilled in the end, the action should return + // the lock once that happens. + expect( fulfillment.next( lock ) ).toMatchObject( { + done: true, + value: lock, + } ); + } ); +} ); + +describe( '__unstableReleaseStoreLock', () => { + const lock = { store, path, exclusive: true }; + + it( 'Releases a lock request and attempts to fulfill pending lock requests', async () => { + const fulfillment = __unstableReleaseStoreLock( lock ); + + // Start + expect( fulfillment.next().value ).toMatchObject( { + type: 'RELEASE_LOCK', + lock, + } ); + + // Attempt to grant any pending lock requests, find none, return + expect( fulfillment.next().value.type ).toBe( + 'PROCESS_PENDING_LOCK_REQUESTS' + ); + expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); + + // Short-circuit with no results and return + expect( fulfillment.next( [] ) ).toMatchObject( { + done: true, + value: undefined, + } ); + } ); +} ); + +const sleep = ( ms ) => { + const promise = new Promise( ( resolve ) => setTimeout( resolve, ms ) ); + jest.advanceTimersByTime( ms + 1 ); + return promise; +}; diff --git a/packages/core-data/src/locks/test/reducer.js b/packages/core-data/src/locks/test/reducer.js new file mode 100644 index 00000000000000..b422ae9aa5ffa2 --- /dev/null +++ b/packages/core-data/src/locks/test/reducer.js @@ -0,0 +1,131 @@ +/** + * External dependencies + */ +import deepFreeze from 'deep-freeze'; + +/** + * Internal dependencies + */ +import { locks } from '../reducer'; + +const buildNode = ( children = {} ) => ( { + locks: [], + children, +} ); + +describe( 'locks', () => { + it( 'Enqueues lock requests', () => { + const request = {}; + const state = deepFreeze( { + requests: [], + } ); + + expect( + locks( state, { + type: 'ENQUEUE_LOCK_REQUEST', + request, + } ) + ).toEqual( { + requests: [ request ], + } ); + } ); + + it( 'Grants lock requests', () => { + const red = buildNode(); + const blue = buildNode(); + const green = buildNode(); + const bird = buildNode( { red, blue, green } ); + const tree = buildNode( { bird } ); + + const request = { store: 'bird', path: [ 'green' ] }; + const state = deepFreeze( { + requests: [ request ], + tree, + } ); + + const lock = {}; + expect( + locks( state, { + type: 'GRANT_LOCK_REQUEST', + lock, + request, + } ) + ).toEqual( { + // Should remove the request... + requests: [], + tree: { + locks: [], + children: { + bird: { + locks: [], + children: { + red, + blue, + green: { + // ...and add the lock + locks: [ lock ], + children: {}, + }, + }, + }, + }, + }, + } ); + } ); + + it( 'Releases acquired locks', () => { + const red = buildNode(); + const blue = buildNode(); + const lock = { + store: 'bird', + path: [ 'green' ], + }; + const state = deepFreeze( { + // Should remove the request... + requests: [], + tree: { + locks: [], + children: { + bird: { + locks: [], + children: { + red, + blue, + green: { + // ...and add the lock + locks: [ lock ], + children: {}, + }, + }, + }, + }, + }, + } ); + + expect( + locks( state, { + type: 'RELEASE_LOCK', + lock, + } ) + ).toEqual( { + requests: [], + tree: { + locks: [], + children: { + bird: { + locks: [], + children: { + red, + blue, + green: { + // Should remove the lock + locks: [], + children: {}, + }, + }, + }, + }, + }, + } ); + } ); +} ); diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js new file mode 100644 index 00000000000000..38d2da80a8ca43 --- /dev/null +++ b/packages/core-data/src/locks/test/selectors.js @@ -0,0 +1,473 @@ +/** + * External dependencies + */ +import deepFreeze from 'deep-freeze'; + +/** + * Internal dependencies + */ +import { + __unstableGetPendingLockRequests, + __unstableIsLockAvailable, +} from '../selectors'; +import { deepCopyLocksTreePath, getNode } from '../utils'; + +describe( '__unstableGetPendingLockRequests', () => { + it( 'returns pending lock requests', () => { + const state = deepFreeze( { + locks: { + requests: [ 1, 2, 3 ], + }, + } ); + + expect( __unstableGetPendingLockRequests( state ) ).toEqual( [ + 1, + 2, + 3, + ] ); + } ); +} ); + +describe( '__unstableIsLockAvailable', () => { + describe( 'smoke tests', () => { + it( 'returns true if lock is available', () => { + const state = deepFreeze( { + locks: { + tree: { + children: {}, + locks: [], + }, + }, + } ); + + expect( + __unstableIsLockAvailable( state, 'core', [], { + exclusive: true, + } ) + ).toBe( true ); + } ); + it( 'returns false if lock is not available', () => { + const state = deepFreeze( { + locks: { + tree: { + children: {}, + locks: [ { exclusive: false } ], + }, + }, + } ); + + expect( + __unstableIsLockAvailable( state, 'core', [], { + exclusive: true, + } ) + ).toBe( false ); + } ); + } ); + + describe( 'Advanced cases - exclusive lock', () => { + let state; + beforeEach( () => { + state = buildState( [ + [ 'core', 'entities', 'root', 'template_part', '3' ], + [ 'core', 'queries' ], + [ 'vendor' ], + ] ); + } ); + it( `returns true if no parent or descendant has any locks`, () => { + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (1)`, () => { + appendLock( state, 'core', [ 'queries' ], { + exclusive: true, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (2)`, () => { + appendLock( state, 'vendor', [], { + exclusive: true, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (3)`, () => { + const subState = { + locks: { + tree: { + locks: [], + children: { + postType: { + locks: [], + children: { + post: { + locks: [], + children: { + '16': { + locks: [ + { + store: 'core', + path: [ + 'entities', + 'data', + 'postType', + 'post', + 16, + ], + exclusive: true, + }, + ], + children: {}, + }, + }, + }, + wp_template_part: { + locks: [], + children: { + '17': { + locks: [], + children: {}, + }, + }, + }, + }, + }, + }, + }, + }, + }; + expect( + __unstableIsLockAvailable( + deepFreeze( subState ), + 'core', + [ 'postType', 'wp_template_part', 17 ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (4)`, () => { + const subState = { + locks: { + tree: { + locks: [], + children: { + core: { + locks: [], + children: { + entities: { + locks: [], + children: { + data: { + locks: [], + children: { + postType: { + locks: [], + children: { + book: { + locks: [], + children: { + 67: { + locks: [ + { + path: [ + 'core', + 'entities', + 'data', + 'postType', + 'book', + 67, + ], + exclusive: true, + }, + ], + children: {}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }; + expect( + __unstableIsLockAvailable( + deepFreeze( subState ), + 'core', + [ 'entities', 'data', 'postType', 'book', 67 ], + { exclusive: false } + ) + ).toBe( false ); + } ); + + [ true, false ].forEach( ( exclusive ) => { + it( `returns true if the path is not accessible and no parent holds a lock`, () => { + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'fake', 'path' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns false if the path is not accessible and any parent holds a lock`, () => { + appendLock( state, 'core', [], { + exclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'fake', 'path' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + + it( `returns false if top-level parent already has a lock with exclusive=${ exclusive }`, () => { + appendLock( state, 'core', [], { + exclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + + it( `returns false if a direct parent already has a lock with exclusive=${ exclusive }`, () => { + appendLock( state, 'core', [ 'entities' ], { + exclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + + it( `returns false if the target node already has a lock with exclusive=${ exclusive }`, () => { + appendLock( state, 'core', [ 'entities', 'root' ], { + exclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + + it( `returns false if a children node already has a lock with exclusive=${ exclusive }`, () => { + appendLock( + state, + 'core', + [ 'entities', 'root', 'template_part' ], + { + exclusive, + } + ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + + it( `returns false if a grand-children node already has a lock with exclusive=${ exclusive }`, () => { + appendLock( + state, + 'core', + [ 'entities', 'root', 'template_part', '3' ], + { + exclusive, + } + ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + } ); + } ); + + describe( 'Advanced cases - shared lock', () => { + let state; + beforeEach( () => { + state = buildState( [ + [ 'core', 'entities', 'root', 'template_part', '3' ], + ] ); + } ); + it( `returns true if no parent or descendant has any locks`, () => { + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + [ true, false ].forEach( ( isOtherLockExclusive ) => { + const expectation = ! isOtherLockExclusive; + it( `returns ${ expectation } if the path is not accessible and any parent holds a lock exclusive=${ isOtherLockExclusive }`, () => { + appendLock( state, 'core', [], { + exclusive: isOtherLockExclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'fake', 'path' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + + it( `returns ${ expectation } if top-level parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( state, 'core', [], { + exclusive: isOtherLockExclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + + it( `returns ${ expectation } if a direct parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( state, 'core', [ 'entities' ], { + exclusive: isOtherLockExclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + + it( `returns ${ expectation } if the target node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( state, 'core', [ 'entities', 'root' ], { + exclusive: isOtherLockExclusive, + } ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + + it( `returns ${ expectation } if a children node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( + state, + 'core', + [ 'entities', 'root', 'template_part' ], + { + exclusive: isOtherLockExclusive, + } + ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + + it( `returns ${ expectation } if a grand-children node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( + state, + 'core', + [ 'entities', 'root', 'template_part', '3' ], + { + exclusive: isOtherLockExclusive, + } + ); + expect( + __unstableIsLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + } ); + } ); +} ); + +function appendLock( state, store, path, lock ) { + getNode( state.locks.tree, [ store, ...path ] ).locks.push( lock ); +} + +function buildState( paths ) { + return { + locks: { + requests: [], + tree: paths.reduce( + ( tree, path ) => deepCopyLocksTreePath( tree, path ), + { + locks: [], + children: {}, + } + ), + }, + }; +} diff --git a/packages/core-data/src/locks/test/utils.js b/packages/core-data/src/locks/test/utils.js new file mode 100644 index 00000000000000..f712e1a2b001f0 --- /dev/null +++ b/packages/core-data/src/locks/test/utils.js @@ -0,0 +1,243 @@ +/** + * External dependencies + */ +import deepFreeze from 'deep-freeze'; + +/** + * Internal dependencies + */ +import { + getNode, + iteratePath, + iterateDescendants, + hasConflictingLock, + deepCopyLocksTreePath, +} from '../utils'; + +describe( 'getNode', () => { + const tree = deepFreeze( { + locks: [], + children: { + target: { + locks: [], + children: {}, + }, + }, + } ); + + it( 'Returns a specified node from the tree', () => { + expect( getNode( tree, [] ) ).toBe( tree ); + expect( getNode( tree, [ 'target' ] ) ).toBe( tree.children.target ); + } ); + it( 'Returns null when specified node does not exist', () => { + expect( getNode( tree, [ 'fake' ] ) ).toBe( null ); + } ); +} ); + +describe( 'iteratePath', () => { + const buildNode = ( children = {} ) => ( { + locks: [], + children, + } ); + const red = buildNode(); + const blue = buildNode(); + const green = buildNode(); + const bird = buildNode( { red, blue, green } ); + const target = buildNode( { bird } ); + const tree = deepFreeze( buildNode( { target } ) ); + + it( 'Is a generator', () => { + const isGenerator = [ + 'GeneratorFunction', + 'AsyncGeneratorFunction', + ].includes( iteratePath.constructor.name ); + expect( isGenerator ).toBe( true ); + } ); + + it( 'Yields the root first', () => { + expect( + Array.from( iteratePath( tree, [ 'target', 'bird' ] ) )[ 0 ] + ).toEqual( tree ); + } ); + + it( 'Iterates over a specified tree path', () => { + expect( + Array.from( iteratePath( tree, [ 'target', 'bird', 'green' ] ) ) + ).toEqual( [ tree, target, bird, green ] ); + } ); + + it( 'Yields just the root if the path is empty', () => { + expect( Array.from( iteratePath( tree, [] ) ) ).toEqual( [ tree ] ); + } ); + + it( 'Yields only the accessible nodes in the path', () => { + expect( + Array.from( iteratePath( tree, [ 'target', 'bird', 'fake' ] ) ) + ).toEqual( [ tree, target, bird ] ); + } ); +} ); + +describe( 'iterateDescendants', () => { + const buildNode = ( children = {} ) => ( { + locks: [], + children, + } ); + const red = buildNode(); + const blue = buildNode(); + const green = buildNode(); + const bird = buildNode( { red, blue, green } ); + const big = buildNode(); + const small = buildNode(); + const large = buildNode(); + const house = buildNode( { big, small, large } ); + + const tree = buildNode( { bird, house } ); + + it( 'Is a generator', () => { + const isGenerator = [ + 'GeneratorFunction', + 'AsyncGeneratorFunction', + ].includes( iterateDescendants.constructor.name ); + expect( isGenerator ).toBe( true ); + } ); + + it( 'Yields nothing when no children are available', () => { + expect( Array.from( iterateDescendants( red ) ) ).toEqual( [] ); + } ); + + it( 'Yields children when there is just one level of nesting', () => { + const results = Array.from( iterateDescendants( bird ) ); + expect( results ).toHaveLength( 3 ); + expect( results ).toEqual( + expect.arrayContaining( [ red, blue, green ] ) + ); + } ); + + it( 'Yields all descendants when ran on deep structure', () => { + const results = Array.from( iterateDescendants( tree ) ); + expect( results ).toHaveLength( 8 ); + expect( results ).toEqual( + expect.arrayContaining( [ + bird, + red, + blue, + green, + house, + big, + small, + green, + ] ) + ); + } ); +} ); + +describe( 'hasConflictingLock', () => { + it( 'Returns false when requesting an exclusive lock and no locks are present', () => { + expect( hasConflictingLock( { exclusive: true }, [] ) ).toBe( false ); + } ); + it( 'Returns true when requesting an exclusive lock and any locks at all are present', () => { + expect( + hasConflictingLock( { exclusive: true }, [ { exclusive: false } ] ) + ).toBe( true ); + expect( + hasConflictingLock( { exclusive: true }, [ { exclusive: true } ] ) + ).toBe( true ); + } ); + + it( 'Returns false when requesting a shared lock and no locks are present', () => { + expect( hasConflictingLock( { exclusive: false }, [] ) ).toBe( false ); + } ); + + it( 'Returns false when requesting a shared lock and only shared locks at all are present', () => { + expect( + hasConflictingLock( { exclusive: false }, [ { exclusive: false } ] ) + ).toBe( false ); + expect( + hasConflictingLock( { exclusive: false }, [ + { exclusive: false }, + { exclusive: false }, + { exclusive: false }, + ] ) + ).toBe( false ); + } ); + + it( 'Returns true when requesting a shared lock and any exclusive shared locks at all are present', () => { + expect( + hasConflictingLock( { exclusive: false }, [ { exclusive: true } ] ) + ).toBe( true ); + expect( + hasConflictingLock( { exclusive: false }, [ + { exclusive: false }, + { exclusive: true }, + { exclusive: false }, + ] ) + ).toBe( true ); + } ); +} ); + +describe( 'deepCopyLocksTreePath', () => { + it( 'Returns a tree with a cloned path', () => { + const tree = deepFreeze( { + locks: [ { exclusive: true } ], + children: { + target: { + locks: [], + children: {}, + }, + }, + } ); + + const deepCopy = deepCopyLocksTreePath( tree, [ 'target' ] ); + expect( deepCopy ).toMatchObject( tree ); + // Path to the target node should be cloned (named branches and their `children` containers) + expect( deepCopy.children ).not.toBe( tree.children ); + expect( deepCopy.children.target ).not.toBe( tree.children.target ); + + // Locks lists should be preserved + expect( deepCopy.locks ).toBe( tree.locks ); + expect( deepCopy.children.target.locks ).toBe( + tree.children.target.locks + ); + + // Specific locks should be preserved + expect( deepCopy.locks[ 0 ] ).toBe( tree.locks[ 0 ] ); + + // No need to clone lower levels of the tree, let's check if they're still the same: + expect( deepCopy.children.target.children ).toBe( + tree.children.target.children + ); + } ); + + it( 'Creates missing branches', () => { + const tree = deepFreeze( { + locks: [ { exclusive: true } ], + children: { + target: { + locks: [], + children: {}, + }, + }, + } ); + + const deepCopy = deepCopyLocksTreePath( + tree, + [ 'target', 'bird', 'blue' ], + { + createMissing: true, + } + ); + const target = deepCopy.children.target; + expect( Object.keys( target.children ) ).toEqual( [ 'bird' ] ); + expect( Object.keys( target.children.bird ) ).toEqual( [ + 'locks', + 'children', + ] ); + expect( Object.keys( target.children.bird.children ) ).toEqual( [ + 'blue', + ] ); + expect( Object.keys( target.children.bird.children.blue ) ).toEqual( [ + 'locks', + 'children', + ] ); + } ); +} ); diff --git a/packages/core-data/src/locks/utils.js b/packages/core-data/src/locks/utils.js new file mode 100644 index 00000000000000..13735b49a36ec9 --- /dev/null +++ b/packages/core-data/src/locks/utils.js @@ -0,0 +1,62 @@ +export function deepCopyLocksTreePath( tree, path ) { + const newTree = { ...tree }; + let currentNode = newTree; + for ( const branchName of path ) { + currentNode.children = { + ...currentNode.children, + [ branchName ]: { + locks: [], + children: {}, + ...currentNode.children[ branchName ], + }, + }; + currentNode = currentNode.children[ branchName ]; + } + return newTree; +} + +export function getNode( tree, path ) { + let currentNode = tree; + for ( const branchName of path ) { + const nextNode = currentNode.children[ branchName ]; + if ( ! nextNode ) { + return null; + } + currentNode = nextNode; + } + return currentNode; +} + +export function* iteratePath( tree, path ) { + let currentNode = tree; + yield currentNode; + for ( const branchName of path ) { + const nextNode = currentNode.children[ branchName ]; + if ( ! nextNode ) { + break; + } + yield nextNode; + currentNode = nextNode; + } +} + +export function* iterateDescendants( node ) { + const stack = Object.values( node.children ); + while ( stack.length ) { + const childNode = stack.pop(); + yield childNode; + stack.push( ...Object.values( childNode.children ) ); + } +} + +export function hasConflictingLock( { exclusive }, locks ) { + if ( exclusive && locks.length ) { + return true; + } + + if ( ! exclusive && locks.filter( ( lock ) => lock.exclusive ).length ) { + return true; + } + + return false; +} diff --git a/packages/core-data/src/reducer.js b/packages/core-data/src/reducer.js index 8238c42380da9f..5bbe9ccbb855a2 100644 --- a/packages/core-data/src/reducer.js +++ b/packages/core-data/src/reducer.js @@ -15,6 +15,7 @@ import isShallowEqual from '@wordpress/is-shallow-equal'; import { ifMatchingAction, replaceAction } from './utils'; import { reducer as queriedDataReducer } from './queried-data'; import { defaultEntities, DEFAULT_ENTITY_KEY } from './entities'; +import { reducer as locksReducer } from './locks'; /** * Reducer managing terms state. Keyed by taxonomy slug, the value is either @@ -567,4 +568,5 @@ export default combineReducers( { embedPreviews, userPermissions, autosaves, + locks: locksReducer, } ); diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index c7b759f0dc643c..20da8cd3e4cf6b 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -26,6 +26,10 @@ import { } from './actions'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; import { ifNotResolved, getNormalizedCommaSeparable } from './utils'; +import { + __unstableAcquireStoreLock, + __unstableReleaseStoreLock, +} from './locks'; /** * Requests authors from the REST API. @@ -61,51 +65,60 @@ export function* getEntityRecord( kind, name, key = '', query ) { return; } - if ( query !== undefined && query._fields ) { - // If requesting specific fields, items and query assocation to said - // records are stored by ID reference. Thus, fields must always include - // the ID. - query = { - ...query, - _fields: uniq( [ - ...( getNormalizedCommaSeparable( query._fields ) || [] ), - entity.key || DEFAULT_ENTITY_KEY, - ] ).join(), - }; - } + const lock = yield* __unstableAcquireStoreLock( + 'core', + [ 'entities', 'data', kind, name, key ], + { exclusive: false } + ); + try { + if ( query !== undefined && query._fields ) { + // If requesting specific fields, items and query assocation to said + // records are stored by ID reference. Thus, fields must always include + // the ID. + query = { + ...query, + _fields: uniq( [ + ...( getNormalizedCommaSeparable( query._fields ) || [] ), + entity.key || DEFAULT_ENTITY_KEY, + ] ).join(), + }; + } - // Disable reason: While true that an early return could leave `path` - // unused, it's important that path is derived using the query prior to - // additional query modifications in the condition below, since those - // modifications are relevant to how the data is tracked in state, and not - // for how the request is made to the REST API. + // Disable reason: While true that an early return could leave `path` + // unused, it's important that path is derived using the query prior to + // additional query modifications in the condition below, since those + // modifications are relevant to how the data is tracked in state, and not + // for how the request is made to the REST API. - // eslint-disable-next-line @wordpress/no-unused-vars-before-return - const path = addQueryArgs( entity.baseURL + '/' + key, { - ...query, - context: 'edit', - } ); + // eslint-disable-next-line @wordpress/no-unused-vars-before-return + const path = addQueryArgs( entity.baseURL + '/' + key, { + ...query, + context: 'edit', + } ); - if ( query !== undefined ) { - query = { ...query, include: [ key ] }; - - // The resolution cache won't consider query as reusable based on the - // fields, so it's tested here, prior to initiating the REST request, - // and without causing `getEntityRecords` resolution to occur. - const hasRecords = yield controls.select( - 'core', - 'hasEntityRecords', - kind, - name, - query - ); - if ( hasRecords ) { - return; + if ( query !== undefined ) { + query = { ...query, include: [ key ] }; + + // The resolution cache won't consider query as reusable based on the + // fields, so it's tested here, prior to initiating the REST request, + // and without causing `getEntityRecords` resolution to occur. + const hasRecords = yield controls.select( + 'core', + 'hasEntityRecords', + kind, + name, + query + ); + if ( hasRecords ) { + return; + } } - } - const record = yield apiFetch( { path } ); - yield receiveEntityRecords( kind, name, record, query ); + const record = yield apiFetch( { path } ); + yield receiveEntityRecords( kind, name, record, query ); + } finally { + yield* __unstableReleaseStoreLock( lock ); + } } /** @@ -138,59 +151,68 @@ export function* getEntityRecords( kind, name, query = {} ) { return; } - if ( query._fields ) { - // If requesting specific fields, items and query assocation to said - // records are stored by ID reference. Thus, fields must always include - // the ID. - query = { - ...query, - _fields: uniq( [ - ...( getNormalizedCommaSeparable( query._fields ) || [] ), - entity.key || DEFAULT_ENTITY_KEY, - ] ).join(), - }; - } + const lock = yield* __unstableAcquireStoreLock( + 'core', + [ 'entities', 'data', kind, name ], + { exclusive: false } + ); + try { + if ( query._fields ) { + // If requesting specific fields, items and query assocation to said + // records are stored by ID reference. Thus, fields must always include + // the ID. + query = { + ...query, + _fields: uniq( [ + ...( getNormalizedCommaSeparable( query._fields ) || [] ), + entity.key || DEFAULT_ENTITY_KEY, + ] ).join(), + }; + } - const path = addQueryArgs( entity.baseURL, { - ...query, - context: 'edit', - } ); + const path = addQueryArgs( entity.baseURL, { + ...query, + context: 'edit', + } ); - let records = Object.values( yield apiFetch( { path } ) ); - // If we request fields but the result doesn't contain the fields, - // explicitely set these fields as "undefined" - // that way we consider the query "fullfilled". - if ( query._fields ) { - records = records.map( ( record ) => { - query._fields.split( ',' ).forEach( ( field ) => { - if ( ! record.hasOwnProperty( field ) ) { - record[ field ] = undefined; - } + let records = Object.values( yield apiFetch( { path } ) ); + // If we request fields but the result doesn't contain the fields, + // explicitely set these fields as "undefined" + // that way we consider the query "fullfilled". + if ( query._fields ) { + records = records.map( ( record ) => { + query._fields.split( ',' ).forEach( ( field ) => { + if ( ! record.hasOwnProperty( field ) ) { + record[ field ] = undefined; + } + } ); + + return record; } ); + } - return record; - } ); - } - - yield receiveEntityRecords( kind, name, records, query ); - // When requesting all fields, the list of results can be used to - // resolve the `getEntityRecord` selector in addition to `getEntityRecords`. - // See https://github.com/WordPress/gutenberg/pull/26575 - if ( ! query?._fields ) { - for ( const record of records ) { - if ( record.id ) { - yield { - type: 'START_RESOLUTION', - selectorName: 'getEntityRecord', - args: [ kind, name, record.id ], - }; - yield { - type: 'FINISH_RESOLUTION', - selectorName: 'getEntityRecord', - args: [ kind, name, record.id ], - }; + yield receiveEntityRecords( kind, name, records, query ); + // When requesting all fields, the list of results can be used to + // resolve the `getEntityRecord` selector in addition to `getEntityRecords`. + // See https://github.com/WordPress/gutenberg/pull/26575 + if ( ! query?._fields ) { + for ( const record of records ) { + if ( record.id ) { + yield { + type: 'START_RESOLUTION', + selectorName: 'getEntityRecord', + args: [ kind, name, record.id ], + }; + yield { + type: 'FINISH_RESOLUTION', + selectorName: 'getEntityRecord', + args: [ kind, name, record.id ], + }; + } } } + } finally { + yield* __unstableReleaseStoreLock( lock ); } } diff --git a/packages/core-data/src/test/actions.js b/packages/core-data/src/test/actions.js index e76936c1ef7873..4dbad511f4503f 100644 --- a/packages/core-data/src/test/actions.js +++ b/packages/core-data/src/test/actions.js @@ -16,6 +16,19 @@ import { receiveCurrentUser, } from '../actions'; +jest.mock( '../locks/actions', () => ( { + __unstableAcquireStoreLock: jest.fn( () => [ + { + type: 'MOCKED_ACQUIRE_LOCK', + }, + ] ), + __unstableReleaseStoreLock: jest.fn( () => [ + { + type: 'MOCKED_RELEASE_LOCK', + }, + ] ), +} ) ); + describe( 'editEntityRecord', () => { it( 'throws when the edited entity does not have a loaded config.', () => { const entity = { kind: 'someKind', name: 'someName', id: 'someId' }; @@ -28,6 +41,7 @@ describe( 'editEntityRecord', () => { expect( fulfillment.next().value ).toEqual( controls.select( 'core', 'getEntity', entity.kind, entity.name ) ); + // Don't pass back an entity config. expect( fulfillment.next.bind( fulfillment ) ).toThrow( `The entity being edited (${ entity.kind }, ${ entity.name }) does not have a loaded config.` @@ -46,8 +60,13 @@ describe( 'deleteEntityRecord', () => { // Trigger generator fulfillment.next(); - // Start + // Acquire lock expect( fulfillment.next( entities ).value.type ).toBe( + 'MOCKED_ACQUIRE_LOCK' + ); + + // Start + expect( fulfillment.next().value.type ).toEqual( 'DELETE_ENTITY_RECORD_START' ); @@ -64,6 +83,11 @@ describe( 'deleteEntityRecord', () => { 'DELETE_ENTITY_RECORD_FINISH' ); + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); + expect( fulfillment.next() ).toMatchObject( { done: true, value: undefined, @@ -80,8 +104,14 @@ describe( 'saveEntityRecord', () => { const fulfillment = saveEntityRecord( 'postType', 'post', post ); // Trigger generator fulfillment.next(); - // Provide entities and trigger apiFetch + + // Provide entities and acquire lock expect( fulfillment.next( entities ).value.type ).toBe( + 'MOCKED_ACQUIRE_LOCK' + ); + + // Trigger apiFetch + expect( fulfillment.next().value.type ).toEqual( 'SAVE_ENTITY_RECORD_START' ); @@ -116,6 +146,11 @@ describe( 'saveEntityRecord', () => { expect( fulfillment.next().value.type ).toBe( 'SAVE_ENTITY_RECORD_FINISH' ); + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); + expect( fulfillment.next().value ).toBe( updatedRecord ); } ); @@ -127,8 +162,14 @@ describe( 'saveEntityRecord', () => { const fulfillment = saveEntityRecord( 'postType', 'post', post ); // Trigger generator fulfillment.next(); - // Provide entities and trigger apiFetch + + // Provide entities and acquire lock expect( fulfillment.next( entities ).value.type ).toBe( + 'MOCKED_ACQUIRE_LOCK' + ); + + // Trigger apiFetch + expect( fulfillment.next().value.type ).toEqual( 'SAVE_ENTITY_RECORD_START' ); expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); @@ -151,6 +192,10 @@ describe( 'saveEntityRecord', () => { expect( fulfillment.next().value.type ).toBe( 'SAVE_ENTITY_RECORD_FINISH' ); + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); } ); it( 'triggers a PUT request for an existing record with a custom key', async () => { @@ -166,8 +211,14 @@ describe( 'saveEntityRecord', () => { const fulfillment = saveEntityRecord( 'root', 'postType', postType ); // Trigger generator fulfillment.next(); - // Provide entities and trigger apiFetch + + // Provide entities and acquire lock expect( fulfillment.next( entities ).value.type ).toBe( + 'MOCKED_ACQUIRE_LOCK' + ); + + // Trigger apiFetch + expect( fulfillment.next().value.type ).toEqual( 'SAVE_ENTITY_RECORD_START' ); expect( fulfillment.next().value.type ).toBe( '@@data/SELECT' ); @@ -194,6 +245,10 @@ describe( 'saveEntityRecord', () => { expect( fulfillment.next().value.type ).toBe( 'SAVE_ENTITY_RECORD_FINISH' ); + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); } ); } ); diff --git a/packages/core-data/src/test/integration.js b/packages/core-data/src/test/integration.js index a54a6e70cb67e2..5622a078f3622c 100644 --- a/packages/core-data/src/test/integration.js +++ b/packages/core-data/src/test/integration.js @@ -9,10 +9,14 @@ import { createRegistry, controls } from '@wordpress/data'; import { receiveEntityRecords } from '../actions'; import * as selectors from '../selectors'; import * as resolvers from '../resolvers'; +import * as locksActions from '../locks/actions'; +import * as locksSelectors from '../locks/selectors'; // Mock to prevent calling window.fetch in test environment jest.mock( '@wordpress/data-controls', () => { + const dataControls = jest.requireActual( '@wordpress/data-controls' ); return { + ...dataControls, apiFetch: jest.fn(), }; } ); @@ -27,13 +31,17 @@ describe( 'receiveEntityRecord', () => { }, }; registry.registerStore( 'core', { + actions: { + ...locksActions, + }, selectors: { getEntitiesByKind: () => [ { name: 'postType', kind: 'root', baseURL: '/wp/v2/types' }, { name: 'postType', kind: 'root', baseURL: '/wp/v2/types' }, ], + ...locksSelectors, }, - reducer: () => ( {} ), + reducer: () => ( { locks: { requests: [], children: {} } } ), } ); registry.registerStore( 'test/resolution', { actions: { diff --git a/packages/core-data/src/test/resolvers.js b/packages/core-data/src/test/resolvers.js index bdf25b14cfe621..cf3a29bd072d79 100644 --- a/packages/core-data/src/test/resolvers.js +++ b/packages/core-data/src/test/resolvers.js @@ -22,6 +22,19 @@ import { receiveCurrentUser, } from '../actions'; +jest.mock( '../locks/actions', () => ( { + __unstableAcquireStoreLock: jest.fn( () => [ + { + type: 'MOCKED_ACQUIRE_LOCK', + }, + ] ), + __unstableReleaseStoreLock: jest.fn( () => [ + { + type: 'MOCKED_RELEASE_LOCK', + }, + ] ), +} ) ); + describe( 'getEntityRecord', () => { const POST_TYPE = { slug: 'post' }; @@ -32,8 +45,12 @@ describe( 'getEntityRecord', () => { const fulfillment = getEntityRecord( 'root', 'postType', 'post' ); // Trigger generator fulfillment.next(); - // Provide entities and trigger apiFetch - const { value: apiFetchAction } = fulfillment.next( entities ); + // Provide entities and acquire lock + expect( fulfillment.next( entities ).value.type ).toEqual( + 'MOCKED_ACQUIRE_LOCK' + ); + // trigger apiFetch + const { value: apiFetchAction } = fulfillment.next(); expect( apiFetchAction.request ).toEqual( { path: '/wp/v2/types/post?context=edit', } ); @@ -42,6 +59,10 @@ describe( 'getEntityRecord', () => { expect( received ).toEqual( receiveEntityRecords( 'root', 'postType', POST_TYPE ) ); + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); } ); } ); @@ -60,8 +81,13 @@ describe( 'getEntityRecords', () => { // Trigger generator fulfillment.next(); - // Provide entities and trigger apiFetch - const { value: apiFetchAction } = fulfillment.next( ENTITIES ); + + // Provide entities and acquire lock + fulfillment.next( ENTITIES ); + + // trigger apiFetch + const { value: apiFetchAction } = fulfillment.next(); + expect( apiFetchAction.request ).toEqual( { path: '/wp/v2/types?context=edit', } ); @@ -77,12 +103,35 @@ describe( 'getEntityRecords', () => { ); } ); + it( 'Uses state locks', async () => { + const fulfillment = getEntityRecords( 'root', 'postType' ); + + // Repeat the steps from `yields with requested post type` test + fulfillment.next(); + // Provide entities and acquire lock + expect( fulfillment.next( ENTITIES ).value.type ).toEqual( + 'MOCKED_ACQUIRE_LOCK' + ); + fulfillment.next(); + fulfillment.next( POST_TYPES ); + + // Resolve specific entity records + fulfillment.next(); + fulfillment.next(); + + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); + } ); + it( 'marks specific entity records as resolved', async () => { const fulfillment = getEntityRecords( 'root', 'postType' ); // Repeat the steps from `yields with requested post type` test fulfillment.next(); fulfillment.next( ENTITIES ); + fulfillment.next(); fulfillment.next( POST_TYPES ); // It should mark the entity record that has an ID as resolved @@ -96,8 +145,6 @@ describe( 'getEntityRecords', () => { selectorName: 'getEntityRecord', args: [ ENTITIES[ 1 ].kind, ENTITIES[ 1 ].name, 2 ], } ); - - expect( fulfillment.next().done ).toEqual( true ); } ); } ); diff --git a/packages/data-controls/README.md b/packages/data-controls/README.md index d9a346956e00c9..d7c75d330c71a2 100644 --- a/packages/data-controls/README.md +++ b/packages/data-controls/README.md @@ -45,6 +45,10 @@ _Returns_ - `Object`: The control descriptor. +# **awaitPromise** + +Undocumented declaration. + # **controls** The default export is what you use to register the controls with your custom @@ -64,14 +68,18 @@ import * as actions from './actions'; import * as resolvers from './resolvers'; registerStore( 'my-custom-store', { - reducer, - controls, - actions, - selectors, - resolvers, +reducer, +controls, +actions, +selectors, +resolvers, } ); ``` +_Parameters_ + +- _paths_ (unknown type): + _Returns_ - `Object`: An object for registering the default controls with the store. diff --git a/packages/data-controls/src/index.js b/packages/data-controls/src/index.js index a789a197b5a5f1..eaf4e17ff13731 100644 --- a/packages/data-controls/src/index.js +++ b/packages/data-controls/src/index.js @@ -73,10 +73,18 @@ export function dispatch( ...args ) { return dataControls.dispatch( ...args ); } +export const awaitPromise = function ( promise ) { + return { + type: 'AWAIT_PROMISE', + promise, + }; +}; + /** * The default export is what you use to register the controls with your custom * store. * + * @param paths * @example * ```js * // WordPress dependencies @@ -90,18 +98,20 @@ export function dispatch( ...args ) { * import * as resolvers from './resolvers'; * * registerStore( 'my-custom-store', { - * reducer, - * controls, - * actions, - * selectors, - * resolvers, + * reducer, + * controls, + * actions, + * selectors, + * resolvers, * } ); * ``` - * * @return {Object} An object for registering the default controls with the - * store. + * store. */ export const controls = { + AWAIT_PROMISE: async ( { promise } ) => { + return await promise; + }, API_FETCH( { request } ) { return triggerFetch( request ); }, diff --git a/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js b/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js index 16a348b2ac7d69..491ec3935577df 100644 --- a/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js +++ b/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js @@ -86,7 +86,10 @@ describe( 'Multi-entity save flow', () => { expect( multiSaveButton ).not.toBeNull(); }; const assertMultiSaveDisabled = async () => { - const multiSaveButton = await page.$( multiSaveSelector ); + const multiSaveButton = await page.waitForSelector( + multiSaveSelector, + { hidden: true } + ); expect( multiSaveButton ).toBeNull(); };