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

vcs.ts

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