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