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