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

vcs.ts

347 lines11.8 KB

1import {
2 type EnvironmentId,
3 type VcsListRefsInput,
4 type VcsListRefsResult,
5 type VcsStatusResult,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Result from "effect/Result";
13import * as Schedule from "effect/Schedule";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import { Atom, AtomRegistry } from "effect/unstable/reactivity";
17​
18import { createEnvironmentRpcCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
19import type { EnvironmentRegistry } from "../connection/registry.ts";
20import { EnvironmentSupervisor } from "../connection/supervisor.ts";
21import { safeErrorLogAttributes } from "../errors/safeLog.ts";
22import { EnvironmentCacheStore } from "../platform/persistence.ts";
23import { request, subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
24import { followStreamInEnvironment } from "./runtime.ts";
25import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts";
26import {
27 invalidateCachedVcsRefs,
28 vcsRefsCacheStateAtom,
29 withVcsRefsPersistenceLock,
30} from "./vcsRefInvalidation.ts";
31​
32const OFFLINE_BRANCH_LIST_LIMIT = 100;
33const VCS_REFS_IDLE_TTL_MS = 30_000;
34// Rows keep the last status they rendered, so the live stream only needs a
35// short grace period when virtualization or scrolling releases its consumer.
36const VCS_STATUS_IDLE_TTL_MS = 10_000;
37const VCS_REFS_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(
38 Schedule.modifyDelay(({ duration }) =>
39 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
40 ),
41);
42​
43function canUseVcsRefsCache(input: VcsListRefsInput): boolean {
44 return (
45 input.query === undefined &&
46 input.cursor === undefined &&
47 input.includeMatchingRemoteRefs === undefined &&
48 input.refKind === undefined &&
49 input.limit === OFFLINE_BRANCH_LIST_LIMIT
50 );
52​
53export const commitVcsRefsRefresh = Effect.fn("CachedVcsRefsState.commitRefresh")(function* (
54 registry: AtomRegistry.AtomRegistry,
55 cache: EnvironmentCacheStore["Service"],
56 input: {
57 readonly environmentId: EnvironmentId;
58 readonly cwd: string;
59 readonly refs: VcsListRefsResult;
60 readonly expectedRevision: number;
61 readonly persist: boolean;
62 },
63) {
64 return yield* withVcsRefsPersistenceLock(
65 input.environmentId,
66 Effect.gen(function* () {
67 const stateAtom = vcsRefsCacheStateAtom({ environmentId: input.environmentId });
68 const state = registry.get(stateAtom);
69 if (state.revision !== input.expectedRevision) {
70 return false;
71 }
72 let persistedCacheReadable = state.persistedCacheReadable;
73 if (input.persist) {
74 if (!persistedCacheReadable) {
75 persistedCacheReadable = yield* cache.clearVcsRefs(input.environmentId).pipe(
76 Effect.as(true),
77 Effect.catch((error) =>
78 Effect.logWarning("Could not recover invalidated cached Git refs.").pipe(
79 Effect.annotateLogs({
80 environmentId: input.environmentId,
81 cwd: input.cwd,
82 ...safeErrorLogAttributes(error),
83 }),
84 Effect.as(false),
85 ),
86 ),
87 );
88 }
89 yield* cache.saveVcsRefs(input.environmentId, input.cwd, input.refs).pipe(
90 Effect.catch((error) =>
91 Effect.logWarning("Could not persist cached Git refs.").pipe(
92 Effect.annotateLogs({
93 environmentId: input.environmentId,
94 cwd: input.cwd,
95 ...safeErrorLogAttributes(error),
96 }),
97 ),
98 ),
99 );
100 if (persistedCacheReadable !== state.persistedCacheReadable) {
101 registry.update(stateAtom, (current) =>
102 current.revision === input.expectedRevision
103 ? { ...current, persistedCacheReadable }
104 : current,
105 );
106 }
107 }
108 return true;
109 }),
110 );
111});
112​
113/**
114 * Retains the last unfiltered branch-list response for the new-task picker.
115 * Filtered or paginated lists intentionally stay live-only: treating a
116 * partial result as a complete offline list would make branch selection
117 * misleading.
118 */
119export const makeCachedVcsRefsChanges = Effect.fn("CachedVcsRefsState.makeChanges")(function* (
120 input: VcsListRefsInput,
121 expectedRevision?: number,
122 registry?: AtomRegistry.AtomRegistry,
123 persistedCacheReadable = true,
124) {
125 const supervisor = yield* EnvironmentSupervisor;
126 const cache = yield* EnvironmentCacheStore;
127 const environmentId = supervisor.target.environmentId;
128 const useCache = canUseVcsRefsCache(input);
129 const cached =
130 useCache && persistedCacheReadable
131 ? yield* cache.loadVcsRefs(environmentId, input.cwd).pipe(
132 Effect.catch((error) =>
133 Effect.logWarning("Could not load cached Git refs.").pipe(
134 Effect.annotateLogs({
135 environmentId,
136 cwd: input.cwd,
137 ...safeErrorLogAttributes(error),
138 }),
139 Effect.as(Option.none<VcsListRefsResult>()),
140 ),
141 ),
142 )
143 : Option.none<VcsListRefsResult>();
144 const refresh = Effect.fn("CachedVcsRefsState.refresh")(function* () {
145 const refs = yield* request(WS_METHODS.vcsListRefs, input).pipe(
146 Effect.provideService(EnvironmentSupervisor, supervisor),
147 );
148 const persist = cache.saveVcsRefs(environmentId, input.cwd, refs).pipe(
149 Effect.catch((error) =>
150 Effect.logWarning("Could not persist cached Git refs.").pipe(
151 Effect.annotateLogs({
152 environmentId,
153 cwd: input.cwd,
154 ...safeErrorLogAttributes(error),
155 }),
156 ),
157 ),
158 );
159 if (expectedRevision === undefined || registry === undefined) {
160 if (useCache) yield* persist;
161 return Option.some(refs);
162 }
163 const committed = yield* commitVcsRefsRefresh(registry, cache, {
164 environmentId,
165 cwd: input.cwd,
166 refs,
167 expectedRevision,
168 persist: useCache,
169 });
170 return committed ? Option.some(refs) : Option.none<VcsListRefsResult>();
171 });
172​
173 const cachedRefs = Stream.fromEffect(Effect.succeed(cached)).pipe(
174 Stream.filterMap((refs) =>
175 Option.match(refs, {
176 onNone: () => Result.failVoid,
177 onSome: Result.succeed,
178 }),
179 ),
180 );
181 const refreshedRefs = Stream.concat(
182 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
183 SubscriptionRef.changes(supervisor.state),
184 ).pipe(
185 Stream.map((connection) => (connection.phase === "connected" ? connection.generation : null)),
186 Stream.changes,
187 Stream.switchMap((generation) =>
188 generation === null
189 ? Stream.empty
190 : Stream.fromEffect(
191 refresh().pipe(
192 Effect.tapError((error) =>
193 Effect.logWarning("Could not refresh Git refs.").pipe(
194 Effect.annotateLogs({
195 environmentId,
196 cwd: input.cwd,
197 ...safeErrorLogAttributes(error),
198 }),
199 ),
200 ),
201 ),
202 ).pipe(
203 Stream.retry(VCS_REFS_RETRY_SCHEDULE),
204 Stream.filterMap((refs) =>
205 Option.match(refs, {
206 onNone: () => Result.failVoid,
207 onSome: Result.succeed,
208 }),
209 ),
210 ),
211 ),
212 );
213​
214 return Stream.concat(cachedRefs, refreshedRefs);
215});
216​
217function cachedVcsRefsChanges(
218 environmentId: EnvironmentId,
219 input: VcsListRefsInput,
220 expectedRevision: number,
221 persistedCacheReadable: boolean,
222) {
223 return followStreamInEnvironment(
224 environmentId,
225 Stream.unwrap(
226 Effect.gen(function* () {
227 const registry = yield* AtomRegistry.AtomRegistry;
228 return yield* makeCachedVcsRefsChanges(
229 input,
230 expectedRevision,
231 registry,
232 persistedCacheReadable,
233 );
234 }),
235 ),
236 );
238​
239export function createVcsEnvironmentAtoms<R, E>(
240 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
241) {
242 /**
243 * One flat family on purpose: families hold entries via WeakRef, so a nested
244 * per-environment family can be collected between lookups, dropping every
245 * cached page atom and collapsing paginated ref lists mid-scroll.
246 */
247 const listRefsFamily = Atom.family((key: string) => {
248 const [environmentId, input] = JSON.parse(key) as [EnvironmentId, VcsListRefsInput];
249 return runtime
250 .atom((get) => {
251 const state = get(vcsRefsCacheStateAtom({ environmentId }));
252 return cachedVcsRefsChanges(
253 environmentId,
254 input,
255 state.revision,
256 state.persistedCacheReadable,
257 );
258 })
259 .pipe(
260 Atom.setIdleTTL(VCS_REFS_IDLE_TTL_MS),
261 Atom.withLabel(`environment-data:vcs:list-refs:${key}`),
262 );
263 });
264 const listRefs = (target: {
265 readonly environmentId: EnvironmentId;
266 readonly input: VcsListRefsInput;
267 }) => listRefsFamily(JSON.stringify([target.environmentId, target.input]));
268 const invalidateRefs = (
269 target: { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } },
270 registry: AtomRegistry.AtomRegistry,
271 ) =>
272 invalidateCachedVcsRefs(registry, {
273 environmentId: target.environmentId,
274 cwd: target.input.cwd,
275 });
276​
277 return {
278 listRefs,
279 status: createEnvironmentSubscriptionAtomFamily(runtime, {
280 label: "environment-data:vcs:status",
281 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
282 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
283 subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
284 Stream.mapAccum(
285 () => null as VcsStatusResult | null,
286 (current, event) => {
287 const next = applyGitStatusStreamEvent(current, event);
288 return [next, [next]] as const;
289 },
290 ),
291 ),
292 }),
293 pull: createEnvironmentRpcCommand(runtime, {
294 label: "environment-data:vcs:pull",
295 tag: WS_METHODS.vcsPull,
296 scheduler: vcsCommandScheduler,
297 concurrency: vcsCommandConcurrency,
298 onSettled: invalidateRefs,
299 }),
300 refreshStatus: createEnvironmentRpcCommand(runtime, {
301 label: "environment-data:vcs:refresh-status",
302 tag: WS_METHODS.vcsRefreshStatus,
303 scheduler: vcsCommandScheduler,
304 concurrency: vcsCommandConcurrency,
305 onSettled: invalidateRefs,
306 }),
307 createWorktree: createEnvironmentRpcCommand(runtime, {
308 label: "environment-data:vcs:create-worktree",
309 tag: WS_METHODS.vcsCreateWorktree,
310 scheduler: vcsCommandScheduler,
311 concurrency: vcsCommandConcurrency,
312 onSettled: invalidateRefs,
313 }),
314 removeWorktree: createEnvironmentRpcCommand(runtime, {
315 label: "environment-data:vcs:remove-worktree",
316 tag: WS_METHODS.vcsRemoveWorktree,
317 scheduler: vcsCommandScheduler,
318 concurrency: vcsCommandConcurrency,
319 onSettled: invalidateRefs,
320 }),
321 createRef: createEnvironmentRpcCommand(runtime, {
322 label: "environment-data:vcs:create-ref",
323 tag: WS_METHODS.vcsCreateRef,
324 scheduler: vcsCommandScheduler,
325 concurrency: vcsCommandConcurrency,
326 onSettled: invalidateRefs,
327 }),
328 switchRef: createEnvironmentRpcCommand(runtime, {
329 label: "environment-data:vcs:switch-ref",
330 tag: WS_METHODS.vcsSwitchRef,
331 scheduler: vcsCommandScheduler,
332 concurrency: vcsCommandConcurrency,
333 onSettled: invalidateRefs,
334 }),
335 init: createEnvironmentRpcCommand(runtime, {
336 label: "environment-data:vcs:init",
337 tag: WS_METHODS.vcsInit,
338 scheduler: vcsCommandScheduler,
339 concurrency: vcsCommandConcurrency,
340 onSettled: invalidateRefs,
341 }),
342 };
344​
345export * from "./gitActions.ts";
346export * from "./vcsAction.ts";
347export * from "./vcsRef.ts";