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

vcs.ts

344 lines11.6 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/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 );
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 );
235​
236export function createVcsEnvironmentAtoms<R, E>(
237 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
238) {
239 /**
240 * One flat family on purpose: families hold entries via WeakRef, so a nested
241 * per-environment family can be collected between lookups, dropping every
242 * cached page atom and collapsing paginated ref lists mid-scroll.
243 */
244 const listRefsFamily = Atom.family((key: string) => {
245 const [environmentId, input] = JSON.parse(key) as [EnvironmentId, VcsListRefsInput];
246 return runtime
247 .atom((get) => {
248 const state = get(vcsRefsCacheStateAtom({ environmentId }));
249 return cachedVcsRefsChanges(
250 environmentId,
251 input,
252 state.revision,
253 state.persistedCacheReadable,
254 );
255 })
256 .pipe(
257 Atom.setIdleTTL(VCS_REFS_IDLE_TTL_MS),
258 Atom.withLabel(`environment-data:vcs:list-refs:${key}`),
259 );
260 });
261 const listRefs = (target: {
262 readonly environmentId: EnvironmentId;
263 readonly input: VcsListRefsInput;
264 }) => listRefsFamily(JSON.stringify([target.environmentId, target.input]));
265 const invalidateRefs = (
266 target: { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } },
267 registry: AtomRegistry.AtomRegistry,
268 ) =>
269 invalidateCachedVcsRefs(registry, {
270 environmentId: target.environmentId,
271 cwd: target.input.cwd,
272 });
273​
274 return {
275 listRefs,
276 status: createEnvironmentSubscriptionAtomFamily(runtime, {
277 label: "environment-data:vcs:status",
278 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
279 subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
280 Stream.mapAccum(
281 () => null as VcsStatusResult | null,
282 (current, event) => {
283 const next = applyGitStatusStreamEvent(current, event);
284 return [next, [next]] as const;
285 },
286 ),
287 ),
288 }),
289 pull: createEnvironmentRpcCommand(runtime, {
290 label: "environment-data:vcs:pull",
291 tag: WS_METHODS.vcsPull,
292 scheduler: vcsCommandScheduler,
293 concurrency: vcsCommandConcurrency,
294 onSettled: invalidateRefs,
295 }),
296 refreshStatus: createEnvironmentRpcCommand(runtime, {
297 label: "environment-data:vcs:refresh-status",
298 tag: WS_METHODS.vcsRefreshStatus,
299 scheduler: vcsCommandScheduler,
300 concurrency: vcsCommandConcurrency,
301 onSettled: invalidateRefs,
302 }),
303 createWorktree: createEnvironmentRpcCommand(runtime, {
304 label: "environment-data:vcs:create-worktree",
305 tag: WS_METHODS.vcsCreateWorktree,
306 scheduler: vcsCommandScheduler,
307 concurrency: vcsCommandConcurrency,
308 onSettled: invalidateRefs,
309 }),
310 removeWorktree: createEnvironmentRpcCommand(runtime, {
311 label: "environment-data:vcs:remove-worktree",
312 tag: WS_METHODS.vcsRemoveWorktree,
313 scheduler: vcsCommandScheduler,
314 concurrency: vcsCommandConcurrency,
315 onSettled: invalidateRefs,
316 }),
317 createRef: createEnvironmentRpcCommand(runtime, {
318 label: "environment-data:vcs:create-ref",
319 tag: WS_METHODS.vcsCreateRef,
320 scheduler: vcsCommandScheduler,
321 concurrency: vcsCommandConcurrency,
322 onSettled: invalidateRefs,
323 }),
324 switchRef: createEnvironmentRpcCommand(runtime, {
325 label: "environment-data:vcs:switch-ref",
326 tag: WS_METHODS.vcsSwitchRef,
327 scheduler: vcsCommandScheduler,
328 concurrency: vcsCommandConcurrency,
329 onSettled: invalidateRefs,
330 }),
331 init: createEnvironmentRpcCommand(runtime, {
332 label: "environment-data:vcs:init",
333 tag: WS_METHODS.vcsInit,
334 scheduler: vcsCommandScheduler,
335 concurrency: vcsCommandConcurrency,
336 onSettled: invalidateRefs,
337 }),
338 };
340​
341export * from "./gitActions.ts";
342export * from "./vcsAction.ts";
343export * from "./vcsRef.ts";
344export * from "./vcsStatus.ts";