Skip to content

Build your personal knowledge base with Trilium Notes

client/backup import: use the updated uploader

Adorian Doran8a7ee3fc40fc
diff --git a/apps/client/src/services/chunked_upload.spec.ts b/apps/client/src/services/chunked_upload.spec.ts
index 7c805bc1e3..2173c9697f 100644
--- a/apps/client/src/services/chunked_upload.spec.ts
+++ b/apps/client/src/services/chunked_upload.spec.ts
@@ -16,20 +16,32 @@ class FakeEndpoint {
received = "";
totalBytes = 0;
aborted = false;
- finished = false;
+ finished = 0;
readonly calls: { method: string; url: string; headers: Record<string, string> }[] = [];
/** Queued failures, applied to chunk requests in order. `null` sends the chunk through. */
private readonly failures: (Failure | null)[] = [];
+ /** Queued failures for everything that is not a chunk, in the order those requests arrive. */
+ private readonly otherFailures: (Failure | null)[] = [];
failNextChunks(...failures: (Failure | null)[]) {
this.failures.push(...failures);
}
+ /** Applies to `begin` and `finish`, which are one request each and share the queue. */
+ failNextRequests(...failures: (Failure | null)[]) {
+ this.otherFailures.push(...failures);
+ }
+
fetch = async (url: string, init: RequestInit = {}): Promise<Response> => {
const method = init.method ?? "GET";
this.calls.push({ method, url, headers: init.headers as Record<string, string> });
if (url.endsWith("/begin")) {
+ const refusal = this.refuseOther();
+ if (refusal) {
+ return refusal;
+ }
+
const body = JSON.parse(String(init.body)) as { totalBytes: number };
this.totalBytes = body.totalBytes;
return json({ uploadId: "upload1", fileName: "backup.db", totalBytes: body.totalBytes, receivedBytes: 0, chunkSize: CHUNK_SIZE, expiresAt: 0 });
@@ -37,6 +49,13 @@ class FakeEndpoint {
if (url.includes("/chunk?offset=")) {
const failure = this.failures.shift();
+ if (failure?.hang) {
+ // Answers nothing at all, the way a connection that was taken away does, and gives
+ // up only when the caller stops waiting on it.
+ return new Promise((_, reject) => {
+ init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
+ });
+ }
if (failure) {
return failure.status ? error(failure.status, failure.message) : Promise.reject(new TypeError("Failed to fetch"));
}
@@ -51,7 +70,12 @@ class FakeEndpoint {
}
if (url.endsWith("/finish")) {
- this.finished = true;
+ const refusal = this.refuseOther();
+ if (refusal) {
+ return refusal;
+ }
+
+ this.finished++;
return json({ restored: this.received });
}
@@ -63,6 +87,16 @@ class FakeEndpoint {
return json(this.status());
};
+ /** The next queued failure for a non-chunk request, or nothing where it should go through. */
+ private refuseOther() {
+ const failure = this.otherFailures.shift();
+ if (!failure) {
+ return null;
+ }
+
+ return failure.status ? error(failure.status, failure.message) : Promise.reject(new TypeError("Failed to fetch"));
+ }
+
private status() {
return { uploadId: "upload1", fileName: "backup.db", totalBytes: this.totalBytes, receivedBytes: this.received.length, chunkSize: CHUNK_SIZE, expiresAt: 0 };
}
@@ -72,6 +106,8 @@ interface Failure {
/** Omitted for a connection that never answered at all. */
status?: number;
message?: string;
+ /** Never answers and never fails, which is what a connection taken away mid-request can do. */
+ hang?: boolean;
}
function json(body: unknown) {
@@ -100,7 +136,12 @@ beforeEach(() => {
vi.stubGlobal("fetch", endpoint.fetch);
});
-afterEach(() => vi.unstubAllGlobals());
+afterEach(() => {
+ vi.unstubAllGlobals();
+ // Timers and the clock are stubbed by the tests that steer them; nothing after them should
+ // inherit a clock that does not move.
+ vi.restoreAllMocks();
+});
describe("chunked upload", () => {
it("sends the file a slice at a time and returns what the endpoint answers", async () => {
@@ -110,7 +151,7 @@ describe("chunked upload", () => {
expect(result).toEqual({ restored: content });
expect(endpoint.received).toBe(content);
- expect(endpoint.finished).toBe(true);
+ expect(endpoint.finished).toBe(1);
const offsets = endpoint.calls.filter((call) => call.url.includes("/chunk?")).map((call) => Number(call.url.split("offset=")[1]));
expect(offsets).toEqual([ 0, 4, 8, 12, 16 ]);
@@ -157,7 +198,7 @@ describe("chunked upload", () => {
it("gives up once the retries are spent", async () => {
endpoint.failNextChunks({}, {}, {}, {});
- await expect(upload(endpoint, "abcd", { maxRetriesPerChunk: 2 })).rejects.toBeInstanceOf(TypeError);
+ await expect(upload(endpoint, "abcd", { maxRetriesPerRequest: 2 })).rejects.toBeInstanceOf(TypeError);
expect(endpoint.calls.filter((call) => call.url.includes("/chunk?"))).toHaveLength(3);
expect(endpoint.aborted).toBe(true);
});
@@ -165,7 +206,7 @@ describe("chunked upload", () => {
it("raises the endpoint's own words, with the status it refused on", async () => {
endpoint.failNextChunks({ status: 507, message: "the disk is full" });
- const failure = await upload(endpoint, "abcd", { maxRetriesPerChunk: 0 }).catch((e) => e);
+ const failure = await upload(endpoint, "abcd", { maxRetriesPerRequest: 0 }).catch((e) => e);
expect(failure).toBeInstanceOf(ChunkedUploadError);
expect(failure).toMatchObject({ message: "the disk is full", status: 507 });
@@ -178,7 +219,7 @@ describe("chunked upload", () => {
await expect(upload(endpoint, "abcdefgh", { signal: controller.signal })).rejects.toThrow();
expect(endpoint.aborted).toBe(true);
- expect(endpoint.finished).toBe(false);
+ expect(endpoint.finished).toBe(0);
});
it("does not try to abort a session that was never started", async () => {
@@ -188,3 +229,121 @@ describe("chunked upload", () => {
expect(endpoint.aborted).toBe(false);
});
});
+
+describe("chunked upload: waiting out a connection", () => {
+ it("keeps sending through an outage far longer than any single retry waits", async () => {
+ // A file this size is uploaded from a phone that goes into a pocket and a laptop that gets
+ // closed. None of that should cost the transfer.
+ endpoint.failNextChunks(...Array.from({ length: 30 }, () => ({})));
+
+ const result = await upload(endpoint, "abcdefgh");
+
+ expect(result).toEqual({ restored: "abcdefgh" });
+ });
+
+ it("says while it is waiting, and stops saying so once the connection is back", async () => {
+ const onProgress = vi.fn();
+ endpoint.failNextChunks({}, {});
+
+ await upload(endpoint, "abcdefgh", { onProgress });
+
+ const reconnecting = onProgress.mock.calls.map(([ progress ]) => progress.reconnecting);
+ expect(reconnecting).toContain(true);
+ expect(reconnecting.at(-1)).toBe(false);
+ });
+
+ it("leaves the time spent waiting out of the rate, which is about transferring", async () => {
+ // A clock that only moves while the upload is waiting on a connection: every byte here goes
+ // out in no time at all, and a minute passes with the connection down. Counting that minute
+ // would leave a rate and an estimate that stay wrong long after the connection is back.
+ const onProgress = vi.fn();
+ let now = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ recordWaits({ onWait: () => (now += 60_000) });
+ endpoint.failNextChunks({});
+
+ await upload(endpoint, "abcd", { onProgress });
+
+ expect(onProgress).toHaveBeenLastCalledWith(expect.objectContaining({ sentBytes: 4, bytesPerSecond: 0, etaMs: null }));
+ });
+
+ it("waits longer after each failure, up to the ceiling it settles at", async () => {
+ const waits = recordWaits();
+ endpoint.failNextChunks({}, {}, {}, {}, {});
+
+ await upload(endpoint, "abcd", { retryDelayMs: 100, maxRetryDelayMs: 250 });
+
+ expect(waits).toEqual([ 100, 200, 250, 250, 250 ]);
+ });
+
+ it("carries on as soon as the browser says the connection is back, rather than waiting it out", async () => {
+ // The wait is never allowed to end on its own, so the upload finishing at all is the event
+ // that ended it. Announced a microtask late, since the wait only starts listening once it
+ // has asked for its timer.
+ recordWaits({ fire: false, onWait: () => queueMicrotask(() => window.dispatchEvent(new Event("online"))) });
+ endpoint.failNextChunks({});
+
+ await expect(upload(endpoint, "abcd", { retryDelayMs: 60_000 })).resolves.toEqual({ restored: "abcd" });
+ });
+
+ it("stops believing in a request that was left hanging while the app was away", async () => {
+ // The connection is gone but the request does not know it, which is what a phone leaves
+ // behind every time it is put in a pocket. Nothing else would ever end this upload.
+ endpoint.failNextChunks({ hang: true });
+
+ const uploaded = upload(endpoint, "abcd");
+ await vi.waitFor(() => expect(endpoint.calls.some((call) => call.url.includes("/chunk?"))).toBe(true));
+ document.dispatchEvent(new Event("visibilitychange"));
+
+ await expect(uploaded).resolves.toEqual({ restored: "abcd" });
+ });
+
+ it("gives up on an upload the endpoint no longer has, which no amount of waiting brings back", async () => {
+ endpoint.failNextChunks({ status: 410, message: "The server restarted, so the upload it was holding is gone." });
+
+ const failure = await upload(endpoint, "abcd").catch((e) => e);
+
+ expect(failure).toMatchObject({ status: 410 });
+ expect(endpoint.calls.filter((call) => call.url.includes("/chunk?"))).toHaveLength(1);
+ });
+
+ it("asks again for an answer to `finish` that was lost, rather than sending the file twice", async () => {
+ endpoint.failNextRequests(null, {});
+
+ const result = await upload(endpoint, "abcd");
+
+ expect(result).toEqual({ restored: "abcd" });
+ expect(endpoint.finished).toBe(1);
+ expect(endpoint.calls.filter((call) => call.url.endsWith("/finish"))).toHaveLength(2);
+ // The one thing that must not happen: the file being sent again from the start.
+ expect(endpoint.calls.filter((call) => call.url.includes("/chunk?"))).toHaveLength(1);
+ });
+
+ it("waits out a connection that fails before the upload has even started", async () => {
+ endpoint.failNextRequests({});
+
+ await expect(upload(endpoint, "abcd")).resolves.toEqual({ restored: "abcd" });
+ });
+});
+
+/**
+ * Collects the delays that are asked for, and by default lets them through at once so a test does
+ * not spend the wait it is asserting on.
+ *
+ * @param options.fire whether the wait ever ends by itself; `false` leaves only whatever else the
+ * upload is listening for to end it.
+ * @param options.onWait called as each wait begins.
+ */
+function recordWaits({ fire = true, onWait }: { fire?: boolean; onWait?: () => void } = {}): number[] {
+ const waits: number[] = [];
+ const realSetTimeout = setTimeout;
+
+ vi.stubGlobal("setTimeout", ((handler: () => void, ms: number) => {
+ waits.push(ms);
+ onWait?.();
+
+ return realSetTimeout(handler, fire ? 0 : 60_000);
+ }) as typeof setTimeout);
+
+ return waits;
+}
diff --git a/apps/client/src/services/chunked_upload.ts b/apps/client/src/services/chunked_upload.ts
index 7e93997b77..e28174d06c 100644
--- a/apps/client/src/services/chunked_upload.ts
+++ b/apps/client/src/services/chunked_upload.ts
@@ -12,6 +12,13 @@ import server from "./server.js";
* where to continue from, so a slice whose response was lost is never sent twice and a slice that
* broke partway resumes at the byte it stopped at.
*
+ * A connection that goes away is waited out rather than treated as the end: a file this size is
+ * uploaded over a quarter of an hour at best and a night at worst, from a phone that will be put in
+ * a pocket and a laptop that will be closed, and none of that should cost the whole transfer. So
+ * every request keeps being retried, at a delay that settles at {@link MAX_RETRY_DELAY_MS}, until
+ * either it goes through or the endpoint says the upload is gone — which is the one answer no amount
+ * of waiting improves, and the only one this gives up on.
+ *
* Nothing here knows what the file is for: the endpoint decides that, and `metadata` reaches it
* untouched.
*
@@ -33,15 +40,31 @@ import server from "./server.js";
* parser would swallow into memory before the route ever saw it. */
export const CHUNK_CONTENT_TYPE = "application/vnd.trilium.chunk";
+/**
+ * Attempts a single request gets before the upload gives up on it. With the delays below, that is
+ * about a quarter of an hour of a connection that is simply not there.
+ */
+const DEFAULT_MAX_RETRIES = 60;
+/** How long the first retry waits, each further one waiting twice as long as the one before it. */
+const DEFAULT_RETRY_DELAY_MS = 1000;
+/**
+ * The longest a retry waits, which is where a drawn-out outage settles: far enough apart not to
+ * hammer a server that is not answering, close enough together that the upload picks up again soon
+ * after the connection does.
+ */
+const MAX_RETRY_DELAY_MS = 15 * 1000;
+
export interface ChunkedUploadProgress {
sentBytes: number;
totalBytes: number;
/** Between 0 and 1. */
fraction: number;
- /** Averaged over the transfer so far; 0 until the first chunk lands. */
+ /** Averaged over the time actually spent transferring; 0 until the first chunk lands. */
bytesPerSecond: number;
/** Milliseconds left at the current rate, or `null` while there is nothing to work that out from. */
etaMs: number | null;
+ /** Whether the upload is waiting on a connection rather than getting on with it. */
+ reconnecting: boolean;
}
export interface ChunkedUploadOptions {
@@ -55,10 +78,12 @@ export interface ChunkedUploadOptions {
onProgress?: (progress: ChunkedUploadProgress) => void;
/** Cancels the upload and tells the server to forget it. */
signal?: AbortSignal;
- /** Attempts per chunk before the upload gives up. Defaults to 5. */
- maxRetriesPerChunk?: number;
- /** Delay before the first retry, doubling with each further one. Defaults to 500ms. */
+ /** Attempts per request, a chunk being one request. Defaults to {@link DEFAULT_MAX_RETRIES}. */
+ maxRetriesPerRequest?: number;
+ /** Delay before the first retry, doubling with each further one. Defaults to a second. */
retryDelayMs?: number;
+ /** Ceiling the doubling stops at. Defaults to {@link MAX_RETRY_DELAY_MS}. */
+ maxRetryDelayMs?: number;
}
/** What the endpoint says about a session, whether it is being started or asked after. */
@@ -79,19 +104,30 @@ export interface ChunkedUploadStatus {
*/
export async function uploadInChunks<T>(options: ChunkedUploadOptions): Promise<T> {
const { endpoint, blob, fileName, metadata, onProgress, signal } = options;
- const maxRetries = options.maxRetriesPerChunk ?? 5;
- const retryDelayMs = options.retryDelayMs ?? 500;
const totalBytes = blob.size;
+ const startedAt = Date.now();
+ let sentBytes = 0;
+ let reconnecting = false;
+ /** Time already waited out, kept out of the rate: see {@link activeMs}. */
+ let stalledMs = 0;
+ let waitingSince: number | null = null;
- const session = await request<ChunkedUploadStatus>("POST", `${endpoint}/begin`, {
- signal,
- body: JSON.stringify({ fileName, totalBytes, metadata }),
- contentType: "application/json"
- });
+ report();
- const startedAt = Date.now();
- let sentBytes = session.receivedBytes;
- report(0);
+ // Retried like everything else, and safe to be: a `begin` whose answer was lost leaves a session
+ // nothing will ever be sent to, which is what an endpoint that lets a new upload take the place
+ // of an old one exists for.
+ const session = await withRetries(
+ () => request<ChunkedUploadStatus>("POST", `${endpoint}/begin`, {
+ signal,
+ body: JSON.stringify({ fileName, totalBytes, metadata }),
+ contentType: "application/json"
+ }),
+ { ...policy(), retryable: isConnectionFailure }
+ );
+
+ sentBytes = session.receivedBytes;
+ report();
try {
while (sentBytes < totalBytes) {
@@ -107,22 +143,30 @@ export async function uploadInChunks<T>(options: ChunkedUploadOptions): Promise<
contentType: CHUNK_CONTENT_TYPE
}
),
- // Whatever went wrong, the server knows what it holds and this side does not: a lost
- // response means the chunk did land, a broken connection means part of it did.
- async () => {
- const status = await request<ChunkedUploadStatus>("GET", `${endpoint}/${session.uploadId}`, { signal });
- sentBytes = status.receivedBytes;
- },
- maxRetries,
- retryDelayMs,
- signal
+ {
+ ...policy(),
+ retryable: isWorthRetrying,
+ // Whatever went wrong, the server knows what it holds and this side does not: a
+ // lost response means the chunk did land, a broken connection means part of it
+ // did.
+ resync: async () => {
+ const status = await request<ChunkedUploadStatus>("GET", `${endpoint}/${session.uploadId}`, { signal });
+ sentBytes = status.receivedBytes;
+ report();
+ }
+ }
);
sentBytes = sent.receivedBytes;
- report(sentBytes);
+ report();
}
- return await request<T>("POST", `${endpoint}/${session.uploadId}/finish`, { signal });
+ // Worth retrying more than any single chunk was: every byte is already there, and an answer
+ // lost on the way back would otherwise mean sending all of them again.
+ return await withRetries(
+ () => request<T>("POST", `${endpoint}/${session.uploadId}/finish`, { signal }),
+ { ...policy(), retryable: isConnectionFailure }
+ );
} catch (e) {
// The session would expire on its own, but not before holding the whole file on the server's
// disk for an hour and, where only one upload is allowed at a time, the next attempt with it.
@@ -130,50 +174,117 @@ export async function uploadInChunks<T>(options: ChunkedUploadOptions): Promise<
throw e;
}
- function report(sent: number) {
+ /** The retry rules every request shares, each adding what it alone is worth retrying for. */
+ function policy(): Omit<RetryPolicy, "retryable"> {
+ return {
+ max: options.maxRetriesPerRequest ?? DEFAULT_MAX_RETRIES,
+ firstDelayMs: options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS,
+ maxDelayMs: options.maxRetryDelayMs ?? MAX_RETRY_DELAY_MS,
+ onWaiting: whileWaiting,
+ signal
+ };
+ }
+
+ /** Notes the connection going and coming back, so the caller can say which it is. */
+ function whileWaiting(waiting: boolean) {
+ if (reconnecting === waiting) {
+ return;
+ }
+
+ reconnecting = waiting;
+ if (waiting) {
+ waitingSince = Date.now();
+ } else if (waitingSince !== null) {
+ stalledMs += Date.now() - waitingSince;
+ waitingSince = null;
+ }
+
+ report();
+ }
+
+ /**
+ * How long the transfer has been transferring, which is what a rate has to divide by: an hour
+ * spent waiting for a connection is not an hour of slow progress, and counting it would leave a
+ * rate and an estimate that stay wrong long after the connection is back.
+ */
+ function activeMs(): number {
+ return Date.now() - startedAt - stalledMs - (waitingSince === null ? 0 : Date.now() - waitingSince);
+ }
+
+ function report() {
if (!onProgress) {
return;
}
- const elapsedMs = Date.now() - startedAt;
- const bytesPerSecond = sent > 0 && elapsedMs > 0 ? (sent / elapsedMs) * 1000 : 0;
+ const elapsedMs = activeMs();
+ const bytesPerSecond = sentBytes > 0 && elapsedMs > 0 ? (sentBytes / elapsedMs) * 1000 : 0;
onProgress({
- sentBytes: sent,
+ sentBytes,
totalBytes,
- fraction: totalBytes > 0 ? sent / totalBytes : 0,
+ fraction: totalBytes > 0 ? sentBytes / totalBytes : 0,
bytesPerSecond,
- etaMs: bytesPerSecond > 0 ? ((totalBytes - sent) / bytesPerSecond) * 1000 : null
+ etaMs: bytesPerSecond > 0 ? ((totalBytes - sentBytes) / bytesPerSecond) * 1000 : null,
+ reconnecting
});
}
}
+/** How a request is retried, and for how long. */
+interface RetryPolicy {
+ /** Whether a failure is one that retrying could fix. */
+ retryable: (e: unknown) => boolean;
+ /** Brings this side back in step with the endpoint before the next attempt. */
+ resync?: () => Promise<void>;
+ /** Told when the wait for a connection begins, and when it ends. */
+ onWaiting?: (waiting: boolean) => void;
+ max: number;
+ firstDelayMs: number;
+ maxDelayMs: number;
+ signal?: AbortSignal;
+}
+
/**
- * Retries `attempt` while the failure is one that retrying can fix: the connection, or the server
- * having moved on from the offset the chunk was for. A rejection the request itself earned, e.g. a
- * malformed one or a session that is gone, is raised immediately rather than repeated.
+ * Retries `attempt` for as long as the failure is one that retrying can fix, waiting longer between
+ * each attempt up to the policy's ceiling.
+ *
+ * The resync is part of the same loop rather than a step before it: it is one more request over the
+ * connection that has just failed, so it fails too, and treating that as the end would undo the
+ * waiting that everything here is for.
*/
-async function withRetries<T>(
- attempt: () => Promise<T>,
- resync: () => Promise<void>,
- maxRetries: number,
- retryDelayMs: number,
- signal?: AbortSignal
-): Promise<T> {
- for (let retriesLeft = maxRetries; ; retriesLeft--) {
+async function withRetries<T>(attempt: () => Promise<T>, policy: RetryPolicy): Promise<T> {
+ for (let retriesLeft = policy.max; ; retriesLeft--) {
try {
- return await attempt();
+ const result = await attempt();
+ policy.onWaiting?.(false);
+
+ return result;
} catch (e) {
- if (retriesLeft <= 0 || !isWorthRetrying(e) || signal?.aborted) {
+ if (retriesLeft <= 0 || !policy.retryable(e) || policy.signal?.aborted) {
+ policy.onWaiting?.(false);
throw e;
}
}
- await delay(retryDelayMs * 2 ** (maxRetries - retriesLeft), signal);
- await resync();
+ policy.onWaiting?.(true);
+ await waitBeforeRetry(delayFor(policy, retriesLeft), policy.signal);
+
+ try {
+ await policy.resync?.();
+ } catch (e) {
+ if (!policy.retryable(e)) {
+ policy.onWaiting?.(false);
+ throw e;
+ }
+ }
}
}
+/** Twice the last wait, up to the ceiling the policy settles at. */
+function delayFor(policy: RetryPolicy, retriesLeft: number): number {
+ return Math.min(policy.firstDelayMs * 2 ** (policy.max - retriesLeft), policy.maxDelayMs);
+}
+
function isWorthRetrying(e: unknown): boolean {
if (e instanceof ChunkedUploadError) {
// A conflict means the offset has moved, which the resync then corrects; anything else in the
@@ -181,8 +292,17 @@ function isWorthRetrying(e: unknown): boolean {
return e.status === 409 || e.status >= 500;
}
- // No status at all: the request never completed, which is exactly what a retry is for.
- return !(e instanceof DOMException && e.name === "AbortError");
+ return isConnectionFailure(e);
+}
+
+/**
+ * Whether the request never got an answer at all, which is the failure retrying is for.
+ *
+ * The one to be sure of excluding is the caller's own cancellation, which arrives the same way a
+ * dropped connection does and would otherwise be waited out rather than obeyed.
+ */
+function isConnectionFailure(e: unknown): boolean {
+ return !(e instanceof ChunkedUploadError) && !(e instanceof DOMException && e.name === "AbortError");
}
/** A response the server refused, carrying the status so the retry rules can tell the cases apart. */
@@ -210,18 +330,78 @@ async function request<T>(method: string, url: string, options: RequestOptions =
headers["content-type"] = options.contentType;
}
- const response = await fetch(`${window.glob.baseApiUrl}${url}`, {
- method,
- headers,
- body: options.body,
- signal: options.signal
- });
+ const attempt = abandonWhenForegrounded(options.signal);
+ try {
+ const response = await fetch(`${window.glob.baseApiUrl}${url}`, {
+ method,
+ headers,
+ body: options.body,
+ signal: attempt.signal
+ });
+
+ if (!response.ok) {
+ throw new ChunkedUploadError(await messageOf(response), response.status);
+ }
+
+ return response.status === 204 ? (undefined as T) : await response.json() as T;
+ } catch (e) {
+ // Ours rather than the caller's, so it reads as a connection to try again over rather than
+ // as the cancellation an abort otherwise means.
+ throw attempt.abandoned && !(e instanceof ChunkedUploadError)
+ ? new Error("The connection was left behind while the app was in the background.")
+ : e;
+ } finally {
+ attempt.release();
+ }
+}
+
+/**
+ * A signal for one attempt, which gives up on the request when the app comes back to the foreground.
+ *
+ * A connection the operating system took away while the app was in the background does not always
+ * fail: the request can sit there, holding the upload at a standstill with nothing to retry and
+ * nothing to say for itself, which is the shape a phone puts an upload in every time it is put in a
+ * pocket. Coming back is the moment to stop believing in it.
+ *
+ * Being wrong about that costs a round trip and nothing else: the server counts what reached its
+ * disk, so the next attempt carries on from the byte this one had got to.
+ */
+function abandonWhenForegrounded(callerSignal?: AbortSignal) {
+ const attempt = new AbortController();
+ const state = {
+ signal: attempt.signal,
+ /** Whether it was this that ended the request, rather than the caller cancelling it. */
+ abandoned: false,
+ release
+ };
+
+ // An already-cancelled signal never fires, so it is acted on rather than listened to.
+ if (callerSignal?.aborted) {
+ attempt.abort();
+ } else {
+ callerSignal?.addEventListener("abort", cancel, { once: true });
+ }
+ document.addEventListener("visibilitychange", onForegrounded);
+
+ return state;
- if (!response.ok) {
- throw new ChunkedUploadError(await messageOf(response), response.status);
+ function cancel() {
+ attempt.abort();
}
- return response.status === 204 ? (undefined as T) : await response.json() as T;
+ function onForegrounded() {
+ if (document.visibilityState !== "visible") {
+ return;
+ }
+
+ state.abandoned = true;
+ attempt.abort();
+ }
+
+ function release() {
+ callerSignal?.removeEventListener("abort", cancel);
+ document.removeEventListener("visibilitychange", onForegrounded);
+ }
}
/** The server's own words where it gave any, since they are what the user is shown. */
@@ -236,18 +416,34 @@ async function messageOf(response: Response): Promise<string> {
}
}
-function delay(ms: number, signal?: AbortSignal): Promise<void> {
+/**
+ * Waits `ms` before the next attempt, or until the browser says the connection is back, whichever
+ * comes first.
+ *
+ * Listening for that is what keeps a long wait from being the thing the user is waiting on: a phone
+ * that has just walked back into signal, or a laptop that has just been opened, should carry on then
+ * rather than a quarter of a minute later.
+ */
+function waitBeforeRetry(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
- const timer = setTimeout(() => {
- signal?.removeEventListener("abort", onAbort);
+ const timer = setTimeout(done, ms);
+ window.addEventListener("online", done);
+ signal?.addEventListener("abort", onAbort, { once: true });
+
+ function done() {
+ cleanUp();
resolve();
- }, ms);
+ }
function onAbort() {
- clearTimeout(timer);
+ cleanUp();
reject(new DOMException("Upload cancelled", "AbortError"));
}
- signal?.addEventListener("abort", onAbort, { once: true });
+ function cleanUp() {
+ clearTimeout(timer);
+ window.removeEventListener("online", done);
+ signal?.removeEventListener("abort", onAbort);
+ }
});
}
diff --git a/apps/client/src/setup_restore.css b/apps/client/src/setup_restore.css
index 519329900c..1e1207e0f3 100644
--- a/apps/client/src/setup_restore.css
+++ b/apps/client/src/setup_restore.css
@@ -108,6 +108,14 @@
margin-inline-start: auto;
font-variant-numeric: tabular-nums;
}
+
+ /* Takes the rate's place, so the line does not shift as the connection comes and goes. */
+ .restore-upload-reconnecting {
+ display: flex;
+ align-items: center;
+ gap: 0.4em;
+ margin-inline-start: auto;
+ }
}
}
diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsx
index 69e41693a6..bd4b2b7729 100644
--- a/apps/client/src/setup_restore.spec.tsx
+++ b/apps/client/src/setup_restore.spec.tsx
@@ -15,7 +15,16 @@ const serverMock = vi.hoisted(() => ({
}));
vi.mock("./services/server", () => ({ default: serverMock }));
-const uploadMock = vi.hoisted(() => ({ uploadInChunks: vi.fn() }));
+const uploadMock = vi.hoisted(() => ({
+ uploadInChunks: vi.fn(),
+ // Stands in for the real one, which the screen tests failures against: mocking the module whole
+ // would otherwise leave it undefined.
+ ChunkedUploadError: class ChunkedUploadError extends Error {
+ constructor(message: string, readonly status: number) {
+ super(message);
+ }
+ }
+}));
vi.mock("./services/chunked_upload", () => uploadMock);
import RestoreFromBackup from "./setup_restore";
@@ -404,6 +413,33 @@ describe("uploading a backup", () => {
expect(container.querySelector("input[type=password]")).toBeTruthy();
});
+ it("says it is waiting on the connection, in place of a rate that has stopped meaning anything", async () => {
+ let report: (progress: unknown) => void = () => {};
+ uploadMock.uploadInChunks.mockImplementation(async ({ onProgress }: { onProgress: (p: unknown) => void }) => {
+ report = onProgress;
+ report({ sentBytes: 1024, totalBytes: 4096, fraction: 0.25, bytesPerSecond: 512, reconnecting: false });
+
+ return new Promise(() => {});
+ });
+ renderRestore();
+ await flushEffects();
+ await chooseFile(new File([ "database bytes" ], "backup.db"));
+
+ report({ sentBytes: 1024, totalBytes: 4096, fraction: 0.25, bytesPerSecond: 512, reconnecting: true });
+ await flushEffects();
+
+ expect(container.querySelector(".restore-upload-reconnecting")?.textContent)
+ .toContain("setup.restore-upload-reconnecting");
+ expect(container.querySelector(".restore-upload-speed")).toBeFalsy();
+ // Still on the upload rather than thrown back to the picker: waiting is not failing.
+ expect(container.querySelector("progress")).toBeTruthy();
+
+ report({ sentBytes: 2048, totalBytes: 4096, fraction: 0.5, bytesPerSecond: 512, reconnecting: false });
+ await flushEffects();
+
+ expect(container.querySelector(".restore-upload-reconnecting")).toBeFalsy();
+ });
+
it("goes back to the picker with the reason when the upload fails", async () => {
uploadMock.uploadInChunks.mockRejectedValue(new Error("the disk is full"));
renderRestore();
@@ -415,6 +451,20 @@ describe("uploading a backup", () => {
expect(container.querySelector(".restore-error-detail")?.textContent).toBe("the disk is full");
expect(container.querySelector(".restore-file-input")).toBeTruthy();
});
+
+ it("says an upload the server no longer holds has to be started again, not retried", async () => {
+ uploadMock.uploadInChunks.mockRejectedValue(
+ new uploadMock.ChunkedUploadError("The server restarted, so the upload it was holding is gone.", 410)
+ );
+ renderRestore();
+ await flushEffects();
+
+ await chooseFile(new File([ "database bytes" ], "backup.db"));
+
+ expect(container.querySelector(".restore-error-headline")?.textContent).toBe("setup.restore-error-upload-interrupted");
+ expect(container.querySelector(".restore-error-detail")?.textContent)
+ .toBe("The server restarted, so the upload it was holding is gone.");
+ });
});
describe("choosing a backup on the desktop", () => {
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsx
index 3e9bfd2509..4ed580e0c6 100644
--- a/apps/client/src/setup_restore.tsx
+++ b/apps/client/src/setup_restore.tsx
@@ -4,7 +4,7 @@ import type { DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commo
import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
-import { uploadInChunks } from "./services/chunked_upload";
+import { ChunkedUploadError, uploadInChunks } from "./services/chunked_upload";
import { describeDatabaseFile, describeDatabaseFormat } from "./services/database_files";
import { t } from "./services/i18n";
import server from "./services/server";
@@ -146,7 +146,7 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
uploadCancellation.current = cancellation;
setStep("uploading");
- setUpload({ sentBytes: 0, totalBytes: file.size, fraction: 0, bytesPerSecond: 0 });
+ setUpload({ sentBytes: 0, totalBytes: file.size, fraction: 0, bytesPerSecond: 0, reconnecting: false });
try {
const uploaded = await uploadInChunks<{ fileName: string; encrypted: boolean }>({
@@ -154,8 +154,8 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
blob: file,
fileName: file.name,
signal: cancellation.signal,
- onProgress: ({ sentBytes, totalBytes, fraction, bytesPerSecond }) =>
- setUpload({ sentBytes, totalBytes, fraction, bytesPerSecond })
+ onProgress: ({ sentBytes, totalBytes, fraction, bytesPerSecond, reconnecting }) =>
+ setUpload({ sentBytes, totalBytes, fraction, bytesPerSecond, reconnecting })
});
await restore({ source: "pending", fileName: uploaded.fileName, encrypted: uploaded.encrypted });
@@ -165,7 +165,7 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
// An upload the user walked away from ends in a failure they chose, and being told
// about it would read as something having gone wrong.
if (!cancellation.signal.aborted) {
- raiseError(t("setup.restore-error-upload-failed"), detailOf(e));
+ raiseError(uploadFailureHeadline(e), detailOf(e));
}
} finally {
uploadCancellation.current = null;
@@ -267,6 +267,20 @@ function Failure({ headline, detail }: { headline: string; detail?: string }) {
);
}
+/**
+ * The sentence for an upload that did not finish.
+ *
+ * A connection that goes away is waited out rather than reported, so an upload only fails here once
+ * there is nothing left to wait for. The two endings differ in what the user should do next: an
+ * upload the server no longer holds has to be started again, while anything else is a reason it
+ * refused, and telling them to try again would be telling them to repeat it.
+ */
+function uploadFailureHeadline(e: unknown): string {
+ const gone = e instanceof ChunkedUploadError && (e.status === 404 || e.status === 410);
+
+ return gone ? t("setup.restore-error-upload-interrupted") : t("setup.restore-error-upload-failed");
+}
+
/** What a thrown failure has to say for itself, for the detail line under the headline. */
function detailOf(e: unknown): string | undefined {
const message = e instanceof Error ? e.message : String(e);
@@ -311,6 +325,8 @@ interface UploadState {
fraction: number;
/** Averaged over the transfer so far, so it settles rather than jumping about between pieces. */
bytesPerSecond: number;
+ /** Whether the upload is waiting on a connection that has gone away. */
+ reconnecting: boolean;
}
/** The backups already here, and the way to a file that is not. */
@@ -440,12 +456,21 @@ function UploadProgress({ upload }: { upload: UploadState }) {
})}
</span>
- {/* Only once something has actually gone out: before the first piece lands there
- is no elapsed time to divide by, and a rate of nothing says nothing. */}
- {upload.bytesPerSecond > 0 && (
- <span class="restore-upload-speed">
- {t("setup.restore-upload-speed", { speed: formatSize(upload.bytesPerSecond) })}
+ {/* In place of the speed while the connection is gone, which is where the eye
+ already is and where a rate averaged over a transfer that has stopped would
+ otherwise sit unchanged, saying everything is fine. */}
+ {upload.reconnecting ? (
+ <span class="restore-upload-reconnecting">
+ <Icon icon="bx bx-wifi-off" /> {t("setup.restore-upload-reconnecting")}
</span>
+ ) : (
+ // Only once something has actually gone out: before the first piece lands
+ // there is no elapsed time to divide by, and a rate of nothing says nothing.
+ upload.bytesPerSecond > 0 && (
+ <span class="restore-upload-speed">
+ {t("setup.restore-upload-speed", { speed: formatSize(upload.bytesPerSecond) })}
+ </span>
+ )
)}
</div>
</CardSection>
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4daedf8b9e..d26e70abe5 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3693,6 +3693,7 @@
"restore-uploading": "Uploading the backup...",
"restore-uploaded-so-far": "{{sent}} of {{total}}",
"restore-upload-speed": "{{speed}}/s",
+ "restore-upload-reconnecting": "Waiting to re-establish connection...",
"restore-error-unusable": "Unsupported or corrupted Trilium backup.",
"restore-error-too-new": "This backup is from a newer version of Trilium. Update Trilium and try again.",
"restore-error-too-old": "This backup is from a version of Trilium that is too old to be restored.",
@@ -3703,6 +3704,7 @@
"restore-error-already-initialized": "This instance already has a knowledge base, so it cannot be restored over. Reload the page.",
"restore-error-could-not-start": "The restore could not be started.",
"restore-error-upload-failed": "The backup could not be uploaded.",
+ "restore-error-upload-interrupted": "The upload was interrupted and could not be continued. Choose the backup again to start over.",
"restore-passphrase": "Encryption password",
"restore-passphrase-description": "This backup is encrypted. Enter the password used to create this backup.",
"restore-wrong-passphrase": "That password does not open this backup. Please try again.",