@app-vitals/agent-admin 1.78.0 → 1.80.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.
@@ -0,0 +1,351 @@
1
+ /**
2
+ * admin/src/github-access-backfill.unit.test.ts
3
+ * Ordering, definitive-vs-error, backoff cap, terminal state and rate-limit
4
+ * stop of backfillAccess (GLC-1.3), against in-memory ports.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
9
+ import {
10
+ type AccessBackfillStore,
11
+ type AccessProbe,
12
+ type AccessRow,
13
+ backfillAccess,
14
+ buildWorkList,
15
+ defaultAccessBackoffMs,
16
+ } from "./github-access-backfill.ts";
17
+ import {
18
+ GithubLookupRateLimitError,
19
+ type LookupRateLimit,
20
+ type RepoRole,
21
+ } from "./github-lookup-client.ts";
22
+ import type { AccessInput } from "./github-repo-cache.ts";
23
+
24
+ const T0 = new Date("2026-11-20T12:00:00Z");
25
+ const DAY = 86_400_000;
26
+ const noLimit: LookupRateLimit = {
27
+ remaining: 4000,
28
+ resetAt: null,
29
+ retryAfterSeconds: null,
30
+ };
31
+ const snapshotKey = {
32
+ accountId: "acc",
33
+ appKind: "lookup" as const,
34
+ appRef: "555",
35
+ org: "acme",
36
+ };
37
+
38
+ function makeStore(initial: AccessRow[] = [], user = "octocat") {
39
+ const rows = new Map<
40
+ string,
41
+ AccessRow & { canPush?: boolean; level?: string | null }
42
+ >();
43
+ for (const r of initial) rows.set(`${user}/${r.repo}`, r);
44
+ let snap: { rateLimitResetAt: Date | null } | null = null;
45
+ const writes: AccessInput[] = [];
46
+ const store: AccessBackfillStore = {
47
+ async getAccessRows(q) {
48
+ return q.repos.flatMap((r) => {
49
+ const row = rows.get(`${q.username}/${r}`);
50
+ return row ? [row] : [];
51
+ });
52
+ },
53
+ async upsertAccess(i) {
54
+ writes.push(i);
55
+ rows.set(`${i.username}/${i.repo}`, {
56
+ repo: i.repo,
57
+ status: i.status,
58
+ checkedAt: T0,
59
+ attempts: i.attempts ?? 0,
60
+ nextAttemptAt: i.nextAttemptAt ?? null,
61
+ canPush: i.canPush,
62
+ level: i.level,
63
+ });
64
+ },
65
+ async getSnapshot() {
66
+ return snap;
67
+ },
68
+ async upsertSnapshot(_k, p) {
69
+ snap = { rateLimitResetAt: p?.rateLimitResetAt ?? null };
70
+ return snap;
71
+ },
72
+ };
73
+ return { store, rows, writes, snap: () => snap };
74
+ }
75
+
76
+ function probeOf(
77
+ fn: (repo: string, user: string) => RepoRole | Error,
78
+ calls: string[] = [],
79
+ ): AccessProbe {
80
+ return {
81
+ async getCollaboratorPermissionWithRateLimit(_o, repo, user) {
82
+ calls.push(`${user}/${repo}`);
83
+ const out = fn(repo, user);
84
+ if (out instanceof Error) throw out;
85
+ return { role: out, rateLimit: noLimit };
86
+ },
87
+ };
88
+ }
89
+
90
+ const run = (
91
+ h: ReturnType<typeof makeStore>,
92
+ probe: AccessProbe,
93
+ extra: Partial<Parameters<typeof backfillAccess>[0]> = {},
94
+ now = T0,
95
+ ) =>
96
+ backfillAccess({
97
+ accountId: "acc",
98
+ org: "acme",
99
+ snapshotKey,
100
+ repos: ["a", "b", "c"],
101
+ users: [{ username: "octocat" }],
102
+ probe,
103
+ store: h.store,
104
+ clock: { now: () => now },
105
+ maxAgeMs: DAY,
106
+ ...extra,
107
+ });
108
+
109
+ const row = (repo: string, over: Partial<AccessRow> = {}): AccessRow => ({
110
+ repo,
111
+ status: "ok",
112
+ checkedAt: T0,
113
+ attempts: 0,
114
+ nextAttemptAt: null,
115
+ ...over,
116
+ });
117
+
118
+ describe("buildWorkList ordering", () => {
119
+ it("puts missing before expired, and configured repos first within each", () => {
120
+ const { work, unanswered } = buildWorkList({
121
+ username: "u",
122
+ repos: ["a", "b", "c", "d", "e"],
123
+ configuredRepos: ["e", "b"],
124
+ rows: [
125
+ row("a", { checkedAt: new Date(T0.getTime() - 2 * DAY) }), // expired
126
+ row("b", { checkedAt: new Date(T0.getTime() - 2 * DAY) }), // expired, configured
127
+ row("c"), // fresh
128
+ ],
129
+ now: T0,
130
+ maxAgeMs: DAY,
131
+ });
132
+ expect(work.map((w) => `${w.kind}:${w.repo}`)).toEqual([
133
+ "missing:e",
134
+ "missing:d",
135
+ "expired:b",
136
+ "expired:a",
137
+ ]);
138
+ expect(unanswered).toBe(2);
139
+ });
140
+
141
+ it("skips terminal rows and rows still backing off, but counts backing-off as unanswered", () => {
142
+ const { work, unanswered } = buildWorkList({
143
+ username: "u",
144
+ repos: ["a", "b", "c"],
145
+ configuredRepos: [],
146
+ rows: [
147
+ row("a", { status: "terminal", attempts: 5 }),
148
+ row("b", {
149
+ status: "error",
150
+ attempts: 1,
151
+ nextAttemptAt: new Date(T0.getTime() + 1000),
152
+ }),
153
+ row("c", {
154
+ status: "error",
155
+ attempts: 1,
156
+ nextAttemptAt: new Date(T0.getTime() - 1000),
157
+ }),
158
+ ],
159
+ now: T0,
160
+ maxAgeMs: DAY,
161
+ });
162
+ expect(work.map((w) => w.repo)).toEqual(["c"]);
163
+ expect(unanswered).toBe(2);
164
+ });
165
+ });
166
+
167
+ describe("backfillAccess", () => {
168
+ it("stores a real no-access as ok/none and a 404 the same way", async () => {
169
+ const h = makeStore();
170
+ const out = await run(
171
+ h,
172
+ probeOf((repo) =>
173
+ repo === "a"
174
+ ? "none"
175
+ : repo === "b"
176
+ ? new GithubEnterpriseError("not_found", "nf", { status: 404 })
177
+ : "write",
178
+ ),
179
+ );
180
+ expect(out).toMatchObject({
181
+ outcome: "complete",
182
+ recorded: 3,
183
+ failed: 0,
184
+ missing: 0,
185
+ });
186
+ const by = Object.fromEntries(h.writes.map((w) => [w.repo, w]));
187
+ expect(by.a).toMatchObject({ status: "ok", canPush: false, level: "none" });
188
+ expect(by.b).toMatchObject({ status: "ok", canPush: false, level: "none" });
189
+ expect(by.c).toMatchObject({ status: "ok", canPush: true, level: "write" });
190
+ });
191
+
192
+ it("never writes an access answer for an error; pair stays missing with backoff", async () => {
193
+ const h = makeStore();
194
+ const err = new GithubEnterpriseError("server", "boom", { status: 503 });
195
+ const out = await run(
196
+ h,
197
+ probeOf((r) => (r === "a" ? err : "read")),
198
+ );
199
+ expect(out).toMatchObject({
200
+ outcome: "in_progress",
201
+ recorded: 2,
202
+ failed: 1,
203
+ missing: 1,
204
+ });
205
+ const w = h.writes.find((x) => x.repo === "a");
206
+ expect(w).toMatchObject({
207
+ status: "error",
208
+ canPush: false,
209
+ level: null,
210
+ attempts: 1,
211
+ });
212
+ expect(w?.nextAttemptAt).toEqual(new Date(T0.getTime() + 60_000));
213
+ });
214
+
215
+ it("caps backoff and turns the pair terminal at maxAttempts, which stops blocking completion", async () => {
216
+ expect(defaultAccessBackoffMs(1)).toBe(60_000);
217
+ expect(defaultAccessBackoffMs(2)).toBe(120_000);
218
+ expect(defaultAccessBackoffMs(40)).toBe(3_600_000);
219
+
220
+ const h = makeStore();
221
+ const err = new GithubEnterpriseError("server", "boom", { status: 500 });
222
+ let now = T0;
223
+ const probe = probeOf((r) => (r === "a" ? err : "read"));
224
+ const results = [];
225
+ for (let i = 0; i < 3; i++) {
226
+ results.push(
227
+ await run(h, probe, { maxAttempts: 3, repos: ["a", "b"] }, now),
228
+ );
229
+ now = new Date(now.getTime() + 3_600_001);
230
+ }
231
+ expect(results.map((r) => r.outcome)).toEqual([
232
+ "in_progress",
233
+ "in_progress",
234
+ "complete",
235
+ ]);
236
+ expect(results[2]).toMatchObject({ terminal: 1, missing: 0 });
237
+ expect(h.rows.get("octocat/a")?.status).toBe("terminal");
238
+
239
+ const calls: string[] = [];
240
+ const again = await run(
241
+ h,
242
+ probeOf(() => "read", calls),
243
+ { maxAttempts: 3, repos: ["a", "b"] },
244
+ now,
245
+ );
246
+ expect(calls).toEqual([]);
247
+ expect(again).toMatchObject({ outcome: "complete", probed: 0, missing: 0 });
248
+ });
249
+
250
+ it("does not call for pairs still backing off", async () => {
251
+ const h = makeStore();
252
+ const calls: string[] = [];
253
+ const err = new GithubEnterpriseError("network", "down");
254
+ await run(
255
+ h,
256
+ probeOf(() => err, calls),
257
+ { repos: ["a"] },
258
+ );
259
+ await run(
260
+ h,
261
+ probeOf(() => "read", calls),
262
+ { repos: ["a"] },
263
+ new Date(T0.getTime() + 1000),
264
+ );
265
+ expect(calls).toEqual(["octocat/a"]);
266
+ });
267
+
268
+ it("probes missing before expired, configured first, and shares rows across agents with one user", async () => {
269
+ const h = makeStore([
270
+ row("a", { checkedAt: new Date(T0.getTime() - 2 * DAY) }),
271
+ ]);
272
+ const calls: string[] = [];
273
+ await run(
274
+ h,
275
+ probeOf(() => "read", calls),
276
+ {
277
+ repos: ["a", "b", "c"],
278
+ users: [
279
+ { username: "OctoCat", configuredRepos: ["c"] },
280
+ { username: "octocat", configuredRepos: [] },
281
+ ],
282
+ },
283
+ );
284
+ expect(calls).toEqual(["octocat/c", "octocat/b", "octocat/a"]);
285
+ });
286
+
287
+ it("stops cleanly on a rate limit, writes no row for it, and resumes without redoing finished pairs", async () => {
288
+ const h = makeStore();
289
+ const reset = new Date(T0.getTime() + 600_000);
290
+ const limited = new GithubLookupRateLimitError(
291
+ new GithubEnterpriseError("rate_limit", "slow down", { status: 429 }),
292
+ reset,
293
+ );
294
+ const first = await run(
295
+ h,
296
+ probeOf((r) => (r === "b" ? limited : "read")),
297
+ );
298
+ expect(first).toMatchObject({
299
+ outcome: "rate_limited",
300
+ recorded: 1,
301
+ failed: 0,
302
+ rateLimitResetAt: reset,
303
+ });
304
+ expect(h.rows.has("octocat/b")).toBe(false);
305
+ expect(h.snap()?.rateLimitResetAt).toEqual(reset);
306
+
307
+ const calls: string[] = [];
308
+ const early = await run(
309
+ h,
310
+ probeOf(() => "read", calls),
311
+ {},
312
+ new Date(T0.getTime() + 1000),
313
+ );
314
+ expect(early).toMatchObject({
315
+ outcome: "rate_limited",
316
+ probed: 0,
317
+ missing: 2,
318
+ });
319
+ expect(calls).toEqual([]);
320
+
321
+ const later = await run(
322
+ h,
323
+ probeOf(() => "read", calls),
324
+ {},
325
+ new Date(reset.getTime() + 1),
326
+ );
327
+ expect(calls).toEqual(["octocat/b", "octocat/c"]);
328
+ expect(later).toMatchObject({ outcome: "complete", recorded: 2 });
329
+ });
330
+
331
+ it("stops after an answer when X-RateLimit-Remaining is low", async () => {
332
+ const h = makeStore();
333
+ const resetAt = new Date(T0.getTime() + 300_000);
334
+ const probe: AccessProbe = {
335
+ async getCollaboratorPermissionWithRateLimit() {
336
+ return {
337
+ role: "read",
338
+ rateLimit: { remaining: 3, resetAt, retryAfterSeconds: null },
339
+ };
340
+ },
341
+ };
342
+ const out = await run(h, probe);
343
+ expect(out).toMatchObject({
344
+ outcome: "rate_limited",
345
+ probed: 1,
346
+ recorded: 1,
347
+ missing: 2,
348
+ rateLimitResetAt: resetAt,
349
+ });
350
+ });
351
+ });
@@ -53,10 +53,9 @@ import { resolveValidation } from "./github-enterprise-warnings.ts";
53
53
  import { GithubLookupClient } from "./github-lookup-client.ts";
54
54
  import {
55
55
  type GithubLookupService,
56
- type LookupInstallerPort,
57
- type LookupRepositoriesPort,
58
- listLookupRepositories,
56
+ summarizeLookupSnapshots,
59
57
  } from "./github-lookup-repositories.ts";
58
+ import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
60
59
  import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
61
60
  import { ErrorSchema } from "./openapi-schemas.ts";
62
61
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
@@ -509,67 +508,41 @@ export function createGithubAccessPreview(
509
508
  };
510
509
  }
511
510
 
512
- /** Backs AdminPlatformServices.githubLookup (SCR-1.7). */
511
+ /** Backs AdminPlatformServices.githubLookup: reads the repo cache, never GitHub. */
513
512
  export function createGithubLookupService(
514
- deps: Pick<
515
- GithubEnterpriseApiDeps,
516
- "appService" | "fetchFn" | "apiBase" | "now"
517
- > & {
518
- /** Test seam: replaces the clients built from the stored Apps. */
519
- clients?: {
520
- installer?: LookupInstallerPort;
521
- lookup: LookupRepositoriesPort;
522
- };
513
+ deps: Pick<GithubEnterpriseApiDeps, "appService" | "now"> & {
514
+ cache: Pick<GitHubRepoCacheService, "listLookupSnapshots">;
515
+ /** Age past which a completed crawl reads as stale. */
516
+ ttlMs?: number;
523
517
  },
524
518
  ): GithubLookupService {
525
519
  return {
526
520
  async listRepositories(accountId) {
527
- let clients = deps.clients;
528
- if (!clients) {
529
- const [installer, lookup] = await Promise.all([
530
- deps.appService.get("installer", accountId),
531
- deps.appService.get("lookup", accountId),
532
- ]);
533
- if (!lookup) return { configured: false, repos: [] };
534
- const lookupKey = await deps.appService.getPrivateKey(
535
- "lookup",
536
- accountId,
537
- );
538
- if (!lookupKey) return { configured: false, repos: [] };
539
- const common = {
540
- apiBase: deps.apiBase,
541
- fetchFn: deps.fetchFn,
542
- now: deps.now,
543
- };
544
- // An installer with an enterprise slug supplies the org list; without
545
- // one the lookup App lists the orgs it is installed on.
546
- const installerKey = installer?.enterpriseSlug
547
- ? await deps.appService.getPrivateKey("installer", accountId)
548
- : null;
549
- if (installer?.enterpriseSlug && !installerKey) {
550
- return { configured: false, repos: [] };
551
- }
552
- clients = {
553
- installer:
554
- installer?.enterpriseSlug && installerKey
555
- ? new GithubEnterpriseClient({
556
- appId: installer.appId,
557
- enterprise: installer.enterpriseSlug,
558
- privateKey: installerKey,
559
- ...common,
560
- })
561
- : undefined,
562
- lookup: new GithubLookupClient({
563
- appId: lookup.appId,
564
- privateKey: lookupKey,
565
- ...common,
566
- }),
567
- };
521
+ const [installer, lookup] = await Promise.all([
522
+ deps.appService.get("installer", accountId),
523
+ deps.appService.get("lookup", accountId),
524
+ ]);
525
+ if (!lookup) return { configured: false, repos: [] };
526
+ const [lookupKey, installerKey] = await Promise.all([
527
+ deps.appService.getPrivateKey("lookup", accountId),
528
+ installer?.enterpriseSlug
529
+ ? deps.appService.getPrivateKey("installer", accountId)
530
+ : null,
531
+ ]);
532
+ if (!lookupKey || (installer?.enterpriseSlug && !installerKey)) {
533
+ return { configured: false, repos: [] };
568
534
  }
569
- return {
570
- configured: true,
571
- repos: await listLookupRepositories(clients.installer, clients.lookup),
572
- };
535
+ // The crawler files a deployment-wide App's snapshots under accountId "".
536
+ const accountIds = accountId ? [accountId, ""] : [""];
537
+ const snapshots = await deps.cache.listLookupSnapshots(
538
+ accountIds,
539
+ lookup.appId,
540
+ );
541
+ return summarizeLookupSnapshots(
542
+ snapshots,
543
+ (deps.now ?? (() => new Date()))(),
544
+ deps.ttlMs,
545
+ );
573
546
  },
574
547
  };
575
548
  }
@@ -345,6 +345,17 @@ export class GithubLookupClient {
345
345
  repo: string,
346
346
  username: string,
347
347
  ): Promise<RepoRole> {
348
+ return (
349
+ await this.getCollaboratorPermissionWithRateLimit(owner, repo, username)
350
+ ).role;
351
+ }
352
+
353
+ /** getCollaboratorPermission plus the quota GitHub reported with the answer. */
354
+ async getCollaboratorPermissionWithRateLimit(
355
+ owner: string,
356
+ repo: string,
357
+ username: string,
358
+ ): Promise<{ role: RepoRole; rateLimit: LookupRateLimit }> {
348
359
  const { token } = await this.getOrgToken(owner);
349
360
  const res = await this.request<{
350
361
  permission?: unknown;
@@ -355,7 +366,10 @@ export class GithubLookupClient {
355
366
  token,
356
367
  "GitHub collaborator permission",
357
368
  );
358
- return mapRepoRole(res.data?.role_name ?? res.data?.permission);
369
+ return {
370
+ role: mapRepoRole(res.data?.role_name ?? res.data?.permission),
371
+ rateLimit: readRateLimit(res.headers),
372
+ };
359
373
  }
360
374
 
361
375
  /** Look up a user. A nonexistent login throws kind "not_found". */