@app-vitals/agent-admin 1.76.0 → 1.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -87,16 +87,58 @@ export interface LookupInstallation {
87
87
  login: string;
88
88
  }
89
89
 
90
+ /** Rate-limit state GitHub reported on a response; null when a header was absent. */
91
+ export interface LookupRateLimit {
92
+ /** X-RateLimit-Remaining. */
93
+ remaining: number | null;
94
+ /** X-RateLimit-Reset (epoch seconds) as a Date. */
95
+ resetAt: Date | null;
96
+ /** Retry-After, in seconds. */
97
+ retryAfterSeconds: number | null;
98
+ }
99
+
100
+ /** One page of GET /installation/repositories. */
101
+ export interface LookupRepositoryPage {
102
+ repositories: LookupRepository[];
103
+ /** GitHub's total_count for the whole listing (not this page). */
104
+ totalCount: number;
105
+ /** A further page exists (Link rel="next", or a full page when no Link). */
106
+ hasNext: boolean;
107
+ rateLimit: LookupRateLimit;
108
+ }
109
+
110
+ /**
111
+ * A rate-limit response (429, or a 403 GitHub marks as rate limited). Still a
112
+ * GithubEnterpriseError of kind "rate_limit"; adds when to try again.
113
+ */
114
+ export class GithubLookupRateLimitError extends GithubEnterpriseError {
115
+ readonly resetAt: Date;
116
+
117
+ constructor(base: GithubEnterpriseError, resetAt: Date) {
118
+ super("rate_limit", base.message, {
119
+ status: base.status,
120
+ retryAfterSeconds: base.retryAfterSeconds,
121
+ });
122
+ this.name = "GithubLookupRateLimitError";
123
+ this.resetAt = resetAt;
124
+ }
125
+ }
126
+
90
127
  export interface GithubLookupClientOptions {
91
128
  appId: string;
92
129
  privateKey: string;
93
130
  apiBase?: string;
94
131
  fetchFn?: typeof fetch;
95
132
  now?: () => Date;
133
+ /** Abort any single GitHub request after this long. Default 30s. */
134
+ requestTimeoutMs?: number;
96
135
  }
97
136
 
98
137
  const PER_PAGE = 100;
99
138
  const MAX_PAGES = 100;
139
+ export const DEFAULT_LOOKUP_REQUEST_TIMEOUT_MS = 30_000;
140
+ /** When a rate-limit response carries no reset hint, wait this long. */
141
+ const DEFAULT_RATE_LIMIT_WAIT_MS = 60_000;
100
142
  /** Refresh a cached installation token this long before it expires. */
101
143
  const TOKEN_REFRESH_SKEW_MS = 60_000;
102
144
 
@@ -106,6 +148,7 @@ export class GithubLookupClient {
106
148
  private readonly apiBase: string;
107
149
  private readonly fetchFn: typeof fetch;
108
150
  private readonly now: () => Date;
151
+ private readonly requestTimeoutMs: number;
109
152
  private readonly cached = new Map<string, LookupToken>();
110
153
 
111
154
  constructor(opts: GithubLookupClientOptions) {
@@ -114,6 +157,8 @@ export class GithubLookupClient {
114
157
  this.apiBase = opts.apiBase ?? "https://api.github.com";
115
158
  this.fetchFn = opts.fetchFn ?? fetch;
116
159
  this.now = opts.now ?? (() => new Date());
160
+ this.requestTimeoutMs =
161
+ opts.requestTimeoutMs ?? DEFAULT_LOOKUP_REQUEST_TIMEOUT_MS;
117
162
  }
118
163
 
119
164
  /** Mint (or reuse a still-fresh) installation token for the lookup App on `org`. */
@@ -241,6 +286,56 @@ export class GithubLookupClient {
241
286
  return all;
242
287
  }
243
288
 
289
+ /**
290
+ * Fetch a single page of the repositories the lookup App can see on `org`,
291
+ * with GitHub's total_count and the response's rate-limit headers. A rate
292
+ * limit throws GithubLookupRateLimitError (kind "rate_limit") with resetAt.
293
+ * Makes no assumption about the order GitHub returns rows in.
294
+ */
295
+ async listInstallationRepositoriesPage(
296
+ org: string,
297
+ page: number,
298
+ ): Promise<LookupRepositoryPage> {
299
+ if (!Number.isInteger(page) || page < 1) {
300
+ throw new GithubEnterpriseError(
301
+ "validation",
302
+ "GitHub installation repositories: page must be an integer >= 1",
303
+ );
304
+ }
305
+ const { token } = await this.getOrgToken(org);
306
+ const res = await this.request<{
307
+ total_count?: unknown;
308
+ repositories?: RawRepository[];
309
+ }>(
310
+ "GET",
311
+ `/installation/repositories?per_page=${PER_PAGE}&page=${page}`,
312
+ token,
313
+ "GitHub installation repositories",
314
+ );
315
+ const rows = res.data?.repositories;
316
+ if (!Array.isArray(rows)) {
317
+ throw new GithubEnterpriseError(
318
+ "unexpected",
319
+ "GitHub installation repositories: response is not a repository list",
320
+ );
321
+ }
322
+ const total = res.data?.total_count;
323
+ if (typeof total !== "number" || !Number.isInteger(total) || total < 0) {
324
+ throw new GithubEnterpriseError(
325
+ "unexpected",
326
+ "GitHub installation repositories: response missing total_count",
327
+ );
328
+ }
329
+ const link = res.headers.get("link");
330
+ return {
331
+ repositories: rows.map(toRepository),
332
+ totalCount: total,
333
+ hasNext:
334
+ link !== null ? /rel="next"/.test(link) : rows.length >= PER_PAGE,
335
+ rateLimit: readRateLimit(res.headers),
336
+ };
337
+ }
338
+
244
339
  /**
245
340
  * A user's role on `owner/repo`. Prefers `role_name` (carries maintain and
246
341
  * triage), falling back to the legacy `permission` field.
@@ -325,15 +420,21 @@ export class GithubLookupClient {
325
420
  resp = await this.fetchFn(`${this.apiBase}${path}`, {
326
421
  method,
327
422
  redirect: "manual",
423
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
328
424
  headers: {
329
425
  Accept: "application/vnd.github+json",
330
426
  Authorization: `Bearer ${bearer}`,
331
427
  "X-GitHub-Api-Version": "2022-11-28",
332
428
  },
333
429
  });
334
- } catch {
430
+ } catch (err) {
335
431
  // The underlying error is dropped on purpose: it must never echo headers.
336
- throw new GithubEnterpriseError("network", `${context}: network error`);
432
+ throw new GithubEnterpriseError(
433
+ "network",
434
+ isTimeout(err)
435
+ ? `${context}: request timed out`
436
+ : `${context}: network error`,
437
+ );
337
438
  }
338
439
  let data: unknown;
339
440
  try {
@@ -342,15 +443,64 @@ export class GithubLookupClient {
342
443
  data = undefined;
343
444
  }
344
445
  if (!resp.ok) {
345
- throw mapGithubEnterpriseError(resp.status, resp.headers, data, context, [
346
- bearer,
347
- this.privateKey,
348
- ]);
446
+ const mapped = mapGithubEnterpriseError(
447
+ resp.status,
448
+ resp.headers,
449
+ data,
450
+ context,
451
+ [bearer, this.privateKey],
452
+ );
453
+ if (mapped.kind === "rate_limit") {
454
+ throw new GithubLookupRateLimitError(
455
+ mapped,
456
+ rateLimitResetAt(readRateLimit(resp.headers), this.now()),
457
+ );
458
+ }
459
+ throw mapped;
349
460
  }
350
461
  return { status: resp.status, headers: resp.headers, data: data as T };
351
462
  }
352
463
  }
353
464
 
465
+ function isTimeout(err: unknown): boolean {
466
+ return (
467
+ err instanceof Error &&
468
+ (err.name === "TimeoutError" || err.name === "AbortError")
469
+ );
470
+ }
471
+
472
+ function headerNumber(headers: Headers, name: string): number | null {
473
+ const raw = headers.get(name);
474
+ if (raw === null || raw.trim() === "") return null;
475
+ const n = Number(raw);
476
+ return Number.isFinite(n) && n >= 0 ? n : null;
477
+ }
478
+
479
+ function readRateLimit(headers: Headers): LookupRateLimit {
480
+ const reset = headerNumber(headers, "x-ratelimit-reset");
481
+ return {
482
+ remaining: headerNumber(headers, "x-ratelimit-remaining"),
483
+ resetAt: reset === null ? null : new Date(reset * 1000),
484
+ retryAfterSeconds: headerNumber(headers, "retry-after"),
485
+ };
486
+ }
487
+
488
+ /**
489
+ * When to try again after a rate limit: the later of Retry-After and
490
+ * X-RateLimit-Reset, or a default wait when GitHub gave neither.
491
+ */
492
+ export function rateLimitResetAt(rl: LookupRateLimit, now: Date): Date {
493
+ const candidates: number[] = [];
494
+ if (rl.retryAfterSeconds !== null && rl.retryAfterSeconds > 0) {
495
+ candidates.push(now.getTime() + rl.retryAfterSeconds * 1000);
496
+ }
497
+ if (rl.resetAt !== null) candidates.push(rl.resetAt.getTime());
498
+ const at = candidates.length
499
+ ? Math.max(...candidates)
500
+ : now.getTime() + DEFAULT_RATE_LIMIT_WAIT_MS;
501
+ return new Date(Math.max(at, now.getTime()));
502
+ }
503
+
354
504
  interface RawInstallation {
355
505
  id?: number;
356
506
  account?: { login?: string; type?: string } | null;
@@ -8,6 +8,7 @@ import { generateKeyPairSync } from "node:crypto";
8
8
  import { GithubEnterpriseError } from "./github-enterprise-client.ts";
9
9
  import {
10
10
  GithubLookupClient,
11
+ GithubLookupRateLimitError,
11
12
  mapRepoRole,
12
13
  REPO_ROLES,
13
14
  } from "./github-lookup-client.ts";
@@ -134,7 +135,10 @@ describe("GithubLookupClient.listInstallations", () => {
134
135
  appId: "555",
135
136
  privateKey,
136
137
  fetchFn: (async () =>
137
- Response.json({ message: "boom" }, { status: 500 })) as unknown as typeof fetch,
138
+ Response.json(
139
+ { message: "boom" },
140
+ { status: 500 },
141
+ )) as unknown as typeof fetch,
138
142
  });
139
143
  await expect(client.listInstallations()).rejects.toBeInstanceOf(
140
144
  GithubEnterpriseError,
@@ -147,6 +151,147 @@ describe("GithubLookupClient.listInstallations", () => {
147
151
  privateKey,
148
152
  fetchFn: (async () => Response.json({})) as unknown as typeof fetch,
149
153
  });
150
- await expect(client.listInstallations()).rejects.toThrow("not an installation list");
154
+ await expect(client.listInstallations()).rejects.toThrow(
155
+ "not an installation list",
156
+ );
157
+ });
158
+ });
159
+
160
+ describe("GithubLookupClient request timeout", () => {
161
+ const { privateKey } = generateKeyPairSync("rsa", {
162
+ modulusLength: 2048,
163
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
164
+ publicKeyEncoding: { type: "spki", format: "pem" },
165
+ });
166
+
167
+ /** A fetch that never answers on its own; it only rejects when aborted. */
168
+ const hanging = (signals: AbortSignal[]) =>
169
+ ((_u: unknown, init?: RequestInit) =>
170
+ new Promise<Response>((_resolve, reject) => {
171
+ const signal = init?.signal;
172
+ if (!signal) return; // would hang forever: the test times out
173
+ signals.push(signal);
174
+ signal.addEventListener("abort", () => reject(signal.reason));
175
+ })) as unknown as typeof fetch;
176
+
177
+ it("aborts a hung request after requestTimeoutMs as a network error", async () => {
178
+ const signals: AbortSignal[] = [];
179
+ const client = new GithubLookupClient({
180
+ appId: "555",
181
+ privateKey,
182
+ fetchFn: hanging(signals),
183
+ requestTimeoutMs: 20,
184
+ });
185
+ try {
186
+ await client.getOrgToken("acme-eng");
187
+ } catch (e) {
188
+ const err = e as GithubEnterpriseError;
189
+ expect(err).toBeInstanceOf(GithubEnterpriseError);
190
+ expect(err.kind).toBe("network");
191
+ expect(err.message).toContain("timed out");
192
+ expect(signals).toHaveLength(1);
193
+ return;
194
+ }
195
+ throw new Error("expected rejection");
196
+ });
197
+
198
+ it("passes an abort signal on every request, including page fetches", async () => {
199
+ const signals: (AbortSignal | undefined)[] = [];
200
+ const client = new GithubLookupClient({
201
+ appId: "555",
202
+ privateKey,
203
+ fetchFn: (async (input: RequestInfo | URL, init?: RequestInit) => {
204
+ signals.push(init?.signal ?? undefined);
205
+ const path = new URL(input.toString()).pathname;
206
+ if (path === "/orgs/acme-eng/installation")
207
+ return Response.json({ id: 1 });
208
+ if (path === "/app/installations/1/access_tokens")
209
+ return Response.json({
210
+ token: "ghs_x",
211
+ expires_at: "2999-01-01T00:00:00Z",
212
+ });
213
+ return Response.json({ total_count: 0, repositories: [] });
214
+ }) as unknown as typeof fetch,
215
+ });
216
+ await client.listInstallationRepositoriesPage("acme-eng", 1);
217
+ expect(signals).toHaveLength(3);
218
+ for (const s of signals) expect(s).toBeInstanceOf(AbortSignal);
219
+ });
220
+ });
221
+
222
+ describe("GithubLookupClient.listInstallationRepositoriesPage", () => {
223
+ const { privateKey } = generateKeyPairSync("rsa", {
224
+ modulusLength: 2048,
225
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
226
+ publicKeyEncoding: { type: "spki", format: "pem" },
227
+ });
228
+ const NOW = new Date("2026-11-20T12:00:00Z");
229
+
230
+ function clientFor(reposResponse: () => Response) {
231
+ return new GithubLookupClient({
232
+ appId: "555",
233
+ privateKey,
234
+ now: () => NOW,
235
+ fetchFn: (async (input: RequestInfo | URL) => {
236
+ const path = new URL(input.toString()).pathname;
237
+ if (path === "/orgs/acme-eng/installation")
238
+ return Response.json({ id: 1 });
239
+ if (path === "/app/installations/1/access_tokens")
240
+ return Response.json({
241
+ token: "ghs_x",
242
+ expires_at: "2999-01-01T00:00:00Z",
243
+ });
244
+ return reposResponse();
245
+ }) as unknown as typeof fetch,
246
+ });
247
+ }
248
+
249
+ it("rejects a response without a numeric total_count", async () => {
250
+ const client = clientFor(() => Response.json({ repositories: [] }));
251
+ await expect(
252
+ client.listInstallationRepositoriesPage("acme-eng", 1),
253
+ ).rejects.toThrow("total_count");
254
+ });
255
+
256
+ it("rejects a page number below 1", async () => {
257
+ const client = clientFor(() =>
258
+ Response.json({ total_count: 0, repositories: [] }),
259
+ );
260
+ await expect(
261
+ client.listInstallationRepositoriesPage("acme-eng", 0),
262
+ ).rejects.toThrow("page");
263
+ });
264
+
265
+ it("falls back to a short page when there is no Link header", async () => {
266
+ const client = clientFor(() =>
267
+ Response.json({
268
+ total_count: 1,
269
+ repositories: [{ id: 1, name: "a", full_name: "acme-eng/a" }],
270
+ }),
271
+ );
272
+ const page = await client.listInstallationRepositoriesPage("acme-eng", 1);
273
+ expect(page.hasNext).toBe(false);
274
+ expect(page.rateLimit).toEqual({
275
+ remaining: null,
276
+ resetAt: null,
277
+ retryAfterSeconds: null,
278
+ });
279
+ });
280
+
281
+ it("defaults a rate limit without reset hints to one minute out", async () => {
282
+ const client = clientFor(() =>
283
+ Response.json({ message: "API rate limit exceeded" }, { status: 429 }),
284
+ );
285
+ try {
286
+ await client.listInstallationRepositoriesPage("acme-eng", 1);
287
+ } catch (e) {
288
+ expect(e).toBeInstanceOf(GithubLookupRateLimitError);
289
+ expect((e as GithubLookupRateLimitError).kind).toBe("rate_limit");
290
+ expect((e as GithubLookupRateLimitError).resetAt).toEqual(
291
+ new Date(NOW.getTime() + 60_000),
292
+ );
293
+ return;
294
+ }
295
+ throw new Error("expected rejection");
151
296
  });
152
297
  });
@@ -168,6 +168,14 @@ export class GitHubRepoCacheService {
168
168
  return repos.length;
169
169
  }
170
170
 
171
+ /** Number of the snapshot's repos with `seenAt >= since` (distinct rows). */
172
+ async countReposSeenSince(snapshotId: string, since: Date): Promise<number> {
173
+ requireNonEmpty("snapshotId", snapshotId);
174
+ return this.prisma.gitHubCachedRepo.count({
175
+ where: { snapshotId, seenAt: { gte: since } },
176
+ });
177
+ }
178
+
171
179
  /**
172
180
  * Delete repos last seen before the snapshot's crawlStartedAt. Returns the
173
181
  * number deleted; 0 (and deletes nothing) when no crawl has started.
@@ -0,0 +1,244 @@
1
+ /**
2
+ * admin/src/github-repo-crawler.integration.test.ts
3
+ * The crawl engine end to end: GithubLookupClient replaying hand-authored
4
+ * cassettes (fixtures/github-lookup-cassette.json) through an INJECTED fetchFn
5
+ * (no global fetch override, no mock.module()), persisting through
6
+ * GitHubRepoCacheService into a real PostgreSQL DB.
7
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import { generateKeyPairSync } from "node:crypto";
12
+ import { readFileSync } from "node:fs";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { GithubLookupClient } from "./github-lookup-client.ts";
15
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
16
+ import { crawlRepos, lookupRepoPageSource } from "./github-repo-crawler.ts";
17
+ import { createAdminPrismaClient } from "./prisma-client.ts";
18
+
19
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
21
+
22
+ interface CassetteEntry {
23
+ status: number;
24
+ headers?: Record<string, string>;
25
+ body: unknown;
26
+ }
27
+
28
+ const cassette: Record<string, CassetteEntry> = JSON.parse(
29
+ readFileSync(
30
+ new URL("./fixtures/github-lookup-cassette.json", import.meta.url).pathname,
31
+ "utf-8",
32
+ ),
33
+ );
34
+
35
+ const { privateKey } = generateKeyPairSync("rsa", {
36
+ modulusLength: 2048,
37
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
38
+ publicKeyEncoding: { type: "spki", format: "pem" },
39
+ });
40
+
41
+ const T0 = new Date("2026-11-09T12:00:00Z");
42
+ const RESET = new Date("2026-11-09T12:15:00Z");
43
+ const key = {
44
+ accountId: "acc",
45
+ appKind: "lookup" as const,
46
+ appRef: "555",
47
+ org: "acme-eng",
48
+ };
49
+
50
+ describeOrSkip("crawlRepos through GithubLookupClient (integration)", () => {
51
+ let prisma: PrismaClient;
52
+ let now: Date;
53
+ let svc: GitHubRepoCacheService;
54
+ /** Repo listing route per page number -> cassette key. */
55
+ let pages: Record<number, string>;
56
+ let fetchedPages: number[];
57
+ let client: GithubLookupClient;
58
+
59
+ const clock = { now: () => new Date(now) };
60
+ const run = () =>
61
+ crawlRepos({
62
+ key,
63
+ source: lookupRepoPageSource(client, "acme-eng"),
64
+ store: svc,
65
+ clock,
66
+ });
67
+ const names = async () =>
68
+ (
69
+ await prisma.gitHubCachedRepo.findMany({ orderBy: { githubId: "asc" } })
70
+ ).map((r) => r.fullName);
71
+
72
+ beforeEach(async () => {
73
+ prisma = createAdminPrismaClient(TEST_DB as string);
74
+ await prisma.gitHubCachedRepo.deleteMany();
75
+ await prisma.gitHubRepoSnapshot.deleteMany();
76
+ now = T0;
77
+ svc = new GitHubRepoCacheService(prisma, clock);
78
+ pages = { 1: "repos_page_1", 2: "repos_page_2" };
79
+ fetchedPages = [];
80
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
81
+ if (!(init?.signal instanceof AbortSignal)) {
82
+ throw new Error("request made without a timeout signal");
83
+ }
84
+ const u = new URL(input.toString());
85
+ const route = `${init?.method ?? "GET"} ${u.pathname}`;
86
+ let name: string | undefined;
87
+ if (route === "GET /orgs/acme-eng/installation") {
88
+ name = "org_installation_success";
89
+ } else if (route === "POST /app/installations/7001/access_tokens") {
90
+ name = "lookup_token_success";
91
+ } else if (route === "GET /installation/repositories") {
92
+ const page = Number(u.searchParams.get("page"));
93
+ fetchedPages.push(page);
94
+ name = pages[page];
95
+ }
96
+ const entry = name ? cassette[name] : undefined;
97
+ if (!entry) throw new Error(`no cassette for ${route}${u.search}`);
98
+ return new Response(JSON.stringify(entry.body), {
99
+ status: entry.status,
100
+ headers: {
101
+ "Content-Type": "application/json",
102
+ ...(entry.headers ?? {}),
103
+ },
104
+ });
105
+ }) as typeof fetch;
106
+ client = new GithubLookupClient({
107
+ appId: "555",
108
+ privateKey,
109
+ apiBase: "https://ghe.test",
110
+ fetchFn,
111
+ now: clock.now,
112
+ });
113
+ });
114
+
115
+ afterEach(async () => {
116
+ await prisma.$disconnect();
117
+ });
118
+
119
+ it("crawls every page, completes, and sweeps repos gone since the last crawl", async () => {
120
+ const snap = await svc.upsertSnapshot(key);
121
+ await svc.upsertRepos(
122
+ snap.id,
123
+ [{ githubId: 99, fullName: "acme-eng/deleted" }],
124
+ new Date(T0.getTime() - 86_400_000),
125
+ );
126
+ const out = await run();
127
+ expect(out).toEqual({ outcome: "complete", pagesFetched: 2, swept: 1 });
128
+ expect(await names()).toEqual([
129
+ "acme-eng/api",
130
+ "acme-eng/web",
131
+ "acme-eng/infra",
132
+ ]);
133
+ const after = await svc.getSnapshot(key);
134
+ expect(after?.completedAt).toEqual(T0);
135
+ expect(after?.crawlStartedAt).toEqual(T0);
136
+ expect(after?.totalCount).toBe(3);
137
+ expect(after?.crawlPage).toBe(2);
138
+ });
139
+
140
+ it("resumes after a mid-crawl failure from the saved page minus one, without duplicates", async () => {
141
+ pages[2] = "repos_500";
142
+ const first = await run();
143
+ expect(first.outcome).toBe("failed");
144
+ let snap = await svc.getSnapshot(key);
145
+ expect(snap?.crawlPage).toBe(1);
146
+ expect(snap?.attempts).toBe(1);
147
+ expect(snap?.lastError).toContain("HTTP 500");
148
+ expect(snap?.completedAt).toBeNull();
149
+
150
+ now = new Date(T0.getTime() + 60_000);
151
+ pages[2] = "repos_page_2";
152
+ fetchedPages = [];
153
+ const second = await run();
154
+ expect(second.outcome).toBe("complete");
155
+ expect(fetchedPages).toEqual([1, 2]);
156
+ expect(await prisma.gitHubCachedRepo.count()).toBe(3);
157
+ snap = await svc.getSnapshot(key);
158
+ expect(snap?.crawlStartedAt).toEqual(T0);
159
+ expect(snap?.completedAt).toEqual(now);
160
+ expect(snap?.attempts).toBe(0);
161
+ });
162
+
163
+ it("leaves completedAt unset on a total_count mismatch and restarts from page 1", async () => {
164
+ pages[2] = "repos_page_2_total_mismatch";
165
+ const out = await run();
166
+ expect(out.outcome).toBe("incomplete");
167
+ let snap = await svc.getSnapshot(key);
168
+ expect(snap?.completedAt).toBeNull();
169
+ expect(snap?.crawlPage).toBe(0);
170
+ expect(snap?.totalCount).toBe(4);
171
+
172
+ now = new Date(T0.getTime() + 60_000);
173
+ pages[2] = "repos_page_2";
174
+ fetchedPages = [];
175
+ expect((await run()).outcome).toBe("complete");
176
+ expect(fetchedPages).toEqual([1, 2]);
177
+ snap = await svc.getSnapshot(key);
178
+ expect(snap?.crawlStartedAt).toEqual(now);
179
+ });
180
+
181
+ it("stops on a 429 with rateLimitResetAt and no failure, keeping saved pages unswept", async () => {
182
+ const snap0 = await svc.upsertSnapshot(key);
183
+ await svc.upsertRepos(
184
+ snap0.id,
185
+ [{ githubId: 99, fullName: "acme-eng/older" }],
186
+ new Date(T0.getTime() - 1000),
187
+ );
188
+ pages[2] = "repos_429";
189
+ const out = await run();
190
+ expect(out.outcome).toBe("rate_limited");
191
+ expect(out.rateLimitResetAt).toEqual(new Date(T0.getTime() + 30_000));
192
+ const snap = await svc.getSnapshot(key);
193
+ expect(snap?.rateLimitResetAt).toEqual(new Date(T0.getTime() + 30_000));
194
+ expect(snap?.attempts).toBe(0);
195
+ expect(snap?.lastError).toBeNull();
196
+ expect(snap?.crawlPage).toBe(1);
197
+ expect(await names()).toEqual([
198
+ "acme-eng/api",
199
+ "acme-eng/web",
200
+ "acme-eng/older",
201
+ ]);
202
+ });
203
+
204
+ it("stops after a page that exhausted the quota, then resumes after the reset", async () => {
205
+ pages[1] = "repos_page_1_rate_limit_exhausted";
206
+ const out = await run();
207
+ expect(out.outcome).toBe("rate_limited");
208
+ expect(out.rateLimitResetAt).toEqual(RESET);
209
+ expect(fetchedPages).toEqual([1]);
210
+ expect(await prisma.gitHubCachedRepo.count()).toBe(2);
211
+
212
+ now = new Date(RESET.getTime() - 1000);
213
+ fetchedPages = [];
214
+ expect((await run()).outcome).toBe("rate_limited");
215
+ expect(fetchedPages).toEqual([]);
216
+
217
+ now = RESET;
218
+ pages[1] = "repos_page_1";
219
+ expect((await run()).outcome).toBe("complete");
220
+ expect(fetchedPages).toEqual([1, 2]);
221
+ expect(await prisma.gitHubCachedRepo.count()).toBe(3);
222
+ const snap = await svc.getSnapshot(key);
223
+ expect(snap?.rateLimitResetAt).toBeNull();
224
+ expect(snap?.crawlStartedAt).toEqual(T0);
225
+ });
226
+
227
+ it("treats a primary-limit 403 as a rate limit using X-RateLimit-Reset", async () => {
228
+ pages[1] = "repos_403_rate_limited";
229
+ const out = await run();
230
+ expect(out.outcome).toBe("rate_limited");
231
+ expect((await svc.getSnapshot(key))?.rateLimitResetAt).toEqual(RESET);
232
+ });
233
+
234
+ it("countReposSeenSince counts only rows seen at or after the cutoff", async () => {
235
+ const snap = await svc.upsertSnapshot(key);
236
+ await svc.upsertRepos(snap.id, [{ githubId: 1, fullName: "a/1" }], T0);
237
+ await svc.upsertRepos(
238
+ snap.id,
239
+ [{ githubId: 2, fullName: "a/2" }],
240
+ new Date(T0.getTime() - 1),
241
+ );
242
+ expect(await svc.countReposSeenSince(snap.id, T0)).toBe(1);
243
+ });
244
+ });