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 an issue
Adorian Doran716fa8926b70
diff --git a/apps/server/src/services/chunked_upload.spec.ts b/apps/server/src/services/chunked_upload.spec.tsindex d23bf13743..8944c9c5dc 100644--- a/apps/server/src/services/chunked_upload.spec.ts+++ b/apps/server/src/services/chunked_upload.spec.ts@@ -322,6 +322,40 @@ describe("chunked upload: telling the consumer a session came to nothing", () =>});});+describe("chunked upload: counting what is open", () => {+ it("counts the uploads in progress", async () => {+ const { upload } = uploadService({ maxConcurrentSessions: 2 });+ expect(upload.activeSessions()).toBe(0);++ await upload.begin(beginRequest(8));+ await upload.begin(beginRequest(8));++ expect(upload.activeSessions()).toBe(2);+ });++ it("stops counting one whose time has run out, before any sweep has got to it", async () => {+ const { upload } = uploadService({ sessionTtlMs: 1 });+ await upload.begin(beginRequest(8));++ await new Promise((resolve) => setTimeout(resolve, 5));++ // Expired is gone as far as anyone asking is concerned; a consumer deciding whether to let+ // go of something cannot be made to wait for the sweeper's next turn.+ expect(upload.activeSessions()).toBe(0);+ });++ it("stops counting one that finished, so its consumer can let go of what it held for it", async () => {+ const { upload } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(4));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ expect(upload.activeSessions()).toBe(1);+ await upload.finish(sessionRequest(uploadId));++ expect(upload.activeSessions()).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 94884bddcc..daea6b7d83 100644--- a/apps/server/src/services/chunked_upload.ts+++ b/apps/server/src/services/chunked_upload.ts@@ -99,6 +99,13 @@ export interface ChunkedUploadStatus {}export interface ChunkedUpload<T> {+ /**+ * How many uploads are open, not counting any whose time has run out since the last sweep.+ *+ * For a consumer that sets something aside for an upload's sake and has to know, before putting+ * it back, whether any upload still depends on it.+ */+ activeSessions(): number;begin(req: Request): Promise<ChunkedUploadStatus>;chunk(req: Request): Promise<ChunkedUploadStatus>;status(req: Request): Promise<ChunkedUploadStatus>;@@ -321,7 +328,18 @@ export function createChunkedUpload<T>(config: ChunkedUploadConfig<T>): ChunkedU};}+ /**+ * Counted rather than taken from the map's size: a session whose time has run out is gone as far+ * as anyone asking is concerned, whether or not a sweep has got to it yet.+ */+ function activeSessions(): number {+ const now = Date.now();++ return [ ...sessions.values() ].filter((session) => session.expiresAt > now).length;+ }+return {+ activeSessions,begin,chunk,status,diff --git a/apps/server/src/services/restore_session.spec.ts b/apps/server/src/services/restore_session.spec.tsindex 803a0d011a..912deda96e 100644--- a/apps/server/src/services/restore_session.spec.ts+++ b/apps/server/src/services/restore_session.spec.ts@@ -81,6 +81,41 @@ describe("reserving setup for a backup that is coming", () => {expect(getRunningSetupOperation()).toBe(null);});+ it("keeps the reservation when a second upload is refused in favour of the first", async () => {+ const { uploadId } = await beginBackupUpload(beginRequest(8));++ // Only one at a time, so this one is turned away — and must leave the running one's+ // reservation exactly where it found it.+ await expect(beginBackupUpload(beginRequest(8))).rejects.toThrow(/already in progress/);++ expect(getRunningSetupOperation()).toBe("restore-backup");+ // Still the one that was accepted, and still receiving.+ await expect(backupUpload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)))).resolves.toBeTruthy();+ });++ it("keeps the reservation the new upload took when opening it sweeps away an old one", async () => {+ const abandoned = await beginBackupUpload(beginRequest(8));+ await backupUpload.chunk(chunkRequest(abandoned.uploadId, 0, Buffer.alloc(4)));++ // The abandoned one ages out. Opening the next upload sweeps it, and that sweep reports a+ // discarded session — after the replacement has already reserved setup for itself.+ vi.advanceTimersByTime(61 * 60 * 1000);+ await beginBackupUpload(beginRequest(8));++ expect(getRunningSetupOperation()).toBe("restore-backup");+ });++ it("keeps the reservation for an upload in flight when the backup that was waiting is dropped", async () => {+ setPendingBackup(localBackup(), "backup-daily.db", { consumable: false });+ const { uploadId } = await beginBackupUpload(beginRequest(8));++ // The backup that was waiting expires while the one replacing it is still arriving.+ discardPendingBackup();++ expect(getRunningSetupOperation()).toBe("restore-backup");+ await expect(backupUpload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)))).resolves.toBeTruthy();+ });+it("keeps setup reserved once a backup is actually waiting to be restored", async () => {setPendingBackup(localBackup(), "backup-daily.db", { consumable: false });diff --git a/apps/server/src/services/restore_session.ts b/apps/server/src/services/restore_session.tsindex f2111436dd..8a0d08bffe 100644--- a/apps/server/src/services/restore_session.ts+++ b/apps/server/src/services/restore_session.ts@@ -78,6 +78,14 @@ const PENDING_TTL_MS = 60 * 60 * 1000;let pending: Pending | null = null;let pendingExpiry: ReturnType<typeof setTimeout> | null = null;let releaseSetupHold: (() => void) | null = null;+/**+ * Uploads that have been reserved for but are not open yet.+ *+ * Opening one sweeps away the sessions whose time has run out, and each of those reports itself as+ * discarded. Without counting the one being opened, that sweep would hand back the reservation the+ * upload took a moment earlier, on its way to taking its place.+ */+let opening = 0;/** Receives a backup a chunk at a time, and makes what arrives the pending one. */export const backupUpload = createChunkedUpload<PendingBackup>({@@ -89,13 +97,8 @@ export const backupUpload = createChunkedUpload<PendingBackup>({// 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: () => {- logRestore(pending- ? "an upload ended with nothing to show for it, but a backup is already waiting"- : "an upload ended with nothing to show for it; setup is free again");-- if (!pending) {- freeSetup();- }+ logRestore("an upload ended with nothing to show for it");+ releaseSetupIfUnused();},// The name the user gave the file is carried on, since the screen shows it back to them; it is// only the log that has no business repeating it.@@ -123,6 +126,7 @@ export const backupUpload = createChunkedUpload<PendingBackup>({*/export async function beginBackupUpload(req: Parameters<typeof backupUpload.begin>[0]) {reserveSetup();+ opening++;try {const session = await backupUpload.begin(req);@@ -132,13 +136,13 @@ export async function beginBackupUpload(req: Parameters<typeof backupUpload.begireturn session;} catch (e) {logRestoreError(`an upload was refused before it started: ${e instanceof Error ? e.message : String(e)}`);-- // Refused before it started, so there is nothing left for the reservation to protect.- if (!pending) {- freeSetup();- }-throw e;+ } finally {+ // Counted down before the reservation is reconsidered, and reconsidered however this ended:+ // an upload refused because another one is already running must leave that one's reservation+ // exactly where it found it.+ opening--;+ releaseSetupIfUnused();}}@@ -233,7 +237,7 @@ export function discardPendingBackup(): void {pending = null;cancelPendingExpiry();- freeSetup();+ releaseSetupIfUnused();}/** Starts the wait over, so a backup only expires after it has been left alone for the whole of it. */@@ -241,7 +245,7 @@ function schedulePendingExpiry(): void {cancelPendingExpiry();pendingExpiry = setTimeout(() => {- logRestore("a backup waited to be restored for longer than it is allowed to; setup is free again");+ logRestore("a backup waited to be restored for longer than it is allowed to");discardPendingBackup();}, PENDING_TTL_MS);// Nothing should be kept alive by a backup nobody came back for.@@ -260,8 +264,20 @@ 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 {+/**+ * Gives setup back, but only once nothing a restore is doing still depends on it.+ *+ * There is one reservation and several things behind it: an upload being opened, uploads in flight,+ * and a backup waiting to be restored. Whichever of them ends first must not hand back what the+ * others are still standing on — a second upload being refused would otherwise unreserve setup for+ * the upload it was refused in favour of, and a pending backup expiring would unreserve it for an+ * upload halfway through replacing it.+ */+function releaseSetupIfUnused(): void {+ if (opening > 0 || pending !== null || backupUpload.activeSessions() > 0) {+ return;+ }+releaseSetupHold?.();releaseSetupHold = null;}