Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(database): let SQLite writes wait out an online backup

Yudhi Armyndharis244c59a16321
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index 82a6983eb..1e96d2e5d 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -629,8 +629,9 @@ curl -H "X-API-Key: $API_KEY" http://localhost:2785/api/health
**Trigger:** Daily schedule, before maintenance, before upgrade
-**Impact:** None for the databases, which are snapshotted consistently online (`sqlite3 .backup`,
-`pg_dump`). Engine authentication state (`sessions/`, `baileys/`) is copied while the engines write
+**Impact:** The databases are snapshotted consistently online (`sqlite3 .backup`, `pg_dump`). On
+SQLite, app writes wait while each database file is copied, and fail if the copy outlasts their 30 s
+busy timeout. Engine authentication state (`sessions/`, `baileys/`) is copied while the engines write
it, so a restored session can need re-pairing; for a copy that is consistent by construction, stop
the sessions first (`POST /api/sessions/:id/stop`), or stop the container and archive the volume.
A stopped session stays down across restarts, even with `AUTO_START_SESSIONS=true`, so start each
diff --git a/src/app.module.ts b/src/app.module.ts
index 29fbcc1ae..72f02509f 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -10,7 +10,7 @@ import { createThrottlerRedisClient } from './common/throttler/throttler-redis.c
import configuration from './config/configuration';
import { validateEnv } from './config/env.validation';
import { createBootDataSource } from './database/pg-boot-migrations';
-import { createMainDataSource, mainConnectionOptions } from './database/main-connection';
+import { createMainDataSource, mainConnectionOptions, SQLITE_BUSY_TIMEOUT_MS } from './database/main-connection';
import { SessionModule } from './modules/session/session.module';
import { MessageModule } from './modules/message/message.module';
import { TemplateModule } from './modules/template/template.module';
@@ -223,6 +223,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
name: 'data',
type: 'better-sqlite3' as const,
database: configService.get<string>('dataDatabase.database', './data/openwa.sqlite'),
+ timeout: SQLITE_BUSY_TIMEOUT_MS,
synchronize,
migrationsRun: !synchronize,
};
diff --git a/src/database/main-connection.ts b/src/database/main-connection.ts
index 3955c2277..6d32002de 100644
--- a/src/database/main-connection.ts
+++ b/src/database/main-connection.ts
@@ -16,6 +16,13 @@ export class MainSchemaMismatchError extends Error {
}
}
+/**
+ * How long a runtime SQLite write waits on a lock before failing with SQLITE_BUSY. scripts/backup.sh
+ * holds a read transaction for each file's whole online copy and blocks writes until it ends, so
+ * this matches the backup's own `.timeout 30000` instead of better-sqlite3's 5 s default.
+ */
+export const SQLITE_BUSY_TIMEOUT_MS = 30_000;
+
/** Retrying cannot fix a schema mismatch, so it fails the boot at once instead of nine times. */
export const retryMainConnection = (err: unknown): boolean => !(err instanceof MainSchemaMismatchError);
@@ -36,6 +43,7 @@ export function mainConnectionOptions(
name: 'main',
type: 'better-sqlite3',
database: configService.get<string>('database.database', './data/main.sqlite'),
+ timeout: SQLITE_BUSY_TIMEOUT_MS,
entities: [
join(__dirname, '..', 'modules/auth/**/*.entity{.ts,.js}'),
join(__dirname, '..', 'modules/audit/**/*.entity{.ts,.js}'),
diff --git a/src/database/sqlite-busy-timeout.spec.ts b/src/database/sqlite-busy-timeout.spec.ts
new file mode 100644
index 000000000..6a1e8269c
--- /dev/null
+++ b/src/database/sqlite-busy-timeout.spec.ts
@@ -0,0 +1,56 @@
+import 'reflect-metadata';
+import type { ConfigService } from '@nestjs/config';
+import { mainConnectionOptions } from './main-connection';
+import { AppModule } from '../app.module';
+
+interface FactoryProvider {
+ provide?: unknown;
+ useFactory?: (config: ConfigService) => Record<string, unknown>;
+}
+interface DynamicModuleLike {
+ imports?: DynamicModuleLike[];
+ providers?: FactoryProvider[];
+}
+
+const config = (values: Record<string, unknown> = {}): ConfigService =>
+ ({ get: (key: string, fallback?: unknown) => (key in values ? values[key] : fallback) }) as unknown as ConfigService;
+
+/**
+ * Every TypeORM options factory AppModule registers, found through its dynamic module imports. Only the
+ * `TypeOrmModuleOptions` providers are taken: the DataSource factories beside them open a real connection.
+ */
+function typeOrmOptionFactories(): Array<(config: ConfigService) => Record<string, unknown>> {
+ const found: Array<(config: ConfigService) => Record<string, unknown>> = [];
+ const visit = (mod: DynamicModuleLike): void => {
+ for (const p of mod.providers ?? []) {
+ if (p?.provide === 'TypeOrmModuleOptions' && typeof p.useFactory === 'function') found.push(p.useFactory);
+ }
+ for (const child of mod.imports ?? []) if (child && typeof child === 'object') visit(child);
+ };
+ for (const imported of (Reflect.getMetadata('imports', AppModule) as DynamicModuleLike[]) ?? []) {
+ if (imported && typeof imported === 'object') visit(imported);
+ }
+ return found;
+}
+
+// scripts/backup.sh holds a read transaction for the whole online copy of each SQLite file, which
+// blocks app writes until it ends. better-sqlite3's 5 s default busy timeout failed those writes on
+// a copy that ran longer, so both runtime connections wait as long as the backup's own timeout.
+describe('SQLite busy timeout', () => {
+ it('lets main-connection writes wait out an online backup', () => {
+ expect(mainConnectionOptions(config())).toMatchObject({ type: 'better-sqlite3', timeout: 30_000 });
+ });
+
+ it('lets data-connection writes wait out an online backup', () => {
+ const data = typeOrmOptionFactories()
+ .map(factory => {
+ try {
+ return factory(config({ 'dataDatabase.type': 'sqlite' }));
+ } catch {
+ return null;
+ }
+ })
+ .find(options => options?.name === 'data');
+ expect(data).toMatchObject({ type: 'better-sqlite3', timeout: 30_000 });
+ });
+});