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