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

IssueService.test.ts

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