Use debug instead of pinojs

This commit is contained in:
Hakan Shehu
2024-12-03 13:42:02 +01:00
parent ad899c1c7c
commit 704dae1efc
21 changed files with 241 additions and 310 deletions

View File

@@ -6,7 +6,7 @@
"description": "Colanode desktop application",
"main": ".vite/build/main.js",
"scripts": {
"dev": "electron-forge start",
"dev": "DEBUG=colanode:* electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
@@ -34,7 +34,6 @@
"@types/unzipper": "^0.10.10",
"autoprefixer": "^10.4.20",
"electron": "^33.2.1",
"pino-pretty": "^13.0.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"vite": "^6.0.1",
@@ -100,7 +99,6 @@
"lowlight": "^3.2.0",
"lucide-react": "^0.462.0",
"mime-types": "^2.1.35",
"pino": "^9.5.0",
"re-resizable": "^6.10.1",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",

View File

@@ -3,8 +3,8 @@ import started from 'electron-squirrel-startup';
import { app, BrowserWindow, ipcMain, protocol } from 'electron';
import path from 'path';
import { createDebugger } from '@/main/debugger';
import { bootstrapper } from '@/main/bootstrapper';
import { closeLoggers, createLogger } from '@/main/logger';
import { assetService } from '@/main/services/asset-service';
import { avatarService } from '@/main/services/avatar-service';
import { commandService } from '@/main/services/command-service';
@@ -12,12 +12,12 @@ import { fileService } from '@/main/services/file-service';
import { mutationService } from '@/main/services/mutation-service';
import { queryService } from '@/main/services/query-service';
import { getAppIconPath } from '@/main/utils';
import { CommandInput,CommandMap } from '@/shared/commands';
import { CommandInput, CommandMap } from '@/shared/commands';
import { eventBus } from '@/shared/lib/event-bus';
import { MutationInput,MutationMap } from '@/shared/mutations';
import { QueryInput,QueryMap } from '@/shared/queries';
import { MutationInput, MutationMap } from '@/shared/mutations';
import { QueryInput, QueryMap } from '@/shared/queries';
const logger = createLogger('main');
const debug = createDebugger('main');
app.setName('Colanode');
app.setAppUserModelId('com.colanode.desktop');
@@ -84,7 +84,7 @@ const createWindow = () => {
});
}
logger.info('Window created');
debug('Window created');
};
// This method will be called when Electron has finished
@@ -111,10 +111,6 @@ app.on('activate', () => {
}
});
app.on('before-quit', () => {
closeLoggers();
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
ipcMain.handle('init', async () => {

View File

@@ -1,5 +1,5 @@
import { createDebugger } from '@/main/debugger';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { accountService } from '@/main/services/account-service';
import { assetService } from '@/main/services/asset-service';
import { fileService } from '@/main/services/file-service';
@@ -13,7 +13,7 @@ import { syncService } from '@/main/services/sync-service';
const EVENT_LOOP_INTERVAL = 1000 * 60;
class Bootstrapper {
private readonly logger = createLogger('bootstrapper');
private readonly debug = createDebugger('bootstrapper');
private initPromise: Promise<void> | null = null;
private eventLoop: NodeJS.Timeout | null = null;
@@ -30,7 +30,7 @@ class Bootstrapper {
}
private async executeInit() {
this.logger.info('Initializing');
this.debug('Initializing');
await databaseService.init();
await assetService.checkAssets();
@@ -45,7 +45,7 @@ class Bootstrapper {
}
private async executeEventLoop() {
this.logger.info('Executing event loop');
this.debug('Executing event loop');
try {
await serverService.syncServers();
@@ -56,7 +56,7 @@ class Bootstrapper {
notificationService.checkBadge();
} catch (error) {
this.logger.error(error, 'Error executing event loop');
this.debug(error, 'Error executing event loop');
}
this.eventLoop = setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);

View File

@@ -1,5 +1,6 @@
import SQLite from 'better-sqlite3';
import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
import debug from 'debug';
import fs from 'fs';
@@ -7,7 +8,6 @@ import { appDatabaseMigrations } from '@/main/data/app/migrations';
import { AppDatabaseSchema } from '@/main/data/app/schema';
import { workspaceDatabaseMigrations } from '@/main/data/workspace/migrations';
import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
import { createLogger } from '@/main/logger';
import { appDatabasePath, getWorkspaceDirectoryPath } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
@@ -19,10 +19,10 @@ class DatabaseService {
> = new Map();
public readonly appDatabase: Kysely<AppDatabaseSchema>;
private readonly logger = createLogger('database-service');
private readonly debugger = debug('database-service');
constructor() {
this.logger.debug('Constructing database service');
this.debugger('Constructing database service');
const dialect = new SqliteDialect({
database: this.buildSqlite(appDatabasePath),
});
@@ -37,7 +37,7 @@ class DatabaseService {
}
public async init(): Promise<void> {
this.logger.debug('Initializing database service');
this.debugger('Initializing database service');
if (!this.initPromise) {
this.initPromise = this.executeInit();
}
@@ -78,7 +78,7 @@ class DatabaseService {
}
public async deleteWorkspaceDatabase(userId: string): Promise<void> {
this.logger.debug(`Deleting workspace database for user: ${userId}`);
this.debugger(`Deleting workspace database for user: ${userId}`);
await this.waitForInit();
if (this.workspaceDatabases.has(userId)) {
@@ -114,7 +114,7 @@ class DatabaseService {
private async initWorkspaceDatabase(
userId: string
): Promise<Kysely<WorkspaceDatabaseSchema>> {
this.logger.debug(`Initializing workspace database for user: ${userId}`);
this.debugger(`Initializing workspace database for user: ${userId}`);
const workspaceDir = getWorkspaceDirectoryPath(userId);
if (!fs.existsSync(workspaceDir)) {
@@ -136,7 +136,7 @@ class DatabaseService {
}
private async migrateAppDatabase(): Promise<void> {
this.logger.debug('Migrating app database');
this.debugger('Migrating app database');
const migrator = new Migrator({
db: this.appDatabase,
provider: {
@@ -152,7 +152,7 @@ class DatabaseService {
private async migrateWorkspaceDatabase(
database: Kysely<WorkspaceDatabaseSchema>
): Promise<void> {
this.logger.debug('Migrating workspace database');
this.debugger('Migrating workspace database');
const migrator = new Migrator({
db: database,
provider: {
@@ -166,7 +166,7 @@ class DatabaseService {
}
private buildSqlite = (filename: string): SQLite.Database => {
this.logger.debug(`Building sqlite database: ${filename}`);
this.debugger(`Building sqlite database: ${filename}`);
const database = new SQLite(filename);
database.pragma('journal_mode = WAL');
return database;

View File

@@ -0,0 +1,5 @@
import debug from 'debug';
export const createDebugger = (namespace: string) => {
return debug(`colanode:${namespace}`);
};

View File

@@ -1,46 +0,0 @@
import pino, { Level, Logger } from 'pino';
import { app } from 'electron';
import path from 'path';
const logConfig: Record<string, Level> = {
main: 'trace',
'server-service': 'trace',
'file-service': 'trace',
};
const loggers: Record<string, Logger> = {};
const logPath = path.join(app.getPath('userData'), 'logs.log');
export const createLogger = (name: string) => {
if (!loggers[name]) {
loggers[name] = pino({
name,
level: logConfig[name] || 'trace',
transport: app.isPackaged
? {
target: 'pino/file',
options: {
destination: logPath,
mkdir: true,
autoEnd: false,
},
}
: {
target: 'pino-pretty',
options: {
colorize: true,
autoEnd: false,
},
},
});
}
return loggers[name];
};
export const closeLoggers = () => {
Object.values(loggers).forEach((logger) => {
logger.flush();
});
};

View File

@@ -2,9 +2,9 @@ import { AccountSyncOutput } from '@colanode/core';
import fs from 'fs';
import { createDebugger } from '@/main/debugger';
import { SelectAccount } from '@/main/data/app/schema';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { serverService } from '@/main/services/server-service';
import {
getAccountAvatarsDirectoryPath,
@@ -16,10 +16,10 @@ import { eventBus } from '@/shared/lib/event-bus';
import { httpClient } from '@/shared/lib/http-client';
class AccountService {
private readonly logger = createLogger('account-service');
private readonly debug = createDebugger('service:account');
async syncAccounts() {
this.logger.debug('Syncing all accounts');
this.debug('Syncing all accounts');
const accounts = await databaseService.appDatabase
.selectFrom('accounts')
@@ -34,7 +34,7 @@ class AccountService {
}
private async syncAccount(account: SelectAccount) {
this.logger.trace(`Syncing account ${account.email}`);
this.debug(`Syncing account ${account.email}`);
const server = await databaseService.appDatabase
.selectFrom('servers')
@@ -43,14 +43,14 @@ class AccountService {
.executeTakeFirst();
if (!server) {
this.logger.warn(
this.debug(
`Server ${account.server} not found for syncing account ${account.email}`
);
return;
}
if (!serverService.isAvailable(server.domain)) {
this.logger.trace(
this.debug(
`Server ${server.domain} is not available for syncing account ${account.email}`
);
return;
@@ -64,10 +64,10 @@ class AccountService {
}
);
this.logger.trace(`Account sync response status code: ${status}`);
this.debug(`Account sync response status code: ${status}`);
if (status >= 400 && status < 500) {
this.logger.info(`Account ${account.email} is not valid, logging out...`);
this.debug(`Account ${account.email} is not valid, logging out...`);
await this.logoutAccount(account);
return;
}
@@ -93,10 +93,10 @@ class AccountService {
.executeTakeFirst();
if (!updatedAccount) {
this.logger.warn(`Failed to update account ${account.email} after sync`);
this.debug(`Failed to update account ${account.email} after sync`);
return;
} else {
this.logger.trace(`Updated account ${account.email} after sync`);
this.debug(`Updated account ${account.email} after sync`);
}
eventBus.publish({
@@ -127,12 +127,12 @@ class AccountService {
.executeTakeFirst();
if (!createdWorkspace) {
this.logger.warn(
this.debug(
`Failed to create workspace ${workspace.id} for account ${account.email}`
);
return;
} else {
this.logger.trace(
this.debug(
`Created workspace ${workspace.id} for account ${account.email} after sync`
);
}
@@ -157,12 +157,12 @@ class AccountService {
.executeTakeFirst();
if (!updatedWorkspace) {
this.logger.warn(
this.debug(
`Failed to update workspace ${currentWorkspace.user_id} for account ${account.email}`
);
return;
} else {
this.logger.trace(
this.debug(
`Updated workspace ${currentWorkspace.user_id} for account ${account.email} after sync`
);
}
@@ -186,7 +186,7 @@ class AccountService {
}
public async logoutAccount(account: SelectAccount): Promise<boolean> {
this.logger.debug(`Logging out account ${account.email}`);
this.debug(`Logging out account ${account.email}`);
const workspaces = await databaseService.appDatabase
.selectFrom('workspaces')
@@ -210,10 +210,10 @@ class AccountService {
.executeTakeFirst();
if (!deletedAccount) {
this.logger.warn(`Failed to delete account ${account.email}`);
this.debug(`Failed to delete account ${account.email}`);
return false;
} else {
this.logger.trace(`Deleted account ${account.email}`);
this.debug(`Deleted account ${account.email}`);
}
eventBus.publish({
@@ -235,7 +235,7 @@ class AccountService {
}
public async syncDeletedTokens() {
this.logger.debug('Syncing deleted tokens');
this.debug('Syncing deleted tokens');
const deletedTokens = await databaseService.appDatabase
.selectFrom('deleted_tokens')
@@ -249,13 +249,13 @@ class AccountService {
.execute();
if (deletedTokens.length === 0) {
this.logger.debug('No deleted tokens found');
this.debug('No deleted tokens found');
return;
}
for (const deletedToken of deletedTokens) {
if (!serverService.isAvailable(deletedToken.domain)) {
this.logger.debug(
this.debug(
`Server ${deletedToken.domain} is not available for logging out account ${deletedToken.account_id}`
);
continue;
@@ -267,9 +267,7 @@ class AccountService {
token: deletedToken.token,
});
this.logger.trace(
`Deleted token logout response status code: ${status}`
);
this.debug(`Deleted token logout response status code: ${status}`);
if (status !== 200) {
return;
@@ -281,11 +279,11 @@ class AccountService {
.where('account_id', '=', deletedToken.account_id)
.execute();
this.logger.debug(
this.debug(
`Logged out account ${deletedToken.account_id} from server ${deletedToken.domain}`
);
} catch {
this.logger.warn(
this.debug(
`Failed to logout account ${deletedToken.account_id} from server ${deletedToken.domain}`
);
}
@@ -293,7 +291,7 @@ class AccountService {
}
private async deleteWorkspace(userId: string): Promise<boolean> {
this.logger.debug(`Deleting workspace ${userId}`);
this.debug(`Deleting workspace ${userId}`);
const deletedWorkspace = await databaseService.appDatabase
.deleteFrom('workspaces')
@@ -302,10 +300,10 @@ class AccountService {
.executeTakeFirst();
if (!deletedWorkspace) {
this.logger.warn(`Failed to delete workspace ${userId}`);
this.debug(`Failed to delete workspace ${userId}`);
return false;
} else {
this.logger.trace(`Deleted workspace ${userId}`);
this.debug(`Deleted workspace ${userId}`);
}
await databaseService.deleteWorkspaceDatabase(userId);
@@ -313,7 +311,7 @@ class AccountService {
if (fs.existsSync(workspaceDir)) {
fs.rmSync(workspaceDir, { recursive: true });
}
this.logger.trace(`Deleted workspace directory ${workspaceDir}`);
this.debug(`Deleted workspace directory ${workspaceDir}`);
eventBus.publish({
type: 'workspace_deleted',

View File

@@ -4,7 +4,7 @@ import { app, net } from 'electron';
import fs from 'fs';
import path from 'path';
import { createLogger } from '@/main/logger';
import { createDebugger } from '@/main/debugger';
import { getAssetsSourcePath } from '@/main/utils';
import { EmojiData } from '@/shared/types/emojis';
import { IconData } from '@/shared/types/icons';
@@ -23,7 +23,7 @@ class AssetService {
app.getPath('userData'),
'assets'
);
private readonly logger = createLogger('asset-service');
private readonly debug = createDebugger('service:asset');
public async handleAssetRequest(request: Request): Promise<Response> {
const url = request.url.replace('asset://', '');
@@ -54,7 +54,7 @@ class AssetService {
public async checkAssets(): Promise<void> {
if (!this.shouldUpdateAssets()) {
this.logger.debug('Assets are up to date');
this.debug('Assets are up to date');
return;
}
@@ -62,7 +62,7 @@ class AssetService {
}
private async updateAssets(): Promise<void> {
this.logger.debug('Updating assets');
this.debug('Updating assets');
await this.updateEmojis();
await this.updateIcons();
@@ -71,7 +71,7 @@ class AssetService {
}
private async updateEmojis(): Promise<void> {
this.logger.debug('Updating emojis');
this.debug('Updating emojis');
const emojisZipPath = path.join(getAssetsSourcePath(), 'emojis.zip');
const emojisDir = path.join(this.assetsDir, 'emojis');
@@ -87,7 +87,7 @@ class AssetService {
}
private async updateIcons(): Promise<void> {
this.logger.debug('Updating icons');
this.debug('Updating icons');
const iconsZipPath = path.join(getAssetsSourcePath(), 'icons.zip');
const iconsDir = path.join(this.assetsDir, 'icons');
@@ -105,7 +105,7 @@ class AssetService {
private shouldUpdateAssets(): boolean {
const assetsVersion = this.readAssetsVersion();
if (!assetsVersion) {
this.logger.debug('No assets version found, updating assets');
this.debug('No assets version found, updating assets');
return true;
}
@@ -118,7 +118,7 @@ class AssetService {
private readAssetsVersion(): AssetsVersion | null {
const assetsVersionPath = path.join(this.assetsDir, 'version.json');
if (!fs.existsSync(assetsVersionPath)) {
this.logger.debug('No assets version found');
this.debug('No assets version found');
return null;
}

View File

@@ -3,18 +3,18 @@ import fs from 'fs';
import path from 'path';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { getAccountAvatarsDirectoryPath } from '@/main/utils';
import { httpClient } from '@/shared/lib/http-client';
import { createDebugger } from '@/main/debugger';
class AvatarService {
private readonly logger = createLogger('avatar-service');
private readonly debug = createDebugger('service:avatar');
public async handleAvatarRequest(request: Request): Promise<Response> {
const url = request.url.replace('avatar://', '');
const [accountId, avatarId] = url.split('/');
if (!accountId || !avatarId) {
this.logger.warn(`Invalid avatar request url: ${url}`);
this.debug(`Invalid avatar request url: ${url}`);
return new Response(null, { status: 400 });
}
@@ -27,9 +27,7 @@ class AvatarService {
return net.fetch(avatarLocalUrl);
}
this.logger.debug(
`Downloading avatar ${avatarId} for account ${accountId}`
);
this.debug(`Downloading avatar ${avatarId} for account ${accountId}`);
// Download the avatar file if it doesn't exist
const credentials = await databaseService.appDatabase
.selectFrom('accounts')
@@ -39,7 +37,7 @@ class AvatarService {
.executeTakeFirst();
if (!credentials) {
this.logger.warn(`Account ${accountId} not found`);
this.debug(`Account ${accountId} not found`);
return new Response(null, { status: 404 });
}
@@ -53,7 +51,7 @@ class AvatarService {
);
if (response.status !== 200 || !response.data) {
this.logger.warn(
this.debug(
`Failed to download avatar ${avatarId} for account ${accountId}`
);
return new Response(null, { status: 404 });
@@ -70,14 +68,12 @@ class AvatarService {
fileStream.on('finish', async () => {
// Ensure the file is written before trying to fetch it
this.logger.debug(
`Avatar ${avatarId} for account ${accountId} downloaded`
);
this.debug(`Avatar ${avatarId} for account ${accountId} downloaded`);
resolve(net.fetch(avatarLocalUrl));
});
fileStream.on('error', (err) => {
this.logger.warn(
this.debug(
`Failed to download avatar ${avatarId} for account ${accountId}`
);
reject(new Response(null, { status: 500, statusText: err.message }));

View File

@@ -3,18 +3,18 @@ import {
ServerCollaborationRevocation,
} from '@colanode/core';
import { createDebugger } from '@/main/debugger';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { eventBus } from '@/shared/lib/event-bus';
class CollaborationService {
private readonly logger = createLogger('collaboration-service');
private readonly debug = createDebugger('service:collaboration');
public async applyServerCollaboration(
userId: string,
collaboration: ServerCollaboration
) {
this.logger.trace(
this.debug(
`Applying server collaboration: ${collaboration.nodeId} for user ${userId}`
);
@@ -55,7 +55,7 @@ class CollaborationService {
userId: string,
revocation: ServerCollaborationRevocation
) {
this.logger.trace(
this.debug(
`Applying server collaboration revocation: ${revocation.nodeId} for user ${userId}`
);

View File

@@ -1,15 +1,15 @@
import { createDebugger } from '@/main/debugger';
import { commandHandlerMap } from '@/main/commands';
import { createLogger } from '@/main/logger';
import { CommandHandler } from '@/main/types';
import { CommandInput, CommandMap } from '@/shared/commands';
class CommandService {
private readonly logger = createLogger('command-service');
private readonly debug = createDebugger('service:command');
public async executeCommand<T extends CommandInput>(
input: T
): Promise<CommandMap[T['type']]['output']> {
this.logger.trace(`Executing command: ${input.type}`);
this.debug(`Executing command: ${input.type}`);
const handler = commandHandlerMap[
input.type

View File

@@ -12,8 +12,8 @@ import { net, shell } from 'electron';
import fs from 'fs';
import path from 'path';
import { createDebugger } from '@/main/debugger';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { serverService } from '@/main/services/server-service';
import { getWorkspaceFilesDirectoryPath } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
@@ -28,7 +28,7 @@ type WorkspaceFileState = {
};
class FileService {
private readonly logger = createLogger('file-service');
private readonly debug = createDebugger('service:file');
private readonly fileStates: Map<string, WorkspaceFileState> = new Map();
constructor() {
@@ -54,7 +54,7 @@ class FileService {
const url = request.url.replace('local-file://', '');
const [userId, file] = url.split('/');
if (!userId || !file) {
this.logger.warn(`Invalid file request url: ${url}`);
this.debug(`Invalid file request url: ${url}`);
return new Response(null, { status: 400 });
}
@@ -66,7 +66,7 @@ class FileService {
return net.fetch(fileUrl);
}
this.logger.warn(`File ${file} not found for user ${userId}`);
this.debug(`File ${file} not found for user ${userId}`);
return new Response(null, { status: 404 });
}
@@ -93,7 +93,7 @@ class FileService {
`${fileId}_${uploadId}${fileExtension}`
);
this.logger.debug(
this.debug(
`Copying file ${filePath} to ${destinationFilePath} for user ${userId}`
);
fs.copyFileSync(filePath, destinationFilePath);
@@ -103,7 +103,7 @@ class FileService {
const filesDir = getWorkspaceFilesDirectoryPath(userId);
const filePath = path.join(filesDir, `${id}${extension}`);
this.logger.debug(`Opening file ${filePath} for user ${userId}`);
this.debug(`Opening file ${filePath} for user ${userId}`);
shell.openPath(filePath);
}
@@ -111,7 +111,7 @@ class FileService {
const filesDir = getWorkspaceFilesDirectoryPath(userId);
const filePath = path.join(filesDir, `${id}${extension}`);
this.logger.debug(`Deleting file ${filePath} for user ${userId}`);
this.debug(`Deleting file ${filePath} for user ${userId}`);
fs.rmSync(filePath, { force: true });
}
@@ -128,7 +128,7 @@ class FileService {
const stats = fs.statSync(filePath);
const type = extractFileType(mimeType);
this.logger.debug(`Getting file metadata for ${filePath}`);
this.debug(`Getting file metadata for ${filePath}`);
return {
path: filePath,
@@ -141,7 +141,7 @@ class FileService {
}
public async syncFiles() {
this.logger.debug('Syncing files');
this.debug('Syncing files');
const workspaces = await databaseService.appDatabase
.selectFrom('workspaces')
@@ -168,7 +168,7 @@ class FileService {
const fileState = this.fileStates.get(userId)!;
if (fileState.isUploading) {
fileState.isUploadScheduled = true;
this.logger.debug(
this.debug(
`Uploading files for user ${userId} is in progress, scheduling upload`
);
return;
@@ -178,7 +178,7 @@ class FileService {
try {
await this.uploadWorkspaceFiles(userId);
} catch (error) {
this.logger.error(error, `Error uploading files for user ${userId}`);
this.debug(error, `Error uploading files for user ${userId}`);
} finally {
fileState.isUploading = false;
if (fileState.isUploadScheduled) {
@@ -201,7 +201,7 @@ class FileService {
const fileState = this.fileStates.get(userId)!;
if (fileState.isDownloading) {
fileState.isDownloadScheduled = true;
this.logger.debug(
this.debug(
`Downloading files for user ${userId} is in progress, scheduling download`
);
return;
@@ -211,7 +211,7 @@ class FileService {
try {
await this.downloadWorkspaceFiles(userId);
} catch (error) {
this.logger.error(error, `Error downloading files for user ${userId}`);
this.debug(error, `Error downloading files for user ${userId}`);
} finally {
fileState.isDownloading = false;
if (fileState.isDownloadScheduled) {
@@ -222,7 +222,7 @@ class FileService {
}
private async uploadWorkspaceFiles(userId: string): Promise<void> {
this.logger.debug(`Uploading files for user ${userId}`);
this.debug(`Uploading files for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -253,7 +253,7 @@ class FileService {
.executeTakeFirst();
if (!workspace) {
this.logger.warn(`Workspace not found for user ${userId}`);
this.debug(`Workspace not found for user ${userId}`);
return;
}
@@ -375,7 +375,7 @@ class FileService {
.executeTakeFirst();
if (!workspace) {
this.logger.warn(`Workspace not found for user ${userId}`);
this.debug(`Workspace not found for user ${userId}`);
return;
}
@@ -510,7 +510,7 @@ class FileService {
}
private async checkDeletedFiles(userId: string): Promise<void> {
this.logger.debug(`Checking deleted files for user ${userId}`);
this.debug(`Checking deleted files for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);

View File

@@ -1,4 +1,4 @@
import { createLogger } from '@/main/logger';
import { createDebugger } from '@/main/debugger';
import { mutationHandlerMap } from '@/main/mutations';
import { MutationHandler } from '@/main/types';
import {
@@ -8,7 +8,7 @@ import {
} from '@/shared/mutations';
class MutationService {
private readonly logger = createLogger('mutation-service');
private readonly debug = createDebugger('service:mutation');
public async executeMutation<T extends MutationInput>(
input: T
@@ -17,7 +17,7 @@ class MutationService {
input.type
] as unknown as MutationHandler<T>;
this.logger.trace(`Executing mutation: ${input.type}`);
this.debug(`Executing mutation: ${input.type}`);
try {
if (!handler) {

View File

@@ -13,6 +13,7 @@ import {
import { decodeState, YDoc } from '@colanode/crdt';
import { sql } from 'kysely';
import { createDebugger } from '@/main/debugger';
import { SelectWorkspace } from '@/main/data/app/schema';
import { databaseService } from '@/main/data/database-service';
import {
@@ -23,7 +24,6 @@ import {
SelectNodeTransaction,
SelectUpload,
} from '@/main/data/workspace/schema';
import { createLogger } from '@/main/logger';
import { interactionService } from '@/main/services/interaction-service';
import {
fetchNodeAncestors,
@@ -49,7 +49,7 @@ export type UpdateNodeResult =
| 'invalid_attributes';
class NodeService {
private readonly logger = createLogger('node-service');
private readonly debug = createDebugger('service:node');
public async fetchNode(nodeId: string, userId: string): Promise<Node | null> {
const workspaceDatabase =
@@ -72,7 +72,7 @@ class NodeService {
userId: string,
input: CreateNodeInput | CreateNodeInput[]
) {
this.logger.trace(`Creating ${Array.isArray(input) ? 'nodes' : 'node'}`);
this.debug(`Creating ${Array.isArray(input) ? 'nodes' : 'node'}`);
const workspace = await this.fetchWorkspace(userId);
const inputs = Array.isArray(input) ? input : [input];
@@ -192,7 +192,7 @@ class NodeService {
});
for (const createdNode of createdNodes) {
this.logger.trace(
this.debug(
`Created node ${createdNode.id} with type ${createdNode.type}`
);
@@ -204,7 +204,7 @@ class NodeService {
}
for (const createdTransaction of createdNodeTransactions) {
this.logger.trace(
this.debug(
`Created transaction ${createdTransaction.id} for node ${createdTransaction.node_id} with operation ${createdTransaction.operation}`
);
@@ -224,7 +224,7 @@ class NodeService {
}
for (const createdUpload of createdUploads) {
this.logger.trace(
this.debug(
`Created upload ${createdUpload.upload_id} for node ${createdUpload.node_id}`
);
@@ -236,7 +236,7 @@ class NodeService {
}
for (const createdDownload of createdDownloads) {
this.logger.trace(
this.debug(
`Created download ${createdDownload.upload_id} for node ${createdDownload.node_id}`
);
@@ -269,7 +269,7 @@ class NodeService {
userId: string,
updater: (attributes: NodeAttributes) => NodeAttributes
): Promise<UpdateNodeResult | null> {
this.logger.trace(`Updating node ${nodeId}`);
this.debug(`Updating node ${nodeId}`);
const workspace = await this.fetchWorkspace(userId);
@@ -370,7 +370,7 @@ class NodeService {
});
if (updatedNode) {
this.logger.trace(
this.debug(
`Updated node ${updatedNode.id} with type ${updatedNode.type}`
);
@@ -380,11 +380,11 @@ class NodeService {
node: mapNode(updatedNode),
});
} else {
this.logger.trace(`Failed to update node ${nodeId}`);
this.debug(`Failed to update node ${nodeId}`);
}
if (createdTransaction) {
this.logger.trace(
this.debug(
`Created transaction ${createdTransaction.id} for node ${nodeId}`
);
@@ -402,7 +402,7 @@ class NodeService {
createdTransaction.id
);
} else {
this.logger.trace(`Failed to create transaction for node ${nodeId}`);
this.debug(`Failed to create transaction for node ${nodeId}`);
}
if (updatedNode) {
@@ -491,7 +491,7 @@ class NodeService {
});
if (deletedNode) {
this.logger.trace(
this.debug(
`Deleted node ${deletedNode.id} with type ${deletedNode.type}`
);
@@ -501,11 +501,11 @@ class NodeService {
node: mapNode(deletedNode),
});
} else {
this.logger.trace(`Failed to delete node ${nodeId}`);
this.debug(`Failed to delete node ${nodeId}`);
}
if (createdTransaction) {
this.logger.trace(
this.debug(
`Created transaction ${createdTransaction.id} for node ${nodeId}`
);
@@ -515,7 +515,7 @@ class NodeService {
transaction: mapTransaction(createdTransaction),
});
} else {
this.logger.trace(`Failed to create transaction for node ${nodeId}`);
this.debug(`Failed to create transaction for node ${nodeId}`);
}
}
@@ -626,7 +626,7 @@ class NodeService {
userId: string,
transaction: ServerNodeCreateTransaction
) {
this.logger.trace(
this.debug(
`Applying server create transaction ${transaction.id} for node ${transaction.nodeId}`
);
@@ -646,7 +646,7 @@ class NodeService {
existingTransaction.version === version &&
existingTransaction.server_created_at === transaction.serverCreatedAt
) {
this.logger.trace(
this.debug(
`Server create transaction ${transaction.id} for node ${transaction.nodeId} is already synced`
);
return;
@@ -662,7 +662,7 @@ class NodeService {
.where('id', '=', transaction.id)
.execute();
this.logger.trace(
this.debug(
`Server create transaction ${transaction.id} for node ${transaction.nodeId} has been synced`
);
return;
@@ -709,7 +709,7 @@ class NodeService {
});
if (createdNode) {
this.logger.trace(
this.debug(
`Created node ${createdNode.id} with type ${createdNode.type} with transaction ${transaction.id}`
);
@@ -727,7 +727,7 @@ class NodeService {
transaction.id
);
} else {
this.logger.trace(
this.debug(
`Server create transaction ${transaction.id} for node ${transaction.nodeId} is incomplete`
);
@@ -759,7 +759,7 @@ class NodeService {
existingTransaction.version === version &&
existingTransaction.server_created_at === transaction.serverCreatedAt
) {
this.logger.trace(
this.debug(
`Server update transaction ${transaction.id} for node ${transaction.nodeId} is already synced`
);
return;
@@ -775,7 +775,7 @@ class NodeService {
.where('id', '=', transaction.id)
.execute();
this.logger.trace(
this.debug(
`Server update transaction ${transaction.id} for node ${transaction.nodeId} has been synced`
);
return;
@@ -835,7 +835,7 @@ class NodeService {
});
if (updatedNode) {
this.logger.trace(
this.debug(
`Updated node ${updatedNode.id} with type ${updatedNode.type} with transaction ${transaction.id}`
);
@@ -853,7 +853,7 @@ class NodeService {
transaction.id
);
} else {
this.logger.trace(
this.debug(
`Server update transaction ${transaction.id} for node ${transaction.nodeId} is incomplete`
);
@@ -869,7 +869,7 @@ class NodeService {
userId: string,
transaction: ServerNodeDeleteTransaction
) {
this.logger.trace(
this.debug(
`Applying server delete transaction ${transaction.id} for node ${transaction.nodeId}`
);
@@ -909,7 +909,7 @@ class NodeService {
});
if (result) {
this.logger.trace(
this.debug(
`Deleted node ${result.id} with type ${result.type} with transaction ${transaction.id}`
);

View File

@@ -1,6 +1,6 @@
import { isEqual } from 'lodash-es';
import { createLogger } from '@/main/logger';
import { createDebugger } from '@/main/debugger';
import { queryHandlerMap } from '@/main/queries';
import { QueryHandler, SubscribedQuery } from '@/main/types';
import { eventBus } from '@/shared/lib/event-bus';
@@ -8,7 +8,7 @@ import { QueryInput, QueryMap } from '@/shared/queries';
import { Event } from '@/shared/types/events';
class QueryService {
private readonly logger = createLogger('query-service');
private readonly debug = createDebugger('service:query');
private readonly subscribedQueries: Map<string, SubscribedQuery<QueryInput>> =
new Map();
@@ -29,7 +29,7 @@ class QueryService {
public async executeQuery<T extends QueryInput>(
input: T
): Promise<QueryMap[T['type']]['output']> {
this.logger.trace(`Executing query: ${input.type}`);
this.debug(`Executing query: ${input.type}`);
const handler = queryHandlerMap[input.type] as unknown as QueryHandler<T>;
@@ -45,7 +45,7 @@ class QueryService {
id: string,
input: T
): Promise<QueryMap[T['type']]['output']> {
this.logger.debug(`Executing query and subscribing: ${input.type}`);
this.debug(`Executing query and subscribing: ${input.type}`);
if (this.subscribedQueries.has(id)) {
return this.subscribedQueries.get(id)!.result;
@@ -65,7 +65,7 @@ class QueryService {
}
public unsubscribeQuery(id: string) {
this.logger.debug(`Unsubscribing query: ${id}`);
this.debug(`Unsubscribing query: ${id}`);
this.subscribedQueries.delete(id);
}

View File

@@ -2,10 +2,10 @@ import { ServerConfig } from '@colanode/core';
import axios from 'axios';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { mapServer } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
import { Server } from '@/shared/types/servers';
import { createDebugger } from '@/main/debugger';
type ServerState = {
isAvailable: boolean;
@@ -16,10 +16,10 @@ type ServerState = {
class ServerService {
private readonly states: Map<string, ServerState> = new Map();
private readonly logger = createLogger('server-service');
private readonly debug = createDebugger('service:server');
public async syncServers() {
this.logger.trace('Syncing servers');
this.debug('Syncing servers');
const rows = await databaseService.appDatabase
.selectFrom('servers')
@@ -60,7 +60,7 @@ class ServerService {
});
}
this.logger.trace(
this.debug(
`Server ${server.domain} is ${isAvailable ? 'available' : 'unavailable'}`
);
@@ -88,7 +88,7 @@ class ServerService {
}
public async fetchServerConfig(domain: string) {
this.logger.trace(`Fetching server config for ${domain}`);
this.debug(`Fetching server config for ${domain}`);
const baseUrl = this.buildApiBaseUrl(domain);
const configUrl = `${baseUrl}/v1/config`;

View File

@@ -1,14 +1,14 @@
import { Message } from '@colanode/core';
import { WebSocket } from 'ws';
import { createDebugger } from '@/main/debugger';
import { SelectAccount } from '@/main/data/app/schema';
import { createLogger } from '@/main/logger';
import { syncService } from '@/main/services/sync-service';
import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
import { eventBus } from '@/shared/lib/event-bus';
export class SocketConnection {
private readonly logger = createLogger('socket-connection');
private readonly debug = createDebugger('service:socket-connection');
private readonly synapseUrl: string;
private readonly account: SelectAccount;
@@ -25,9 +25,7 @@ export class SocketConnection {
}
public init(): void {
this.logger.trace(
`Initializing socket connection for account ${this.account.id}`
);
this.debug(`Initializing socket connection for account ${this.account.id}`);
if (this.isConnected()) {
return;
@@ -55,7 +53,7 @@ export class SocketConnection {
return;
}
const message: Message = JSON.parse(data);
this.logger.trace(
this.debug(
`Received message of type ${message.type} for account ${this.account.id}`
);
@@ -71,9 +69,7 @@ export class SocketConnection {
};
this.socket.onopen = () => {
this.logger.trace(
`Socket connection for account ${this.account.id} opened`
);
this.debug(`Socket connection for account ${this.account.id} opened`);
this.backoffCalculator.reset();
eventBus.publish({
@@ -83,18 +79,12 @@ export class SocketConnection {
};
this.socket.onerror = () => {
this.logger.trace(
`Socket connection for account ${this.account.id} errored`
);
this.debug(`Socket connection for account ${this.account.id} errored`);
this.backoffCalculator.increaseError();
};
this.socket.onclose = () => {
this.logger.trace(
`Socket connection for account ${this.account.id} closed`
);
this.debug(`Socket connection for account ${this.account.id} closed`);
this.backoffCalculator.increaseError();
};
}
@@ -105,7 +95,7 @@ export class SocketConnection {
public sendMessage(message: Message): boolean {
if (this.socket && this.isConnected()) {
this.logger.trace(
this.debug(
`Sending message of type ${message.type} for account ${this.account.id}`
);
@@ -118,10 +108,7 @@ export class SocketConnection {
public close(): void {
if (this.socket) {
this.logger.trace(
`Closing socket connection for account ${this.account.id}`
);
this.debug(`Closing socket connection for account ${this.account.id}`);
this.socket.close();
}
}

View File

@@ -1,13 +1,13 @@
import { Message } from '@colanode/core';
import { createDebugger } from '@/main/debugger';
import { databaseService } from '@/main/data/database-service';
import { createLogger } from '@/main/logger';
import { serverService } from '@/main/services/server-service';
import { SocketConnection } from '@/main/services/socket-connection';
import { eventBus } from '@/shared/lib/event-bus';
class SocketService {
private readonly logger = createLogger('socket-service');
private readonly debug = createDebugger('service:socket');
private readonly sockets: Map<string, SocketConnection> = new Map();
constructor() {
@@ -34,7 +34,7 @@ class SocketService {
}
public async checkConnections() {
this.logger.trace('Checking socket connections');
this.debug('Checking socket connections');
const accounts = await databaseService.appDatabase
.selectFrom('accounts')
@@ -45,7 +45,7 @@ class SocketService {
// Update accounts map
for (const account of accounts) {
if (!serverService.isAvailable(account.server)) {
this.logger.trace(
this.debug(
`Server ${account.server} is not available, skipping socket connection`
);

View File

@@ -14,12 +14,12 @@ import {
} from '@colanode/core';
import { sql } from 'kysely';
import { createDebugger } from '@/main/debugger';
import { databaseService } from '@/main/data/database-service';
import {
SelectInteractionEvent,
SelectNodeTransaction,
} from '@/main/data/workspace/schema';
import { createLogger } from '@/main/logger';
import { collaborationService } from '@/main/services/collaboration-service';
import { interactionService } from '@/main/services/interaction-service';
import { nodeService } from '@/main/services/node-service';
@@ -35,7 +35,7 @@ type WorkspaceSyncState = {
};
class SyncService {
private readonly logger = createLogger('sync-service');
private readonly debug = createDebugger('service:sync');
private readonly localPendingTransactionStates: Map<
string,
WorkspaceSyncState
@@ -75,7 +75,7 @@ class SyncService {
}
public async syncAllWorkspaces() {
this.logger.trace('Syncing all workspaces');
this.debug('Syncing all workspaces');
const workspaces = await databaseService.appDatabase
.selectFrom('workspaces')
@@ -97,7 +97,7 @@ class SyncService {
}
public async syncLocalPendingTransactions(userId: string) {
this.logger.trace(`Syncing local pending transactions for user ${userId}`);
this.debug(`Syncing local pending transactions for user ${userId}`);
if (!this.localPendingTransactionStates.has(userId)) {
this.localPendingTransactionStates.set(userId, {
@@ -108,7 +108,7 @@ class SyncService {
const syncState = this.localPendingTransactionStates.get(userId)!;
if (syncState.isSyncing) {
this.logger.trace(
this.debug(
`Syncing of local pending transactions already in progress for user ${userId}, scheduling sync`
);
syncState.scheduledSync = true;
@@ -119,13 +119,10 @@ class SyncService {
try {
await this.sendLocalTransactions(userId);
} catch (error) {
this.logger.error(
error,
`Error syncing local transactions for user ${userId}`
);
this.debug(error, `Error syncing local transactions for user ${userId}`);
} finally {
syncState.isSyncing = false;
this.logger.trace(
this.debug(
`Syncing of local pending transactions completed for user ${userId}`
);
@@ -137,7 +134,7 @@ class SyncService {
}
public async syncLocalPendingInteractions(userId: string) {
this.logger.trace(`Syncing local pending interactions for user ${userId}`);
this.debug(`Syncing local pending interactions for user ${userId}`);
if (!this.localPendingInteractionStates.has(userId)) {
this.localPendingInteractionStates.set(userId, {
@@ -148,7 +145,7 @@ class SyncService {
const syncState = this.localPendingInteractionStates.get(userId)!;
if (syncState.isSyncing) {
this.logger.trace(
this.debug(
`Syncing of local pending interactions already in progress for user ${userId}, scheduling sync`
);
syncState.scheduledSync = true;
@@ -159,13 +156,10 @@ class SyncService {
try {
await this.sendLocalInteractions(userId);
} catch (error) {
this.logger.error(
error,
`Error syncing local interactions for user ${userId}`
);
this.debug(error, `Error syncing local interactions for user ${userId}`);
} finally {
syncState.isSyncing = false;
this.logger.trace(
this.debug(
`Syncing of local pending interactions completed for user ${userId}`
);
@@ -177,9 +171,7 @@ class SyncService {
}
public async syncLocalIncompleteTransactions(userId: string) {
this.logger.trace(
`Syncing local incomplete transactions for user ${userId}`
);
this.debug(`Syncing local incomplete transactions for user ${userId}`);
if (!this.localIncompleteTransactionStates.has(userId)) {
this.localIncompleteTransactionStates.set(userId, {
@@ -190,7 +182,7 @@ class SyncService {
const syncState = this.localIncompleteTransactionStates.get(userId)!;
if (syncState.isSyncing) {
this.logger.trace(
this.debug(
`Syncing of local incomplete transactions already in progress for user ${userId}, scheduling sync`
);
syncState.scheduledSync = true;
@@ -201,13 +193,13 @@ class SyncService {
try {
await this.syncIncompleteTransactions(userId);
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing incomplete transactions for user ${userId}`
);
} finally {
syncState.isSyncing = false;
this.logger.trace(
this.debug(
`Syncing of local incomplete transactions completed for user ${userId}`
);
@@ -219,10 +211,10 @@ class SyncService {
}
public async syncServerTransactions(message: NodeTransactionsBatchMessage) {
this.logger.trace(`Syncing server transactions for user ${message.userId}`);
this.debug(`Syncing server transactions for user ${message.userId}`);
if (this.syncingTransactions.has(message.userId)) {
this.logger.trace(
this.debug(
`Syncing of server transactions already in progress for user ${message.userId}, skipping`
);
return;
@@ -240,12 +232,12 @@ class SyncService {
this.updateNodeTransactionCursor(message.userId, cursor);
}
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing server transactions for user ${message.userId}`
);
} finally {
this.logger.trace(
this.debug(
`Syncing of server transactions completed for user ${message.userId}`
);
@@ -255,12 +247,10 @@ class SyncService {
}
public async syncServerCollaborations(message: CollaborationsBatchMessage) {
this.logger.trace(
`Syncing server collaborations for user ${message.userId}`
);
this.debug(`Syncing server collaborations for user ${message.userId}`);
if (this.syncingCollaborations.has(message.userId)) {
this.logger.trace(
this.debug(
`Syncing of server collaborations already in progress for user ${message.userId}, skipping`
);
return;
@@ -281,7 +271,7 @@ class SyncService {
this.updateCollaborationCursor(message.userId, cursor);
}
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing server collaborations for user ${message.userId}`
);
@@ -294,10 +284,10 @@ class SyncService {
public async syncServerRevocations(
message: CollaborationRevocationsBatchMessage
) {
this.logger.trace(`Syncing server revocations for user ${message.userId}`);
this.debug(`Syncing server revocations for user ${message.userId}`);
if (this.syncingRevocations.has(message.userId)) {
this.logger.trace(
this.debug(
`Syncing of server revocations already in progress for user ${message.userId}, skipping`
);
return;
@@ -318,12 +308,12 @@ class SyncService {
this.updateCollaborationRevocationCursor(message.userId, cursor);
}
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing server revocations for user ${message.userId}`
);
} finally {
this.logger.trace(
this.debug(
`Syncing of server revocations completed for user ${message.userId}`
);
@@ -333,10 +323,10 @@ class SyncService {
}
public async syncServerInteractions(message: InteractionsBatchMessage) {
this.logger.trace(`Syncing server interactions for user ${message.userId}`);
this.debug(`Syncing server interactions for user ${message.userId}`);
if (this.syncingInteractions.has(message.userId)) {
this.logger.trace(
this.debug(
`Syncing of server interactions already in progress for user ${message.userId}, skipping`
);
return;
@@ -357,12 +347,12 @@ class SyncService {
this.updateInteractionCursor(message.userId, cursor);
}
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing server interactions for user ${message.userId}`
);
} finally {
this.logger.trace(
this.debug(
`Syncing of server interactions completed for user ${message.userId}`
);
@@ -372,7 +362,7 @@ class SyncService {
}
private async syncIncompleteTransactions(userId: string) {
this.logger.trace(`Syncing incomplete transactions for user ${userId}`);
this.debug(`Syncing incomplete transactions for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -384,7 +374,7 @@ class SyncService {
.execute();
if (incompleteTransactions.length === 0) {
this.logger.trace(
this.debug(
`No incomplete transactions found for user ${userId}, skipping`
);
return;
@@ -406,14 +396,12 @@ class SyncService {
.executeTakeFirst();
if (!workspace) {
this.logger.trace(`No workspace found for user ${userId}, skipping`);
this.debug(`No workspace found for user ${userId}, skipping`);
return;
}
if (!serverService.isAvailable(workspace.domain)) {
this.logger.trace(
`Server ${workspace.domain} is not available, skipping`
);
this.debug(`Server ${workspace.domain} is not available, skipping`);
return;
}
@@ -429,7 +417,7 @@ class SyncService {
for (const [nodeId, transactions] of Object.entries(groupedByNodeId)) {
try {
this.logger.trace(
this.debug(
`Syncing incomplete transactions for node ${nodeId} for user ${userId}`
);
@@ -442,7 +430,7 @@ class SyncService {
);
if (data.transactions.length === 0) {
this.logger.trace(
this.debug(
`No transactions found for node ${nodeId} for user ${userId}, deleting`
);
@@ -464,7 +452,7 @@ class SyncService {
);
if (!synced) {
this.logger.trace(
this.debug(
`Failed to sync transactions for node ${nodeId} for user ${userId}, incrementing retry count`
);
@@ -478,7 +466,7 @@ class SyncService {
)
.execute();
} else {
this.logger.trace(
this.debug(
`Successfully synced transactions for node ${nodeId} for user ${userId}, resetting retry count`
);
@@ -494,7 +482,7 @@ class SyncService {
.execute();
}
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing incomplete transactions for node ${nodeId} for user ${userId}`
);
@@ -503,7 +491,7 @@ class SyncService {
}
private async syncMissingNodes(userId: string) {
this.logger.trace(`Syncing missing nodes for user ${userId}`);
this.debug(`Syncing missing nodes for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -516,7 +504,7 @@ class SyncService {
.execute();
if (missingNodes.length === 0) {
this.logger.trace(`No missing nodes found for user ${userId}, skipping`);
this.debug(`No missing nodes found for user ${userId}, skipping`);
return;
}
@@ -536,22 +524,18 @@ class SyncService {
.executeTakeFirst();
if (!workspace) {
this.logger.trace(`No workspace found for user ${userId}, skipping`);
this.debug(`No workspace found for user ${userId}, skipping`);
return;
}
if (!serverService.isAvailable(workspace.domain)) {
this.logger.trace(
`Server ${workspace.domain} is not available, skipping`
);
this.debug(`Server ${workspace.domain} is not available, skipping`);
return;
}
for (const node of missingNodes) {
try {
this.logger.trace(
`Syncing missing node ${node.node_id} for user ${userId}`
);
this.debug(`Syncing missing node ${node.node_id} for user ${userId}`);
const { data } = await httpClient.get<GetNodeTransactionsOutput>(
`/v1/nodes/${workspace.workspace_id}/transactions/${node.node_id}`,
@@ -567,7 +551,7 @@ class SyncService {
data.transactions
);
} catch (error) {
this.logger.error(
this.debug(
error,
`Error syncing missing node ${node.node_id} for user ${userId}`
);
@@ -576,7 +560,7 @@ class SyncService {
}
private async checkForMissingNode(userId: string, nodeId: string) {
this.logger.trace(`Checking for missing node ${nodeId} for user ${userId}`);
this.debug(`Checking for missing node ${nodeId} for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -588,7 +572,7 @@ class SyncService {
.executeTakeFirst();
if (node) {
this.logger.trace(`Node ${nodeId} for user ${userId} found, skipping`);
this.debug(`Node ${nodeId} for user ${userId} found, skipping`);
return;
}
@@ -608,14 +592,12 @@ class SyncService {
.executeTakeFirst();
if (!workspace) {
this.logger.trace(`No workspace found for user ${userId}, skipping`);
this.debug(`No workspace found for user ${userId}, skipping`);
return;
}
if (!serverService.isAvailable(workspace.domain)) {
this.logger.trace(
`Server ${workspace.domain} is not available, skipping`
);
this.debug(`Server ${workspace.domain} is not available, skipping`);
return;
}
@@ -630,7 +612,7 @@ class SyncService {
await nodeService.replaceTransactions(userId, nodeId, data.transactions);
} catch (error) {
this.logger.error(
this.debug(
error,
`Error checking for missing node ${nodeId} for user ${userId}`
);
@@ -638,7 +620,7 @@ class SyncService {
}
private async sendLocalTransactions(userId: string) {
this.logger.trace(`Sending local pending transactions for user ${userId}`);
this.debug(`Sending local pending transactions for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -655,7 +637,7 @@ class SyncService {
return;
}
this.logger.trace(
this.debug(
`Sending ${unsyncedTransactions.length} local pending transactions for user ${userId}`
);
@@ -675,14 +657,14 @@ class SyncService {
.executeTakeFirst();
if (!workspace) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping sending local pending transactions`
);
return;
}
if (!serverService.isAvailable(workspace.domain)) {
this.logger.trace(
this.debug(
`Server ${workspace.domain} is not available, skipping sending local pending transactions`
);
return;
@@ -713,7 +695,7 @@ class SyncService {
}
if (syncedTransactionIds.length > 0) {
this.logger.trace(
this.debug(
`Marking ${syncedTransactionIds.length} local pending transactions as sent for user ${userId}`
);
@@ -726,7 +708,7 @@ class SyncService {
}
if (unsyncedTransactionIds.length > 0) {
this.logger.trace(
this.debug(
`Marking ${unsyncedTransactionIds.length} local pending transactions as failed for user ${userId}`
);
@@ -740,7 +722,7 @@ class SyncService {
}
private async sendLocalInteractions(userId: string) {
this.logger.trace(`Sending local pending interactions for user ${userId}`);
this.debug(`Sending local pending interactions for user ${userId}`);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
@@ -761,14 +743,14 @@ class SyncService {
.executeTakeFirst();
if (!workspace) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping sending local pending interactions`
);
return;
}
if (!serverService.isAvailable(workspace.domain)) {
this.logger.trace(
this.debug(
`Server ${workspace.domain} is not available, skipping sending local pending interactions`
);
return;
@@ -790,14 +772,14 @@ class SyncService {
.execute();
if (interactionEvents.length === 0) {
this.logger.trace(
this.debug(
`No local pending interactions found for user ${userId}, stopping sync`
);
hasMore = false;
break;
}
this.logger.trace(
this.debug(
`Sending ${interactionEvents.length} local pending interactions for user ${userId}`
);
@@ -841,7 +823,7 @@ class SyncService {
}
if (sentEventIds.length > 0) {
this.logger.trace(
this.debug(
`Marking ${sentEventIds.length} local pending interactions as sent for user ${userId}`
);
@@ -855,7 +837,7 @@ class SyncService {
}
private async requireNodeTransactions(userId: string) {
this.logger.trace(`Requiring node transactions for user ${userId}`);
this.debug(`Requiring node transactions for user ${userId}`);
const workspaceWithCursor = await databaseService.appDatabase
.selectFrom('workspaces as w')
@@ -870,7 +852,7 @@ class SyncService {
.executeTakeFirst();
if (!workspaceWithCursor) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping requiring node transactions`
);
return;
@@ -887,7 +869,7 @@ class SyncService {
}
private async requireCollaborations(userId: string) {
this.logger.trace(`Requiring collaborations for user ${userId}`);
this.debug(`Requiring collaborations for user ${userId}`);
const workspaceWithCursor = await databaseService.appDatabase
.selectFrom('workspaces as w')
@@ -902,7 +884,7 @@ class SyncService {
.executeTakeFirst();
if (!workspaceWithCursor) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping requiring collaborations`
);
return;
@@ -919,7 +901,7 @@ class SyncService {
}
private async requireCollaborationRevocations(userId: string) {
this.logger.trace(`Requiring collaboration revocations for user ${userId}`);
this.debug(`Requiring collaboration revocations for user ${userId}`);
const workspaceWithCursor = await databaseService.appDatabase
.selectFrom('workspaces as w')
@@ -929,7 +911,7 @@ class SyncService {
.executeTakeFirst();
if (!workspaceWithCursor) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping requiring collaboration revocations`
);
return;
@@ -946,7 +928,7 @@ class SyncService {
}
private async requireInteractions(userId: string) {
this.logger.trace(`Requiring interactions for user ${userId}`);
this.debug(`Requiring interactions for user ${userId}`);
const workspaceWithCursor = await databaseService.appDatabase
.selectFrom('workspaces as w')
@@ -961,7 +943,7 @@ class SyncService {
.executeTakeFirst();
if (!workspaceWithCursor) {
this.logger.trace(
this.debug(
`No workspace found for user ${userId}, skipping requiring interactions`
);
return;
@@ -978,7 +960,7 @@ class SyncService {
}
private async updateNodeTransactionCursor(userId: string, cursor: bigint) {
this.logger.trace(
this.debug(
`Updating node transaction cursor for user ${userId} to ${cursor}`
);
@@ -999,9 +981,7 @@ class SyncService {
}
private async updateCollaborationCursor(userId: string, cursor: bigint) {
this.logger.trace(
`Updating collaboration cursor for user ${userId} to ${cursor}`
);
this.debug(`Updating collaboration cursor for user ${userId} to ${cursor}`);
await databaseService.appDatabase
.insertInto('workspace_cursors')
@@ -1023,7 +1003,7 @@ class SyncService {
userId: string,
cursor: bigint
) {
this.logger.trace(
this.debug(
`Updating collaboration revocation cursor for user ${userId} to ${cursor}`
);
@@ -1044,9 +1024,7 @@ class SyncService {
}
private async updateInteractionCursor(userId: string, cursor: bigint) {
this.logger.trace(
`Updating interaction cursor for user ${userId} to ${cursor}`
);
this.debug(`Updating interaction cursor for user ${userId} to ${cursor}`);
await databaseService.appDatabase
.insertInto('workspace_cursors')

21
package-lock.json generated
View File

@@ -12,9 +12,11 @@
"apps/*"
],
"dependencies": {
"debug": "^4.3.7",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"@types/debug": "^4.1.12",
"@types/lodash-es": "^4.17.12",
"@typescript-eslint/eslint-plugin": "^8.16.0",
"eslint": "^8.57.1",
@@ -86,7 +88,6 @@
"lowlight": "^3.2.0",
"lucide-react": "^0.462.0",
"mime-types": "^2.1.35",
"pino": "^9.5.0",
"re-resizable": "^6.10.1",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -124,7 +125,6 @@
"@types/unzipper": "^0.10.10",
"autoprefixer": "^10.4.20",
"electron": "^33.2.1",
"pino-pretty": "^13.0.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"vite": "^6.0.1",
@@ -6036,6 +6036,16 @@
"@types/node": "*"
}
},
"node_modules/@types/debug": {
"version": "4.1.12",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
"integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/ms": "*"
}
},
"node_modules/@types/diff": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@types/diff/-/diff-6.0.0.tgz",
@@ -6217,6 +6227,13 @@
"license": "MIT",
"optional": true
},
"node_modules/@types/ms": {
"version": "0.7.34",
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz",
"integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/multer": {
"version": "1.4.12",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.12.tgz",

View File

@@ -25,6 +25,7 @@
"format": "prettier --write ."
},
"devDependencies": {
"@types/debug": "^4.1.12",
"@types/lodash-es": "^4.17.12",
"@typescript-eslint/eslint-plugin": "^8.16.0",
"eslint": "^8.57.1",
@@ -37,6 +38,7 @@
"vitest": "^2.1.6"
},
"dependencies": {
"debug": "^4.3.7",
"lodash-es": "^4.17.21"
}
}