@app-vitals/agent-admin 1.75.0 → 1.76.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/package.json +2 -2
- package/prisma/client/browser.ts +15 -0
- package/prisma/client/client.ts +15 -0
- package/prisma/client/internal/class.ts +34 -4
- package/prisma/client/internal/prismaNamespace.ts +284 -2
- package/prisma/client/internal/prismaNamespaceBrowser.ts +58 -1
- package/prisma/client/models/GitHubCachedRepo.ts +1430 -0
- package/prisma/client/models/GitHubRepoAccess.ts +1397 -0
- package/prisma/client/models/GitHubRepoSnapshot.ts +1807 -0
- package/prisma/client/models.ts +3 -0
- package/prisma/migrations/20261120000000_add_github_repo_cache/migration.sql +75 -0
- package/prisma/schema/schema.prisma +62 -0
- package/src/github-repo-cache.integration.test.ts +227 -0
- package/src/github-repo-cache.ts +296 -0
- package/src/github-repo-cache.unit.test.ts +66 -0
package/prisma/client/models.ts
CHANGED
|
@@ -40,4 +40,7 @@ export type * from './models/ChatThreadWatch.ts'
|
|
|
40
40
|
export type * from './models/UserNotificationPrefs.ts'
|
|
41
41
|
export type * from './models/AgentMarketplace.ts'
|
|
42
42
|
export type * from './models/GitHubReconcileAudit.ts'
|
|
43
|
+
export type * from './models/GitHubRepoSnapshot.ts'
|
|
44
|
+
export type * from './models/GitHubCachedRepo.ts'
|
|
45
|
+
export type * from './models/GitHubRepoAccess.ts'
|
|
43
46
|
export type * from './commonInputTypes.ts'
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
-- GLC-1.1: GitHub repo/access cache. Additive only: three new tables, nothing existing is touched.
|
|
2
|
+
-- CreateTable
|
|
3
|
+
CREATE TABLE "GitHubRepoSnapshot" (
|
|
4
|
+
"id" TEXT NOT NULL,
|
|
5
|
+
"accountId" TEXT NOT NULL,
|
|
6
|
+
"appKind" TEXT NOT NULL,
|
|
7
|
+
"appRef" TEXT NOT NULL,
|
|
8
|
+
"org" TEXT NOT NULL,
|
|
9
|
+
"crawlPage" INTEGER NOT NULL DEFAULT 0,
|
|
10
|
+
"crawlStartedAt" TIMESTAMP(3),
|
|
11
|
+
"completedAt" TIMESTAMP(3),
|
|
12
|
+
"totalCount" INTEGER,
|
|
13
|
+
"lastError" TEXT,
|
|
14
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
15
|
+
"nextAttemptAt" TIMESTAMP(3),
|
|
16
|
+
"rateLimitResetAt" TIMESTAMP(3),
|
|
17
|
+
"leaseHolder" TEXT,
|
|
18
|
+
"leasedUntil" TIMESTAMP(3),
|
|
19
|
+
"lastTickAt" TIMESTAMP(3),
|
|
20
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
21
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
22
|
+
|
|
23
|
+
CONSTRAINT "GitHubRepoSnapshot_pkey" PRIMARY KEY ("id")
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
-- CreateTable
|
|
27
|
+
CREATE TABLE "GitHubCachedRepo" (
|
|
28
|
+
"id" TEXT NOT NULL,
|
|
29
|
+
"snapshotId" TEXT NOT NULL,
|
|
30
|
+
"githubId" BIGINT NOT NULL,
|
|
31
|
+
"fullName" TEXT NOT NULL,
|
|
32
|
+
"archived" BOOLEAN NOT NULL DEFAULT false,
|
|
33
|
+
"seenAt" TIMESTAMP(3) NOT NULL,
|
|
34
|
+
|
|
35
|
+
CONSTRAINT "GitHubCachedRepo_pkey" PRIMARY KEY ("id")
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
-- CreateTable
|
|
39
|
+
CREATE TABLE "GitHubRepoAccess" (
|
|
40
|
+
"id" TEXT NOT NULL,
|
|
41
|
+
"accountId" TEXT NOT NULL,
|
|
42
|
+
"org" TEXT NOT NULL,
|
|
43
|
+
"repo" TEXT NOT NULL,
|
|
44
|
+
"username" TEXT NOT NULL,
|
|
45
|
+
"canPush" BOOLEAN NOT NULL DEFAULT false,
|
|
46
|
+
"level" TEXT,
|
|
47
|
+
"checkedAt" TIMESTAMP(3) NOT NULL,
|
|
48
|
+
"status" TEXT NOT NULL,
|
|
49
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
50
|
+
"nextAttemptAt" TIMESTAMP(3),
|
|
51
|
+
"lastError" TEXT,
|
|
52
|
+
|
|
53
|
+
CONSTRAINT "GitHubRepoAccess_pkey" PRIMARY KEY ("id")
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
-- CreateIndex
|
|
57
|
+
CREATE INDEX "GitHubRepoSnapshot_accountId_appKind_org_idx" ON "GitHubRepoSnapshot"("accountId", "appKind", "org");
|
|
58
|
+
|
|
59
|
+
-- CreateIndex
|
|
60
|
+
CREATE UNIQUE INDEX "GitHubRepoSnapshot_accountId_appKind_appRef_org_key" ON "GitHubRepoSnapshot"("accountId", "appKind", "appRef", "org");
|
|
61
|
+
|
|
62
|
+
-- CreateIndex
|
|
63
|
+
CREATE INDEX "GitHubCachedRepo_snapshotId_seenAt_idx" ON "GitHubCachedRepo"("snapshotId", "seenAt");
|
|
64
|
+
|
|
65
|
+
-- CreateIndex
|
|
66
|
+
CREATE UNIQUE INDEX "GitHubCachedRepo_snapshotId_githubId_key" ON "GitHubCachedRepo"("snapshotId", "githubId");
|
|
67
|
+
|
|
68
|
+
-- CreateIndex
|
|
69
|
+
CREATE INDEX "GitHubRepoAccess_accountId_org_username_nextAttemptAt_idx" ON "GitHubRepoAccess"("accountId", "org", "username", "nextAttemptAt");
|
|
70
|
+
|
|
71
|
+
-- CreateIndex
|
|
72
|
+
CREATE UNIQUE INDEX "GitHubRepoAccess_accountId_org_repo_username_key" ON "GitHubRepoAccess"("accountId", "org", "repo", "username");
|
|
73
|
+
|
|
74
|
+
-- AddForeignKey
|
|
75
|
+
ALTER TABLE "GitHubCachedRepo" ADD CONSTRAINT "GitHubCachedRepo_snapshotId_fkey" FOREIGN KEY ("snapshotId") REFERENCES "GitHubRepoSnapshot"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
@@ -744,3 +744,65 @@ model GitHubReconcileAudit {
|
|
|
744
744
|
|
|
745
745
|
@@index([agentId, createdAt])
|
|
746
746
|
}
|
|
747
|
+
|
|
748
|
+
// ─── GitHub repo/access cache (GLC-1.1) ──────────────────────────────────────
|
|
749
|
+
// Per-org crawl snapshot, the repos seen by it, and per-user push access.
|
|
750
|
+
// accountId/appRef are plain columns (no relations): cache rows are disposable.
|
|
751
|
+
// Debug detail (lastError, attempts, timestamps) is stored as plain columns so
|
|
752
|
+
// any existing view can show it.
|
|
753
|
+
|
|
754
|
+
model GitHubRepoSnapshot {
|
|
755
|
+
id String @id @default(cuid())
|
|
756
|
+
accountId String
|
|
757
|
+
appKind String // 'lookup' | 'agent'
|
|
758
|
+
appRef String // app id (lookup) or agent id (agent)
|
|
759
|
+
org String
|
|
760
|
+
crawlPage Int @default(0)
|
|
761
|
+
crawlStartedAt DateTime?
|
|
762
|
+
completedAt DateTime?
|
|
763
|
+
totalCount Int?
|
|
764
|
+
lastError String?
|
|
765
|
+
attempts Int @default(0)
|
|
766
|
+
nextAttemptAt DateTime?
|
|
767
|
+
rateLimitResetAt DateTime?
|
|
768
|
+
leaseHolder String?
|
|
769
|
+
leasedUntil DateTime?
|
|
770
|
+
lastTickAt DateTime?
|
|
771
|
+
createdAt DateTime @default(now())
|
|
772
|
+
updatedAt DateTime @updatedAt
|
|
773
|
+
repos GitHubCachedRepo[]
|
|
774
|
+
|
|
775
|
+
@@unique([accountId, appKind, appRef, org])
|
|
776
|
+
@@index([accountId, appKind, org])
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
model GitHubCachedRepo {
|
|
780
|
+
id String @id @default(cuid())
|
|
781
|
+
snapshotId String
|
|
782
|
+
snapshot GitHubRepoSnapshot @relation(fields: [snapshotId], references: [id], onDelete: Cascade)
|
|
783
|
+
githubId BigInt
|
|
784
|
+
fullName String
|
|
785
|
+
archived Boolean @default(false)
|
|
786
|
+
seenAt DateTime
|
|
787
|
+
|
|
788
|
+
@@unique([snapshotId, githubId])
|
|
789
|
+
@@index([snapshotId, seenAt])
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
model GitHubRepoAccess {
|
|
793
|
+
id String @id @default(cuid())
|
|
794
|
+
accountId String
|
|
795
|
+
org String
|
|
796
|
+
repo String
|
|
797
|
+
username String
|
|
798
|
+
canPush Boolean @default(false)
|
|
799
|
+
level String?
|
|
800
|
+
checkedAt DateTime
|
|
801
|
+
status String // 'ok' | 'error' | 'terminal'
|
|
802
|
+
attempts Int @default(0)
|
|
803
|
+
nextAttemptAt DateTime?
|
|
804
|
+
lastError String?
|
|
805
|
+
|
|
806
|
+
@@unique([accountId, org, repo, username])
|
|
807
|
+
@@index([accountId, org, username, nextAttemptAt])
|
|
808
|
+
}
|
|
@@ -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,296 @@
|
|
|
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
|
+
/**
|
|
172
|
+
* Delete repos last seen before the snapshot's crawlStartedAt. Returns the
|
|
173
|
+
* number deleted; 0 (and deletes nothing) when no crawl has started.
|
|
174
|
+
*/
|
|
175
|
+
async sweepGeneration(snapshotId: string): Promise<number> {
|
|
176
|
+
requireNonEmpty("snapshotId", snapshotId);
|
|
177
|
+
const snap = await this.prisma.gitHubRepoSnapshot.findUnique({
|
|
178
|
+
where: { id: snapshotId },
|
|
179
|
+
select: { crawlStartedAt: true },
|
|
180
|
+
});
|
|
181
|
+
if (!snap?.crawlStartedAt) return 0;
|
|
182
|
+
const { count } = await this.prisma.gitHubCachedRepo.deleteMany({
|
|
183
|
+
where: { snapshotId, seenAt: { lt: snap.crawlStartedAt } },
|
|
184
|
+
});
|
|
185
|
+
return count;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Take the org's lease for `ttlMs`. True when this holder now owns it; false
|
|
190
|
+
* when another holder's lease is still live or the snapshot does not exist.
|
|
191
|
+
*/
|
|
192
|
+
async acquireLease(
|
|
193
|
+
snapshotId: string,
|
|
194
|
+
holder: string,
|
|
195
|
+
ttlMs: number,
|
|
196
|
+
): Promise<boolean> {
|
|
197
|
+
requireNonEmpty("snapshotId", snapshotId);
|
|
198
|
+
requireNonEmpty("holder", holder);
|
|
199
|
+
validatePositiveMs("ttlMs", ttlMs);
|
|
200
|
+
const now = this.clock.now();
|
|
201
|
+
const { count } = await this.prisma.gitHubRepoSnapshot.updateMany({
|
|
202
|
+
where: {
|
|
203
|
+
id: snapshotId,
|
|
204
|
+
OR: [{ leasedUntil: null }, { leasedUntil: { lte: now } }],
|
|
205
|
+
},
|
|
206
|
+
data: {
|
|
207
|
+
leaseHolder: holder,
|
|
208
|
+
leasedUntil: new Date(now.getTime() + ttlMs),
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
return count === 1;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Release the lease if `holder` still owns it. Idempotent. */
|
|
215
|
+
async releaseLease(snapshotId: string, holder: string): Promise<void> {
|
|
216
|
+
requireNonEmpty("snapshotId", snapshotId);
|
|
217
|
+
requireNonEmpty("holder", holder);
|
|
218
|
+
await this.prisma.gitHubRepoSnapshot.updateMany({
|
|
219
|
+
where: { id: snapshotId, leaseHolder: holder },
|
|
220
|
+
data: { leaseHolder: null, leasedUntil: null },
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async upsertAccess(input: AccessInput) {
|
|
225
|
+
requireNonEmpty("accountId", input.accountId);
|
|
226
|
+
requireNonEmpty("org", input.org);
|
|
227
|
+
requireNonEmpty("repo", input.repo);
|
|
228
|
+
requireNonEmpty("username", input.username);
|
|
229
|
+
if (!(GITHUB_ACCESS_STATUSES as readonly string[]).includes(input.status)) {
|
|
230
|
+
throw new BadRequestError(
|
|
231
|
+
`status must be one of: ${GITHUB_ACCESS_STATUSES.join(", ")}`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
const data = {
|
|
235
|
+
canPush: input.canPush,
|
|
236
|
+
level: input.level ?? null,
|
|
237
|
+
checkedAt: this.clock.now(),
|
|
238
|
+
status: input.status,
|
|
239
|
+
attempts: input.attempts ?? 0,
|
|
240
|
+
nextAttemptAt: input.nextAttemptAt ?? null,
|
|
241
|
+
lastError: input.lastError ?? null,
|
|
242
|
+
};
|
|
243
|
+
return this.prisma.gitHubRepoAccess.upsert({
|
|
244
|
+
where: {
|
|
245
|
+
accountId_org_repo_username: {
|
|
246
|
+
accountId: input.accountId,
|
|
247
|
+
org: input.org,
|
|
248
|
+
repo: input.repo,
|
|
249
|
+
username: input.username,
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
create: {
|
|
253
|
+
accountId: input.accountId,
|
|
254
|
+
org: input.org,
|
|
255
|
+
repo: input.repo,
|
|
256
|
+
username: input.username,
|
|
257
|
+
...data,
|
|
258
|
+
},
|
|
259
|
+
update: data,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Repos in `query.repos` that still need an access check: no row yet, an ok
|
|
265
|
+
* row older than maxAgeMs, or an error row whose nextAttemptAt has passed.
|
|
266
|
+
* Terminal rows are never returned.
|
|
267
|
+
*/
|
|
268
|
+
async findMissingOrExpiredAccess(query: AccessQuery): Promise<string[]> {
|
|
269
|
+
requireNonEmpty("accountId", query.accountId);
|
|
270
|
+
requireNonEmpty("org", query.org);
|
|
271
|
+
requireNonEmpty("username", query.username);
|
|
272
|
+
validatePositiveMs("maxAgeMs", query.maxAgeMs);
|
|
273
|
+
if (query.repos.length === 0) return [];
|
|
274
|
+
const now = this.clock.now();
|
|
275
|
+
const rows = await this.prisma.gitHubRepoAccess.findMany({
|
|
276
|
+
where: {
|
|
277
|
+
accountId: query.accountId,
|
|
278
|
+
org: query.org,
|
|
279
|
+
username: query.username,
|
|
280
|
+
repo: { in: query.repos },
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
const staleBefore = now.getTime() - query.maxAgeMs;
|
|
284
|
+
const settled = new Set<string>();
|
|
285
|
+
for (const row of rows) {
|
|
286
|
+
const due =
|
|
287
|
+
row.status === "ok"
|
|
288
|
+
? row.checkedAt.getTime() < staleBefore
|
|
289
|
+
: row.status === "error"
|
|
290
|
+
? row.nextAttemptAt === null || row.nextAttemptAt <= now
|
|
291
|
+
: false;
|
|
292
|
+
if (!due) settled.add(row.repo);
|
|
293
|
+
}
|
|
294
|
+
return query.repos.filter((r) => !settled.has(r));
|
|
295
|
+
}
|
|
296
|
+
}
|