From 7723389d178eeb040819f7b02c10d6840c264bd9 Mon Sep 17 00:00:00 2001 From: frederico santos Date: Fri, 13 Nov 2026 18:41:41 +0900 Subject: [PATCH 1/2] Retry requests that Overleaf rate limits (HTTP 429) Overleaf answers bursts with 429 before doing anything, so a retry is safe for every method. Wait 1, 2, 4, 8 and 16 s with jitter, or Retry-After when sent. The extra pool sockets opt out, so a rate-limited pool still shrinks at once. --- CHANGELOG.md | 5 +++++ src/client.ts | 24 ++++++++++++++++++++---- test/client.test.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c1d3e7..6e39d27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to this project will be documented in this file. +## [Unreleased] + +### Fixed +- **Requests rate limited by Overleaf (HTTP 429) are retried** - Overleaf answers a burst of requests with 429 before doing anything, and its limit lasts about 25 seconds, so commands that send several requests in a row (adding a comment, then reading the threads back) failed with "Overleaf is rate limiting requests" although waiting a little would have worked. A 429 is now retried up to 5 times after 1, 2, 4, 8 and 16 seconds, with some jitter so parallel requests do not retry in step, or after `Retry-After` when Overleaf sends one. The extra sockets of the doc-joining pool still give up at once, so a rate-limited pool shrinks right away instead of waiting. `--verbose` logs each retry + ## [0.16.2] - 2026-11-11 ### Fixed diff --git a/src/client.ts b/src/client.ts index eb29471..9bc1d6d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -41,6 +41,8 @@ import { HttpStatusError, ProjectOwnerOnlyError, SessionExpiredError, httpError, const __dirname = dirname(fileURLToPath(import.meta.url)); const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')); const USER_AGENT = `olcli/${pkg.version}`; +/** How often a request answered with HTTP 429 is retried before the 429 is returned to the caller. */ +const MAX_429_RETRIES = 5; const DEFAULT_BASE_URL = 'https://www.overleaf.com'; const RESOURCE_PATH_FAILURE_HINT = ' (Perhaps the resource file you specified does not exist in the project?)'; @@ -669,6 +671,8 @@ export class OverleafClient { timeoutMs?: number; maxRedirects?: number; expect?: 'text' | 'json' | 'buffer'; + /** Wait and retry when Overleaf answers 429 (default). Off where a 429 has its own handling. */ + retryOn429?: boolean; } = {}): Promise<{ status: number; ok: boolean; headers: Record; body: string | Buffer | any }> { const method = options.method || 'GET'; const timeoutMs = options.timeoutMs ?? this.timeoutMs; @@ -768,7 +772,17 @@ export class OverleafClient { }); }; - return doRequest(url, maxRedirects); + // Overleaf answers bursts with 429 before doing anything, so a retry is safe for every method. It sends no + // Retry-After in practice and its limit lasts about 25 s, so wait 1, 2, 4, 8 and 16 s (about 30 s in all), with + // +/-25% jitter so parallel callers do not retry in step. A Retry-After header wins when present. + for (let attempt = 0; ; attempt++) { + const res = await doRequest(url, maxRedirects); + if (res.status !== 429 || options.retryOn429 === false || attempt >= MAX_429_RETRIES) return res; + const retryAfter = Number(res.headers['retry-after']); + const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 1000 * 2 ** attempt * (0.75 + Math.random() * 0.5); + this.logVerbose(`${method} ${url} -> 429, retrying in ${Math.round(waitMs)}ms (${attempt + 1}/${MAX_429_RETRIES})`); + await new Promise(resolve => setTimeout(resolve, waitMs)); + } } /** @@ -1317,12 +1331,14 @@ export class OverleafClient { return docs; } - private async openProjectSocket(projectId: string): Promise { + /** `retryOn429: false` for sockets the caller can do without: a rate-limited one then fails at once. */ + private async openProjectSocket(projectId: string, { retryOn429 = true } = {}): Promise { const handshakeUrl = `${this.baseUrl}/socket.io/1/?projectId=${encodeURIComponent(projectId)}&t=${Date.now()}`; const handshakeResponse = await this.httpRequest(handshakeUrl, { headers: { 'Cookie': this.getCookieHeader(), 'User-Agent': USER_AGENT }, expect: 'text', - timeoutMs: 5000 + timeoutMs: 5000, + retryOn429 }); if (!handshakeResponse.ok) { @@ -2401,7 +2417,7 @@ export class OverleafClient { const extra = Array.from({ length: Math.min(concurrency, docs.length) - 1 }, async () => { let session: ProjectSocketSession; try { - session = await this.openProjectSocket(projectId); + session = await this.openProjectSocket(projectId, { retryOn429: false }); } catch (error) { if ((error as { status?: number }).status === 429) return; if (failure === undefined) failure = error; diff --git a/test/client.test.ts b/test/client.test.ts index d45a007..ec0a390 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -360,3 +360,30 @@ test('refusals happen before any write request', async () => { assert.deepEqual(writes(requests), []); }); }); + +test('httpRequest retries 429 (honoring Retry-After), gives up after 5 retries, and can be told not to retry', async () => { + const cases = [ + { failures: 2, options: {}, status: 200, calls: 3 }, + { failures: 99, options: {}, status: 429, calls: 6 }, + { failures: 99, options: { retryOn429: false }, status: 429, calls: 1 } + ]; + for (const c of cases) { + let calls = 0; + const server = createServer((_req, res) => { + calls++; + const limited = calls <= c.failures; + res.writeHead(limited ? 429 : 200, { 'Content-Type': 'application/json', ...(limited ? { 'Retry-After': '0' } : {}) }); + res.end('{}'); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as { port: number }; + const client = new OverleafClient({ cookies: { session: 's' }, csrf: 'c', baseUrl: `http://127.0.0.1:${port}` }); + const res = await (client as any).httpRequest(`http://127.0.0.1:${port}/x`, { expect: 'json', ...c.options }); + assert.equal(res.status, c.status); + assert.equal(calls, c.calls); + } finally { + await new Promise(resolve => server.close(resolve)); + } + } +}); From 9f002b1b8a647a8771727d79346c4d56639e503c Mon Sep 17 00:00:00 2001 From: Alexander Loth Date: Sun, 15 Nov 2026 19:06:06 +0100 Subject: [PATCH 2/2] Cap Retry-After at 60 seconds A Retry-After value from the server was used as is, so a 429 with Retry-After: 3600 would make olcli wait an hour before the retry. The wait from Retry-After is now capped at 60 seconds; a missing, non-numeric or negative value falls back to the exponential backoff as before. The computation moves into retryDelayMs, and a test next to the existing 429 test checks the cap both on the helper and end to end with a server sending Retry-After: 3600 and a stubbed setTimeout. --- CHANGELOG.md | 2 +- src/client.ts | 19 ++++++++++++++++--- test/client.test.ts | 42 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e39d27..b0f0a3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Fixed -- **Requests rate limited by Overleaf (HTTP 429) are retried** - Overleaf answers a burst of requests with 429 before doing anything, and its limit lasts about 25 seconds, so commands that send several requests in a row (adding a comment, then reading the threads back) failed with "Overleaf is rate limiting requests" although waiting a little would have worked. A 429 is now retried up to 5 times after 1, 2, 4, 8 and 16 seconds, with some jitter so parallel requests do not retry in step, or after `Retry-After` when Overleaf sends one. The extra sockets of the doc-joining pool still give up at once, so a rate-limited pool shrinks right away instead of waiting. `--verbose` logs each retry +- **Requests rate limited by Overleaf (HTTP 429) are retried** - Overleaf answers a burst of requests with 429 before doing anything, and its limit lasts about 25 seconds, so commands that send several requests in a row (adding a comment, then reading the threads back) failed with "Overleaf is rate limiting requests" although waiting a little would have worked. A 429 is now retried up to 5 times after 1, 2, 4, 8 and 16 seconds, with some jitter so parallel requests do not retry in step, or after `Retry-After` when Overleaf sends one, capped at 60 seconds. The extra sockets of the doc-joining pool still give up at once, so a rate-limited pool shrinks right away instead of waiting. `--verbose` logs each retry ## [0.16.2] - 2026-11-11 diff --git a/src/client.ts b/src/client.ts index 9bc1d6d..3b0c036 100644 --- a/src/client.ts +++ b/src/client.ts @@ -43,6 +43,20 @@ const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf- const USER_AGENT = `olcli/${pkg.version}`; /** How often a request answered with HTTP 429 is retried before the 429 is returned to the caller. */ const MAX_429_RETRIES = 5; +/** Longest wait olcli accepts from a Retry-After header, so a server cannot stall a command for an hour. */ +export const MAX_RETRY_AFTER_MS = 60_000; + +/** + * How long to wait before retry number `attempt + 1` of a request answered with 429. A Retry-After value in + * seconds wins when present, capped at 60 s; a missing, non-numeric or negative value falls back to exponential + * backoff (1, 2, 4, 8, 16 s with +/-25% jitter). + */ +export function retryDelayMs(retryAfter: string | string[] | undefined, attempt: number, random: () => number = Math.random): number { + const raw = Array.isArray(retryAfter) ? retryAfter[0] : retryAfter; + const seconds = raw === undefined || raw.trim() === '' ? NaN : Number(raw); + if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS); + return 1000 * 2 ** attempt * (0.75 + random() * 0.5); +} const DEFAULT_BASE_URL = 'https://www.overleaf.com'; const RESOURCE_PATH_FAILURE_HINT = ' (Perhaps the resource file you specified does not exist in the project?)'; @@ -774,12 +788,11 @@ export class OverleafClient { // Overleaf answers bursts with 429 before doing anything, so a retry is safe for every method. It sends no // Retry-After in practice and its limit lasts about 25 s, so wait 1, 2, 4, 8 and 16 s (about 30 s in all), with - // +/-25% jitter so parallel callers do not retry in step. A Retry-After header wins when present. + // +/-25% jitter so parallel callers do not retry in step. A Retry-After header wins when present, capped at 60 s. for (let attempt = 0; ; attempt++) { const res = await doRequest(url, maxRedirects); if (res.status !== 429 || options.retryOn429 === false || attempt >= MAX_429_RETRIES) return res; - const retryAfter = Number(res.headers['retry-after']); - const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 1000 * 2 ** attempt * (0.75 + Math.random() * 0.5); + const waitMs = retryDelayMs(res.headers['retry-after'], attempt); this.logVerbose(`${method} ${url} -> 429, retrying in ${Math.round(waitMs)}ms (${attempt + 1}/${MAX_429_RETRIES})`); await new Promise(resolve => setTimeout(resolve, waitMs)); } diff --git a/test/client.test.ts b/test/client.test.ts index ec0a390..968d931 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -1,7 +1,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; -import { OverleafClient, resolveCommentConcurrency } from '../src/client.js'; +import { MAX_RETRY_AFTER_MS, OverleafClient, resolveCommentConcurrency, retryDelayMs } from '../src/client.js'; interface CapturedRequest { method?: string; @@ -387,3 +387,43 @@ test('httpRequest retries 429 (honoring Retry-After), gives up after 5 retries, } } }); + +test('a 429 with Retry-After: 3600 waits at most 60 seconds, not an hour', async () => { + assert.equal(MAX_RETRY_AFTER_MS, 60_000); + assert.equal(retryDelayMs('3600', 0), 60_000); + assert.equal(retryDelayMs('61', 0), 60_000); + assert.equal(retryDelayMs('60', 0), 60_000); + assert.equal(retryDelayMs('2', 0), 2000); + assert.equal(retryDelayMs('0', 3), 0); + // Missing, non-numeric or negative values fall back to the exponential backoff. + for (const value of [undefined, '', 'soon', '-5']) { + assert.equal(retryDelayMs(value, 2, () => 0.5), 4000); + } + + // End to end: the server asks for an hour, the client waits no longer than the cap. + let calls = 0; + const server = createServer((_req, res) => { + calls++; + res.writeHead(calls === 1 ? 429 : 200, { 'Content-Type': 'application/json', ...(calls === 1 ? { 'Retry-After': '3600' } : {}) }); + res.end('{}'); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const realSetTimeout = globalThis.setTimeout; + const waits: number[] = []; + globalThis.setTimeout = ((fn: () => void, ms?: number) => { + waits.push(ms ?? 0); + return realSetTimeout(fn, 0); + }) as typeof setTimeout; + try { + const { port } = server.address() as { port: number }; + const client = new OverleafClient({ cookies: { session: 's' }, csrf: 'c', baseUrl: `http://127.0.0.1:${port}` }); + const res = await (client as any).httpRequest(`http://127.0.0.1:${port}/x`, { expect: 'json' }); + assert.equal(res.status, 200); + assert.equal(calls, 2); + assert.ok(waits.includes(MAX_RETRY_AFTER_MS), `expected a ${MAX_RETRY_AFTER_MS} ms wait, got ${waits.join(', ')}`); + assert.ok(waits.every(ms => ms <= MAX_RETRY_AFTER_MS), `no wait may exceed the cap, got ${waits.join(', ')}`); + } finally { + globalThis.setTimeout = realSetTimeout; + await new Promise(resolve => server.close(resolve)); + } +});