@app-vitals/agent-admin 1.82.0 → 1.84.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/openapi.platform.json +115 -1
- package/package.json +2 -2
- package/src/admin-boot.ts +14 -3
- package/src/admin-ui-github-refresh.smoke.test.ts +96 -0
- package/src/admin-ui-installation-repos-pages.ts +51 -3
- package/src/admin-ui-installation-repos-pages.unit.test.ts +49 -1
- package/src/admin-ui-pages.ts +1 -0
- package/src/admin-ui.ts +40 -5
- package/src/agents-api.smoke.test.ts +39 -2
- package/src/agents-api.ts +28 -1
- package/src/github-enterprise-api.smoke.test.ts +73 -0
- package/src/github-enterprise-api.ts +51 -0
- package/src/github-installation-wiring.ts +61 -1
- package/src/github-installation-wiring.unit.test.ts +55 -3
- package/src/github-installation.fixtures.ts +44 -3
- package/src/github-refresh-action.ts +45 -0
- package/src/github-refresh-action.unit.test.ts +121 -0
- package/src/github-repo-cache.ts +52 -0
- package/src/github-repo-refresher.ts +5 -0
- package/src/github-sync-cache.integration.test.ts +134 -0
- package/src/github-sync-cached-access.ts +125 -0
- package/src/github-sync-reverify.unit.test.ts +138 -0
- package/src/github-sync.ts +174 -8
- package/src/installation-repos-service.ts +70 -1
- package/src/installation-repos-service.unit.test.ts +34 -0
- package/src/repo-access-rules.ts +13 -1
|
@@ -15,6 +15,7 @@ import type {
|
|
|
15
15
|
GitHubEnterpriseAppRole,
|
|
16
16
|
SaveGitHubEnterpriseAppInput,
|
|
17
17
|
} from "./github-enterprise-apps.ts";
|
|
18
|
+
import type { GithubRefreshAction } from "./github-refresh-action.ts";
|
|
18
19
|
|
|
19
20
|
interface CassetteEntry {
|
|
20
21
|
status: number;
|
|
@@ -117,6 +118,7 @@ function build(
|
|
|
117
118
|
opts: {
|
|
118
119
|
routes?: Record<string, string>;
|
|
119
120
|
agents?: Record<string, Record<string, string> | null>;
|
|
121
|
+
refreshAction?: GithubRefreshAction;
|
|
120
122
|
} = {},
|
|
121
123
|
) {
|
|
122
124
|
const appService = fakeAppService();
|
|
@@ -151,6 +153,7 @@ function build(
|
|
|
151
153
|
"root:tok-admin:*,ro:tok-read:platform.read,bot:tok-agent:agent-1",
|
|
152
154
|
),
|
|
153
155
|
agentTokenService: { validate: async () => null },
|
|
156
|
+
...(opts.refreshAction ? { refreshAction: opts.refreshAction } : {}),
|
|
154
157
|
fetchFn,
|
|
155
158
|
apiBase: "https://ghe.test",
|
|
156
159
|
});
|
|
@@ -175,6 +178,7 @@ describe("auth", () => {
|
|
|
175
178
|
["DELETE", "/github-enterprise/apps/installer", ""],
|
|
176
179
|
["POST", "/github-enterprise/apps/installer/validate", ""],
|
|
177
180
|
["GET", "/github-enterprise/orgs", ""],
|
|
181
|
+
["POST", "/github-enterprise/refresh", ""],
|
|
178
182
|
[
|
|
179
183
|
"POST",
|
|
180
184
|
"/github-enterprise/orgs/org-1/install",
|
|
@@ -916,3 +920,72 @@ describe("account-scoped routes", () => {
|
|
|
916
920
|
expect(res.status).toBe(403);
|
|
917
921
|
});
|
|
918
922
|
});
|
|
923
|
+
|
|
924
|
+
describe("refresh action (GLC-2.4)", () => {
|
|
925
|
+
const stub = () => {
|
|
926
|
+
const calls: string[] = [];
|
|
927
|
+
const action: GithubRefreshAction = {
|
|
928
|
+
requestRefresh: async () => {
|
|
929
|
+
calls.push("refresh");
|
|
930
|
+
return { snapshots: 2, accessPairs: 1 };
|
|
931
|
+
},
|
|
932
|
+
};
|
|
933
|
+
return { calls, action };
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
it("returns 202 for an admin and makes no GitHub call", async () => {
|
|
937
|
+
const { calls: marks, action } = stub();
|
|
938
|
+
const h = build({ refreshAction: action });
|
|
939
|
+
const res = await h.app.request("/github-enterprise/refresh", {
|
|
940
|
+
method: "POST",
|
|
941
|
+
headers: ADMIN,
|
|
942
|
+
});
|
|
943
|
+
expect(res.status).toBe(202);
|
|
944
|
+
expect(await res.json()).toEqual({
|
|
945
|
+
status: "accepted",
|
|
946
|
+
snapshots: 2,
|
|
947
|
+
accessPairs: 1,
|
|
948
|
+
});
|
|
949
|
+
expect(marks).toEqual(["refresh"]);
|
|
950
|
+
expect(h.calls).toEqual([]);
|
|
951
|
+
});
|
|
952
|
+
|
|
953
|
+
it("is 503 when refresh is not wired", async () => {
|
|
954
|
+
const h = build();
|
|
955
|
+
const res = await h.app.request("/github-enterprise/refresh", {
|
|
956
|
+
method: "POST",
|
|
957
|
+
headers: ADMIN,
|
|
958
|
+
});
|
|
959
|
+
expect(res.status).toBe(503);
|
|
960
|
+
expect(h.calls).toEqual([]);
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
it("marks stale after an App is saved, and a failed mark does not fail the save", async () => {
|
|
964
|
+
const { calls: marks, action } = stub();
|
|
965
|
+
const h = build({ refreshAction: action });
|
|
966
|
+
const res = await h.app.request("/github-enterprise/apps/installer", {
|
|
967
|
+
method: "PUT",
|
|
968
|
+
headers: JSON_ADMIN,
|
|
969
|
+
body: JSON.stringify(installerBody),
|
|
970
|
+
});
|
|
971
|
+
expect(res.status).toBe(200);
|
|
972
|
+
expect(marks).toEqual(["refresh"]);
|
|
973
|
+
|
|
974
|
+
const failing = build({
|
|
975
|
+
refreshAction: {
|
|
976
|
+
requestRefresh: async () => {
|
|
977
|
+
throw new Error("db down");
|
|
978
|
+
},
|
|
979
|
+
},
|
|
980
|
+
});
|
|
981
|
+
const res2 = await failing.app.request(
|
|
982
|
+
"/github-enterprise/apps/installer",
|
|
983
|
+
{
|
|
984
|
+
method: "PUT",
|
|
985
|
+
headers: JSON_ADMIN,
|
|
986
|
+
body: JSON.stringify(installerBody),
|
|
987
|
+
},
|
|
988
|
+
);
|
|
989
|
+
expect(res2.status).toBe(200);
|
|
990
|
+
});
|
|
991
|
+
});
|
|
@@ -55,6 +55,7 @@ import {
|
|
|
55
55
|
type GithubLookupService,
|
|
56
56
|
summarizeLookupSnapshots,
|
|
57
57
|
} from "./github-lookup-repositories.ts";
|
|
58
|
+
import type { GithubRefreshAction } from "./github-refresh-action.ts";
|
|
58
59
|
import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
|
|
59
60
|
import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
|
|
60
61
|
import { ErrorSchema } from "./openapi-schemas.ts";
|
|
@@ -72,6 +73,11 @@ export interface GithubEnterpriseApiDeps {
|
|
|
72
73
|
sessionSecret: string;
|
|
73
74
|
adminApiKeys?: Map<string, AdminApiKey>;
|
|
74
75
|
agentTokenService: Pick<AgentTokenService, "validate">;
|
|
76
|
+
/**
|
|
77
|
+
* GLC-2.4: marks the GitHub cache stale. Backs POST /github-enterprise/refresh
|
|
78
|
+
* and runs (best effort) after an App is saved or an agent App is installed.
|
|
79
|
+
*/
|
|
80
|
+
refreshAction?: GithubRefreshAction;
|
|
75
81
|
/** Test seams; default to the real GitHub API. */
|
|
76
82
|
fetchFn?: typeof fetch;
|
|
77
83
|
apiBase?: string;
|
|
@@ -352,6 +358,31 @@ const orgsRoute = createRoute({
|
|
|
352
358
|
},
|
|
353
359
|
});
|
|
354
360
|
|
|
361
|
+
const refreshRoute = createRoute({
|
|
362
|
+
method: "post",
|
|
363
|
+
path: "/github-enterprise/refresh",
|
|
364
|
+
tags,
|
|
365
|
+
summary: "Request a refresh of the GitHub cache",
|
|
366
|
+
description:
|
|
367
|
+
"Admin-only. Marks the cached GitHub repo lists stale and clears retry waits so the background refresher works them next, then returns at once. It makes no GitHub call and does not wait for the refresher; reload the page to see progress. The refresher still honours its per-org lease and rate-limit window.",
|
|
368
|
+
responses: {
|
|
369
|
+
202: {
|
|
370
|
+
description: "Refresh requested",
|
|
371
|
+
content: {
|
|
372
|
+
"application/json": {
|
|
373
|
+
schema: z.object({
|
|
374
|
+
status: z.literal("accepted"),
|
|
375
|
+
snapshots: z.number().int(),
|
|
376
|
+
accessPairs: z.number().int(),
|
|
377
|
+
}),
|
|
378
|
+
},
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
503: { description: "Refresh is not available", ...jsonError },
|
|
382
|
+
...errorResponses,
|
|
383
|
+
},
|
|
384
|
+
});
|
|
385
|
+
|
|
355
386
|
const installRoute = createRoute({
|
|
356
387
|
method: "post",
|
|
357
388
|
path: "/github-enterprise/orgs/{org}/install",
|
|
@@ -721,9 +752,28 @@ export function createGithubEnterpriseApp(
|
|
|
721
752
|
enterpriseSlug: body.enterpriseSlug ?? null,
|
|
722
753
|
privateKey: body.privateKey,
|
|
723
754
|
});
|
|
755
|
+
await markStaleQuietly();
|
|
724
756
|
return c.json(serializeApp(saved), 200);
|
|
725
757
|
});
|
|
726
758
|
|
|
759
|
+
/** Best effort: a failed mark never fails the App change that caused it. */
|
|
760
|
+
const markStaleQuietly = async () => {
|
|
761
|
+
try {
|
|
762
|
+
await deps.refreshAction?.requestRefresh();
|
|
763
|
+
} catch (err) {
|
|
764
|
+
console.error("[github-enterprise] cache refresh mark failed:", err);
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
app.openapi(refreshRoute, async (c) => {
|
|
769
|
+
requireAdmin(c);
|
|
770
|
+
if (!deps.refreshAction) {
|
|
771
|
+
return c.json({ error: "GitHub cache refresh is not available" }, 503);
|
|
772
|
+
}
|
|
773
|
+
const res = await deps.refreshAction.requestRefresh();
|
|
774
|
+
return c.json({ status: "accepted" as const, ...res }, 202);
|
|
775
|
+
});
|
|
776
|
+
|
|
727
777
|
app.openapi(deleteRoute, async (c) => {
|
|
728
778
|
requireAdmin(c);
|
|
729
779
|
await appService.delete(
|
|
@@ -919,6 +969,7 @@ export function createGithubEnterpriseApp(
|
|
|
919
969
|
repositorySelection: body.repositorySelection,
|
|
920
970
|
...(body.repositories ? { repositories: body.repositories } : {}),
|
|
921
971
|
});
|
|
972
|
+
await markStaleQuietly();
|
|
922
973
|
return c.json(
|
|
923
974
|
{
|
|
924
975
|
org,
|
|
@@ -18,7 +18,8 @@ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
|
|
|
18
18
|
import type { CrawlStore } from "./github-repo-crawler.ts";
|
|
19
19
|
import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
|
|
20
20
|
import type { RefreshDiscovery } from "./github-repo-refresher.ts";
|
|
21
|
-
import {
|
|
21
|
+
import { canPushForRole } from "./user-repo-access-resolver.ts";
|
|
22
|
+
import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
|
|
22
23
|
import {
|
|
23
24
|
createInstallationPort,
|
|
24
25
|
type InstallationAgentRecord,
|
|
@@ -95,6 +96,8 @@ export interface InstallationReposWiringDeps
|
|
|
95
96
|
extends GithubInstallationWiringDeps {
|
|
96
97
|
/** Test seam: replaces the installer-App-backed port. */
|
|
97
98
|
installationRepos?: InstallationReposPort;
|
|
99
|
+
/** Test seam: replaces the lookup-App-backed sync cache source and re-check. */
|
|
100
|
+
syncOverrides?: Pick<GithubSyncDeps, "lookupRepos" | "verifyPush">;
|
|
98
101
|
}
|
|
99
102
|
|
|
100
103
|
/**
|
|
@@ -125,9 +128,66 @@ export function createGithubSync(
|
|
|
125
128
|
deps: InstallationReposWiringDeps,
|
|
126
129
|
): GithubSyncService {
|
|
127
130
|
const client = lazyInstallerClient(deps);
|
|
131
|
+
const cache = new GitHubRepoCacheService(deps.prisma);
|
|
132
|
+
const lookupClients = new Map<string, GithubLookupClient>();
|
|
133
|
+
// The lookup client per App (and key version), reused with its installation tokens.
|
|
134
|
+
const lookupClient = async (accountId?: string | null) => {
|
|
135
|
+
const meta = await deps.appService.get("lookup", accountId);
|
|
136
|
+
if (!meta) return null;
|
|
137
|
+
const privateKey = await deps.appService.getPrivateKey("lookup", accountId);
|
|
138
|
+
if (!privateKey) return null;
|
|
139
|
+
const cacheKey = `${meta.accountId ?? ""}|${meta.appId}|${meta.updatedAt.getTime()}`;
|
|
140
|
+
let c = lookupClients.get(cacheKey);
|
|
141
|
+
if (!c) {
|
|
142
|
+
c = new GithubLookupClient({
|
|
143
|
+
appId: meta.appId,
|
|
144
|
+
privateKey,
|
|
145
|
+
apiBase: deps.apiBase,
|
|
146
|
+
fetchFn: deps.fetchFn,
|
|
147
|
+
now: deps.now,
|
|
148
|
+
});
|
|
149
|
+
lookupClients.set(cacheKey, c);
|
|
150
|
+
}
|
|
151
|
+
return { client: c, appId: meta.appId };
|
|
152
|
+
};
|
|
128
153
|
return new GithubSyncService({
|
|
129
154
|
agents: new PrismaInstallationAgents(deps.prisma, deps.agentEnv),
|
|
130
155
|
access: deps.access,
|
|
156
|
+
cache,
|
|
157
|
+
...(deps.now ? { now: deps.now } : {}),
|
|
158
|
+
lookupRepos: async (accountId) => {
|
|
159
|
+
const lookup = await lookupClient(accountId);
|
|
160
|
+
if (!lookup) return [];
|
|
161
|
+
// The crawler files a deployment-wide App's snapshots under accountId "".
|
|
162
|
+
const snapshots = await cache.listLookupOrgSnapshots(
|
|
163
|
+
accountId ? [accountId, ""] : [""],
|
|
164
|
+
lookup.appId,
|
|
165
|
+
);
|
|
166
|
+
return snapshots.map((s) => ({
|
|
167
|
+
org: s.org,
|
|
168
|
+
completedAt: s.completedAt,
|
|
169
|
+
repos: s.repos.map((r) => r.fullName),
|
|
170
|
+
}));
|
|
171
|
+
},
|
|
172
|
+
// One permission call per removal candidate; undefined on any failure.
|
|
173
|
+
verifyPush: async (username, repo, accountId) => {
|
|
174
|
+
try {
|
|
175
|
+
const lookup = await lookupClient(accountId);
|
|
176
|
+
if (!lookup) return undefined;
|
|
177
|
+
const [owner, name] = repo.split("/");
|
|
178
|
+
if (!owner || !name) return undefined;
|
|
179
|
+
const { role } =
|
|
180
|
+
await lookup.client.getCollaboratorPermissionWithRateLimit(
|
|
181
|
+
owner,
|
|
182
|
+
name,
|
|
183
|
+
username,
|
|
184
|
+
);
|
|
185
|
+
return canPushForRole(role);
|
|
186
|
+
} catch {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
...deps.syncOverrides,
|
|
131
191
|
installation:
|
|
132
192
|
deps.installationRepos ??
|
|
133
193
|
createInstallationReposPort(createInstallationPort(client), client),
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
envWith,
|
|
5
5
|
fakeOpenWork,
|
|
6
6
|
fakePrisma,
|
|
7
|
+
freshCache,
|
|
7
8
|
} from "./github-installation.fixtures.ts";
|
|
8
9
|
import {
|
|
9
10
|
createGithubInstallationRepos,
|
|
@@ -72,17 +73,35 @@ describe("createGithubInstallationRepos", () => {
|
|
|
72
73
|
});
|
|
73
74
|
|
|
74
75
|
describe("createGithubSync", () => {
|
|
75
|
-
const
|
|
76
|
-
|
|
76
|
+
const ALL = ["acme/old", "acme/api"];
|
|
77
|
+
const build = (
|
|
78
|
+
openWork?: ReturnType<typeof fakeOpenWork>["port"],
|
|
79
|
+
opts: { checkedAt?: Date; verify?: boolean | undefined } = {},
|
|
80
|
+
) => {
|
|
81
|
+
const checkedAt = opts.checkedAt ?? new Date();
|
|
82
|
+
const { prisma, state } = fakePrisma(
|
|
83
|
+
ALL,
|
|
84
|
+
freshCache("acme", ALL, ["acme/api"], checkedAt),
|
|
85
|
+
);
|
|
86
|
+
const verified: string[] = [];
|
|
77
87
|
const svc = createGithubSync({
|
|
78
88
|
prisma,
|
|
79
89
|
appService: noApp,
|
|
80
90
|
access: accessFor(["acme/api"]),
|
|
81
91
|
agentEnv: envWith({ GH_APP_ID: "42" }),
|
|
82
92
|
installationRepos: portWith([]),
|
|
93
|
+
syncOverrides: {
|
|
94
|
+
lookupRepos: async () => [
|
|
95
|
+
{ org: "acme", completedAt: checkedAt, repos: ALL },
|
|
96
|
+
],
|
|
97
|
+
verifyPush: async (_u, repo) => {
|
|
98
|
+
verified.push(repo);
|
|
99
|
+
return "verify" in opts ? opts.verify : false;
|
|
100
|
+
},
|
|
101
|
+
},
|
|
83
102
|
openWork,
|
|
84
103
|
});
|
|
85
|
-
return { svc, state };
|
|
104
|
+
return { svc, state, verified };
|
|
86
105
|
};
|
|
87
106
|
|
|
88
107
|
it("with a port: preview lists affected open work and apply blocks it", async () => {
|
|
@@ -116,4 +135,37 @@ describe("createGithubSync", () => {
|
|
|
116
135
|
expect(res.status).toBe("applied");
|
|
117
136
|
expect(state.repos).toEqual(["acme/api"]);
|
|
118
137
|
});
|
|
138
|
+
|
|
139
|
+
it("reads the cache: a stale org is skipped with the reason and nothing is removed", async () => {
|
|
140
|
+
const old = new Date(Date.now() - 24 * 3_600_000);
|
|
141
|
+
const { svc, state, verified } = build(undefined, { checkedAt: old });
|
|
142
|
+
const preview = await svc.preview("a1");
|
|
143
|
+
if (preview.status !== "previewed") throw new Error(preview.status);
|
|
144
|
+
expect(preview.plan.removedRepos).toEqual([]);
|
|
145
|
+
expect(preview.plan.skippedOrgs[0]?.reason).toContain("stale (checked");
|
|
146
|
+
const res = await svc.apply({
|
|
147
|
+
agentId: "a1",
|
|
148
|
+
caller: "root",
|
|
149
|
+
appAdds: [],
|
|
150
|
+
appRemoves: ["acme/old"],
|
|
151
|
+
agentRemoves: ["acme/old"],
|
|
152
|
+
});
|
|
153
|
+
expect(res.status).toBe("noop");
|
|
154
|
+
expect(verified).toEqual([]);
|
|
155
|
+
expect(state.repos).toEqual(ALL);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("apply drops a candidate the live re-check still sees as pushable", async () => {
|
|
159
|
+
const { svc, state, verified } = build(undefined, { verify: true });
|
|
160
|
+
const res = await svc.apply({
|
|
161
|
+
agentId: "a1",
|
|
162
|
+
caller: "root",
|
|
163
|
+
appAdds: [],
|
|
164
|
+
appRemoves: [],
|
|
165
|
+
agentRemoves: ["acme/old"],
|
|
166
|
+
});
|
|
167
|
+
expect(res.status).toBe("noop");
|
|
168
|
+
expect(verified).toEqual(["acme/old"]);
|
|
169
|
+
expect(state.repos).toEqual(ALL);
|
|
170
|
+
});
|
|
119
171
|
});
|
|
@@ -33,7 +33,48 @@ export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
|
|
|
33
33
|
});
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
/** Cached rows the fake prisma serves (GLC-2.3 sync reads them). */
|
|
37
|
+
export interface FakeCache {
|
|
38
|
+
snapshots?: unknown[];
|
|
39
|
+
access?: unknown[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A completed agent-App snapshot plus ok access rows for `repos` in `org`, all checked at `checkedAt`. */
|
|
43
|
+
export function freshCache(
|
|
44
|
+
org: string,
|
|
45
|
+
repos: string[],
|
|
46
|
+
pushable: string[],
|
|
47
|
+
checkedAt: Date,
|
|
48
|
+
): FakeCache {
|
|
49
|
+
return {
|
|
50
|
+
snapshots: [
|
|
51
|
+
{
|
|
52
|
+
org,
|
|
53
|
+
completedAt: checkedAt,
|
|
54
|
+
totalCount: repos.length,
|
|
55
|
+
lastError: null,
|
|
56
|
+
rateLimitResetAt: null,
|
|
57
|
+
attempts: 0,
|
|
58
|
+
nextAttemptAt: null,
|
|
59
|
+
leaseHolder: null,
|
|
60
|
+
leasedUntil: null,
|
|
61
|
+
lastTickAt: null,
|
|
62
|
+
repos: repos.map((fullName) => ({ fullName })),
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
access: repos.map((f) => ({
|
|
66
|
+
repo: f.slice(f.indexOf("/") + 1),
|
|
67
|
+
status: "ok",
|
|
68
|
+
canPush: pushable.includes(f),
|
|
69
|
+
level: pushable.includes(f) ? "write" : "none",
|
|
70
|
+
checkedAt,
|
|
71
|
+
attempts: 0,
|
|
72
|
+
lastError: null,
|
|
73
|
+
})),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function fakePrisma(repos: string[], cache: FakeCache = {}) {
|
|
37
78
|
const state = {
|
|
38
79
|
repos: [...repos],
|
|
39
80
|
audits: 0,
|
|
@@ -53,10 +94,10 @@ export function fakePrisma(repos: string[]) {
|
|
|
53
94
|
gitHubRepoSnapshot: {
|
|
54
95
|
findMany: async (args: unknown) => {
|
|
55
96
|
state.snapshotQueries.push(args);
|
|
56
|
-
return [];
|
|
97
|
+
return cache.snapshots ?? [];
|
|
57
98
|
},
|
|
58
99
|
},
|
|
59
|
-
gitHubRepoAccess: { findMany: async () => [] },
|
|
100
|
+
gitHubRepoAccess: { findMany: async () => cache.access ?? [] },
|
|
60
101
|
gitHubReconcileAudit: {
|
|
61
102
|
create: async () => {
|
|
62
103
|
state.audits += 1;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-refresh-action.ts
|
|
3
|
+
* The fire-and-forget Refresh action (GLC-2.4). requestRefresh() only writes
|
|
4
|
+
* to the database (ages the cache snapshots past the staleness cap, clears
|
|
5
|
+
* crawl and access backoff) and asks discovery to run again; it never calls
|
|
6
|
+
* GitHub and never waits on the refresher. The next tick does the work, still
|
|
7
|
+
* behind the snapshot lease and the rate-limit window.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { type Clock, SystemClock } from "./clock.ts";
|
|
11
|
+
import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
|
|
12
|
+
|
|
13
|
+
export interface RefreshRequestResult {
|
|
14
|
+
snapshots: number;
|
|
15
|
+
accessPairs: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface GithubRefreshAction {
|
|
19
|
+
requestRefresh(): Promise<RefreshRequestResult>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createGithubRefreshAction(deps: {
|
|
23
|
+
cache: Pick<GitHubRepoCacheService, "markStale">;
|
|
24
|
+
/** Snapshots are aged past this so the planner treats them as capped work. */
|
|
25
|
+
stalenessCapMs: number;
|
|
26
|
+
/** Runs after the mark (e.g. refresher.invalidateDiscovery). Failures are ignored. */
|
|
27
|
+
onMarked?: () => void;
|
|
28
|
+
clock?: Clock;
|
|
29
|
+
}): GithubRefreshAction {
|
|
30
|
+
const clock = deps.clock ?? SystemClock();
|
|
31
|
+
return {
|
|
32
|
+
async requestRefresh() {
|
|
33
|
+
const staleBefore = new Date(
|
|
34
|
+
clock.now().getTime() - deps.stalenessCapMs - 1,
|
|
35
|
+
);
|
|
36
|
+
const res = await deps.cache.markStale(staleBefore);
|
|
37
|
+
try {
|
|
38
|
+
deps.onMarked?.();
|
|
39
|
+
} catch {
|
|
40
|
+
// discovery refresh is best effort
|
|
41
|
+
}
|
|
42
|
+
return res;
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-refresh-action.unit.test.ts
|
|
3
|
+
* GLC-2.4: stale-marking resets the right rows (and only those), and the
|
|
4
|
+
* action never touches leases or rate-limit windows. Fake prisma; no DB.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it } from "bun:test";
|
|
8
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
9
|
+
import { createGithubRefreshAction } from "./github-refresh-action.ts";
|
|
10
|
+
import { GitHubRepoCacheService } from "./github-repo-cache.ts";
|
|
11
|
+
|
|
12
|
+
type Call = { model: string; args: { where: unknown; data: unknown } };
|
|
13
|
+
|
|
14
|
+
function fakePrisma(counts = { snap: 2, access: 3 }) {
|
|
15
|
+
const calls: Call[] = [];
|
|
16
|
+
const model = (name: string, count: number) => ({
|
|
17
|
+
updateMany: async (args: Call["args"]) => {
|
|
18
|
+
calls.push({ model: name, args });
|
|
19
|
+
return { count };
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
const prisma = {
|
|
23
|
+
gitHubRepoSnapshot: model("snapshot", counts.snap),
|
|
24
|
+
gitHubRepoAccess: model("access", counts.access),
|
|
25
|
+
} as unknown as PrismaClient;
|
|
26
|
+
return { prisma, calls };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe("GitHubRepoCacheService.markStale", () => {
|
|
30
|
+
const staleBefore = new Date("2026-11-01T00:00:00Z");
|
|
31
|
+
|
|
32
|
+
it("ages completed snapshots, clears backoff on snapshots and pending access pairs", async () => {
|
|
33
|
+
const { prisma, calls } = fakePrisma();
|
|
34
|
+
const res = await new GitHubRepoCacheService(prisma).markStale(staleBefore);
|
|
35
|
+
expect(res).toEqual({ snapshots: 2, accessPairs: 3 });
|
|
36
|
+
expect(calls).toEqual([
|
|
37
|
+
{
|
|
38
|
+
model: "snapshot",
|
|
39
|
+
args: {
|
|
40
|
+
where: { completedAt: { gt: staleBefore } },
|
|
41
|
+
data: { completedAt: staleBefore },
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
model: "snapshot",
|
|
46
|
+
args: {
|
|
47
|
+
where: { nextAttemptAt: { not: null } },
|
|
48
|
+
data: { nextAttemptAt: null },
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
model: "access",
|
|
53
|
+
args: {
|
|
54
|
+
where: { status: "error", nextAttemptAt: { not: null } },
|
|
55
|
+
data: { nextAttemptAt: null },
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("never writes the lease, rate-limit or terminal/ok-row columns", async () => {
|
|
62
|
+
const { prisma, calls } = fakePrisma();
|
|
63
|
+
await new GitHubRepoCacheService(prisma).markStale(staleBefore);
|
|
64
|
+
for (const c of calls) {
|
|
65
|
+
const written = Object.keys(c.args.data as object);
|
|
66
|
+
for (const col of [
|
|
67
|
+
"leaseHolder",
|
|
68
|
+
"leasedUntil",
|
|
69
|
+
"rateLimitResetAt",
|
|
70
|
+
"status",
|
|
71
|
+
"checkedAt",
|
|
72
|
+
]) {
|
|
73
|
+
expect(written).not.toContain(col);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const access = calls.find((c) => c.model === "access");
|
|
77
|
+
expect(JSON.stringify(access?.args.where)).toContain('"status":"error"');
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
describe("createGithubRefreshAction", () => {
|
|
82
|
+
const now = new Date("2026-11-20T12:00:00Z");
|
|
83
|
+
|
|
84
|
+
it("marks snapshots past the staleness cap and notifies", async () => {
|
|
85
|
+
const seen: Date[] = [];
|
|
86
|
+
let notified = 0;
|
|
87
|
+
const action = createGithubRefreshAction({
|
|
88
|
+
cache: {
|
|
89
|
+
markStale: async (d: Date) => {
|
|
90
|
+
seen.push(d);
|
|
91
|
+
return { snapshots: 1, accessPairs: 0 };
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
stalenessCapMs: 6 * 3_600_000,
|
|
95
|
+
onMarked: () => {
|
|
96
|
+
notified++;
|
|
97
|
+
},
|
|
98
|
+
clock: { now: () => now },
|
|
99
|
+
});
|
|
100
|
+
expect(await action.requestRefresh()).toEqual({
|
|
101
|
+
snapshots: 1,
|
|
102
|
+
accessPairs: 0,
|
|
103
|
+
});
|
|
104
|
+
expect(seen[0]?.getTime()).toBeLessThan(now.getTime() - 6 * 3_600_000);
|
|
105
|
+
expect(notified).toBe(1);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("ignores a failing onMarked hook", async () => {
|
|
109
|
+
const action = createGithubRefreshAction({
|
|
110
|
+
cache: { markStale: async () => ({ snapshots: 0, accessPairs: 0 }) },
|
|
111
|
+
stalenessCapMs: 1000,
|
|
112
|
+
onMarked: () => {
|
|
113
|
+
throw new Error("boom");
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
await expect(action.requestRefresh()).resolves.toEqual({
|
|
117
|
+
snapshots: 0,
|
|
118
|
+
accessPairs: 0,
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
});
|
package/src/github-repo-cache.ts
CHANGED
|
@@ -146,6 +146,21 @@ export class GitHubRepoCacheService {
|
|
|
146
146
|
}));
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
+
/** Lookup-App snapshots with their org and repos (GitHub Sync, GLC-2.3). Reads only the cache. */
|
|
150
|
+
async listLookupOrgSnapshots(accountIds: string[], appRef: string) {
|
|
151
|
+
requireNonEmpty("appRef", appRef);
|
|
152
|
+
const rows = await this.prisma.gitHubRepoSnapshot.findMany({
|
|
153
|
+
where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
|
|
154
|
+
include: { repos: { select: { fullName: true } } },
|
|
155
|
+
orderBy: { org: "asc" },
|
|
156
|
+
});
|
|
157
|
+
return rows.map((r) => ({
|
|
158
|
+
org: r.org,
|
|
159
|
+
completedAt: r.completedAt,
|
|
160
|
+
repos: r.repos,
|
|
161
|
+
}));
|
|
162
|
+
}
|
|
163
|
+
|
|
149
164
|
/** Agent-App installation snapshots (with their repos) for one account scope and App id. Reads only the cache. */
|
|
150
165
|
async listAgentSnapshots(accountId: string, appRef: string) {
|
|
151
166
|
requireNonEmpty("accountId", accountId);
|
|
@@ -161,6 +176,11 @@ export class GitHubRepoCacheService {
|
|
|
161
176
|
totalCount: r.totalCount,
|
|
162
177
|
lastError: r.lastError,
|
|
163
178
|
rateLimitResetAt: r.rateLimitResetAt,
|
|
179
|
+
attempts: r.attempts,
|
|
180
|
+
nextAttemptAt: r.nextAttemptAt,
|
|
181
|
+
leaseHolder: r.leaseHolder,
|
|
182
|
+
leasedUntil: r.leasedUntil,
|
|
183
|
+
lastTickAt: r.lastTickAt,
|
|
164
184
|
repos: r.repos,
|
|
165
185
|
}));
|
|
166
186
|
}
|
|
@@ -241,6 +261,38 @@ export class GitHubRepoCacheService {
|
|
|
241
261
|
return count;
|
|
242
262
|
}
|
|
243
263
|
|
|
264
|
+
/**
|
|
265
|
+
* Refresh request (GLC-2.4): make every snapshot's work the next thing the
|
|
266
|
+
* refresher runs, without touching GitHub. A completed list is aged to
|
|
267
|
+
* `staleBefore` (callers pass a time past the staleness cap, so the planner
|
|
268
|
+
* ranks it ahead of expired-only work); any snapshot's crawl backoff
|
|
269
|
+
* (nextAttemptAt) is cleared, and so is the backoff on access pairs that
|
|
270
|
+
* are still pending (status error). Leases and rateLimitResetAt are left
|
|
271
|
+
* alone, so the lease and the rate-limit window still gate the work.
|
|
272
|
+
* Terminal and ok access rows are not touched.
|
|
273
|
+
*/
|
|
274
|
+
async markStale(staleBefore: Date): Promise<{
|
|
275
|
+
snapshots: number;
|
|
276
|
+
accessPairs: number;
|
|
277
|
+
}> {
|
|
278
|
+
const aged = await this.prisma.gitHubRepoSnapshot.updateMany({
|
|
279
|
+
where: { completedAt: { gt: staleBefore } },
|
|
280
|
+
data: { completedAt: staleBefore },
|
|
281
|
+
});
|
|
282
|
+
const backoff = await this.prisma.gitHubRepoSnapshot.updateMany({
|
|
283
|
+
where: { nextAttemptAt: { not: null } },
|
|
284
|
+
data: { nextAttemptAt: null },
|
|
285
|
+
});
|
|
286
|
+
const access = await this.prisma.gitHubRepoAccess.updateMany({
|
|
287
|
+
where: { status: "error", nextAttemptAt: { not: null } },
|
|
288
|
+
data: { nextAttemptAt: null },
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
snapshots: Math.max(aged.count, backoff.count),
|
|
292
|
+
accessPairs: access.count,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
244
296
|
/**
|
|
245
297
|
* Take the org's lease for `ttlMs`. True when this holder now owns it; false
|
|
246
298
|
* when another holder's lease is still live or the snapshot does not exist.
|
|
@@ -313,6 +313,11 @@ export class GithubRepoRefresher {
|
|
|
313
313
|
deps.discoveryIntervalMs ?? DEFAULT_REFRESH_DISCOVERY_INTERVAL_MS;
|
|
314
314
|
}
|
|
315
315
|
|
|
316
|
+
/** Make the next tick re-discover targets (new or changed GitHub Apps). */
|
|
317
|
+
invalidateDiscovery(): void {
|
|
318
|
+
this.discoveredAt = null;
|
|
319
|
+
}
|
|
320
|
+
|
|
316
321
|
/** Debug snapshot of the last ticks (a copy). */
|
|
317
322
|
status(): RefreshStatus {
|
|
318
323
|
return {
|