diff --git a/packages/store-graph/src/Graph.test.ts b/packages/store-graph/src/Graph.test.ts index cb246c5343..8269422aa3 100644 --- a/packages/store-graph/src/Graph.test.ts +++ b/packages/store-graph/src/Graph.test.ts @@ -150,6 +150,51 @@ scenario( .and('should keep the original node', ({ graph }) => expect(graph.getSnapshot().get('_:m-1')).toHaveProperty('text', ['Hello']) ); + + bdd + .given('a graph with a node and a listener', () => { + const { controller, graph } = createGraphWithNodes(); + const affectedNodeIdsList: string[][] = []; + + graph.subscribe(affectedNodeIds => affectedNodeIdsList.push(Array.from(affectedNodeIds))); + + return { affectedNodeIdsList, controller, graph }; + }) + .when('the updater returns the same instance of the node', ({ controller, graph }) => { + const snapshot = graph.getSnapshot(); + + controller.edit(transaction => transaction.upsert('_:m-1', node => node!)); + + return snapshot; + }) + .then('should not modify any nodes', ({ graph }, snapshot) => + expect(getChangedNodeIds(snapshot, graph.getSnapshot())).toEqual([]) + ) + .and('should keep the same snapshot', ({ graph }, snapshot) => expect(graph.getSnapshot()).toBe(snapshot)) + .and('should not notify listeners', ({ affectedNodeIdsList }) => expect(affectedNodeIdsList).toEqual([])); + + bdd + .given('a graph with a node', () => createGraphWithNodes()) + .when('the updater returns the same instance of the node, then the parent drops it', ({ controller }) => + controller.edit(transaction => { + transaction.upsert('_:m-1', node => node!); + transaction.upsert('_:conversation', node => ({ ...node!, hasPart: new Set([{ '@id': '_:m-2' }]) })); + }) + ) + .then('should auto-fix isPartOf of the untouched node', ({ graph }) => + expect(graph.getSnapshot().get('_:m-1')).not.toHaveProperty('isPartOf') + ); + + bdd + .given('an empty graph', () => createGraph()) + .when('the updater returns undefined on insert', ({ controller }) => + catchError(() => + // `node!` makes TypeScript happy, at runtime, the updater returns `undefined`. + controller.edit(transaction => transaction.upsert('_:m-1', node => node!)) + ) + ) + .then('should throw', (_, error) => expect(error).toEqual(expect.any(Error))) + .and('should not add the node', ({ graph }) => expect(graph.getSnapshot().has('_:m-1')).toBe(false)); }, NodeTest ); diff --git a/packages/store-graph/src/Graph.ts b/packages/store-graph/src/Graph.ts index 65fb3e4e41..ff1b073792 100644 --- a/packages/store-graph/src/Graph.ts +++ b/packages/store-graph/src/Graph.ts @@ -82,6 +82,10 @@ interface GraphTransaction { * The updater must be a pure function of the node it receives. Transaction methods (i.e. `upsert()` and `delete()`) * cannot be called inside the updater, they will throw without making any changes. Reading the graph (e.g. * `getSnapshot()`) inside the updater is allowed. + * + * If the node exists and has not been changed in this transaction, returning the same instance of the node received + * (i.e. `node => node`) means no edit. If the node does not exist, the updater must return a node, returning + * `undefined` will throw. */ upsert(id: NodeIdentifier, updater: (node: VettedNode | undefined) => Node): void; } @@ -452,6 +456,30 @@ class Graph { setDraft(child); }; + // Runs the updater inside the lock, returns `undefined` if the updater made no edit. + const runUpdater = ( + updater: (node: VettedNode | undefined) => Node, + node: VettedNode | undefined, + isCleanRead: boolean + ): DraftNode | undefined => { + updating = true; + + try { + const nextNode: unknown = updater(node); + + // OPINION: Returning the same instance of a clean read means no edit, the node is frozen and unchanged. + // A dirty read is writable and could be modified in place, it is always treated as an edit. + // When inserting, there is no node to return, returning `undefined` will throw. + // Reading the returned node could call userland code (e.g. getters), it must be read inside the lock. + return isCleanRead && node && nextNode === node ? undefined : createDraftNode(nextNode); + } finally { + updating = false; + + // OPINION: The node is writable only inside the updater, it is locked after the updater returns or throws. + node && Object.freeze(node); + } + }; + try { const result: unknown = transactor( Object.freeze({ @@ -533,18 +561,11 @@ class Graph { const node: VettedNode | undefined = draftToRead?.read(shownChildIds, safePendingParentIds) ?? nextState.get(safeId); - let safeNode: DraftNode; - - updating = true; - - try { - // Reading the returned node could call userland code (e.g. getters), it must be read inside the lock. - safeNode = createDraftNode(updater(node)); - } finally { - updating = false; + const safeNode = runUpdater(updater, node, !draftToRead); - // OPINION: The node is writable only inside the updater, it is locked after the updater returns or throws. - node && Object.freeze(node); + // A clean read has no pending links, nothing to confirm. + if (!safeNode) { + return; } if (safeNode['@id'] !== safeId) { diff --git a/packages/store-graph/src/OPINIONS.md b/packages/store-graph/src/OPINIONS.md index af7f5f53ca..d10fbdbc84 100644 --- a/packages/store-graph/src/OPINIONS.md +++ b/packages/store-graph/src/OPINIONS.md @@ -24,6 +24,9 @@ The new design is distributed, transactional (consistent without locking), and h - Schema.org is huge spec, we prefer "assume validated by writer" and "assume reader will validate and drop invalid" - Synchronous transactional edit and one session at a time - Updaters must be pure functions of the node they receive, calling transaction methods (`upsert()`/`delete()`) inside them is not allowed (for now) +- Updater returning the same instance of the node it received (i.e. `node => node`) is no edit, if the node was not changed in the same transaction + - When inserting, the updater receives `undefined` and must return a node, returning `undefined` will throw + - Node changed in the same transaction is writable and could be modified in place, returning the same instance is still an edit - Always plural: singular value is stored in single-item array - `hasPart` and `isPartOf` must be always inverse of other, validate on commit, offer helper to fix them - Every node must have a single and unique `@id`, no multiple `@id`