Skip to content

Build your personal knowledge base with Trilium Notes

fix(import): bound OneNote resource downloads and retry on throttling

Elian Doranb08fbac5e8e7
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
new file mode 100644
index 0000000000..b7661e9ad9
--- /dev/null
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { retryDelayMs } from "./graph.js";
+
+describe("retryDelayMs", () => {
+ it("honours a numeric Retry-After header (seconds → ms)", () => {
+ expect(retryDelayMs("3", 0)).toBe(3000);
+ });
+
+ it("falls back to exponential backoff when the header is absent or non-numeric", () => {
+ expect(retryDelayMs(null, 0)).toBe(2000);
+ expect(retryDelayMs(null, 1)).toBe(4000);
+ expect(retryDelayMs("soon", 2)).toBe(8000);
+ });
+
+ it("caps the delay at the maximum", () => {
+ // Both a huge Retry-After and a far-out backoff attempt clamp to the 30s ceiling.
+ expect(retryDelayMs("3600", 0)).toBe(30_000);
+ expect(retryDelayMs(null, 10)).toBe(30_000);
+ });
+});
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 6f123f4826..bf12226f34 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -14,16 +14,47 @@ const GRAPH_BASE = "https://graph.microsoft.com/v1.0";
// be large and slow. Allow a generous per-request budget instead.
const GRAPH_TIMEOUT_MS = 60_000;
+// Graph throttles aggressively under load (HTTP 429, occasionally 503). Retry those a few times,
+// honouring the Retry-After header when present, before giving up — otherwise a large import would
+// silently drop most of its pages/resources the moment Graph starts throttling.
+const MAX_RETRIES = 5;
+const DEFAULT_RETRY_DELAY_MS = 2000;
+const MAX_RETRY_DELAY_MS = 30_000;
+
/**
* Fetches a Microsoft Graph URL through {@link safeFetch} so the request is hardened against SSRF —
* pagination (`@odata.nextLink`) and resource URLs come from Graph responses and page HTML, so they
* must not be trusted to point at the public Graph host. The bearer token is sent on every hop.
+ *
+ * Retries on throttling (429/503): Graph returns a Retry-After header we honour, falling back to an
+ * exponential backoff when it is absent.
*/
-function graphFetch(accessToken: string, url: string): Promise<Response> {
- return safeFetch(url, {
- headers: { Authorization: `Bearer ${accessToken}` },
- signal: AbortSignal.timeout(GRAPH_TIMEOUT_MS)
- });
+async function graphFetch(accessToken: string, url: string): Promise<Response> {
+ for (let attempt = 0; ; attempt++) {
+ const response = await safeFetch(url, {
+ headers: { Authorization: `Bearer ${accessToken}` },
+ signal: AbortSignal.timeout(GRAPH_TIMEOUT_MS)
+ });
+
+ if ((response.status !== 429 && response.status !== 503) || attempt >= MAX_RETRIES) {
+ return response;
+ }
+
+ // Drain the throttled response so its connection is released before we wait and retry.
+ await response.body?.cancel();
+ await delay(retryDelayMs(response.headers.get("Retry-After"), attempt));
+ }
+}
+
+/** Resolves the wait before a throttling retry: the Retry-After header (seconds), else exponential backoff. */
+export function retryDelayMs(retryAfter: string | null, attempt: number): number {
+ const headerSeconds = retryAfter ? Number(retryAfter) : NaN;
+ const delayMs = Number.isFinite(headerSeconds) ? headerSeconds * 1000 : DEFAULT_RETRY_DELAY_MS * 2 ** attempt;
+ return Math.min(delayMs, MAX_RETRY_DELAY_MS);
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
}
export interface GraphAccount {
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index 09b6948d59..e538d7aaf2 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { resolveSubpageParents } from "./importer.js";
+import { mapWithConcurrency, resolveSubpageParents } from "./importer.js";
describe("resolveSubpageParents", () => {
it("keeps top-level pages directly under the section", () => {
@@ -29,3 +29,30 @@ describe("resolveSubpageParents", () => {
expect(resolveSubpageParents([0, 2])).toEqual([-1, -1]);
});
});
+
+describe("mapWithConcurrency", () => {
+ it("returns results in input order regardless of completion order", async () => {
+ // Later items resolve sooner, so order can only be preserved by index, not completion.
+ const out = await mapWithConcurrency([30, 20, 10], 3, (ms) => new Promise<number>((resolve) => setTimeout(() => resolve(ms), ms)));
+ expect(out).toEqual([30, 20, 10]);
+ });
+
+ it("never runs more than `limit` workers at once", async () => {
+ let inFlight = 0;
+ let peak = 0;
+ const work = async () => {
+ inFlight++;
+ peak = Math.max(peak, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight--;
+ return null;
+ };
+
+ await mapWithConcurrency(Array.from({ length: 20 }), 4, work);
+ expect(peak).toBeLessThanOrEqual(4);
+ });
+
+ it("handles an empty list", async () => {
+ expect(await mapWithConcurrency([], 4, async (x) => x)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index bccb65ff7e..5bde62ecee 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -328,22 +328,44 @@ async function downloadPageResources(accessToken: string, html: string): Promise
}
}
- // Downloads are independent stateless GETs, so fetch them in parallel — image-heavy pages would
- // otherwise stall on a long sequential chain. A failed download drops to null and is filtered out.
- const resources = await Promise.all(
- Array.from(refs.values()).map(async (ref) => {
- try {
- const { content, contentType } = await graph.getResource(accessToken, ref.url);
- return { ...ref, mime: ref.mime || contentType, content };
- } catch (e: unknown) {
- getLog().error(`OneNote import: could not download resource ${ref.url}: ${e instanceof Error ? e.message : e}`);
- return null;
- }
- })
- );
+ // Downloads are independent stateless GETs, so fetch them concurrently — but with a bounded pool,
+ // not all at once: an image-heavy page (hundreds of images) would otherwise open hundreds of
+ // simultaneous connections, triggering Graph throttling (429) and a large memory spike, which in
+ // practice dropped most images and left the note nearly empty. A failed download is skipped.
+ const resources = await mapWithConcurrency(Array.from(refs.values()), RESOURCE_DOWNLOAD_CONCURRENCY, async (ref) => {
+ try {
+ const { content, contentType } = await graph.getResource(accessToken, ref.url);
+ return { ...ref, mime: ref.mime || contentType, content };
+ } catch (e: unknown) {
+ getLog().error(`OneNote import: could not download resource ${ref.url}: ${e instanceof Error ? e.message : e}`);
+ return null;
+ }
+ });
return resources.filter((resource): resource is DownloadedResource => resource !== null);
}
+/** Caps how many page resources (images, attachments) are downloaded from Graph at once. */
+const RESOURCE_DOWNLOAD_CONCURRENCY = 6;
+
+/**
+ * Maps `items` through `worker` with at most `limit` invocations in flight at once, preserving input
+ * order in the result. A small fixed pool of workers each pulls the next item until the list is drained.
+ */
+export async function mapWithConcurrency<T, R>(items: T[], limit: number, worker: (item: T) => Promise<R>): Promise<R[]> {
+ const results = new Array<R>(items.length);
+ let next = 0;
+
+ const runWorker = async () => {
+ while (next < items.length) {
+ const index = next++;
+ results[index] = await worker(items[index]);
+ }
+ };
+
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runWorker));
+ return results;
+}
+
/**
* Re-parses the converted page and swaps each downloaded Graph URL for a local Trilium reference:
* images become attachment-backed `<img src="api/attachments/…">`, file attachments become Trilium