Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IssueService.test.ts

531 lines18.8 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
6import {
7 IssueTrackerKind,
8 type IssueTrackerProjectBinding,
9 SourceControlProviderKind,
10 type OrchestrationProjectShell,
11 type ProjectId,
12} from "@t3tools/contracts";
13import {
14 IssueTrackerError,
15 type IssueTrackerApi,
16 type StandaloneIssueTrackerApi,
17 type TrackerIssueDetail,
18} from "@t3tools/source-control-core/server/IssueTracker";
19​
20import { PersistenceSqlError } from "../persistence/Errors.ts";
21import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
22import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
23​
24import * as ProjectService from "../project/ProjectService.ts";
25import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
26import * as IssueService from "./IssueService.ts";
27import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
28​
29const GITHUB = IssueTrackerKind.make("github");
30const LINEAR = IssueTrackerKind.make("linear");
31​
32/** A standalone tracker shaped like Linear: its own host, team keys for scopes, `ENG-1` keys. */
33function fakeStandaloneTracker(
34 overrides: Partial<IssueTrackerApi> = {},
35): StandaloneIssueTrackerApi {
36 return {
37 ...fakeTracker({
38 getViewer: () => Effect.succeed("usr_julius"),
39 getIssue: (input) =>
40 Effect.succeed({ ...issue(input.key), displayKey: input.key, viewer: "usr_julius" }),
41 ...overrides,
42 }),
43 kind: LINEAR,
44 standalone: {
45 tracker: LINEAR,
46 displayName: "Linear",
47 host: "linear.app",
48 scopeNoun: "team",
49 credential: { label: "Personal API key", helpUrl: null },
50 },
51 probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }),
52 };
54​
55function project(input: {
56 readonly id: string;
57 readonly repository?: string;
58 readonly provider?: string;
59 readonly host?: string;
60}): OrchestrationProjectShell {
61 const host = input.host ?? "github.com";
62 return {
63 id: input.id as ProjectId,
64 title: input.id,
65 workspaceRoot: `/w/${input.id}`,
66 ...(input.repository
67 ? {
68 repositoryIdentity: {
69 canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
70 locator: {
71 source: "git-remote" as const,
72 remoteName: "origin",
73 remoteUrl: `https://${host}/${input.repository}.git`,
74 },
75 provider: SourceControlProviderKind.make(input.provider ?? "github"),
76 displayName: input.repository,
77 },
78 }
79 : {}),
80 defaultModelSelection: null,
81 scripts: [],
82 createdAt: "2026-07-01T00:00:00Z",
83 updatedAt: "2026-07-01T00:00:00Z",
84 };
86​
87function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
88 return {
89 key,
90 displayKey: `#${key}`,
91 title: `Issue ${key}`,
92 url: `https://github.com/acme/web/issues/${key}`,
93 author: null,
94 state: { category: "open", name: "open" },
95 createdAt: "2026-07-01T00:00:00Z",
96 updatedAt,
97 closedAt: null,
98 assignees: [],
99 labels: [],
100 commentCount: 0,
101 body: "",
102 viewer: "julius",
103 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
104 states: [],
105 comments: [],
106 commentsCursor: null,
107 events: [],
108 linkedPullRequests: [],
109 };
111​
112function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
113 return {
114 kind: GITHUB,
115 capabilities: {
116 create: true,
117 edit: true,
118 comment: true,
119 labels: true,
120 assignees: true,
121 reactions: false,
122 templates: false,
123 linkedPullRequests: true,
124 events: true,
125 search: true,
126 },
127 getViewer: () => Effect.succeed("julius"),
128 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
129 getIssue: (input) => Effect.succeed(issue(input.key)),
130 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
131 comment: () => Effect.void,
132 update: () => Effect.void,
133 setState: () => Effect.void,
134 ...overrides,
135 };
137​
138function makeService(input: {
139 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
140 readonly trackers: ReadonlyArray<IssueTrackerApi>;
141 readonly bindings?: Record<string, IssueTrackerProjectBinding>;
142 readonly bindingsFailure?: PersistenceSqlError;
143}) {
144 return IssueService.IssueService.pipe(
145 Effect.provide(
146 IssueService.layer.pipe(
147 Layer.provide(
148 Layer.mergeAll(
149 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
150 list:
151 input.bindingsFailure !== undefined
152 ? Effect.fail(input.bindingsFailure)
153 : Effect.succeed(
154 new Map(
155 Object.entries(input.bindings ?? {}).map(([id, binding]) => [
156 id as ProjectId,
157 binding,
158 ]),
159 ),
160 ),
161 }),
162 Layer.succeed(
163 IssueTrackerRegistry.IssueTrackerRegistry,
164 IssueTrackerRegistry.fromTrackers(input.trackers),
165 ),
166 Layer.mock(ProjectService.ProjectService)({
167 listShells: () => Effect.succeed(input.projects),
168 getShell: (projectId) =>
169 Effect.succeed(
170 Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
171 ),
172 }),
173 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
174 resolve: () => Effect.succeed(null),
175 }),
176 ),
177 ),
178 ),
179 ),
180 );
182​
183describe("IssueService", () => {
184 it.effect("places a project where its host keeps its issues", () =>
185 Effect.gen(function* () {
186 const azure = IssueTrackerKind.make("azure-devops");
187 const service = yield* makeService({
188 projects: [
189 project({
190 id: "p",
191 provider: "azure-devops",
192 host: "dev.azure.com",
193 repository: "acme/Web App/_git/web",
194 }),
195 ],
196 trackers: [fakeTracker({ kind: azure })],
197 });
198 expect(yield* service.projectScope("p" as ProjectId)).toEqual({
199 projectId: "p",
200 tracker: "azure-devops",
201 host: "dev.azure.com",
202 scope: "acme/Web App",
203 });
204 }),
205 );
206​
207 it.effect("reads another repository on the same host but refuses to write to it", () =>
208 Effect.gen(function* () {
209 const writes: string[] = [];
210 const service = yield* makeService({
211 projects: [project({ id: "web", repository: "acme/web" })],
212 trackers: [
213 fakeTracker({
214 comment: (input) =>
215 Effect.sync(() => {
216 writes.push(`${input.scope}#${input.key}`);
217 }),
218 }),
219 ],
220 });
221 const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
222 const external = { ...own, scope: "other/backend", key: "7" };
223​
224 expect((yield* service.detail(own)).writable).toBe(true);
225 // The external issue is served by the project's checkout and credentials, read-only.
226 const detail = yield* service.detail(external);
227 expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
228​
229 yield* service.comment({ ...own, body: "ok" });
230 const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
231 expect(refused).toMatchObject({
232 _tag: "Failure",
233 failure: { _tag: "IssueOperationError", reason: "read-only" },
234 });
235 expect(writes).toEqual(["acme/web#1"]);
236​
237 // A link's port picks the server: the project bound with it, not a default-port namesake.
238 const ported = yield* makeService({
239 projects: [
240 project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
241 project({
242 id: "ported",
243 repository: "acme/web",
244 provider: "forgejo",
245 host: "gitea.test:8443",
246 }),
247 ],
248 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
249 });
250 expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
251 projectId: "ported",
252 host: "gitea.test:8443",
253 key: "3",
254 writable: true,
255 });
256 expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
257 projectId: "plain",
258 host: "gitea.test",
259 });
260​
261 // Another host is not reachable through this project's credentials at all.
262 const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
263 expect(elsewhere).toMatchObject({
264 _tag: "IssueUnavailableError",
265 reason: "tracker-unsupported",
266 });
267 }),
268 );
269​
270 it.effect("sends writes as interactive requests and reads as background ones", () =>
271 Effect.gen(function* () {
272 const interactive: Array<readonly [string, boolean]> = [];
273 const record = (operation: string) =>
274 Effect.gen(function* () {
275 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
276 });
277 const service = yield* makeService({
278 projects: [project({ id: "web", repository: "acme/web" })],
279 trackers: [
280 fakeTracker({
281 getComments: () =>
282 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
283 comment: () => record("comment"),
284 }),
285 ],
286 });
287 const ref = {
288 projectId: "web" as ProjectId,
289 tracker: GITHUB,
290 scope: "acme/web",
291 key: "42",
292 };
293 yield* service.comments({ ...ref, cursor: "next" });
294 yield* service.comment({ ...ref, body: "Repro attached." });
295 expect(interactive).toEqual([
296 ["comments", false],
297 ["comment", true],
298 ]);
299 }),
300 );
301​
302 it.effect("refuses what the tracker did not declare before calling it", () =>
303 Effect.gen(function* () {
304 let calls = 0;
305 const service = yield* makeService({
306 projects: [project({ id: "web", repository: "acme/web" })],
307 trackers: [
308 fakeTracker({
309 setState: () =>
310 Effect.sync(() => {
311 calls += 1;
312 }),
313 setReaction: () =>
314 Effect.sync(() => {
315 calls += 1;
316 }),
317 }),
318 ],
319 });
320 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
321​
322 // The state is the tracker's own name, passed through: the tracker is what proves it.
323 yield* service.setState({ ...ref, state: "In Review" });
324 const reaction = yield* Effect.flip(
325 service.react({ ...ref, content: "heart", reacted: true }),
326 );
327 expect(reaction._tag).toBe("IssueOperationError");
328 expect(calls).toBe(1);
329 }),
330 );
331​
332 it.effect("deduplicates and pages repositories despite partial failures", () =>
333 Effect.gen(function* () {
334 const listed: string[] = [];
335 let failContinuation = true;
336 const service = yield* makeService({
337 projects: [
338 project({ id: "web", repository: "Acme/Web" }),
339 project({ id: "web-worktree", repository: "acme/web" }),
340 project({ id: "api", repository: "acme/api" }),
341 project({ id: "docs", repository: "acme/docs" }),
342 project({
343 id: "gitlab",
344 repository: "acme/gl",
345 provider: "gitlab",
346 host: "gitlab.com",
347 }),
348 project({ id: "plain" }),
349 ],
350 trackers: [
351 fakeTracker({
352 listIssues: (input) =>
353 Effect.gen(function* () {
354 listed.push(input.scope);
355 if (input.scope === "acme/api")
356 return yield* new IssueTrackerError({
357 tracker: GITHUB,
358 operation: "listIssues",
359 reason: "failed",
360 // A tracker may fail without a detail; the wire error still needs one.
361 detail: " ",
362 });
363 if (input.scope === "acme/docs")
364 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
365 if (input.cursor === "next" && failContinuation) {
366 failContinuation = false;
367 return yield* new IssueTrackerError({
368 tracker: GITHUB,
369 operation: "listIssues",
370 reason: "failed",
371 detail: "try again",
372 });
373 }
374 if (input.cursor === "next")
375 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
376 return {
377 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
378 nextCursor: "next",
379 };
380 }),
381 }),
382 ],
383 });
384 const result = yield* service.list({ state: "open" });
385 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
386 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
387 ["web", "2"],
388 ["docs", "3"],
389 ["web", "1"],
390 ]);
391 expect(
392 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
393 ).toEqual(["Acme/Web", "Acme/Web"]);
394 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
395 expect(result.errors).toEqual([
396 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
397 ]);
398 expect(result.viewers).toEqual({ "github.com": "julius" });
399 expect(result.trackers).toEqual([
400 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
401 expect.objectContaining({
402 host: "gitlab.com",
403 tracker: "gitlab",
404 projectCount: 1,
405 configured: false,
406 capabilities: null,
407 }),
408 ]);
409​
410 // A continuation only reads the scopes it names.
411 listed.length = 0;
412 const failed = yield* service.list({
413 state: "open",
414 cursors: result.nextCursors,
415 });
416 expect(listed).toEqual(["Acme/Web"]);
417 expect(failed.nextCursors).toEqual(result.nextCursors);
418 expect(failed.errors).toEqual([
419 { projectId: "web", projectTitle: "web", message: "try again" },
420 ]);
421 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
422 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
423 expect(next.nextCursors).toEqual({});
424 expect(next.errors).toEqual([]);
425​
426 // The cursor belongs to the scope, not to the project whose spelling first read it.
427 listed.length = 0;
428 const through = yield* service.list({
429 state: "open",
430 projectId: "web-worktree" as ProjectId,
431 cursors: result.nextCursors,
432 });
433 expect(listed).toEqual(["acme/web"]);
434 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
435 }),
436 );
437});
438​
439describe("IssueService with a standalone tracker", () => {
440 it.effect("lists a bound project's standalone scope beside its git host and serves both", () =>
441 Effect.gen(function* () {
442 const listed: string[] = [];
443 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
444 listIssues: (input) =>
445 Effect.sync(() => {
446 listed.push(`${tracker} ${input.host} ${input.scope}`);
447 return { items: [issue(tracker === LINEAR ? "ENG-1" : "1")], nextCursor: null };
448 }),
449 });
450 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
451 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
452 const bound = yield* makeService({
453 projects,
454 trackers,
455 bindings: { ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG" } },
456 });
457​
458 const result = yield* bound.list({ state: "open" });
459 expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]);
460 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
461 [
462 ["github", "acme/web", "1"],
463 ["linear", "ENG", "ENG-1"],
464 ],
465 );
466 expect(result.trackers.map((tracker) => [tracker.tracker, tracker.host]).sort()).toEqual([
467 ["github", "github.com"],
468 ["linear", "linear.app"],
469 ]);
470 expect(result.scopes).toContainEqual({
471 projectId: "web",
472 tracker: "linear",
473 host: "linear.app",
474 scope: "ENG",
475 });
476 // A reference picks the project's tracker by kind; both are the project's own, so writable.
477 const linearRef = {
478 projectId: "web" as ProjectId,
479 tracker: LINEAR,
480 scope: "ENG",
481 key: "ENG-1",
482 };
483 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
484 expect(
485 yield* bound.detail({
486 projectId: "web" as ProjectId,
487 tracker: GITHUB,
488 scope: "acme/web",
489 key: "1",
490 }),
491 ).toMatchObject({ host: "github.com", writable: true });
492​
493 // Unbound, the standalone scope is gone and its references are unsupported.
494 listed.length = 0;
495 const unbound = yield* makeService({ projects, trackers });
496 const after = yield* unbound.list({ state: "open" });
497 expect(listed).toEqual(["github github.com acme/web"]);
498 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
499 const refused = yield* Effect.flip(unbound.detail(linearRef));
500 expect(refused).toMatchObject({
501 _tag: "IssueUnavailableError",
502 reason: "tracker-unsupported",
503 });
504​
505 // A project with no remote at all can still be bound, and then has only the standalone one.
506 const standaloneOnly = yield* makeService({
507 projects,
508 trackers,
509 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
510 });
511 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
512 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
513 ["notes", "OPS"],
514 ]);
515​
516 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
517 const unreadable = yield* makeService({
518 projects,
519 trackers,
520 bindingsFailure: new PersistenceSqlError({
521 operation: "IssueTrackerBindingsRepository.list",
522 detail: "disk I/O error",
523 }),
524 });
525 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
526 _tag: "IssueOperationError",
527 operation: "listProjects",
528 });
529 }),
530 );
531});