@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.
@@ -0,0 +1,237 @@
1
+ /**
2
+ * admin/src/github-repo-refresh-discovery.unit.test.ts
3
+ * Target discovery for the GLC-1.4 refresher: orgs from the installer App (or
4
+ * the lookup App's own installations), agents from stored Apps, scoping,
5
+ * dedupe and failure isolation, against fake ports.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
10
+ import {
11
+ createRefreshDiscovery,
12
+ type DiscoveryPorts,
13
+ type LookupAppClient,
14
+ notFoundAsEmpty,
15
+ } from "./github-repo-refresh-discovery.ts";
16
+ import type { PageSource } from "./github-repo-crawler.ts";
17
+ import type { InstallationAgentRecord } from "./installation-ports.ts";
18
+
19
+ const clock = { now: () => new Date("2026-11-20T12:00:00Z") };
20
+
21
+ function lookupClient(installed: string[] = []): LookupAppClient {
22
+ return {
23
+ async listInstallations() {
24
+ return installed.map((login, i) => ({ id: i + 1, login }));
25
+ },
26
+ async listInstallationRepositoriesPage() {
27
+ throw new Error("not used");
28
+ },
29
+ async getCollaboratorPermissionWithRateLimit() {
30
+ throw new Error("not used");
31
+ },
32
+ };
33
+ }
34
+
35
+ const agent = (
36
+ over: Partial<InstallationAgentRecord> = {},
37
+ ): InstallationAgentRecord => ({
38
+ id: "a1",
39
+ accountId: null,
40
+ repos: [],
41
+ githubUsername: null,
42
+ ...over,
43
+ });
44
+
45
+ function ports(over: Partial<DiscoveryPorts> = {}): DiscoveryPorts {
46
+ return {
47
+ listAppScopes: async () => [],
48
+ listAgents: async () => [],
49
+ lookupApp: async () => ({
50
+ accountId: null,
51
+ appId: "555",
52
+ client: lookupClient(),
53
+ }),
54
+ installerOrgs: async () => ["acme", "beta"],
55
+ installer: {
56
+ async listOrgInstallations() {
57
+ return [];
58
+ },
59
+ async listInstallationRepositoriesPage() {
60
+ throw new Error("not used");
61
+ },
62
+ },
63
+ store: {} as DiscoveryPorts["store"],
64
+ clock,
65
+ log: () => {},
66
+ ...over,
67
+ };
68
+ }
69
+
70
+ const keys = (
71
+ ts: {
72
+ key: { accountId: string; appKind: string; appRef: string; org: string };
73
+ }[],
74
+ ) =>
75
+ ts.map(
76
+ (t) => `${t.key.accountId}|${t.key.appKind}|${t.key.appRef}|${t.key.org}`,
77
+ );
78
+
79
+ describe("createRefreshDiscovery", () => {
80
+ it("builds a lookup target per installer org and an agent target per agent App and org", async () => {
81
+ const d = createRefreshDiscovery(
82
+ ports({
83
+ listAgents: async () => [
84
+ agent({
85
+ id: "a1",
86
+ appId: 777,
87
+ githubUsername: "Octocat",
88
+ repos: ["acme/api", "beta/x", "ACME/web"],
89
+ }),
90
+ agent({ id: "a2", appId: 777, githubUsername: "octocat" }),
91
+ agent({ id: "a3", githubUsername: "nobody-without-app" }),
92
+ ],
93
+ }),
94
+ );
95
+ const targets = await d.listTargets();
96
+ expect(keys(targets)).toEqual([
97
+ "deployment|lookup|555|acme",
98
+ "deployment|lookup|555|beta",
99
+ "deployment|agent|777|acme",
100
+ "deployment|agent|777|beta",
101
+ ]);
102
+ const acme = targets[0];
103
+ expect(acme?.access?.users).toEqual([
104
+ { username: "Octocat", configuredRepos: ["api", "web"] },
105
+ { username: "octocat", configuredRepos: [] },
106
+ ]);
107
+ expect(targets[2]?.access).toBeUndefined();
108
+ });
109
+
110
+ it("uses the lookup App's own installations when no installer is configured, with no agent targets", async () => {
111
+ const d = createRefreshDiscovery(
112
+ ports({
113
+ installerOrgs: async () => null,
114
+ lookupApp: async () => ({
115
+ accountId: null,
116
+ appId: "555",
117
+ client: lookupClient(["solo"]),
118
+ }),
119
+ listAgents: async () => [agent({ appId: 777 })],
120
+ }),
121
+ );
122
+ expect(keys(await d.listTargets())).toEqual(["deployment|lookup|555|solo"]);
123
+ });
124
+
125
+ it("gives an account with its own Apps its own scope and binds its agents there", async () => {
126
+ const d = createRefreshDiscovery(
127
+ ports({
128
+ listAppScopes: async () => ["acc1"],
129
+ lookupApp: async (scope) =>
130
+ scope === "acc1"
131
+ ? { accountId: "acc1", appId: "900", client: lookupClient() }
132
+ : { accountId: null, appId: "555", client: lookupClient() },
133
+ installerOrgs: async (scope) =>
134
+ scope === "acc1" ? ["corp"] : ["acme"],
135
+ listAgents: async () => [
136
+ agent({
137
+ id: "a1",
138
+ accountId: "acc1",
139
+ githubUsername: "alice",
140
+ appId: 1,
141
+ }),
142
+ agent({
143
+ id: "a2",
144
+ accountId: "acc2",
145
+ githubUsername: "bob",
146
+ appId: 2,
147
+ }),
148
+ ],
149
+ }),
150
+ );
151
+ const targets = await d.listTargets();
152
+ expect(keys(targets)).toEqual([
153
+ "deployment|lookup|555|acme",
154
+ "acc1|lookup|900|corp",
155
+ "acc1|agent|1|corp",
156
+ // acc2 has no Apps of its own: the deployment pair, its own cache key.
157
+ "acc2|agent|2|acme",
158
+ ]);
159
+ const byKey = Object.fromEntries(
160
+ targets
161
+ .filter((t) => t.key.appKind === "lookup")
162
+ .map((t) => [`${t.key.accountId}|${t.key.org}`, t]),
163
+ );
164
+ expect(byKey["deployment|acme"]?.access?.users).toEqual([
165
+ { username: "bob", configuredRepos: [] },
166
+ ]);
167
+ expect(byKey["acc1|corp"]?.access?.users).toEqual([
168
+ { username: "alice", configuredRepos: [] },
169
+ ]);
170
+ });
171
+
172
+ it("does not duplicate a scope that resolves to the deployment-wide Apps", async () => {
173
+ const d = createRefreshDiscovery(
174
+ ports({ listAppScopes: async () => ["acc-installer-only"] }),
175
+ );
176
+ expect(keys(await d.listTargets())).toEqual([
177
+ "deployment|lookup|555|acme",
178
+ "deployment|lookup|555|beta",
179
+ ]);
180
+ });
181
+
182
+ it("skips a scope whose discovery fails without blocking the others", async () => {
183
+ const lines: string[] = [];
184
+ const d = createRefreshDiscovery(
185
+ ports({
186
+ listAppScopes: async () => ["broken"],
187
+ lookupApp: async (scope) => {
188
+ if (scope === "broken") throw new Error("key decrypt failed");
189
+ return { accountId: null, appId: "555", client: lookupClient() };
190
+ },
191
+ log: (l) => lines.push(l),
192
+ }),
193
+ );
194
+ expect(keys(await d.listTargets())).toEqual([
195
+ "deployment|lookup|555|acme",
196
+ "deployment|lookup|555|beta",
197
+ ]);
198
+ expect(lines.join("\n")).toContain("key decrypt failed");
199
+ });
200
+
201
+ it("returns nothing when no lookup or installer App is configured", async () => {
202
+ const d = createRefreshDiscovery(
203
+ ports({
204
+ lookupApp: async () => null,
205
+ installerOrgs: async () => null,
206
+ listAgents: async () => [agent({ appId: 1 })],
207
+ }),
208
+ );
209
+ expect(await d.listTargets()).toEqual([]);
210
+ });
211
+ });
212
+
213
+ describe("notFoundAsEmpty", () => {
214
+ it("turns a not_found (App not installed on the org) into an empty last page", async () => {
215
+ const src: PageSource = {
216
+ async fetchPage() {
217
+ throw new GithubEnterpriseError("not_found", "no installation");
218
+ },
219
+ };
220
+ expect(await notFoundAsEmpty(src).fetchPage(1)).toEqual({
221
+ repos: [],
222
+ totalCount: 0,
223
+ hasNext: false,
224
+ });
225
+ });
226
+
227
+ it("passes other errors through", async () => {
228
+ const src: PageSource = {
229
+ async fetchPage() {
230
+ throw new GithubEnterpriseError("rate_limit", "slow down");
231
+ },
232
+ };
233
+ await expect(notFoundAsEmpty(src).fetchPage(1)).rejects.toThrow(
234
+ "slow down",
235
+ );
236
+ });
237
+ });
@@ -0,0 +1,179 @@
1
+ /**
2
+ * admin/src/github-repo-refresher.integration.test.ts
3
+ * GithubRepoRefresher against a real PostgreSQL DB through
4
+ * GitHubRepoCacheService: two workers ticking concurrently over the same orgs
5
+ * (the snapshot lease means each org is worked by exactly one of them), plus
6
+ * the crawl engine and access backfill end to end with fake GitHub ports.
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 type { PrismaClient } from "../prisma/client/client.ts";
12
+ import type { AccessProbe } from "./github-access-backfill.ts";
13
+ import {
14
+ GitHubRepoCacheService,
15
+ type SnapshotKey,
16
+ } from "./github-repo-cache.ts";
17
+ import { crawlRepos, type PageSource } from "./github-repo-crawler.ts";
18
+ import {
19
+ GithubRepoRefresher,
20
+ type RefreshTarget,
21
+ } from "./github-repo-refresher.ts";
22
+ import { createAdminPrismaClient } from "./prisma-client.ts";
23
+
24
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
25
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
26
+
27
+ const T0 = new Date("2026-11-20T12:00:00Z");
28
+ const HOUR = 3_600_000;
29
+ const ORGS = ["acme", "beta", "gamma"];
30
+
31
+ describeOrSkip("GithubRepoRefresher (integration)", () => {
32
+ let prisma: PrismaClient;
33
+ let now: Date;
34
+ let svc: GitHubRepoCacheService;
35
+ /** "<org>:<page>" per page fetch, across both workers. */
36
+ let fetches: string[];
37
+ let probes: string[];
38
+
39
+ const clock = { now: () => new Date(now) };
40
+
41
+ /** Three repos per org, two per page, with a small delay per fetch. */
42
+ const source = (org: string): PageSource => ({
43
+ async fetchPage(page) {
44
+ fetches.push(`${org}:${page}`);
45
+ await Bun.sleep(20);
46
+ const ids = [1, 2, 3].slice((page - 1) * 2, page * 2);
47
+ return {
48
+ repos: ids.map((i) => ({
49
+ githubId: org.length * 100 + i,
50
+ fullName: `${org}/r${i}`,
51
+ })),
52
+ totalCount: 3,
53
+ hasNext: page < 2,
54
+ };
55
+ },
56
+ });
57
+
58
+ const probe: AccessProbe = {
59
+ async getCollaboratorPermissionWithRateLimit(org, repo, user) {
60
+ probes.push(`${org}/${repo}@${user}`);
61
+ await Bun.sleep(5);
62
+ return {
63
+ role: "write",
64
+ rateLimit: { remaining: 4000, resetAt: null, retryAfterSeconds: null },
65
+ };
66
+ },
67
+ };
68
+
69
+ const targets = (): RefreshTarget[] =>
70
+ ORGS.map((org) => {
71
+ const key: SnapshotKey = {
72
+ accountId: "acc",
73
+ appKind: "lookup",
74
+ appRef: "555",
75
+ org,
76
+ };
77
+ const src = source(org);
78
+ return {
79
+ key,
80
+ crawl: (ctx) =>
81
+ crawlRepos({
82
+ key,
83
+ source: src,
84
+ store: svc,
85
+ clock,
86
+ shouldStop: ctx.shouldStop,
87
+ }),
88
+ access: { probe, users: [{ username: "octocat" }] },
89
+ };
90
+ });
91
+
92
+ const worker = (holder: string) =>
93
+ new GithubRepoRefresher({
94
+ discovery: { listTargets: async () => targets() },
95
+ store: svc,
96
+ clock,
97
+ holder,
98
+ config: {
99
+ intervalMs: 60_000,
100
+ ttlMs: HOUR,
101
+ stalenessCapMs: 6 * HOUR,
102
+ timeBudgetMs: 45_000,
103
+ },
104
+ log: () => {},
105
+ });
106
+
107
+ beforeEach(async () => {
108
+ prisma = createAdminPrismaClient(TEST_DB as string);
109
+ await prisma.gitHubRepoAccess.deleteMany();
110
+ await prisma.gitHubCachedRepo.deleteMany();
111
+ await prisma.gitHubRepoSnapshot.deleteMany();
112
+ now = T0;
113
+ svc = new GitHubRepoCacheService(prisma, clock);
114
+ fetches = [];
115
+ probes = [];
116
+ });
117
+
118
+ afterEach(async () => {
119
+ await prisma.$disconnect();
120
+ });
121
+
122
+ it("two workers ticking concurrently work each org exactly once", async () => {
123
+ const [a, b] = await Promise.all([
124
+ worker("worker-a").tick(),
125
+ worker("worker-b").tick(),
126
+ ]);
127
+
128
+ // Every page fetched once, every pair probed once, across both workers.
129
+ expect([...fetches].sort()).toEqual(
130
+ ORGS.flatMap((o) => [`${o}:1`, `${o}:2`]).sort(),
131
+ );
132
+ expect(probes.length).toBe(ORGS.length * 3);
133
+ expect(new Set(probes).size).toBe(probes.length);
134
+
135
+ // Per org: one worker worked it, the other skipped (lease) or found it done.
136
+ for (const org of ORGS) {
137
+ const states = [a, b].map(
138
+ (r) => r.targets.find((t) => t.key.org === org)?.state,
139
+ );
140
+ expect(states.filter((s) => s === "worked")).toHaveLength(1);
141
+ }
142
+
143
+ const snaps = await prisma.gitHubRepoSnapshot.findMany();
144
+ expect(snaps).toHaveLength(ORGS.length);
145
+ for (const s of snaps) {
146
+ expect(s.completedAt).not.toBeNull();
147
+ expect(s.leaseHolder).toBeNull();
148
+ expect(s.leasedUntil).toBeNull();
149
+ expect(s.lastTickAt).not.toBeNull();
150
+ }
151
+ expect(await prisma.gitHubCachedRepo.count()).toBe(ORGS.length * 3);
152
+ expect(
153
+ await prisma.gitHubRepoAccess.count({ where: { status: "ok" } }),
154
+ ).toBe(ORGS.length * 3);
155
+ });
156
+
157
+ it("an overlapping tick on the same worker is a no-op", async () => {
158
+ const w = worker("worker-a");
159
+ const [first, second] = await Promise.all([w.tick(), w.tick()]);
160
+ expect(first.skipped).toBeUndefined();
161
+ expect(second.skipped).toBe("overlap");
162
+ expect(fetches.length).toBe(ORGS.length * 2);
163
+ });
164
+
165
+ it("a later tick within the TTL is idle; after the TTL it refreshes", async () => {
166
+ await worker("worker-a").tick();
167
+ fetches = [];
168
+ probes = [];
169
+ now = new Date(T0.getTime() + 60_000);
170
+ const idle = await worker("worker-b").tick();
171
+ expect(fetches).toEqual([]);
172
+ expect(idle.targets.every((t) => t.state === "idle")).toBe(true);
173
+
174
+ now = new Date(T0.getTime() + 2 * HOUR);
175
+ await worker("worker-b").tick();
176
+ expect(fetches.length).toBe(ORGS.length * 2);
177
+ expect(probes.length).toBe(ORGS.length * 3);
178
+ });
179
+ });