Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ All notable changes to this project will be documented in this file.
- **Accept tracked changes of one doc with a single request** - `acceptTrackedChangesInDoc(projectId, docId, ids)` sends just the editor's accept request. `acceptTrackedChanges` reads the whole project before and after to resolve the ids and check the result, which is right for the CLI but costs two passes over every doc; an editor integration that already holds the changes and re-reads the project after every write can skip both. `acceptTrackedChanges` now uses it for each doc, so the request is built in one place
- **The text around a tracked change, on request** - `listTrackedChanges` and `listReview` take `surroundingChars`, and each change then carries `before` and `after`: up to that many characters of the visible text right before the change and right after it (after the inserted text for an insert). `position` only fits Overleaf's current copy of the doc; a tool that shows tracked changes in a local copy that was edited since, such as a git clone, needs some surrounding text to find each change again. Off by default, so the output of `olcli changes` does not change

### 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, 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

### Fixed
Expand Down
37 changes: 33 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,22 @@ 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;
/** 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?)';
Expand Down Expand Up @@ -681,6 +697,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<string, string | string[]>; body: string | Buffer | any }> {
const method = options.method || 'GET';
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
Expand Down Expand Up @@ -780,7 +798,16 @@ 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, 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 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));
}
}

/**
Expand Down Expand Up @@ -1329,12 +1356,14 @@ export class OverleafClient {
return docs;
}

private async openProjectSocket(projectId: string): Promise<ProjectSocketSession> {
/** `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<ProjectSocketSession> {
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) {
Expand Down Expand Up @@ -2413,7 +2442,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;
Expand Down
69 changes: 68 additions & 1 deletion test/client.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -360,3 +360,70 @@ 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<void>(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));
}
}
});

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<void>(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));
}
});
Loading