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
5 changes: 4 additions & 1 deletion ts/src/github/ratelimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,12 @@ export class GitHubRateLimiter {
const limit = parseInt(h("x-ratelimit-limit") ?? String(this.budget), 10);
const used = Math.max(0, limit - parseInt(remaining, 10));
const raw = await this.client.get(this.key);
if (used > (raw !== null ? parseInt(raw, 10) : 0)) await this.client.set(this.key, used);
const raised = used > (raw !== null ? parseInt(raw, 10) : 0);
if (raised) await this.client.set(this.key, used);
const reset = h("x-ratelimit-reset");
// SET clears the key's TTL; restore a window so the counter cannot outlive it.
if (reset !== null) await this.client.expire(this.key, Math.max(1, parseInt(reset, 10) - Math.floor(Date.now() / 1000)));
else if (raised) await this.client.expire(this.key, this.window);
} catch { this.disable(); }
}
private disable() { this.disabledUntil = Date.now() + DISABLE_COOLDOWN_MS; }
Expand Down
16 changes: 16 additions & 0 deletions ts/tests/lote1.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,22 @@ test("rate limiter: budget, wait, exhaustion, fail-open, observe reconciliation"
await new GitHubRateLimiter(bad, "t", 1).acquire("/x"); // fail-open
});

// Redis SET drops the key's TTL; without x-ratelimit-reset the counter used to become permanent and lock the budget forever.
test("rate limiter: observe keeps the window TTL when the reset header is missing", async () => {
const ttl = new Map<string, number>();
const r = new FakeRedis();
r.expire = (async (k: string, s: number) => { ttl.set(k, s); return 1; }) as any;
r.ttl = (async (k: string) => ttl.get(k) ?? -1) as any;
const set = r.set.bind(r);
r.set = async (k: string, v: any) => { ttl.delete(k); await set(k, v); };
const lim = new GitHubRateLimiter(r, "tok", 4800, 3600);
await lim.acquire("/a");
await lim.observe(new Headers({ "x-ratelimit-limit": "5000", "x-ratelimit-remaining": "100" }));
const key = [...r.m.keys()][0]!;
expect(r.m.get(key)).toBe(4900);
expect(await (r as RedisLike).ttl(key)).toBeGreaterThan(0);
});

const PR_BASE = { number: 7, base: { repo: { full_name: "a/b" } }, head: { sha: "abc12345", ref: "f", repo: { full_name: "a/b" } } };
const gh = () => new GithubClient("t", null);
test("merge: sha guard, passes sha lock, refreshes on base-modified 405", async () => {
Expand Down
Loading