diff --git a/src/apps/api/main.ts b/src/apps/api/main.ts index 822d1e6..6be6786 100644 --- a/src/apps/api/main.ts +++ b/src/apps/api/main.ts @@ -1,3 +1,4 @@ +import { Cron } from "@m4rc3l05/cron"; import { ProcessLifecycle } from "@m4rc3l05/process-lifecycle"; import { makeLogger } from "#src/common/logger/mod.ts"; import { gracefulShutdown } from "#src/common/process/mod.ts"; @@ -17,6 +18,39 @@ processLifecycle.registerService({ shutdown: (db) => db.close(), }); +processLifecycle.registerService({ + name: "db-optimise", + boot: (pl) => { + const db = pl.getService("db"); + const cronInstance = new Cron((signal) => { + log.info("DB optimize runing"); + + try { + db.exec("pragma optimize"); + + log.info("DB optimize completed"); + } catch (error) { + log.error("DB optimize failed", { error }); + } + + if (!signal.aborted) { + log.info(`Next db optimize at ${cronInstance.nextAt()}`); + } + }, { + when: "0 * * * *", + timezone: "UTC", + tickerTimeout: 300, + }); + + log.info(`Next db optimize at ${cronInstance.nextAt()}`); + + cronInstance.start(); + + return cronInstance; + }, + shutdown: (cron) => cron.stop(), +}); + processLifecycle.registerService({ name: "api", boot: (pl) => { diff --git a/src/database/mod.ts b/src/database/mod.ts index 86cf0ba..c4e7fa7 100644 --- a/src/database/mod.ts +++ b/src/database/mod.ts @@ -81,6 +81,7 @@ export const makeDatabase = () => { db.exec("pragma temp_store = MEMORY"); // 4096 page_size * 10000 pages (cache_size) ≃ 40MB db.exec("pragma cache_size = 10000"); + db.exec("pragma optimize = 0x10002"); db.function("uuid_v4", () => globalThis.crypto.randomUUID()); return db;