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

IssueService.ts

1,053 lines41.1 KB

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 }
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(" ");
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.";
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;
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;
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 }));
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;
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}`;
154​
155function viewerKey(project: ProjectTrackerBinding): string {
156 return project.accountId === null ? project.host : `${project.host} ${project.accountId}`;
158​
159function isTrackerUnusable(error: IssueTrackerError): boolean {
160 return error.reason === "missing-tool" || error.reason === "unauthenticated";
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 });
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.
274 */
275 const resolveProjectTracker = (
276 project: OrchestrationProjectShell,
277 binding: IssueTrackerProjectBinding | undefined,
278 ) =>
279 (project.repositoryIdentity != null
280 ? Effect.succeed(project.repositoryIdentity)
281 : repositoryIdentities.resolve(project.workspaceRoot)
282 ).pipe(
283 Effect.map((repositoryIdentity) => {
284 const gitHost = resolveGitHostBindings({ ...project, repositoryIdentity });
285 return [...resolveStandaloneBindings(binding), ...gitHost];
286 }),
287 );
288​
289 const listProjects = (filter: {
290 readonly projectId?: IssueListInput["projectId"];
291 readonly excludeProjectIds?: IssueListInput["excludeProjectIds"];
292 readonly host?: string | undefined;
293 /** The link's `host:port`, for a host whose binding keeps its port. */
294 readonly authority?: string | undefined;
295 }) =>
296 (filter.projectId === undefined
297 ? projects.listShells()
298 : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
299 ).pipe(
300 Effect.mapError(
301 (cause) =>
302 new IssueOperationError({
303 operation: "listProjects",
304 detail: "The project list could not be read.",
305 cause,
306 }),
307 ),
308 Effect.flatMap(
309 Effect.fnUntraced(function* (allShells) {
310 const shells = allShells.filter(
311 (project) => !filter.excludeProjectIds?.includes(project.id),
312 );
313 if (shells.length === 0) return [];
314 // One read per listing, not per project, and never cached so Settings changes apply.
315 const bound = yield* bindings.list(filter.projectId).pipe(
316 // A failed read is not an unbound project: that would list the git host's issues alone.
317 Effect.mapError(
318 (cause) =>
319 new IssueOperationError({
320 operation: "listProjects",
321 detail: "The project's issue tracker binding could not be read.",
322 cause,
323 }),
324 ),
325 );
326 return yield* Effect.forEach(
327 shells,
328 (project) =>
329 resolveProjectTracker(project, bound.get(project.id)).pipe(
330 Effect.map((candidates) =>
331 candidates.map((candidate) => ({ project, ...candidate })),
332 ),
333 ),
334 { concurrency: SCOPE_CONCURRENCY },
335 );
336 }),
337 ),
338 Effect.map((bound) => {
339 const host = filter.host?.trim().toLowerCase();
340 const supported: SupportedProject[] = [];
341 const unimplemented = new Map<
342 string,
343 { tracker: IssueTrackerKind; projectIds: Set<ProjectId> }
344 >();
345 for (const candidate of bound.flat()) {
346 if (host !== undefined && candidate.host !== host && candidate.host !== filter.authority)
347 continue;
348 const api = registry.get(candidate.tracker);
349 if (api === null) {
350 const counted = unimplemented.get(candidate.host);
351 if (counted === undefined)
352 unimplemented.set(candidate.host, {
353 tracker: candidate.tracker,
354 projectIds: new Set([candidate.project.id]),
355 });
356 else counted.projectIds.add(candidate.project.id);
357 continue;
358 }
359 supported.push({ ...candidate, api: asIssueTrackerAccount(api, candidate.accountId) });
360 }
361 return { supported, unimplemented };
362 }),
363 );
364​
365 /**
366 * A project with no binding for a standalone tracker, the No project included, serves its
367 * references with the environment's credential. The tracker decides what the account may change.
368 */
369 const requireStandaloneProject = (
370 ref: IssueScopeRef,
371 api: StandaloneIssueTrackerApi,
372 ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> => {
373 const host = ref.host?.trim().toLowerCase();
374 if (host !== undefined && host !== api.standalone.host) {
375 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
376 }
377 return projects.getShell(ref.projectId).pipe(
378 Effect.mapError(
379 (cause) =>
380 new IssueOperationError({
381 operation: "listProjects",
382 detail: "The project list could not be read.",
383 cause,
384 }),
385 ),
386 Effect.flatMap(
387 Option.match({
388 onNone: () => Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" })),
389 onSome: (project) =>
390 Effect.succeed({
391 project,
392 api,
393 // No binding names an account, so the tracker's first one serves.
394 accountId: null,
395 tracker: ref.tracker,
396 host: api.standalone.host,
397 scope: ref.scope.trim(),
398 writable: true,
399 }),
400 }),
401 ),
402 );
403 };
404​
405 /**
406 * The project whose checkout and credentials serve a reference, and whether the reference is
407 * one of the project's own scopes. A reference naming another scope on the same tracker and
408 * host is served by the project but marked read-only. A project with two trackers serves the
409 * one the reference names, and one with no binding for a standalone tracker still serves it.
410 */
411 const requireProject = (
412 ref: IssueScopeRef,
413 ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> =>
414 listProjects({ projectId: ref.projectId }).pipe(
415 Effect.flatMap(({ supported }) => {
416 const host = ref.host?.trim().toLowerCase();
417 const onTracker = supported.filter((candidate) => candidate.tracker === ref.tracker);
418 const api = registry.get(ref.tracker);
419 if (onTracker.length === 0 && api !== null && isStandaloneIssueTracker(api)) {
420 return requireStandaloneProject(ref, api);
421 }
422 const onHost = onTracker.filter(
423 (candidate) => host === undefined || candidate.host === host,
424 );
425 const scope = ref.scope.trim();
426 const own = onHost.find(
427 (candidate) => candidate.scope.toLowerCase() === scope.toLowerCase(),
428 );
429 const served = own ?? onHost[0];
430 if (served === undefined) {
431 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
432 }
433 return Effect.succeed({ ...served, scope, writable: own !== undefined });
434 }),
435 );
436​
437 const requireWritable = (ref: IssueScopeRef, operation: string) =>
438 requireProject(ref).pipe(
439 Effect.filterOrFail(
440 (project) => project.writable,
441 () => readOnly(operation),
442 ),
443 );
444​
445 const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
446 // Trackers name every host so a client narrowed to one can switch to another; only the
447 // narrowed host's scopes are read.
448 const { supported, unimplemented } = yield* listProjects({
449 projectId: input.projectId,
450 excludeProjectIds: input.excludeProjectIds,
451 });
452 const host = input.host?.trim().toLowerCase();
453 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
454 // Worktrees of one repository are separate projects, and every repository of an Azure
455 // DevOps project shares its work items; read each scope once.
456 const scopes = new Map<string, SupportedProject>();
457 for (const project of supported) {
458 if (host !== undefined && project.host !== host) continue;
459 const key = listCursorKey(project);
460 if (!scopes.has(key)) scopes.set(key, project);
461 }
462 const continuing = input.cursors;
463 const viewers = new Map<string, string>();
464 const trackers = new Map<string, IssueTrackerSummary>();
465 const entries: IssueListEntry[] = [];
466 const errors: IssueListProjectError[] = [];
467 const nextCursors: Record<string, string> = {};
468​
469 const involvement = input.involvement ?? "all";
470 const sort = input.sort ?? "updated";
471 // Only a narrowed listing compares against the signed-in account; `all` never reads it.
472 const viewerRequests = new Map<string, Effect.Effect<string, IssueTrackerError>>();
473 for (const project of involvement === "all" ? [] : scopes.values()) {
474 const key = viewerKey(project);
475 if (viewerRequests.has(key)) continue;
476 const request = yield* Effect.cached(
477 project.api
478 .getViewer({ cwd: project.project.workspaceRoot, host: project.host })
479 .pipe(Effect.tap((viewer) => Effect.sync(() => viewers.set(key, viewer)))),
480 );
481 viewerRequests.set(key, request);
482 }
483​
484 // Every project counts once, including worktrees of a scope read once below and forks.
485 const counted = new Set<string>();
486 for (const project of supported) {
487 const countKey = `${project.host} ${project.project.id}`;
488 if (counted.has(countKey)) continue;
489 counted.add(countKey);
490 const existing = trackers.get(project.host);
491 trackers.set(
492 project.host,
493 existing === undefined
494 ? {
495 tracker: project.tracker,
496 host: project.host,
497 projectCount: 1,
498 capabilities: project.api.capabilities,
499 configured: true,
500 detail: null,
501 }
502 : { ...existing, projectCount: existing.projectCount + 1 },
503 );
504 }
505 // Accounts of one tracker share its host: the host is unusable only when every account read
506 // failed for want of a tool or credential. Otherwise a failure stays its projects' error.
507 const hostAccounts = new Map<string, Set<string>>();
508 for (const project of scopes.values()) {
509 const accounts = hostAccounts.get(project.host) ?? new Set();
510 hostAccounts.set(project.host, accounts.add(viewerKey(project)));
511 }
512 const unusable = new Map<string, string>();
513 const usable = new Set<string>();
514 const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
515 if (isTrackerUnusable(failure)) unusable.set(viewerKey(project), trackerDetail(failure));
516 else usable.add(project.host);
517 };
518​
519 yield* Effect.forEach(
520 scopes.values(),
521 (project) =>
522 Effect.gen(function* () {
523 const key = listCursorKey(project);
524 // A continuation names the scopes it wants; one not named has nothing to add.
525 if (continuing !== undefined && continuing[key] === undefined) return;
526 const cursor = continuing?.[key];
527 const filter: Effect.Effect<IssueInvolvementFilter, IssueTrackerError> =
528 involvement === "all"
529 ? Effect.succeed({ involvement })
530 : viewerRequests
531 .get(viewerKey(project))!
532 .pipe(Effect.map((viewer) => ({ involvement, viewer })));
533 const page = yield* filter.pipe(
534 Effect.flatMap((filter) =>
535 project.api.listIssues({
536 ...filter,
537 cwd: project.project.workspaceRoot,
538 host: project.host,
539 scope: project.scope,
540 state: input.state,
541 limit,
542 query: input.query,
543 labels: input.labels,
544 assignee: input.assignee,
545 sort,
546 cursor,
547 refresh: input.refresh,
548 }),
549 ),
550 Effect.result,
551 );
552 if (page._tag === "Failure") {
553 if (cursor !== undefined) nextCursors[key] = cursor;
554 recordFailure(project, page.failure);
555 // A fork or a multi-team binding reads several scopes; the failure names its own.
556 const forked = supported.some(
557 (other) => other.project.id === project.project.id && other.scope !== project.scope,
558 );
559 errors.push({
560 projectId: project.project.id,
561 projectTitle: forked
562 ? `${project.project.title} (${project.scope})`
563 : project.project.title,
564 message: trackerDetail(page.failure),
565 });
566 return;
567 }
568 usable.add(project.host);
569 for (const item of page.success.items) {
570 entries.push({
571 ...item,
572 tracker: project.tracker,
573 host: project.host,
574 scope: project.scope,
575 projectId: project.project.id,
576 projectTitle: project.project.title,
577 });
578 }
579 if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
580 }),
581 { concurrency: SCOPE_CONCURRENCY, discard: true },
582 );
583​
584 for (const [host, accounts] of hostAccounts) {
585 const details = [...accounts].map((account) => unusable.get(account));
586 const existing = trackers.get(host);
587 if (existing === undefined || usable.has(host) || details.includes(undefined)) continue;
588 trackers.set(host, { ...existing, configured: false, detail: details[0] ?? null });
589 }
590 for (const [host, { tracker, projectIds }] of unimplemented) {
591 trackers.set(host, {
592 tracker,
593 host,
594 projectCount: projectIds.size,
595 capabilities: null,
596 configured: false,
597 detail: "Issues cannot be browsed for this host yet.",
598 });
599 }
600 const sortField = sort === "created" ? "createdAt" : "updatedAt";
601 const parseSortTime = (iso: string) => {
602 const time = Date.parse(iso);
603 return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;
604 };
605 entries.sort((a, b) => {
606 const aTime = parseSortTime(a[sortField]);
607 const bTime = parseSortTime(b[sortField]);
608 if (aTime !== bTime) return bTime > aTime ? 1 : -1;
609 return b[sortField].localeCompare(a[sortField]);
610 });
611 return {
612 viewers: Object.fromEntries(viewers),
613 trackers: [...trackers.values()],
614 entries,
615 errors,
616 nextCursors,
617 scopes: [...scopes.values()].map((project) => ({
618 projectId: project.project.id,
619 tracker: project.tracker,
620 host: project.host,
621 scope: project.scope,
622 })),
623 };
624 });
625​
626 const toDetail = (
627 project: SupportedProject & { readonly writable: boolean },
628 issue: TrackerIssueDetail,
629 ): IssueDetail => ({
630 ...issue,
631 tracker: project.tracker,
632 host: project.host,
633 scope: project.scope,
634 projectId: project.project.id,
635 projectTitle: project.project.title,
636 writable: project.writable,
637 capabilities: project.api.capabilities,
638 });
639​
640 const detail: IssueService["Service"]["detail"] = (input) =>
641 requireProject(input).pipe(
642 Effect.tap((project) =>
643 input.refresh === true ? invalidateDetail(project, input.key) : Effect.void,
644 ),
645 Effect.flatMap((project) =>
646 Cache.get(
647 details,
648 new DetailRead(
649 detailCacheKey(project, input.key),
650 project.api
651 .getIssue({
652 cwd: project.project.workspaceRoot,
653 host: project.host,
654 scope: project.scope,
655 key: input.key,
656 })
657 .pipe(Effect.mapError(toIssueError("detail"))),
658 ),
659 ).pipe(Effect.map((issue) => toDetail(project, issue))),
660 ),
661 );
662​
663 const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) =>
664 requireProject(input).pipe(
665 Effect.flatMap((project) => {
666 const read = project.api.getIssueLink ?? project.api.getIssue;
667 return read({
668 cwd: project.project.workspaceRoot,
669 host: project.host,
670 scope: project.scope,
671 key: input.key,
672 }).pipe(
673 Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })),
674 Effect.mapError(toIssueError("detail")),
675 );
676 }),
677 );
678​
679 const comments: IssueService["Service"]["comments"] = (input) =>
680 requireProject(input).pipe(
681 Effect.flatMap((project) =>
682 project.api
683 .getComments({
684 cwd: project.project.workspaceRoot,
685 host: project.host,
686 scope: project.scope,
687 key: input.key,
688 cursor: input.cursor,
689 })
690 .pipe(Effect.mapError(toIssueError("comments"))),
691 ),
692 );
693​
694 const templates: IssueService["Service"]["templates"] = (input) =>
695 requireProject(input).pipe(
696 Effect.flatMap((project) =>
697 project.api.listTemplates === undefined || !project.api.capabilities.templates
698 ? Effect.fail(unsupported("templates", "issue templates"))
699 : project.api
700 .listTemplates({
701 cwd: project.project.workspaceRoot,
702 host: project.host,
703 scope: project.scope,
704 })
705 .pipe(Effect.mapError(toIssueError("templates"))),
706 ),
707 );
708​
709 const candidates: IssueService["Service"]["candidates"] = (input) =>
710 requireProject(input).pipe(
711 Effect.flatMap((project) =>
712 project.api.listCandidates === undefined ||
713 !(project.api.capabilities.labels || project.api.capabilities.assignees)
714 ? Effect.fail(unsupported("candidates", "labels or assignees"))
715 : project.api
716 .listCandidates({
717 cwd: project.project.workspaceRoot,
718 host: project.host,
719 scope: project.scope,
720 ...(input.query?.trim() ? { query: input.query.trim() } : {}),
721 })
722 .pipe(Effect.mapError(toIssueError("candidates"))),
723 ),
724 );
725​
726 const create: IssueService["Service"]["create"] = (input) =>
727 requireWritable(input, "create").pipe(
728 Effect.flatMap((project) =>
729 project.api.create === undefined || !project.api.capabilities.create
730 ? Effect.fail(unsupported("create", "filing issues"))
731 : project.api
732 .create({
733 cwd: project.project.workspaceRoot,
734 host: project.host,
735 scope: project.scope,
736 title: input.title,
737 body: input.body,
738 labels: input.labels,
739 assignees: input.assignees,
740 })
741 .pipe(Effect.mapError(toIssueError("create"))),
742 ),
743 );
744​
745 const comment: IssueService["Service"]["comment"] = (input) =>
746 requireWritable(input, "comment").pipe(
747 Effect.flatMap((project) => {
748 if (input.body.trim().length === 0) {
749 return Effect.fail(
750 new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
751 );
752 }
753 if (input.audience === "internal" && project.api.capabilities.internalComments !== true) {
754 return Effect.fail(unsupported("comment", "internal notes"));
755 }
756 return project.api.comment === undefined || !project.api.capabilities.comment
757 ? Effect.fail(unsupported("comment", "comments"))
758 : project.api
759 .comment({
760 cwd: project.project.workspaceRoot,
761 host: project.host,
762 scope: project.scope,
763 key: input.key,
764 body: input.body,
765 audience: input.audience,
766 })
767 .pipe(
768 Effect.mapError(toIssueError("comment")),
769 Effect.ensuring(invalidateDetail(project, input.key)),
770 );
771 }),
772 );
773​
774 const update: IssueService["Service"]["update"] = (input) =>
775 requireWritable(input, "update").pipe(
776 Effect.flatMap((project) => {
777 const { capabilities } = project.api;
778 const wantsWords = input.title !== undefined || input.body !== undefined;
779 if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
780 return Effect.fail(
781 new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
782 );
783 }
784 if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
785 if (wantsWords && !capabilities.edit)
786 return Effect.fail(unsupported("update", "editing the title or body"));
787 if (input.labels !== undefined && !capabilities.labels)
788 return Effect.fail(unsupported("update", "labels"));
789 if (input.assignees !== undefined && !capabilities.assignees)
790 return Effect.fail(unsupported("update", "assignees"));
791 return project.api
792 .update({
793 cwd: project.project.workspaceRoot,
794 host: project.host,
795 scope: project.scope,
796 key: input.key,
797 title: input.title,
798 body: input.body,
799 labels: input.labels,
800 assignees: input.assignees,
801 })
802 .pipe(
803 Effect.mapError(toIssueError("update")),
804 Effect.ensuring(invalidateDetail(project, input.key)),
805 );
806 }),
807 );
808​
809 const setState: IssueService["Service"]["setState"] = (input) =>
810 requireWritable(input, "setState").pipe(
811 Effect.flatMap((project) => {
812 if (project.api.setState === undefined)
813 return Effect.fail(unsupported("setState", "changing an issue's state"));
814 return project.api
815 .setState({
816 cwd: project.project.workspaceRoot,
817 host: project.host,
818 scope: project.scope,
819 key: input.key,
820 state: input.state,
821 })
822 .pipe(
823 Effect.mapError(toIssueError("setState")),
824 Effect.ensuring(invalidateDetail(project, input.key)),
825 );
826 }),
827 );
828​
829 const react: IssueService["Service"]["react"] = (input) =>
830 requireWritable(input, "react").pipe(
831 Effect.flatMap((project) =>
832 project.api.setReaction === undefined || !project.api.capabilities.reactions
833 ? Effect.fail(unsupported("react", "reactions"))
834 : project.api
835 .setReaction({
836 cwd: project.project.workspaceRoot,
837 host: project.host,
838 scope: project.scope,
839 key: input.key,
840 subjectId: input.subjectId,
841 content: input.content,
842 reacted: input.reacted,
843 })
844 .pipe(
845 Effect.mapError(toIssueError("react")),
846 Effect.ensuring(invalidateDetail(project, input.key)),
847 ),
848 ),
849 );
850​
851 const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
852 "IssueService.projectScope",
853 )(function* (projectId, select) {
854 const { supported } = yield* listProjects({ projectId });
855 if (supported.length === 0) {
856 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
857 }
858 const named = select?.scope?.trim().toLowerCase();
859 const prefix = select?.key?.toLowerCase();
860 const own =
861 named === undefined
862 ? (supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ??
863 supported[0])
864 : supported.find((candidate) => candidate.scope.toLowerCase() === named);
865 if (own === undefined) {
866 return yield* new IssueOperationError({
867 operation: "scope",
868 reason: "not-found",
869 detail: `This project does not track ${select?.scope?.trim()}. Use one of: ${[...new Set(supported.map((candidate) => candidate.scope))].join(", ")}.`,
870 });
871 }
872 return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
873 });
874​
875 /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
876 const parseOnProjectHost = (value: string) => {
877 const url = parseUrl(value);
878 if (url === null) return Effect.succeed(null);
879 return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe(
880 Effect.map(({ supported }) => {
881 for (const project of supported) {
882 const parsed = sourceControlDefinitions.parseIssueUrl(
883 value,
884 SourceControlProviderKind.make(project.tracker),
885 );
886 if (parsed !== null) return parsed;
887 }
888 return null;
889 }),
890 );
891 };
892​
893 const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
894 function* (url, preferredProjectId) {
895 const recognized = sourceControlDefinitions.parseIssueUrl(url);
896 const standalone =
897 recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
898 const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null);
899 const parsed =
900 gitHost === null
901 ? standalone
902 : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link };
903 if (parsed === null) {
904 return yield* new IssueOperationError({
905 operation: "resolveUrl",
906 reason: "not-found",
907 detail: "This is not a recognised issue URL.",
908 });
909 }
910 const { tracker, link } = parsed;
911 // A link names its server's port; a binding does only when its remote or web URL did.
912 const authority = new URL(url).host.toLowerCase();
913 const { supported } = yield* listProjects({ host: link.host, authority });
914 const onHost = supported.filter((project) => project.tracker === tracker);
915 const onAuthority = onHost.filter((project) => project.host === authority);
916 const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
917 const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
918 projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
919 const scope = link.scope.toLowerCase();
920 const serve = (candidates: ReadonlyArray<SupportedProject>) => {
921 const own =
922 preferFirst(candidates.filter((project) => project.scope.toLowerCase() === scope)) ??
923 preferFirst(
924 candidates.filter(
925 (project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias,
926 ),
927 );
928 const lender = own ?? preferFirst(candidates);
929 if (lender === undefined) return null;
930 const served = {
931 ...lender,
932 scope: own === undefined ? link.scope : lender.scope,
933 writable: own !== undefined,
934 };
935 const resolved = {
936 projectId: lender.project.id,
937 tracker: lender.tracker,
938 host: lender.host,
939 scope: served.scope,
940 key: link.key,
941 writable: served.writable,
942 };
943 return { lender, served, resolved };
944 };
945 if (standalone === null) {
946 const found = serve(onTracker);
947 if (found === null) {
948 return yield* new IssueOperationError({
949 operation: "resolveUrl",
950 detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`,
951 });
952 }
953 return found.resolved;
954 }
955 // Team keys repeat across workspaces, and each account reaches one: try the accounts in
956 // preference order, and keep the one whose canonical issue URL names the link's workspace.
957 // The exact team before a fallback, as `serve` and the client resolver pick it.
958 const exact = onTracker.filter((project) => project.scope.toLowerCase() === scope);
959 const preferred = (projects: ReadonlyArray<SupportedProject>) => [
960 ...projects.filter((project) => project.project.id === preferredProjectId),
961 ...projects,
962 ];
963 const ordered = [...preferred(exact), ...preferred(onTracker)];
964 const accounts = [...new Set(ordered.map((project) => project.accountId))];
965 if (accounts.length === 0) {
966 // No project is bound to the tracker: the caller's project, the No project included,
967 // reads the link with the environment's credential.
968 if (preferredProjectId === undefined) {
969 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
970 }
971 const served = yield* requireStandaloneProject(
972 { projectId: preferredProjectId, tracker, scope: link.scope },
973 standalone.api,
974 );
975 const issue = yield* served.api
976 .getIssue({
977 cwd: served.project.workspaceRoot,
978 host: served.host,
979 scope: link.scope,
980 key: link.key,
981 })
982 .pipe(Effect.mapError(toIssueError("resolveUrl")));
983 const canonicalUrl = parseUrl(issue.url);
984 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
985 if (canonical === null || canonical.workspace !== standalone.link.workspace) {
986 return yield* new IssueOperationError({
987 operation: "resolveUrl",
988 reason: "not-found",
989 detail: "This issue URL does not belong to the connected workspace.",
990 });
991 }
992 return {
993 projectId: served.project.id,
994 tracker: served.tracker,
995 host: served.host,
996 scope: served.scope,
997 key: link.key,
998 writable: served.writable,
999 issue: toDetail(served, issue),
1000 };
1002 let failure: IssueError | null = null;
1003 for (const accountId of accounts) {
1004 const found = serve(onTracker.filter((project) => project.accountId === accountId));
1005 if (found === null) continue;
1006 const read = yield* found.lender.api
1007 .getIssue({
1008 cwd: found.lender.project.workspaceRoot,
1009 host: found.lender.host,
1010 scope: link.scope,
1011 key: link.key,
1012 })
1013 .pipe(Effect.mapError(toIssueError("resolveUrl")), Effect.result);
1014 if (read._tag === "Failure") {
1015 // Another workspace's account not having the key is a miss, not why the link failed.
1016 if (failure === null || isNotFound(failure)) failure = read.failure;
1017 continue;
1019 const canonicalUrl = parseUrl(read.success.url);
1020 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
1021 if (canonical !== null && canonical.workspace === standalone.link.workspace) {
1022 return { ...found.resolved, issue: toDetail(found.served, read.success) };
1025 return yield* (
1026 failure ??
1027 new IssueOperationError({
1028 operation: "resolveUrl",
1029 reason: "not-found",
1030 detail: "This issue URL does not belong to the connected workspace.",
1031 })
1032 );
1033 },
1034 );
1035​
1036 return IssueService.of({
1037 list,
1038 detail: traced("detail", detail),
1039 linkMetadata: traced("linkMetadata", linkMetadata),
1040 comments: traced("comments", comments),
1041 templates: traced("templates", templates),
1042 candidates: interactive(traced("candidates", candidates)),
1043 create: interactive(traced("create", create)),
1044 comment: interactive(traced("comment", comment)),
1045 update: interactive(traced("update", update)),
1046 setState: interactive(traced("setState", setState)),
1047 react: interactive(traced("react", react)),
1048 projectScope,
1049 resolveUrl,
1050 });
1051});
1052​
1053export const layer = Layer.effect(IssueService, make);