@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
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-repo-crawler.ts
|
|
3
|
+
* Resumable, rate-limit-aware crawl of an org's GitHub repositories into the
|
|
4
|
+
* repo cache (GLC-1.2). The engine is generic over a PageSource port; the
|
|
5
|
+
* lookup-App source (lookupRepoPageSource) adapts GithubLookupClient.
|
|
6
|
+
*
|
|
7
|
+
* One call to crawlRepos() is one run:
|
|
8
|
+
* - Fresh start (no crawl in progress, or the last one completed or was
|
|
9
|
+
* abandoned): crawlStartedAt = now, completedAt = null, from page 1.
|
|
10
|
+
* - Resume: keep crawlStartedAt, start at max(1, crawlPage - 1). The overlap
|
|
11
|
+
* page catches rows that shifted back a page between runs; GitHub's order
|
|
12
|
+
* is not documented, so nothing here relies on it.
|
|
13
|
+
* - Each page is upserted (seenAt = now) and crawlPage saved as it lands.
|
|
14
|
+
* - On the last page, the distinct rows seen this crawl (seenAt >=
|
|
15
|
+
* crawlStartedAt) are compared with total_count. Equal: completedAt is set
|
|
16
|
+
* and the generation sweep drops rows from earlier crawls. Unequal: the
|
|
17
|
+
* crawl is not trusted, completedAt stays unset, and the next run starts
|
|
18
|
+
* over from page 1. A partial crawl never sweeps.
|
|
19
|
+
* - A rate limit records rateLimitResetAt and ends the run cleanly (no
|
|
20
|
+
* attempts/lastError); runs before that time do not fetch. Other source
|
|
21
|
+
* errors record lastError, bump attempts and set a backoff nextAttemptAt.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { Clock } from "./clock.ts";
|
|
25
|
+
import { GithubEnterpriseError } from "./github-enterprise-client.ts";
|
|
26
|
+
import {
|
|
27
|
+
type GithubLookupClient,
|
|
28
|
+
GithubLookupRateLimitError,
|
|
29
|
+
rateLimitResetAt,
|
|
30
|
+
} from "./github-lookup-client.ts";
|
|
31
|
+
import type {
|
|
32
|
+
CachedRepoInput,
|
|
33
|
+
SnapshotKey,
|
|
34
|
+
SnapshotProgress,
|
|
35
|
+
} from "./github-repo-cache.ts";
|
|
36
|
+
|
|
37
|
+
/** One page of the listing being crawled. */
|
|
38
|
+
export interface RepoPage {
|
|
39
|
+
repos: CachedRepoInput[];
|
|
40
|
+
/** The source's total row count for the whole listing. */
|
|
41
|
+
totalCount: number;
|
|
42
|
+
/** Whether a further page exists. An empty page is always the last. */
|
|
43
|
+
hasNext: boolean;
|
|
44
|
+
/** Quota state reported with this page; remaining 0 ends the run. */
|
|
45
|
+
rateLimit?: { remaining: number | null; resetAt: Date | null };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Port: fetch page `page` (1-based). A rate limit is signalled by throwing a
|
|
50
|
+
* GithubEnterpriseError of kind "rate_limit" (GithubLookupRateLimitError
|
|
51
|
+
* carries the exact resetAt). Implementations must time out their fetches.
|
|
52
|
+
*/
|
|
53
|
+
export interface PageSource {
|
|
54
|
+
fetchPage(page: number): Promise<RepoPage>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The snapshot fields the engine reads. */
|
|
58
|
+
export interface CrawlSnapshot {
|
|
59
|
+
id: string;
|
|
60
|
+
crawlPage: number;
|
|
61
|
+
crawlStartedAt: Date | null;
|
|
62
|
+
completedAt: Date | null;
|
|
63
|
+
totalCount: number | null;
|
|
64
|
+
lastError: string | null;
|
|
65
|
+
attempts: number;
|
|
66
|
+
nextAttemptAt: Date | null;
|
|
67
|
+
rateLimitResetAt: Date | null;
|
|
68
|
+
lastTickAt: Date | null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Port: the storage the engine needs. GitHubRepoCacheService satisfies it. */
|
|
72
|
+
export interface CrawlStore {
|
|
73
|
+
getSnapshot(key: SnapshotKey): Promise<CrawlSnapshot | null>;
|
|
74
|
+
upsertSnapshot(
|
|
75
|
+
key: SnapshotKey,
|
|
76
|
+
progress?: SnapshotProgress,
|
|
77
|
+
): Promise<CrawlSnapshot>;
|
|
78
|
+
upsertRepos(
|
|
79
|
+
snapshotId: string,
|
|
80
|
+
repos: CachedRepoInput[],
|
|
81
|
+
seenAt?: Date,
|
|
82
|
+
): Promise<number>;
|
|
83
|
+
countReposSeenSince(snapshotId: string, since: Date): Promise<number>;
|
|
84
|
+
sweepGeneration(snapshotId: string): Promise<number>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type CrawlOutcome =
|
|
88
|
+
/** Last page reached and seen rows matched total_count; swept. */
|
|
89
|
+
| "complete"
|
|
90
|
+
/** Last page reached but the counts disagreed; next run restarts. */
|
|
91
|
+
| "incomplete"
|
|
92
|
+
/** Page budget used up; next run resumes. */
|
|
93
|
+
| "in_progress"
|
|
94
|
+
/** Stopped on a rate limit; next run resumes after rateLimitResetAt. */
|
|
95
|
+
| "rate_limited"
|
|
96
|
+
/** A source error; recorded on the snapshot. */
|
|
97
|
+
| "failed";
|
|
98
|
+
|
|
99
|
+
export interface CrawlResult {
|
|
100
|
+
outcome: CrawlOutcome;
|
|
101
|
+
pagesFetched: number;
|
|
102
|
+
/** Rows deleted by the generation sweep (complete only). */
|
|
103
|
+
swept?: number;
|
|
104
|
+
rateLimitResetAt?: Date;
|
|
105
|
+
error?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface CrawlOptions {
|
|
109
|
+
key: SnapshotKey;
|
|
110
|
+
source: PageSource;
|
|
111
|
+
store: CrawlStore;
|
|
112
|
+
clock: Clock;
|
|
113
|
+
/** Most pages to fetch in this run. Default 1000. */
|
|
114
|
+
maxPages?: number;
|
|
115
|
+
/** Delay before retrying after the n-th consecutive failure. */
|
|
116
|
+
backoffMs?: (attempts: number) => number;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const DEFAULT_MAX_PAGES = 1000;
|
|
120
|
+
const MAX_ERROR_LENGTH = 500;
|
|
121
|
+
|
|
122
|
+
/** 1m, 2m, 4m, ... capped at 1h. */
|
|
123
|
+
export function defaultCrawlBackoffMs(attempts: number): number {
|
|
124
|
+
return Math.min(60_000 * 2 ** Math.max(0, attempts - 1), 3_600_000);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function crawlRepos(opts: CrawlOptions): Promise<CrawlResult> {
|
|
128
|
+
const { key, source, store, clock } = opts;
|
|
129
|
+
const maxPages = opts.maxPages ?? DEFAULT_MAX_PAGES;
|
|
130
|
+
const backoffMs = opts.backoffMs ?? defaultCrawlBackoffMs;
|
|
131
|
+
|
|
132
|
+
let snap =
|
|
133
|
+
(await store.getSnapshot(key)) ?? (await store.upsertSnapshot(key));
|
|
134
|
+
|
|
135
|
+
const resetAt = snap.rateLimitResetAt;
|
|
136
|
+
if (resetAt && resetAt.getTime() > clock.now().getTime()) {
|
|
137
|
+
return {
|
|
138
|
+
outcome: "rate_limited",
|
|
139
|
+
pagesFetched: 0,
|
|
140
|
+
rateLimitResetAt: resetAt,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const fresh =
|
|
145
|
+
snap.crawlStartedAt === null ||
|
|
146
|
+
snap.completedAt !== null ||
|
|
147
|
+
snap.crawlPage < 1;
|
|
148
|
+
if (fresh) {
|
|
149
|
+
snap = await store.upsertSnapshot(key, {
|
|
150
|
+
crawlStartedAt: clock.now(),
|
|
151
|
+
completedAt: null,
|
|
152
|
+
crawlPage: 0,
|
|
153
|
+
totalCount: null,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
const crawlStartedAt = snap.crawlStartedAt as Date;
|
|
157
|
+
const startPage = fresh ? 1 : Math.max(1, snap.crawlPage - 1);
|
|
158
|
+
|
|
159
|
+
let pagesFetched = 0;
|
|
160
|
+
for (let page = startPage; pagesFetched < maxPages; page++) {
|
|
161
|
+
let result: RepoPage;
|
|
162
|
+
try {
|
|
163
|
+
result = await source.fetchPage(page);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
return recordError(err);
|
|
166
|
+
}
|
|
167
|
+
pagesFetched++;
|
|
168
|
+
|
|
169
|
+
await store.upsertRepos(snap.id, result.repos, clock.now());
|
|
170
|
+
await store.upsertSnapshot(key, {
|
|
171
|
+
crawlPage: page,
|
|
172
|
+
totalCount: result.totalCount,
|
|
173
|
+
rateLimitResetAt: null,
|
|
174
|
+
lastTickAt: clock.now(),
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
const last = !result.hasNext || result.repos.length === 0;
|
|
178
|
+
if (last) return finish(result.totalCount);
|
|
179
|
+
|
|
180
|
+
const rl = result.rateLimit;
|
|
181
|
+
if (rl && rl.remaining === 0) {
|
|
182
|
+
const at = rateLimitResetAt(
|
|
183
|
+
{ remaining: 0, resetAt: rl.resetAt, retryAfterSeconds: null },
|
|
184
|
+
clock.now(),
|
|
185
|
+
);
|
|
186
|
+
await store.upsertSnapshot(key, { rateLimitResetAt: at });
|
|
187
|
+
return { outcome: "rate_limited", pagesFetched, rateLimitResetAt: at };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return { outcome: "in_progress", pagesFetched };
|
|
191
|
+
|
|
192
|
+
async function finish(totalCount: number): Promise<CrawlResult> {
|
|
193
|
+
const seen = await store.countReposSeenSince(snap.id, crawlStartedAt);
|
|
194
|
+
if (seen !== totalCount) {
|
|
195
|
+
const error = `total_count mismatch: saw ${seen} repos this crawl, GitHub reported ${totalCount}`;
|
|
196
|
+
await store.upsertSnapshot(key, {
|
|
197
|
+
crawlPage: 0,
|
|
198
|
+
completedAt: null,
|
|
199
|
+
lastError: error,
|
|
200
|
+
lastTickAt: clock.now(),
|
|
201
|
+
});
|
|
202
|
+
return { outcome: "incomplete", pagesFetched, error };
|
|
203
|
+
}
|
|
204
|
+
await store.upsertSnapshot(key, {
|
|
205
|
+
completedAt: clock.now(),
|
|
206
|
+
lastError: null,
|
|
207
|
+
attempts: 0,
|
|
208
|
+
nextAttemptAt: null,
|
|
209
|
+
lastTickAt: clock.now(),
|
|
210
|
+
});
|
|
211
|
+
const swept = await store.sweepGeneration(snap.id);
|
|
212
|
+
return { outcome: "complete", pagesFetched, swept };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function recordError(err: unknown): Promise<CrawlResult> {
|
|
216
|
+
const now = clock.now();
|
|
217
|
+
if (err instanceof GithubEnterpriseError && err.kind === "rate_limit") {
|
|
218
|
+
const at =
|
|
219
|
+
err instanceof GithubLookupRateLimitError
|
|
220
|
+
? err.resetAt
|
|
221
|
+
: rateLimitResetAt(
|
|
222
|
+
{
|
|
223
|
+
remaining: null,
|
|
224
|
+
resetAt: null,
|
|
225
|
+
retryAfterSeconds: err.retryAfterSeconds ?? null,
|
|
226
|
+
},
|
|
227
|
+
now,
|
|
228
|
+
);
|
|
229
|
+
await store.upsertSnapshot(key, {
|
|
230
|
+
rateLimitResetAt: at,
|
|
231
|
+
lastTickAt: now,
|
|
232
|
+
});
|
|
233
|
+
return { outcome: "rate_limited", pagesFetched, rateLimitResetAt: at };
|
|
234
|
+
}
|
|
235
|
+
const error = (err instanceof Error ? err.message : String(err)).slice(
|
|
236
|
+
0,
|
|
237
|
+
MAX_ERROR_LENGTH,
|
|
238
|
+
);
|
|
239
|
+
const attempts = snap.attempts + 1;
|
|
240
|
+
await store.upsertSnapshot(key, {
|
|
241
|
+
lastError: error,
|
|
242
|
+
attempts,
|
|
243
|
+
nextAttemptAt: new Date(now.getTime() + backoffMs(attempts)),
|
|
244
|
+
lastTickAt: now,
|
|
245
|
+
});
|
|
246
|
+
return { outcome: "failed", pagesFetched, error };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** PageSource over the lookup App's GET /installation/repositories for `org`. */
|
|
251
|
+
export function lookupRepoPageSource(
|
|
252
|
+
client: Pick<GithubLookupClient, "listInstallationRepositoriesPage">,
|
|
253
|
+
org: string,
|
|
254
|
+
): PageSource {
|
|
255
|
+
return {
|
|
256
|
+
async fetchPage(page: number): Promise<RepoPage> {
|
|
257
|
+
const res = await client.listInstallationRepositoriesPage(org, page);
|
|
258
|
+
return {
|
|
259
|
+
repos: res.repositories.map((r) => ({
|
|
260
|
+
githubId: r.id,
|
|
261
|
+
fullName: r.fullName,
|
|
262
|
+
archived: r.archived,
|
|
263
|
+
})),
|
|
264
|
+
totalCount: res.totalCount,
|
|
265
|
+
hasNext: res.hasNext,
|
|
266
|
+
rateLimit: {
|
|
267
|
+
remaining: res.rateLimit.remaining,
|
|
268
|
+
resetAt: res.rateLimit.resetAt,
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
}
|