Skip to content

Commit

Permalink
Add db optimize pragma
Browse files Browse the repository at this point in the history
Signed-off-by: m4rc3l05 <[email protected]>
  • Loading branch information
M4RC3L05 committed Jun 8, 2024
1 parent f91909a commit 93b7562
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/apps/api/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { type CustomDatabase, makeDatabase } from "#src/database/mod.ts";
import { makeApp } from "#src/apps/api/app.ts";
import config from "config";
import FeedService from "#src/services/feed-service.ts";
import { Cron } from "@m4rc3l05/cron";

const log = makeLogger("api");
const { host, port } = config.get("apps.api");
Expand All @@ -15,7 +16,46 @@ gracefulShutdown({ processLifecycle, log });
processLifecycle.registerService({
name: "db",
boot: () => makeDatabase(),
shutdown: (db) => db.close(),
shutdown: (db) => {
// Improve performance.
db.exec("pragma analysis_limit = 400");
db.exec("pragma optimize");

db.close();
},
});

processLifecycle.registerService({
name: "db-optimise",
boot: (pl) => {
const db = pl.getService<CustomDatabase>("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({
Expand Down
1 change: 1 addition & 0 deletions src/database/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 93b7562

Please sign in to comment.