Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): survive sustained Graph throttling during huge OneNote imports

perfectra1n10222a57a3c7
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index 1782443153..fb8afaaaf3 100644
--- a/apps/server/src/services/import/onenote/graph.spec.ts
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -1,15 +1,15 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../safe_fetch.js", () => ({ safeFetch: vi.fn() }));
import { safeFetch } from "../../safe_fetch.js";
-import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, listPages } from "./graph.js";
+import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, listPages, resetThrottleGate, retryAfterMs } from "./graph.js";
const safeFetchMock = vi.mocked(safeFetch);
/** Builds a Graph HTTP response as the mocked safeFetch returns it. */
-function graphResponse(status: number, body: string): Awaited<ReturnType<typeof safeFetch>> {
- return new Response(body, { status }) as unknown as Awaited<ReturnType<typeof safeFetch>>;
+function graphResponse(status: number, body: string, headers?: Record<string, string>): Awaited<ReturnType<typeof safeFetch>> {
+ return new Response(body, { status, headers }) as unknown as Awaited<ReturnType<typeof safeFetch>>;
}
describe("backoffDelayMs", () => {
@@ -20,8 +20,98 @@ describe("backoffDelayMs", () => {
expect(backoffDelayMs(3)).toBe(16000);
});
- it("caps the delay at the maximum", () => {
- expect(backoffDelayMs(10)).toBe(30_000);
+ it("caps the delay at one minute", () => {
+ expect(backoffDelayMs(10)).toBe(60_000);
+ });
+});
+
+describe("retryAfterMs", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("parses a delta-seconds value", () => {
+ expect(retryAfterMs("120")).toBe(120_000);
+ expect(retryAfterMs("0")).toBe(0);
+ });
+
+ it("parses an HTTP-date relative to now", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-07-21T12:00:00Z"));
+ expect(retryAfterMs("Tue, 21 Jul 2026 12:01:30 GMT")).toBe(90_000);
+ // A date in the past means the throttle already expired.
+ expect(retryAfterMs("Tue, 21 Jul 2026 11:59:00 GMT")).toBe(0);
+ });
+
+ it("returns null for absent or malformed headers", () => {
+ expect(retryAfterMs(null)).toBeNull();
+ expect(retryAfterMs("")).toBeNull();
+ expect(retryAfterMs(" ")).toBeNull();
+ expect(retryAfterMs("soon")).toBeNull();
+ });
+});
+
+describe("throttling retries", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ resetThrottleGate();
+ });
+
+ afterEach(() => {
+ resetThrottleGate();
+ vi.useRealTimers();
+ safeFetchMock.mockReset();
+ });
+
+ it("keeps retrying well past eight attempts while the wait budget lasts", async () => {
+ let calls = 0;
+ safeFetchMock.mockImplementation(async () => {
+ calls++;
+ return calls <= 12 ? graphResponse(429, "") : graphResponse(200, JSON.stringify({ displayName: "Ada" }));
+ });
+
+ const promise = getAccount("token");
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toEqual({ name: "Ada", email: "" });
+ expect(safeFetchMock).toHaveBeenCalledTimes(13);
+ });
+
+ it("waits out Graph's Retry-After header instead of the computed backoff", async () => {
+ safeFetchMock
+ .mockResolvedValueOnce(graphResponse(429, "", { "Retry-After": "120" }))
+ .mockResolvedValueOnce(graphResponse(200, JSON.stringify({ displayName: "Ada" })));
+
+ const promise = getAccount("token");
+
+ // The plain exponential backoff for a first attempt is 2s; Retry-After must override it,
+ // so just before the 120s mark the retry must not have fired yet.
+ await vi.advanceTimersByTimeAsync(119_000);
+ expect(safeFetchMock).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expect(promise).resolves.toEqual({ name: "Ada", email: "" });
+ expect(safeFetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("gives up with the throttled response once the wait budget is exhausted", async () => {
+ safeFetchMock.mockImplementation(async () =>
+ graphResponse(429, JSON.stringify({ error: { code: "20166", message: "Too many requests" } })));
+
+ const promise = getAccount("token").catch((e: unknown) => e);
+ await vi.runAllTimersAsync();
+ const error = await promise;
+
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain("HTTP 429: 20166: Too many requests");
+ // The budget bounds total waiting: with the fake clock starting at 0, now === total waited.
+ // OneNote throttle windows have been observed to last the better part of an hour for a
+ // heavily-throttled user, so the budget must tolerate at least that before giving up.
+ expect(Date.now()).toBeGreaterThan(30 * 60_000);
+ expect(Date.now()).toBeLessThanOrEqual(60 * 60_000);
+ // ...and it must be attempt-count agnostic — far more patient than the old 8-retry limit.
+ expect(safeFetchMock.mock.calls.length).toBeGreaterThan(10);
});
});
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index ea58d257d5..40db2c6639 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -17,12 +17,17 @@ 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). OneNote's 429s carry no
-// Retry-After header, so retry with exponential backoff before giving up — otherwise a large import
-// would silently drop most of its pages/resources once throttling kicks in.
-const MAX_RETRIES = 8;
+// Graph throttles aggressively under load (HTTP 429, occasionally 503). When the response carries a
+// Retry-After header that wait is used verbatim — but OneNote's 429s usually omit it
+// (https://learn.microsoft.com/en-us/graph/throttling), so retries mostly fall back to exponential
+// backoff. A request only gives up once it has spent MAX_THROTTLE_WAIT_MS waiting out throttles: a
+// fixed retry count proved too small for huge imports. Microsoft publishes no hard OneNote limits —
+// throttling is per app+user and time-based ("simply waiting will eventually reset the limit"), and
+// a heavily-throttled user can stay throttled for the better part of an hour, so the budget must
+// cover that; one page giving up aborts the whole import.
const BASE_RETRY_DELAY_MS = 2000;
-const MAX_RETRY_DELAY_MS = 30_000;
+const MAX_RETRY_DELAY_MS = 60_000;
+const MAX_THROTTLE_WAIT_MS = 60 * 60_000;
// Shared throttle gate. Graph throttles per app/tenant, so a 429 on one request means every other
// in-flight and subsequent request is being throttled too. Rather than each request independently
@@ -36,9 +41,12 @@ let throttledUntilMs = 0;
* must not be trusted to point at the public Graph host. The bearer token is sent on every hop.
*
* Retries on throttling (429/503) via the shared {@link throttledUntilMs} gate, so concurrent
- * requests pause together instead of dog-piling the throttle.
+ * requests pause together instead of dog-piling the throttle. Gives up only once this request has
+ * spent {@link MAX_THROTTLE_WAIT_MS} waiting, returning the throttled response for the caller to
+ * report as an error.
*/
async function graphFetch(accessToken: string, url: string): Promise<Response> {
+ const giveUpAtMs = Date.now() + MAX_THROTTLE_WAIT_MS;
for (let attempt = 0; ; attempt++) {
const gateWaitMs = throttledUntilMs - Date.now();
if (gateWaitMs > 0) {
@@ -50,7 +58,14 @@ async function graphFetch(accessToken: string, url: string): Promise<Response> {
signal: AbortSignal.timeout(GRAPH_TIMEOUT_MS)
});
- if ((response.status !== 429 && response.status !== 503) || attempt >= MAX_RETRIES) {
+ if (response.status !== 429 && response.status !== 503) {
+ return response;
+ }
+
+ // Graph's Retry-After, when present, states exactly how long the throttle lasts — trust it
+ // over the computed backoff.
+ const waitMs = retryAfterMs(response.headers.get("retry-after")) ?? backoffDelayMs(attempt);
+ if (Date.now() + waitMs > giveUpAtMs) {
return response;
}
@@ -59,9 +74,8 @@ async function graphFetch(accessToken: string, url: string): Promise<Response> {
// Extend the shared gate (Math.max: simultaneous 429s converge on one window rather than
// stacking). The wait itself happens at the top of the next iteration, shared across the pool.
- const waitMs = backoffDelayMs(attempt);
throttledUntilMs = Math.max(throttledUntilMs, Date.now() + waitMs);
- getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${url}; retry ${attempt + 1}/${MAX_RETRIES} after ${waitMs}ms`);
+ getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${url}; retry ${attempt + 1} after ${waitMs}ms (${Math.round((giveUpAtMs - Date.now()) / 60_000)}min of wait budget left)`);
}
}
@@ -70,6 +84,28 @@ export function backoffDelayMs(attempt: number): number {
return Math.min(BASE_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
}
+/**
+ * Parses a Retry-After header (delta-seconds or HTTP-date) into a wait in milliseconds, or null when
+ * the header is absent or unparseable.
+ */
+export function retryAfterMs(header: string | null): number | null {
+ const trimmed = header?.trim();
+ if (!trimmed) {
+ return null;
+ }
+ const seconds = Number(trimmed);
+ if (Number.isFinite(seconds)) {
+ return Math.max(0, seconds * 1000);
+ }
+ const dateMs = Date.parse(trimmed);
+ return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());
+}
+
+/** Resets the shared throttle gate; exported for tests only. */
+export function resetThrottleGate(): void {
+ throttledUntilMs = 0;
+}
+
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}