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

IssueService.ts

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