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

vcs.ts

415 lines14.5 KB

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