Open History to see the last commit
1import {
2 PullRequestListInput,
3 SourceControlProviderKind,
4 type EnvironmentId,
5 type ProjectId,
6 type PullRequestProviderSummary,
7} from "@t3tools/contracts";
8import * as Schema from "effect/Schema";
9import { describe, expect, it } from "vite-plus/test";
10
11import {
12 assignProjectsToEnvironments,
13 rememberPullRequestHosts,
14 resetPullRequestHosts,
15 pullRequestProjectQueries,
16 resolvePickableEnvironments,
17 type AssignableProject,
18} from "./pullRequestProjectAssignment.logic";
19
20const project = (
21 id: string,
22 environmentId: string,
23 canonicalKey?: string,
24): AssignableProject & { workspaceRoot: string } => ({
25 id: id as ProjectId,
26 environmentId: environmentId as EnvironmentId,
27 repositoryIdentity: canonicalKey === undefined ? null : { canonicalKey },
28 workspaceRoot: `/srv/${environmentId}/${id}`,
29});
30
31const envs = (...ids: ReadonlyArray<string>) => ids as ReadonlyArray<EnvironmentId>;
32
33const plain = (assignment: Map<EnvironmentId, ProjectId[]>) =>
34 Object.fromEntries([...assignment].map(([id, projectIds]) => [id, projectIds]));
35const decodeListInput = Schema.decodeSync(PullRequestListInput);
36
37const hostAvailability = (hosts: ReadonlyMap<string, boolean>) => ({
38 hosts: new Map([...hosts].map(([host, configured]) => [host, { configured, observedAt: 0 }])),
39 projectHosts: new Map<ProjectId, { host: string; observedAt: number }>(),
40});
41
42const provider = (host: string, configured: boolean): PullRequestProviderSummary => ({
43 host,
44 kind: "bitbucket" as PullRequestProviderSummary["kind"],
45 searchesOnHost: false,
46 projectCount: 1,
47 configured,
48 detail: configured ? null : "Credentials rejected",
49});
50
51describe("host read results", () => {
52 const environmentId = "env-1" as EnvironmentId;
53
54 it("remembers a failed host after the assignment stops requesting it", () => {
55 const failed = rememberPullRequestHosts(new Map(), [
56 [environmentId, { providers: [provider("BITBUCKET.org", false)] }, 100],
57 ]);
58 const next = rememberPullRequestHosts(failed, [
59 [environmentId, { providers: [provider("github.com", true)] }, 200],
60 ]);
61 expect(
62 [...next.get(environmentId)!.hosts].map(([host, read]) => [host, read.configured]),
63 ).toEqual([
64 ["bitbucket.org", false],
65 ["github.com", true],
66 ]);
67 expect(
68 [...failed.get(environmentId)!.hosts].map(([host, read]) => [host, read.configured]),
69 ).toEqual([["bitbucket.org", false]]);
70 });
71
72 it("does not replay cached failures after refresh clears availability", () => {
73 const cleared = new Map([
74 [
75 environmentId,
76 { observedAt: 100, resetAt: 100, ...hostAvailability(new Map<string, boolean>()) },
77 ],
78 ]);
79 expect(
80 rememberPullRequestHosts(cleared, [
81 [environmentId, { providers: [provider("bitbucket.org", false)] }, 100],
82 ]),
83 ).toBe(cleared);
84 const refreshed = rememberPullRequestHosts(cleared, [
85 [environmentId, { providers: [provider("bitbucket.org", true)] }, 200],
86 ]);
87 expect(refreshed.get(environmentId)!.hosts.get("bitbucket.org")?.configured).toBe(true);
88 });
89
90 it("ignores an older answer when a newer read has already succeeded", () => {
91 const readable = rememberPullRequestHosts(new Map(), [
92 [environmentId, { providers: [provider("bitbucket.org", true)] }, 200],
93 ]);
94 expect(
95 rememberPullRequestHosts(readable, [
96 [environmentId, { providers: [provider("bitbucket.org", false)] }, 100],
97 ]),
98 ).toBe(readable);
99 });
100
101 it.each([false, true])(
102 "treats a host as readable when any active batch succeeds (reversed: %s)",
103 (reverse) => {
104 const observations = [
105 [environmentId, { providers: [provider("gitlab.example", true)] }, 100],
106 [environmentId, { providers: [provider("gitlab.example", false)] }, 200],
107 ] as const;
108 const next = rememberPullRequestHosts(
109 new Map(),
110 reverse ? observations.toReversed() : observations,
111 );
112 expect(next.get(environmentId)!.hosts.get("gitlab.example")).toEqual({
113 configured: true,
114 observedAt: 200,
115 });
116 expect(next.get(environmentId)!.observedAt).toBe(200);
117 const cleared = resetPullRequestHosts(next);
118 expect(rememberPullRequestHosts(cleared, observations)).toBe(cleared);
119 const failed = rememberPullRequestHosts(next, [
120 [environmentId, { providers: [provider("gitlab.example", false)] }, 300],
121 ]);
122 expect(failed.get(environmentId)!.hosts.get("gitlab.example")?.configured).toBe(false);
123 },
124 );
125});
126
127describe("assignment query limits", () => {
128 it("splits the healthy remainder after fallback into valid project filters", () => {
129 const healthy = Array.from({ length: 101 }, (_, index) =>
130 project(`healthy-${index}`, "env-1", `github.com/acme/repo-${index}`),
131 );
132 const projects = [
133 project("shared", "env-1", "bitbucket.org/acme/app"),
134 ...healthy,
135 project("copy", "env-2", "bitbucket.org/acme/app"),
136 ];
137 const queries = pullRequestProjectQueries(
138 projects,
139 envs("env-1", "env-2"),
140 new Map([["env-1" as EnvironmentId, hostAvailability(new Map([["bitbucket.org", false]]))]]),
141 );
142 expect(
143 queries.map(({ environmentId, projectIds }) => [environmentId, projectIds?.length]),
144 ).toEqual([
145 ["env-1", 100],
146 ["env-1", 1],
147 ["env-2", undefined],
148 ]);
149 expect(
150 queries
151 .filter(({ environmentId }) => environmentId === "env-1")
152 .flatMap(({ projectIds }) => projectIds ?? []),
153 ).toEqual(healthy.map(({ id }) => id));
154 for (const { projectIds } of queries)
155 expect(() =>
156 decodeListInput({
157 state: "open",
158 ...(projectIds === undefined ? {} : { projectIds }),
159 }),
160 ).not.toThrow();
161 });
162});
163
164describe("one server per repository", () => {
165 it("lets the first server list a repository both hold", () => {
166 const assignment = assignProjectsToEnvironments(
167 [
168 project("a1", "env-1", "github.com/acme/app"),
169 project("b1", "env-1", "github.com/acme/tools"),
170 project("a2", "env-2", "github.com/acme/app"),
171 project("c2", "env-2", "github.com/acme/site"),
172 ],
173 envs("env-1", "env-2"),
174 "env-1" as EnvironmentId,
175 );
176 expect(plain(assignment)).toEqual({ "env-1": ["a1", "b1"], "env-2": ["c2"] });
177 });
178
179 it("prefers the named server over the first one", () => {
180 const assignment = assignProjectsToEnvironments(
181 [
182 project("a1", "env-1", "github.com/acme/app"),
183 project("a2", "env-2", "github.com/acme/app"),
184 ],
185 envs("env-1", "env-2"),
186 "env-2" as EnvironmentId,
187 );
188 expect(plain(assignment)).toEqual({ "env-2": ["a2"] });
189 });
190
191 it("falls back from an unreadable host without moving other repositories", () => {
192 const assignment = assignProjectsToEnvironments(
193 [
194 project("a1", "env-1", "bitbucket.org/acme/app"),
195 project("b1", "env-1", "github.com/acme/tools"),
196 project("a2", "env-2", "bitbucket.org/acme/app"),
197 project("b2", "env-2", "github.com/acme/tools"),
198 ],
199 envs("env-1", "env-2"),
200 "env-1" as EnvironmentId,
201 new Map([["env-1" as EnvironmentId, hostAvailability(new Map([["bitbucket.org", false]]))]]),
202 );
203 expect(plain(assignment)).toEqual({ "env-1": ["b1"], "env-2": ["a2"] });
204 });
205
206 it("keeps one stable owner and its error when every copy is unreadable", () => {
207 const projects = [
208 project("a1", "env-1", "bitbucket.org/acme/app"),
209 project("a2", "env-2", "bitbucket.org/acme/app"),
210 project("only1", "env-1", "bitbucket.org/acme/only"),
211 ];
212 const availability = new Map(
213 envs("env-1", "env-2").map((id) => [
214 id,
215 hostAvailability(new Map([["bitbucket.org", false]])),
216 ]),
217 );
218 expect(
219 plain(
220 assignProjectsToEnvironments(
221 projects,
222 envs("env-1", "env-2"),
223 "env-1" as EnvironmentId,
224 availability,
225 ),
226 ),
227 ).toEqual({ "env-1": ["a1", "only1"] });
228 expect(
229 plain(
230 assignProjectsToEnvironments(
231 projects,
232 envs("env-2"),
233 "env-2" as EnvironmentId,
234 availability,
235 ),
236 ),
237 ).toEqual({ "env-2": ["a2"] });
238 });
239
240 it("checks the owner's HTTP authority using its own identity in either project order", () => {
241 const projects = [
242 {
243 ...project("a1", "env-1", "forge.example/team/repo"),
244 repositoryIdentity: {
245 canonicalKey: "forge.example/team/repo",
246 provider: SourceControlProviderKind.make("forgejo"),
247 locator: {
248 source: "git-remote",
249 remoteName: "origin",
250 remoteUrl: "https://forge.example:3000/team/repo.git",
251 },
252 },
253 },
254 {
255 ...project("a2", "env-2", "forge.example/team/repo"),
256 repositoryIdentity: {
257 canonicalKey: "forge.example/team/repo",
258 provider: SourceControlProviderKind.make("forgejo"),
259 locator: {
260 source: "git-remote",
261 remoteName: "origin",
262 remoteUrl: "git@forge.example:team/repo.git",
263 },
264 },
265 },
266 ] as const;
267 const availability = new Map([
268 ["env-1" as EnvironmentId, hostAvailability(new Map([["forge.example:3000", false]]))],
269 ]);
270 for (const copies of [projects, projects.toReversed()]) {
271 expect(
272 plain(
273 assignProjectsToEnvironments(
274 copies,
275 envs("env-1", "env-2"),
276 "env-1" as EnvironmentId,
277 availability,
278 ),
279 ),
280 ).toEqual({ "env-2": ["a2"] });
281 }
282 });
283
284 it("uses a server-resolved host for SSH without conflating ports on that host", () => {
285 const projects = envs("env-1", "env-2").map((environmentId) => ({
286 ...project(`a-${environmentId}`, environmentId, "ssh.forge.example/team/repo"),
287 repositoryIdentity: {
288 canonicalKey: "ssh.forge.example/team/repo",
289 provider: SourceControlProviderKind.make("forgejo"),
290 locator: {
291 source: "git-remote" as const,
292 remoteName: "origin",
293 remoteUrl: "ssh://git@ssh.forge.example:2222/team/repo.git",
294 },
295 },
296 }));
297 const availability = rememberPullRequestHosts(new Map(), [
298 [
299 "env-1" as EnvironmentId,
300 {
301 providers: [
302 { ...provider("forge.example:3000", false), projectIds: ["a-env-1" as ProjectId] },
303 { ...provider("forge.example:4000", true), projectIds: ["unrelated" as ProjectId] },
304 ],
305 },
306 100,
307 ],
308 ]);
309 for (const copies of [projects, projects.toReversed()]) {
310 expect(
311 plain(
312 assignProjectsToEnvironments(
313 copies,
314 envs("env-1", "env-2"),
315 "env-1" as EnvironmentId,
316 availability,
317 ),
318 ),
319 ).toEqual({ "env-2": ["a-env-2"] });
320 }
321 });
322
323 it("keeps every copy of a project that has no identity to compare", () => {
324 const assignment = assignProjectsToEnvironments(
325 [project("p1", "env-1"), project("p2", "env-2")],
326 envs("env-1", "env-2"),
327 "env-1" as EnvironmentId,
328 );
329 expect(plain(assignment)).toEqual({ "env-1": ["p1"], "env-2": ["p2"] });
330 });
331
332 it("keeps a server's own worktrees of the repository it lists", () => {
333 const assignment = assignProjectsToEnvironments(
334 [
335 project("a1", "env-1", "github.com/acme/app"),
336 project("a1-wt", "env-1", "GitHub.com/acme/app"),
337 project("a2", "env-2", "github.com/acme/app"),
338 ],
339 envs("env-1", "env-2"),
340 "env-1" as EnvironmentId,
341 );
342 expect(plain(assignment)).toEqual({ "env-1": ["a1", "a1-wt"] });
343 });
344
345 it("reads two servers' copies of one repository as one however the remote is cased", () => {
346 const assignment = assignProjectsToEnvironments(
347 [
348 project("a1", "env-1", "git.example.com/Team/App"),
349 project("a2", "env-2", "GIT.example.com/team/app"),
350 ],
351 envs("env-1", "env-2"),
352 "env-1" as EnvironmentId,
353 );
354 expect(plain(assignment)).toEqual({ "env-1": ["a1"] });
355 });
356
357 it("answers the same whatever order the projects arrive in", () => {
358 const projects = [
359 project("a2", "env-2", "github.com/acme/app"),
360 project("a1", "env-1", "github.com/acme/app"),
361 ];
362 const forward = assignProjectsToEnvironments(projects, envs("env-1", "env-2"), null);
363 const backward = assignProjectsToEnvironments(
364 projects.toReversed(),
365 envs("env-1", "env-2"),
366 null,
367 );
368 expect(plain(forward)).toEqual({ "env-1": ["a1"] });
369 expect(plain(backward)).toEqual(plain(forward));
370 });
371});
372
373const connected = (...ids: ReadonlyArray<string>) =>
374 ids.map((id) => ({ environmentId: id as EnvironmentId, label: `Server ${id}` }));
375
376const on = (environmentId: string, projectId: string) => ({
377 environmentId: environmentId as EnvironmentId,
378 projectId: projectId as ProjectId,
379});
380
381describe("where a pull request can be acted on", () => {
382 it("offers every server holding the repository, the panel's own first", () => {
383 const pickable = resolvePickableEnvironments(
384 on("env-2", "a2"),
385 [
386 project("a1", "env-1", "github.com/acme/app"),
387 project("a2", "env-2", "github.com/acme/app"),
388 project("c3", "env-3", "github.com/acme/site"),
389 ],
390 connected("env-1", "env-2", "env-3"),
391 );
392 expect(pickable).toEqual([
393 {
394 environmentId: "env-2",
395 projectId: "a2",
396 workspaceRoot: "/srv/env-2/a2",
397 label: "Server env-2",
398 },
399 {
400 environmentId: "env-1",
401 projectId: "a1",
402 workspaceRoot: "/srv/env-1/a1",
403 label: "Server env-1",
404 },
405 ]);
406 });
407
408 it("names one copy per server, so two worktrees are one choice", () => {
409 const pickable = resolvePickableEnvironments(
410 on("env-1", "a1"),
411 [
412 project("a1", "env-1", "github.com/acme/app"),
413 project("a1-wt", "env-1", "github.com/acme/app"),
414 project("a2", "env-2", "github.com/acme/app"),
415 project("a2-wt", "env-2", "github.com/acme/app"),
416 ],
417 connected("env-1", "env-2"),
418 );
419 expect(pickable.map((entry) => entry.projectId)).toEqual(["a1", "a2"]);
420 });
421
422 it("keeps the panel's own worktree rather than the server's first copy", () => {
423 const pickable = resolvePickableEnvironments(
424 on("env-1", "a1-wt"),
425 [
426 project("a1", "env-1", "github.com/acme/app"),
427 project("a1-wt", "env-1", "github.com/acme/app"),
428 project("a2", "env-2", "github.com/acme/app"),
429 ],
430 connected("env-1", "env-2"),
431 );
432 expect(pickable[0]).toEqual({
433 environmentId: "env-1",
434 projectId: "a1-wt",
435 workspaceRoot: "/srv/env-1/a1-wt",
436 label: "Server env-1",
437 });
438 });
439});