Skip to content

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

Imrpove sync service to be more real-time

Hakan Shehu54bb91a8668c
diff --git a/apps/desktop/src/main/handlers/mutations/mark-node-as-seen.ts b/apps/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
index eebc160f..415a3801 100644
--- a/apps/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
+++ b/apps/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
@@ -5,6 +5,8 @@ import {
MarkNodeAsSeenMutationInput,
MarkNodeAsSeenMutationOutput,
} from '@/shared/mutations/mark-node-as-seen';
+import { UserNode } from '@/shared/types/nodes';
+import { eventBus } from '@/shared/lib/event-bus';
export class MarkNodeAsSeenMutationHandler
implements MutationHandler<MarkNodeAsSeenMutationInput>
@@ -16,6 +18,9 @@ export class MarkNodeAsSeenMutationHandler
input.userId
);
+ let changeId: number | undefined;
+ let userNode: UserNode | undefined;
+
const changeData: LocalUserNodeChangeData = {
type: 'user_node_update',
nodeId: input.nodeId,
@@ -27,7 +32,7 @@ export class MarkNodeAsSeenMutationHandler
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
+ const updatedUserNode = await trx
.updateTable('user_nodes')
.set({
last_seen_version_id: input.versionId,
@@ -37,18 +42,54 @@ export class MarkNodeAsSeenMutationHandler
})
.where('node_id', '=', input.nodeId)
.where('user_id', '=', input.userId)
- .execute();
+ .returningAll()
+ .executeTakeFirst();
+
+ if (updatedUserNode) {
+ userNode = {
+ userId: updatedUserNode.user_id,
+ nodeId: updatedUserNode.node_id,
+ lastSeenAt: updatedUserNode.last_seen_at,
+ lastSeenVersionId: updatedUserNode.last_seen_version_id,
+ mentionsCount: updatedUserNode.mentions_count,
+ attributes: updatedUserNode.attributes,
+ versionId: updatedUserNode.version_id,
+ createdAt: updatedUserNode.created_at,
+ updatedAt: updatedUserNode.updated_at,
+ };
+ }
- await trx
+ const createdChange = await trx
.insertInto('changes')
.values({
data: JSON.stringify(changeData),
created_at: new Date().toISOString(),
retry_count: 0,
})
- .execute();
+ .returning('id')
+ .executeTakeFirst();
+
+ if (createdChange) {
+ changeId = createdChange.id;
+ }
});
+ if (userNode) {
+ eventBus.publish({
+ type: 'user_node_created',
+ userId: input.userId,
+ userNode,
+ });
+ }
+
+ if (changeId) {
+ eventBus.publish({
+ type: 'change_created',
+ userId: input.userId,
+ changeId,
+ });
+ }
+
return {
success: true,
};
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 3ab2cb65..a19887ef 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -4,7 +4,7 @@ import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import { eventBus } from '@/shared/lib/event-bus';
import { databaseService } from '@/main/data/database-service';
import { socketService } from '@/main/services/socket-service';
-import { synchronizer } from '@/main/synchronizer';
+import { syncService } from '@/main/services/sync-service';
import { avatarService } from '@/main/services/avatar-service';
import { fileService } from '@/main/services/file-service';
import { FileMetadata } from '@/shared/types/files';
@@ -24,7 +24,7 @@ const createWindow = async (): Promise<void> => {
await databaseService.init();
assetService.checkAssets();
socketService.init();
- synchronizer.init();
+ syncService.init();
radarService.init();
// Create the browser window.
diff --git a/apps/desktop/src/main/services/node-service.ts b/apps/desktop/src/main/services/node-service.ts
index ec9a40d5..02888ebe 100644
--- a/apps/desktop/src/main/services/node-service.ts
+++ b/apps/desktop/src/main/services/node-service.ts
@@ -39,6 +39,7 @@ class NodeService {
const createdNodes: Node[] = [];
const createdUploads: Upload[] = [];
const createdDownloads: Download[] = [];
+ const createdChangeIds: number[] = [];
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -104,14 +105,19 @@ class NodeService {
createdNodes.push(createdNode);
}
- await transaction
+ const createdChange = await transaction
.insertInto('changes')
+ .returning('id')
.values({
data: JSON.stringify(changeData),
created_at: createdAt,
retry_count: 0,
})
- .execute();
+ .executeTakeFirst();
+
+ if (createdChange) {
+ createdChangeIds.push(createdChange.id);
+ }
if (input.upload) {
const createdUploadRow = await transaction
@@ -174,6 +180,14 @@ class NodeService {
download: createdDownload,
});
}
+
+ for (const createdChangeId of createdChangeIds) {
+ eventBus.publish({
+ type: 'change_created',
+ userId,
+ changeId: createdChangeId,
+ });
+ }
}
async updateNode(
@@ -252,6 +266,7 @@ class NodeService {
return true;
}
+ let changeId: number | undefined;
const changeData: LocalUpdateNodeChangeData = {
type: 'node_update',
id: nodeId,
@@ -281,14 +296,19 @@ class NodeService {
if (updatedRow) {
node = mapNode(updatedRow);
- await trx
+ const createdChange = await trx
.insertInto('changes')
+ .returning('id')
.values({
data: JSON.stringify(changeData),
created_at: updatedAt,
retry_count: 0,
})
- .execute();
+ .executeTakeFirst();
+
+ if (createdChange) {
+ changeId = createdChange.id;
+ }
}
return true;
@@ -302,6 +322,14 @@ class NodeService {
});
}
+ if (changeId) {
+ eventBus.publish({
+ type: 'change_created',
+ userId,
+ changeId,
+ });
+ }
+
return result;
}
@@ -340,6 +368,7 @@ class NodeService {
throw new Error('Insufficient permissions');
}
+ let changeId: number | undefined;
const changeData: LocalDeleteNodeChangeData = {
type: 'node_delete',
id: nodeId,
@@ -356,14 +385,19 @@ class NodeService {
await trx.deleteFrom('uploads').where('node_id', '=', nodeId).execute();
await trx.deleteFrom('downloads').where('node_id', '=', nodeId).execute();
- await trx
+ const createdChange = await trx
.insertInto('changes')
+ .returning('id')
.values({
data: JSON.stringify(changeData),
created_at: new Date().toISOString(),
retry_count: 0,
})
- .execute();
+ .executeTakeFirst();
+
+ if (createdChange) {
+ changeId = createdChange.id;
+ }
});
eventBus.publish({
@@ -371,6 +405,14 @@ class NodeService {
userId,
node: node,
});
+
+ if (changeId) {
+ eventBus.publish({
+ type: 'change_created',
+ userId,
+ changeId,
+ });
+ }
}
}
diff --git a/apps/desktop/src/main/services/radar-service.ts b/apps/desktop/src/main/services/radar-service.ts
index 53a777c6..e25ca056 100644
--- a/apps/desktop/src/main/services/radar-service.ts
+++ b/apps/desktop/src/main/services/radar-service.ts
@@ -94,7 +94,10 @@ class RadarService {
eventBus.publish({
type: 'radar_data_updated',
});
- } else if (event.type === 'user_node_created') {
+ } else if (
+ event.type === 'user_node_created' ||
+ event.type === 'user_node_updated'
+ ) {
// to be optimized
const workspaceDatabase = await databaseService.getWorkspaceDatabase(
event.userId
diff --git a/apps/desktop/src/main/synchronizer.ts b/apps/desktop/src/main/services/sync-service.ts
similarity index 60%
rename from apps/desktop/src/main/synchronizer.ts
rename to apps/desktop/src/main/services/sync-service.ts
index ff5fb9ed..323134b7 100644
--- a/apps/desktop/src/main/synchronizer.ts
+++ b/apps/desktop/src/main/services/sync-service.ts
@@ -1,21 +1,28 @@
import { httpClient } from '@/shared/lib/http-client';
import { databaseService } from '@/main/data/database-service';
import { LocalChange, SyncChangesOutput } from '@colanode/core';
-import { WorkspaceCredentials } from '@/shared/types/workspaces';
-import { fileService } from '@/main/services/file-service';
import {
SelectChange,
WorkspaceDatabaseSchema,
} from '@/main/data/workspace/schema';
import { Kysely } from 'kysely';
+import { eventBus } from '@/shared/lib/event-bus';
-const EVENT_LOOP_INTERVAL = 1000;
+type SyncState = {
+ isSyncing: boolean;
+ scheduledSync: boolean;
+};
-class Synchronizer {
+class SyncService {
private initiated: boolean = false;
+ private syncStates: Map<string, SyncState> = new Map();
constructor() {
- this.executeEventLoop = this.executeEventLoop.bind(this);
+ eventBus.subscribe((event) => {
+ if (event.type === 'change_created') {
+ this.syncWorkspace(event.userId);
+ }
+ });
}
public init() {
@@ -23,62 +30,100 @@ class Synchronizer {
return;
}
- setTimeout(this.executeEventLoop, 10);
this.initiated = true;
+ this.syncAllWorkspaces();
}
- private async executeEventLoop() {
- try {
- await this.syncDeletedTokens();
- await this.syncWorkspaces();
- } catch (error) {
- console.log('error', error);
- }
+ private async syncAllWorkspaces() {
+ const workspaces = await databaseService.appDatabase
+ .selectFrom('workspaces')
+ .select(['user_id'])
+ .execute();
- setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
+ for (const workspace of workspaces) {
+ this.syncWorkspace(workspace.user_id);
+ }
}
- private async syncDeletedTokens() {
- const deletedTokens = await databaseService.appDatabase
- .selectFrom('deleted_tokens')
- .innerJoin('servers', 'deleted_tokens.server', 'servers.domain')
- .select([
- 'deleted_tokens.token',
- 'deleted_tokens.account_id',
- 'servers.domain',
- 'servers.attributes',
- ])
- .execute();
+ public async syncWorkspace(userId: string) {
+ if (!this.syncStates.has(userId)) {
+ this.syncStates.set(userId, {
+ isSyncing: false,
+ scheduledSync: false,
+ });
+ }
- if (deletedTokens.length === 0) {
+ const syncState = this.syncStates.get(userId)!;
+ if (syncState.isSyncing) {
+ syncState.scheduledSync = true;
return;
}
- for (const deletedToken of deletedTokens) {
- try {
- const { status } = await httpClient.delete(`/v1/accounts/logout`, {
- serverDomain: deletedToken.domain,
- serverAttributes: deletedToken.attributes,
- token: deletedToken.token,
- });
-
- if (status !== 200) {
- return;
- }
+ syncState.isSyncing = true;
+ try {
+ await this.syncWorkspaceChanges(userId);
+ } catch (error) {
+ console.log('error', error);
+ } finally {
+ syncState.isSyncing = false;
- await databaseService.appDatabase
- .deleteFrom('deleted_tokens')
- .where('token', '=', deletedToken.token)
- .where('account_id', '=', deletedToken.account_id)
- .execute();
- } catch (error) {
- // console.log('error', error);
+ if (syncState.scheduledSync) {
+ syncState.scheduledSync = false;
+ this.syncWorkspace(userId);
}
}
}
- private async syncWorkspaces() {
- const workspaces = await databaseService.appDatabase
+ // private async syncDeletedTokens() {
+ // const deletedTokens = await databaseService.appDatabase
+ // .selectFrom('deleted_tokens')
+ // .innerJoin('servers', 'deleted_tokens.server', 'servers.domain')
+ // .select([
+ // 'deleted_tokens.token',
+ // 'deleted_tokens.account_id',
+ // 'servers.domain',
+ // 'servers.attributes',
+ // ])
+ // .execute();
+
+ // if (deletedTokens.length === 0) {
+ // return;
+ // }
+
+ // for (const deletedToken of deletedTokens) {
+ // try {
+ // const { status } = await httpClient.delete(`/v1/accounts/logout`, {
+ // serverDomain: deletedToken.domain,
+ // serverAttributes: deletedToken.attributes,
+ // token: deletedToken.token,
+ // });
+
+ // if (status !== 200) {
+ // return;
+ // }
+
+ // await databaseService.appDatabase
+ // .deleteFrom('deleted_tokens')
+ // .where('token', '=', deletedToken.token)
+ // .where('account_id', '=', deletedToken.account_id)
+ // .execute();
+ // } catch (error) {
+ // // console.log('error', error);
+ // }
+ // }
+ // }
+
+ private async syncWorkspaceChanges(userId: string) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ const changes =
+ await this.fetchAndCompactWorkspaceChanges(workspaceDatabase);
+ if (changes.length === 0) {
+ return;
+ }
+
+ const workspace = await databaseService.appDatabase
.selectFrom('workspaces')
.innerJoin('accounts', 'workspaces.account_id', 'accounts.id')
.innerJoin('servers', 'accounts.server', 'servers.domain')
@@ -90,45 +135,24 @@ class Synchronizer {
'servers.domain',
'servers.attributes',
])
- .execute();
+ .where('workspaces.user_id', '=', userId)
+ .executeTakeFirst();
- for (const workspace of workspaces) {
- const credentials: WorkspaceCredentials = {
- workspaceId: workspace.workspace_id,
- accountId: workspace.account_id,
- userId: workspace.user_id,
- token: workspace.token,
- serverDomain: workspace.domain,
- serverAttributes: workspace.attributes,
- };
-
- try {
- await this.checkForChanges(credentials);
- await fileService.checkForUploads(credentials);
- await fileService.checkForDownloads(credentials);
- } catch (error) {
- // console.log('error', error);
- }
+ if (!workspace) {
+ return;
}
- }
-
- private async checkForChanges(credentials: WorkspaceCredentials) {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- credentials.userId
- );
- const changes = await this.fetchAndCompactChanges(workspaceDatabase);
while (changes.length > 0) {
const changesToSync = changes.splice(0, 20);
const { data } = await httpClient.post<SyncChangesOutput>(
- `/v1/sync/${credentials.workspaceId}`,
+ `/v1/sync/${workspace.workspace_id}`,
{
changes: changesToSync,
},
{
- serverDomain: credentials.serverDomain,
- serverAttributes: credentials.serverAttributes,
- token: credentials.token,
+ serverDomain: workspace.domain,
+ serverAttributes: workspace.attributes,
+ token: workspace.token,
}
);
@@ -166,7 +190,7 @@ class Synchronizer {
}
}
- private async fetchAndCompactChanges(
+ private async fetchAndCompactWorkspaceChanges(
database: Kysely<WorkspaceDatabaseSchema>
): Promise<LocalChange[]> {
const changeRows = await database
@@ -242,4 +266,4 @@ class Synchronizer {
}
}
-export const synchronizer = new Synchronizer();
+export const syncService = new SyncService();
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 1903c4d6..fe8e46cf 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -63,6 +63,12 @@ export type UserNodeCreatedEvent = {
userNode: UserNode;
};
+export type UserNodeUpdatedEvent = {
+ type: 'user_node_updated';
+ userId: string;
+ userNode: UserNode;
+};
+
export type DownloadCreatedEvent = {
type: 'download_created';
userId: string;
@@ -109,6 +115,12 @@ export type RadarDataUpdatedEvent = {
type: 'radar_data_updated';
};
+export type ChangeCreatedEvent = {
+ type: 'change_created';
+ userId: string;
+ changeId: number;
+};
+
export type Event =
| NodeCreatedEvent
| NodeUpdatedEvent
@@ -121,6 +133,7 @@ export type Event =
| WorkspaceDeletedEvent
| ServerCreatedEvent
| UserNodeCreatedEvent
+ | UserNodeUpdatedEvent
| DownloadCreatedEvent
| DownloadUpdatedEvent
| DownloadDeletedEvent
@@ -128,4 +141,5 @@ export type Event =
| UploadUpdatedEvent
| UploadDeletedEvent
| QueryResultUpdatedEvent
- | RadarDataUpdatedEvent;
+ | RadarDataUpdatedEvent
+ | ChangeCreatedEvent;