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

vcs.test.ts

510 lines18.1 KB

1import { vi } from "vite-plus/test";
2import {
3 EnvironmentId,
4 AuthSourceControlWriteScope,
5 WS_METHODS,
6 type VcsListRefsResult,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Ref from "effect/Ref";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
17​
18import {
19 AVAILABLE_CONNECTION_STATE,
20 PrimaryConnectionTarget,
21 type PreparedConnection,
22 type SupervisorConnectionState,
23} from "../connection/model.ts";
24import * as EnvironmentRegistry from "../connection/registry.ts";
25import * as EnvironmentSupervisor from "../connection/supervisor.ts";
26import * as Persistence from "../platform/persistence.ts";
27import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
28import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29import type { RpcSession } from "../rpc/session.ts";
30​
31import {
32 commitVcsRefsRefresh,
33 createVcsEnvironmentAtoms,
34 makeCachedVcsRefsChanges,
35} from "./vcs.ts";
36import {
37 invalidateCachedVcsRefs,
38 invalidateVcsRefs,
39 vcsRefsCacheStateAtom,
40} from "./vcsRefInvalidation.ts";
41​
42const TARGET = new PrimaryConnectionTarget({
43 environmentId: EnvironmentId.make("environment-1"),
44 label: "Test environment",
45 httpBaseUrl: "https://environment.example.test",
46 wsBaseUrl: "wss://environment.example.test",
47});
48​
49const CONNECTED_CONNECTION_STATE: SupervisorConnectionState = {
50 ...AVAILABLE_CONNECTION_STATE,
51 desired: true,
52 network: "online",
53 phase: "connected",
54 attempt: 1,
55 generation: 1,
56};
57​
58const CACHED_REFS: VcsListRefsResult = {
59 refs: [
60 {
61 name: "main",
62 current: true,
63 isDefault: true,
64 worktreePath: "/repo",
65 },
66 ],
67 isRepo: true,
68 hasPrimaryRemote: true,
69 nextCursor: null,
70 totalCount: 1,
71};
72​
73const LIVE_REFS: VcsListRefsResult = {
74 ...CACHED_REFS,
75 refs: [
76 {
77 name: "release",
78 current: true,
79 isDefault: true,
80 worktreePath: "/repo",
81 },
82 ],
83};
84​
85function session(client: WsRpcProtocolClient): RpcSession {
86 return {
87 client,
88 initialConfig: Effect.never,
89 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
90 ready: Effect.void,
91 probe: Effect.void,
92 closed: Effect.never,
93 };
95​
96function cacheWithRefs(
97 refs: Option.Option<VcsListRefsResult>,
98 overrides: Partial<Persistence.EnvironmentCacheStore["Service"]> = {},
99) {
100 return Persistence.EnvironmentCacheStore.of({
101 loadShell: () => Effect.succeedNone,
102 saveShell: () => Effect.void,
103 loadThread: () => Effect.succeedNone,
104 saveThread: () => Effect.void,
105 removeThread: () => Effect.void,
106 loadServerConfig: () => Effect.succeedNone,
107 saveServerConfig: () => Effect.void,
108 loadVcsRefs: () => Effect.succeed(refs),
109 saveVcsRefs: () => Effect.void,
110 removeVcsRefs: () => Effect.void,
111 clearVcsRefs: () => Effect.void,
112 clear: () => Effect.void,
113 ...overrides,
114 });
116​
117describe("cached VCS refs", () => {
118 it("invalidates all ref streams in the mutated environment", () => {
119 const registry = AtomRegistry.make();
120 const environment = {
121 environmentId: TARGET.environmentId,
122 };
123 const otherEnvironment = {
124 environmentId: EnvironmentId.make("environment-2"),
125 };
126​
127 expect(registry.get(vcsRefsCacheStateAtom(environment))).toEqual({
128 revision: 0,
129 persistedCacheReadable: true,
130 });
131 expect(registry.get(vcsRefsCacheStateAtom(otherEnvironment))).toEqual({
132 revision: 0,
133 persistedCacheReadable: true,
134 });
135​
136 invalidateVcsRefs(registry, environment);
137​
138 expect(registry.get(vcsRefsCacheStateAtom(environment))).toEqual({
139 revision: 1,
140 persistedCacheReadable: true,
141 });
142 expect(registry.get(vcsRefsCacheStateAtom(otherEnvironment))).toEqual({
143 revision: 0,
144 persistedCacheReadable: true,
145 });
146 registry.dispose();
147 });
148​
149 it.effect("does not repersist a refresh superseded by ref invalidation", () =>
150 Effect.scoped(
151 Effect.gen(function* () {
152 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
153 Effect.sync(() => registry.dispose()),
154 );
155 const saved = yield* Ref.make<ReadonlyArray<VcsListRefsResult>>([]);
156 const clears = yield* Ref.make(0);
157 const revisionsObservedDuringClear = yield* Ref.make<ReadonlyArray<number>>([]);
158 const cache = cacheWithRefs(Option.none(), {
159 saveVcsRefs: (_environmentId, _cwd, refs) =>
160 Ref.update(saved, (current) => [...current, refs]),
161 clearVcsRefs: () =>
162 Effect.all([
163 Ref.update(clears, (count) => count + 1),
164 Ref.update(revisionsObservedDuringClear, (current) => [
165 ...current,
166 registry.get(vcsRefsCacheStateAtom(TARGET)).revision,
167 ]),
168 ]).pipe(Effect.asVoid),
169 });
170​
171 yield* invalidateCachedVcsRefs(registry, {
172 environmentId: TARGET.environmentId,
173 cwd: "/repo-worktree",
174 }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
175​
176 expect(
177 yield* commitVcsRefsRefresh(registry, cache, {
178 environmentId: TARGET.environmentId,
179 cwd: "/repo",
180 refs: CACHED_REFS,
181 expectedRevision: 0,
182 persist: true,
183 }),
184 ).toBe(false);
185​
186 expect(yield* Ref.get(saved)).toEqual([]);
187 expect(yield* Ref.get(clears)).toBe(1);
188 expect(yield* Ref.get(revisionsObservedDuringClear)).toEqual([0]);
189 expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual({
190 revision: 1,
191 persistedCacheReadable: true,
192 });
193​
194 expect(
195 yield* commitVcsRefsRefresh(registry, cache, {
196 environmentId: TARGET.environmentId,
197 cwd: "/repo",
198 refs: LIVE_REFS,
199 expectedRevision: 1,
200 persist: true,
201 }),
202 ).toBe(true);
203 expect(yield* Ref.get(saved)).toEqual([LIVE_REFS]);
204 }),
205 ),
206 );
207​
208 it.effect("invalidates persisted refs when ref-affecting commands settle", () =>
209 Effect.scoped(
210 Effect.gen(function* () {
211 const expectedError = new EnvironmentRpcUnavailableError({
212 environmentId: TARGET.environmentId,
213 message: "pull failed after fetching refs",
214 });
215 const client = {
216 [WS_METHODS.vcsPull]: () => Effect.fail(expectedError),
217 [WS_METHODS.vcsRefreshStatus]: () => Effect.void,
218 } as unknown as WsRpcProtocolClient;
219 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
220 target: TARGET,
221 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
222 session: yield* SubscriptionRef.make(Option.some(session(client))),
223 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
224 connect: Effect.void,
225 disconnect: Effect.void,
226 retryNow: Effect.void,
227 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
228 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
229 _environmentId,
230 effect,
231 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
232 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
233 run,
234 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
235 const clears = yield* Ref.make(0);
236 const runtime = Atom.runtime(
237 Layer.merge(
238 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
239 Layer.succeed(
240 Persistence.EnvironmentCacheStore,
241 cacheWithRefs(Option.none(), {
242 clearVcsRefs: () => Ref.update(clears, (count) => count + 1),
243 }),
244 ),
245 ),
246 );
247 const atoms = createVcsEnvironmentAtoms(runtime);
248 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
249 Effect.sync(() => registry.dispose()),
250 );
251​
252 const result = yield* Effect.promise(() =>
253 atoms.pull.run(registry, {
254 environmentId: TARGET.environmentId,
255 input: { cwd: "/repo" },
256 }),
257 );
258​
259 expect(AsyncResult.isFailure(result)).toBe(true);
260 expect(yield* Ref.get(clears)).toBe(1);
261 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1);
262​
263 const refreshResult = yield* Effect.promise(() =>
264 atoms.refreshStatus.run(registry, {
265 environmentId: TARGET.environmentId,
266 input: { cwd: "/repo" },
267 }),
268 );
269​
270 expect(AsyncResult.isSuccess(refreshResult)).toBe(true);
271 expect(yield* Ref.get(clears)).toBe(2);
272 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
273 }),
274 ),
275 );
276​
277 it.effect("suppresses persisted snapshots after an environment-wide clear fails", () =>
278 Effect.scoped(
279 Effect.gen(function* () {
280 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
281 Effect.sync(() => registry.dispose()),
282 );
283 const persisted = yield* Ref.make<Option.Option<VcsListRefsResult>>(
284 Option.some(CACHED_REFS),
285 );
286 const loads = yield* Ref.make(0);
287 const clearAttempts = yield* Ref.make(0);
288 const cache = cacheWithRefs(Option.none(), {
289 loadVcsRefs: () =>
290 Ref.update(loads, (count) => count + 1).pipe(Effect.andThen(Ref.get(persisted))),
291 saveVcsRefs: (_environmentId, _cwd, refs) => Ref.set(persisted, Option.some(refs)),
292 clearVcsRefs: () =>
293 Ref.updateAndGet(clearAttempts, (count) => count + 1).pipe(
294 Effect.flatMap((attempt) =>
295 attempt === 1
296 ? Effect.fail(
297 new Persistence.ConnectionPersistenceError({
298 operation: "clear-vcs-refs",
299 message: "storage unavailable",
300 }),
301 )
302 : Ref.set(persisted, Option.none()),
303 ),
304 ),
305 });
306​
307 yield* invalidateCachedVcsRefs(registry, {
308 environmentId: TARGET.environmentId,
309 cwd: "/repo",
310 }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
311​
312 const state = registry.get(vcsRefsCacheStateAtom(TARGET));
313 expect(state).toEqual({
314 revision: 1,
315 persistedCacheReadable: false,
316 });
317​
318 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
319 target: TARGET,
320 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
321 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
322 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
323 connect: Effect.void,
324 disconnect: Effect.void,
325 retryNow: Effect.void,
326 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
327 const refs = yield* Stream.unwrap(
328 makeCachedVcsRefsChanges(
329 { cwd: "/repo", limit: 100 },
330 state.revision,
331 registry,
332 state.persistedCacheReadable,
333 ).pipe(
334 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
335 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
336 ),
337 ).pipe(Stream.runHead, Effect.forkChild({ startImmediately: true }));
338​
339 yield* Effect.yieldNow;
340 expect(yield* Ref.get(loads)).toBe(0);
341 yield* Fiber.interrupt(refs);
342 expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual(state);
343​
344 expect(
345 yield* commitVcsRefsRefresh(registry, cache, {
346 environmentId: TARGET.environmentId,
347 cwd: "/repo",
348 refs: LIVE_REFS,
349 expectedRevision: state.revision,
350 persist: true,
351 }),
352 ).toBe(true);
353 const recoveredState = registry.get(vcsRefsCacheStateAtom(TARGET));
354 expect(recoveredState).toEqual({
355 revision: 1,
356 persistedCacheReadable: true,
357 });
358 expect(yield* Ref.get(clearAttempts)).toBe(2);
359​
360 const recoveredRefs = yield* Stream.unwrap(
361 makeCachedVcsRefsChanges(
362 { cwd: "/repo", limit: 100 },
363 recoveredState.revision,
364 registry,
365 recoveredState.persistedCacheReadable,
366 ).pipe(
367 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
368 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
369 ),
370 ).pipe(Stream.runHead);
371​
372 expect(Option.getOrThrow(recoveredRefs)).toEqual(LIVE_REFS);
373 expect(yield* Ref.get(loads)).toBe(1);
374 }),
375 ),
376 );
377​
378 it.effect("loads an unfiltered branch list without a connection", () =>
379 Effect.scoped(
380 Effect.gen(function* () {
381 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
382 target: TARGET,
383 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
384 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
385 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
386 connect: Effect.void,
387 disconnect: Effect.void,
388 retryNow: Effect.void,
389 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
390 const refs = yield* Stream.unwrap(
391 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
392 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
393 Effect.provideService(
394 Persistence.EnvironmentCacheStore,
395 cacheWithRefs(Option.some(CACHED_REFS)),
396 ),
397 ),
398 ).pipe(Stream.runHead);
399​
400 expect(Option.getOrThrow(refs)).toEqual(CACHED_REFS);
401 }),
402 ),
403 );
404​
405 it.effect("cancels an in-flight refresh when the connection generation changes", () =>
406 Effect.scoped(
407 Effect.gen(function* () {
408 const calls = yield* Ref.make(0);
409 const interruptions = yield* Ref.make(0);
410 const connectionState = yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE);
411 const client = {
412 [WS_METHODS.vcsListRefs]: () =>
413 Ref.updateAndGet(calls, (count) => count + 1).pipe(
414 Effect.flatMap((count) =>
415 count === 1
416 ? Effect.never.pipe(
417 Effect.onInterrupt(() =>
418 Ref.update(interruptions, (interruptions) => interruptions + 1),
419 ),
420 )
421 : Effect.succeed(LIVE_REFS),
422 ),
423 ),
424 } as unknown as WsRpcProtocolClient;
425 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
426 target: TARGET,
427 state: connectionState,
428 session: yield* SubscriptionRef.make(Option.some(session(client))),
429 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
430 connect: Effect.void,
431 disconnect: Effect.void,
432 retryNow: Effect.void,
433 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
434​
435 const result = Stream.unwrap(
436 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
437 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
438 Effect.provideService(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
439 ),
440 ).pipe(Stream.runHead);
441 const fiber = yield* Effect.forkChild(result);
442​
443 for (let attempt = 0; attempt < 100 && (yield* Ref.get(calls)) < 1; attempt += 1) {
444 yield* Effect.yieldNow;
445 }
446 yield* SubscriptionRef.set(connectionState, AVAILABLE_CONNECTION_STATE);
447 for (let attempt = 0; attempt < 100 && (yield* Ref.get(interruptions)) < 1; attempt += 1) {
448 yield* Effect.yieldNow;
449 }
450 expect(yield* Ref.get(interruptions)).toBe(1);
451​
452 yield* SubscriptionRef.set(connectionState, {
453 ...CONNECTED_CONNECTION_STATE,
454 generation: 2,
455 });
456 expect(Option.getOrThrow(yield* Fiber.join(fiber))).toEqual(LIVE_REFS);
457 expect(yield* Ref.get(calls)).toBe(2);
458 }),
459 ),
460 );
461​
462 it.effect("emits persisted refs before a live refresh", () =>
463 Effect.scoped(
464 Effect.gen(function* () {
465 const client = {
466 [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
467 } as unknown as WsRpcProtocolClient;
468 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
469 target: TARGET,
470 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
471 session: yield* SubscriptionRef.make(Option.some(session(client))),
472 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
473 connect: Effect.void,
474 disconnect: Effect.void,
475 retryNow: Effect.void,
476 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
477​
478 const refs = yield* Stream.unwrap(
479 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
480 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
481 Effect.provideService(
482 Persistence.EnvironmentCacheStore,
483 cacheWithRefs(Option.some(CACHED_REFS)),
484 ),
485 ),
486 ).pipe(Stream.take(2), Stream.runCollect);
487​
488 expect(refs).toEqual([CACHED_REFS, LIVE_REFS]);
489 }),
490 ),
491 );
492});
493​
494vi.mock("./session.ts", () => ({
495 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
496}));
497const grantedSessions = Atom.family((_id: EnvironmentId) =>
498 Atom.make(
499 AsyncResult.success({
500 authenticated: true,
501 auth: {
502 policy: "remote-reachable",
503 bootstrapMethods: [],
504 sessionMethods: [],
505 sessionCookieName: "test",
506 },
507 scopes: [AuthSourceControlWriteScope],
508 }),
509 ),
510);