Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/backup import: fix some issues
Adorian Doran873553ca3e9e
diff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.tsindex 5e37a95cb9..477ef91e49 100644--- a/apps/server/src/routes/api/setup_restore.ts+++ b/apps/server/src/routes/api/setup_restore.ts@@ -6,6 +6,7 @@ import type ServerBackupService from "../../backup_provider.js";import { getRestoreProgress, type RestoreProgress, type RestoreRequest } from "../../services/database_restore.js";import {backupUpload,+ beginBackupUpload,beginRestore,discardPendingBackup,pendingRestoreRequest@@ -25,7 +26,7 @@ import {*/async function beginUpload(req: Request) {- return await backupUpload.begin(req);+ return await beginBackupUpload(req);}async function uploadChunk(req: Request) {diff --git a/apps/server/src/services/chunked_upload.spec.ts b/apps/server/src/services/chunked_upload.spec.tsindex 1c26595537..d23bf13743 100644--- a/apps/server/src/services/chunked_upload.spec.ts+++ b/apps/server/src/services/chunked_upload.spec.ts@@ -143,6 +143,39 @@ describe("chunked upload: the offset rule", () => {await expect(upload.status(sessionRequest(uploadId))).rejects.toThrow(/No such upload/);});+ it("cuts an oversized body off as it is written, rather than measuring it once it is on disk", async () => {+ // Nothing authenticates the caller during setup, so a declared size that the body then+ // ignores must stop at the declared size: the check cannot wait until the disk is full.+ const { upload } = uploadService({ maxTotalBytes: 1024 * 1024 });+ const { uploadId } = await upload.begin(beginRequest(8));+ const written: number[] = [];+ const flood = new Readable({+ read() {+ // Far more than was declared, and the stream keeps offering it until it is stopped.+ written.push(64 * 1024);+ this.push(Buffer.alloc(64 * 1024));+ }+ });++ await expect(upload.chunk(chunkRequest(uploadId, 0, flood))).rejects.toThrow(/more bytes than it declared/);++ // Whatever was let through, it is bounded by what was declared, not by what was sent.+ expect(fs.existsSync(partialPath(tempRoot, uploadId))).toBe(false);+ expect(written.reduce((total, size) => total + size, 0)).toBeLessThan(1024 * 1024);+ });++ it("keeps what the declared size allows and refuses only the byte past it", async () => {+ const { upload } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(8));++ // Exactly the allowance, in two chunks, is not an overshoot.+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4, 1)));+ const status = await upload.chunk(chunkRequest(uploadId, 4, Buffer.alloc(4, 2)));++ expect(status.receivedBytes).toBe(8);+ await expect(upload.finish(sessionRequest(uploadId))).resolves.toBeTruthy();+ });+it("counts what reached the disk when a chunk breaks partway, and resumes from there", async () => {const { upload } = uploadService({ maxTotalBytes: 4096 });const content = Buffer.alloc(2048, 3);@@ -236,6 +269,59 @@ describe("chunked upload: starting and ending a session", () => {});});+describe("chunked upload: telling the consumer a session came to nothing", () => {+ /** An upload that records every ending its consumer is told about. */+ function watchedService(overrides: Partial<ChunkedUploadConfig<string>> = {}) {+ const discarded = { count: 0 };+ const { upload } = uploadService({ onSessionDiscarded: () => discarded.count++, ...overrides });++ return { upload, discarded };+ }++ it("says so when an upload expires, which has no caller of its own to fail", async () => {+ const { upload, discarded } = watchedService({ sessionTtlMs: 1 });+ await upload.begin(beginRequest(8));++ await new Promise((resolve) => setTimeout(resolve, 5));+ await upload.sweep();++ expect(discarded.count).toBe(1);+ });++ it("says so when an upload is abandoned or contradicts its declared size", async () => {+ const { upload, discarded } = watchedService();+ const first = await upload.begin(beginRequest(8));+ await upload.abort(sessionRequest(first.uploadId));++ const second = await upload.begin(beginRequest(4));+ await expect(upload.chunk(chunkRequest(second.uploadId, 0, Buffer.alloc(8)))).rejects.toThrow();++ expect(discarded.count).toBe(2);+ });++ it("says so when the consumer itself refuses the finished file", async () => {+ const { upload, discarded } = watchedService({+ onComplete: async () => { throw new Error("not a database"); }+ });+ const { uploadId } = await upload.begin(beginRequest(4));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ await expect(upload.finish(sessionRequest(uploadId))).rejects.toThrow("not a database");++ expect(discarded.count).toBe(1);+ });++ it("stays quiet when the upload becomes what it was for", async () => {+ const { upload, discarded } = watchedService();+ const { uploadId } = await upload.begin(beginRequest(4));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));+ await upload.finish(sessionRequest(uploadId));++ // Nothing was set aside in vain, so nothing is put back.+ expect(discarded.count).toBe(0);+ });+});+describe("chunked upload: sweeping", () => {it("drops a session that has gone quiet for too long, and frees its slot", async () => {const { upload } = uploadService({ sessionTtlMs: 1 });diff --git a/apps/server/src/services/chunked_upload.ts b/apps/server/src/services/chunked_upload.tsindex c68d560fbd..94884bddcc 100644--- a/apps/server/src/services/chunked_upload.ts+++ b/apps/server/src/services/chunked_upload.ts@@ -4,6 +4,7 @@ import type { Request } from "express";import { createWriteStream } from "fs";import fsp from "fs/promises";import path from "path";+import { Transform, type TransformCallback } from "stream";import { pipeline } from "stream/promises";/**@@ -75,6 +76,14 @@ export interface ChunkedUploadConfig<T> {requireFreeSpace?: boolean;/** Called once the file is complete. See {@link CompletedUpload} on ownership. */onComplete(upload: CompletedUpload): Promise<T>;+ /**+ * Called when a session ends without producing anything: expired, aborted, refused for+ * contradicting its declared size, or completed but rejected by {@link onComplete}.+ *+ * For a consumer that set something aside for the upload's sake, which nothing would otherwise+ * put back: an expiry happens on a timer, with no request to fail and nobody to tell.+ */+ onSessionDiscarded?(): void;}/** What a client is told about a session, whether it is starting one or resuming one. */@@ -182,19 +191,30 @@ export function createChunkedUpload<T>(config: ChunkedUploadConfig<T>): ChunkedU}const destination = createWriteStream(session.path, { flags: "a" });+ let failure: unknown;try {- await pipeline(req, destination);- } finally {- // Whether the chunk arrived whole or the connection dropped partway, what counts is- // what reached the disk. Reading it back is what lets a broken chunk be resumed from- // the exact byte it stopped at rather than being re-sent or, worse, double-written.- session.receivedBytes = (await fsp.stat(session.path)).size;- session.expiresAt = Date.now() + sessionTtlMs;+ // Capped as it is written, not measured once it is written: nothing authenticates the+ // caller here, so one that declares a megabyte and then sends a hundred gigabytes has+ // to be cut off mid-flight rather than found out when the disk is already full.+ await pipeline(req, cappedAt(session.totalBytes - session.receivedBytes), destination);+ } catch (e) {+ failure = e;}- if (session.receivedBytes > session.totalBytes) {- await drop(session);- throw new ValidationError("The upload sent more bytes than it declared.");+ // Whether the chunk arrived whole or the connection dropped partway, what counts is what+ // reached the disk. Reading it back is what lets a broken chunk be resumed from the exact+ // byte it stopped at rather than being re-sent or, worse, double-written.+ session.receivedBytes = await sizeOf(session.path);+ session.expiresAt = Date.now() + sessionTtlMs;++ if (failure) {+ // An overshoot is the caller contradicting what it declared, so the upload goes with+ // it; a broken connection is kept, since that is exactly what resuming is for.+ if (failure instanceof ValidationError) {+ await drop(session);+ }++ throw failure;}return describe(session);@@ -230,6 +250,8 @@ export function createChunkedUpload<T>(config: ChunkedUploadConfig<T>): ChunkedU// The consumer may have taken the file or may have failed before touching it; either// way nothing else will come back for it.await fsp.rm(session.path, { force: true }).catch(() => {});+ config.onSessionDiscarded?.();+throw e;}});@@ -275,9 +297,17 @@ export function createChunkedUpload<T>(config: ChunkedUploadConfig<T>): ChunkedUreturn session;}+ /**+ * Ends a session that produced nothing: expired, aborted, or contradicted what it declared.+ *+ * The consumer is told, because an upload is rarely the only thing that was set aside for it, and+ * these are the endings nobody is waiting on a response for — an expiry has no caller at all.+ */async function drop(session: Session): Promise<void> {sessions.delete(session.uploadId);await fsp.rm(session.path, { force: true }).catch(() => {});++ config.onSessionDiscarded?.();}function describe(session: Session): ChunkedUploadStatus {@@ -320,6 +350,39 @@ interface BeginBody {metadata?: Record<string, unknown>;}+/**+ * Passes at most `allowance` bytes through and fails on the one that would exceed it.+ *+ * A body arrives with nothing bounding it but what the sender chooses to send: `Content-Length` is+ * the sender's own claim, and the chunk content type is deliberately one no body parser handles. So+ * the ceiling is applied to the bytes themselves, on their way past, and the write ends the moment+ * one too many arrives.+ */+function cappedAt(allowance: number): Transform {+ let seen = 0;++ return new Transform({+ transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {+ seen += chunk.length;+ if (seen > allowance) {+ callback(new ValidationError("The upload sent more bytes than it declared."));+ return;+ }++ callback(null, chunk);+ }+ });+}++/** How much of the file is there, counting a file that is not there at all as nothing. */+async function sizeOf(filePath: string): Promise<number> {+ try {+ return (await fsp.stat(filePath)).size;+ } catch {+ return 0;+ }+}+/*** Refuses an upload the filesystem cannot hold, which is worth knowing at the start of an hour-long* transfer rather than at the end of one. A filesystem that cannot be measured is taken as roomy:diff --git a/apps/server/src/services/restore_session.spec.ts b/apps/server/src/services/restore_session.spec.tsnew file mode 100644index 0000000000..803a0d011a--- /dev/null+++ b/apps/server/src/services/restore_session.spec.ts@@ -0,0 +1,138 @@+import { getRunningSetupOperation } from "@triliumnext/core";+import type { Request } from "express";+import fs from "fs";+import path from "path";+import { Readable } from "stream";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import dataDir from "./data_dir.js";+import {+ backupUpload,+ beginBackupUpload,+ discardPendingBackup,+ getPendingBackup,+ pendingRestoreRequest,+ setPendingBackup+} from "./restore_session.js";++const UPLOAD_DIR = path.join(dataDir.TMP_DIR, "uploads");++function beginRequest(totalBytes: number, fileName = "backup.db") {+ return { body: { fileName, totalBytes } } as unknown as Request;+}++function chunkRequest(uploadId: string, offset: number, body: Buffer) {+ return Object.assign(Readable.from([ body ]), {+ params: { uploadId },+ query: { offset: String(offset) }+ }) as unknown as Request;+}++/** A file standing in for one of the user's own backups, which a restore may never consume. */+function localBackup(name = "backup-daily.db") {+ const filePath = path.join(UPLOAD_DIR, name);+ fs.mkdirSync(UPLOAD_DIR, { recursive: true });+ fs.writeFileSync(filePath, "SQLite format 3\0");++ return filePath;+}++beforeEach(() => {+ vi.useFakeTimers();+ discardPendingBackup();+});++afterEach(async () => {+ // The upload is a singleton across the file, so an open session outlives the test that opened+ // it. Age it past its own expiry and sweep, which is the only way in from outside.+ vi.advanceTimersByTime(2 * 60 * 60 * 1000);+ await backupUpload.sweep();+ discardPendingBackup();++ vi.useRealTimers();+ fs.rmSync(UPLOAD_DIR, { recursive: true, force: true });+});++describe("reserving setup for a backup that is coming", () => {+ it("reserves setup before the first byte, so nothing else can build a document meanwhile", async () => {+ expect(getRunningSetupOperation()).toBe(null);++ await beginBackupUpload(beginRequest(8));++ expect(getRunningSetupOperation()).toBe("restore-backup");+ });++ it("gives setup back when the upload expires, which nothing else would put right", async () => {+ const { uploadId } = await beginBackupUpload(beginRequest(8));+ await backupUpload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ // An hour later, with the user long gone.+ vi.advanceTimersByTime(61 * 60 * 1000);+ await backupUpload.sweep();++ expect(getRunningSetupOperation()).toBe(null);+ });++ it("gives setup back when the upload contradicts the size it declared", async () => {+ const { uploadId } = await beginBackupUpload(beginRequest(4));++ await expect(backupUpload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(8)))).rejects.toThrow();++ expect(getRunningSetupOperation()).toBe(null);+ });++ it("keeps setup reserved once a backup is actually waiting to be restored", async () => {+ setPendingBackup(localBackup(), "backup-daily.db", { consumable: false });++ expect(getPendingBackup()).toEqual({ fileName: "backup-daily.db", encrypted: false });+ expect(getRunningSetupOperation()).toBe("restore-backup");+ });+});++describe("a backup nobody comes back for", () => {+ it("gives setup back after it has waited long enough, and leaves the user's own file alone", () => {+ const filePath = localBackup();+ setPendingBackup(filePath, "backup-daily.db", { consumable: false });++ vi.advanceTimersByTime(61 * 60 * 1000);++ expect(getPendingBackup()).toBe(null);+ expect(getRunningSetupOperation()).toBe(null);+ // Never consumable: it is the user's file, not something uploaded to be spent.+ expect(fs.existsSync(filePath)).toBe(true);+ });++ it("deletes an uploaded one, which existed for nothing else", () => {+ const filePath = localBackup("pending-backup");+ setPendingBackup(filePath, "backup.db", { consumable: true });++ vi.advanceTimersByTime(61 * 60 * 1000);++ expect(fs.existsSync(filePath)).toBe(false);+ });++ it("starts its wait over each time a new backup takes its place", () => {+ setPendingBackup(localBackup("first.db"), "first.db", { consumable: false });+ vi.advanceTimersByTime(50 * 60 * 1000);++ setPendingBackup(localBackup("second.db"), "second.db", { consumable: false });+ vi.advanceTimersByTime(50 * 60 * 1000);++ // The first one's hour has passed, but the second one's has not.+ expect(getPendingBackup()).toMatchObject({ fileName: "second.db" });+ });++ it("hands the restore what it needs, and forgets it once discarded", () => {+ const filePath = localBackup();+ setPendingBackup(filePath, "backup-daily.db", { consumable: false });++ expect(pendingRestoreRequest()).toEqual({+ path: filePath, fileName: "backup-daily.db", consumable: false+ });++ discardPendingBackup();++ expect(pendingRestoreRequest()).toBe(null);+ expect(getRunningSetupOperation()).toBe(null);+ });+});diff --git a/apps/server/src/services/restore_session.ts b/apps/server/src/services/restore_session.tsindex a64169b346..ff4ee7a6ec 100644--- a/apps/server/src/services/restore_session.ts+++ b/apps/server/src/services/restore_session.ts@@ -61,7 +61,18 @@ interface Pending extends PendingBackup {consumable: boolean;}+/**+ * How long a backup may wait to be restored before setup is given back, matching how long an upload+ * may go quiet for.+ *+ * A backup goes pending as soon as it arrives, which is before the user has been asked for its+ * passphrase — and they may never answer. Without a limit, closing that tab would leave the instance+ * refusing every other way of setting itself up until it was restarted.+ */+const PENDING_TTL_MS = 60 * 60 * 1000;+let pending: Pending | null = null;+let pendingExpiry: ReturnType<typeof setTimeout> | null = null;let releaseSetupHold: (() => void) | null = null;/** Receives a backup a chunk at a time, and makes what arrives the pending one. */@@ -70,6 +81,14 @@ export const backupUpload = createChunkedUpload<PendingBackup>({directory: path.join(dataDir.TMP_DIR, "uploads"),maxTotalBytes: MAX_BACKUP_BYTES,requireFreeSpace: true,+ // An upload that ends with nothing to show for it gives setup back. Expiry is the case that+ // needs saying: it happens on a timer, with no request to fail and nobody to tell, and without+ // this the instance would refuse every other way of setting itself up until it was restarted.+ onSessionDiscarded: () => {+ if (!pending) {+ freeSetup();+ }+ },onComplete: async ({ path: uploadedPath, fileName }) => {fs.mkdirSync(path.dirname(PENDING_UPLOAD_PATH), { recursive: true });fs.rmSync(PENDING_UPLOAD_PATH, { force: true });@@ -83,6 +102,30 @@ export const backupUpload = createChunkedUpload<PendingBackup>({}});+/**+ * Begins receiving an uploaded backup, reserving setup before the first byte of it arrives.+ *+ * Reserved this early because the reservation is the point: an hour of uploading must not end with+ * another tab having created a document in the meantime. Given back by `onSessionDiscarded` if the+ * upload never becomes a backup.+ *+ * @throws ConflictError when setup is busy with something else.+ */+export async function beginBackupUpload(req: Parameters<typeof backupUpload.begin>[0]) {+ reserveSetup();++ try {+ return await backupUpload.begin(req);+ } catch (e) {+ // Refused before it started, so there is nothing left for the reservation to protect.+ if (!pending) {+ freeSetup();+ }++ throw e;+ }+}+/*** Makes the backup at `filePath` the one waiting to be restored, and reserves setup for it.*@@ -93,7 +136,7 @@ export const backupUpload = createChunkedUpload<PendingBackup>({export function setPendingBackup(filePath: string, fileName: string, options: { consumable: boolean }): PendingBackup {// Taken before the backup is recorded, so a refusal leaves nothing pending behind it. Released// when the restore ends, or when the backup is discarded.- releaseSetupHold ??= holdSetup("restore-backup");+ reserveSetup();pending = {path: filePath,@@ -103,6 +146,7 @@ export function setPendingBackup(filePath: string, fileName: string, options: {// without having to try the restore and fail first.encrypted: readBackupFormat(filePath)?.encrypted ?? false};+ schedulePendingExpiry();return { fileName: pending.fileName, encrypted: pending.encrypted };}@@ -125,16 +169,22 @@ export function pendingRestoreRequest(): Omit<RestoreRequest, "passphrase"> | nu* The setup lock is held for the whole of it, not just for starting it.*/export function beginRestore(request: RestoreRequest): void {+ // A restore is not a backup waiting to be restored, and a large one can outlast the wait it is+ // allowed: left armed, the timer would delete the very file the restore is reading.+ cancelPendingExpiry();+void withSetupLock("restore-backup", async () => {try {await restoreDatabase(request);discardPendingBackup();} catch (e) {// A passphrase that was wrong or missing is the one failure the same backup can still- // recover from, so it is kept for the next attempt. Anything else will fail the same way- // however often it is tried.+ // recover from, so it is kept for the next attempt — and starts waiting again, since the+ // next attempt is another answer that may never come.if (!(e instanceof RestoreFailure) || !RETRYABLE_WITH_ANOTHER_PASSPHRASE.has(e.reason)) {discardPendingBackup();+ } else {+ schedulePendingExpiry();}throw e;@@ -162,6 +212,36 @@ export function discardPendingBackup(): void {}pending = null;+ cancelPendingExpiry();+ freeSetup();+}++/** Starts the wait over, so a backup only expires after it has been left alone for the whole of it. */+function schedulePendingExpiry(): void {+ cancelPendingExpiry();++ pendingExpiry = setTimeout(() => {+ getLog().info("A backup waiting to be restored was left long enough to give setup back.");+ discardPendingBackup();+ }, PENDING_TTL_MS);+ // Nothing should be kept alive by a backup nobody came back for.+ pendingExpiry.unref?.();+}++function cancelPendingExpiry(): void {+ if (pendingExpiry) {+ clearTimeout(pendingExpiry);+ pendingExpiry = null;+ }+}++/** Reserves setup for the restore that is coming, if it is not reserved already. */+function reserveSetup(): void {+ releaseSetupHold ??= holdSetup("restore-backup");+}++/** Gives setup back. Doing it twice is not an error; leaving it taken is the one that matters. */+function freeSetup(): void {releaseSetupHold?.();releaseSetupHold = null;}