From a6eedcd6e83973147e70ae5c5f2b96b0789dd16e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 28 Oct 2020 12:20:57 +0100 Subject: [PATCH 01/17] squash --- packages/core-data/package.json | 3 +- packages/core-data/src/index.js | 6 +- packages/core-data/src/locks/README.md | 108 ++++++ packages/core-data/src/locks/actions.js | 58 ++++ packages/core-data/src/locks/index.js | 3 + packages/core-data/src/locks/reducer.js | 62 ++++ packages/core-data/src/locks/selectors.js | 30 ++ packages/core-data/src/locks/test/actions.js | 308 ++++++++++++++++++ packages/core-data/src/locks/test/reducer.js | 130 ++++++++ .../core-data/src/locks/test/selectors.js | 303 +++++++++++++++++ packages/core-data/src/locks/test/utils.js | 237 ++++++++++++++ packages/core-data/src/locks/utils.js | 62 ++++ packages/core-data/src/reducer.js | 2 + packages/core-data/src/test/actions.js | 63 +++- packages/core-data/src/test/resolvers.js | 41 ++- packages/data-controls/README.md | 22 +- packages/data-controls/src/index.js | 24 +- 17 files changed, 1439 insertions(+), 23 deletions(-) create mode 100644 packages/core-data/src/locks/README.md create mode 100644 packages/core-data/src/locks/actions.js create mode 100644 packages/core-data/src/locks/index.js create mode 100644 packages/core-data/src/locks/reducer.js create mode 100644 packages/core-data/src/locks/selectors.js create mode 100644 packages/core-data/src/locks/test/actions.js create mode 100644 packages/core-data/src/locks/test/reducer.js create mode 100644 packages/core-data/src/locks/test/selectors.js create mode 100644 packages/core-data/src/locks/test/utils.js create mode 100644 packages/core-data/src/locks/utils.js diff --git a/packages/core-data/package.json b/packages/core-data/package.json index fb16c6212c62a6..b8e0c8c261c81d 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.1" }, "publishConfig": { "access": "public" 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..60fd15aa3aec0c --- /dev/null +++ b/packages/core-data/src/locks/actions.js @@ -0,0 +1,58 @@ +/** + * WordPress dependencies + */ +import { syncSelect, awaitPromise } from '@wordpress/data-controls'; + +export function* acquireStoreLock( store, path, { exclusive } ) { + const promise = yield* enqueueLockRequest( store, path, { exclusive } ); + yield* processPendingLockRequests(); + return yield awaitPromise( promise ); +} + +export function* enqueueLockRequest( store, path, { exclusive } ) { + let notifyAcquired; + const promise = new Promise( ( resolve ) => { + notifyAcquired = resolve; + } ); + yield { + type: 'ENQUEUE_LOCK_REQUEST', + request: { store, path: [ store, ...path ], exclusive, notifyAcquired }, + }; + return promise; +} + +export function* releaseStoreLock( lock ) { + yield { + type: 'RELEASE_LOCK', + lock, + }; + yield* processPendingLockRequests(); +} + +export function* processPendingLockRequests() { + yield { + type: 'PROCESS_PENDING_LOCK_REQUESTS', + }; + const lockRequests = yield syncSelect( 'core', 'getPendingLockRequests' ); + for ( const request of lockRequests ) { + const { store, path, exclusive, notifyAcquired } = request; + const isAvailable = yield syncSelect( + 'core', + 'isLockAvailable', + store, + path, + { + exclusive, + } + ); + if ( isAvailable ) { + const lock = { 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..3efaeebfce3fcf --- /dev/null +++ b/packages/core-data/src/locks/reducer.js @@ -0,0 +1,62 @@ +/** + * 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 { path } = request; + + const newTree = deepCopyLocksTreePath( state.tree, path ); + const node = getNode( newTree, path ); + node.locks = [ ...node.locks, lock ]; + + return { + ...state, + requests: state.requests.filter( ( r ) => r !== request ), + tree: newTree, + }; + } + case 'RELEASE_LOCK': { + const { lock } = action; + + const newTree = deepCopyLocksTreePath( state.tree, lock.path ); + const node = getNode( newTree, lock.path ); + 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..b5f58511941673 --- /dev/null +++ b/packages/core-data/src/locks/selectors.js @@ -0,0 +1,30 @@ +/** + * Internal dependencies + */ +import { iterateDescendants, iteratePath, hasConflictingLock } from './utils'; + +export function getPendingLockRequests( state ) { + return state.locks.requests; +} + +export function isLockAvailable( state, store, path, { exclusive } ) { + path = [ store, ...path ]; + const locks = state.locks.tree; + let node; + + // Validate all parents and the node itself + for ( node of iteratePath( locks, path ) ) { + if ( hasConflictingLock( { exclusive }, node.locks ) ) { + return false; + } + } + + // 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..d1a283e82fa4a0 --- /dev/null +++ b/packages/core-data/src/locks/test/actions.js @@ -0,0 +1,308 @@ +/** + * Internal dependencies + */ +import { + acquireStoreLock, + enqueueLockRequest, + releaseStoreLock, + processPendingLockRequests, +} from '../actions'; + +const store = 'test'; +const path = [ 'blue', 'bird' ]; +const lockPath = [ store, ...path ]; + +describe( 'enqueueLockRequest', () => { + it( 'Enqueues a lock request', async () => { + const fulfillment = enqueueLockRequest( store, path, { + exclusive: true, + } ); + + // Start + expect( fulfillment.next().value ).toMatchObject( { + type: 'ENQUEUE_LOCK_REQUEST', + request: { + store, + path: lockPath, + 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 = enqueueLockRequest( 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( 'processPendingLockRequests', () => { + const exclusive = true; + const lock = { path: lockPath, exclusive }; + + let notifyAcquired; + let request; + + beforeEach( () => { + notifyAcquired = jest.fn(); + request = { path: lockPath, exclusive, notifyAcquired }; + } ); + + it( 'Grants a lock request that may be granted', async () => { + const fulfillment = processPendingLockRequests(); + + // 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 = processPendingLockRequests(); + + // 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 = processPendingLockRequests(); + + // 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( 'acquireStoreLock', () => { + const exclusive = true; + const lock = { path: lockPath, exclusive }; + + let notifyAcquired; + let request; + + beforeEach( () => { + notifyAcquired = jest.fn(); + request = { path: lockPath, exclusive, notifyAcquired }; + } ); + + it( 'Enqueues a lock request and attempts to fulfill it', async () => { + const fulfillment = acquireStoreLock( 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 = acquireStoreLock( 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( 'releaseStoreLock', () => { + const lock = { path: lockPath, exclusive: true }; + + it( 'Releases a lock request and attempts to fulfill pending lock requests', async () => { + const fulfillment = releaseStoreLock( 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..e5c0e569461fe4 --- /dev/null +++ b/packages/core-data/src/locks/test/reducer.js @@ -0,0 +1,130 @@ +/** + * 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 = { path: [ 'bird', 'green' ] }; + const state = deepFreeze( { + requests: [ request ], + tree: 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 = { + path: [ 'bird', '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..e411bc6f2131f2 --- /dev/null +++ b/packages/core-data/src/locks/test/selectors.js @@ -0,0 +1,303 @@ +/** + * External dependencies + */ +import deepFreeze from 'deep-freeze'; + +/** + * Internal dependencies + */ +import { getPendingLockRequests, isLockAvailable } from '../selectors'; +import { deepCopyLocksTreePath, getNode } from '../utils'; + +describe( 'getPendingLockRequests', () => { + it( 'returns pending lock requests', () => { + const state = deepFreeze( { + locks: { + requests: [ 1, 2, 3 ], + }, + } ); + + expect( getPendingLockRequests( state ) ).toEqual( [ 1, 2, 3 ] ); + } ); +} ); + +describe( 'isLockAvailable', () => { + describe( 'smoke tests', () => { + it( 'returns true if lock is available', () => { + const state = deepFreeze( { + locks: { + tree: { + children: {}, + locks: [], + }, + }, + } ); + + expect( + isLockAvailable( state, 'core', [], { exclusive: true } ) + ).toBe( true ); + } ); + it( 'returns true if lock is not available', () => { + const state = deepFreeze( { + locks: { + tree: { + children: {}, + locks: [ { exclusive: false } ], + }, + }, + } ); + + expect( + isLockAvailable( 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( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (1/2)`, () => { + appendLock( state, [ 'core', 'queries' ], { + exclusive: true, + } ); + expect( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + it( `returns true if another branch holds a locks (2/2)`, () => { + appendLock( state, [ 'vendor' ], { + exclusive: true, + } ); + expect( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + [ true, false ].forEach( ( exclusive ) => { + it( `returns false if top-level parent already has a lock with exclusive=${ exclusive }`, () => { + appendLock( state, [], { + exclusive, + } ); + expect( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: true } + ) + ).toBe( true ); + } ); + + [ true, false ].forEach( ( isOtherLockExclusive ) => { + const expectation = ! isOtherLockExclusive; + it( `returns ${ expectation } if top-level parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { + appendLock( state, [], { + exclusive: isOtherLockExclusive, + } ); + expect( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + 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( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'entities', 'root' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + } ); + } ); +} ); + +function appendLock( state, path, lock ) { + getNode( state.locks.tree, 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..7ba2ca1742621a --- /dev/null +++ b/packages/core-data/src/locks/test/utils.js @@ -0,0 +1,237 @@ +/** + * 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 ] ); + } ); +} ); + +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/test/actions.js b/packages/core-data/src/test/actions.js index e76936c1ef7873..42fba5f4d674a8 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', () => ( { + acquireStoreLock: jest.fn( () => [ + { + type: 'MOCKED_ACQUIRE_LOCK', + }, + ] ), + releaseStoreLock: 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/resolvers.js b/packages/core-data/src/test/resolvers.js index bdf25b14cfe621..bc52fca997fbb3 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', () => ( { + acquireStoreLock: jest.fn( () => [ + { + type: 'MOCKED_ACQUIRE_LOCK', + }, + ] ), + releaseStoreLock: 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,15 @@ describe( 'getEntityRecords', () => { // 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?context=edit', } ); @@ -75,6 +103,11 @@ describe( 'getEntityRecords', () => { {} ) ); + + // Release lock + expect( fulfillment.next().value.type ).toEqual( + 'MOCKED_RELEASE_LOCK' + ); } ); it( 'marks specific entity records as resolved', async () => { diff --git a/packages/data-controls/README.md b/packages/data-controls/README.md index d9a346956e00c9..0fe95451ae351c 100644 --- a/packages/data-controls/README.md +++ b/packages/data-controls/README.md @@ -20,6 +20,10 @@ The following controls are available on the object returned by the module: +# **acquireStoreLock** + +Undocumented declaration. + # **apiFetch** Dispatches a control action for triggering an api fetch call. @@ -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. @@ -85,6 +93,10 @@ _Parameters_ - _args_ `Array`: Arguments passed without change to the `@wordpress/data` control. +# **releaseStoreLock** + +Undocumented declaration. + # **select** Control for resolving a selector in a registered data 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 ); }, From 69188dc2ad94571c1e9014890408de584ec404d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 28 Oct 2020 12:21:29 +0100 Subject: [PATCH 02/17] Lint --- packages/core-data/src/locks/test/reducer.js | 2 +- packages/data-controls/README.md | 12 ++++-------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/packages/core-data/src/locks/test/reducer.js b/packages/core-data/src/locks/test/reducer.js index e5c0e569461fe4..e458c8ba53e06a 100644 --- a/packages/core-data/src/locks/test/reducer.js +++ b/packages/core-data/src/locks/test/reducer.js @@ -40,7 +40,7 @@ describe( 'locks', () => { const request = { path: [ 'bird', 'green' ] }; const state = deepFreeze( { requests: [ request ], - tree: tree, + tree, } ); const lock = {}; diff --git a/packages/data-controls/README.md b/packages/data-controls/README.md index 0fe95451ae351c..d7c75d330c71a2 100644 --- a/packages/data-controls/README.md +++ b/packages/data-controls/README.md @@ -20,10 +20,6 @@ The following controls are available on the object returned by the module: -# **acquireStoreLock** - -Undocumented declaration. - # **apiFetch** Dispatches a control action for triggering an api fetch call. @@ -49,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 @@ -93,10 +93,6 @@ _Parameters_ - _args_ `Array`: Arguments passed without change to the `@wordpress/data` control. -# **releaseStoreLock** - -Undocumented declaration. - # **select** Control for resolving a selector in a registered data store. From 4b9a9299ff0a012b4253f9bf9178c56c1288ec66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 28 Oct 2020 12:25:09 +0100 Subject: [PATCH 03/17] Rebase actions and resolvers --- packages/core-data/src/actions.js | 502 +++++++++++++++------------- packages/core-data/src/resolvers.js | 193 ++++++----- 2 files changed, 375 insertions(+), 320 deletions(-) diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index c72bfdf97a6ed1..2643a368bc578e 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,7 @@ import { addQueryArgs } from '@wordpress/url'; */ import { receiveItems, removeItems, receiveQueriedItems } from './queried-data'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; +import { acquireStoreLock, releaseStoreLock } from './locks'; /** * Returns an action object used in signalling that authors have been received. @@ -162,39 +164,48 @@ export function* deleteEntityRecord( kind, name, recordId, query ) { return; } - yield { - type: 'DELETE_ENTITY_RECORD_START', - kind, - name, - recordId, - }; - + const lock = yield* acquireStoreLock( + '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* releaseStoreLock( lock ); + } } /** @@ -334,232 +345,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* acquireStoreLock( + '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* releaseStoreLock( lock ); } - yield { - type: 'SAVE_ENTITY_RECORD_FINISH', - kind, - name, - recordId, - error, - isAutosave, - }; - - return updatedRecord; } /** diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index c7b759f0dc643c..a58161c14b6629 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -26,6 +26,7 @@ import { } from './actions'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; import { ifNotResolved, getNormalizedCommaSeparable } from './utils'; +import { acquireStoreLock, releaseStoreLock } from './locks'; /** * Requests authors from the REST API. @@ -61,51 +62,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* acquireStoreLock( + '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* releaseStoreLock( lock ); + } } /** @@ -138,59 +148,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* acquireStoreLock( + '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* releaseStoreLock( lock ); } } From 824a7bc371ff72e3a09e61cb11d975192d1d53c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 28 Oct 2020 12:35:39 +0100 Subject: [PATCH 04/17] Remove the usage of syncSelect --- packages/core-data/src/locks/actions.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/core-data/src/locks/actions.js b/packages/core-data/src/locks/actions.js index 60fd15aa3aec0c..0ec24bcb905c52 100644 --- a/packages/core-data/src/locks/actions.js +++ b/packages/core-data/src/locks/actions.js @@ -1,7 +1,8 @@ /** * WordPress dependencies */ -import { syncSelect, awaitPromise } from '@wordpress/data-controls'; +import { awaitPromise } from '@wordpress/data-controls'; +import { controls } from '@wordpress/data'; export function* acquireStoreLock( store, path, { exclusive } ) { const promise = yield* enqueueLockRequest( store, path, { exclusive } ); @@ -33,10 +34,13 @@ export function* processPendingLockRequests() { yield { type: 'PROCESS_PENDING_LOCK_REQUESTS', }; - const lockRequests = yield syncSelect( 'core', 'getPendingLockRequests' ); + const lockRequests = yield controls.select( + 'core', + 'getPendingLockRequests' + ); for ( const request of lockRequests ) { const { store, path, exclusive, notifyAcquired } = request; - const isAvailable = yield syncSelect( + const isAvailable = yield controls.select( 'core', 'isLockAvailable', store, From 8013dbce19a02f8719b320375ee0b3771ccfbdca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 13:40:28 +0100 Subject: [PATCH 05/17] Update package-lock.json --- package-lock.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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": { From 74018d9316c5e1b0e5e959680ea313ab21aa7d00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 14:45:59 +0100 Subject: [PATCH 06/17] Update package-lock.json --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 1909925e760bd0..b6f26aa79ba7fa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17736,7 +17736,7 @@ "equivalent-key-map": "^0.2.2", "lodash": "^4.17.19", "rememo": "^3.0.0", - "uuid": "^8.3.0" + "uuid": "^8.3.1" } }, "@wordpress/create-block": { From c35eaea63a8140f01da044574abefaf9710d8eaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 14:57:28 +0100 Subject: [PATCH 07/17] Update package-lock.json --- package-lock.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index b6f26aa79ba7fa..41a5f2f7f33270 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17735,8 +17735,7 @@ "@wordpress/url": "file:packages/url", "equivalent-key-map": "^0.2.2", "lodash": "^4.17.19", - "rememo": "^3.0.0", - "uuid": "^8.3.1" + "rememo": "^3.0.0" } }, "@wordpress/create-block": { From f3f3a5af6f9c2ef25a73045bece93ec9f52c2844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 15:42:11 +0100 Subject: [PATCH 08/17] Fix a problem with lock not granted if a children of sibling of a parent (cousin? :D) held a conflicting lock --- packages/core-data/src/locks/selectors.js | 17 ++- .../core-data/src/locks/test/selectors.js | 100 +++++++++++++++++- packages/core-data/src/locks/test/utils.js | 6 ++ 3 files changed, 117 insertions(+), 6 deletions(-) diff --git a/packages/core-data/src/locks/selectors.js b/packages/core-data/src/locks/selectors.js index b5f58511941673..8b773e6df62ebf 100644 --- a/packages/core-data/src/locks/selectors.js +++ b/packages/core-data/src/locks/selectors.js @@ -1,7 +1,12 @@ /** * Internal dependencies */ -import { iterateDescendants, iteratePath, hasConflictingLock } from './utils'; +import { + iterateDescendants, + iteratePath, + hasConflictingLock, + getNode, +} from './utils'; export function getPendingLockRequests( state ) { return state.locks.requests; @@ -10,15 +15,21 @@ export function getPendingLockRequests( state ) { export function isLockAvailable( state, store, path, { exclusive } ) { path = [ store, ...path ]; const locks = state.locks.tree; - let node; // Validate all parents and the node itself - for ( node of iteratePath( locks, path ) ) { + for ( const node of iteratePath( locks, path ) ) { 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, path ); + if ( ! node ) { + return true; + } + // Validate all nested nodes for ( const descendant of iterateDescendants( node ) ) { if ( hasConflictingLock( { exclusive }, descendant.locks ) ) { diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js index e411bc6f2131f2..4afbe0e81066c9 100644 --- a/packages/core-data/src/locks/test/selectors.js +++ b/packages/core-data/src/locks/test/selectors.js @@ -37,7 +37,7 @@ describe( 'isLockAvailable', () => { isLockAvailable( state, 'core', [], { exclusive: true } ) ).toBe( true ); } ); - it( 'returns true if lock is not available', () => { + it( 'returns false if lock is not available', () => { const state = deepFreeze( { locks: { tree: { @@ -73,7 +73,7 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); - it( `returns true if another branch holds a locks (1/2)`, () => { + it( `returns true if another branch holds a locks (1/3)`, () => { appendLock( state, [ 'core', 'queries' ], { exclusive: true, } ); @@ -87,7 +87,7 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); - it( `returns true if another branch holds a locks (2/2)`, () => { + it( `returns true if another branch holds a locks (2/3)`, () => { appendLock( state, [ 'vendor' ], { exclusive: true, } ); @@ -101,7 +101,87 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); + it( `returns true if another branch holds a locks (3/3)`, () => { + const subState = { + locks: { + tree: { + locks: [], + children: { + postType: { + locks: [], + children: { + post: { + locks: [], + children: { + '16': { + locks: [ + { + path: [ + 'core', + 'entities', + 'data', + 'postType', + 'post', + 16, + ], + exclusive: true, + }, + ], + children: {}, + }, + }, + }, + wp_template_part: { + locks: [], + children: { + '17': { + locks: [], + children: {}, + }, + }, + }, + }, + }, + }, + }, + }, + }; + expect( + isLockAvailable( + deepFreeze( subState ), + 'core', + [ 'postType', 'wp_template_part', 17 ], + { exclusive: true } + ) + ).toBe( true ); + } ); + [ true, false ].forEach( ( exclusive ) => { + it( `returns true if the path is not accessible and no parent holds a lock`, () => { + expect( + isLockAvailable( + deepFreeze( state ), + 'core', + [ '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( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'core', 'fake', 'path' ], + { exclusive: true } + ) + ).toBe( false ); + } ); + it( `returns false if top-level parent already has a lock with exclusive=${ exclusive }`, () => { appendLock( state, [], { exclusive, @@ -202,6 +282,20 @@ describe( 'isLockAvailable', () => { [ 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( + isLockAvailable( + deepFreeze( state ), + 'core', + [ 'core', 'fake', 'path' ], + { exclusive: false } + ) + ).toBe( expectation ); + } ); + it( `returns ${ expectation } if top-level parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { appendLock( state, [], { exclusive: isOtherLockExclusive, diff --git a/packages/core-data/src/locks/test/utils.js b/packages/core-data/src/locks/test/utils.js index 7ba2ca1742621a..f712e1a2b001f0 100644 --- a/packages/core-data/src/locks/test/utils.js +++ b/packages/core-data/src/locks/test/utils.js @@ -69,6 +69,12 @@ describe( 'iteratePath', () => { 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', () => { From 9c36ab53e99ca5b00a8889ec9c29520850f49a1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 16:14:45 +0100 Subject: [PATCH 09/17] Fix multi-entity-saving.test.js --- .../specs/experiments/multi-entity-saving.test.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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..74eb67c0704072 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(); }; @@ -193,7 +196,7 @@ describe( 'Multi-entity save flow', () => { const saveA11ySelector = '.edit-site-editor__toggle-save-panel-button'; it( 'Save flow should work as expected', async () => { - expect.assertions( 5 ); + expect.assertions( 6 ); // Navigate to site editor. const query = addQueryArgs( '', { page: 'gutenberg-edit-site', From 42266f9e06cc39dfae893b7d7199188565aa613b Mon Sep 17 00:00:00 2001 From: Adam Zielinski Date: Thu, 29 Oct 2020 16:54:44 +0100 Subject: [PATCH 10/17] Update multi-entity-saving.test.js Restore expectation of 5 assertions --- .../e2e-tests/specs/experiments/multi-entity-saving.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 74eb67c0704072..491ec3935577df 100644 --- a/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js +++ b/packages/e2e-tests/specs/experiments/multi-entity-saving.test.js @@ -196,7 +196,7 @@ describe( 'Multi-entity save flow', () => { const saveA11ySelector = '.edit-site-editor__toggle-save-panel-button'; it( 'Save flow should work as expected', async () => { - expect.assertions( 6 ); + expect.assertions( 5 ); // Navigate to site editor. const query = addQueryArgs( '', { page: 'gutenberg-edit-site', From 47719754df6f897d1735c1154806a51c77d05f8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 17:23:22 +0100 Subject: [PATCH 11/17] Update required UUID version --- packages/core-data/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core-data/package.json b/packages/core-data/package.json index b8e0c8c261c81d..47ddfbab6de835 100644 --- a/packages/core-data/package.json +++ b/packages/core-data/package.json @@ -39,7 +39,7 @@ "equivalent-key-map": "^0.2.2", "lodash": "^4.17.19", "rememo": "^3.0.0", - "uuid": "^8.3.1" + "uuid": "^8.3.0" }, "publishConfig": { "access": "public" From dda83b190083c04bc1c7ddc639fa54a965ad883e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Thu, 29 Oct 2020 17:41:57 +0100 Subject: [PATCH 12/17] Update package-lock.json --- package-lock.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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": { From 775a02058fbc7308a501a5e75706be360e43ed5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Tue, 3 Nov 2020 12:38:47 +0100 Subject: [PATCH 13/17] Formalize store path as separate arguments in the public API --- packages/core-data/src/locks/actions.js | 4 +- packages/core-data/src/locks/reducer.js | 12 +- packages/core-data/src/locks/selectors.js | 6 +- packages/core-data/src/locks/test/actions.js | 13 +- packages/core-data/src/locks/test/reducer.js | 5 +- .../core-data/src/locks/test/selectors.js | 111 ++++++++++++++---- 6 files changed, 109 insertions(+), 42 deletions(-) diff --git a/packages/core-data/src/locks/actions.js b/packages/core-data/src/locks/actions.js index 0ec24bcb905c52..b1220225f3648b 100644 --- a/packages/core-data/src/locks/actions.js +++ b/packages/core-data/src/locks/actions.js @@ -17,7 +17,7 @@ export function* enqueueLockRequest( store, path, { exclusive } ) { } ); yield { type: 'ENQUEUE_LOCK_REQUEST', - request: { store, path: [ store, ...path ], exclusive, notifyAcquired }, + request: { store, path, exclusive, notifyAcquired }, }; return promise; } @@ -50,7 +50,7 @@ export function* processPendingLockRequests() { } ); if ( isAvailable ) { - const lock = { path, exclusive }; + const lock = { store, path, exclusive }; yield { type: 'GRANT_LOCK_REQUEST', lock, diff --git a/packages/core-data/src/locks/reducer.js b/packages/core-data/src/locks/reducer.js index 3efaeebfce3fcf..6a29de6a3ffaba 100644 --- a/packages/core-data/src/locks/reducer.js +++ b/packages/core-data/src/locks/reducer.js @@ -30,10 +30,11 @@ export function locks( state = DEFAULT_STATE, action ) { } case 'GRANT_LOCK_REQUEST': { const { lock, request } = action; - const { path } = request; + const { store, path } = request; + const storePath = [ store, ...path ]; - const newTree = deepCopyLocksTreePath( state.tree, path ); - const node = getNode( newTree, path ); + const newTree = deepCopyLocksTreePath( state.tree, storePath ); + const node = getNode( newTree, storePath ); node.locks = [ ...node.locks, lock ]; return { @@ -44,9 +45,10 @@ export function locks( state = DEFAULT_STATE, action ) { } case 'RELEASE_LOCK': { const { lock } = action; + const storePath = [ lock.store, ...lock.path ]; - const newTree = deepCopyLocksTreePath( state.tree, lock.path ); - const node = getNode( newTree, lock.path ); + const newTree = deepCopyLocksTreePath( state.tree, storePath ); + const node = getNode( newTree, storePath ); node.locks = node.locks.filter( ( l ) => l !== lock ); return { diff --git a/packages/core-data/src/locks/selectors.js b/packages/core-data/src/locks/selectors.js index 8b773e6df62ebf..6ec7d1a446a139 100644 --- a/packages/core-data/src/locks/selectors.js +++ b/packages/core-data/src/locks/selectors.js @@ -13,11 +13,11 @@ export function getPendingLockRequests( state ) { } export function isLockAvailable( state, store, path, { exclusive } ) { - path = [ store, ...path ]; + const storePath = [ store, ...path ]; const locks = state.locks.tree; // Validate all parents and the node itself - for ( const node of iteratePath( locks, path ) ) { + for ( const node of iteratePath( locks, storePath ) ) { if ( hasConflictingLock( { exclusive }, node.locks ) ) { return false; } @@ -25,7 +25,7 @@ export function isLockAvailable( state, store, path, { exclusive } ) { // iteratePath terminates early if path is unreachable, let's // re-fetch the node and check it exists in the tree. - const node = getNode( locks, path ); + const node = getNode( locks, storePath ); if ( ! node ) { return true; } diff --git a/packages/core-data/src/locks/test/actions.js b/packages/core-data/src/locks/test/actions.js index d1a283e82fa4a0..0f316ab5e9f9c1 100644 --- a/packages/core-data/src/locks/test/actions.js +++ b/packages/core-data/src/locks/test/actions.js @@ -10,7 +10,6 @@ import { const store = 'test'; const path = [ 'blue', 'bird' ]; -const lockPath = [ store, ...path ]; describe( 'enqueueLockRequest', () => { it( 'Enqueues a lock request', async () => { @@ -23,7 +22,7 @@ describe( 'enqueueLockRequest', () => { type: 'ENQUEUE_LOCK_REQUEST', request: { store, - path: lockPath, + path, exclusive: true, notifyAcquired: expect.any( Function ), }, @@ -64,14 +63,14 @@ describe( 'enqueueLockRequest', () => { describe( 'processPendingLockRequests', () => { const exclusive = true; - const lock = { path: lockPath, exclusive }; + const lock = { store, path, exclusive }; let notifyAcquired; let request; beforeEach( () => { notifyAcquired = jest.fn(); - request = { path: lockPath, exclusive, notifyAcquired }; + request = { store, path, exclusive, notifyAcquired }; } ); it( 'Grants a lock request that may be granted', async () => { @@ -184,14 +183,14 @@ describe( 'processPendingLockRequests', () => { describe( 'acquireStoreLock', () => { const exclusive = true; - const lock = { path: lockPath, exclusive }; + const lock = { store, path, exclusive }; let notifyAcquired; let request; beforeEach( () => { notifyAcquired = jest.fn(); - request = { path: lockPath, exclusive, notifyAcquired }; + request = { store, path, exclusive, notifyAcquired }; } ); it( 'Enqueues a lock request and attempts to fulfill it', async () => { @@ -276,7 +275,7 @@ describe( 'acquireStoreLock', () => { } ); describe( 'releaseStoreLock', () => { - const lock = { path: lockPath, exclusive: true }; + const lock = { store, path, exclusive: true }; it( 'Releases a lock request and attempts to fulfill pending lock requests', async () => { const fulfillment = releaseStoreLock( lock ); diff --git a/packages/core-data/src/locks/test/reducer.js b/packages/core-data/src/locks/test/reducer.js index e458c8ba53e06a..b422ae9aa5ffa2 100644 --- a/packages/core-data/src/locks/test/reducer.js +++ b/packages/core-data/src/locks/test/reducer.js @@ -37,7 +37,7 @@ describe( 'locks', () => { const bird = buildNode( { red, blue, green } ); const tree = buildNode( { bird } ); - const request = { path: [ 'bird', 'green' ] }; + const request = { store: 'bird', path: [ 'green' ] }; const state = deepFreeze( { requests: [ request ], tree, @@ -77,7 +77,8 @@ describe( 'locks', () => { const red = buildNode(); const blue = buildNode(); const lock = { - path: [ 'bird', 'green' ], + store: 'bird', + path: [ 'green' ], }; const state = deepFreeze( { // Should remove the request... diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js index 4afbe0e81066c9..56d095f8b2749d 100644 --- a/packages/core-data/src/locks/test/selectors.js +++ b/packages/core-data/src/locks/test/selectors.js @@ -73,8 +73,8 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); - it( `returns true if another branch holds a locks (1/3)`, () => { - appendLock( state, [ 'core', 'queries' ], { + it( `returns true if another branch holds a locks (1)`, () => { + appendLock( state, 'core', [ 'queries' ], { exclusive: true, } ); expect( @@ -87,8 +87,8 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); - it( `returns true if another branch holds a locks (2/3)`, () => { - appendLock( state, [ 'vendor' ], { + it( `returns true if another branch holds a locks (2)`, () => { + appendLock( state, 'vendor', [], { exclusive: true, } ); expect( @@ -101,7 +101,7 @@ describe( 'isLockAvailable', () => { ).toBe( true ); } ); - it( `returns true if another branch holds a locks (3/3)`, () => { + it( `returns true if another branch holds a locks (3)`, () => { const subState = { locks: { tree: { @@ -116,8 +116,8 @@ describe( 'isLockAvailable', () => { '16': { locks: [ { + store: 'core', path: [ - 'core', 'entities', 'data', 'postType', @@ -156,34 +156,95 @@ describe( 'isLockAvailable', () => { ).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( + isLockAvailable( + 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( isLockAvailable( deepFreeze( state ), 'core', - [ 'core', 'fake', 'path' ], + [ 'fake', 'path' ], { exclusive: true } ) ).toBe( true ); } ); it( `returns false if the path is not accessible and any parent holds a lock`, () => { - appendLock( state, [ 'core' ], { + appendLock( state, 'core', [], { exclusive, } ); expect( isLockAvailable( deepFreeze( state ), 'core', - [ 'core', 'fake', 'path' ], + [ 'fake', 'path' ], { exclusive: true } ) ).toBe( false ); } ); it( `returns false if top-level parent already has a lock with exclusive=${ exclusive }`, () => { - appendLock( state, [], { + appendLock( state, 'core', [], { exclusive, } ); expect( @@ -197,7 +258,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns false if a direct parent already has a lock with exclusive=${ exclusive }`, () => { - appendLock( state, [ 'core', 'entities' ], { + appendLock( state, 'core', [ 'entities' ], { exclusive, } ); expect( @@ -211,7 +272,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns false if the target node already has a lock with exclusive=${ exclusive }`, () => { - appendLock( state, [ 'core', 'entities', 'root' ], { + appendLock( state, 'core', [ 'entities', 'root' ], { exclusive, } ); expect( @@ -227,7 +288,8 @@ describe( 'isLockAvailable', () => { it( `returns false if a children node already has a lock with exclusive=${ exclusive }`, () => { appendLock( state, - [ 'core', 'entities', 'root', 'template_part' ], + 'core', + [ 'entities', 'root', 'template_part' ], { exclusive, } @@ -245,7 +307,8 @@ describe( 'isLockAvailable', () => { it( `returns false if a grand-children node already has a lock with exclusive=${ exclusive }`, () => { appendLock( state, - [ 'core', 'entities', 'root', 'template_part', '3' ], + 'core', + [ 'entities', 'root', 'template_part', '3' ], { exclusive, } @@ -283,21 +346,21 @@ describe( 'isLockAvailable', () => { [ 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' ], { + appendLock( state, 'core', [], { exclusive: isOtherLockExclusive, } ); expect( isLockAvailable( deepFreeze( state ), 'core', - [ 'core', 'fake', 'path' ], + [ 'fake', 'path' ], { exclusive: false } ) ).toBe( expectation ); } ); it( `returns ${ expectation } if top-level parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { - appendLock( state, [], { + appendLock( state, 'core', [], { exclusive: isOtherLockExclusive, } ); expect( @@ -311,7 +374,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns ${ expectation } if a direct parent already has a lock with exclusive=${ isOtherLockExclusive }`, () => { - appendLock( state, [ 'core', 'entities' ], { + appendLock( state, 'core', [ 'entities' ], { exclusive: isOtherLockExclusive, } ); expect( @@ -325,7 +388,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns ${ expectation } if the target node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { - appendLock( state, [ 'core', 'entities', 'root' ], { + appendLock( state, 'core', [ 'entities', 'root' ], { exclusive: isOtherLockExclusive, } ); expect( @@ -341,7 +404,8 @@ describe( 'isLockAvailable', () => { it( `returns ${ expectation } if a children node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { appendLock( state, - [ 'core', 'entities', 'root', 'template_part' ], + 'core', + [ 'entities', 'root', 'template_part' ], { exclusive: isOtherLockExclusive, } @@ -359,7 +423,8 @@ describe( 'isLockAvailable', () => { it( `returns ${ expectation } if a grand-children node already has a lock with exclusive=${ isOtherLockExclusive }`, () => { appendLock( state, - [ 'core', 'entities', 'root', 'template_part', '3' ], + 'core', + [ 'entities', 'root', 'template_part', '3' ], { exclusive: isOtherLockExclusive, } @@ -377,8 +442,8 @@ describe( 'isLockAvailable', () => { } ); } ); -function appendLock( state, path, lock ) { - getNode( state.locks.tree, path ).locks.push( lock ); +function appendLock( state, store, path, lock ) { + getNode( state.locks.tree, [ store, ...path ] ).locks.push( lock ); } function buildState( paths ) { From 7278fc0767a82c722e63b13d0dc39aa10b216ed2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Wed, 4 Nov 2020 13:00:13 +0100 Subject: [PATCH 14/17] Fix resolvers tests --- packages/core-data/src/test/resolvers.js | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/packages/core-data/src/test/resolvers.js b/packages/core-data/src/test/resolvers.js index bc52fca997fbb3..3137a7237a4114 100644 --- a/packages/core-data/src/test/resolvers.js +++ b/packages/core-data/src/test/resolvers.js @@ -83,9 +83,7 @@ describe( 'getEntityRecords', () => { fulfillment.next(); // Provide entities and acquire lock - expect( fulfillment.next( ENTITIES ).value.type ).toEqual( - 'MOCKED_ACQUIRE_LOCK' - ); + fulfillment.next( ENTITIES ); // trigger apiFetch const { value: apiFetchAction } = fulfillment.next(); @@ -103,6 +101,23 @@ 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( @@ -116,6 +131,7 @@ describe( 'getEntityRecords', () => { // 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 @@ -129,8 +145,6 @@ describe( 'getEntityRecords', () => { selectorName: 'getEntityRecord', args: [ ENTITIES[ 1 ].kind, ENTITIES[ 1 ].name, 2 ], } ); - - expect( fulfillment.next().done ).toEqual( true ); } ); } ); From ea37361b9d4b1a969fec8b93d674b0d3dc6718e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Mon, 9 Nov 2020 16:33:20 +0100 Subject: [PATCH 15/17] Fix integration tests --- packages/core-data/src/test/integration.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) 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: { From 95c989110f92e1a09e9921a70d0f849261da9a01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Mon, 9 Nov 2020 16:36:57 +0100 Subject: [PATCH 16/17] Mark the new public API as __unstable --- packages/core-data/src/actions.js | 10 ++-- packages/core-data/src/locks/actions.js | 18 +++---- packages/core-data/src/locks/selectors.js | 4 +- packages/core-data/src/locks/test/actions.js | 32 ++++++------ .../core-data/src/locks/test/selectors.js | 50 +++++++++---------- packages/core-data/src/resolvers.js | 10 ++-- packages/core-data/src/test/actions.js | 4 +- packages/core-data/src/test/resolvers.js | 4 +- 8 files changed, 66 insertions(+), 66 deletions(-) diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index 2643a368bc578e..3b189dae3e6fca 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -16,7 +16,7 @@ import { addQueryArgs } from '@wordpress/url'; */ import { receiveItems, removeItems, receiveQueriedItems } from './queried-data'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; -import { acquireStoreLock, releaseStoreLock } from './locks'; +import { __unstableAcquireStoreLock, __unstableReleaseStoreLock } from './locks'; /** * Returns an action object used in signalling that authors have been received. @@ -164,7 +164,7 @@ export function* deleteEntityRecord( kind, name, recordId, query ) { return; } - const lock = yield* acquireStoreLock( + const lock = yield* __unstableAcquireStoreLock( 'core', [ 'entities', 'data', kind, name, recordId ], { exclusive: true } @@ -204,7 +204,7 @@ export function* deleteEntityRecord( kind, name, recordId, query ) { return deletedRecord; } finally { - yield* releaseStoreLock( lock ); + yield* __unstableReleaseStoreLock( lock ); } } @@ -345,7 +345,7 @@ export function* saveEntityRecord( const entityIdKey = entity.key || DEFAULT_ENTITY_KEY; const recordId = record[ entityIdKey ]; - const lock = yield* acquireStoreLock( + const lock = yield* __unstableAcquireStoreLock( 'core', [ 'entities', 'data', kind, name, recordId || uuid() ], { exclusive: true } @@ -594,7 +594,7 @@ export function* saveEntityRecord( return updatedRecord; } finally { - yield* releaseStoreLock( lock ); + yield* __unstableReleaseStoreLock( lock ); } } diff --git a/packages/core-data/src/locks/actions.js b/packages/core-data/src/locks/actions.js index b1220225f3648b..f25ac3a4ed61b5 100644 --- a/packages/core-data/src/locks/actions.js +++ b/packages/core-data/src/locks/actions.js @@ -4,13 +4,13 @@ import { awaitPromise } from '@wordpress/data-controls'; import { controls } from '@wordpress/data'; -export function* acquireStoreLock( store, path, { exclusive } ) { - const promise = yield* enqueueLockRequest( store, path, { exclusive } ); - yield* processPendingLockRequests(); +export function* __unstableAcquireStoreLock( store, path, { exclusive } ) { + const promise = yield* __unstableEnqueueLockRequest( store, path, { exclusive } ); + yield* __unstableProcessPendingLockRequests(); return yield awaitPromise( promise ); } -export function* enqueueLockRequest( store, path, { exclusive } ) { +export function* __unstableEnqueueLockRequest( store, path, { exclusive } ) { let notifyAcquired; const promise = new Promise( ( resolve ) => { notifyAcquired = resolve; @@ -22,27 +22,27 @@ export function* enqueueLockRequest( store, path, { exclusive } ) { return promise; } -export function* releaseStoreLock( lock ) { +export function* __unstableReleaseStoreLock( lock ) { yield { type: 'RELEASE_LOCK', lock, }; - yield* processPendingLockRequests(); + yield* __unstableProcessPendingLockRequests(); } -export function* processPendingLockRequests() { +export function* __unstableProcessPendingLockRequests() { yield { type: 'PROCESS_PENDING_LOCK_REQUESTS', }; const lockRequests = yield controls.select( 'core', - 'getPendingLockRequests' + '__unstableGetPendingLockRequests' ); for ( const request of lockRequests ) { const { store, path, exclusive, notifyAcquired } = request; const isAvailable = yield controls.select( 'core', - 'isLockAvailable', + '__unstableIsLockAvailable', store, path, { diff --git a/packages/core-data/src/locks/selectors.js b/packages/core-data/src/locks/selectors.js index 6ec7d1a446a139..233b36985a5c54 100644 --- a/packages/core-data/src/locks/selectors.js +++ b/packages/core-data/src/locks/selectors.js @@ -8,11 +8,11 @@ import { getNode, } from './utils'; -export function getPendingLockRequests( state ) { +export function __unstableGetPendingLockRequests( state ) { return state.locks.requests; } -export function isLockAvailable( state, store, path, { exclusive } ) { +export function __unstableIsLockAvailable( state, store, path, { exclusive } ) { const storePath = [ store, ...path ]; const locks = state.locks.tree; diff --git a/packages/core-data/src/locks/test/actions.js b/packages/core-data/src/locks/test/actions.js index 0f316ab5e9f9c1..f3d2cbdb1b44a1 100644 --- a/packages/core-data/src/locks/test/actions.js +++ b/packages/core-data/src/locks/test/actions.js @@ -2,18 +2,18 @@ * Internal dependencies */ import { - acquireStoreLock, - enqueueLockRequest, - releaseStoreLock, - processPendingLockRequests, + __unstableAcquireStoreLock, + __unstableEnqueueLockRequest, + __unstableReleaseStoreLock, + __unstableProcessPendingLockRequests, } from '../actions'; const store = 'test'; const path = [ 'blue', 'bird' ]; -describe( 'enqueueLockRequest', () => { +describe( '__unstableEnqueueLockRequest', () => { it( 'Enqueues a lock request', async () => { - const fulfillment = enqueueLockRequest( store, path, { + const fulfillment = __unstableEnqueueLockRequest( store, path, { exclusive: true, } ); @@ -36,7 +36,7 @@ describe( 'enqueueLockRequest', () => { } ); it( 'Returns a promise fulfilled only after calling notifyAcquired', async () => { - const fulfillment = enqueueLockRequest( store, path, { + const fulfillment = __unstableEnqueueLockRequest( store, path, { exclusive: true, } ); const { request } = fulfillment.next().value; @@ -61,7 +61,7 @@ describe( 'enqueueLockRequest', () => { } ); } ); -describe( 'processPendingLockRequests', () => { +describe( '__unstableProcessPendingLockRequests', () => { const exclusive = true; const lock = { store, path, exclusive }; @@ -74,7 +74,7 @@ describe( 'processPendingLockRequests', () => { } ); it( 'Grants a lock request that may be granted', async () => { - const fulfillment = processPendingLockRequests(); + const fulfillment = __unstableProcessPendingLockRequests(); // Start expect( fulfillment.next().value.type ).toBe( @@ -115,7 +115,7 @@ describe( 'processPendingLockRequests', () => { } ); it( 'Does not grants a lock request that may not be granted', async () => { - const fulfillment = processPendingLockRequests(); + const fulfillment = __unstableProcessPendingLockRequests(); // Start expect( fulfillment.next().value.type ).toBe( @@ -138,7 +138,7 @@ describe( 'processPendingLockRequests', () => { } ); it( 'Handles multiple lock requests', async () => { - const fulfillment = processPendingLockRequests(); + const fulfillment = __unstableProcessPendingLockRequests(); // Start expect( fulfillment.next().value.type ).toBe( @@ -181,7 +181,7 @@ describe( 'processPendingLockRequests', () => { } ); } ); -describe( 'acquireStoreLock', () => { +describe( '__unstableAcquireStoreLock', () => { const exclusive = true; const lock = { store, path, exclusive }; @@ -194,7 +194,7 @@ describe( 'acquireStoreLock', () => { } ); it( 'Enqueues a lock request and attempts to fulfill it', async () => { - const fulfillment = acquireStoreLock( store, path, { + const fulfillment = __unstableAcquireStoreLock( store, path, { exclusive, } ); @@ -236,7 +236,7 @@ describe( 'acquireStoreLock', () => { } ); it( 'Enqueues a lock request and waits until fultillment it when not available', async () => { - const fulfillment = acquireStoreLock( store, path, { + const fulfillment = __unstableAcquireStoreLock( store, path, { exclusive, } ); @@ -274,11 +274,11 @@ describe( 'acquireStoreLock', () => { } ); } ); -describe( 'releaseStoreLock', () => { +describe( '__unstableReleaseStoreLock', () => { const lock = { store, path, exclusive: true }; it( 'Releases a lock request and attempts to fulfill pending lock requests', async () => { - const fulfillment = releaseStoreLock( lock ); + const fulfillment = __unstableReleaseStoreLock( lock ); // Start expect( fulfillment.next().value ).toMatchObject( { diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js index 56d095f8b2749d..42f3dd90cf30f2 100644 --- a/packages/core-data/src/locks/test/selectors.js +++ b/packages/core-data/src/locks/test/selectors.js @@ -6,10 +6,10 @@ import deepFreeze from 'deep-freeze'; /** * Internal dependencies */ -import { getPendingLockRequests, isLockAvailable } from '../selectors'; +import { __unstableGetPendingLockRequests, __unstableIsLockAvailable } from '../selectors'; import { deepCopyLocksTreePath, getNode } from '../utils'; -describe( 'getPendingLockRequests', () => { +describe( '__unstableGetPendingLockRequests', () => { it( 'returns pending lock requests', () => { const state = deepFreeze( { locks: { @@ -17,11 +17,11 @@ describe( 'getPendingLockRequests', () => { }, } ); - expect( getPendingLockRequests( state ) ).toEqual( [ 1, 2, 3 ] ); + expect( __unstableGetPendingLockRequests( state ) ).toEqual( [ 1, 2, 3 ] ); } ); } ); -describe( 'isLockAvailable', () => { +describe( '__unstableIsLockAvailable', () => { describe( 'smoke tests', () => { it( 'returns true if lock is available', () => { const state = deepFreeze( { @@ -34,7 +34,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( state, 'core', [], { exclusive: true } ) + __unstableIsLockAvailable( state, 'core', [], { exclusive: true } ) ).toBe( true ); } ); it( 'returns false if lock is not available', () => { @@ -48,7 +48,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( state, 'core', [], { exclusive: true } ) + __unstableIsLockAvailable( state, 'core', [], { exclusive: true } ) ).toBe( false ); } ); } ); @@ -64,7 +64,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns true if no parent or descendant has any locks`, () => { expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -78,7 +78,7 @@ describe( 'isLockAvailable', () => { exclusive: true, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -92,7 +92,7 @@ describe( 'isLockAvailable', () => { exclusive: true, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -147,7 +147,7 @@ describe( 'isLockAvailable', () => { }, }; expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( subState ), 'core', [ 'postType', 'wp_template_part', 17 ], @@ -208,7 +208,7 @@ describe( 'isLockAvailable', () => { }, }; expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( subState ), 'core', [ 'entities', 'data', 'postType', 'book', 67 ], @@ -220,7 +220,7 @@ describe( 'isLockAvailable', () => { [ true, false ].forEach( ( exclusive ) => { it( `returns true if the path is not accessible and no parent holds a lock`, () => { expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'fake', 'path' ], @@ -234,7 +234,7 @@ describe( 'isLockAvailable', () => { exclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'fake', 'path' ], @@ -248,7 +248,7 @@ describe( 'isLockAvailable', () => { exclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -262,7 +262,7 @@ describe( 'isLockAvailable', () => { exclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -276,7 +276,7 @@ describe( 'isLockAvailable', () => { exclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -295,7 +295,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -314,7 +314,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -334,7 +334,7 @@ describe( 'isLockAvailable', () => { } ); it( `returns true if no parent or descendant has any locks`, () => { expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -350,7 +350,7 @@ describe( 'isLockAvailable', () => { exclusive: isOtherLockExclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'fake', 'path' ], @@ -364,7 +364,7 @@ describe( 'isLockAvailable', () => { exclusive: isOtherLockExclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -378,7 +378,7 @@ describe( 'isLockAvailable', () => { exclusive: isOtherLockExclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -392,7 +392,7 @@ describe( 'isLockAvailable', () => { exclusive: isOtherLockExclusive, } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -411,7 +411,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], @@ -430,7 +430,7 @@ describe( 'isLockAvailable', () => { } ); expect( - isLockAvailable( + __unstableIsLockAvailable( deepFreeze( state ), 'core', [ 'entities', 'root' ], diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index a58161c14b6629..0d7e1f59bed217 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -26,7 +26,7 @@ import { } from './actions'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; import { ifNotResolved, getNormalizedCommaSeparable } from './utils'; -import { acquireStoreLock, releaseStoreLock } from './locks'; +import { __unstableAcquireStoreLock, __unstableReleaseStoreLock } from './locks'; /** * Requests authors from the REST API. @@ -62,7 +62,7 @@ export function* getEntityRecord( kind, name, key = '', query ) { return; } - const lock = yield* acquireStoreLock( + const lock = yield* __unstableAcquireStoreLock( 'core', [ 'entities', 'data', kind, name, key ], { exclusive: false } @@ -114,7 +114,7 @@ export function* getEntityRecord( kind, name, key = '', query ) { const record = yield apiFetch( { path } ); yield receiveEntityRecords( kind, name, record, query ); } finally { - yield* releaseStoreLock( lock ); + yield* __unstableReleaseStoreLock( lock ); } } @@ -148,7 +148,7 @@ export function* getEntityRecords( kind, name, query = {} ) { return; } - const lock = yield* acquireStoreLock( + const lock = yield* __unstableAcquireStoreLock( 'core', [ 'entities', 'data', kind, name ], { exclusive: false } @@ -209,7 +209,7 @@ export function* getEntityRecords( kind, name, query = {} ) { } } } finally { - yield* releaseStoreLock( lock ); + yield* __unstableReleaseStoreLock( lock ); } } diff --git a/packages/core-data/src/test/actions.js b/packages/core-data/src/test/actions.js index 42fba5f4d674a8..4dbad511f4503f 100644 --- a/packages/core-data/src/test/actions.js +++ b/packages/core-data/src/test/actions.js @@ -17,12 +17,12 @@ import { } from '../actions'; jest.mock( '../locks/actions', () => ( { - acquireStoreLock: jest.fn( () => [ + __unstableAcquireStoreLock: jest.fn( () => [ { type: 'MOCKED_ACQUIRE_LOCK', }, ] ), - releaseStoreLock: jest.fn( () => [ + __unstableReleaseStoreLock: jest.fn( () => [ { type: 'MOCKED_RELEASE_LOCK', }, diff --git a/packages/core-data/src/test/resolvers.js b/packages/core-data/src/test/resolvers.js index 3137a7237a4114..cf3a29bd072d79 100644 --- a/packages/core-data/src/test/resolvers.js +++ b/packages/core-data/src/test/resolvers.js @@ -23,12 +23,12 @@ import { } from '../actions'; jest.mock( '../locks/actions', () => ( { - acquireStoreLock: jest.fn( () => [ + __unstableAcquireStoreLock: jest.fn( () => [ { type: 'MOCKED_ACQUIRE_LOCK', }, ] ), - releaseStoreLock: jest.fn( () => [ + __unstableReleaseStoreLock: jest.fn( () => [ { type: 'MOCKED_RELEASE_LOCK', }, From 5758cf5fc0155f41e41bd4694e0f6c7e04cc78f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zieli=C5=84ski?= Date: Mon, 9 Nov 2020 16:58:04 +0100 Subject: [PATCH 17/17] lint --- packages/core-data/src/actions.js | 5 ++++- packages/core-data/src/locks/actions.js | 4 +++- .../core-data/src/locks/test/selectors.js | 19 +++++++++++++++---- packages/core-data/src/resolvers.js | 5 ++++- 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index 3b189dae3e6fca..31163cae4dcbf4 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -16,7 +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'; +import { + __unstableAcquireStoreLock, + __unstableReleaseStoreLock, +} from './locks'; /** * Returns an action object used in signalling that authors have been received. diff --git a/packages/core-data/src/locks/actions.js b/packages/core-data/src/locks/actions.js index f25ac3a4ed61b5..2af5f4f8463b1b 100644 --- a/packages/core-data/src/locks/actions.js +++ b/packages/core-data/src/locks/actions.js @@ -5,7 +5,9 @@ import { awaitPromise } from '@wordpress/data-controls'; import { controls } from '@wordpress/data'; export function* __unstableAcquireStoreLock( store, path, { exclusive } ) { - const promise = yield* __unstableEnqueueLockRequest( store, path, { exclusive } ); + const promise = yield* __unstableEnqueueLockRequest( store, path, { + exclusive, + } ); yield* __unstableProcessPendingLockRequests(); return yield awaitPromise( promise ); } diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js index 42f3dd90cf30f2..38d2da80a8ca43 100644 --- a/packages/core-data/src/locks/test/selectors.js +++ b/packages/core-data/src/locks/test/selectors.js @@ -6,7 +6,10 @@ import deepFreeze from 'deep-freeze'; /** * Internal dependencies */ -import { __unstableGetPendingLockRequests, __unstableIsLockAvailable } from '../selectors'; +import { + __unstableGetPendingLockRequests, + __unstableIsLockAvailable, +} from '../selectors'; import { deepCopyLocksTreePath, getNode } from '../utils'; describe( '__unstableGetPendingLockRequests', () => { @@ -17,7 +20,11 @@ describe( '__unstableGetPendingLockRequests', () => { }, } ); - expect( __unstableGetPendingLockRequests( state ) ).toEqual( [ 1, 2, 3 ] ); + expect( __unstableGetPendingLockRequests( state ) ).toEqual( [ + 1, + 2, + 3, + ] ); } ); } ); @@ -34,7 +41,9 @@ describe( '__unstableIsLockAvailable', () => { } ); expect( - __unstableIsLockAvailable( state, 'core', [], { exclusive: true } ) + __unstableIsLockAvailable( state, 'core', [], { + exclusive: true, + } ) ).toBe( true ); } ); it( 'returns false if lock is not available', () => { @@ -48,7 +57,9 @@ describe( '__unstableIsLockAvailable', () => { } ); expect( - __unstableIsLockAvailable( state, 'core', [], { exclusive: true } ) + __unstableIsLockAvailable( state, 'core', [], { + exclusive: true, + } ) ).toBe( false ); } ); } ); diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 0d7e1f59bed217..20da8cd3e4cf6b 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -26,7 +26,10 @@ import { } from './actions'; import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities'; import { ifNotResolved, getNormalizedCommaSeparable } from './utils'; -import { __unstableAcquireStoreLock, __unstableReleaseStoreLock } from './locks'; +import { + __unstableAcquireStoreLock, + __unstableReleaseStoreLock, +} from './locks'; /** * Requests authors from the REST API.