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

vcs.ts

227 lines7.9 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 Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Result from "effect/Result";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { Atom } from "effect/unstable/reactivity";
15​
16import { createEnvironmentRpcCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
17import type { EnvironmentRegistry } from "../connection/registry.ts";
18import { EnvironmentSupervisor } from "../connection/supervisor.ts";
19import { safeErrorLogAttributes } from "../errors/safeLog.ts";
20import { EnvironmentCacheStore } from "../platform/persistence.ts";
21import { request, subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
22import { followStreamInEnvironment } from "./runtime.ts";
23import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts";
24​
25const OFFLINE_BRANCH_LIST_LIMIT = 100;
26const VCS_REFS_REVALIDATE_INTERVAL = "5 seconds";
27​
28function canUseVcsRefsCache(input: VcsListRefsInput): boolean {
29 return (
30 input.query === undefined &&
31 input.cursor === undefined &&
32 input.includeMatchingRemoteRefs === undefined &&
33 input.refKind === undefined &&
34 input.limit === OFFLINE_BRANCH_LIST_LIMIT
35 );
37​
38/**
39 * Retains the last unfiltered branch-list response for the new-task picker.
40 * Filtered or paginated lists intentionally stay live-only: treating a
41 * partial result as a complete offline list would make branch selection
42 * misleading.
43 */
44export const makeCachedVcsRefsChanges = Effect.fn("CachedVcsRefsState.makeChanges")(function* (
45 input: VcsListRefsInput,
46) {
47 const supervisor = yield* EnvironmentSupervisor;
48 const cache = yield* EnvironmentCacheStore;
49 const environmentId = supervisor.target.environmentId;
50 const useCache = canUseVcsRefsCache(input);
51 const cached = useCache
52 ? yield* cache.loadVcsRefs(environmentId, input.cwd).pipe(
53 Effect.catch((error) =>
54 Effect.logWarning("Could not load cached Git refs.").pipe(
55 Effect.annotateLogs({
56 environmentId,
57 cwd: input.cwd,
58 ...safeErrorLogAttributes(error),
59 }),
60 Effect.as(Option.none<VcsListRefsResult>()),
61 ),
62 ),
63 )
64 : Option.none<VcsListRefsResult>();
65 const refresh = Effect.fn("CachedVcsRefsState.refresh")(function* () {
66 const refs = yield* request(WS_METHODS.vcsListRefs, input).pipe(
67 Effect.provideService(EnvironmentSupervisor, supervisor),
68 );
69 if (useCache) {
70 yield* cache.saveVcsRefs(environmentId, input.cwd, refs).pipe(
71 Effect.catch((error) =>
72 Effect.logWarning("Could not persist cached Git refs.").pipe(
73 Effect.annotateLogs({
74 environmentId,
75 cwd: input.cwd,
76 ...safeErrorLogAttributes(error),
77 }),
78 ),
79 ),
80 );
81 }
82 return refs;
83 });
84​
85 const cachedRefs = Stream.fromEffect(
86 SubscriptionRef.get(supervisor.state).pipe(
87 Effect.flatMap((connection) =>
88 connection.phase === "connected"
89 ? Effect.succeed(Option.none<VcsListRefsResult>())
90 : Effect.succeed(cached),
91 ),
92 ),
93 ).pipe(
94 Stream.filterMap((refs) =>
95 Option.match(refs, {
96 onNone: () => Result.failVoid,
97 onSome: Result.succeed,
98 }),
99 ),
100 );
101 const refreshedRefs = Stream.concat(
102 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
103 SubscriptionRef.changes(supervisor.state),
104 ).pipe(
105 Stream.map((connection) => (connection.phase === "connected" ? connection.generation : null)),
106 Stream.changes,
107 Stream.switchMap((generation) =>
108 generation === null
109 ? Stream.empty
110 : Stream.tick(VCS_REFS_REVALIDATE_INTERVAL).pipe(
111 Stream.mapEffect(
112 () =>
113 refresh().pipe(
114 Effect.map(Option.some),
115 Effect.catch((error) =>
116 Effect.logWarning("Could not refresh Git refs.").pipe(
117 Effect.annotateLogs({
118 environmentId,
119 cwd: input.cwd,
120 ...safeErrorLogAttributes(error),
121 }),
122 Effect.as(Option.none<VcsListRefsResult>()),
123 ),
124 ),
125 ),
126 { concurrency: 1 },
127 ),
128 Stream.filterMap((refs) =>
129 Option.match(refs, {
130 onNone: () => Result.failVoid,
131 onSome: Result.succeed,
132 }),
133 ),
134 ),
135 ),
136 );
137​
138 return Stream.concat(cachedRefs, refreshedRefs);
139});
140​
141export function cachedVcsRefsChanges(environmentId: EnvironmentId, input: VcsListRefsInput) {
142 return followStreamInEnvironment(environmentId, Stream.unwrap(makeCachedVcsRefsChanges(input)));
144​
145export function createVcsEnvironmentAtoms<R, E>(
146 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
147) {
148 const listRefsByEnvironment = Atom.family((environmentId: EnvironmentId) =>
149 Atom.family((inputKey: string) => {
150 const input = JSON.parse(inputKey) as VcsListRefsInput;
151 return runtime
152 .atom(cachedVcsRefsChanges(environmentId, input))
153 .pipe(
154 Atom.setIdleTTL(5 * 60_000),
155 Atom.withLabel(`environment-data:vcs:list-refs:${environmentId}:${inputKey}`),
156 );
157 }),
158 );
159 const listRefs = (target: {
160 readonly environmentId: EnvironmentId;
161 readonly input: VcsListRefsInput;
162 }) => listRefsByEnvironment(target.environmentId)(JSON.stringify(target.input));
163​
164 return {
165 listRefs,
166 status: createEnvironmentSubscriptionAtomFamily(runtime, {
167 label: "environment-data:vcs:status",
168 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
169 subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
170 Stream.mapAccum(
171 () => null as VcsStatusResult | null,
172 (current, event) => {
173 const next = applyGitStatusStreamEvent(current, event);
174 return [next, [next]] as const;
175 },
176 ),
177 ),
178 }),
179 pull: createEnvironmentRpcCommand(runtime, {
180 label: "environment-data:vcs:pull",
181 tag: WS_METHODS.vcsPull,
182 scheduler: vcsCommandScheduler,
183 concurrency: vcsCommandConcurrency,
184 }),
185 refreshStatus: createEnvironmentRpcCommand(runtime, {
186 label: "environment-data:vcs:refresh-status",
187 tag: WS_METHODS.vcsRefreshStatus,
188 scheduler: vcsCommandScheduler,
189 concurrency: vcsCommandConcurrency,
190 }),
191 createWorktree: createEnvironmentRpcCommand(runtime, {
192 label: "environment-data:vcs:create-worktree",
193 tag: WS_METHODS.vcsCreateWorktree,
194 scheduler: vcsCommandScheduler,
195 concurrency: vcsCommandConcurrency,
196 }),
197 removeWorktree: createEnvironmentRpcCommand(runtime, {
198 label: "environment-data:vcs:remove-worktree",
199 tag: WS_METHODS.vcsRemoveWorktree,
200 scheduler: vcsCommandScheduler,
201 concurrency: vcsCommandConcurrency,
202 }),
203 createRef: createEnvironmentRpcCommand(runtime, {
204 label: "environment-data:vcs:create-ref",
205 tag: WS_METHODS.vcsCreateRef,
206 scheduler: vcsCommandScheduler,
207 concurrency: vcsCommandConcurrency,
208 }),
209 switchRef: createEnvironmentRpcCommand(runtime, {
210 label: "environment-data:vcs:switch-ref",
211 tag: WS_METHODS.vcsSwitchRef,
212 scheduler: vcsCommandScheduler,
213 concurrency: vcsCommandConcurrency,
214 }),
215 init: createEnvironmentRpcCommand(runtime, {
216 label: "environment-data:vcs:init",
217 tag: WS_METHODS.vcsInit,
218 scheduler: vcsCommandScheduler,
219 concurrency: vcsCommandConcurrency,
220 }),
221 };
223​
224export * from "./gitActions.ts";
225export * from "./vcsAction.ts";
226export * from "./vcsRef.ts";
227export * from "./vcsStatus.ts";