Open History to see the last commit
1import {
2 WS_METHODS,
3 type EnvironmentId,
4 type IssueAssigneeCandidate,
5 type IssueCandidates,
6 type IssueComment,
7 type IssueCommentAudience,
8 type IssueCommentsPage,
9 type IssueDetail,
10 type IssueLabelCandidate,
11 type IssueListEntry,
12 type IssueListInput,
13 type IssueListResult,
14 type IssueRef,
15 type IssueScopeRef,
16} from "@t3tools/contracts";
17import type * as Cause from "effect/Cause";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Option from "effect/Option";
21import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
22
23import {
24 type AtomCommandResult,
25 createAtomCommandScheduler,
26 createEnvironmentRpcCommand,
27 createEnvironmentRpcQueryAtomFamily,
28 createEnvironmentRpcSubscriptionAtomFamily,
29 createEnvironmentQueryAtomFamily,
30} from "./runtime.ts";
31import type { EnvironmentRegistry } from "../connection/registry.ts";
32import * as EnvironmentSupervisor from "../connection/supervisor.ts";
33import { request } from "../rpc/client.ts";
34
35type IssueCommentDraft = {
36 readonly body: string;
37 readonly audience: IssueCommentAudience;
38 readonly posting: boolean;
39};
40
41const emptyCommentDraft: IssueCommentDraft = { body: "", audience: "internal", posting: false };
42const commentDrafts = Atom.make(new Map<string, IssueCommentDraft>()).pipe(Atom.keepAlive);
43const commentDraftFamily = Atom.family((key: string) =>
44 Atom.writable(
45 (get) => get(commentDrafts).get(key) ?? emptyCommentDraft,
46 (context, draft: IssueCommentDraft) => {
47 const drafts = new Map(context.get(commentDrafts));
48 if (draft.body === "" && draft.audience === "internal" && !draft.posting) {
49 drafts.delete(key);
50 } else {
51 drafts.set(key, draft);
52 }
53 context.set(commentDrafts, drafts);
54 },
55 ),
56);
57
58function commentDraftEnvironmentPrefix(environmentId: EnvironmentId) {
59 return `${JSON.stringify(environmentId)}:`;
60}
61
62export function issueCommentDraftAtom(environmentId: EnvironmentId, issueUrl: string) {
63 return commentDraftFamily(commentDraftEnvironmentPrefix(environmentId) + issueUrl);
64}
65
66export function clearIssueCommentDraftsEnvironment(
67 registry: AtomRegistry.AtomRegistry,
68 environmentId: EnvironmentId,
69) {
70 const prefix = commentDraftEnvironmentPrefix(environmentId);
71 const drafts = registry.get(commentDrafts);
72 const remaining = new Map([...drafts].filter(([key]) => !key.startsWith(prefix)));
73 if (remaining.size !== drafts.size) registry.set(commentDrafts, remaining);
74}
75
76type IssueCommentDraftAtom = ReturnType<typeof issueCommentDraftAtom>;
77
78export function editIssueCommentDraft(
79 registry: AtomRegistry.AtomRegistry,
80 atom: IssueCommentDraftAtom,
81 changes: Partial<Pick<IssueCommentDraft, "body" | "audience">>,
82) {
83 const draft = registry.get(atom);
84 if (!draft.posting) registry.set(atom, { ...draft, ...changes });
85}
86
87export function beginIssueCommentPost(
88 registry: AtomRegistry.AtomRegistry,
89 atom: IssueCommentDraftAtom,
90 dictatedBody?: string,
91) {
92 const draft = registry.get(atom);
93 const body = dictatedBody ?? draft.body;
94 if (draft.posting || body.trim().length === 0) return null;
95 const pending = { ...draft, body, posting: true };
96 registry.set(atom, pending);
97 return pending;
98}
99
100export function finishIssueCommentPost(
101 registry: AtomRegistry.AtomRegistry,
102 atom: IssueCommentDraftAtom,
103 pending: IssueCommentDraft,
104 sent: boolean,
105) {
106 if (registry.get(atom) === pending) {
107 registry.set(atom, sent ? emptyCommentDraft : { ...pending, posting: false });
108 }
109}
110
111/** One row's identity across list pages and detail reads; hosts compare case-insensitively. */
112export function issueEntryKey(
113 entry: Pick<IssueListEntry, "projectId" | "host" | "scope" | "key">,
114): string {
115 return `${entry.projectId}\u0000${entry.host.toLowerCase()}\u0000${entry.scope.toLowerCase()}\u0000${entry.key}`;
116}
117
118/**
119 * Lay a continuation page over the rows already held. A page only covers the scopes it was asked
120 * to continue, so rows from other scopes stay; a row the page repeats replaces the held one, so a
121 * title or state that moved between reads shows the newer words. Order stays newest-updated first,
122 * which is how every tracker hands them over.
123 */
124export function mergeIssueListPage(
125 held: ReadonlyArray<IssueListEntry>,
126 page: ReadonlyArray<IssueListEntry>,
127): ReadonlyArray<IssueListEntry> {
128 if (held.length === 0) return page;
129 if (page.length === 0) return held;
130 const byKey = new Map<string, IssueListEntry>();
131 for (const entry of held) byKey.set(issueEntryKey(entry), entry);
132 for (const entry of page) byKey.set(issueEntryKey(entry), entry);
133 return [...byKey.values()].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
134}
135
136/** Older comments go in front: the detail carries the newest page and pages walk backwards. */
137function prependIssueComments(
138 current: ReadonlyArray<IssueComment>,
139 older: ReadonlyArray<IssueComment>,
140): ReadonlyArray<IssueComment> {
141 if (older.length === 0) return current;
142 const seen = new Set(current.map((comment) => comment.id));
143 return [...older.filter((comment) => !seen.has(comment.id)), ...current];
144}
145
146export function createIssueCommentPager<E>(
147 detailAtom: Atom.Atom<
148 AsyncResult.AsyncResult<Pick<IssueDetail, "comments" | "commentsCursor">, E>
149 >,
150) {
151 const state = Atom.make<{
152 readonly older: (IssueCommentsPage & { readonly seed: string }) | null;
153 readonly loadingOlder: boolean;
154 readonly refreshing: boolean;
155 readonly refreshes: number;
156 }>({ older: null, loadingOlder: false, refreshing: false, refreshes: 0 });
157 const page = Atom.make((get) => {
158 const detailResult = get(detailAtom);
159 const detail = AsyncResult.getOrElse(detailResult, () => null);
160 const current = get(state);
161 const seed = detail?.commentsCursor ?? null;
162 const older = current.older?.seed === seed ? current.older : null;
163 const nextCursor = older ? older.nextCursor : seed;
164 return {
165 comments: detail?.comments ?? [],
166 seed,
167 older,
168 nextCursor,
169 loadingOlder: current.loadingOlder,
170 unavailable: detailResult.waiting || current.refreshing || current.loadingOlder,
171 };
172 });
173 const view = Atom.make((get) => {
174 const { comments, older, nextCursor, loadingOlder, unavailable } = get(page);
175 return {
176 comments: prependIssueComments(comments, older?.comments ?? []),
177 nextCursor,
178 loadingOlder,
179 canLoadOlder: nextCursor !== null && !unavailable,
180 };
181 });
182
183 return {
184 view,
185 /** `read` settles once the detail has been read again, whether or not that read failed. */
186 async refresh(registry: AtomRegistry.AtomRegistry, read: () => Promise<unknown>) {
187 const current = registry.get(state);
188 if (current.refreshing) return;
189 registry.set(state, { ...current, refreshing: true });
190 let succeeded = false;
191 try {
192 await read();
193 const result = registry.get(detailAtom);
194 succeeded = result._tag === "Success" && !result.waiting;
195 } finally {
196 const latest = registry.get(state);
197 // A successful read invalidates older pages even when the query reuses unchanged detail.
198 registry.set(
199 state,
200 succeeded
201 ? { ...latest, older: null, refreshing: false, refreshes: latest.refreshes + 1 }
202 : { ...latest, refreshing: false },
203 );
204 }
205 },
206 async loadOlder(
207 registry: AtomRegistry.AtomRegistry,
208 read: (cursor: string) => Promise<AtomCommandResult<IssueCommentsPage, unknown>>,
209 ) {
210 const { seed, older, nextCursor, unavailable } = registry.get(page);
211 if (seed === null || nextCursor === null || unavailable) return;
212 const current = registry.get(state);
213 registry.set(state, { ...current, loadingOlder: true });
214 try {
215 const result = await read(nextCursor);
216 const latest = registry.get(state);
217 if (latest.refreshes !== current.refreshes) return;
218 if (result._tag === "Failure") return result;
219 registry.set(state, {
220 ...latest,
221 older: {
222 seed,
223 comments: prependIssueComments(older?.comments ?? [], result.value.comments),
224 nextCursor: result.value.nextCursor,
225 },
226 });
227 } finally {
228 registry.set(state, { ...registry.get(state), loadingOlder: false });
229 }
230 },
231 };
232}
233
234type IssueListRefreshMode = "manual" | "background";
235
236/**
237 * Every read goes to a tracker API over the environment, so results are reused for a short while
238 * and refreshed explicitly. Mutations run serially per environment: changes to one issue are
239 * order-sensitive. Each confirmed write refreshes the detail it touched; the list is refreshed by
240 * the page, which knows which listings it is showing.
241 */
242export function createIssueEnvironmentAtoms<R, E>(
243 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
244) {
245 const commandScheduler = createAtomCommandScheduler();
246 const serialPerEnvironment = {
247 mode: "serial",
248 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
249 } as const;
250 // Atoms owed an explicit refresh: their next read asks the server to skip what it shares.
251 const pendingRefreshes = new WeakMap<
252 AtomRegistry.AtomRegistry,
253 WeakMap<Atom.Atom<unknown>, symbol>
254 >();
255 const owe = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<unknown>) => {
256 let pending = pendingRefreshes.get(registry);
257 if (pending === undefined) {
258 pending = new WeakMap();
259 pendingRefreshes.set(registry, pending);
260 }
261 pending.set(atom, Symbol());
262 };
263 const readOwing = Effect.fn("IssueEnvironment.readOwing")(function* <A, E, R>(
264 atom: Atom.Atom<unknown>,
265 read: (refresh: boolean) => Effect.Effect<A, E, R>,
266 ) {
267 const pending = pendingRefreshes.get(yield* AtomRegistry.AtomRegistry);
268 const intent = pending?.get(atom);
269 if (pending === undefined || intent === undefined) return yield* read(false);
270 return yield* read(true).pipe(
271 // Invalidation interrupts the read; its replacement still owes the explicit refresh.
272 Effect.onExit((exit) =>
273 Effect.sync(() => {
274 if (!Exit.hasInterrupts(exit) && pending.get(atom) === intent) pending.delete(atom);
275 }),
276 ),
277 );
278 });
279 type DetailRequest = ReturnType<typeof request<typeof WS_METHODS.issuesDetail>>;
280 const detail = createEnvironmentQueryAtomFamily(runtime, {
281 label: "environment-data:issues:detail",
282 staleTimeMs: 30_000,
283 execute: Effect.fnUntraced(function* (
284 input: IssueRef,
285 ): Effect.fn.Return<
286 IssueDetail,
287 Effect.Error<DetailRequest>,
288 Effect.Services<DetailRequest> | AtomRegistry.AtomRegistry
289 > {
290 const {
291 target: { environmentId },
292 } = yield* EnvironmentSupervisor.EnvironmentSupervisor;
293 return yield* readOwing(detail({ environmentId, input }), (refresh) =>
294 request(WS_METHODS.issuesDetail, refresh ? { ...input, refresh } : input),
295 );
296 }),
297 });
298 const detailRef = ({ projectId, tracker, host, scope, key }: IssueRef): IssueRef => ({
299 projectId,
300 tracker,
301 ...(host === undefined ? {} : { host }),
302 scope,
303 key,
304 });
305 const refreshDetail = (
306 { environmentId, input }: { readonly environmentId: EnvironmentId; readonly input: IssueRef },
307 registry: AtomRegistry.AtomRegistry,
308 ) => Effect.sync(() => registry.refresh(detail({ environmentId, input: detailRef(input) })));
309 const linkedThreadSignals = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
310 label: "environment-data:issues:linked-thread-refreshes",
311 tag: WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes,
312 });
313 type ListRequest = ReturnType<typeof request<typeof WS_METHODS.issuesList>>;
314 const listQuery = createEnvironmentQueryAtomFamily(runtime, {
315 label: "environment-data:issues:list",
316 staleTimeMs: 30_000,
317 execute: Effect.fnUntraced(function* (
318 input: IssueListInput,
319 ): Effect.fn.Return<
320 IssueListResult,
321 Effect.Error<ListRequest>,
322 Effect.Services<ListRequest> | AtomRegistry.AtomRegistry
323 > {
324 const {
325 target: { environmentId },
326 } = yield* EnvironmentSupervisor.EnvironmentSupervisor;
327 return yield* readOwing(list({ environmentId, input }), (refresh) =>
328 request(WS_METHODS.issuesList, refresh ? { ...input, refresh } : input),
329 );
330 }),
331 });
332 // An issue must carry every label asked for, so their order is not part of the listing's key.
333 const list = ({ environmentId, input }: IssueListTarget) =>
334 listQuery({
335 environmentId,
336 input: input.labels === undefined ? input : { ...input, labels: [...input.labels].sort() },
337 });
338 return {
339 /** The threads an issue is linked to, reread when the server signals a link changed. */
340 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
341 label: "environment-data:issues:linked-threads",
342 tag: WS_METHODS.issuesLinkedThreads,
343 staleTimeMs: 0,
344 refreshTrigger: ({ environmentId }) => linkedThreadSignals({ environmentId, input: {} }),
345 }),
346 list,
347 refreshList(
348 registry: AtomRegistry.AtomRegistry,
349 target: IssueListTarget,
350 mode: IssueListRefreshMode,
351 ) {
352 const atom = list(target);
353 if (mode === "manual") owe(registry, atom);
354 registry.refresh(atom);
355 },
356 /**
357 * A continuation of the listing, run as a command rather than read as a query: a page is
358 * asked for once and laid over the rows held, and a refresh of the first page forgets it.
359 */
360 listPage: createEnvironmentRpcCommand(runtime, {
361 label: "environment-data:issues:list-page",
362 tag: WS_METHODS.issuesList,
363 scheduler: commandScheduler,
364 concurrency: {
365 mode: "singleFlight",
366 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
367 },
368 }),
369 detail,
370 /** Marks a detail atom so its next read skips the server's shared copy of the issue. */
371 oweDetailRefresh: owe,
372 /** Older comments past the cursor the detail handed over; the panel prepends what arrives. */
373 comments: createEnvironmentRpcCommand(runtime, {
374 label: "environment-data:issues:comments",
375 tag: WS_METHODS.issuesComments,
376 scheduler: commandScheduler,
377 concurrency: {
378 mode: "singleFlight",
379 key: ({ environmentId, input }) =>
380 JSON.stringify([environmentId, input.projectId, input.scope, input.key, input.cursor]),
381 },
382 }),
383 /** Read when the composer opens: what a scope offers a new issue changes with a commit. */
384 templates: createEnvironmentRpcQueryAtomFamily(runtime, {
385 label: "environment-data:issues:templates",
386 tag: WS_METHODS.issuesTemplates,
387 staleTimeMs: 5 * 60_000,
388 }),
389 /** Read when a label or assignee picker opens, not with every issue. */
390 candidates: createEnvironmentRpcQueryAtomFamily(runtime, {
391 label: "environment-data:issues:candidates",
392 tag: WS_METHODS.issuesCandidates,
393 staleTimeMs: 60_000,
394 }),
395 create: createEnvironmentRpcCommand(runtime, {
396 label: "environment-data:issues:create",
397 tag: WS_METHODS.issuesCreate,
398 scheduler: commandScheduler,
399 concurrency: serialPerEnvironment,
400 }),
401 comment: createEnvironmentRpcCommand(runtime, {
402 label: "environment-data:issues:comment",
403 tag: WS_METHODS.issuesComment,
404 scheduler: commandScheduler,
405 concurrency: serialPerEnvironment,
406 onSuccess: refreshDetail,
407 }),
408 update: createEnvironmentRpcCommand(runtime, {
409 label: "environment-data:issues:update",
410 tag: WS_METHODS.issuesUpdate,
411 scheduler: commandScheduler,
412 concurrency: serialPerEnvironment,
413 onSuccess: refreshDetail,
414 }),
415 setState: createEnvironmentRpcCommand(runtime, {
416 label: "environment-data:issues:set-state",
417 tag: WS_METHODS.issuesSetState,
418 scheduler: commandScheduler,
419 concurrency: serialPerEnvironment,
420 onSuccess: refreshDetail,
421 }),
422 react: createEnvironmentRpcCommand(runtime, {
423 label: "environment-data:issues:react",
424 tag: WS_METHODS.issuesReact,
425 scheduler: commandScheduler,
426 concurrency: serialPerEnvironment,
427 onSuccess: refreshDetail,
428 }),
429 };
430}
431
432export interface IssueListTarget {
433 readonly environmentId: EnvironmentId;
434 readonly input: IssueListInput;
435}
436
437export interface MergedIssueList {
438 /** One answer per environment that has one, in target order. */
439 readonly answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>;
440 /** The first environment that failed outright; the others may still have answered. */
441 readonly error: string | null;
442 readonly isPending: boolean;
443}
444
445const NO_ISSUE_LISTS: MergedIssueList = { answers: [], error: null, isPending: false };
446
447function refreshFailed<Target, A, E>(
448 registry: AtomRegistry.AtomRegistry,
449 targets: ReadonlyArray<Target>,
450 query: (target: Target) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
451) {
452 for (const target of targets) {
453 const atom = query(target);
454 const result = registry.get(atom);
455 if (result._tag === "Failure" && !result.waiting) registry.refresh(atom);
456 }
457}
458
459/**
460 * One listing read across every environment at once: React cannot subscribe to a list of atoms
461 * whose length changes, so the fan-out lives in one derived atom keyed by the targets. An
462 * environment that fails contributes nothing rather than blanking the list. Retry reloads only
463 * the environments that failed, so a read still in flight elsewhere is not restarted.
464 */
465export function createMergedIssueListAtoms<E>(
466 {
467 list,
468 refreshList,
469 }: {
470 readonly list: (
471 target: IssueListTarget,
472 ) => Atom.Atom<AsyncResult.AsyncResult<IssueListResult, E>>;
473 readonly refreshList: (
474 registry: AtomRegistry.AtomRegistry,
475 target: IssueListTarget,
476 mode: IssueListRefreshMode,
477 ) => void;
478 },
479 formatError: (cause: Cause.Cause<E>) => string,
480) {
481 const empty = Atom.make(NO_ISSUE_LISTS).pipe(Atom.withLabel("issues:merged-list:empty"));
482 const family = Atom.family((key: string) =>
483 Atom.make((get): MergedIssueList => {
484 const answers: Array<readonly [EnvironmentId, IssueListResult]> = [];
485 let error: string | null = null;
486 let isPending = false;
487 for (const target of JSON.parse(key) as ReadonlyArray<IssueListTarget>) {
488 const result = get(list(target));
489 isPending ||= result.waiting;
490 if (result._tag === "Failure" && error === null) error = formatError(result.cause);
491 const value = Option.getOrNull(AsyncResult.value(result));
492 if (value !== null) answers.push([target.environmentId, value]);
493 }
494 return { answers, error, isPending };
495 }).pipe(Atom.withLabel(`issues:merged-list:${key}`)),
496 );
497 const refresh = (
498 registry: AtomRegistry.AtomRegistry,
499 targets: ReadonlyArray<IssueListTarget>,
500 mode: IssueListRefreshMode,
501 ) => {
502 for (const target of targets) refreshList(registry, target, mode);
503 };
504 // The targets behind each listing atom, so a write made elsewhere can refresh the ones still
505 // shown. Weak, so a closed search goes with its atom once the registry drops it.
506 const targetsOf = new WeakMap<Atom.Atom<MergedIssueList>, ReadonlyArray<IssueListTarget>>();
507 return {
508 atom: (targets: ReadonlyArray<IssueListTarget>) => {
509 if (targets.length === 0) return empty;
510 const atom = family(JSON.stringify(targets));
511 targetsOf.set(atom, targets);
512 return atom;
513 },
514 refresh,
515 retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray<IssueListTarget>) =>
516 refreshFailed(registry, targets, list),
517 /** Refreshes each listing of `environmentId` that something still reads. */
518 refreshEnvironment: (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => {
519 for (const node of registry.getNodes().values()) {
520 const targets = targetsOf.get(node.atom);
521 if (targets === undefined) continue;
522 refresh(
523 registry,
524 targets.filter((target) => target.environmentId === environmentId),
525 "background",
526 );
527 }
528 },
529 };
530}
531
532export interface IssueCandidatesTarget {
533 readonly environmentId: EnvironmentId;
534 readonly input: IssueScopeRef;
535}
536
537/** What a list filter can offer: the labels and people of every scope asked, each named once. */
538export interface MergedIssueCandidates {
539 readonly labels: ReadonlyArray<IssueLabelCandidate>;
540 readonly assignees: ReadonlyArray<IssueAssigneeCandidate>;
541 readonly error: string | null;
542 readonly isPending: boolean;
543 readonly truncated: boolean;
544}
545
546const NO_ISSUE_CANDIDATES: MergedIssueCandidates = {
547 labels: [],
548 assignees: [],
549 error: null,
550 isPending: false,
551 truncated: false,
552};
553
554/**
555 * Fans out like the merged listing: a scope that fails leaves the others' answers in place.
556 * Retry skips scopes that already answered or still have a request in flight.
557 */
558export function createMergedIssueCandidatesAtoms<E>(
559 candidates: (
560 target: IssueCandidatesTarget,
561 ) => Atom.Atom<AsyncResult.AsyncResult<IssueCandidates, E>>,
562 formatError: (cause: Cause.Cause<E>) => string,
563) {
564 const empty = Atom.make(NO_ISSUE_CANDIDATES).pipe(Atom.withLabel("issues:candidates:empty"));
565 const family = Atom.family((key: string) =>
566 Atom.make((get): MergedIssueCandidates => {
567 const labels = new Map<string, IssueLabelCandidate>();
568 const assignees = new Map<string, IssueAssigneeCandidate>();
569 let error: string | null = null;
570 let isPending = false;
571 let truncated = false;
572 for (const target of JSON.parse(key) as ReadonlyArray<IssueCandidatesTarget>) {
573 const result = get(candidates(target));
574 isPending ||= result.waiting;
575 if (result._tag === "Failure" && error === null) error = formatError(result.cause);
576 const value = Option.getOrNull(AsyncResult.value(result));
577 if (value === null) continue;
578 truncated ||= value.truncated;
579 for (const label of value.labels)
580 if (!labels.has(label.name)) labels.set(label.name, label);
581 for (const actor of value.assignees)
582 if (!assignees.has(actor.login)) assignees.set(actor.login, actor);
583 }
584 return {
585 labels: [...labels.values()].sort((a, b) => a.name.localeCompare(b.name)),
586 assignees: [...assignees.values()].sort((a, b) => a.login.localeCompare(b.login)),
587 error,
588 isPending,
589 truncated,
590 };
591 }).pipe(Atom.withLabel(`issues:candidates:${key}`)),
592 );
593 return {
594 atom: (targets: ReadonlyArray<IssueCandidatesTarget>) =>
595 targets.length === 0 ? empty : family(JSON.stringify(targets)),
596 retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray<IssueCandidatesTarget>) =>
597 refreshFailed(registry, targets, candidates),
598 };
599}