Skip to content

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

Introduce a service to check fi servers are available

Hakan Shehu90d7f548aba7
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index a4e57092..1357a992 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -13,10 +13,7 @@ import { QueryInput } from '@/shared/queries';
import { CommandMap } from '@/shared/commands';
import { CommandInput } from '@/shared/commands';
import { commandService } from '@/main/services/command-service';
-import { databaseService } from '@/main/data/database-service';
-import { socketService } from '@/main/services/socket-service';
-import { syncService } from '@/main/services/sync-service';
-import { radarService } from '@/main/services/radar-service';
+import { bootstrapper } from '@/main/bootstrapper';
import started from 'electron-squirrel-startup';
let subscriptionId: string | null = null;
@@ -27,11 +24,7 @@ if (started) {
}
const createWindow = async () => {
- await databaseService.init();
- assetService.checkAssets();
- socketService.init();
- syncService.init();
- radarService.init();
+ await bootstrapper.init();
// Create the browser window.
const mainWindow = new BrowserWindow({
diff --git a/apps/desktop/src/main/bootstrapper.ts b/apps/desktop/src/main/bootstrapper.ts
new file mode 100644
index 00000000..c4603e7a
--- /dev/null
+++ b/apps/desktop/src/main/bootstrapper.ts
@@ -0,0 +1,54 @@
+import { databaseService } from '@/main/data/database-service';
+import { assetService } from '@/main/services/asset-service';
+import { radarService } from '@/main/services/radar-service';
+import { socketService } from '@/main/services/socket-service';
+import { serverService } from '@/main/services/server-service';
+import { accountService } from '@/main/services/account-service';
+import { workspaceService } from '@/main/services/workspace-service';
+
+const EVENT_LOOP_INTERVAL = 1000 * 60;
+
+class Bootstrapper {
+ private initPromise: Promise<void> | null = null;
+ private eventLoop: NodeJS.Timeout | null = null;
+
+ constructor() {
+ this.executeEventLoop = this.executeEventLoop.bind(this);
+ }
+
+ public init(): Promise<void> {
+ if (!this.initPromise) {
+ this.initPromise = this.executeInit();
+ }
+
+ return this.initPromise;
+ }
+
+ private async executeInit() {
+ await databaseService.init();
+ await assetService.checkAssets();
+ await serverService.syncServers();
+ await radarService.init();
+
+ socketService.init();
+
+ if (!this.eventLoop) {
+ this.eventLoop = setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
+ }
+ }
+
+ private async executeEventLoop() {
+ try {
+ await serverService.syncServers();
+ await accountService.syncAccounts();
+ await accountService.syncDeletedTokens();
+ await workspaceService.syncAllWorkspaces();
+ } catch (error) {
+ console.log('error', error);
+ }
+
+ this.eventLoop = setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
+ }
+}
+
+export const bootstrapper = new Bootstrapper();
diff --git a/apps/desktop/src/main/services/account-service.ts b/apps/desktop/src/main/services/account-service.ts
index dbfdec45..5cff2ae1 100644
--- a/apps/desktop/src/main/services/account-service.ts
+++ b/apps/desktop/src/main/services/account-service.ts
@@ -7,6 +7,7 @@ import { mapAccount, mapWorkspace } from '@/main/utils';
import { getAccountAvatarsDirectoryPath } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
import { workspaceService } from '@/main/services/workspace-service';
+import { serverService } from '@/main/services/server-service';
class AccountService {
async syncAccounts() {
@@ -31,6 +32,10 @@ class AccountService {
throw new Error('Server not found!');
}
+ if (!serverService.isAvailable(server.domain)) {
+ return;
+ }
+
const { data, status } = await httpClient.get<AccountSyncOutput>(
'/v1/accounts/sync',
{
@@ -202,6 +207,10 @@ class AccountService {
}
for (const deletedToken of deletedTokens) {
+ if (!serverService.isAvailable(deletedToken.domain)) {
+ continue;
+ }
+
try {
const { status } = await httpClient.delete(`/v1/accounts/logout`, {
serverDomain: deletedToken.domain,
diff --git a/apps/desktop/src/main/services/device-service.ts b/apps/desktop/src/main/services/device-service.ts
deleted file mode 100644
index d481531d..00000000
--- a/apps/desktop/src/main/services/device-service.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { eventBus } from '@/shared/lib/event-bus';
-// import { publicIp } from 'public-ip';
-
-type OnlineState = {
- isOnline: boolean;
- lastCheckedAt: Date;
- lastCheckedSuccessfullyAt: Date | null;
- count: number;
-};
-
-class DeviceService {
- private readonly onlineState: OnlineState = {
- isOnline: false,
- lastCheckedAt: new Date(),
- lastCheckedSuccessfullyAt: null,
- count: 0,
- };
-
- private deviceIp: string | null = null;
-
- public get isOnline() {
- return this.onlineState.isOnline;
- }
-
- public get ip() {
- return this.deviceIp;
- }
-
- public async checkOnlineState() {
- const wasOnline = this.onlineState.isOnline;
- const isOnline = await this.checkIsOnline();
-
- this.onlineState.isOnline = isOnline;
- this.onlineState.lastCheckedAt = new Date();
- this.onlineState.count++;
- if (isOnline) {
- this.onlineState.lastCheckedSuccessfullyAt = new Date();
- }
-
- if (wasOnline !== isOnline) {
- eventBus.publish({
- type: 'online_state_changed',
- isOnline,
- });
- }
- }
-
- private async checkIsOnline() {
- try {
- // this.deviceIp = await publicIp();
- return true;
- } catch (error) {
- return false;
- }
- }
-}
-
-export const deviceService = new DeviceService();
diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts
index 0e577db5..f88f1a2b 100644
--- a/apps/desktop/src/main/services/file-service.ts
+++ b/apps/desktop/src/main/services/file-service.ts
@@ -14,6 +14,7 @@ import { httpClient } from '@/shared/lib/http-client';
import { getWorkspaceFilesDirectoryPath } from '@/main/utils';
import { FileAttributes } from '@colanode/core';
import { eventBus } from '@/shared/lib/event-bus';
+import { serverService } from '@/main/services/server-service';
class FileService {
public async handleFileRequest(request: Request): Promise<Response> {
@@ -145,6 +146,10 @@ class FileService {
continue;
}
+ if (!serverService.isAvailable(credentials.serverDomain)) {
+ continue;
+ }
+
try {
const { data } = await httpClient.post<ServerFileUploadResponse>(
`/v1/files/${credentials.workspaceId}/${upload.node_id}`,
@@ -260,6 +265,10 @@ class FileService {
continue;
}
+ if (!serverService.isAvailable(credentials.serverDomain)) {
+ continue;
+ }
+
try {
const { data } = await httpClient.get<ServerFileDownloadResponse>(
`/v1/files/${credentials.workspaceId}/${download.node_id}`,
diff --git a/apps/desktop/src/main/services/server-service.ts b/apps/desktop/src/main/services/server-service.ts
new file mode 100644
index 00000000..63a89fbf
--- /dev/null
+++ b/apps/desktop/src/main/services/server-service.ts
@@ -0,0 +1,80 @@
+import axios from 'axios';
+import { Server, ServerConfig } from '@/shared/types/servers';
+import { databaseService } from '@/main/data/database-service';
+import { mapServer } from '@/main/utils';
+import { eventBus } from '@/shared/lib/event-bus';
+
+type ServerState = {
+ isAvailable: boolean;
+ lastCheckedAt: Date;
+ lastCheckedSuccessfullyAt: Date | null;
+ count: number;
+};
+
+class ServerService {
+ private readonly states: Map<string, ServerState> = new Map();
+
+ public async syncServers() {
+ const rows = await databaseService.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .execute();
+
+ const servers = rows.map(mapServer);
+ for (const server of servers) {
+ await this.syncServer(server);
+ }
+ }
+
+ public isAvailable(domain: string) {
+ const state = this.states.get(domain);
+ return state?.isAvailable ?? false;
+ }
+
+ private async syncServer(server: Server) {
+ const config = await this.fetchServerConfig(server);
+ const existingState = this.states.get(server.domain);
+
+ const newState: ServerState = {
+ isAvailable: config !== null,
+ lastCheckedAt: new Date(),
+ lastCheckedSuccessfullyAt: config !== null ? new Date() : null,
+ count: existingState ? existingState.count + 1 : 1,
+ };
+
+ this.states.set(server.domain, newState);
+
+ const wasAvailable = existingState?.isAvailable ?? false;
+ const isAvailable = newState.isAvailable;
+ if (wasAvailable !== isAvailable) {
+ eventBus.publish({
+ type: 'server_availability_changed',
+ server,
+ isAvailable,
+ });
+ }
+
+ console.log(
+ `Server ${server.domain} is ${isAvailable ? 'available' : 'unavailable'}`
+ );
+ }
+
+ private async fetchServerConfig(server: Server) {
+ const baseUrl = this.buildServerBaseUrl(server);
+ const configUrl = `${baseUrl}/v1/config`;
+ try {
+ const { status, data } = await axios.get<ServerConfig>(configUrl);
+ return status === 200 ? data : null;
+ } catch (error) {
+ return null;
+ }
+ }
+
+ private buildServerBaseUrl(server: Server) {
+ const domain = server.domain;
+ const protocol = domain.startsWith('localhost:') ? 'http' : 'https';
+ return `${protocol}://${domain}`;
+ }
+}
+
+export const serverService = new ServerService();
diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.ts
deleted file mode 100644
index b3ea5204..00000000
--- a/apps/desktop/src/main/services/sync-service.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { accountService } from '@/main/services/account-service';
-import { workspaceService } from '@/main/services/workspace-service';
-import { deviceService } from '@/main/services/device-service';
-
-// one minute
-const EVENT_LOOP_INTERVAL = 1000 * 60;
-
-class SyncService {
- private initiated: boolean = false;
-
- constructor() {
- this.executeEventLoop = this.executeEventLoop.bind(this);
- }
-
- public init() {
- if (this.initiated) {
- return;
- }
-
- this.initiated = true;
- setTimeout(this.executeEventLoop, 10);
- }
-
- private async executeEventLoop() {
- try {
- await deviceService.checkOnlineState();
- if (deviceService.isOnline) {
- await accountService.syncAccounts();
- await accountService.syncDeletedTokens();
- await workspaceService.syncAllWorkspaces();
- }
- } catch (error) {
- console.log('error', error);
- }
-
- setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
- }
-}
-
-export const syncService = new SyncService();
diff --git a/apps/desktop/src/main/services/workspace-service.ts b/apps/desktop/src/main/services/workspace-service.ts
index 004d5ea7..9195c010 100644
--- a/apps/desktop/src/main/services/workspace-service.ts
+++ b/apps/desktop/src/main/services/workspace-service.ts
@@ -10,6 +10,7 @@ import { LocalChange, SyncChangesOutput } from '@colanode/core';
import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
import { Kysely } from 'kysely';
import { httpClient } from '@/shared/lib/http-client';
+import { serverService } from '@/main/services/server-service';
type WorkspaceSyncState = {
isSyncing: boolean;
@@ -121,6 +122,10 @@ class WorkspaceService {
return;
}
+ if (!serverService.isAvailable(workspace.domain)) {
+ return;
+ }
+
while (changes.length > 0) {
const changesToSync = changes.splice(0, 20);
const { data } = await httpClient.post<SyncChangesOutput>(
diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.ts
index ec36c43a..3477593d 100644
--- a/apps/desktop/src/main/utils.ts
+++ b/apps/desktop/src/main/utils.ts
@@ -14,8 +14,13 @@ import {
} from '@/main/data/workspace/schema';
import { LocalChange, Node, NodeTypes } from '@colanode/core';
import { Account } from '@/shared/types/accounts';
-import { SelectAccount, SelectWorkspace } from './data/app/schema';
+import {
+ SelectAccount,
+ SelectServer,
+ SelectWorkspace,
+} from './data/app/schema';
import { Workspace } from '@/shared/types/workspaces';
+import { Server } from '@/shared/types/servers';
export const appPath = app.getPath('userData');
@@ -120,10 +125,22 @@ export const mapWorkspace = (row: SelectWorkspace): Workspace => {
};
};
-export const mapChange = (change: SelectChange): LocalChange => {
+export const mapChange = (row: SelectChange): LocalChange => {
+ return {
+ id: row.id,
+ data: JSON.parse(row.data),
+ createdAt: row.created_at,
+ };
+};
+
+export const mapServer = (row: SelectServer): Server => {
return {
- id: change.id,
- data: JSON.parse(change.data),
- createdAt: change.created_at,
+ domain: row.domain,
+ name: row.name,
+ avatar: row.avatar,
+ attributes: JSON.parse(row.attributes),
+ version: row.version,
+ createdAt: new Date(row.created_at),
+ lastSyncedAt: row.last_synced_at ? new Date(row.last_synced_at) : null,
};
};
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 0c232311..e19b3a31 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -121,9 +121,10 @@ export type ChangeCreatedEvent = {
changeId: number;
};
-export type OnlineStateChangedEvent = {
- type: 'online_state_changed';
- isOnline: boolean;
+export type ServerAvailabilityChangedEvent = {
+ type: 'server_availability_changed';
+ server: Server;
+ isAvailable: boolean;
};
export type Event =
@@ -148,4 +149,4 @@ export type Event =
| QueryResultUpdatedEvent
| RadarDataUpdatedEvent
| ChangeCreatedEvent
- | OnlineStateChangedEvent;
+ | ServerAvailabilityChangedEvent;