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