@app-vitals/agent-admin 1.75.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/prisma/client/browser.ts +15 -0
- package/prisma/client/client.ts +15 -0
- package/prisma/client/internal/class.ts +34 -4
- package/prisma/client/internal/prismaNamespace.ts +284 -2
- package/prisma/client/internal/prismaNamespaceBrowser.ts +58 -1
- package/prisma/client/models/GitHubCachedRepo.ts +1430 -0
- package/prisma/client/models/GitHubRepoAccess.ts +1397 -0
- package/prisma/client/models/GitHubRepoSnapshot.ts +1807 -0
- package/prisma/client/models.ts +3 -0
- package/prisma/migrations/20261120000000_add_github_repo_cache/migration.sql +75 -0
- package/prisma/schema/schema.prisma +62 -0
- 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.integration.test.ts +227 -0
- package/src/github-repo-cache.ts +304 -0
- package/src/github-repo-cache.unit.test.ts +66 -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/prisma/client/models.ts
CHANGED
|
@@ -40,4 +40,7 @@ export type * from './models/ChatThreadWatch.ts'
|
|
|
40
40
|
export type * from './models/UserNotificationPrefs.ts'
|
|
41
41
|
export type * from './models/AgentMarketplace.ts'
|
|
42
42
|
export type * from './models/GitHubReconcileAudit.ts'
|
|
43
|
+
export type * from './models/GitHubRepoSnapshot.ts'
|
|
44
|
+
export type * from './models/GitHubCachedRepo.ts'
|
|
45
|
+
export type * from './models/GitHubRepoAccess.ts'
|
|
43
46
|
export type * from './commonInputTypes.ts'
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
-- GLC-1.1: GitHub repo/access cache. Additive only: three new tables, nothing existing is touched.
|
|
2
|
+
-- CreateTable
|
|
3
|
+
CREATE TABLE "GitHubRepoSnapshot" (
|
|
4
|
+
"id" TEXT NOT NULL,
|
|
5
|
+
"accountId" TEXT NOT NULL,
|
|
6
|
+
"appKind" TEXT NOT NULL,
|
|
7
|
+
"appRef" TEXT NOT NULL,
|
|
8
|
+
"org" TEXT NOT NULL,
|
|
9
|
+
"crawlPage" INTEGER NOT NULL DEFAULT 0,
|
|
10
|
+
"crawlStartedAt" TIMESTAMP(3),
|
|
11
|
+
"completedAt" TIMESTAMP(3),
|
|
12
|
+
"totalCount" INTEGER,
|
|
13
|
+
"lastError" TEXT,
|
|
14
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
15
|
+
"nextAttemptAt" TIMESTAMP(3),
|
|
16
|
+
"rateLimitResetAt" TIMESTAMP(3),
|
|
17
|
+
"leaseHolder" TEXT,
|
|
18
|
+
"leasedUntil" TIMESTAMP(3),
|
|
19
|
+
"lastTickAt" TIMESTAMP(3),
|
|
20
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
21
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
22
|
+
|
|
23
|
+
CONSTRAINT "GitHubRepoSnapshot_pkey" PRIMARY KEY ("id")
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
-- CreateTable
|
|
27
|
+
CREATE TABLE "GitHubCachedRepo" (
|
|
28
|
+
"id" TEXT NOT NULL,
|
|
29
|
+
"snapshotId" TEXT NOT NULL,
|
|
30
|
+
"githubId" BIGINT NOT NULL,
|
|
31
|
+
"fullName" TEXT NOT NULL,
|
|
32
|
+
"archived" BOOLEAN NOT NULL DEFAULT false,
|
|
33
|
+
"seenAt" TIMESTAMP(3) NOT NULL,
|
|
34
|
+
|
|
35
|
+
CONSTRAINT "GitHubCachedRepo_pkey" PRIMARY KEY ("id")
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
-- CreateTable
|
|
39
|
+
CREATE TABLE "GitHubRepoAccess" (
|
|
40
|
+
"id" TEXT NOT NULL,
|
|
41
|
+
"accountId" TEXT NOT NULL,
|
|
42
|
+
"org" TEXT NOT NULL,
|
|
43
|
+
"repo" TEXT NOT NULL,
|
|
44
|
+
"username" TEXT NOT NULL,
|
|
45
|
+
"canPush" BOOLEAN NOT NULL DEFAULT false,
|
|
46
|
+
"level" TEXT,
|
|
47
|
+
"checkedAt" TIMESTAMP(3) NOT NULL,
|
|
48
|
+
"status" TEXT NOT NULL,
|
|
49
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
50
|
+
"nextAttemptAt" TIMESTAMP(3),
|
|
51
|
+
"lastError" TEXT,
|
|
52
|
+
|
|
53
|
+
CONSTRAINT "GitHubRepoAccess_pkey" PRIMARY KEY ("id")
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
-- CreateIndex
|
|
57
|
+
CREATE INDEX "GitHubRepoSnapshot_accountId_appKind_org_idx" ON "GitHubRepoSnapshot"("accountId", "appKind", "org");
|
|
58
|
+
|
|
59
|
+
-- CreateIndex
|
|
60
|
+
CREATE UNIQUE INDEX "GitHubRepoSnapshot_accountId_appKind_appRef_org_key" ON "GitHubRepoSnapshot"("accountId", "appKind", "appRef", "org");
|
|
61
|
+
|
|
62
|
+
-- CreateIndex
|
|
63
|
+
CREATE INDEX "GitHubCachedRepo_snapshotId_seenAt_idx" ON "GitHubCachedRepo"("snapshotId", "seenAt");
|
|
64
|
+
|
|
65
|
+
-- CreateIndex
|
|
66
|
+
CREATE UNIQUE INDEX "GitHubCachedRepo_snapshotId_githubId_key" ON "GitHubCachedRepo"("snapshotId", "githubId");
|
|
67
|
+
|
|
68
|
+
-- CreateIndex
|
|
69
|
+
CREATE INDEX "GitHubRepoAccess_accountId_org_username_nextAttemptAt_idx" ON "GitHubRepoAccess"("accountId", "org", "username", "nextAttemptAt");
|
|
70
|
+
|
|
71
|
+
-- CreateIndex
|
|
72
|
+
CREATE UNIQUE INDEX "GitHubRepoAccess_accountId_org_repo_username_key" ON "GitHubRepoAccess"("accountId", "org", "repo", "username");
|
|
73
|
+
|
|
74
|
+
-- AddForeignKey
|
|
75
|
+
ALTER TABLE "GitHubCachedRepo" ADD CONSTRAINT "GitHubCachedRepo_snapshotId_fkey" FOREIGN KEY ("snapshotId") REFERENCES "GitHubRepoSnapshot"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
@@ -744,3 +744,65 @@ model GitHubReconcileAudit {
|
|
|
744
744
|
|
|
745
745
|
@@index([agentId, createdAt])
|
|
746
746
|
}
|
|
747
|
+
|
|
748
|
+
// ─── GitHub repo/access cache (GLC-1.1) ──────────────────────────────────────
|
|
749
|
+
// Per-org crawl snapshot, the repos seen by it, and per-user push access.
|
|
750
|
+
// accountId/appRef are plain columns (no relations): cache rows are disposable.
|
|
751
|
+
// Debug detail (lastError, attempts, timestamps) is stored as plain columns so
|
|
752
|
+
// any existing view can show it.
|
|
753
|
+
|
|
754
|
+
model GitHubRepoSnapshot {
|
|
755
|
+
id String @id @default(cuid())
|
|
756
|
+
accountId String
|
|
757
|
+
appKind String // 'lookup' | 'agent'
|
|
758
|
+
appRef String // app id (lookup) or agent id (agent)
|
|
759
|
+
org String
|
|
760
|
+
crawlPage Int @default(0)
|
|
761
|
+
crawlStartedAt DateTime?
|
|
762
|
+
completedAt DateTime?
|
|
763
|
+
totalCount Int?
|
|
764
|
+
lastError String?
|
|
765
|
+
attempts Int @default(0)
|
|
766
|
+
nextAttemptAt DateTime?
|
|
767
|
+
rateLimitResetAt DateTime?
|
|
768
|
+
leaseHolder String?
|
|
769
|
+
leasedUntil DateTime?
|
|
770
|
+
lastTickAt DateTime?
|
|
771
|
+
createdAt DateTime @default(now())
|
|
772
|
+
updatedAt DateTime @updatedAt
|
|
773
|
+
repos GitHubCachedRepo[]
|
|
774
|
+
|
|
775
|
+
@@unique([accountId, appKind, appRef, org])
|
|
776
|
+
@@index([accountId, appKind, org])
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
model GitHubCachedRepo {
|
|
780
|
+
id String @id @default(cuid())
|
|
781
|
+
snapshotId String
|
|
782
|
+
snapshot GitHubRepoSnapshot @relation(fields: [snapshotId], references: [id], onDelete: Cascade)
|
|
783
|
+
githubId BigInt
|
|
784
|
+
fullName String
|
|
785
|
+
archived Boolean @default(false)
|
|
786
|
+
seenAt DateTime
|
|
787
|
+
|
|
788
|
+
@@unique([snapshotId, githubId])
|
|
789
|
+
@@index([snapshotId, seenAt])
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
model GitHubRepoAccess {
|
|
793
|
+
id String @id @default(cuid())
|
|
794
|
+
accountId String
|
|
795
|
+
org String
|
|
796
|
+
repo String
|
|
797
|
+
username String
|
|
798
|
+
canPush Boolean @default(false)
|
|
799
|
+
level String?
|
|
800
|
+
checkedAt DateTime
|
|
801
|
+
status String // 'ok' | 'error' | 'terminal'
|
|
802
|
+
attempts Int @default(0)
|
|
803
|
+
nextAttemptAt DateTime?
|
|
804
|
+
lastError String?
|
|
805
|
+
|
|
806
|
+
@@unique([accountId, org, repo, username])
|
|
807
|
+
@@index([accountId, org, username, nextAttemptAt])
|
|
808
|
+
}
|
|
@@ -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;
|