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

vcsAction.test.ts

595 lines18.8 KB

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