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

issues.ts

522 lines19.9 KB

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