@app-vitals/agent-admin 1.79.0 → 1.81.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.
@@ -1,391 +1,86 @@
1
1
  /**
2
- * admin/src/github-lookup-repositories.integration.test.ts
3
- * The AdminPlatformServices.githubLookup lister over a real GithubLookupClient
4
- * replaying hand-authored responses through an injected fetchFn (no global
5
- * fetch override). The installer side is a stub org list. RSA key generated
6
- * in-test.
2
+ * Integration: githubLookup.listRepositories over a real repo cache. Requires
3
+ * DATABASE_URL_ADMIN_TEST; skips otherwise. A throwing fetch proves no GitHub
4
+ * call is made.
7
5
  */
8
6
 
9
- import { describe, expect, it } from "bun:test";
10
- import { generateKeyPairSync } from "node:crypto";
7
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
9
  import { createGithubLookupService } from "./github-enterprise-api.ts";
12
10
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
13
- import { GithubEnterpriseError } from "./github-enterprise-client.ts";
14
- import { GithubLookupClient } from "./github-lookup-client.ts";
15
-
16
- const { privateKey } = generateKeyPairSync("rsa", {
17
- modulusLength: 2048,
18
- privateKeyEncoding: { type: "pkcs8", format: "pem" },
19
- publicKeyEncoding: { type: "spki", format: "pem" },
20
- });
21
-
22
- const NOW = new Date("2026-11-09T12:00:00Z");
23
- const INSTALLATIONS: Record<string, number> = { acme: 1, beta: 2 };
24
-
25
- const repo = (owner: string, name: string, archived = false, id = 1) => ({
26
- id,
27
- name,
28
- full_name: `${owner}/${name}`,
29
- private: true,
30
- archived,
11
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
12
+ import { createAdminPrismaClient } from "./prisma-client.ts";
13
+
14
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
15
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
16
+
17
+ const NOW = new Date("2026-11-20T12:00:00Z");
18
+ const key = (org: string) => ({
19
+ accountId: "acct",
20
+ appKind: "lookup" as const,
21
+ appRef: "555",
22
+ org,
31
23
  });
32
24
 
33
- type Handler = (url: URL, installId?: number) => Response;
34
-
35
- /** Replays the org-installation, token and repository-list endpoints. */
36
- function replay(repos: Handler) {
37
- return (async (input: RequestInfo | URL, init?: RequestInit) => {
38
- const u = new URL(input.toString());
39
- const method = init?.method ?? "GET";
40
- const inst = u.pathname.match(/^\/orgs\/([^/]+)\/installation$/);
41
- if (inst) {
42
- const id = INSTALLATIONS[inst[1]];
43
- return id
44
- ? Response.json({ id, repository_selection: "all" })
45
- : Response.json({ message: "Not Found" }, { status: 404 });
46
- }
47
- const mint = u.pathname.match(
48
- /^\/app\/installations\/(\d+)\/access_tokens$/,
49
- );
50
- if (mint && method === "POST") {
51
- return Response.json({
52
- token: `ghs_tok${mint[1]}`,
53
- expires_at: "2026-11-09T13:00:00Z",
54
- });
55
- }
56
- if (u.pathname === "/app/installations") {
57
- return Response.json(
58
- Object.entries(INSTALLATIONS).map(([login, id]) => ({
59
- id,
60
- account: { login, type: "Organization" },
61
- })),
62
- );
63
- }
64
- if (u.pathname === "/installation/repositories") {
65
- const bearer = String(new Headers(init?.headers).get("authorization"));
66
- return repos(u, Number(bearer.replace(/\D/g, "")));
67
- }
68
- return Response.json({ message: "Not Found" }, { status: 404 });
69
- }) as unknown as typeof fetch;
70
- }
71
-
72
- function service(orgs: string[], fetchFn: typeof fetch) {
73
- return createGithubLookupService({
74
- appService: {} as never,
75
- clients: {
76
- installer: {
77
- listInstallableOrganizations: async () =>
78
- orgs.map((login) => ({ login })),
79
- },
80
- lookup: new GithubLookupClient({
81
- appId: "555",
82
- privateKey,
83
- fetchFn,
84
- now: () => NOW,
85
- }),
86
- },
87
- });
88
- }
89
-
90
- describe("githubLookup.listRepositories", () => {
91
- it("lists repos across multiple orgs, carrying archived", async () => {
92
- const svc = service(
93
- ["acme", "beta"],
94
- replay((_u, id) =>
95
- Response.json({
96
- repositories:
97
- id === 1
98
- ? [repo("acme", "api", false, 10), repo("acme", "old", true, 11)]
99
- : [repo("beta", "web", false, 20)],
100
- }),
101
- ),
102
- );
103
- expect(await svc.listRepositories()).toEqual({
104
- configured: true,
105
- repos: [
106
- { fullName: "acme/api", archived: false },
107
- { fullName: "acme/old", archived: true },
108
- { fullName: "beta/web", archived: false },
109
- ],
110
- });
111
- });
112
-
113
- it("follows pagination within an org", async () => {
114
- const page1 = Array.from({ length: 100 }, (_, i) =>
115
- repo("acme", `r${i}`, false, i),
116
- );
117
- const svc = service(
118
- ["acme"],
119
- replay((u) =>
120
- u.searchParams.get("page") === "1"
121
- ? Response.json(
122
- { repositories: page1 },
123
- { headers: { link: '<https://x/?page=2>; rel="next"' } },
124
- )
125
- : Response.json({ repositories: [repo("acme", "last", false, 999)] }),
126
- ),
127
- );
128
- const out = await svc.listRepositories();
129
- expect(out.repos).toHaveLength(101);
130
- expect(out.repos.at(-1)).toEqual({
131
- fullName: "acme/last",
132
- archived: false,
133
- });
134
- });
25
+ describeOrSkip("githubLookup.listRepositories (cache, integration)", () => {
26
+ let prisma: PrismaClient;
27
+ let cache: GitHubRepoCacheService;
28
+ const realFetch = globalThis.fetch;
135
29
 
136
- it("skips an org without the lookup App installed", async () => {
137
- const svc = service(
138
- ["ghost", "acme"],
139
- replay(() => Response.json({ repositories: [repo("acme", "api")] })),
140
- );
141
- expect((await svc.listRepositories()).repos).toEqual([
142
- { fullName: "acme/api", archived: false },
143
- ]);
144
- });
145
-
146
- it("returns configured:false with no repos when the Apps are not set", async () => {
147
- const svc = createGithubLookupService({
30
+ const svc = () =>
31
+ createGithubLookupService({
148
32
  appService: {
149
- get: async () => null,
150
- getPrivateKey: async () => null,
33
+ get: async (role: string) =>
34
+ role === "lookup" ? { appId: "555", enterpriseSlug: null } : null,
35
+ getPrivateKey: async (role: string) =>
36
+ role === "lookup" ? "pem" : null,
151
37
  } as unknown as GitHubEnterpriseAppService,
152
- });
153
- expect(await svc.listRepositories()).toEqual({
154
- configured: false,
155
- repos: [],
156
- });
157
- });
158
-
159
- it("rejects on a GitHub error instead of returning an empty list", async () => {
160
- const svc = service(
161
- ["acme"],
162
- replay(() => Response.json({ message: "boom" }, { status: 500 })),
163
- );
164
- const err = await svc.listRepositories().then(
165
- () => null,
166
- (e) => e,
167
- );
168
- expect(err).toBeInstanceOf(GithubEnterpriseError);
169
- expect((err as GithubEnterpriseError).kind).toBe("server");
170
- });
171
-
172
- it("rejects when listing installable organizations fails", async () => {
173
- const svc = createGithubLookupService({
174
- appService: {} as never,
175
- clients: {
176
- installer: {
177
- listInstallableOrganizations: async () => {
178
- throw new GithubEnterpriseError("rate_limit", "limited");
179
- },
180
- },
181
- lookup: { listInstallationRepositories: async () => [] },
182
- },
183
- });
184
- await expect(svc.listRepositories()).rejects.toThrow("limited");
185
- });
186
-
187
- describe("without an installer", () => {
188
- const lookupApp = { appId: "555", enterpriseSlug: null };
189
- const stored = (installer: unknown) =>
190
- ({
191
- get: async (kind: string) =>
192
- kind === "lookup" ? lookupApp : installer,
193
- getPrivateKey: async (kind: string) =>
194
- kind === "lookup" || installer ? privateKey : null,
195
- }) as unknown as GitHubEnterpriseAppService;
196
-
197
- it("lists repos from every org the lookup App is installed on", async () => {
198
- const svc = createGithubLookupService({
199
- appService: stored(null),
200
- fetchFn: replay((_u, id) =>
201
- Response.json({
202
- repositories:
203
- id === 1
204
- ? [repo("acme", "api", false, 10)]
205
- : [repo("beta", "web", false, 20)],
206
- }),
207
- ),
208
- now: () => NOW,
209
- });
210
- expect(await svc.listRepositories()).toEqual({
211
- configured: true,
212
- repos: [
213
- { fullName: "acme/api", archived: false },
214
- { fullName: "beta/web", archived: false },
215
- ],
216
- });
217
- });
218
-
219
- it("lists only the selected repos of a selected-scope installation", async () => {
220
- const svc = createGithubLookupService({
221
- appService: stored(null),
222
- fetchFn: replay((_u, id) =>
223
- Response.json({
224
- repositories: id === 1 ? [repo("acme", "only-this")] : [],
225
- }),
226
- ),
227
- now: () => NOW,
228
- });
229
- expect((await svc.listRepositories()).repos).toEqual([
230
- { fullName: "acme/only-this", archived: false },
231
- ]);
232
- });
233
-
234
- it("rejects on a GitHub failure instead of returning an empty list", async () => {
235
- const svc = createGithubLookupService({
236
- appService: stored(null),
237
- fetchFn: (async () =>
238
- Response.json(
239
- { message: "boom" },
240
- { status: 500 },
241
- )) as unknown as typeof fetch,
242
- now: () => NOW,
243
- });
244
- await expect(svc.listRepositories()).rejects.toBeInstanceOf(
245
- GithubEnterpriseError,
246
- );
247
- });
248
-
249
- it("an installer with a slug but no key stays unconfigured", async () => {
250
- const svc = createGithubLookupService({
251
- appService: {
252
- get: async (kind: string) =>
253
- kind === "lookup"
254
- ? lookupApp
255
- : { appId: "1", enterpriseSlug: "ent" },
256
- getPrivateKey: async (kind: string) =>
257
- kind === "lookup" ? privateKey : null,
258
- } as unknown as GitHubEnterpriseAppService,
259
- });
260
- expect(await svc.listRepositories()).toEqual({
261
- configured: false,
262
- repos: [],
263
- });
38
+ cache,
39
+ now: () => NOW,
264
40
  });
265
41
 
266
- it("with an installer configured the org list still comes from it", async () => {
267
- const svc = service(
268
- ["acme"],
269
- replay(() => Response.json({ repositories: [repo("acme", "api")] })),
270
- );
271
- expect((await svc.listRepositories()).repos).toEqual([
272
- { fullName: "acme/api", archived: false },
273
- ]);
274
- });
42
+ beforeEach(async () => {
43
+ prisma = createAdminPrismaClient(TEST_DB as string);
44
+ await prisma.gitHubCachedRepo.deleteMany();
45
+ await prisma.gitHubRepoSnapshot.deleteMany();
46
+ cache = new GitHubRepoCacheService(prisma, { now: () => NOW });
47
+ globalThis.fetch = (() => {
48
+ throw new Error("GitHub must not be called");
49
+ }) as unknown as typeof fetch;
275
50
  });
276
- });
277
-
278
- describe("githubLookup.listRepositories(accountId)", () => {
279
- type Row = { appId: string; enterpriseSlug: string | null };
280
- /** In-memory app service with the real account-then-deployment-wide fallback. */
281
- function scopedApps(rows: Record<string, Row | undefined>) {
282
- const key = (role: string, accountId?: string | null) =>
283
- `${accountId ?? ""}:${role}`;
284
- const resolve = (role: string, accountId?: string | null) =>
285
- (accountId ? rows[key(role, accountId)] : undefined) ??
286
- rows[key(role, null)];
287
- return {
288
- get: async (role: string, accountId?: string | null) =>
289
- resolve(role, accountId) ?? null,
290
- getPrivateKey: async (role: string, accountId?: string | null) =>
291
- resolve(role, accountId) ? privateKey : null,
292
- } as unknown as GitHubEnterpriseAppService;
293
- }
294
51
 
295
- /** The lookup App id (JWT iss) decides which org installation it sees. */
296
- const byApp: typeof fetch = (async (
297
- input: RequestInfo | URL,
298
- init?: RequestInit,
299
- ) => {
300
- const u = new URL(input.toString());
301
- const bearer = String(new Headers(init?.headers).get("authorization"));
302
- const jwt = bearer.replace(/^Bearer /, "");
303
- if (u.pathname === "/app/installations") {
304
- const iss = JSON.parse(
305
- Buffer.from(jwt.split(".")[1], "base64url").toString(),
306
- ).iss;
307
- const org = String(iss) === "777" ? "gamma" : "acme";
308
- return Response.json([
309
- {
310
- id: org === "gamma" ? 3 : 1,
311
- account: { login: org, type: "Organization" },
312
- },
313
- ]);
314
- }
315
- const inst = u.pathname.match(/^\/orgs\/([^/]+)\/installation$/);
316
- if (inst) {
317
- return Response.json({
318
- id: inst[1] === "gamma" ? 3 : 1,
319
- repository_selection: "all",
320
- });
321
- }
322
- if (u.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/)) {
323
- const id = u.pathname.match(/installations\/(\d+)/)?.[1];
324
- return Response.json({
325
- token: `ghs_tok${id}`,
326
- expires_at: "2026-11-09T13:00:00Z",
327
- });
328
- }
329
- if (u.pathname === "/installation/repositories") {
330
- return Response.json({
331
- repositories: bearer.endsWith("tok3")
332
- ? [repo("gamma", "tenant", false, 30)]
333
- : [repo("acme", "shared", false, 10)],
334
- });
335
- }
336
- return Response.json({ message: "Not Found" }, { status: 404 });
337
- }) as unknown as typeof fetch;
338
-
339
- const lookup = (appId: string): Row => ({ appId, enterpriseSlug: null });
340
-
341
- it("lists through the account's own lookup App", async () => {
342
- const svc = createGithubLookupService({
343
- appService: scopedApps({
344
- ":lookup": lookup("555"),
345
- "acct-1:lookup": lookup("777"),
346
- }),
347
- fetchFn: byApp,
348
- now: () => NOW,
349
- });
350
- expect((await svc.listRepositories("acct-1")).repos).toEqual([
351
- { fullName: "gamma/tenant", archived: false },
352
- ]);
52
+ afterEach(async () => {
53
+ globalThis.fetch = realFetch;
54
+ await prisma.$disconnect();
353
55
  });
354
56
 
355
- it("falls back to the deployment-wide pair when the account has none", async () => {
356
- const svc = createGithubLookupService({
357
- appService: scopedApps({ ":lookup": lookup("555") }),
358
- fetchFn: byApp,
359
- now: () => NOW,
57
+ it("cold start returns an empty syncing result", async () => {
58
+ expect(await svc().listRepositories("acct")).toEqual({
59
+ configured: true,
60
+ repos: [],
61
+ syncState: "syncing",
360
62
  });
361
- expect((await svc.listRepositories("acct-2")).repos).toEqual([
362
- { fullName: "acme/shared", archived: false },
363
- ]);
364
63
  });
365
64
 
366
- it("with no argument uses the deployment-wide pair, ignoring account rows", async () => {
367
- const svc = createGithubLookupService({
368
- appService: scopedApps({
369
- ":lookup": lookup("555"),
370
- "acct-1:lookup": lookup("777"),
371
- }),
372
- fetchFn: byApp,
373
- now: () => NOW,
65
+ it("serves a partial crawl with progress, then a completed one as ready", async () => {
66
+ const snap = await cache.upsertSnapshot(key("acme"), {
67
+ crawlPage: 1,
68
+ crawlStartedAt: NOW,
69
+ totalCount: 2,
374
70
  });
375
- expect((await svc.listRepositories()).repos).toEqual([
376
- { fullName: "acme/shared", archived: false },
71
+ await cache.upsertRepos(snap.id, [{ githubId: 1, fullName: "acme/a" }]);
72
+ const partial = await svc().listRepositories("acct");
73
+ expect(partial.syncState).toBe("syncing");
74
+ expect(partial.repos).toEqual([{ fullName: "acme/a", archived: false }]);
75
+ expect(partial.progress).toEqual({ reposSeen: 1, totalCount: 2 });
76
+
77
+ await cache.upsertRepos(snap.id, [
78
+ { githubId: 2, fullName: "acme/b", archived: true },
377
79
  ]);
378
- });
379
-
380
- it("is unconfigured when neither the account nor the deployment has a lookup App", async () => {
381
- const svc = createGithubLookupService({
382
- appService: scopedApps({}),
383
- fetchFn: byApp,
384
- now: () => NOW,
385
- });
386
- expect(await svc.listRepositories("acct-1")).toEqual({
387
- configured: false,
388
- repos: [],
389
- });
80
+ await cache.upsertSnapshot(key("acme"), { completedAt: NOW });
81
+ const done = await svc().listRepositories("acct");
82
+ expect(done.syncState).toBe("ready");
83
+ expect(done.repos).toHaveLength(2);
84
+ expect(done.fetchedAt).toEqual(NOW);
390
85
  });
391
86
  });
@@ -1,26 +1,37 @@
1
1
  /**
2
2
  * admin/src/github-lookup-repositories.ts
3
3
  * The lookup-App repository lister exposed to extensions as
4
- * AdminPlatformServices.githubLookup: every repository the lookup App can see,
5
- * across the organizations the installer App can reach, or, with no
6
- * installer configured, the organizations the lookup App is installed on.
4
+ * AdminPlatformServices.githubLookup. It reads the cached crawl snapshots
5
+ * (GLC-1.2 crawler) and never calls GitHub, so a GitHub outage or rate limit
6
+ * cannot fail it; the crawl state is reported in optional fields instead.
7
7
  *
8
- * A GitHub failure rejects; it is never reported as an empty list. An org
9
- * without the lookup App installed (not_found) is skipped. The stored-App
10
- * wiring (key-bearing) lives in github-enterprise-api.ts.
8
+ * A configured account with no snapshot yet returns an empty list with
9
+ * syncState "syncing" (older consumers treat that as their existing empty-list
10
+ * path). The stored-App wiring lives in github-enterprise-api.ts.
11
11
  */
12
12
 
13
- import { GithubEnterpriseError } from "./github-enterprise-client.ts";
14
- import type { LookupRepository } from "./github-lookup-client.ts";
15
-
16
13
  export interface GithubLookupRepository {
17
14
  fullName: string;
18
15
  archived: boolean;
19
16
  }
20
17
 
18
+ /** syncing: a crawl is incomplete; ready: complete and fresh; stale: complete but past the TTL; failed: the last crawl errored. */
19
+ export type GithubLookupSyncState = "syncing" | "ready" | "stale" | "failed";
20
+
21
+ export interface GithubLookupProgress {
22
+ reposSeen: number;
23
+ /** Sum of GitHub's total_count across orgs; absent until every org reports one. */
24
+ totalCount?: number;
25
+ }
26
+
21
27
  export interface GithubLookupRepositories {
22
28
  configured: boolean;
23
29
  repos: GithubLookupRepository[];
30
+ /** Optional: consumers that predate the cache ignore these. */
31
+ syncState?: GithubLookupSyncState;
32
+ /** Oldest completed crawl across orgs; absent until one has completed. */
33
+ fetchedAt?: Date;
34
+ progress?: GithubLookupProgress;
24
35
  }
25
36
 
26
37
  /** The extension-facing lister (optional member of AdminPlatformServices). */
@@ -31,48 +42,65 @@ export interface GithubLookupService {
31
42
  ): Promise<GithubLookupRepositories>;
32
43
  }
33
44
 
34
- /** The installer-side client surface the lister needs. */
35
- export interface LookupInstallerPort {
36
- listInstallableOrganizations(): Promise<{ login: string }[]>;
45
+ /** One org's cached snapshot with its repos. */
46
+ export interface LookupSnapshotView {
47
+ completedAt: Date | null;
48
+ totalCount: number | null;
49
+ lastError: string | null;
50
+ repos: GithubLookupRepository[];
37
51
  }
38
52
 
39
- /** The lookup-side client surface the lister needs. */
40
- export interface LookupRepositoriesPort {
41
- listInstallationRepositories(org: string): Promise<LookupRepository[]>;
42
- /** Required only when no installer is configured (the App lists its own orgs). */
43
- listInstallations?(): Promise<{ login: string }[]>;
44
- }
53
+ /** Default age after which a completed crawl is reported stale (hourly refresh). */
54
+ export const DEFAULT_LOOKUP_TTL_MS = 3_600_000;
45
55
 
46
- export async function listLookupRepositories(
47
- installer: LookupInstallerPort | undefined,
48
- lookup: LookupRepositoriesPort,
49
- ): Promise<GithubLookupRepository[]> {
56
+ /** Folds per-org snapshots into one result: failed > syncing > stale > ready. */
57
+ export function summarizeLookupSnapshots(
58
+ snapshots: LookupSnapshotView[],
59
+ now: Date,
60
+ ttlMs: number = DEFAULT_LOOKUP_TTL_MS,
61
+ ): GithubLookupRepositories {
62
+ if (snapshots.length === 0) {
63
+ return { configured: true, repos: [], syncState: "syncing" };
64
+ }
50
65
  const repos = new Map<string, GithubLookupRepository>();
51
- const orgs = installer
52
- ? await installer.listInstallableOrganizations()
53
- : await listOwnInstallations(lookup);
54
- for (const { login } of orgs) {
55
- let rows: LookupRepository[];
56
- try {
57
- rows = await lookup.listInstallationRepositories(login);
58
- } catch (e) {
59
- // No lookup App installation on this org: nothing to list.
60
- if (e instanceof GithubEnterpriseError && e.kind === "not_found")
61
- continue;
62
- throw e;
63
- }
64
- for (const r of rows) {
66
+ let reposSeen = 0;
67
+ let totalCount: number | undefined = 0;
68
+ let failed = false;
69
+ let incomplete = false;
70
+ let oldest: Date | undefined;
71
+ for (const s of snapshots) {
72
+ for (const r of s.repos) {
65
73
  repos.set(r.fullName, { fullName: r.fullName, archived: r.archived });
66
74
  }
75
+ reposSeen += s.repos.length;
76
+ totalCount =
77
+ totalCount === undefined || s.totalCount === null
78
+ ? undefined
79
+ : totalCount + s.totalCount;
80
+ if (s.completedAt) {
81
+ if (!oldest || s.completedAt < oldest) oldest = s.completedAt;
82
+ } else {
83
+ incomplete = true;
84
+ if (s.lastError) failed = true;
85
+ }
67
86
  }
68
- return [...repos.values()];
69
- }
70
-
71
- async function listOwnInstallations(
72
- lookup: LookupRepositoriesPort,
73
- ): Promise<{ login: string }[]> {
74
- if (!lookup.listInstallations) {
75
- throw new Error("lookup client cannot list its own installations");
76
- }
77
- return lookup.listInstallations();
87
+ const stale =
88
+ oldest !== undefined && now.getTime() - oldest.getTime() > ttlMs;
89
+ const syncState: GithubLookupSyncState = failed
90
+ ? "failed"
91
+ : incomplete
92
+ ? "syncing"
93
+ : stale
94
+ ? "stale"
95
+ : "ready";
96
+ return {
97
+ configured: true,
98
+ repos: [...repos.values()],
99
+ syncState,
100
+ ...(oldest && !incomplete ? { fetchedAt: oldest } : {}),
101
+ progress: {
102
+ reposSeen,
103
+ ...(totalCount === undefined ? {} : { totalCount }),
104
+ },
105
+ };
78
106
  }