Skip to content

Build your personal knowledge base with Trilium Notes

chore(standalone): start implementing backup service

Elian Doran065afd02145a
diff --git a/apps/client-standalone/src/lightweight/backup_provider.ts b/apps/client-standalone/src/lightweight/backup_provider.ts
index a4dd102538..2c93b6fc2e 100644
--- a/apps/client-standalone/src/lightweight/backup_provider.ts
+++ b/apps/client-standalone/src/lightweight/backup_provider.ts
@@ -1,20 +1,175 @@
-import { BackupService } from "@triliumnext/core";
+import type { DatabaseBackup } from "@triliumnext/commons";
+import { BackupService, getSql } from "@triliumnext/core";
+
+const BACKUP_DIR_NAME = "backups";
+const BACKUP_FILE_PATTERN = /^backup-.*\.db$/;
/**
- * No-op backup service for standalone.
- * Backups are not yet implemented in standalone mode.
+ * Standalone backup service using OPFS (Origin Private File System).
+ * Stores database backups as serialized byte arrays in OPFS.
+ * Falls back to no-op behavior when OPFS is not available (e.g., in tests).
*/
-export default class NoopBackupService extends BackupService {
+export default class StandaloneBackupService extends BackupService {
+ private backupDir: FileSystemDirectoryHandle | null = null;
+ private opfsAvailable: boolean | null = null;
+
+ private isOpfsAvailable(): boolean {
+ if (this.opfsAvailable === null) {
+ this.opfsAvailable = typeof navigator !== "undefined"
+ && navigator.storage
+ && typeof navigator.storage.getDirectory === "function";
+ }
+ return this.opfsAvailable;
+ }
+
+ private async ensureBackupDirectory(): Promise<FileSystemDirectoryHandle | null> {
+ if (!this.isOpfsAvailable()) {
+ return null;
+ }
+
+ if (!this.backupDir) {
+ const root = await navigator.storage.getDirectory();
+ this.backupDir = await root.getDirectoryHandle(BACKUP_DIR_NAME, { create: true });
+ }
+ return this.backupDir;
+ }
+
override async backupNow(name: string): Promise<string> {
- console.warn("Backup not available in standalone mode.");
- return `backup-${name}-${new Date().toISOString()}.db`;
+ const fileName = `backup-${name}.db`;
+
+ // Check if OPFS is available
+ if (!this.isOpfsAvailable()) {
+ console.warn(`[Backup] OPFS not available, skipping backup: ${fileName}`);
+ return `/${BACKUP_DIR_NAME}/${fileName}`;
+ }
+
+ try {
+ const dir = await this.ensureBackupDirectory();
+ if (!dir) {
+ console.warn(`[Backup] Backup directory not available, skipping: ${fileName}`);
+ return `/${BACKUP_DIR_NAME}/${fileName}`;
+ }
+
+ // Serialize the database
+ const data = getSql().serialize();
+
+ // Write to OPFS (convert to Blob for compatibility)
+ const fileHandle = await dir.getFileHandle(fileName, { create: true });
+ const writable = await fileHandle.createWritable();
+ await writable.write(new Blob([data]));
+ await writable.close();
+
+ console.log(`[Backup] Created backup: ${fileName} (${data.byteLength} bytes)`);
+ return `/${BACKUP_DIR_NAME}/${fileName}`;
+ } catch (error) {
+ console.error(`[Backup] Failed to create backup ${fileName}:`, error);
+ // Don't throw - backup failure shouldn't block operations
+ return `/${BACKUP_DIR_NAME}/${fileName}`;
+ }
}
override regularBackup(): void {
- // No-op - scheduled backups not available in standalone
+ // For standalone, we don't implement scheduled backups yet
+ // since we don't have easy access to the options service for
+ // checking daily/weekly/monthly settings.
+ // Manual backups via backupNow() still work.
}
- override getExistingBackups(): [] {
+ override getExistingBackups(): DatabaseBackup[] {
+ // This method is synchronous in the interface, but OPFS is async.
+ // Return empty array - the UI can use an async method if needed.
+ // A future improvement could cache the backup list.
return [];
}
+
+ /**
+ * Async version of getExistingBackups for use in standalone UI.
+ */
+ async getExistingBackupsAsync(): Promise<DatabaseBackup[]> {
+ if (!this.isOpfsAvailable()) {
+ return [];
+ }
+
+ try {
+ const dir = await this.ensureBackupDirectory();
+ if (!dir) {
+ return [];
+ }
+
+ const backups: DatabaseBackup[] = [];
+
+ for await (const [name, handle] of dir.entries()) {
+ if (handle.kind !== "file" || !BACKUP_FILE_PATTERN.test(name)) {
+ continue;
+ }
+
+ // OPFS doesn't provide mtime, so we parse from filename or use current time
+ const file = await (handle as FileSystemFileHandle).getFile();
+ backups.push({
+ fileName: name,
+ filePath: `/${BACKUP_DIR_NAME}/${name}`,
+ mtime: new Date(file.lastModified)
+ });
+ }
+
+ // Sort by modification time, newest first
+ backups.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
+ return backups;
+ } catch (error) {
+ console.error("[Backup] Failed to list backups:", error);
+ return [];
+ }
+ }
+
+ /**
+ * Delete a backup by filename.
+ */
+ async deleteBackup(fileName: string): Promise<void> {
+ if (!this.isOpfsAvailable()) {
+ return;
+ }
+
+ try {
+ const dir = await this.ensureBackupDirectory();
+ if (!dir) {
+ return;
+ }
+ await dir.removeEntry(fileName);
+ console.log(`[Backup] Deleted backup: ${fileName}`);
+ } catch (error) {
+ console.error(`[Backup] Failed to delete backup ${fileName}:`, error);
+ }
+ }
+
+ /**
+ * Download a backup to the user's device.
+ */
+ async downloadBackup(fileName: string): Promise<void> {
+ if (!this.isOpfsAvailable()) {
+ throw new Error("OPFS not available - cannot download backup");
+ }
+
+ try {
+ const dir = await this.ensureBackupDirectory();
+ if (!dir) {
+ throw new Error("Backup directory not available");
+ }
+
+ const fileHandle = await dir.getFileHandle(fileName);
+ const file = await fileHandle.getFile();
+ const data = await file.arrayBuffer();
+
+ // Create download link
+ const blob = new Blob([data], { type: "application/x-sqlite3" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = fileName;
+ a.click();
+ URL.revokeObjectURL(url);
+ } catch (error) {
+ console.error(`[Backup] Failed to download backup ${fileName}:`, error);
+ throw error;
+ }
+ }
}
diff --git a/apps/client-standalone/src/local-server-worker.ts b/apps/client-standalone/src/local-server-worker.ts
index e6bd9265f1..bea560bd1c 100644
--- a/apps/client-standalone/src/local-server-worker.ts
+++ b/apps/client-standalone/src/local-server-worker.ts
@@ -59,7 +59,7 @@ let BrowserZipProvider: typeof import('./lightweight/zip_provider').default;
let FetchRequestProvider: typeof import('./lightweight/request_provider').default;
let StandalonePlatformProvider: typeof import('./lightweight/platform_provider').default;
let StandaloneLogService: typeof import('./lightweight/log_provider').default;
-let NoopBackupService: typeof import('./lightweight/backup_provider').default;
+let StandaloneBackupService: typeof import('./lightweight/backup_provider').default;
let translationProvider: typeof import('./lightweight/translation_provider').default;
let createConfiguredRouter: typeof import('./lightweight/browser_routes').createConfiguredRouter;
@@ -114,7 +114,7 @@ async function loadModules(): Promise<void> {
FetchRequestProvider = requestModule.default;
StandalonePlatformProvider = platformModule.default;
StandaloneLogService = logModule.default;
- NoopBackupService = backupModule.default;
+ StandaloneBackupService = backupModule.default;
translationProvider = translationModule.default;
createConfiguredRouter = routesModule.createConfiguredRouter;
@@ -176,7 +176,7 @@ async function initialize(): Promise<void> {
request: new FetchRequestProvider(),
platform: new StandalonePlatformProvider(queryString),
log: logService,
- backup: new NoopBackupService(),
+ backup: new StandaloneBackupService(),
translations: translationProvider,
schema: schemaModule.default,
getDemoArchive: async () => {
diff --git a/apps/client-standalone/src/test_setup.ts b/apps/client-standalone/src/test_setup.ts
index 0b93dd0c12..1191d785ab 100644
--- a/apps/client-standalone/src/test_setup.ts
+++ b/apps/client-standalone/src/test_setup.ts
@@ -8,7 +8,7 @@ import HappyDomHtmlParser from "happy-dom/lib/html-parser/HTMLParser.js";
import serverEnTranslations from "../../server/src/assets/translations/en/server.json";
import { beforeAll } from "vitest";
-import NoopBackupService from "./lightweight/backup_provider.js";
+import StandaloneBackupService from "./lightweight/backup_provider.js";
import BrowserExecutionContext from "./lightweight/cls_provider.js";
import BrowserCryptoProvider from "./lightweight/crypto_provider.js";
import StandalonePlatformProvider from "./lightweight/platform_provider.js";
@@ -130,7 +130,7 @@ beforeAll(async () => {
});
},
platform: new StandalonePlatformProvider(""),
- backup: new NoopBackupService(),
+ backup: new StandaloneBackupService(),
schema: schemaSql,
dbConfig: {
provider: sqlProvider,
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 497ce0cc7e..19d4a1313b 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -11,6 +11,7 @@ import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import tray from "@triliumnext/server/src/services/tray.js";
import windowService from "@triliumnext/server/src/services/window.js";
import WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";
+import ServerBackupService from "@triliumnext/server/src/backup_provider.js";
import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";
import { app, BrowserWindow,globalShortcut } from "electron";
@@ -150,6 +151,7 @@ async function main() {
// both source and bundled-production modes.
getDemoArchive: async () => fs.readFileSync(path.join(RESOURCE_DIR, "db", "demo.zip")),
inAppHelp: new NodejsInAppHelpProvider(),
+ backup: new ServerBackupService(),
extraAppInfo: {
nodeVersion: process.version,
dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)
diff --git a/apps/server/src/sql_provider.ts b/apps/server/src/sql_provider.ts
index 8195e08060..a17a23a396 100644
--- a/apps/server/src/sql_provider.ts
+++ b/apps/server/src/sql_provider.ts
@@ -46,6 +46,11 @@ export default class BetterSqlite3Provider implements DatabaseProvider {
this.dbConnection?.backup(destinationFile);
}
+ serialize(): Uint8Array {
+ // Server uses backup() for file-based backups, serialize() is only needed for standalone (OPFS)
+ throw new Error("serialize() is not implemented on the server - use backup() instead");
+ }
+
prepare(query: string): Statement {
if (!this.dbConnection) throw new Error("DB not open.");
// Cast is safe: better-sqlite3 only returns bigint when safeIntegers() is enabled, which we don't use.
diff --git a/packages/trilium-core/src/services/sql/sql.ts b/packages/trilium-core/src/services/sql/sql.ts
index 5d9a655417..de7ee6e03c 100644
--- a/packages/trilium-core/src/services/sql/sql.ts
+++ b/packages/trilium-core/src/services/sql/sql.ts
@@ -373,6 +373,18 @@ export class SqlService {
await this.dbConnection.backup(targetFilePath);
}
+ /**
+ * Serialize the database to a byte array.
+ * Only available with browser-based providers.
+ * @throws Error if the provider doesn't support serialization
+ */
+ serialize(): Uint8Array {
+ if (!this.dbConnection.serialize) {
+ throw new Error("Database provider does not support serialization");
+ }
+ return this.dbConnection.serialize();
+ }
+
disableSlowQueryLogging<T>(cb: () => T) {
const orig = isSlowQueryLoggingDisabled();
diff --git a/packages/trilium-core/src/services/sql/types.ts b/packages/trilium-core/src/services/sql/types.ts
index edbbc1a3b6..786c7e7bbf 100644
--- a/packages/trilium-core/src/services/sql/types.ts
+++ b/packages/trilium-core/src/services/sql/types.ts
@@ -23,6 +23,11 @@ export interface DatabaseProvider {
loadFromMemory(): void;
loadFromBuffer(buffer: Uint8Array): void;
backup(destinationFile: string): void;
+ /**
+ * Serialize the database to a byte array.
+ * Optional - only implemented by browser-based providers.
+ */
+ serialize?(): Uint8Array;
prepare(query: string): Statement;
transaction<T>(func: (statement: Statement) => T): Transaction;
get inTransaction(): boolean;