@app-vitals/agent-admin 1.76.0 → 1.77.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.
- package/package.json +2 -2
- package/src/fixtures/github-lookup-cassette.json +65 -0
- package/src/github-lookup-client.integration.test.ts +90 -1
- package/src/github-lookup-client.ts +156 -6
- package/src/github-lookup-client.unit.test.ts +147 -2
- package/src/github-repo-cache.ts +8 -0
- package/src/github-repo-crawler.integration.test.ts +244 -0
- package/src/github-repo-crawler.ts +273 -0
- package/src/github-repo-crawler.unit.test.ts +452 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@app-vitals/agent-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.77.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/app-vitals/agent.git",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@anthropic-ai/sdk": "0.137.0",
|
|
46
|
-
"@app-vitals/agent-lib": "1.
|
|
46
|
+
"@app-vitals/agent-lib": "1.77.0",
|
|
47
47
|
"@hono/zod-openapi": "^1.0.0",
|
|
48
48
|
"@prisma/adapter-pg": "^7.10.0",
|
|
49
49
|
"@prisma/client": "^7.10.0",
|
|
@@ -513,5 +513,70 @@
|
|
|
513
513
|
"message": "Service Unavailable",
|
|
514
514
|
"documentation_url": "https://docs.github.com/rest"
|
|
515
515
|
}
|
|
516
|
+
},
|
|
517
|
+
"repos_page_1_rate_limit_exhausted": {
|
|
518
|
+
"status": 200,
|
|
519
|
+
"headers": {
|
|
520
|
+
"link": "<https://ghe.test/installation/repositories?per_page=100&page=2>; rel=\"next\"",
|
|
521
|
+
"x-ratelimit-limit": "5000",
|
|
522
|
+
"x-ratelimit-remaining": "0",
|
|
523
|
+
"x-ratelimit-reset": "1794226500"
|
|
524
|
+
},
|
|
525
|
+
"body": {
|
|
526
|
+
"total_count": 3,
|
|
527
|
+
"repositories": [
|
|
528
|
+
{
|
|
529
|
+
"id": 1,
|
|
530
|
+
"name": "api",
|
|
531
|
+
"full_name": "acme-eng/api",
|
|
532
|
+
"private": false,
|
|
533
|
+
"archived": false
|
|
534
|
+
},
|
|
535
|
+
{
|
|
536
|
+
"id": 2,
|
|
537
|
+
"name": "web",
|
|
538
|
+
"full_name": "acme-eng/web",
|
|
539
|
+
"private": true,
|
|
540
|
+
"archived": false
|
|
541
|
+
}
|
|
542
|
+
]
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
"repos_page_2_total_mismatch": {
|
|
546
|
+
"status": 200,
|
|
547
|
+
"body": {
|
|
548
|
+
"total_count": 4,
|
|
549
|
+
"repositories": [
|
|
550
|
+
{
|
|
551
|
+
"id": 3,
|
|
552
|
+
"name": "infra",
|
|
553
|
+
"full_name": "acme-eng/infra",
|
|
554
|
+
"private": false,
|
|
555
|
+
"archived": false
|
|
556
|
+
}
|
|
557
|
+
]
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
"repos_403_rate_limited": {
|
|
561
|
+
"status": 403,
|
|
562
|
+
"headers": {
|
|
563
|
+
"x-ratelimit-limit": "5000",
|
|
564
|
+
"x-ratelimit-remaining": "0",
|
|
565
|
+
"x-ratelimit-reset": "1794226500"
|
|
566
|
+
},
|
|
567
|
+
"body": {
|
|
568
|
+
"message": "API rate limit exceeded for installation ID 7001.",
|
|
569
|
+
"documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"
|
|
570
|
+
}
|
|
571
|
+
},
|
|
572
|
+
"repos_403_secondary_retry_after": {
|
|
573
|
+
"status": 403,
|
|
574
|
+
"headers": {
|
|
575
|
+
"retry-after": "120"
|
|
576
|
+
},
|
|
577
|
+
"body": {
|
|
578
|
+
"message": "You have exceeded a secondary rate limit. Please wait a few minutes before you try again.",
|
|
579
|
+
"documentation_url": "https://docs.github.com/rest/overview/rate-limits-for-the-rest-api#about-secondary-rate-limits"
|
|
580
|
+
}
|
|
516
581
|
}
|
|
517
582
|
}
|
|
@@ -12,7 +12,11 @@ import { describe, expect, it } from "bun:test";
|
|
|
12
12
|
import { generateKeyPairSync } from "node:crypto";
|
|
13
13
|
import { readFileSync } from "node:fs";
|
|
14
14
|
import type { GithubEnterpriseErrorKind } from "./github-enterprise-client.ts";
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
GithubLookupClient,
|
|
17
|
+
GithubLookupRateLimitError,
|
|
18
|
+
type RepoRole,
|
|
19
|
+
} from "./github-lookup-client.ts";
|
|
16
20
|
|
|
17
21
|
interface CassetteEntry {
|
|
18
22
|
status: number;
|
|
@@ -228,6 +232,91 @@ describe("listInstallationRepositories", () => {
|
|
|
228
232
|
}
|
|
229
233
|
});
|
|
230
234
|
|
|
235
|
+
describe("listInstallationRepositoriesPage", () => {
|
|
236
|
+
const RESET = new Date("2026-11-09T12:15:00Z");
|
|
237
|
+
|
|
238
|
+
it("returns one page's rows, total_count and Link-driven hasNext", async () => {
|
|
239
|
+
const { client, calls } = makeClient({
|
|
240
|
+
[`${REPOS}?page=1`]: "repos_page_1",
|
|
241
|
+
[`${REPOS}?page=2`]: "repos_page_2",
|
|
242
|
+
});
|
|
243
|
+
const p1 = await client.listInstallationRepositoriesPage("acme-eng", 1);
|
|
244
|
+
expect(p1.repositories.map((r) => r.fullName)).toEqual([
|
|
245
|
+
"acme-eng/api",
|
|
246
|
+
"acme-eng/web",
|
|
247
|
+
]);
|
|
248
|
+
expect(p1.totalCount).toBe(3);
|
|
249
|
+
expect(p1.hasNext).toBe(true);
|
|
250
|
+
const p2 = await client.listInstallationRepositoriesPage("acme-eng", 2);
|
|
251
|
+
expect(p2.repositories.map((r) => r.id)).toEqual([3]);
|
|
252
|
+
expect(p2.hasNext).toBe(false);
|
|
253
|
+
const pages = calls.filter((c) =>
|
|
254
|
+
c.path.startsWith("/installation/repositories"),
|
|
255
|
+
);
|
|
256
|
+
expect(pages.map((c) => c.path)).toEqual([
|
|
257
|
+
"/installation/repositories?per_page=100&page=1",
|
|
258
|
+
"/installation/repositories?per_page=100&page=2",
|
|
259
|
+
]);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("reports the rate-limit headers of a successful page", async () => {
|
|
263
|
+
const { client } = makeClient({
|
|
264
|
+
[REPOS]: "repos_page_1_rate_limit_exhausted",
|
|
265
|
+
});
|
|
266
|
+
const page = await client.listInstallationRepositoriesPage("acme-eng", 1);
|
|
267
|
+
expect(page.repositories).toHaveLength(2);
|
|
268
|
+
expect(page.rateLimit).toEqual({
|
|
269
|
+
remaining: 0,
|
|
270
|
+
resetAt: RESET,
|
|
271
|
+
retryAfterSeconds: null,
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("raises a rate-limit error carrying Retry-After as resetAt on 429", async () => {
|
|
276
|
+
const { client } = makeClient({ [REPOS]: "repos_429" });
|
|
277
|
+
const e = await errOf(
|
|
278
|
+
client.listInstallationRepositoriesPage("acme-eng", 1),
|
|
279
|
+
);
|
|
280
|
+
expect(e).toBeInstanceOf(GithubLookupRateLimitError);
|
|
281
|
+
expect(e.kind).toBe("rate_limit");
|
|
282
|
+
expect((e as GithubLookupRateLimitError).resetAt).toEqual(
|
|
283
|
+
new Date(NOW.getTime() + 30_000),
|
|
284
|
+
);
|
|
285
|
+
expectNoSecrets(e);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("raises a rate-limit error carrying X-RateLimit-Reset on a primary-limit 403", async () => {
|
|
289
|
+
const { client } = makeClient({ [REPOS]: "repos_403_rate_limited" });
|
|
290
|
+
const e = await errOf(
|
|
291
|
+
client.listInstallationRepositoriesPage("acme-eng", 1),
|
|
292
|
+
);
|
|
293
|
+
expect(e).toBeInstanceOf(GithubLookupRateLimitError);
|
|
294
|
+
expect((e as GithubLookupRateLimitError).resetAt).toEqual(RESET);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("raises a rate-limit error on a secondary-limit 403 with Retry-After", async () => {
|
|
298
|
+
const { client } = makeClient({
|
|
299
|
+
[REPOS]: "repos_403_secondary_retry_after",
|
|
300
|
+
});
|
|
301
|
+
const e = await errOf(
|
|
302
|
+
client.listInstallationRepositoriesPage("acme-eng", 1),
|
|
303
|
+
);
|
|
304
|
+
expect(e).toBeInstanceOf(GithubLookupRateLimitError);
|
|
305
|
+
expect((e as GithubLookupRateLimitError).resetAt).toEqual(
|
|
306
|
+
new Date(NOW.getTime() + 120_000),
|
|
307
|
+
);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("keeps a plain permission 403 a permission error", async () => {
|
|
311
|
+
const { client } = makeClient({ [REPOS]: "repos_403" });
|
|
312
|
+
const e = await errOf(
|
|
313
|
+
client.listInstallationRepositoriesPage("acme-eng", 1),
|
|
314
|
+
);
|
|
315
|
+
expect(e.kind).toBe("permission");
|
|
316
|
+
expect(e).not.toBeInstanceOf(GithubLookupRateLimitError);
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
|
|
231
320
|
describe("getCollaboratorPermission", () => {
|
|
232
321
|
const roles: Array<[string, RepoRole]> = [
|
|
233
322
|
["permission_admin", "admin"],
|
|
@@ -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(
|
|
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
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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(
|
|
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(
|
|
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
|
});
|
package/src/github-repo-cache.ts
CHANGED
|
@@ -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.
|