@app-vitals/agent-admin 1.75.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.
@@ -8,6 +8,7 @@ import { generateKeyPairSync } from "node:crypto";
8
8
  import { GithubEnterpriseError } from "./github-enterprise-client.ts";
9
9
  import {
10
10
  GithubLookupClient,
11
+ GithubLookupRateLimitError,
11
12
  mapRepoRole,
12
13
  REPO_ROLES,
13
14
  } from "./github-lookup-client.ts";
@@ -134,7 +135,10 @@ describe("GithubLookupClient.listInstallations", () => {
134
135
  appId: "555",
135
136
  privateKey,
136
137
  fetchFn: (async () =>
137
- Response.json({ message: "boom" }, { status: 500 })) as unknown as typeof fetch,
138
+ Response.json(
139
+ { message: "boom" },
140
+ { status: 500 },
141
+ )) as unknown as typeof fetch,
138
142
  });
139
143
  await expect(client.listInstallations()).rejects.toBeInstanceOf(
140
144
  GithubEnterpriseError,
@@ -147,6 +151,147 @@ describe("GithubLookupClient.listInstallations", () => {
147
151
  privateKey,
148
152
  fetchFn: (async () => Response.json({})) as unknown as typeof fetch,
149
153
  });
150
- await expect(client.listInstallations()).rejects.toThrow("not an installation list");
154
+ await expect(client.listInstallations()).rejects.toThrow(
155
+ "not an installation list",
156
+ );
157
+ });
158
+ });
159
+
160
+ describe("GithubLookupClient request timeout", () => {
161
+ const { privateKey } = generateKeyPairSync("rsa", {
162
+ modulusLength: 2048,
163
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
164
+ publicKeyEncoding: { type: "spki", format: "pem" },
165
+ });
166
+
167
+ /** A fetch that never answers on its own; it only rejects when aborted. */
168
+ const hanging = (signals: AbortSignal[]) =>
169
+ ((_u: unknown, init?: RequestInit) =>
170
+ new Promise<Response>((_resolve, reject) => {
171
+ const signal = init?.signal;
172
+ if (!signal) return; // would hang forever: the test times out
173
+ signals.push(signal);
174
+ signal.addEventListener("abort", () => reject(signal.reason));
175
+ })) as unknown as typeof fetch;
176
+
177
+ it("aborts a hung request after requestTimeoutMs as a network error", async () => {
178
+ const signals: AbortSignal[] = [];
179
+ const client = new GithubLookupClient({
180
+ appId: "555",
181
+ privateKey,
182
+ fetchFn: hanging(signals),
183
+ requestTimeoutMs: 20,
184
+ });
185
+ try {
186
+ await client.getOrgToken("acme-eng");
187
+ } catch (e) {
188
+ const err = e as GithubEnterpriseError;
189
+ expect(err).toBeInstanceOf(GithubEnterpriseError);
190
+ expect(err.kind).toBe("network");
191
+ expect(err.message).toContain("timed out");
192
+ expect(signals).toHaveLength(1);
193
+ return;
194
+ }
195
+ throw new Error("expected rejection");
196
+ });
197
+
198
+ it("passes an abort signal on every request, including page fetches", async () => {
199
+ const signals: (AbortSignal | undefined)[] = [];
200
+ const client = new GithubLookupClient({
201
+ appId: "555",
202
+ privateKey,
203
+ fetchFn: (async (input: RequestInfo | URL, init?: RequestInit) => {
204
+ signals.push(init?.signal ?? undefined);
205
+ const path = new URL(input.toString()).pathname;
206
+ if (path === "/orgs/acme-eng/installation")
207
+ return Response.json({ id: 1 });
208
+ if (path === "/app/installations/1/access_tokens")
209
+ return Response.json({
210
+ token: "ghs_x",
211
+ expires_at: "2999-01-01T00:00:00Z",
212
+ });
213
+ return Response.json({ total_count: 0, repositories: [] });
214
+ }) as unknown as typeof fetch,
215
+ });
216
+ await client.listInstallationRepositoriesPage("acme-eng", 1);
217
+ expect(signals).toHaveLength(3);
218
+ for (const s of signals) expect(s).toBeInstanceOf(AbortSignal);
219
+ });
220
+ });
221
+
222
+ describe("GithubLookupClient.listInstallationRepositoriesPage", () => {
223
+ const { privateKey } = generateKeyPairSync("rsa", {
224
+ modulusLength: 2048,
225
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
226
+ publicKeyEncoding: { type: "spki", format: "pem" },
227
+ });
228
+ const NOW = new Date("2026-11-20T12:00:00Z");
229
+
230
+ function clientFor(reposResponse: () => Response) {
231
+ return new GithubLookupClient({
232
+ appId: "555",
233
+ privateKey,
234
+ now: () => NOW,
235
+ fetchFn: (async (input: RequestInfo | URL) => {
236
+ const path = new URL(input.toString()).pathname;
237
+ if (path === "/orgs/acme-eng/installation")
238
+ return Response.json({ id: 1 });
239
+ if (path === "/app/installations/1/access_tokens")
240
+ return Response.json({
241
+ token: "ghs_x",
242
+ expires_at: "2999-01-01T00:00:00Z",
243
+ });
244
+ return reposResponse();
245
+ }) as unknown as typeof fetch,
246
+ });
247
+ }
248
+
249
+ it("rejects a response without a numeric total_count", async () => {
250
+ const client = clientFor(() => Response.json({ repositories: [] }));
251
+ await expect(
252
+ client.listInstallationRepositoriesPage("acme-eng", 1),
253
+ ).rejects.toThrow("total_count");
254
+ });
255
+
256
+ it("rejects a page number below 1", async () => {
257
+ const client = clientFor(() =>
258
+ Response.json({ total_count: 0, repositories: [] }),
259
+ );
260
+ await expect(
261
+ client.listInstallationRepositoriesPage("acme-eng", 0),
262
+ ).rejects.toThrow("page");
263
+ });
264
+
265
+ it("falls back to a short page when there is no Link header", async () => {
266
+ const client = clientFor(() =>
267
+ Response.json({
268
+ total_count: 1,
269
+ repositories: [{ id: 1, name: "a", full_name: "acme-eng/a" }],
270
+ }),
271
+ );
272
+ const page = await client.listInstallationRepositoriesPage("acme-eng", 1);
273
+ expect(page.hasNext).toBe(false);
274
+ expect(page.rateLimit).toEqual({
275
+ remaining: null,
276
+ resetAt: null,
277
+ retryAfterSeconds: null,
278
+ });
279
+ });
280
+
281
+ it("defaults a rate limit without reset hints to one minute out", async () => {
282
+ const client = clientFor(() =>
283
+ Response.json({ message: "API rate limit exceeded" }, { status: 429 }),
284
+ );
285
+ try {
286
+ await client.listInstallationRepositoriesPage("acme-eng", 1);
287
+ } catch (e) {
288
+ expect(e).toBeInstanceOf(GithubLookupRateLimitError);
289
+ expect((e as GithubLookupRateLimitError).kind).toBe("rate_limit");
290
+ expect((e as GithubLookupRateLimitError).resetAt).toEqual(
291
+ new Date(NOW.getTime() + 60_000),
292
+ );
293
+ return;
294
+ }
295
+ throw new Error("expected rejection");
151
296
  });
152
297
  });
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Integration tests for GitHubRepoCacheService against a real PostgreSQL DB.
3
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
4
+ */
5
+
6
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
7
+ import type { PrismaClient } from "../prisma/client/client.ts";
8
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
9
+ import { createAdminPrismaClient } from "./prisma-client.ts";
10
+
11
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
12
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
13
+
14
+ const key = {
15
+ accountId: "acc",
16
+ appKind: "lookup" as const,
17
+ appRef: "1",
18
+ org: "acme",
19
+ };
20
+ const T0 = new Date("2026-11-20T12:00:00Z");
21
+ const min = (n: number) => new Date(T0.getTime() + n * 60_000);
22
+
23
+ describeOrSkip("GitHubRepoCacheService (integration)", () => {
24
+ let prisma: PrismaClient;
25
+ let now: Date;
26
+ let svc: GitHubRepoCacheService;
27
+
28
+ beforeEach(async () => {
29
+ prisma = createAdminPrismaClient(TEST_DB as string);
30
+ await prisma.gitHubCachedRepo.deleteMany();
31
+ await prisma.gitHubRepoSnapshot.deleteMany();
32
+ await prisma.gitHubRepoAccess.deleteMany();
33
+ now = T0;
34
+ svc = new GitHubRepoCacheService(prisma, { now: () => now });
35
+ });
36
+
37
+ afterEach(async () => {
38
+ await prisma.$disconnect();
39
+ });
40
+
41
+ it("upserts and reads a snapshot, merging progress", async () => {
42
+ expect(await svc.getSnapshot(key)).toBeNull();
43
+ const a = await svc.upsertSnapshot(key, { crawlPage: 1, totalCount: 5 });
44
+ const b = await svc.upsertSnapshot(key, { crawlPage: 2 });
45
+ expect(b.id).toBe(a.id);
46
+ expect(b.crawlPage).toBe(2);
47
+ expect(b.totalCount).toBe(5);
48
+ expect((await svc.getSnapshot(key))?.id).toBe(a.id);
49
+ });
50
+
51
+ it("batch-upserts repos without duplicating", async () => {
52
+ const snap = await svc.upsertSnapshot(key);
53
+ const repos = Array.from({ length: 1200 }, (_, i) => ({
54
+ githubId: 10_000_000_000 + i,
55
+ fullName: `acme/r${i}`,
56
+ }));
57
+ await svc.upsertRepos(snap.id, repos, T0);
58
+ await svc.upsertRepos(
59
+ snap.id,
60
+ [{ githubId: 10_000_000_000, fullName: "acme/renamed", archived: true }],
61
+ min(1),
62
+ );
63
+ expect(await prisma.gitHubCachedRepo.count()).toBe(1200);
64
+ const r = await prisma.gitHubCachedRepo.findFirstOrThrow({
65
+ where: { githubId: 10_000_000_000n },
66
+ });
67
+ expect(r.fullName).toBe("acme/renamed");
68
+ expect(r.archived).toBe(true);
69
+ });
70
+
71
+ it("sweep deletes only rows seen before crawlStartedAt", async () => {
72
+ const snap = await svc.upsertSnapshot(key, { crawlStartedAt: min(10) });
73
+ await svc.upsertRepos(
74
+ snap.id,
75
+ [{ githubId: 1, fullName: "acme/old" }],
76
+ min(5),
77
+ );
78
+ await svc.upsertRepos(
79
+ snap.id,
80
+ [{ githubId: 2, fullName: "acme/new" }],
81
+ min(10),
82
+ );
83
+ await svc.upsertRepos(
84
+ snap.id,
85
+ [{ githubId: 3, fullName: "acme/newer" }],
86
+ min(11),
87
+ );
88
+ expect(await svc.sweepGeneration(snap.id)).toBe(1);
89
+ const left = await prisma.gitHubCachedRepo.findMany({
90
+ orderBy: { githubId: "asc" },
91
+ });
92
+ expect(left.map((r) => r.fullName)).toEqual(["acme/new", "acme/newer"]);
93
+ });
94
+
95
+ it("sweep is a no-op before a crawl has started and spares other snapshots", async () => {
96
+ const a = await svc.upsertSnapshot(key);
97
+ const b = await svc.upsertSnapshot(
98
+ { ...key, org: "other" },
99
+ { crawlStartedAt: min(10) },
100
+ );
101
+ await svc.upsertRepos(a.id, [{ githubId: 1, fullName: "acme/x" }], min(1));
102
+ await svc.upsertRepos(
103
+ b.id,
104
+ [{ githubId: 2, fullName: "other/y" }],
105
+ min(20),
106
+ );
107
+ expect(await svc.sweepGeneration(a.id)).toBe(0);
108
+ expect(await prisma.gitHubCachedRepo.count()).toBe(2);
109
+ });
110
+
111
+ it("lease: first concurrent acquirer wins; others fail until expiry", async () => {
112
+ const snap = await svc.upsertSnapshot(key);
113
+ const results = await Promise.all(
114
+ ["w1", "w2", "w3", "w4"].map((w) => svc.acquireLease(snap.id, w, 60_000)),
115
+ );
116
+ expect(results.filter(Boolean).length).toBe(1);
117
+ const holder = (await svc.getSnapshot(key))?.leaseHolder as string;
118
+ expect(await svc.acquireLease(snap.id, "late", 60_000)).toBe(false);
119
+ now = min(2); // past leasedUntil
120
+ expect(await svc.acquireLease(snap.id, "late", 60_000)).toBe(true);
121
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBe("late");
122
+ expect(holder).not.toBe("late");
123
+ });
124
+
125
+ it("lease: release is idempotent, owner-only, and frees the lease", async () => {
126
+ const snap = await svc.upsertSnapshot(key);
127
+ expect(await svc.acquireLease(snap.id, "w1", 60_000)).toBe(true);
128
+ await svc.releaseLease(snap.id, "intruder");
129
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBe("w1");
130
+ await svc.releaseLease(snap.id, "w1");
131
+ await svc.releaseLease(snap.id, "w1");
132
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBeNull();
133
+ expect(await svc.acquireLease(snap.id, "w2", 60_000)).toBe(true);
134
+ });
135
+
136
+ it("acquire on a missing snapshot returns false", async () => {
137
+ expect(await svc.acquireLease("nope", "w", 1000)).toBe(false);
138
+ });
139
+
140
+ it("access: missing-or-expired query", async () => {
141
+ const base = {
142
+ accountId: "acc",
143
+ org: "acme",
144
+ username: "dan",
145
+ canPush: true,
146
+ };
147
+ await svc.upsertAccess({ ...base, repo: "fresh", status: "ok" });
148
+ await svc.upsertAccess({
149
+ ...base,
150
+ repo: "terminal",
151
+ status: "terminal",
152
+ lastError: "404",
153
+ });
154
+ await svc.upsertAccess({
155
+ ...base,
156
+ repo: "err-later",
157
+ status: "error",
158
+ attempts: 1,
159
+ nextAttemptAt: min(30),
160
+ });
161
+ await svc.upsertAccess({
162
+ ...base,
163
+ repo: "err-due",
164
+ status: "error",
165
+ attempts: 1,
166
+ nextAttemptAt: min(-1),
167
+ });
168
+ await svc.upsertAccess({
169
+ ...base,
170
+ repo: "other-user",
171
+ status: "ok",
172
+ username: "eve",
173
+ });
174
+ const repos = [
175
+ "fresh",
176
+ "terminal",
177
+ "err-later",
178
+ "err-due",
179
+ "other-user",
180
+ "absent",
181
+ ];
182
+ const q = {
183
+ accountId: "acc",
184
+ org: "acme",
185
+ username: "dan",
186
+ repos,
187
+ maxAgeMs: 3_600_000,
188
+ };
189
+ expect(await svc.findMissingOrExpiredAccess(q)).toEqual([
190
+ "err-due",
191
+ "other-user",
192
+ "absent",
193
+ ]);
194
+ now = min(120); // everything ok is now older than 1h; error-later is due too
195
+ expect(await svc.findMissingOrExpiredAccess(q)).toEqual([
196
+ "fresh",
197
+ "err-later",
198
+ "err-due",
199
+ "other-user",
200
+ "absent",
201
+ ]);
202
+ });
203
+
204
+ it("access: upsert updates in place", async () => {
205
+ const base = { accountId: "acc", org: "acme", username: "dan", repo: "r" };
206
+ await svc.upsertAccess({
207
+ ...base,
208
+ canPush: false,
209
+ status: "error",
210
+ attempts: 1,
211
+ });
212
+ await svc.upsertAccess({
213
+ ...base,
214
+ canPush: true,
215
+ level: "write",
216
+ status: "ok",
217
+ });
218
+ const rows = await prisma.gitHubRepoAccess.findMany();
219
+ expect(rows).toHaveLength(1);
220
+ expect(rows[0]).toMatchObject({
221
+ canPush: true,
222
+ level: "write",
223
+ status: "ok",
224
+ attempts: 0,
225
+ });
226
+ });
227
+ });
@@ -0,0 +1,304 @@
1
+ /**
2
+ * admin/src/github-repo-cache.ts
3
+ * GitHubRepoCacheService — storage for the GitHub repo/access cache (GLC-1.1):
4
+ * a per-org crawl snapshot, the repos each crawl saw, and per-user push access.
5
+ *
6
+ * Crawl generations: a crawl stamps every repo it sees with `seenAt >=
7
+ * crawlStartedAt`; sweepGeneration() then deletes rows older than that, i.e.
8
+ * repos that disappeared since the previous crawl.
9
+ *
10
+ * Leases are a compare-and-set on `leasedUntil` (one UPDATE), so of several
11
+ * concurrent acquirers exactly one wins until the lease expires or is released.
12
+ */
13
+
14
+ import type { PrismaClient } from "../prisma/client/client.ts";
15
+ import { type Clock, SystemClock } from "./clock.ts";
16
+ import { BadRequestError } from "./errors.ts";
17
+
18
+ export const GITHUB_REPO_APP_KINDS = ["lookup", "agent"] as const;
19
+ export type GitHubRepoAppKind = (typeof GITHUB_REPO_APP_KINDS)[number];
20
+
21
+ export const GITHUB_ACCESS_STATUSES = ["ok", "error", "terminal"] as const;
22
+ export type GitHubAccessStatus = (typeof GITHUB_ACCESS_STATUSES)[number];
23
+
24
+ export interface SnapshotKey {
25
+ accountId: string;
26
+ appKind: GitHubRepoAppKind;
27
+ appRef: string;
28
+ org: string;
29
+ }
30
+
31
+ export type SnapshotProgress = Partial<{
32
+ crawlPage: number;
33
+ crawlStartedAt: Date | null;
34
+ completedAt: Date | null;
35
+ totalCount: number | null;
36
+ lastError: string | null;
37
+ attempts: number;
38
+ nextAttemptAt: Date | null;
39
+ rateLimitResetAt: Date | null;
40
+ lastTickAt: Date | null;
41
+ }>;
42
+
43
+ export interface CachedRepoInput {
44
+ githubId: number | bigint;
45
+ fullName: string;
46
+ archived?: boolean;
47
+ }
48
+
49
+ export interface AccessInput {
50
+ accountId: string;
51
+ org: string;
52
+ repo: string;
53
+ username: string;
54
+ canPush: boolean;
55
+ level?: string | null;
56
+ status: GitHubAccessStatus;
57
+ attempts?: number;
58
+ nextAttemptAt?: Date | null;
59
+ lastError?: string | null;
60
+ }
61
+
62
+ export interface AccessQuery {
63
+ accountId: string;
64
+ org: string;
65
+ username: string;
66
+ /** Repo names (without org) to consider. */
67
+ repos: string[];
68
+ /** Rows with status ok older than this are expired. */
69
+ maxAgeMs: number;
70
+ }
71
+
72
+ const REPO_BATCH_SIZE = 500;
73
+
74
+ function requireNonEmpty(name: string, value: unknown): void {
75
+ if (typeof value !== "string" || value.trim() === "") {
76
+ throw new BadRequestError(`${name} is required`);
77
+ }
78
+ }
79
+
80
+ function validateKey(key: SnapshotKey): void {
81
+ requireNonEmpty("accountId", key.accountId);
82
+ requireNonEmpty("appRef", key.appRef);
83
+ requireNonEmpty("org", key.org);
84
+ if (!(GITHUB_REPO_APP_KINDS as readonly string[]).includes(key.appKind)) {
85
+ throw new BadRequestError(
86
+ `appKind must be one of: ${GITHUB_REPO_APP_KINDS.join(", ")}`,
87
+ );
88
+ }
89
+ }
90
+
91
+ function validatePositiveMs(name: string, value: number): void {
92
+ if (!Number.isFinite(value) || value <= 0) {
93
+ throw new BadRequestError(`${name} must be a positive number`);
94
+ }
95
+ }
96
+
97
+ export class GitHubRepoCacheService {
98
+ constructor(
99
+ private readonly prisma: PrismaClient,
100
+ private readonly clock: Clock = SystemClock(),
101
+ ) {}
102
+
103
+ private where(key: SnapshotKey) {
104
+ return {
105
+ accountId_appKind_appRef_org: {
106
+ accountId: key.accountId,
107
+ appKind: key.appKind,
108
+ appRef: key.appRef,
109
+ org: key.org,
110
+ },
111
+ };
112
+ }
113
+
114
+ /** Create the snapshot row, or merge `progress` into the existing one. */
115
+ async upsertSnapshot(key: SnapshotKey, progress: SnapshotProgress = {}) {
116
+ validateKey(key);
117
+ return this.prisma.gitHubRepoSnapshot.upsert({
118
+ where: this.where(key),
119
+ create: { ...key, ...progress },
120
+ update: progress,
121
+ });
122
+ }
123
+
124
+ async getSnapshot(key: SnapshotKey) {
125
+ validateKey(key);
126
+ return this.prisma.gitHubRepoSnapshot.findUnique({
127
+ where: this.where(key),
128
+ });
129
+ }
130
+
131
+ /** Upsert repos for a snapshot in batches, stamping each with `seenAt`. */
132
+ async upsertRepos(
133
+ snapshotId: string,
134
+ repos: CachedRepoInput[],
135
+ seenAt: Date = this.clock.now(),
136
+ ): Promise<number> {
137
+ requireNonEmpty("snapshotId", snapshotId);
138
+ for (const r of repos) {
139
+ requireNonEmpty("fullName", r.fullName);
140
+ }
141
+ for (let i = 0; i < repos.length; i += REPO_BATCH_SIZE) {
142
+ const batch = repos.slice(i, i + REPO_BATCH_SIZE);
143
+ await this.prisma.$transaction(
144
+ batch.map((r) =>
145
+ this.prisma.gitHubCachedRepo.upsert({
146
+ where: {
147
+ snapshotId_githubId: {
148
+ snapshotId,
149
+ githubId: BigInt(r.githubId),
150
+ },
151
+ },
152
+ create: {
153
+ snapshotId,
154
+ githubId: BigInt(r.githubId),
155
+ fullName: r.fullName,
156
+ archived: r.archived ?? false,
157
+ seenAt,
158
+ },
159
+ update: {
160
+ fullName: r.fullName,
161
+ archived: r.archived ?? false,
162
+ seenAt,
163
+ },
164
+ }),
165
+ ),
166
+ );
167
+ }
168
+ return repos.length;
169
+ }
170
+
171
+ /** Number of the snapshot's repos with `seenAt >= since` (distinct rows). */
172
+ async countReposSeenSince(snapshotId: string, since: Date): Promise<number> {
173
+ requireNonEmpty("snapshotId", snapshotId);
174
+ return this.prisma.gitHubCachedRepo.count({
175
+ where: { snapshotId, seenAt: { gte: since } },
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Delete repos last seen before the snapshot's crawlStartedAt. Returns the
181
+ * number deleted; 0 (and deletes nothing) when no crawl has started.
182
+ */
183
+ async sweepGeneration(snapshotId: string): Promise<number> {
184
+ requireNonEmpty("snapshotId", snapshotId);
185
+ const snap = await this.prisma.gitHubRepoSnapshot.findUnique({
186
+ where: { id: snapshotId },
187
+ select: { crawlStartedAt: true },
188
+ });
189
+ if (!snap?.crawlStartedAt) return 0;
190
+ const { count } = await this.prisma.gitHubCachedRepo.deleteMany({
191
+ where: { snapshotId, seenAt: { lt: snap.crawlStartedAt } },
192
+ });
193
+ return count;
194
+ }
195
+
196
+ /**
197
+ * Take the org's lease for `ttlMs`. True when this holder now owns it; false
198
+ * when another holder's lease is still live or the snapshot does not exist.
199
+ */
200
+ async acquireLease(
201
+ snapshotId: string,
202
+ holder: string,
203
+ ttlMs: number,
204
+ ): Promise<boolean> {
205
+ requireNonEmpty("snapshotId", snapshotId);
206
+ requireNonEmpty("holder", holder);
207
+ validatePositiveMs("ttlMs", ttlMs);
208
+ const now = this.clock.now();
209
+ const { count } = await this.prisma.gitHubRepoSnapshot.updateMany({
210
+ where: {
211
+ id: snapshotId,
212
+ OR: [{ leasedUntil: null }, { leasedUntil: { lte: now } }],
213
+ },
214
+ data: {
215
+ leaseHolder: holder,
216
+ leasedUntil: new Date(now.getTime() + ttlMs),
217
+ },
218
+ });
219
+ return count === 1;
220
+ }
221
+
222
+ /** Release the lease if `holder` still owns it. Idempotent. */
223
+ async releaseLease(snapshotId: string, holder: string): Promise<void> {
224
+ requireNonEmpty("snapshotId", snapshotId);
225
+ requireNonEmpty("holder", holder);
226
+ await this.prisma.gitHubRepoSnapshot.updateMany({
227
+ where: { id: snapshotId, leaseHolder: holder },
228
+ data: { leaseHolder: null, leasedUntil: null },
229
+ });
230
+ }
231
+
232
+ async upsertAccess(input: AccessInput) {
233
+ requireNonEmpty("accountId", input.accountId);
234
+ requireNonEmpty("org", input.org);
235
+ requireNonEmpty("repo", input.repo);
236
+ requireNonEmpty("username", input.username);
237
+ if (!(GITHUB_ACCESS_STATUSES as readonly string[]).includes(input.status)) {
238
+ throw new BadRequestError(
239
+ `status must be one of: ${GITHUB_ACCESS_STATUSES.join(", ")}`,
240
+ );
241
+ }
242
+ const data = {
243
+ canPush: input.canPush,
244
+ level: input.level ?? null,
245
+ checkedAt: this.clock.now(),
246
+ status: input.status,
247
+ attempts: input.attempts ?? 0,
248
+ nextAttemptAt: input.nextAttemptAt ?? null,
249
+ lastError: input.lastError ?? null,
250
+ };
251
+ return this.prisma.gitHubRepoAccess.upsert({
252
+ where: {
253
+ accountId_org_repo_username: {
254
+ accountId: input.accountId,
255
+ org: input.org,
256
+ repo: input.repo,
257
+ username: input.username,
258
+ },
259
+ },
260
+ create: {
261
+ accountId: input.accountId,
262
+ org: input.org,
263
+ repo: input.repo,
264
+ username: input.username,
265
+ ...data,
266
+ },
267
+ update: data,
268
+ });
269
+ }
270
+
271
+ /**
272
+ * Repos in `query.repos` that still need an access check: no row yet, an ok
273
+ * row older than maxAgeMs, or an error row whose nextAttemptAt has passed.
274
+ * Terminal rows are never returned.
275
+ */
276
+ async findMissingOrExpiredAccess(query: AccessQuery): Promise<string[]> {
277
+ requireNonEmpty("accountId", query.accountId);
278
+ requireNonEmpty("org", query.org);
279
+ requireNonEmpty("username", query.username);
280
+ validatePositiveMs("maxAgeMs", query.maxAgeMs);
281
+ if (query.repos.length === 0) return [];
282
+ const now = this.clock.now();
283
+ const rows = await this.prisma.gitHubRepoAccess.findMany({
284
+ where: {
285
+ accountId: query.accountId,
286
+ org: query.org,
287
+ username: query.username,
288
+ repo: { in: query.repos },
289
+ },
290
+ });
291
+ const staleBefore = now.getTime() - query.maxAgeMs;
292
+ const settled = new Set<string>();
293
+ for (const row of rows) {
294
+ const due =
295
+ row.status === "ok"
296
+ ? row.checkedAt.getTime() < staleBefore
297
+ : row.status === "error"
298
+ ? row.nextAttemptAt === null || row.nextAttemptAt <= now
299
+ : false;
300
+ if (!due) settled.add(row.repo);
301
+ }
302
+ return query.repos.filter((r) => !settled.has(r));
303
+ }
304
+ }