Skip to content

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

Refactor socket services

Hakan Shehue2634de92980
diff --git a/apps/desktop/src/main/bootstrapper.ts b/apps/desktop/src/main/bootstrapper.ts
index c4603e7a..2fc220a4 100644
--- a/apps/desktop/src/main/bootstrapper.ts
+++ b/apps/desktop/src/main/bootstrapper.ts
@@ -29,8 +29,7 @@ class Bootstrapper {
await assetService.checkAssets();
await serverService.syncServers();
await radarService.init();
-
- socketService.init();
+ await socketService.checkConnections();
if (!this.eventLoop) {
this.eventLoop = setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
@@ -41,6 +40,7 @@ class Bootstrapper {
try {
await serverService.syncServers();
await accountService.syncAccounts();
+ await socketService.checkConnections();
await accountService.syncDeletedTokens();
await workspaceService.syncAllWorkspaces();
} catch (error) {
diff --git a/apps/desktop/src/main/services/server-service.ts b/apps/desktop/src/main/services/server-service.ts
index 63a89fbf..6ee7f7ba 100644
--- a/apps/desktop/src/main/services/server-service.ts
+++ b/apps/desktop/src/main/services/server-service.ts
@@ -60,7 +60,7 @@ class ServerService {
}
private async fetchServerConfig(server: Server) {
- const baseUrl = this.buildServerBaseUrl(server);
+ const baseUrl = this.buildApiBaseUrl(server.domain);
const configUrl = `${baseUrl}/v1/config`;
try {
const { status, data } = await axios.get<ServerConfig>(configUrl);
@@ -70,11 +70,15 @@ class ServerService {
}
}
- private buildServerBaseUrl(server: Server) {
- const domain = server.domain;
+ public buildApiBaseUrl(domain: string) {
const protocol = domain.startsWith('localhost:') ? 'http' : 'https';
return `${protocol}://${domain}`;
}
+
+ public buildSynapseUrl(domain: string) {
+ const protocol = domain.startsWith('localhost:') ? 'ws' : 'wss';
+ return `${protocol}://${domain}/v1/synapse`;
+ }
}
export const serverService = new ServerService();
diff --git a/apps/desktop/src/main/services/socket-connection.ts b/apps/desktop/src/main/services/socket-connection.ts
index c4e30afb..2af0ab6f 100644
--- a/apps/desktop/src/main/services/socket-connection.ts
+++ b/apps/desktop/src/main/services/socket-connection.ts
@@ -3,7 +3,7 @@ import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
import { Message } from '@colanode/core';
import { SelectAccount, SelectServer } from '@/main/data/app/schema';
import { ServerAttributes } from '@/shared/types/servers';
-import { mutationService } from './mutation-service';
+import { mutationService } from '@/main/services/mutation-service';
const buildSynapseUrl = (server: SelectServer, deviceId: string) => {
const attributes = JSON.parse(server.attributes) as ServerAttributes;
@@ -12,14 +12,14 @@ const buildSynapseUrl = (server: SelectServer, deviceId: string) => {
};
export class SocketConnection {
- private readonly server: SelectServer;
+ private readonly synapseUrl: string;
private readonly account: SelectAccount;
private socket: WebSocket | null;
private backoffCalculator: BackoffCalculator;
private closingCount: number;
- constructor(server: SelectServer, account: SelectAccount) {
- this.server = server;
+ constructor(synapseUrl: string, account: SelectAccount) {
+ this.synapseUrl = synapseUrl;
this.account = account;
this.socket = null;
this.backoffCalculator = new BackoffCalculator();
@@ -35,14 +35,11 @@ export class SocketConnection {
return;
}
- this.socket = new WebSocket(
- buildSynapseUrl(this.server, this.account.device_id),
- {
- headers: {
- authorization: this.account.token,
- },
- }
- );
+ this.socket = new WebSocket(this.synapseUrl, {
+ headers: {
+ authorization: this.account.token,
+ },
+ });
this.socket.onmessage = async (event) => {
let data: string;
@@ -102,6 +99,10 @@ export class SocketConnection {
this.socket.onerror = () => {
this.backoffCalculator.increaseError();
};
+
+ this.socket.onclose = () => {
+ this.backoffCalculator.increaseError();
+ };
}
public isConnected(): boolean {
diff --git a/apps/desktop/src/main/services/socket-service.ts b/apps/desktop/src/main/services/socket-service.ts
index 4665e1b7..74a550e5 100644
--- a/apps/desktop/src/main/services/socket-service.ts
+++ b/apps/desktop/src/main/services/socket-service.ts
@@ -1,29 +1,28 @@
import { SocketConnection } from '@/main/services/socket-connection';
import { databaseService } from '@/main/data/database-service';
import { Message } from '@colanode/core';
-
-const EVENT_LOOP_INTERVAL = 5000;
+import { serverService } from './server-service';
+import { eventBus } from '@/shared/lib/event-bus';
class SocketService {
- private readonly accounts: Map<string, SocketConnection> = new Map();
- private initiated: boolean = false;
+ private readonly sockets: Map<string, SocketConnection> = new Map();
constructor() {
- this.executeEventLoop = this.executeEventLoop.bind(this);
- }
-
- public init() {
- if (this.initiated) {
- return;
- }
-
- // for the first time we execute event loop almost instantly
- setTimeout(this.executeEventLoop, 10);
- this.initiated = true;
+ eventBus.subscribe((event) => {
+ if (event.type === 'server_availability_changed' && event.isAvailable) {
+ this.checkConnections();
+ } else if (
+ event.type === 'account_created' ||
+ event.type === 'account_updated' ||
+ event.type === 'account_deleted'
+ ) {
+ this.checkConnections();
+ }
+ });
}
public sendMessage(accountId: string, message: Message) {
- const connection = this.accounts.get(accountId);
+ const connection = this.sockets.get(accountId);
if (!connection) {
return;
}
@@ -31,19 +30,7 @@ class SocketService {
connection.sendMessage(message);
}
- private async executeEventLoop() {
- await this.checkAccounts();
- this.checkConnections();
-
- setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
- }
-
- private async checkAccounts() {
- const servers = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .execute();
-
+ public async checkConnections() {
const accounts = await databaseService.appDatabase
.selectFrom('accounts')
.selectAll()
@@ -52,37 +39,32 @@ class SocketService {
// Update accounts map
for (const account of accounts) {
- const server = servers.find((s) => s.domain === account.server);
- if (!server) {
- this.accounts.delete(account.id);
+ if (!serverService.isAvailable(account.server)) {
continue;
}
- if (this.accounts.has(account.id)) {
+ const socket = this.sockets.get(account.id);
+ if (socket) {
+ socket.checkConnection();
continue;
}
- const connection = new SocketConnection(server, account);
+ const synapseUrl = serverService.buildSynapseUrl(account.server);
+ const connection = new SocketConnection(synapseUrl, account);
connection.init();
- this.accounts.set(account.id, connection);
+ this.sockets.set(account.id, connection);
}
// Remove logged out or missing accounts
- for (const [accountId, connection] of this.accounts.entries()) {
+ for (const [accountId, connection] of this.sockets.entries()) {
const account = accounts.find((acc) => acc.id === accountId);
if (!account) {
connection.close();
- this.accounts.delete(accountId);
+ this.sockets.delete(accountId);
}
}
}
-
- private checkConnections() {
- for (const connection of this.accounts.values()) {
- connection.checkConnection();
- }
- }
}
export const socketService = new SocketService();