From 907e09682bdfc073415860fc124e251cb6169551 Mon Sep 17 00:00:00 2001 From: Julien Froidefond Date: Thu, 6 Mar 2025 21:41:24 +0100 Subject: [PATCH] fix: little bugs and refacto debug service --- docker-compose.yml | 2 + src/app/login/page.tsx | 4 +- src/i18n/messages/en/common.json | 4 +- src/i18n/messages/fr/common.json | 3 +- src/lib/mongodb.ts | 1 + src/lib/services/debug.service.ts | 132 ++++++++++++----------- src/lib/services/server-cache.service.ts | 5 + 7 files changed, 84 insertions(+), 67 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 2b53bbc..8ebd70d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -48,6 +48,8 @@ services: limits: cpus: "0.5" memory: 512M + ports: + - "27017:27017" command: ["mongod", "--auth", "--bind_ip_all"] networks: diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index d984e41..bea9868 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -13,7 +13,7 @@ export const metadata: Metadata = { description: "Connectez-vous à votre compte StripStream", }; -function LoginPage({ searchParams }: PageProps) { - return ; +async function LoginPage({ searchParams }: PageProps) { + return ; } export default withPageTiming("LoginPage", LoginPage); diff --git a/src/i18n/messages/en/common.json b/src/i18n/messages/en/common.json index 86f31cb..9f64691 100644 --- a/src/i18n/messages/en/common.json +++ b/src/i18n/messages/en/common.json @@ -301,7 +301,9 @@ "SERIES_NO_BOOKS_FOUND": "No books found in the series", "BOOK_PAGES_FETCH_ERROR": "Error fetching book pages", - "GENERIC_ERROR": "An error occurred" + "GENERIC_ERROR": "An error occurred", + + "MONGODB_CONNECTION_FAILED": "MongoDB connection failed" }, "reader": { "controls": { diff --git a/src/i18n/messages/fr/common.json b/src/i18n/messages/fr/common.json index 703ba10..7921615 100644 --- a/src/i18n/messages/fr/common.json +++ b/src/i18n/messages/fr/common.json @@ -299,7 +299,8 @@ "SERIES_NO_BOOKS_FOUND": "Aucun livre trouvé dans la série", "BOOK_PAGES_FETCH_ERROR": "Erreur lors de la récupération des pages du livre", - "GENERIC_ERROR": "Une erreur est survenue" + "GENERIC_ERROR": "Une erreur est survenue", + "MONGODB_CONNECTION_FAILED": "Erreur lors de la connexion à MongoDB" }, "reader": { "controls": { diff --git a/src/lib/mongodb.ts b/src/lib/mongodb.ts index 2532ff5..4a41f4a 100644 --- a/src/lib/mongodb.ts +++ b/src/lib/mongodb.ts @@ -41,6 +41,7 @@ async function connectDB(): Promise { try { cached.conn = await cached.promise; } catch (e) { + console.error("Error connecting to MongoDB:", e); cached.promise = null; throw new AppError(ERROR_CODES.MONGODB.CONNECTION_FAILED, {}, e); } diff --git a/src/lib/services/debug.service.ts b/src/lib/services/debug.service.ts index 922f18c..70bdc17 100644 --- a/src/lib/services/debug.service.ts +++ b/src/lib/services/debug.service.ts @@ -46,36 +46,70 @@ export class DebugService { } } + private static async isDebugEnabled(): Promise { + const user = await AuthServerService.getCurrentUser(); + if (!user) { + return false; + } + const preferences = await PreferencesService.getPreferences(); + return preferences.debug === true; + } + + private static async readLogs(filePath: string): Promise { + try { + const content = await fs.readFile(filePath, "utf-8"); + return JSON.parse(content); + } catch { + return []; + } + } + + private static async writeLogs(filePath: string, logs: RequestTiming[]): Promise { + const trimmedLogs = logs.slice(-99); + await fs.writeFile(filePath, JSON.stringify(trimmedLogs, null, 2)); + } + + private static createTiming( + url: string, + startTime: number, + endTime: number, + fromCache: boolean, + additionalData?: Partial + ): RequestTiming { + return { + url, + startTime, + endTime, + duration: endTime - startTime, + timestamp: new Date().toISOString(), + fromCache, + ...additionalData, + }; + } + static async logRequest(timing: Omit) { try { + if (!(await this.isDebugEnabled())) return; + const userId = await this.getCurrentUserId(); - const preferences = await PreferencesService.getPreferences(); - if (!preferences.debug) { - return; - } await this.ensureDebugDir(); const filePath = this.getLogFilePath(userId); - let logs: RequestTiming[] = []; - try { - const content = await fs.readFile(filePath, "utf-8"); - logs = JSON.parse(content); - } catch { - // Le fichier n'existe pas encore ou est vide - } + const logs = await this.readLogs(filePath); + const newTiming = this.createTiming( + timing.url, + timing.startTime, + timing.endTime, + timing.fromCache, + { + cacheType: timing.cacheType, + mongoAccess: timing.mongoAccess, + pageRender: timing.pageRender, + } + ); - const newTiming: RequestTiming = { - ...timing, - duration: timing.endTime - timing.startTime, - timestamp: new Date().toISOString(), - }; - - // Garde les 100 dernières requêtes - logs = [...logs.slice(-99), newTiming]; - - await fs.writeFile(filePath, JSON.stringify(logs, null, 2)); + await this.writeLogs(filePath, [...logs, newTiming]); } catch (error) { - // On ignore les erreurs de logging mais on les trace quand même console.error("Erreur lors de l'enregistrement du log:", error); } } @@ -84,12 +118,9 @@ export class DebugService { try { const userId = await this.getCurrentUserId(); const filePath = this.getLogFilePath(userId); - const content = await fs.readFile(filePath, "utf-8"); - return JSON.parse(content); + return await this.readLogs(filePath); } catch (error) { - if (error instanceof AppError) { - throw error; - } + if (error instanceof AppError) throw error; return []; } } @@ -98,53 +129,28 @@ export class DebugService { try { const userId = await this.getCurrentUserId(); const filePath = this.getLogFilePath(userId); - await fs.writeFile(filePath, "[]"); + await this.writeLogs(filePath, []); } catch (error) { - if (error instanceof AppError) { - throw error; - } - // On ignore les autres erreurs si le fichier n'existe pas + if (error instanceof AppError) throw error; } } static async logPageRender(page: string, duration: number) { try { + if (!(await this.isDebugEnabled())) return; + const userId = await this.getCurrentUserId(); - const preferences = await PreferencesService.getPreferences(); - if (!preferences.debug) { - return; - } await this.ensureDebugDir(); const filePath = this.getLogFilePath(userId); - let logs: RequestTiming[] = []; - try { - const content = await fs.readFile(filePath, "utf-8"); - logs = JSON.parse(content); - } catch { - // Le fichier n'existe pas encore ou est vide - } - + const logs = await this.readLogs(filePath); const now = performance.now(); - const newTiming: RequestTiming = { - url: `Page Render: ${page}`, - startTime: now - duration, - endTime: now, - duration, - timestamp: new Date().toISOString(), - fromCache: false, - pageRender: { - page, - duration, - }, - }; + const newTiming = this.createTiming(`Page Render: ${page}`, now - duration, now, false, { + pageRender: { page, duration }, + }); - // Garde les 100 dernières requêtes - logs = [...logs.slice(-99), newTiming]; - - await fs.writeFile(filePath, JSON.stringify(logs, null, 2)); + await this.writeLogs(filePath, [...logs, newTiming]); } catch (error) { - // On ignore les erreurs de logging mais on les trace quand même console.error("Erreur lors de l'enregistrement du log de rendu:", error); } } @@ -152,10 +158,10 @@ export class DebugService { static async measureMongoOperation(operation: string, func: () => Promise): Promise { const startTime = performance.now(); try { - const preferences = await PreferencesService.getPreferences(); - if (!preferences.debug) { + if (!(await this.isDebugEnabled())) { return func(); } + const result = await func(); const endTime = performance.now(); diff --git a/src/lib/services/server-cache.service.ts b/src/lib/services/server-cache.service.ts index fbd5d76..3445cf2 100644 --- a/src/lib/services/server-cache.service.ts +++ b/src/lib/services/server-cache.service.ts @@ -45,6 +45,11 @@ class ServerCacheService { private async initializeCacheMode(): Promise { try { + const user = await AuthServerService.getCurrentUser(); + if (!user) { + this.setCacheMode("memory"); + return; + } const preferences = await PreferencesService.getPreferences(); this.setCacheMode(preferences.cacheMode); } catch (error) {