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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/store-graph/src/Graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
Expand Down
43 changes: 32 additions & 11 deletions packages/store-graph/src/Graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(id: NodeIdentifier, updater: (node: VettedNode | undefined) => Node<T>): void;
}
Expand Down Expand Up @@ -452,6 +456,30 @@ class Graph {
setDraft(child);
};

// Runs the updater inside the lock, returns `undefined` if the updater made no edit.
const runUpdater = <T>(
updater: (node: VettedNode | undefined) => Node<T>,
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({
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions packages/store-graph/src/OPINIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down