Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Atomic node updates

Hakan Shehu432b0a4c5883
diff --git a/desktop/src/lib/editor.ts b/desktop/src/lib/editor.ts
index 8747f405..dc07e20f 100644
--- a/desktop/src/lib/editor.ts
+++ b/desktop/src/lib/editor.ts
@@ -202,8 +202,10 @@ const getIdFromContent = (content: JSONContent): string => {
return content.attrs?.id ?? generateId(getIdTypeFromNode(content.type));
};
-export const applyChangeToYDoc = (doc: Y.Doc, blocks: NodeBlock[]) => {
- const attributesMap = doc.getMap('attributes');
+export const applyChangeToAttributesMap = (
+ attributesMap: Y.Map<any>,
+ blocks: NodeBlock[],
+) => {
if (!attributesMap.has('content')) {
attributesMap.set('content', new Y.Map());
}
diff --git a/desktop/src/main/handlers/mutations/document-save.ts b/desktop/src/main/handlers/mutations/document-save.ts
index 69cb5d95..9cfacdc7 100644
--- a/desktop/src/main/handlers/mutations/document-save.ts
+++ b/desktop/src/main/handlers/mutations/document-save.ts
@@ -1,13 +1,8 @@
-import * as Y from 'yjs';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import { databaseManager } from '@/main/data/database-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { DocumentSaveMutationInput } from '@/operations/mutations/document-save';
-import { generateId, IdType } from '@/lib/id';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
-import { applyChangeToYDoc, mapContentsToBlocks } from '@/lib/editor';
-import { LocalNodeAttributes, NodeBlock } from '@/types/nodes';
-import { hasUpdateChanges } from '@/main/utils';
+import { applyChangeToAttributesMap, mapContentsToBlocks } from '@/lib/editor';
+import { NodeBlock } from '@/types/nodes';
+import { updateNodeAtomically } from '@/main/utils';
export class DocumentSaveMutationHandler
implements MutationHandler<DocumentSaveMutationInput>
@@ -15,136 +10,51 @@ export class DocumentSaveMutationHandler
async handleMutation(
input: DocumentSaveMutationInput,
): Promise<MutationResult<DocumentSaveMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
- );
-
- let count = 0;
- while (count++ < 10) {
- const document = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', input.documentId)
- .executeTakeFirst();
-
- if (!document) {
- return {
- output: {
- success: false,
- },
- changes: [],
- };
- }
-
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: document.id,
- });
- Y.applyUpdate(doc, toUint8Array(document.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributes = JSON.parse(document.attributes) as LocalNodeAttributes;
- const blocksMap = new Map<string, NodeBlock>();
- if (attributes.content) {
- for (const [key, value] of Object.entries(attributes.content)) {
- blocksMap.set(key, value);
+ input.documentId,
+ (attributesMap, attributes) => {
+ const blocksMap = new Map<string, NodeBlock>();
+ if (attributes.content) {
+ for (const [key, value] of Object.entries(attributes.content)) {
+ blocksMap.set(key, value);
+ }
}
- }
-
- const blocks = mapContentsToBlocks(
- document.id,
- input.content.content,
- blocksMap,
- );
- doc.transact(() => {
- applyChangeToYDoc(doc, blocks);
- });
+ const blocks = mapContentsToBlocks(
+ input.documentId,
+ input.content.content,
+ blocksMap,
+ );
- if (updates.length === 0) {
- return {
- output: {
- success: true,
- },
- changes: [],
- };
- }
-
- const attributesMap = doc.getMap('attributes');
- const attributesJson = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+ applyChangeToAttributesMap(attributesMap, blocks);
+ },
+ );
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: document.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
};
-
- const result = await workspaceDatabase
- .transaction()
- .execute(async (trx) => {
- const result = await trx
- .updateTable('nodes')
- .set({
- attributes: attributesJson,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.documentId)
- .where('version_id', '=', document.version_id)
- .execute();
-
- const hasChanges = hasUpdateChanges(result);
-
- if (hasChanges) {
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- }
-
- return hasChanges;
- });
-
- if (result) {
- return {
- output: {
- success: true,
- },
- changes: [
- {
- type: 'workspace',
- table: 'nodes',
- userId: input.userId,
- },
- {
- type: 'workspace',
- table: 'changes',
- userId: input.userId,
- },
- ],
- };
- }
}
return {
output: {
- success: false,
+ success: true,
},
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ {
+ type: 'workspace',
+ table: 'changes',
+ userId: input.userId,
+ },
+ ],
};
}
}
diff --git a/desktop/src/main/handlers/mutations/message-create.ts b/desktop/src/main/handlers/mutations/message-create.ts
index 136f758f..f8916a6a 100644
--- a/desktop/src/main/handlers/mutations/message-create.ts
+++ b/desktop/src/main/handlers/mutations/message-create.ts
@@ -6,7 +6,7 @@ import { MutationHandler, MutationResult } from '@/operations/mutations';
import { MessageCreateMutationInput } from '@/operations/mutations/message-create';
import { fromUint8Array } from 'js-base64';
import { LocalCreateNodeChangeData } from '@/types/sync';
-import { applyChangeToYDoc, mapContentsToBlocks } from '@/lib/editor';
+import { applyChangeToAttributesMap, mapContentsToBlocks } from '@/lib/editor';
export class MessageCreateMutationHandler
implements MutationHandler<MessageCreateMutationInput>
@@ -32,7 +32,7 @@ export class MessageCreateMutationHandler
doc.transact(() => {
attributesMap.set('type', NodeTypes.Message);
attributesMap.set('parentId', input.conversationId);
- applyChangeToYDoc(doc, blocks);
+ applyChangeToAttributesMap(attributesMap, blocks);
});
const attributes = JSON.stringify(attributesMap.toJSON());
diff --git a/desktop/src/main/handlers/mutations/node-attribute-delete.ts b/desktop/src/main/handlers/mutations/node-attribute-delete.ts
index 65702245..0387e2c4 100644
--- a/desktop/src/main/handlers/mutations/node-attribute-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-attribute-delete.ts
@@ -1,10 +1,6 @@
-import { databaseManager } from '@/main/data/database-manager';
-import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeAttributeDeleteMutationInput } from '@/operations/mutations/node-attribute-delete';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import * as Y from 'yjs';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class NodeAttributeDeleteMutationHandler
implements MutationHandler<NodeAttributeDeleteMutationInput>
@@ -12,77 +8,26 @@ export class NodeAttributeDeleteMutationHandler
async handleMutation(
input: NodeAttributeDeleteMutationInput,
): Promise<MutationResult<NodeAttributeDeleteMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
- );
-
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
- }
+ input.nodeId,
+ (attributesMap) => {
+ if (!attributesMap.has(input.attribute)) {
+ return;
+ }
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
+ attributesMap.delete(input.attribute);
+ },
+ );
- const attributesMap = doc.getMap('attributes');
- if (!attributesMap.has(input.attribute)) {
+ if (!result) {
return {
output: {
- success: true,
+ success: false,
},
};
}
- attributesMap.delete(input.attribute);
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-attribute-set.ts b/desktop/src/main/handlers/mutations/node-attribute-set.ts
index 4ebf1da8..58830c04 100644
--- a/desktop/src/main/handlers/mutations/node-attribute-set.ts
+++ b/desktop/src/main/handlers/mutations/node-attribute-set.ts
@@ -1,10 +1,6 @@
-import { databaseManager } from '@/main/data/database-manager';
-import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeAttributeSetMutationInput } from '@/operations/mutations/node-attribute-set';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import * as Y from 'yjs';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class NodeAttributeSetMutationHandler
implements MutationHandler<NodeAttributeSetMutationInput>
@@ -12,71 +8,22 @@ export class NodeAttributeSetMutationHandler
async handleMutation(
input: NodeAttributeSetMutationInput,
): Promise<MutationResult<NodeAttributeSetMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ attributesMap.set(input.attribute, input.value);
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
-
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
- attributesMap.set(input.attribute, input.value);
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-create.ts b/desktop/src/main/handlers/mutations/node-collaborator-create.ts
index 1220f2a5..3a55f8e4 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-create.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-create.ts
@@ -1,10 +1,7 @@
-import { databaseManager } from '@/main/data/database-manager';
-import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorCreateMutationInput } from '@/operations/mutations/node-collaborator-create';
import * as Y from 'yjs';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class NodeCollaboratorCreateMutationHandler
implements MutationHandler<NodeCollaboratorCreateMutationInput>
@@ -12,80 +9,31 @@ export class NodeCollaboratorCreateMutationHandler
async handleMutation(
input: NodeCollaboratorCreateMutationInput,
): Promise<MutationResult<NodeCollaboratorCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ if (!attributesMap.has('collaborators')) {
+ attributesMap.set('collaborators', new Y.Map());
+ }
+
+ const collaboratorsMap = attributesMap.get(
+ 'collaborators',
+ ) as Y.Map<any>;
+ input.collaboratorIds.forEach((collaboratorId) => {
+ collaboratorsMap.set(collaboratorId, input.role);
+ });
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- if (!attributesMap.has('collaborators')) {
- attributesMap.set('collaborators', new Y.Map());
- }
-
- const collaboratorsMap = attributesMap.get('collaborators') as Y.Map<any>;
- input.collaboratorIds.forEach((collaboratorId) => {
- collaboratorsMap.set(collaboratorId, input.role);
- });
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-delete.ts b/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
index eda1043d..6235e7b0 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
@@ -1,9 +1,6 @@
-import { generateId, IdType } from '@/lib/id';
-import { databaseManager } from '@/main/data/database-manager';
+import { updateNodeAtomically } from '@/main/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorDeleteMutationInput } from '@/operations/mutations/node-collaborator-delete';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
-import { fromUint8Array, toUint8Array } from 'js-base64';
import * as Y from 'yjs';
export class NodeCollaboratorDeleteMutationHandler
@@ -12,74 +9,25 @@ export class NodeCollaboratorDeleteMutationHandler
async handleMutation(
input: NodeCollaboratorDeleteMutationInput,
): Promise<MutationResult<NodeCollaboratorDeleteMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ const collaboratorsMap = attributesMap.get(
+ 'collaborators',
+ ) as Y.Map<any>;
+ collaboratorsMap.delete(input.collaboratorId);
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- const collaboratorsMap = attributesMap.get('collaborators') as Y.Map<any>;
- collaboratorsMap.delete(input.collaboratorId);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-update.ts b/desktop/src/main/handlers/mutations/node-collaborator-update.ts
index 657da82c..c839a935 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-update.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-update.ts
@@ -1,10 +1,7 @@
-import { databaseManager } from '@/main/data/database-manager';
-import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorUpdateMutationInput } from '@/operations/mutations/node-collaborator-update';
import * as Y from 'yjs';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class NodeCollaboratorUpdateMutationHandler
implements MutationHandler<NodeCollaboratorUpdateMutationInput>
@@ -12,78 +9,29 @@ export class NodeCollaboratorUpdateMutationHandler
async handleMutation(
input: NodeCollaboratorUpdateMutationInput,
): Promise<MutationResult<NodeCollaboratorUpdateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ if (!attributesMap.has('collaborators')) {
+ attributesMap.set('collaborators', new Y.Map());
+ }
+
+ const collaboratorsMap = attributesMap.get(
+ 'collaborators',
+ ) as Y.Map<any>;
+ collaboratorsMap.set(input.collaboratorId, input.role);
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- if (!attributesMap.has('collaborators')) {
- attributesMap.set('collaborators', new Y.Map());
- }
-
- const collaboratorsMap = attributesMap.get('collaborators') as Y.Map<any>;
- collaboratorsMap.set(input.collaboratorId, input.role);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-reaction-create.ts b/desktop/src/main/handlers/mutations/node-reaction-create.ts
index c1c03cf4..c1ade04b 100644
--- a/desktop/src/main/handlers/mutations/node-reaction-create.ts
+++ b/desktop/src/main/handlers/mutations/node-reaction-create.ts
@@ -1,9 +1,6 @@
-import { generateId, IdType } from '@/lib/id';
-import { databaseManager } from '@/main/data/database-manager';
+import { updateNodeAtomically } from '@/main/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeReactionCreateMutationInput } from '@/operations/mutations/node-reaction-create';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
-import { fromUint8Array, toUint8Array } from 'js-base64';
import * as Y from 'yjs';
export class NodeReactionCreateMutationHandler
@@ -12,91 +9,38 @@ export class NodeReactionCreateMutationHandler
async handleMutation(
input: NodeReactionCreateMutationInput,
): Promise<MutationResult<NodeReactionCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ if (!attributesMap.has('reactions')) {
+ attributesMap.set('reactions', new Y.Map());
+ }
+
+ const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
+ if (!reactionsMap.has(input.reaction)) {
+ reactionsMap.set(input.reaction, new Y.Array());
+ }
+
+ const reactionArray = reactionsMap.get(
+ input.reaction,
+ ) as Y.Array<string>;
+ if (reactionArray.toArray().includes(input.userId)) {
+ return;
+ }
+
+ reactionArray.push([input.userId]);
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
- }
-
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- if (!attributesMap.has('reactions')) {
- attributesMap.set('reactions', new Y.Map());
- }
-
- const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
- if (!reactionsMap.has(input.reaction)) {
- reactionsMap.set(input.reaction, new Y.Array());
- }
-
- const reactionArray = reactionsMap.get(input.reaction) as Y.Array<string>;
- if (reactionArray.toArray().includes(input.userId)) {
- return;
- }
-
- reactionArray.push([input.userId]);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- if (encodedState === node.state) {
- return;
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/node-reaction-delete.ts b/desktop/src/main/handlers/mutations/node-reaction-delete.ts
index f56e8cef..ce9a380e 100644
--- a/desktop/src/main/handlers/mutations/node-reaction-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-reaction-delete.ts
@@ -1,10 +1,7 @@
-import { databaseManager } from '@/main/data/database-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeReactionDeleteMutationInput } from '@/operations/mutations/node-reaction-delete';
import * as Y from 'yjs';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import { generateId, IdType } from '@/lib/id';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class NodeReactionDeleteMutationHandler
implements MutationHandler<NodeReactionDeleteMutationInput>
@@ -12,93 +9,40 @@ export class NodeReactionDeleteMutationHandler
async handleMutation(
input: NodeReactionDeleteMutationInput,
): Promise<MutationResult<NodeReactionDeleteMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.nodeId,
+ (attributesMap) => {
+ if (!attributesMap.has('reactions')) {
+ attributesMap.set('reactions', new Y.Map());
+ }
+
+ const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
+ if (!reactionsMap.has(input.reaction)) {
+ reactionsMap.set(input.reaction, new Y.Array());
+ }
+
+ const reactionArray = reactionsMap.get(
+ input.reaction,
+ ) as Y.Array<string>;
+
+ const index = reactionArray.toArray().indexOf(input.userId);
+ if (index === -1) {
+ return;
+ }
+
+ reactionArray.delete(index);
+ },
);
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
- }
-
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: node.id,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- if (!attributesMap.has('reactions')) {
- attributesMap.set('reactions', new Y.Map());
- }
-
- const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
- if (!reactionsMap.has(input.reaction)) {
- reactionsMap.set(input.reaction, new Y.Array());
- }
-
- const reactionArray = reactionsMap.get(input.reaction) as Y.Array<string>;
-
- const index = reactionArray.toArray().indexOf(input.userId);
- if (index === -1) {
- return;
- }
-
- reactionArray.delete(index);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- if (encodedState === node.state) {
- return;
+ if (!result) {
+ return {
+ output: {
+ success: false,
+ },
+ };
}
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: node.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.nodeId)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/server-node-sync.ts b/desktop/src/main/handlers/mutations/server-node-sync.ts
index d3307009..48046478 100644
--- a/desktop/src/main/handlers/mutations/server-node-sync.ts
+++ b/desktop/src/main/handlers/mutations/server-node-sync.ts
@@ -1,10 +1,7 @@
import { databaseManager } from '@/main/data/database-manager';
import { socketManager } from '@/main/sockets/socket-manager';
-import {
- MutationChange,
- MutationHandler,
- MutationResult,
-} from '@/operations/mutations';
+import { hasInsertChanges, hasUpdateChanges } from '@/main/utils';
+import { MutationHandler, MutationResult } from '@/operations/mutations';
import { ServerNodeSyncMutationInput } from '@/operations/mutations/server-node-sync';
import { toUint8Array } from 'js-base64';
import * as Y from 'yjs';
@@ -15,8 +12,6 @@ export class ServerNodeSyncMutationHandler
public async handleMutation(
input: ServerNodeSyncMutationInput,
): Promise<MutationResult<ServerNodeSyncMutationInput>> {
- const changes: MutationChange[] = [];
-
const workspace = await databaseManager.appDatabase
.selectFrom('workspaces')
.selectAll()
@@ -28,6 +23,10 @@ export class ServerNodeSyncMutationHandler
)
.executeTakeFirst();
+ const userId = workspace.user_id;
+ const workspaceDatabase =
+ await databaseManager.getWorkspaceDatabase(userId);
+
if (!workspace) {
return {
output: {
@@ -36,93 +35,117 @@ export class ServerNodeSyncMutationHandler
};
}
- const userId = workspace.user_id;
- const workspaceDatabase =
- await databaseManager.getWorkspaceDatabase(userId);
+ let count = 0;
+ while (count++ < 10) {
+ const existingNode = await workspaceDatabase
+ .selectFrom('nodes')
+ .where('id', '=', input.id)
+ .selectAll()
+ .executeTakeFirst();
- const existingNode = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.id)
- .selectAll()
- .executeTakeFirst();
+ if (!existingNode) {
+ const doc = new Y.Doc({
+ guid: input.id,
+ });
- if (!existingNode) {
- const doc = new Y.Doc({
- guid: input.id,
- });
-
- Y.applyUpdate(doc, toUint8Array(input.state));
-
- const attributesMap = doc.getMap('attributes');
- const attributes = JSON.stringify(attributesMap.toJSON());
-
- await workspaceDatabase
- .insertInto('nodes')
- .values({
- id: input.id,
- attributes: attributes,
- state: input.state,
- created_at: input.createdAt,
- created_by: input.createdBy,
- version_id: input.versionId,
- server_created_at: input.serverCreatedAt,
- server_version_id: input.versionId,
- })
- .onConflict((cb) =>
- cb
- .doUpdateSet({
- server_created_at: input.serverCreatedAt,
- server_updated_at: input.serverUpdatedAt,
- server_version_id: input.versionId,
- })
- .where('version_id', '=', input.versionId),
- )
- .execute();
- } else {
- const doc = new Y.Doc({
- guid: input.id,
- });
-
- Y.applyUpdate(doc, toUint8Array(existingNode.state));
- Y.applyUpdate(doc, toUint8Array(input.state));
-
- const attributesMap = doc.getMap('attributes');
- const attributes = JSON.stringify(attributesMap.toJSON());
-
- await workspaceDatabase
- .updateTable('nodes')
- .set({
- state: input.state,
- attributes: attributes,
- server_created_at: input.serverCreatedAt,
- server_updated_at: input.serverUpdatedAt,
- server_version_id: input.versionId,
- updated_at: input.updatedAt,
- updated_by: input.updatedBy,
- version_id: input.versionId,
- })
- .where('id', '=', input.id)
- .execute();
- }
+ Y.applyUpdate(doc, toUint8Array(input.state));
+
+ const attributesMap = doc.getMap('attributes');
+ const attributes = JSON.stringify(attributesMap.toJSON());
+
+ const result = await workspaceDatabase
+ .insertInto('nodes')
+ .values({
+ id: input.id,
+ attributes: attributes,
+ state: input.state,
+ created_at: input.createdAt,
+ created_by: input.createdBy,
+ version_id: input.versionId,
+ server_created_at: input.serverCreatedAt,
+ server_version_id: input.versionId,
+ })
+ .onConflict((cb) => cb.doNothing())
+ .execute();
+
+ const isInserted = hasInsertChanges(result);
+ if (isInserted) {
+ socketManager.sendMessage(workspace.account_id, {
+ type: 'local_node_sync',
+ nodeId: input.id,
+ versionId: input.versionId,
+ workspaceId: input.workspaceId,
+ });
- changes.push({
- type: 'workspace',
- table: 'nodes',
- userId: userId,
- });
+ return {
+ output: {
+ success: true,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: userId,
+ },
+ ],
+ };
+ }
+ } else {
+ const doc = new Y.Doc({
+ guid: input.id,
+ });
- socketManager.sendMessage(workspace.account_id, {
- type: 'local_node_sync',
- nodeId: input.id,
- versionId: input.versionId,
- workspaceId: input.workspaceId,
- });
+ Y.applyUpdate(doc, toUint8Array(existingNode.state));
+ Y.applyUpdate(doc, toUint8Array(input.state));
+
+ const attributesMap = doc.getMap('attributes');
+ const attributes = JSON.stringify(attributesMap.toJSON());
+
+ const result = await workspaceDatabase
+ .updateTable('nodes')
+ .set({
+ state: input.state,
+ attributes: attributes,
+ server_created_at: input.serverCreatedAt,
+ server_updated_at: input.serverUpdatedAt,
+ server_version_id: input.versionId,
+ updated_at: input.updatedAt,
+ updated_by: input.updatedBy,
+ version_id: input.versionId,
+ })
+ .where('id', '=', input.id)
+ .where('version_id', '=', existingNode.version_id)
+ .execute();
+
+ const isUpdated = hasUpdateChanges(result);
+ if (isUpdated) {
+ socketManager.sendMessage(workspace.account_id, {
+ type: 'local_node_sync',
+ nodeId: input.id,
+ versionId: input.versionId,
+ workspaceId: input.workspaceId,
+ });
+
+ return {
+ output: {
+ success: true,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: userId,
+ },
+ ],
+ };
+ }
+ }
+ }
return {
output: {
- success: true,
+ success: false,
},
- changes: changes,
};
}
}
diff --git a/desktop/src/main/handlers/mutations/space-update.ts b/desktop/src/main/handlers/mutations/space-update.ts
index 4c675882..7901c87e 100644
--- a/desktop/src/main/handlers/mutations/space-update.ts
+++ b/desktop/src/main/handlers/mutations/space-update.ts
@@ -1,11 +1,6 @@
-import { databaseManager } from '@/main/data/database-manager';
-import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { SpaceUpdateMutationInput } from '@/operations/mutations/space-update';
-import * as Y from 'yjs';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import { LocalNodeAttributes } from '@/types/nodes';
-import { LocalUpdateNodeChangeData } from '@/types/sync';
+import { updateNodeAtomically } from '@/main/utils';
export class SpaceUpdateMutationHandler
implements MutationHandler<SpaceUpdateMutationInput>
@@ -13,17 +8,25 @@ export class SpaceUpdateMutationHandler
async handleMutation(
input: SpaceUpdateMutationInput,
): Promise<MutationResult<SpaceUpdateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const result = await updateNodeAtomically(
input.userId,
+ input.id,
+ (attributesMap) => {
+ if (input.name !== attributesMap.get('name')) {
+ attributesMap.set('name', input.name);
+ }
+
+ if (input.description !== attributesMap.get('description')) {
+ attributesMap.set('description', input.description);
+ }
+
+ if (input.avatar !== attributesMap.get('avatar')) {
+ attributesMap.set('avatar', input.avatar);
+ }
+ },
);
- const space = await workspaceDatabase
- .selectFrom('nodes')
- .where('id', '=', input.id)
- .selectAll()
- .executeTakeFirst();
-
- if (!space) {
+ if (!result) {
return {
output: {
success: false,
@@ -31,69 +34,6 @@ export class SpaceUpdateMutationHandler
};
}
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- const doc = new Y.Doc({
- guid: space.id,
- });
- Y.applyUpdate(doc, toUint8Array(space.state));
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const currentAttributes: LocalNodeAttributes = JSON.parse(space.attributes);
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- if (input.name !== currentAttributes.name) {
- attributesMap.set('name', input.name);
- }
-
- if (input.description !== currentAttributes.description) {
- attributesMap.set('description', input.description);
- }
-
- if (input.avatar !== currentAttributes.avatar) {
- attributesMap.set('avatar', input.avatar);
- }
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: space.id,
- updatedAt: updatedAt,
- updatedBy: input.userId,
- versionId: versionId,
- updates: updates,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .updateTable('nodes')
- .set({
- attributes: attributes,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: input.userId,
- version_id: versionId,
- })
- .where('id', '=', input.id)
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- });
-
return {
output: {
success: true,
diff --git a/desktop/src/main/utils.ts b/desktop/src/main/utils.ts
index 9dfc380b..bc8bf5f1 100644
--- a/desktop/src/main/utils.ts
+++ b/desktop/src/main/utils.ts
@@ -1,6 +1,12 @@
import { app } from 'electron';
import { DeleteResult, InsertResult, UpdateResult } from 'kysely';
import path from 'path';
+import * as Y from 'yjs';
+import { databaseManager } from '@/main/data/database-manager';
+import { LocalNodeAttributes } from '@/types/nodes';
+import { generateId, IdType } from '@/lib/id';
+import { fromUint8Array, toUint8Array } from 'js-base64';
+import { LocalUpdateNodeChangeData } from '@/types/sync';
export const appPath = app.getPath('userData');
@@ -39,3 +45,97 @@ export const hasUpdateChanges = (result: UpdateResult[]): boolean => {
export const hasDeleteChanges = (result: DeleteResult[]): boolean => {
return result.some((r) => r.numDeletedRows && r.numDeletedRows > 0n);
};
+
+export const updateNodeAtomically = async (
+ userId: string,
+ nodeId: string,
+ update: (attributesMap: Y.Map<any>, attributes: LocalNodeAttributes) => void,
+) => {
+ const workspaceDatabase = await databaseManager.getWorkspaceDatabase(userId);
+
+ let count = 0;
+ while (count++ < 10) {
+ const node = await workspaceDatabase
+ .selectFrom('nodes')
+ .select(['state', 'attributes', 'version_id'])
+ .where('id', '=', nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const doc = new Y.Doc({
+ guid: nodeId,
+ });
+ Y.applyUpdate(doc, toUint8Array(node.state));
+
+ const versionId = generateId(IdType.Version);
+ const updatedAt = new Date().toISOString();
+ const updates: string[] = [];
+
+ doc.on('update', (update) => {
+ updates.push(fromUint8Array(update));
+ });
+
+ const attributes = JSON.parse(node.attributes) as LocalNodeAttributes;
+ const attributesMap = doc.getMap('attributes');
+
+ doc.transact(() => {
+ update(attributesMap, attributes);
+ });
+
+ if (updates.length === 0) {
+ return true;
+ }
+
+ const attributesJson = JSON.stringify(attributesMap.toJSON());
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ const changeData: LocalUpdateNodeChangeData = {
+ type: 'node_update',
+ id: nodeId,
+ updatedAt: updatedAt,
+ updatedBy: userId,
+ versionId: versionId,
+ updates: updates,
+ };
+
+ const result = await workspaceDatabase
+ .transaction()
+ .execute(async (trx) => {
+ const result = await trx
+ .updateTable('nodes')
+ .set({
+ attributes: attributesJson,
+ state: encodedState,
+ updated_at: updatedAt,
+ updated_by: userId,
+ version_id: versionId,
+ })
+ .where('id', '=', nodeId)
+ .where('version_id', '=', node.version_id)
+ .execute();
+
+ const hasChanges = hasUpdateChanges(result);
+
+ if (hasChanges) {
+ await trx
+ .insertInto('changes')
+ .values({
+ data: JSON.stringify(changeData),
+ created_at: updatedAt,
+ })
+ .execute();
+ }
+
+ return hasChanges;
+ });
+
+ if (result) {
+ return true;
+ }
+ }
+
+ return false;
+};