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

vcs.ts

363 lines12.4 KB

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 );
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 = SubscriptionRef.changes(supervisor.session).pipe(
183 Stream.map(Option.getOrNull),
184 Stream.changes,
185 Stream.switchMap((session) =>
186 session === null
187 ? Stream.empty
188 : Stream.fromEffect(
189 refresh().pipe(
190 // Session removal can precede switchMap cancelling this refresh.
191 Effect.catchTags({ EnvironmentRpcUnavailableError: () => Effect.never }),
192 Effect.tapError((error) =>
193 Effect.logWarning("Could not refresh Git refs.").pipe(
194 Effect.annotateLogs({
195 environmentId,
196 cwd: input.cwd,
197 ...safeErrorLogAttributes(error),
198 }),
199 ),
200 ),
201 ),
202 ).pipe(
203 Stream.retry(VCS_REFS_RETRY_SCHEDULE),
204 Stream.filterMap((refs) =>
205 Option.match(refs, {
206 onNone: () => Result.failVoid,
207 onSome: Result.succeed,
208 }),
209 ),
210 ),
211 ),
212 );
213​
214 return Stream.concat(cachedRefs, refreshedRefs);
215});
216​
217function cachedVcsRefsChanges(
218 environmentId: EnvironmentId,
219 input: VcsListRefsInput,
220 expectedRevision: number,
221 persistedCacheReadable: boolean,
222) {
223 return followStreamInEnvironment(
224 environmentId,
225 Stream.unwrap(
226 Effect.gen(function* () {
227 const registry = yield* AtomRegistry.AtomRegistry;
228 return yield* makeCachedVcsRefsChanges(
229 input,
230 expectedRevision,
231 registry,
232 persistedCacheReadable,
233 );
234 }),
235 ),
236 );
238​
239export function createVcsEnvironmentAtoms<R, E>(
240 runtime: Atom.AtomRuntime<EnvironmentRegistry | Persistence.EnvironmentCacheStore | R, E>,
241) {
242 /**
243 * One flat family on purpose: families hold entries via WeakRef, so a nested
244 * per-environment family can be collected between lookups, dropping every
245 * cached page atom and collapsing paginated ref lists mid-scroll.
246 */
247 const listRefsFamily = Atom.family((key: string) => {
248 const [environmentId, input] = JSON.parse(key) as [EnvironmentId, VcsListRefsInput];
249 return runtime
250 .atom((get) => {
251 const state = get(vcsRefsCacheStateAtom({ environmentId }));
252 return cachedVcsRefsChanges(
253 environmentId,
254 input,
255 state.revision,
256 state.persistedCacheReadable,
257 );
258 })
259 .pipe(
260 Atom.setIdleTTL(VCS_REFS_IDLE_TTL_MS),
261 Atom.withLabel(`environment-data:vcs:list-refs:${key}`),
262 );
263 });
264 const listRefs = (target: {
265 readonly environmentId: EnvironmentId;
266 readonly input: VcsListRefsInput;
267 }) => listRefsFamily(JSON.stringify([target.environmentId, target.input]));
268 const invalidateRefs = (
269 target: { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } },
270 registry: AtomRegistry.AtomRegistry,
271 ) =>
272 invalidateCachedVcsRefs(registry, {
273 environmentId: target.environmentId,
274 cwd: target.input.cwd,
275 });
276​
277 return {
278 listRefs,
279 // An uncached read for decisions that must match the repository now, not
280 // the persisted list a picker renders from.
281 readRefs: createEnvironmentRpcCommand(runtime, {
282 label: "environment-data:vcs:read-refs",
283 tag: WS_METHODS.vcsListRefs,
284 }),
285 status: createEnvironmentSubscriptionAtomFamily(runtime, {
286 label: "environment-data:vcs:status",
287 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
288 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
289 subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
290 Stream.mapAccum(
291 () => null as VcsStatusResult | null,
292 (current, event) => {
293 const next = applyGitStatusStreamEvent(current, event);
294 return [next, [next]] as const;
295 },
296 ),
297 ),
298 }),
299 pull: createEnvironmentRpcCommand(runtime, {
300 label: "environment-data:vcs:pull",
301 tag: WS_METHODS.vcsPull,
302 scheduler: vcsCommandScheduler,
303 concurrency: vcsCommandConcurrency,
304 onSettled: invalidateRefs,
305 }),
306 refreshStatus: createEnvironmentRpcCommand(runtime, {
307 label: "environment-data:vcs:refresh-status",
308 tag: WS_METHODS.vcsRefreshStatus,
309 scheduler: vcsCommandScheduler,
310 concurrency: vcsCommandConcurrency,
311 onSettled: invalidateRefs,
312 }),
313 createWorktree: createEnvironmentRpcCommand(runtime, {
314 label: "environment-data:vcs:create-worktree",
315 tag: WS_METHODS.vcsCreateWorktree,
316 scheduler: vcsCommandScheduler,
317 concurrency: vcsCommandConcurrency,
318 onSettled: invalidateRefs,
319 }),
320 worktreeSetup: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
321 label: "environment-data:vcs:worktree-setup",
322 tag: WS_METHODS.subscribeWorktreeSetup,
323 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
324 }),
325 cancelWorktreeSetup: createEnvironmentRpcCommand(runtime, {
326 label: "environment-data:vcs:cancel-worktree-setup",
327 tag: WS_METHODS.worktreeSetupCancel,
328 }),
329 removeWorktree: createEnvironmentRpcCommand(runtime, {
330 label: "environment-data:vcs:remove-worktree",
331 tag: WS_METHODS.vcsRemoveWorktree,
332 scheduler: vcsCommandScheduler,
333 concurrency: vcsCommandConcurrency,
334 onSettled: invalidateRefs,
335 }),
336 createRef: createEnvironmentRpcCommand(runtime, {
337 label: "environment-data:vcs:create-ref",
338 tag: WS_METHODS.vcsCreateRef,
339 scheduler: vcsCommandScheduler,
340 concurrency: vcsCommandConcurrency,
341 onSettled: invalidateRefs,
342 }),
343 switchRef: createEnvironmentRpcCommand(runtime, {
344 label: "environment-data:vcs:switch-ref",
345 tag: WS_METHODS.vcsSwitchRef,
346 scheduler: vcsCommandScheduler,
347 concurrency: vcsCommandConcurrency,
348 onSettled: invalidateRefs,
349 }),
350 init: createEnvironmentRpcCommand(runtime, {
351 label: "environment-data:vcs:init",
352 tag: WS_METHODS.vcsInit,
353 scheduler: vcsCommandScheduler,
354 concurrency: vcsCommandConcurrency,
355 onSettled: invalidateRefs,
356 }),
357 };
359​
360export * from "./gitActions.ts";
361export * from "./vcsAction.ts";
362export * from "./vcsRef.ts";
363export * from "./vcsStatusRevalidation.ts";