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