Open History to see the last commit
1// A project bound to a standalone tracker (Linear) in settings lists it beside its git host's.
2// References outside the project's own repositories (upstream and fork) may be read on the host,
3// but every write must pass through requireWritable.
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import {
9 IssueOperationError,
10 IssueTrackerKind,
11 IssueUnavailableError,
12 type IssueTrackerAccountId,
13 SourceControlProviderKind,
14 type IssueCandidates,
15 type IssueCommentInput,
16 type IssueCommentsPage,
17 type IssueCommentsPageInput,
18 type IssueCreateInput,
19 type IssueCreateResult,
20 type IssueDetail,
21 type IssueError,
22 type IssueListEntry,
23 type IssueListInput,
24 type IssueListProjectError,
25 type IssueListResult,
26 type IssueReactionInput,
27 type IssueRef,
28 type IssueScopeRef,
29 type IssueSetStateInput,
30 type IssueTemplateList,
31 type IssueTrackerSummary,
32 type IssueTrackerProjectBinding,
33 issueTrackerBindingScopes,
34 type IssueUpdateInput,
35 type OrchestrationProjectShell,
36 type ProjectId,
37} from "@t3tools/contracts";
38import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
39import {
40 IssueTrackerError,
41 isStandaloneIssueTracker,
42 type IssueInvolvementFilter,
43 type IssueTrackerApi,
44 type StandaloneIssueTrackerApi,
45 type TrackerIssueDetail,
46 type TrackerIssueLink,
47} from "@t3tools/source-control-core/server/IssueTracker";
48import { asIssueTrackerAccount } from "@t3tools/source-control-core/server/IssueTrackerHost";
49import { parseUrl } from "@t3tools/shared/url";
50
51import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
52import * as ProjectService from "../project/ProjectService.ts";
53import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
54import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
55import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
56
57const DEFAULT_LIST_LIMIT = 50;
58const SCOPE_CONCURRENCY = 4;
59
60const interactive =
61 <I, A>(call: (input: I) => Effect.Effect<A, IssueError>) =>
62 (input: I) =>
63 call(input).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
64
65const traced =
66 <I, A>(operation: string, call: (input: I) => Effect.Effect<A, IssueError>) =>
67 (input: I) =>
68 call(input).pipe(Effect.withSpan(`IssueService.${operation}`));
69
70/** A tracker may fail with no detail; the wire errors carry a non-empty one. */
71export function trackerDetail(error: IssueTrackerError): string {
72 return error.detail.trim() || "The issue tracker request failed.";
73}
74
75/** One project's resolved tracker: which driver, where it is served from, and its container. */
76interface ProjectTrackerBinding {
77 readonly tracker: IssueTrackerKind;
78 readonly host: string;
79 readonly scope: string;
80 /** The standalone tracker account the scope is read with; null for git hosts and first accounts. */
81 readonly accountId: IssueTrackerAccountId | null;
82}
83
84/** A project the registry has a tracker for, ready to serve reads and writes. */
85interface SupportedProject extends ProjectTrackerBinding {
86 readonly project: OrchestrationProjectShell;
87 readonly api: IssueTrackerApi;
88}
89
90/**
91 * The git-host path of resolution: the tracker is the host's own, named like the remote's
92 * provider kind. A fork reads its upstream and its own repository.
93 */
94function resolveGitHostBindings(
95 project: OrchestrationProjectShell,
96): ReadonlyArray<ProjectTrackerBinding> {
97 return sourceControlDefinitions.issueBindings(project.repositoryIdentity).map((binding) => ({
98 ...binding,
99 tracker: IssueTrackerKind.make(binding.tracker),
100 accountId: null,
101 }));
102}
103
104function findStandaloneIssueUrl(trackers: ReadonlyArray<StandaloneIssueTrackerApi>, value: string) {
105 const url = parseUrl(value);
106 if (url === null) return null;
107 for (const api of trackers) {
108 const link = api.parseIssueUrl(url);
109 if (link !== null) return { api, tracker: api.kind, link };
110 }
111 return null;
112}
113
114/** Lower case, so a scope keeps its cursor whichever project's spelling is read. Clients group by the leading host. */
115function listCursorKey(project: ProjectTrackerBinding): string {
116 const scope = project.scope.toLowerCase();
117 return project.accountId === null
118 ? `${project.host} ${scope}`
119 : `${project.host} ${project.accountId}/${scope}`;
120}
121
122function viewerKey(project: ProjectTrackerBinding): string {
123 return project.accountId === null ? project.host : `${project.host} ${project.accountId}`;
124}
125
126function isTrackerUnusable(error: IssueTrackerError): boolean {
127 return error.reason === "missing-tool" || error.reason === "unauthenticated";
128}
129
130function toIssueError(operation: string): (error: IssueTrackerError) => IssueError {
131 return (error) =>
132 isTrackerUnusable(error)
133 ? new IssueUnavailableError({
134 reason: error.reason === "missing-tool" ? "tool-missing" : "unauthenticated",
135 tracker: error.tracker,
136 cause: error,
137 })
138 : new IssueOperationError({
139 operation,
140 detail: trackerDetail(error),
141 ...(error.reason === "not-found" || error.reason === "rate-limited"
142 ? { reason: error.reason }
143 : {}),
144 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
145 cause: error,
146 });
147}
148
149const isNotFound = (error: IssueError) =>
150 error._tag === "IssueOperationError" && error.reason === "not-found";
151
152const readOnly = (operation: string) =>
153 new IssueOperationError({
154 operation,
155 reason: "read-only",
156 detail:
157 "This issue belongs to a repository outside the selected project and cannot be changed from here.",
158 });
159
160const unsupported = (operation: string, what: string) =>
161 new IssueOperationError({ operation, detail: `This tracker does not support ${what}.` });
162
163export class IssueService extends Context.Service<
164 IssueService,
165 {
166 readonly list: (input: IssueListInput) => Effect.Effect<IssueListResult, IssueError>;
167 readonly detail: (input: IssueRef) => Effect.Effect<IssueDetail, IssueError>;
168 readonly linkMetadata: (input: IssueRef) => Effect.Effect<TrackerIssueLink, IssueError>;
169 readonly comments: (
170 input: IssueCommentsPageInput,
171 ) => Effect.Effect<IssueCommentsPage, IssueError>;
172 readonly templates: (input: IssueScopeRef) => Effect.Effect<IssueTemplateList, IssueError>;
173 readonly candidates: (input: IssueScopeRef) => Effect.Effect<IssueCandidates, IssueError>;
174 readonly create: (input: IssueCreateInput) => Effect.Effect<IssueCreateResult, IssueError>;
175 readonly comment: (input: IssueCommentInput) => Effect.Effect<void, IssueError>;
176 readonly update: (input: IssueUpdateInput) => Effect.Effect<void, IssueError>;
177 readonly setState: (input: IssueSetStateInput) => Effect.Effect<void, IssueError>;
178 readonly react: (input: IssueReactionInput) => Effect.Effect<void, IssueError>;
179 /**
180 * The tracker and container a project's own issues live in: the bound `scope` when named, else
181 * the one `key`'s prefix names, else the project's default.
182 */
183 readonly projectScope: (
184 projectId: ProjectId,
185 select?: { readonly key?: string | undefined; readonly scope?: string | undefined },
186 ) => Effect.Effect<IssueScopeRef & { readonly host: string }, IssueError>;
187 /**
188 * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only.
189 * Standalone links must match the workspace in the issue's canonical URL from the connected
190 * tracker; that read comes back as `issue`, so callers need not read it again.
191 */
192 readonly resolveUrl: (
193 url: string,
194 preferredProjectId?: ProjectId,
195 ) => Effect.Effect<
196 IssueRef & {
197 readonly host: string;
198 readonly writable: boolean;
199 readonly issue?: IssueDetail;
200 },
201 IssueError
202 >;
203 }
204>()("t3/issue/IssueService") {}
205
206const make = Effect.gen(function* () {
207 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
208 const projects = yield* ProjectService.ProjectService;
209 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
210 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
211
212 const resolveStandaloneBindings = (
213 binding: IssueTrackerProjectBinding | undefined,
214 ): ReadonlyArray<ProjectTrackerBinding> => {
215 if (binding === undefined) return [];
216 const api = registry.get(binding.tracker);
217 if (api === null || !isStandaloneIssueTracker(api)) return [];
218 const host = api.standalone.host;
219 const accountId = binding.accountId ?? null;
220 return issueTrackerBindingScopes(binding).map((scope) => ({
221 tracker: binding.tracker,
222 host,
223 scope,
224 accountId,
225 }));
226 };
227
228 /**
229 * Where a project's issues live: its bound standalone tracker, its git host's, or both. The
230 * tracker bound in Settings leads, as the one the user chose for the project.
231 */
232 const resolveProjectTracker = (
233 project: OrchestrationProjectShell,
234 binding: IssueTrackerProjectBinding | undefined,
235 ) =>
236 (project.repositoryIdentity != null
237 ? Effect.succeed(project.repositoryIdentity)
238 : repositoryIdentities.resolve(project.workspaceRoot)
239 ).pipe(
240 Effect.map((repositoryIdentity) => {
241 const gitHost = resolveGitHostBindings({ ...project, repositoryIdentity });
242 return [...resolveStandaloneBindings(binding), ...gitHost];
243 }),
244 );
245
246 const listProjects = (filter: {
247 readonly projectId?: IssueListInput["projectId"];
248 readonly excludeProjectIds?: IssueListInput["excludeProjectIds"];
249 readonly host?: string | undefined;
250 /** The link's `host:port`, for a host whose binding keeps its port. */
251 readonly authority?: string | undefined;
252 }) =>
253 (filter.projectId === undefined
254 ? projects.listShells()
255 : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
256 ).pipe(
257 Effect.mapError(
258 (cause) =>
259 new IssueOperationError({
260 operation: "listProjects",
261 detail: "The project list could not be read.",
262 cause,
263 }),
264 ),
265 Effect.flatMap(
266 Effect.fnUntraced(function* (allShells) {
267 const shells = allShells.filter(
268 (project) => !filter.excludeProjectIds?.includes(project.id),
269 );
270 if (shells.length === 0) return [];
271 // One read per listing, not per project, and never cached so Settings changes apply.
272 const bound = yield* bindings.list(filter.projectId).pipe(
273 // A failed read is not an unbound project: that would list the git host's issues alone.
274 Effect.mapError(
275 (cause) =>
276 new IssueOperationError({
277 operation: "listProjects",
278 detail: "The project's issue tracker binding could not be read.",
279 cause,
280 }),
281 ),
282 );
283 return yield* Effect.forEach(
284 shells,
285 (project) =>
286 resolveProjectTracker(project, bound.get(project.id)).pipe(
287 Effect.map((candidates) =>
288 candidates.map((candidate) => ({ project, ...candidate })),
289 ),
290 ),
291 { concurrency: SCOPE_CONCURRENCY },
292 );
293 }),
294 ),
295 Effect.map((bound) => {
296 const host = filter.host?.trim().toLowerCase();
297 const supported: SupportedProject[] = [];
298 const unimplemented = new Map<
299 string,
300 { tracker: IssueTrackerKind; projectIds: Set<ProjectId> }
301 >();
302 for (const candidate of bound.flat()) {
303 if (host !== undefined && candidate.host !== host && candidate.host !== filter.authority)
304 continue;
305 const api = registry.get(candidate.tracker);
306 if (api === null) {
307 const counted = unimplemented.get(candidate.host);
308 if (counted === undefined)
309 unimplemented.set(candidate.host, {
310 tracker: candidate.tracker,
311 projectIds: new Set([candidate.project.id]),
312 });
313 else counted.projectIds.add(candidate.project.id);
314 continue;
315 }
316 supported.push({ ...candidate, api: asIssueTrackerAccount(api, candidate.accountId) });
317 }
318 return { supported, unimplemented };
319 }),
320 );
321
322 /**
323 * The project whose checkout and credentials serve a reference, and whether the reference is
324 * one of the project's own scopes. A reference naming another scope on the same tracker and
325 * host is served by the project but marked read-only. A project with two trackers serves the
326 * one the reference names.
327 */
328 const requireProject = (
329 ref: IssueScopeRef,
330 ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> =>
331 listProjects({ projectId: ref.projectId }).pipe(
332 Effect.flatMap(({ supported }) => {
333 const host = ref.host?.trim().toLowerCase();
334 const onHost = supported.filter(
335 (candidate) =>
336 candidate.tracker === ref.tracker && (host === undefined || candidate.host === host),
337 );
338 const scope = ref.scope.trim();
339 const own = onHost.find(
340 (candidate) => candidate.scope.toLowerCase() === scope.toLowerCase(),
341 );
342 const served = own ?? onHost[0];
343 if (served === undefined) {
344 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
345 }
346 return Effect.succeed({ ...served, scope, writable: own !== undefined });
347 }),
348 );
349
350 const requireWritable = (ref: IssueScopeRef, operation: string) =>
351 requireProject(ref).pipe(
352 Effect.filterOrFail(
353 (project) => project.writable,
354 () => readOnly(operation),
355 ),
356 );
357
358 const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
359 // Trackers name every host so a client narrowed to one can switch to another; only the
360 // narrowed host's scopes are read.
361 const { supported, unimplemented } = yield* listProjects({
362 projectId: input.projectId,
363 excludeProjectIds: input.excludeProjectIds,
364 });
365 const host = input.host?.trim().toLowerCase();
366 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
367 // Worktrees of one repository are separate projects, and every repository of an Azure
368 // DevOps project shares its work items; read each scope once.
369 const scopes = new Map<string, SupportedProject>();
370 for (const project of supported) {
371 if (host !== undefined && project.host !== host) continue;
372 const key = listCursorKey(project);
373 if (!scopes.has(key)) scopes.set(key, project);
374 }
375 const continuing = input.cursors;
376 const viewers = new Map<string, string>();
377 const trackers = new Map<string, IssueTrackerSummary>();
378 const entries: IssueListEntry[] = [];
379 const errors: IssueListProjectError[] = [];
380 const nextCursors: Record<string, string> = {};
381
382 const involvement = input.involvement ?? "all";
383 const sort = input.sort ?? "updated";
384 // Only a narrowed listing compares against the signed-in account; `all` never reads it.
385 const viewerRequests = new Map<string, Effect.Effect<string, IssueTrackerError>>();
386 for (const project of involvement === "all" ? [] : scopes.values()) {
387 const key = viewerKey(project);
388 if (viewerRequests.has(key)) continue;
389 const request = yield* Effect.cached(
390 project.api
391 .getViewer({ cwd: project.project.workspaceRoot, host: project.host })
392 .pipe(Effect.tap((viewer) => Effect.sync(() => viewers.set(key, viewer)))),
393 );
394 viewerRequests.set(key, request);
395 }
396
397 // Every project counts once, including worktrees of a scope read once below and forks.
398 const counted = new Set<string>();
399 for (const project of supported) {
400 const countKey = `${project.host} ${project.project.id}`;
401 if (counted.has(countKey)) continue;
402 counted.add(countKey);
403 const existing = trackers.get(project.host);
404 trackers.set(
405 project.host,
406 existing === undefined
407 ? {
408 tracker: project.tracker,
409 host: project.host,
410 projectCount: 1,
411 capabilities: project.api.capabilities,
412 configured: true,
413 detail: null,
414 }
415 : { ...existing, projectCount: existing.projectCount + 1 },
416 );
417 }
418 // Accounts of one tracker share its host: the host is unusable only when every account read
419 // failed for want of a tool or credential. Otherwise a failure stays its projects' error.
420 const hostAccounts = new Map<string, Set<string>>();
421 for (const project of scopes.values()) {
422 const accounts = hostAccounts.get(project.host) ?? new Set();
423 hostAccounts.set(project.host, accounts.add(viewerKey(project)));
424 }
425 const unusable = new Map<string, string>();
426 const usable = new Set<string>();
427 const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
428 if (isTrackerUnusable(failure)) unusable.set(viewerKey(project), trackerDetail(failure));
429 else usable.add(project.host);
430 };
431
432 yield* Effect.forEach(
433 scopes.values(),
434 (project) =>
435 Effect.gen(function* () {
436 const key = listCursorKey(project);
437 // A continuation names the scopes it wants; one not named has nothing to add.
438 if (continuing !== undefined && continuing[key] === undefined) return;
439 const cursor = continuing?.[key];
440 const filter: Effect.Effect<IssueInvolvementFilter, IssueTrackerError> =
441 involvement === "all"
442 ? Effect.succeed({ involvement })
443 : viewerRequests
444 .get(viewerKey(project))!
445 .pipe(Effect.map((viewer) => ({ involvement, viewer })));
446 const page = yield* filter.pipe(
447 Effect.flatMap((filter) =>
448 project.api.listIssues({
449 ...filter,
450 cwd: project.project.workspaceRoot,
451 host: project.host,
452 scope: project.scope,
453 state: input.state,
454 limit,
455 query: input.query,
456 labels: input.labels,
457 assignee: input.assignee,
458 sort,
459 cursor,
460 refresh: input.refresh,
461 }),
462 ),
463 Effect.result,
464 );
465 if (page._tag === "Failure") {
466 if (cursor !== undefined) nextCursors[key] = cursor;
467 recordFailure(project, page.failure);
468 // A fork or a multi-team binding reads several scopes; the failure names its own.
469 const forked = supported.some(
470 (other) => other.project.id === project.project.id && other.scope !== project.scope,
471 );
472 errors.push({
473 projectId: project.project.id,
474 projectTitle: forked
475 ? `${project.project.title} (${project.scope})`
476 : project.project.title,
477 message: trackerDetail(page.failure),
478 });
479 return;
480 }
481 usable.add(project.host);
482 for (const item of page.success.items) {
483 entries.push({
484 ...item,
485 tracker: project.tracker,
486 host: project.host,
487 scope: project.scope,
488 projectId: project.project.id,
489 projectTitle: project.project.title,
490 });
491 }
492 if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
493 }),
494 { concurrency: SCOPE_CONCURRENCY, discard: true },
495 );
496
497 for (const [host, accounts] of hostAccounts) {
498 const details = [...accounts].map((account) => unusable.get(account));
499 const existing = trackers.get(host);
500 if (existing === undefined || usable.has(host) || details.includes(undefined)) continue;
501 trackers.set(host, { ...existing, configured: false, detail: details[0] ?? null });
502 }
503 for (const [host, { tracker, projectIds }] of unimplemented) {
504 trackers.set(host, {
505 tracker,
506 host,
507 projectCount: projectIds.size,
508 capabilities: null,
509 configured: false,
510 detail: "Issues cannot be browsed for this host yet.",
511 });
512 }
513 const sortField = sort === "created" ? "createdAt" : "updatedAt";
514 const parseSortTime = (iso: string) => {
515 const time = Date.parse(iso);
516 return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;
517 };
518 entries.sort((a, b) => {
519 const aTime = parseSortTime(a[sortField]);
520 const bTime = parseSortTime(b[sortField]);
521 if (aTime !== bTime) return bTime > aTime ? 1 : -1;
522 return b[sortField].localeCompare(a[sortField]);
523 });
524 return {
525 viewers: Object.fromEntries(viewers),
526 trackers: [...trackers.values()],
527 entries,
528 errors,
529 nextCursors,
530 scopes: [...scopes.values()].map((project) => ({
531 projectId: project.project.id,
532 tracker: project.tracker,
533 host: project.host,
534 scope: project.scope,
535 })),
536 };
537 });
538
539 const toDetail = (
540 project: SupportedProject & { readonly writable: boolean },
541 issue: TrackerIssueDetail,
542 ): IssueDetail => ({
543 ...issue,
544 tracker: project.tracker,
545 host: project.host,
546 scope: project.scope,
547 projectId: project.project.id,
548 projectTitle: project.project.title,
549 writable: project.writable,
550 capabilities: project.api.capabilities,
551 });
552
553 const detail: IssueService["Service"]["detail"] = (input) =>
554 requireProject(input).pipe(
555 Effect.flatMap((project) =>
556 project.api
557 .getIssue({
558 cwd: project.project.workspaceRoot,
559 host: project.host,
560 scope: project.scope,
561 key: input.key,
562 })
563 .pipe(
564 Effect.mapError(toIssueError("detail")),
565 Effect.map((issue) => toDetail(project, issue)),
566 ),
567 ),
568 );
569
570 const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) =>
571 requireProject(input).pipe(
572 Effect.flatMap((project) => {
573 const read = project.api.getIssueLink ?? project.api.getIssue;
574 return read({
575 cwd: project.project.workspaceRoot,
576 host: project.host,
577 scope: project.scope,
578 key: input.key,
579 }).pipe(
580 Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })),
581 Effect.mapError(toIssueError("detail")),
582 );
583 }),
584 );
585
586 const comments: IssueService["Service"]["comments"] = (input) =>
587 requireProject(input).pipe(
588 Effect.flatMap((project) =>
589 project.api
590 .getComments({
591 cwd: project.project.workspaceRoot,
592 host: project.host,
593 scope: project.scope,
594 key: input.key,
595 cursor: input.cursor,
596 })
597 .pipe(Effect.mapError(toIssueError("comments"))),
598 ),
599 );
600
601 const templates: IssueService["Service"]["templates"] = (input) =>
602 requireProject(input).pipe(
603 Effect.flatMap((project) =>
604 project.api.listTemplates === undefined || !project.api.capabilities.templates
605 ? Effect.fail(unsupported("templates", "issue templates"))
606 : project.api
607 .listTemplates({
608 cwd: project.project.workspaceRoot,
609 host: project.host,
610 scope: project.scope,
611 })
612 .pipe(Effect.mapError(toIssueError("templates"))),
613 ),
614 );
615
616 const candidates: IssueService["Service"]["candidates"] = (input) =>
617 requireProject(input).pipe(
618 Effect.flatMap((project) =>
619 project.api.listCandidates === undefined ||
620 !(project.api.capabilities.labels || project.api.capabilities.assignees)
621 ? Effect.fail(unsupported("candidates", "labels or assignees"))
622 : project.api
623 .listCandidates({
624 cwd: project.project.workspaceRoot,
625 host: project.host,
626 scope: project.scope,
627 })
628 .pipe(Effect.mapError(toIssueError("candidates"))),
629 ),
630 );
631
632 const create: IssueService["Service"]["create"] = (input) =>
633 requireWritable(input, "create").pipe(
634 Effect.flatMap((project) =>
635 project.api.create === undefined || !project.api.capabilities.create
636 ? Effect.fail(unsupported("create", "filing issues"))
637 : project.api
638 .create({
639 cwd: project.project.workspaceRoot,
640 host: project.host,
641 scope: project.scope,
642 title: input.title,
643 body: input.body,
644 labels: input.labels,
645 assignees: input.assignees,
646 })
647 .pipe(Effect.mapError(toIssueError("create"))),
648 ),
649 );
650
651 const comment: IssueService["Service"]["comment"] = (input) =>
652 requireWritable(input, "comment").pipe(
653 Effect.flatMap((project) => {
654 if (input.body.trim().length === 0) {
655 return Effect.fail(
656 new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
657 );
658 }
659 return project.api.comment === undefined || !project.api.capabilities.comment
660 ? Effect.fail(unsupported("comment", "comments"))
661 : project.api
662 .comment({
663 cwd: project.project.workspaceRoot,
664 host: project.host,
665 scope: project.scope,
666 key: input.key,
667 body: input.body,
668 })
669 .pipe(Effect.mapError(toIssueError("comment")));
670 }),
671 );
672
673 const update: IssueService["Service"]["update"] = (input) =>
674 requireWritable(input, "update").pipe(
675 Effect.flatMap((project) => {
676 const { capabilities } = project.api;
677 const wantsWords = input.title !== undefined || input.body !== undefined;
678 if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
679 return Effect.fail(
680 new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
681 );
682 }
683 if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
684 if (wantsWords && !capabilities.edit)
685 return Effect.fail(unsupported("update", "editing the title or body"));
686 if (input.labels !== undefined && !capabilities.labels)
687 return Effect.fail(unsupported("update", "labels"));
688 if (input.assignees !== undefined && !capabilities.assignees)
689 return Effect.fail(unsupported("update", "assignees"));
690 return project.api
691 .update({
692 cwd: project.project.workspaceRoot,
693 host: project.host,
694 scope: project.scope,
695 key: input.key,
696 title: input.title,
697 body: input.body,
698 labels: input.labels,
699 assignees: input.assignees,
700 })
701 .pipe(Effect.mapError(toIssueError("update")));
702 }),
703 );
704
705 const setState: IssueService["Service"]["setState"] = (input) =>
706 requireWritable(input, "setState").pipe(
707 Effect.flatMap((project) => {
708 if (project.api.setState === undefined)
709 return Effect.fail(unsupported("setState", "changing an issue's state"));
710 return project.api
711 .setState({
712 cwd: project.project.workspaceRoot,
713 host: project.host,
714 scope: project.scope,
715 key: input.key,
716 state: input.state,
717 })
718 .pipe(Effect.mapError(toIssueError("setState")));
719 }),
720 );
721
722 const react: IssueService["Service"]["react"] = (input) =>
723 requireWritable(input, "react").pipe(
724 Effect.flatMap((project) =>
725 project.api.setReaction === undefined || !project.api.capabilities.reactions
726 ? Effect.fail(unsupported("react", "reactions"))
727 : project.api
728 .setReaction({
729 cwd: project.project.workspaceRoot,
730 host: project.host,
731 scope: project.scope,
732 key: input.key,
733 subjectId: input.subjectId,
734 content: input.content,
735 reacted: input.reacted,
736 })
737 .pipe(Effect.mapError(toIssueError("react"))),
738 ),
739 );
740
741 const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
742 "IssueService.projectScope",
743 )(function* (projectId, select) {
744 const { supported } = yield* listProjects({ projectId });
745 if (supported.length === 0) {
746 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
747 }
748 const named = select?.scope?.trim().toLowerCase();
749 const prefix = select?.key?.toLowerCase();
750 const own =
751 named === undefined
752 ? (supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ??
753 supported[0])
754 : supported.find((candidate) => candidate.scope.toLowerCase() === named);
755 if (own === undefined) {
756 return yield* new IssueOperationError({
757 operation: "scope",
758 reason: "not-found",
759 detail: `This project does not track ${select?.scope?.trim()}. Use one of: ${[...new Set(supported.map((candidate) => candidate.scope))].join(", ")}.`,
760 });
761 }
762 return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
763 });
764
765 /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
766 const parseOnProjectHost = (value: string) => {
767 const url = parseUrl(value);
768 if (url === null) return Effect.succeed(null);
769 return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe(
770 Effect.map(({ supported }) => {
771 for (const project of supported) {
772 const parsed = sourceControlDefinitions.parseIssueUrl(
773 value,
774 SourceControlProviderKind.make(project.tracker),
775 );
776 if (parsed !== null) return parsed;
777 }
778 return null;
779 }),
780 );
781 };
782
783 const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
784 function* (url, preferredProjectId) {
785 const recognized = sourceControlDefinitions.parseIssueUrl(url);
786 const standalone =
787 recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
788 const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null);
789 const parsed =
790 gitHost === null
791 ? standalone
792 : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link };
793 if (parsed === null) {
794 return yield* new IssueOperationError({
795 operation: "resolveUrl",
796 reason: "not-found",
797 detail: "This is not a recognised issue URL.",
798 });
799 }
800 const { tracker, link } = parsed;
801 // A link names its server's port; a binding does only when its remote or web URL did.
802 const authority = new URL(url).host.toLowerCase();
803 const { supported } = yield* listProjects({ host: link.host, authority });
804 const onHost = supported.filter((project) => project.tracker === tracker);
805 const onAuthority = onHost.filter((project) => project.host === authority);
806 const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
807 const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
808 projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
809 const scope = link.scope.toLowerCase();
810 const serve = (candidates: ReadonlyArray<SupportedProject>) => {
811 const own =
812 preferFirst(candidates.filter((project) => project.scope.toLowerCase() === scope)) ??
813 preferFirst(
814 candidates.filter(
815 (project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias,
816 ),
817 );
818 const lender = own ?? preferFirst(candidates);
819 if (lender === undefined) return null;
820 const served = {
821 ...lender,
822 scope: own === undefined ? link.scope : lender.scope,
823 writable: own !== undefined,
824 };
825 const resolved = {
826 projectId: lender.project.id,
827 tracker: lender.tracker,
828 host: lender.host,
829 scope: served.scope,
830 key: link.key,
831 writable: served.writable,
832 };
833 return { lender, served, resolved };
834 };
835 if (standalone === null) {
836 const found = serve(onTracker);
837 if (found === null) {
838 return yield* new IssueOperationError({
839 operation: "resolveUrl",
840 detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`,
841 });
842 }
843 return found.resolved;
844 }
845 // Team keys repeat across workspaces, and each account reaches one: try the accounts in
846 // preference order, and keep the one whose canonical issue URL names the link's workspace.
847 // The exact team before a fallback, as `serve` and the client resolver pick it.
848 const exact = onTracker.filter((project) => project.scope.toLowerCase() === scope);
849 const preferred = (projects: ReadonlyArray<SupportedProject>) => [
850 ...projects.filter((project) => project.project.id === preferredProjectId),
851 ...projects,
852 ];
853 const ordered = [...preferred(exact), ...preferred(onTracker)];
854 const accounts = [...new Set(ordered.map((project) => project.accountId))];
855 if (accounts.length === 0) {
856 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
857 }
858 let failure: IssueError | null = null;
859 for (const accountId of accounts) {
860 const found = serve(onTracker.filter((project) => project.accountId === accountId));
861 if (found === null) continue;
862 const read = yield* found.lender.api
863 .getIssue({
864 cwd: found.lender.project.workspaceRoot,
865 host: found.lender.host,
866 scope: link.scope,
867 key: link.key,
868 })
869 .pipe(Effect.mapError(toIssueError("resolveUrl")), Effect.result);
870 if (read._tag === "Failure") {
871 // Another workspace's account not having the key is a miss, not why the link failed.
872 if (failure === null || isNotFound(failure)) failure = read.failure;
873 continue;
874 }
875 const canonicalUrl = parseUrl(read.success.url);
876 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
877 if (canonical !== null && canonical.workspace === standalone.link.workspace) {
878 return { ...found.resolved, issue: toDetail(found.served, read.success) };
879 }
880 }
881 return yield* (
882 failure ??
883 new IssueOperationError({
884 operation: "resolveUrl",
885 reason: "not-found",
886 detail: "This issue URL does not belong to the connected workspace.",
887 })
888 );
889 },
890 );
891
892 return IssueService.of({
893 list,
894 detail: traced("detail", detail),
895 linkMetadata: traced("linkMetadata", linkMetadata),
896 comments: traced("comments", comments),
897 templates: traced("templates", templates),
898 candidates: interactive(traced("candidates", candidates)),
899 create: interactive(traced("create", create)),
900 comment: interactive(traced("comment", comment)),
901 update: interactive(traced("update", update)),
902 setState: interactive(traced("setState", setState)),
903 react: interactive(traced("react", react)),
904 projectScope,
905 resolveUrl,
906 });
907});
908
909export const layer = Layer.effect(IssueService, make);