Open History to see the last commit
1import {
2 type EnvironmentId,
3 type VcsListRefsInput,
4 type VcsListRefsResult,
5 type VcsRefreshStatusResult,
6 type VcsStatusResult,
7 WS_METHODS,
8} from "@t3tools/contracts";
9import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Option from "effect/Option";
14import * as Result from "effect/Result";
15import * as Schedule from "effect/Schedule";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import { Atom, AtomRegistry } from "effect/reactivity";
19
20import {
21 createEnvironmentRpcCommand,
22 createEnvironmentRpcSubscriptionAtomFamily,
23 createEnvironmentSubscriptionAtomFamily,
24} from "./runtime.ts";
25import type { EnvironmentRegistry } from "../connection/registry.ts";
26import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27import { safeErrorLogAttributes } from "../errors/safeLog.ts";
28import * as Persistence from "../platform/persistence.ts";
29import {
30 request,
31 requestGuarded,
32 subscribe,
33 subscribeVcsBranch,
34 refreshVcsBranch,
35 type EnvironmentRpcInput,
36} from "../rpc/client.ts";
37import { followStreamInEnvironment } from "./runtime.ts";
38import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts";
39import {
40 invalidateCachedVcsRefs,
41 invalidateCachedVcsRefsIfChanged,
42 vcsRefsCacheStateAtom,
43 withVcsRefsPersistenceLock,
44} from "./vcsRefInvalidation.ts";
45
46// Share freshness across search and pagination keys, but keep it local to this registry.
47const serverRefsRevisionAtom = Atom.family((_key: string) => Atom.make(0).pipe(Atom.keepAlive));
48
49type VcsRefsTarget = {
50 readonly environmentId: EnvironmentId;
51 readonly input: { readonly cwd: string };
52};
53
54const OFFLINE_BRANCH_LIST_LIMIT = 100;
55const VCS_REFS_IDLE_TTL_MS = 30_000;
56const VCS_STATUS_IDLE_TTL_MS = 10_000;
57const VCS_REFS_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(
58 Schedule.modifyDelay(({ duration }) =>
59 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
60 ),
61);
62
63function canUseVcsRefsCache(input: VcsListRefsInput): boolean {
64 return (
65 input.query === undefined &&
66 input.cursor === undefined &&
67 input.includeMatchingRemoteRefs === undefined &&
68 input.refKind === undefined &&
69 input.limit === OFFLINE_BRANCH_LIST_LIMIT
70 );
71}
72
73export const commitVcsRefsRefresh = Effect.fn("CachedVcsRefsState.commitRefresh")(function* (
74 registry: AtomRegistry.AtomRegistry,
75 cache: Persistence.EnvironmentCacheStore["Service"],
76 input: {
77 readonly environmentId: EnvironmentId;
78 readonly cwd: string;
79 readonly refs: VcsListRefsResult;
80 readonly expectedRevision: number;
81 readonly persist: boolean;
82 },
83) {
84 return yield* withVcsRefsPersistenceLock(
85 input.environmentId,
86 Effect.gen(function* () {
87 const stateAtom = vcsRefsCacheStateAtom({ environmentId: input.environmentId });
88 const state = registry.get(stateAtom);
89 if (state.revision !== input.expectedRevision) {
90 return false;
91 }
92 let persistedCacheReadable = state.persistedCacheReadable;
93 if (input.persist) {
94 if (!persistedCacheReadable) {
95 persistedCacheReadable = yield* cache.clearVcsRefs(input.environmentId).pipe(
96 Effect.as(true),
97 Effect.catch((error) =>
98 Effect.logWarning("Could not recover invalidated cached Git refs.").pipe(
99 Effect.annotateLogs({
100 environmentId: input.environmentId,
101 cwd: input.cwd,
102 ...safeErrorLogAttributes(error),
103 }),
104 Effect.as(false),
105 ),
106 ),
107 );
108 }
109 yield* cache.saveVcsRefs(input.environmentId, input.cwd, input.refs).pipe(
110 Effect.catch((error) =>
111 Effect.logWarning("Could not persist cached Git refs.").pipe(
112 Effect.annotateLogs({
113 environmentId: input.environmentId,
114 cwd: input.cwd,
115 ...safeErrorLogAttributes(error),
116 }),
117 ),
118 ),
119 );
120 if (persistedCacheReadable !== state.persistedCacheReadable) {
121 registry.update(stateAtom, (current) =>
122 current.revision === input.expectedRevision
123 ? { ...current, persistedCacheReadable }
124 : current,
125 );
126 }
127 }
128 return true;
129 }),
130 );
131});
132
133/**
134 * Filtered or paginated lists intentionally stay live-only: treating a
135 * partial result as a complete offline list would make branch selection
136 * misleading.
137 */
138export const makeCachedVcsRefsChanges = Effect.fn("CachedVcsRefsState.makeChanges")(function* (
139 input: VcsListRefsInput,
140 expectedRevision?: number,
141 registry?: AtomRegistry.AtomRegistry,
142 persistedCacheReadable = true,
143) {
144 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
145 const cache = yield* Persistence.EnvironmentCacheStore;
146 const environmentId = supervisor.target.environmentId;
147 const useCache = canUseVcsRefsCache(input);
148 const cached =
149 useCache && persistedCacheReadable
150 ? yield* cache.loadVcsRefs(environmentId, input.cwd).pipe(
151 Effect.catch((error) =>
152 Effect.logWarning("Could not load cached Git refs.").pipe(
153 Effect.annotateLogs({
154 environmentId,
155 cwd: input.cwd,
156 ...safeErrorLogAttributes(error),
157 }),
158 Effect.as(Option.none<VcsListRefsResult>()),
159 ),
160 ),
161 )
162 : Option.none<VcsListRefsResult>();
163 const refresh = Effect.fn("CachedVcsRefsState.refresh")(function* () {
164 const revisionAtom = serverRefsRevisionAtom(
165 `${environmentId.length}:${environmentId}${input.cwd}`,
166 );
167 const bypassServerSnapshot =
168 expectedRevision !== undefined &&
169 registry !== undefined &&
170 expectedRevision > registry.get(revisionAtom);
171 const refs = yield* request(
172 WS_METHODS.vcsListRefs,
173 bypassServerSnapshot ? { ...input, refresh: true } : input,
174 ).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
175 const persist = cache.saveVcsRefs(environmentId, input.cwd, refs).pipe(
176 Effect.catch((error) =>
177 Effect.logWarning("Could not persist cached Git refs.").pipe(
178 Effect.annotateLogs({
179 environmentId,
180 cwd: input.cwd,
181 ...safeErrorLogAttributes(error),
182 }),
183 ),
184 ),
185 );
186 if (expectedRevision === undefined || registry === undefined) {
187 if (useCache) yield* persist;
188 return Option.some(refs);
189 }
190 const committed = yield* commitVcsRefsRefresh(registry, cache, {
191 environmentId,
192 cwd: input.cwd,
193 refs,
194 expectedRevision,
195 persist: useCache,
196 });
197 if (committed && bypassServerSnapshot) registry.set(revisionAtom, expectedRevision);
198 return committed ? Option.some(refs) : Option.none<VcsListRefsResult>();
199 });
200
201 const cachedRefs = Stream.fromEffect(Effect.succeed(cached)).pipe(
202 Stream.filterMap((refs) =>
203 Option.match(refs, {
204 onNone: () => Result.failVoid,
205 onSome: Result.succeed,
206 }),
207 ),
208 );
209 const refreshedRefs = SubscriptionRef.changes(supervisor.session).pipe(
210 Stream.map(Option.getOrNull),
211 Stream.changes,
212 Stream.switchMap((session) =>
213 session === null
214 ? Stream.empty
215 : Stream.fromEffect(
216 refresh().pipe(
217 // Session removal can precede switchMap cancelling this refresh.
218 Effect.catchTags({ EnvironmentRpcUnavailableError: () => Effect.never }),
219 Effect.tapError((error) =>
220 Effect.logWarning("Could not refresh Git refs.").pipe(
221 Effect.annotateLogs({
222 environmentId,
223 cwd: input.cwd,
224 ...safeErrorLogAttributes(error),
225 }),
226 ),
227 ),
228 ),
229 ).pipe(
230 Stream.retry(VCS_REFS_RETRY_SCHEDULE),
231 Stream.filterMap((refs) =>
232 Option.match(refs, {
233 onNone: () => Result.failVoid,
234 onSome: Result.succeed,
235 }),
236 ),
237 ),
238 ),
239 );
240
241 return Stream.concat(cachedRefs, refreshedRefs);
242});
243
244function cachedVcsRefsChanges(
245 environmentId: EnvironmentId,
246 input: VcsListRefsInput,
247 expectedRevision: number,
248 persistedCacheReadable: boolean,
249) {
250 return followStreamInEnvironment(
251 environmentId,
252 Stream.unwrap(
253 Effect.gen(function* () {
254 const registry = yield* AtomRegistry.AtomRegistry;
255 return yield* makeCachedVcsRefsChanges(
256 input,
257 expectedRevision,
258 registry,
259 persistedCacheReadable,
260 );
261 }),
262 ),
263 );
264}
265
266// A background fetch moves refs without any client command, so lists already open reload on it.
267const reloadRefsWhenRevisionMoves =
268 (cwd: string) =>
269 <E, R>(statuses: Stream.Stream<VcsStatusResult, E, R>) =>
270 Stream.unwrap(
271 Effect.gen(function* () {
272 const registry = yield* AtomRegistry.AtomRegistry;
273 const { environmentId } = (yield* EnvironmentSupervisor.EnvironmentSupervisor).target;
274 let started = false;
275 let seen: number | undefined;
276 return statuses.pipe(
277 Stream.tap((status) => {
278 const previous = seen;
279 seen = status.refsRevision ?? previous;
280 // A status cached before any poll has no revision, so the first one can follow a fetch.
281 const moved = started && seen !== previous;
282 started = true;
283 return moved ? invalidateCachedVcsRefs(registry, { environmentId, cwd }) : Effect.void;
284 }),
285 );
286 }),
287 );
288
289export function createVcsEnvironmentAtoms<R, E>(
290 runtime: Atom.AtomRuntime<EnvironmentRegistry | Persistence.EnvironmentCacheStore | R, E>,
291) {
292 /**
293 * One flat family on purpose: families hold entries via WeakRef, so a nested
294 * per-environment family can be collected between lookups, dropping every
295 * cached page atom and collapsing paginated ref lists mid-scroll.
296 */
297 const listRefsFamily = Atom.family((key: string) => {
298 const [environmentId, input] = JSON.parse(key) as [EnvironmentId, VcsListRefsInput];
299 return runtime
300 .atom((get) => {
301 const state = get(vcsRefsCacheStateAtom({ environmentId }));
302 return cachedVcsRefsChanges(
303 environmentId,
304 input,
305 state.revision,
306 state.persistedCacheReadable,
307 );
308 })
309 .pipe(
310 Atom.setIdleTTL(VCS_REFS_IDLE_TTL_MS),
311 Atom.withLabel(`environment-data:vcs:list-refs:${key}`),
312 );
313 });
314 const listRefs = (target: {
315 readonly environmentId: EnvironmentId;
316 readonly input: VcsListRefsInput;
317 }) => listRefsFamily(JSON.stringify([target.environmentId, target.input]));
318 const invalidateRefs = (target: VcsRefsTarget, registry: AtomRegistry.AtomRegistry) =>
319 invalidateCachedVcsRefs(registry, {
320 environmentId: target.environmentId,
321 cwd: target.input.cwd,
322 });
323
324 const refreshStatusChangedRefs = {
325 onStart: (target: VcsRefsTarget, registry: AtomRegistry.AtomRegistry) =>
326 registry.get(vcsRefsCacheStateAtom(target)).revision,
327 onSuccess: (
328 target: VcsRefsTarget,
329 registry: AtomRegistry.AtomRegistry,
330 result: VcsRefreshStatusResult,
331 startedAtRevision: number | undefined,
332 ) =>
333 invalidateCachedVcsRefsIfChanged(
334 registry,
335 { environmentId: target.environmentId, cwd: target.input.cwd },
336 result.refsDigest,
337 startedAtRevision,
338 ),
339 };
340 // A failed remote refresh may have fetched refs before failing; a local-only read cannot.
341 const refreshStatusInvalidation = {
342 ...refreshStatusChangedRefs,
343 onSettled: (
344 target: VcsRefsTarget,
345 registry: AtomRegistry.AtomRegistry,
346 exit: Exit.Exit<VcsRefreshStatusResult, unknown>,
347 ) => (Exit.isSuccess(exit) ? Effect.void : invalidateRefs(target, registry)),
348 };
349
350 return {
351 listRefs,
352 // An uncached read for decisions that must match the repository now, not
353 // the persisted list a picker renders from.
354 readRefs: createEnvironmentRpcCommand(runtime, {
355 label: "environment-data:vcs:read-refs",
356 tag: WS_METHODS.vcsListRefs,
357 }),
358 branch: createEnvironmentSubscriptionAtomFamily(runtime, {
359 label: "environment-data:vcs:branch",
360 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
361 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsBranch>) =>
362 subscribeVcsBranch(input),
363 }),
364 refreshBranch: createEnvironmentRpcCommand(runtime, {
365 label: "environment-data:vcs:refresh-branch",
366 tag: WS_METHODS.vcsRefreshBranch,
367 execute: refreshVcsBranch,
368 scheduler: vcsCommandScheduler,
369 concurrency: vcsCommandConcurrency,
370 }),
371 status: createEnvironmentSubscriptionAtomFamily(runtime, {
372 label: "environment-data:vcs:status",
373 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
374 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
375 subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
376 Stream.mapAccum(
377 () => null as VcsStatusResult | null,
378 (current, event) => {
379 const next = applyGitStatusStreamEvent(current, event);
380 return [next, [next]] as const;
381 },
382 ),
383 reloadRefsWhenRevisionMoves(input.cwd),
384 ),
385 }),
386 pull: createEnvironmentRpcCommand(runtime, {
387 label: "environment-data:vcs:pull",
388 tag: WS_METHODS.vcsPull,
389 scheduler: vcsCommandScheduler,
390 concurrency: vcsCommandConcurrency,
391 onSettled: invalidateRefs,
392 }),
393 refreshStatus: createEnvironmentRpcCommand(runtime, {
394 label: "environment-data:vcs:refresh-status",
395 tag: WS_METHODS.vcsRefreshStatus,
396 scheduler: vcsCommandScheduler,
397 concurrency: vcsCommandConcurrency,
398 ...refreshStatusInvalidation,
399 }),
400 // Outside the serial queue: it only reads status, and a checkout picked right after opening
401 // the picker must not wait behind that read.
402 refreshLocalStatusForPicker: createEnvironmentRpcCommand(runtime, {
403 label: "environment-data:vcs:refresh-local-status-for-picker",
404 tag: WS_METHODS.vcsRefreshStatus,
405 execute: (input: { readonly cwd: string }) =>
406 requestGuarded(WS_METHODS.vcsRefreshStatus, { cwd: input.cwd, localOnly: true }),
407 ...refreshStatusChangedRefs,
408 }),
409 createWorktree: createEnvironmentRpcCommand(runtime, {
410 label: "environment-data:vcs:create-worktree",
411 tag: WS_METHODS.vcsCreateWorktree,
412 scheduler: vcsCommandScheduler,
413 concurrency: vcsCommandConcurrency,
414 onSettled: invalidateRefs,
415 }),
416 worktreeSetup: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
417 label: "environment-data:vcs:worktree-setup",
418 tag: WS_METHODS.subscribeWorktreeSetup,
419 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
420 }),
421 cancelWorktreeSetup: createEnvironmentRpcCommand(runtime, {
422 label: "environment-data:vcs:cancel-worktree-setup",
423 tag: WS_METHODS.worktreeSetupCancel,
424 }),
425 removeWorktree: createEnvironmentRpcCommand(runtime, {
426 label: "environment-data:vcs:remove-worktree",
427 tag: WS_METHODS.vcsRemoveWorktree,
428 scheduler: vcsCommandScheduler,
429 concurrency: vcsCommandConcurrency,
430 onSettled: invalidateRefs,
431 }),
432 createRef: createEnvironmentRpcCommand(runtime, {
433 label: "environment-data:vcs:create-ref",
434 tag: WS_METHODS.vcsCreateRef,
435 scheduler: vcsCommandScheduler,
436 concurrency: vcsCommandConcurrency,
437 onSettled: invalidateRefs,
438 }),
439 switchRef: createEnvironmentRpcCommand(runtime, {
440 label: "environment-data:vcs:switch-ref",
441 tag: WS_METHODS.vcsSwitchRef,
442 scheduler: vcsCommandScheduler,
443 concurrency: vcsCommandConcurrency,
444 onSettled: invalidateRefs,
445 }),
446 init: createEnvironmentRpcCommand(runtime, {
447 label: "environment-data:vcs:init",
448 tag: WS_METHODS.vcsInit,
449 scheduler: vcsCommandScheduler,
450 concurrency: vcsCommandConcurrency,
451 onSettled: invalidateRefs,
452 }),
453 };
454}
455
456export * from "./gitActions.ts";
457export * from "./vcsAction.ts";
458export * from "./vcsRef.ts";
459export * from "./vcsStatusRevalidation.ts";