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

vcsAction.test.ts

679 lines20.6 KB

1import {
2 EnvironmentId,
3 WS_METHODS,
4 type GitActionProgressEvent,
5 type GitRunStackedActionResult,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
16​
17import {
18 AVAILABLE_CONNECTION_STATE,
19 PrimaryConnectionTarget,
20 type PreparedConnection,
21 type SupervisorConnectionState,
22} from "../connection/model.ts";
23import * as EnvironmentRegistry from "../connection/registry.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25import * as Persistence from "../platform/persistence.ts";
26import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
27import type { RpcSession } from "../rpc/session.ts";
28import type { AtomCommandResult } from "./runtime.ts";
29import {
30 applyVcsActionProgressEvent,
31 beginVcsActionState,
32 consumeVcsActionProgress,
33 createVcsActionManager,
34 createVcsActionTransportId,
35 EMPTY_VCS_ACTION_STATE,
36 getVcsActionTargetKey,
37 normalizeVcsActionProgressEvent,
38 parseVcsActionTargetKey,
39 VcsActionMissingTerminalEventError,
40 VcsActionRemoteFailureError,
41 VcsActionTargetKeyParseError,
42 VcsActionUnavailableError,
43} from "./vcsAction.ts";
44import { vcsRefsCacheStateAtom } from "./vcsRefInvalidation.ts";
45​
46const actionId = "action-123";
47const action = "commit_push" as const;
48const cwd = "/repo";
49const environmentId = EnvironmentId.make("environment-1");
50const isVcsActionUnavailableError = Schema.is(VcsActionUnavailableError);
51const result: GitRunStackedActionResult = {
52 action,
53 branch: {
54 status: "skipped_not_requested",
55 },
56 commit: {
57 status: "created",
58 commitSha: "abc123",
59 subject: "Test commit",
60 },
61 push: {
62 status: "pushed",
63 branch: "feature",
64 },
65 pr: {
66 status: "skipped_not_requested",
67 },
68 toast: {
69 title: "Changes pushed",
70 cta: {
71 kind: "none",
72 },
73 },
74};
75​
76const target = new PrimaryConnectionTarget({
77 environmentId,
78 label: "Test environment",
79 httpBaseUrl: "https://environment.example.test",
80 wsBaseUrl: "wss://environment.example.test",
81});
82​
83function session(client: WsRpcProtocolClient): RpcSession {
84 return {
85 client,
86 initialConfig: Effect.never,
87 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
88 ready: Effect.void,
89 probe: Effect.void,
90 closed: Effect.never,
91 };
93​
94function progress<T extends GitActionProgressEvent>(event: T): T {
95 return event;
97​
98function cacheStore(onClearVcsRefs: (environmentId: EnvironmentId) => void) {
99 return Persistence.EnvironmentCacheStore.of({
100 loadShell: () => Effect.succeed(Option.none()),
101 saveShell: () => Effect.void,
102 loadThread: () => Effect.succeed(Option.none()),
103 saveThread: () => Effect.void,
104 removeThread: () => Effect.void,
105 loadServerConfig: () => Effect.succeed(Option.none()),
106 saveServerConfig: () => Effect.void,
107 loadVcsRefs: () => Effect.succeed(Option.none()),
108 saveVcsRefs: () => Effect.void,
109 removeVcsRefs: () => Effect.void,
110 clearVcsRefs: (environmentId) => Effect.sync(() => onClearVcsRefs(environmentId)),
111 clear: () => Effect.void,
112 });
114​
115describe("vcsActionState", () => {
116 it("preserves malformed target key diagnostics and the native cause without copying the key", () => {
117 const key = "not-json-with-credential=do-not-log";
118 let error: unknown;
119​
120 try {
121 parseVcsActionTargetKey(key);
122 } catch (cause) {
123 error = cause;
124 }
125​
126 expect(error).toBeInstanceOf(VcsActionTargetKeyParseError);
127 expect(error).toMatchObject({ keyLength: key.length, cause: expect.any(SyntaxError) });
128 expect(error).not.toHaveProperty("key");
129 expect((error as Error).message).not.toContain(key);
130 });
131​
132 it("rejects invalid target key shapes", () => {
133 const key = JSON.stringify([environmentId]);
134​
135 expect(() => parseVcsActionTargetKey(key)).toThrowError(VcsActionTargetKeyParseError);
136 });
137​
138 it("projects phase and hook progress without owning the async operation", () => {
139 const initial = beginVcsActionState({
140 operation: "run_change_request",
141 label: "Running source control action",
142 actionId,
143 });
144 const phase = applyVcsActionProgressEvent(
145 initial,
146 progress({
147 actionId,
148 action,
149 cwd,
150 kind: "phase_started",
151 phase: "commit",
152 label: "Committing...",
153 }),
154 );
155 const hook = applyVcsActionProgressEvent(
156 phase,
157 progress({
158 actionId,
159 action,
160 cwd,
161 kind: "hook_started",
162 hookName: "post-commit",
163 }),
164 );
165 const output = applyVcsActionProgressEvent(
166 hook,
167 progress({
168 actionId,
169 action,
170 cwd,
171 kind: "hook_output",
172 hookName: "post-commit",
173 stream: "stdout",
174 text: "hook output",
175 }),
176 );
177 const finished = applyVcsActionProgressEvent(
178 output,
179 progress({
180 actionId,
181 action,
182 cwd,
183 kind: "hook_finished",
184 hookName: "post-commit",
185 exitCode: 0,
186 durationMs: 12,
187 }),
188 );
189​
190 expect(phase).toMatchObject({
191 isRunning: true,
192 currentLabel: "Committing...",
193 currentPhaseLabel: "Committing...",
194 });
195 expect(output).toMatchObject({
196 currentLabel: "Running post-commit...",
197 hookName: "post-commit",
198 lastOutputLine: "hook output",
199 });
200 expect(finished).toMatchObject({
201 currentLabel: "Committing...",
202 hookName: null,
203 lastOutputLine: null,
204 });
205 });
206​
207 it("clears running presentation state once the action finishes", () => {
208 const initial = beginVcsActionState({
209 operation: "run_change_request",
210 label: "Running source control action",
211 actionId,
212 });
213 const pushing = applyVcsActionProgressEvent(
214 initial,
215 progress({
216 actionId,
217 action,
218 cwd,
219 kind: "phase_started",
220 phase: "push",
221 label: "Pushing...",
222 }),
223 );
224 const finished = applyVcsActionProgressEvent(
225 pushing,
226 progress({
227 actionId,
228 action,
229 cwd,
230 kind: "action_finished",
231 result,
232 }),
233 );
234​
235 expect(finished).toMatchObject({
236 isRunning: false,
237 operation: "run_change_request",
238 actionId,
239 action,
240 currentLabel: null,
241 currentPhaseLabel: null,
242 lastOutputLine: null,
243 error: null,
244 });
245 });
246​
247 it("retains a terminal action error for presentation", () => {
248 const initial = beginVcsActionState({
249 operation: "run_change_request",
250 label: "Running source control action",
251 actionId,
252 });
253 const failed = applyVcsActionProgressEvent(
254 initial,
255 progress({
256 actionId,
257 action,
258 cwd,
259 kind: "action_failed",
260 phase: null,
261 message: "Push failed.",
262 }),
263 );
264​
265 expect(failed).toMatchObject({
266 isRunning: false,
267 operation: "run_change_request",
268 actionId,
269 action,
270 error: "Push failed.",
271 });
272 });
273​
274 it("ignores progress after a newer action owns the target", () => {
275 const current = beginVcsActionState({
276 operation: "pull",
277 label: "Pulling latest changes",
278 actionId: "newer-action",
279 });
280​
281 expect(
282 applyVcsActionProgressEvent(
283 current,
284 progress({
285 actionId,
286 action,
287 cwd,
288 kind: "phase_started",
289 phase: "push",
290 label: "Pushing...",
291 }),
292 ),
293 ).toBe(current);
294 });
295​
296 it("keys presentation state only when the environment and repository are known", () => {
297 expect(
298 getVcsActionTargetKey({
299 environmentId,
300 cwd,
301 }),
302 ).toBe(JSON.stringify([environmentId, cwd]));
303 expect(getVcsActionTargetKey({ environmentId: null, cwd })).toBeNull();
304 expect(
305 getVcsActionTargetKey({
306 environmentId,
307 cwd: null,
308 }),
309 ).toBeNull();
310 });
311​
312 it("normalizes progress only for the matching environment-scoped action", () => {
313 const target = { environmentId, cwd };
314 const otherTarget = {
315 environmentId: EnvironmentId.make("environment-2"),
316 cwd,
317 };
318 const transportActionId = createVcsActionTransportId(target, actionId);
319 const event = progress({
320 actionId: createVcsActionTransportId(otherTarget, actionId),
321 action,
322 cwd,
323 kind: "phase_started",
324 phase: "push",
325 label: "Pushing...",
326 });
327​
328 expect(normalizeVcsActionProgressEvent(target, transportActionId, actionId, event)).toBeNull();
329 expect(
330 normalizeVcsActionProgressEvent(target, transportActionId, actionId, {
331 ...event,
332 actionId: transportActionId,
333 }),
334 ).toEqual({
335 ...event,
336 actionId,
337 });
338 });
339​
340 it.effect("consumes progress through the terminal event and returns its result", () =>
341 Effect.gen(function* () {
342 const target = { environmentId, cwd };
343 const transportActionId = createVcsActionTransportId(target, actionId);
344 const observed: GitActionProgressEvent[] = [];
345 const events: GitActionProgressEvent[] = [
346 {
347 actionId: "unrelated-action",
348 action,
349 cwd,
350 kind: "phase_started",
351 phase: "commit",
352 label: "Ignored",
353 },
354 {
355 actionId: transportActionId,
356 action,
357 cwd,
358 kind: "phase_started",
359 phase: "push",
360 label: "Pushing...",
361 },
362 {
363 actionId: transportActionId,
364 action,
365 cwd,
366 kind: "action_finished",
367 result,
368 },
369 ];
370​
371 const actual = yield* consumeVcsActionProgress(Stream.fromIterable(events), {
372 target,
373 transportActionId,
374 actionId,
375 action,
376 onProgress: (event) =>
377 Effect.sync(() => {
378 observed.push(event);
379 }),
380 });
381​
382 expect(actual).toEqual(result);
383 expect(observed.map((event) => event.actionId)).toEqual([actionId, actionId]);
384 expect(observed.map((event) => event.kind)).toEqual(["phase_started", "action_finished"]);
385 }),
386 );
387​
388 it.effect("retains structural remote failure context without copying the remote payload", () =>
389 Effect.gen(function* () {
390 const target = { environmentId, cwd };
391 const transportActionId = createVcsActionTransportId(target, actionId);
392 const remoteMessage = "The remote rejected the push with credential=do-not-log.";
393 const error = yield* consumeVcsActionProgress(
394 Stream.fromIterable<GitActionProgressEvent>([
395 {
396 actionId: transportActionId,
397 action,
398 cwd,
399 kind: "action_failed",
400 phase: "push",
401 message: remoteMessage,
402 },
403 ]),
404 {
405 target,
406 transportActionId,
407 actionId,
408 action,
409 onProgress: () => Effect.void,
410 },
411 ).pipe(Effect.flip);
412​
413 expect(error).toBeInstanceOf(VcsActionRemoteFailureError);
414 expect(error).toMatchObject({
415 actionId,
416 transportActionId,
417 action,
418 environmentId,
419 cwd,
420 phase: "push",
421 remoteMessageLength: remoteMessage.length,
422 });
423 expect(error).not.toHaveProperty("detail");
424 expect(error.message).toBe("Source control action 'commit_push' failed during push.");
425 expect(error.message).not.toContain(remoteMessage);
426 }),
427 );
428​
429 it.effect("reports a missing terminal event as a protocol failure", () =>
430 Effect.gen(function* () {
431 const target = { environmentId, cwd };
432 const transportActionId = createVcsActionTransportId(target, actionId);
433 const error = yield* consumeVcsActionProgress(
434 Stream.fromIterable<GitActionProgressEvent>([
435 {
436 actionId: transportActionId,
437 action,
438 cwd,
439 kind: "phase_started",
440 phase: "commit",
441 label: "Committing...",
442 },
443 ]),
444 {
445 target,
446 transportActionId,
447 actionId,
448 action,
449 onProgress: () => Effect.void,
450 },
451 ).pipe(Effect.flip);
452​
453 expect(error).toBeInstanceOf(VcsActionMissingTerminalEventError);
454 expect(error).toMatchObject({
455 actionId,
456 transportActionId,
457 action,
458 environmentId,
459 cwd,
460 });
461 expect(error.message).toBe(
462 "Source control action 'commit_push' ended without a terminal result.",
463 );
464 }),
465 );
466​
467 it("keys mutation ownership by environment and cwd", () => {
468 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
469 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
470 never
471 >;
472 const manager = createVcsActionManager(runtime);
473 const registry = AtomRegistry.make();
474 const target = { environmentId, cwd };
475 const otherTarget = {
476 environmentId: EnvironmentId.make("environment-2"),
477 cwd,
478 };
479​
480 expect(manager.runStackedAction(target)).toBe(manager.runStackedAction({ ...target }));
481 expect(manager.runStackedAction(target)).not.toBe(manager.runStackedAction(otherTarget));
482 expect(registry.get(manager.stateAtom(target))).toEqual(EMPTY_VCS_ACTION_STATE);
483​
484 registry.dispose();
485 });
486​
487 it("retains the incomplete target and operation when tracking is unavailable", async () => {
488 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
489 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
490 never
491 >;
492 const manager = createVcsActionManager(runtime);
493 const registry = AtomRegistry.make();
494 const result = await manager.track(
495 registry,
496 { environmentId, cwd: null },
497 { operation: "pull", label: "Pulling latest changes" },
498 async () => AsyncResult.success(undefined),
499 );
500​
501 expect(AsyncResult.isFailure(result)).toBe(true);
502 if (AsyncResult.isFailure(result)) {
503 const error = Cause.squash(result.cause);
504 expect(error).toBeInstanceOf(VcsActionUnavailableError);
505 if (!isVcsActionUnavailableError(error)) {
506 throw error;
507 }
508 expect(error).toMatchObject({
509 operation: "pull",
510 environmentId,
511 cwd: null,
512 });
513 expect(error.message).toBe("Source control operation 'pull' is unavailable.");
514 }
515​
516 registry.dispose();
517 });
518​
519 it("tracks finite mutations without letting an older completion clear newer state", async () => {
520 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
521 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
522 never
523 >;
524 const manager = createVcsActionManager(runtime);
525 const registry = AtomRegistry.make();
526 const target = { environmentId, cwd };
527 let finishFirst!: () => void;
528 let failSecond!: (error: Error) => void;
529 const firstAction = new Promise<AtomCommandResult<void, never>>((resolve) => {
530 finishFirst = () => resolve(AsyncResult.success(undefined));
531 });
532 const secondAction = new Promise<AtomCommandResult<void, Error>>((resolve) => {
533 failSecond = (error) => resolve(AsyncResult.failure(Cause.fail(error)));
534 });
535​
536 const first = manager.track(
537 registry,
538 target,
539 { operation: "pull", label: "Pulling latest changes" },
540 () => firstAction,
541 );
542 const firstActionId = registry.get(manager.stateAtom(target)).actionId;
543 const second = manager.track(
544 registry,
545 target,
546 { operation: "switch_ref", label: "Switching branch" },
547 () => secondAction,
548 );
549 const secondActionId = registry.get(manager.stateAtom(target)).actionId;
550​
551 finishFirst();
552 await first;
553 expect(registry.get(manager.stateAtom(target))).toMatchObject({
554 actionId: secondActionId,
555 isRunning: true,
556 operation: "switch_ref",
557 });
558 expect(secondActionId).not.toBe(firstActionId);
559​
560 failSecond(new Error("switch failed"));
561 const secondFailure = await second;
562 expect(AsyncResult.isFailure(secondFailure)).toBe(true);
563 expect(registry.get(manager.stateAtom(target))).toMatchObject({
564 actionId: secondActionId,
565 error: "switch failed",
566 isRunning: false,
567 operation: "switch_ref",
568 });
569​
570 registry.dispose();
571 });
572​
573 it.effect("invalidates persisted refs after successful and failed stacked actions", () =>
574 Effect.scoped(
575 Effect.gen(function* () {
576 const connectionState: SupervisorConnectionState = {
577 ...AVAILABLE_CONNECTION_STATE,
578 desired: true,
579 network: "online",
580 phase: "connected",
581 attempt: 1,
582 generation: 1,
583 };
584 const targetKey = { environmentId, cwd };
585 const successfulActionId = "invalidate-success";
586 const failedActionId = "invalidate-failure";
587 const successfulTransportActionId = createVcsActionTransportId(
588 targetKey,
589 successfulActionId,
590 );
591 const failedTransportActionId = createVcsActionTransportId(targetKey, failedActionId);
592 const client = {
593 [WS_METHODS.gitRunStackedAction]: (input: { readonly actionId: string }) =>
594 input.actionId === successfulTransportActionId
595 ? Stream.make(
596 progress({
597 kind: "action_finished",
598 actionId: successfulTransportActionId,
599 cwd,
600 action,
601 result,
602 }),
603 )
604 : Stream.make(
605 progress({
606 kind: "action_failed",
607 actionId: failedTransportActionId,
608 cwd,
609 action,
610 phase: "push",
611 message: "push failed after creating the branch",
612 }),
613 ),
614 } as unknown as WsRpcProtocolClient;
615 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
616 target,
617 state: yield* SubscriptionRef.make(connectionState),
618 session: yield* SubscriptionRef.make(Option.some(session(client))),
619 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
620 connect: Effect.void,
621 disconnect: Effect.void,
622 retryNow: Effect.void,
623 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
624 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
625 _environmentId,
626 effect,
627 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
628 const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = (
629 _environmentId,
630 stream,
631 ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
632 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
633 run,
634 runStream,
635 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
636 const removed = new Array<string>();
637 const runtime = Atom.runtime(
638 Layer.merge(
639 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
640 Layer.succeed(
641 Persistence.EnvironmentCacheStore,
642 cacheStore((removedEnvironmentId) => {
643 removed.push(`${removedEnvironmentId}:*`);
644 }),
645 ),
646 ),
647 );
648 const manager = createVcsActionManager(runtime);
649 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
650 Effect.sync(() => registry.dispose()),
651 );
652 const state = vcsRefsCacheStateAtom({ environmentId });
653​
654 expect(registry.get(state).revision).toBe(0);
655 const successfulResult = yield* Effect.promise(() =>
656 manager.runStackedAction(targetKey).run(registry, {
657 actionId: successfulActionId,
658 action,
659 }),
660 );
661​
662 expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
663 expect(registry.get(state).revision).toBe(1);
664 expect(removed).toEqual([`${environmentId}:*`]);
665​
666 const failedResult = yield* Effect.promise(() =>
667 manager.runStackedAction(targetKey).run(registry, {
668 actionId: failedActionId,
669 action,
670 }),
671 );
672​
673 expect(AsyncResult.isFailure(failedResult)).toBe(true);
674 expect(registry.get(state).revision).toBe(2);
675 expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]);
676 }),
677 ),
678 );
679});