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

vcsAction.ts

577 lines17.5 KB

1import {
2 EnvironmentId,
3 type EnvironmentId as EnvironmentIdType,
4 GitActionProgressPhase,
5 type GitActionProgressEvent,
6 type GitRunStackedActionInput,
7 type GitRunStackedActionResult,
8 GitStackedAction,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
17​
18import type { EnvironmentRegistry } from "../connection/registry.ts";
19import { EnvironmentCacheStore } from "../platform/persistence.ts";
20import { runStream } from "../rpc/client.ts";
21import {
22 createRuntimeCommand,
23 runStreamInEnvironment,
24 type AtomCommand,
25 type AtomCommandResult,
26} from "./runtime.ts";
27import { vcsCommandScheduler } from "./vcsCommandScheduler.ts";
28import { invalidateCachedVcsRefs } from "./vcsRefInvalidation.ts";
29​
30export const VcsActionOperation = Schema.Literals([
31 "refresh_status",
32 "run_change_request",
33 "pull",
34 "switch_ref",
35 "create_ref",
36 "create_worktree",
37 "init",
38 "publish_repository",
39 "prepare_pull_request_thread",
40]);
41export type VcsActionOperation = typeof VcsActionOperation.Type;
42​
43export interface VcsActionState {
44 readonly isRunning: boolean;
45 readonly operation: VcsActionOperation | null;
46 readonly actionId: string | null;
47 readonly action: GitStackedAction | null;
48 readonly currentLabel: string | null;
49 readonly currentPhaseLabel: string | null;
50 readonly hookName: string | null;
51 readonly lastOutputLine: string | null;
52 readonly phaseStartedAtMs: number | null;
53 readonly hookStartedAtMs: number | null;
54 readonly error: string | null;
56​
57export interface VcsActionTarget {
58 readonly environmentId: EnvironmentIdType | null;
59 readonly cwd: string | null;
61​
62export interface ResolvedVcsActionTarget {
63 readonly environmentId: EnvironmentIdType;
64 readonly cwd: string;
66​
67export interface BeginVcsActionInput {
68 readonly operation: VcsActionOperation;
69 readonly label: string;
70 readonly actionId?: string;
72​
73export interface RunVcsStackedActionInput {
74 readonly actionId: string;
75 readonly action: GitStackedAction;
76 readonly commitMessage?: string;
77 readonly featureBranch?: boolean;
78 readonly filePaths?: ReadonlyArray<string>;
79 readonly onProgress?: (event: GitActionProgressEvent) => void;
81​
82export class VcsActionUnavailableError extends Schema.TaggedErrorClass<VcsActionUnavailableError>()(
83 "VcsActionUnavailableError",
84 {
85 operation: VcsActionOperation,
86 environmentId: Schema.NullOr(EnvironmentId),
87 cwd: Schema.NullOr(Schema.String),
88 },
89) {
90 override get message(): string {
91 return `Source control operation '${this.operation.replaceAll("_", " ")}' is unavailable.`;
92 }
94​
95export class VcsActionRemoteFailureError extends Schema.TaggedErrorClass<VcsActionRemoteFailureError>()(
96 "VcsActionRemoteFailureError",
97 {
98 actionId: Schema.String,
99 transportActionId: Schema.String,
100 action: GitStackedAction,
101 environmentId: EnvironmentId,
102 cwd: Schema.String,
103 phase: Schema.NullOr(GitActionProgressPhase),
104 remoteMessageLength: Schema.Number,
105 },
106) {
107 override get message(): string {
108 const phase = this.phase === null ? "execution" : this.phase;
109 return `Source control action '${this.action}' failed during ${phase}.`;
110 }
112​
113export class VcsActionMissingTerminalEventError extends Schema.TaggedErrorClass<VcsActionMissingTerminalEventError>()(
114 "VcsActionMissingTerminalEventError",
115 {
116 actionId: Schema.String,
117 transportActionId: Schema.String,
118 action: GitStackedAction,
119 environmentId: EnvironmentId,
120 cwd: Schema.String,
121 },
122) {
123 override get message(): string {
124 return `Source control action '${this.action}' ended without a terminal result.`;
125 }
127​
128export class VcsActionTargetKeyParseError extends Schema.TaggedErrorClass<VcsActionTargetKeyParseError>()(
129 "VcsActionTargetKeyParseError",
130 {
131 keyLength: Schema.Number,
132 cause: Schema.Defect(),
133 },
134) {
135 override get message(): string {
136 return `Invalid source control action target key (${this.keyLength} characters).`;
137 }
139​
140export const VcsActionExecutionError = Schema.Union([
141 VcsActionRemoteFailureError,
142 VcsActionMissingTerminalEventError,
143]);
144export type VcsActionExecutionError = typeof VcsActionExecutionError.Type;
145​
146export const EMPTY_VCS_ACTION_STATE = Object.freeze<VcsActionState>({
147 isRunning: false,
148 operation: null,
149 actionId: null,
150 action: null,
151 currentLabel: null,
152 currentPhaseLabel: null,
153 hookName: null,
154 lastOutputLine: null,
155 phaseStartedAtMs: null,
156 hookStartedAtMs: null,
157 error: null,
158});
159​
160const nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe());
161let nextLocalActionId = 0;
162const decodeVcsActionTargetKey = Schema.decodeUnknownSync(
163 Schema.Tuple([EnvironmentId, Schema.String]),
164);
165​
166export const vcsActionStateAtom = Atom.family((key: string) => {
167 return Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
168 Atom.keepAlive,
169 Atom.withLabel(`vcs-action:${key}`),
170 );
171});
172​
173export const EMPTY_VCS_ACTION_ATOM = Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
174 Atom.keepAlive,
175 Atom.withLabel("vcs-action:null"),
176);
177​
178export function getVcsActionTargetKey(target: VcsActionTarget): string | null {
179 if (target.environmentId === null || target.cwd === null) {
180 return null;
181 }
182 return JSON.stringify([target.environmentId, target.cwd]);
184​
185export function parseVcsActionTargetKey(key: string): ResolvedVcsActionTarget {
186 try {
187 const [environmentId, cwd] = decodeVcsActionTargetKey(JSON.parse(key));
188 return { environmentId, cwd };
189 } catch (cause) {
190 throw new VcsActionTargetKeyParseError({ keyLength: key.length, cause });
191 }
193​
194export function getVcsActionStateAtom(target: VcsActionTarget) {
195 const key = getVcsActionTargetKey(target);
196 return key === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(key);
198​
199function createLocalActionId(): string {
200 nextLocalActionId += 1;
201 return `local-vcs-action:${nextLocalActionId}`;
203​
204export function beginVcsActionState(
205 input: BeginVcsActionInput,
206): VcsActionState & { readonly actionId: string } {
207 const actionId = input.actionId ?? createLocalActionId();
208 const startedAt = nowMs();
209 return {
210 ...EMPTY_VCS_ACTION_STATE,
211 isRunning: true,
212 operation: input.operation,
213 actionId,
214 currentLabel: input.label,
215 currentPhaseLabel: input.label,
216 phaseStartedAtMs: startedAt,
217 };
219​
220export function failVcsActionState(
221 operation: VcsActionOperation,
222 actionId: string,
223 error: unknown,
224): VcsActionState {
225 return {
226 ...EMPTY_VCS_ACTION_STATE,
227 operation,
228 actionId,
229 error: error instanceof Error ? error.message : "Source control action failed.",
230 };
232​
233export function createVcsActionTransportId(
234 target: ResolvedVcsActionTarget,
235 actionId: string,
236): string {
237 const targetKey = JSON.stringify([target.environmentId, target.cwd]);
238 return `${targetKey.length}:${targetKey}${actionId}`;
240​
241export function normalizeVcsActionProgressEvent(
242 target: ResolvedVcsActionTarget,
243 transportActionId: string,
244 actionId: string,
245 event: GitActionProgressEvent,
246): GitActionProgressEvent | null {
247 if (event.actionId !== transportActionId || event.cwd !== target.cwd) {
248 return null;
249 }
250 return {
251 ...event,
252 actionId,
253 };
255​
256export function consumeVcsActionProgress<E, R>(
257 stream: Stream.Stream<GitActionProgressEvent, E, R>,
258 input: {
259 readonly target: ResolvedVcsActionTarget;
260 readonly transportActionId: string;
261 readonly actionId: string;
262 readonly action: GitStackedAction;
263 readonly onProgress: (event: GitActionProgressEvent) => Effect.Effect<void>;
264 },
265): Effect.Effect<GitRunStackedActionResult, E | VcsActionExecutionError, R> {
266 return Effect.suspend(() => {
267 let terminalEvent: GitActionProgressEvent | null = null;
268 return stream.pipe(
269 Stream.runForEach((event) => {
270 const normalized = normalizeVcsActionProgressEvent(
271 input.target,
272 input.transportActionId,
273 input.actionId,
274 event,
275 );
276 if (normalized === null) {
277 return Effect.void;
278 }
279 if (normalized.kind === "action_finished" || normalized.kind === "action_failed") {
280 terminalEvent = normalized;
281 }
282 return input.onProgress(normalized);
283 }),
284 Effect.flatMap(() => {
285 if (terminalEvent?.kind === "action_finished") {
286 return Effect.succeed(terminalEvent.result);
287 }
288 if (terminalEvent?.kind === "action_failed") {
289 return Effect.fail<VcsActionExecutionError>(
290 new VcsActionRemoteFailureError({
291 actionId: input.actionId,
292 transportActionId: input.transportActionId,
293 action: terminalEvent.action,
294 environmentId: input.target.environmentId,
295 cwd: input.target.cwd,
296 phase: terminalEvent.phase,
297 remoteMessageLength: terminalEvent.message.length,
298 }),
299 );
300 }
301 return Effect.fail<VcsActionExecutionError>(
302 new VcsActionMissingTerminalEventError({
303 actionId: input.actionId,
304 transportActionId: input.transportActionId,
305 action: input.action,
306 environmentId: input.target.environmentId,
307 cwd: input.target.cwd,
308 }),
309 );
310 }),
311 );
312 });
314​
315export function applyVcsActionProgressEvent(
316 current: VcsActionState,
317 event: GitActionProgressEvent,
318): VcsActionState {
319 if (current.actionId !== event.actionId) {
320 return current;
321 }
322 const now = nowMs();
323​
324 switch (event.kind) {
325 case "action_started":
326 return {
327 ...current,
328 isRunning: true,
329 actionId: event.actionId,
330 action: event.action,
331 operation: "run_change_request",
332 phaseStartedAtMs: now,
333 hookStartedAtMs: null,
334 hookName: null,
335 lastOutputLine: null,
336 error: null,
337 };
338 case "phase_started":
339 return {
340 ...current,
341 isRunning: true,
342 actionId: event.actionId,
343 action: event.action,
344 operation: "run_change_request",
345 currentLabel: event.label,
346 currentPhaseLabel: event.label,
347 phaseStartedAtMs: now,
348 hookStartedAtMs: null,
349 hookName: null,
350 lastOutputLine: null,
351 error: null,
352 };
353 case "hook_started":
354 return {
355 ...current,
356 isRunning: true,
357 actionId: event.actionId,
358 action: event.action,
359 operation: "run_change_request",
360 currentLabel: `Running ${event.hookName}...`,
361 hookName: event.hookName,
362 hookStartedAtMs: now,
363 lastOutputLine: null,
364 error: null,
365 };
366 case "hook_output":
367 return {
368 ...current,
369 isRunning: true,
370 actionId: event.actionId,
371 action: event.action,
372 operation: "run_change_request",
373 lastOutputLine: event.text,
374 error: null,
375 };
376 case "hook_finished":
377 return {
378 ...current,
379 isRunning: true,
380 actionId: event.actionId,
381 action: event.action,
382 operation: "run_change_request",
383 currentLabel: current.currentPhaseLabel,
384 hookName: null,
385 hookStartedAtMs: null,
386 lastOutputLine: null,
387 error: null,
388 };
389 case "action_finished":
390 return {
391 ...EMPTY_VCS_ACTION_STATE,
392 actionId: event.actionId,
393 action: event.action,
394 operation: "run_change_request",
395 };
396 case "action_failed":
397 return {
398 ...EMPTY_VCS_ACTION_STATE,
399 actionId: event.actionId,
400 action: event.action,
401 operation: "run_change_request",
402 error: event.message,
403 };
404 }
406​
407export function createVcsActionManager<R, E>(
408 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
409) {
410 const runStackedActionCommands = new Map<
411 string,
412 AtomCommand<RunVcsStackedActionInput, GitRunStackedActionResult, unknown>
413 >();
414 const getRunStackedActionCommand = (requestedTarget: VcsActionTarget) => {
415 const targetKey = getVcsActionTargetKey(requestedTarget);
416 const commandKey =
417 targetKey ??
418 JSON.stringify([
419 "vcs-action-target:unavailable",
420 requestedTarget.environmentId,
421 requestedTarget.cwd,
422 ]);
423 const existing = runStackedActionCommands.get(commandKey);
424 if (existing !== undefined) {
425 return existing;
426 }
427 const target = targetKey === null ? null : parseVcsActionTargetKey(targetKey);
428 const stateAtom = targetKey === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(targetKey);
429 const command = createRuntimeCommand<
430 EnvironmentRegistry | EnvironmentCacheStore | R,
431 E,
432 RunVcsStackedActionInput,
433 GitRunStackedActionResult,
434 unknown
435 >(runtime, {
436 label: `vcs-action:run-stacked:${commandKey}`,
437 scheduler: vcsCommandScheduler,
438 concurrency: { mode: "serial", key: () => commandKey },
439 execute: (input: RunVcsStackedActionInput, registry) => {
440 if (target === null) {
441 return Effect.fail(
442 new VcsActionUnavailableError({
443 operation: "run_change_request",
444 environmentId: requestedTarget.environmentId,
445 cwd: requestedTarget.cwd,
446 }),
447 );
448 }
449 const transportActionId = createVcsActionTransportId(target, input.actionId);
450 registry.set(
451 stateAtom,
452 beginVcsActionState({
453 operation: "run_change_request",
454 label: "Running source control action",
455 actionId: input.actionId,
456 }),
457 );
458​
459 const rpcInput: GitRunStackedActionInput = {
460 actionId: transportActionId,
461 cwd: target.cwd,
462 action: input.action,
463 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
464 ...(input.featureBranch ? { featureBranch: true } : {}),
465 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
466 };
467 return consumeVcsActionProgress(
468 runStreamInEnvironment(
469 target.environmentId,
470 runStream(WS_METHODS.gitRunStackedAction, rpcInput),
471 ),
472 {
473 target,
474 transportActionId,
475 actionId: input.actionId,
476 action: input.action,
477 onProgress: (event) =>
478 Effect.sync(() => {
479 const current = registry.get(stateAtom);
480 if (current.actionId !== input.actionId) {
481 return;
482 }
483 registry.set(stateAtom, applyVcsActionProgressEvent(current, event));
484 if (input.onProgress !== undefined) {
485 try {
486 input.onProgress(event);
487 } catch {
488 // Presentation callbacks must not fail the source-control operation.
489 }
490 }
491 }),
492 },
493 ).pipe(
494 Effect.ensuring(invalidateCachedVcsRefs(registry, target)),
495 Effect.tapError((error) =>
496 Effect.sync(() => {
497 const current = registry.get(stateAtom);
498 if (current.actionId === input.actionId && current.isRunning) {
499 registry.set(
500 stateAtom,
501 failVcsActionState("run_change_request", input.actionId, error),
502 );
503 }
504 }),
505 ),
506 );
507 },
508 });
509 runStackedActionCommands.set(commandKey, command);
510 return command;
511 };
512​
513 const setState = (
514 registry: AtomRegistry.AtomRegistry,
515 target: VcsActionTarget,
516 update: (current: VcsActionState) => VcsActionState,
517 ): void => {
518 const key = getVcsActionTargetKey(target);
519 if (key === null) {
520 return;
521 }
522 const stateAtom = vcsActionStateAtom(key);
523 registry.set(stateAtom, update(registry.get(stateAtom)));
524 };
525​
526 return {
527 stateAtom: getVcsActionStateAtom,
528 runStackedAction: (target: VcsActionTarget) => getRunStackedActionCommand(target),
529 track: async <A, E>(
530 registry: AtomRegistry.AtomRegistry,
531 target: VcsActionTarget,
532 input: BeginVcsActionInput,
533 action: () => Promise<AtomCommandResult<A, E>>,
534 ): Promise<AtomCommandResult<A, E | VcsActionUnavailableError>> => {
535 const key = getVcsActionTargetKey(target);
536 if (key === null) {
537 return AsyncResult.failure<never, VcsActionUnavailableError>(
538 Cause.fail(
539 new VcsActionUnavailableError({
540 operation: input.operation,
541 environmentId: target.environmentId,
542 cwd: target.cwd,
543 }),
544 ),
545 );
546 }
547 const stateAtom = vcsActionStateAtom(key);
548 const next = beginVcsActionState(input);
549 registry.set(stateAtom, next);
550 const result = await action();
551 const current = registry.get(stateAtom);
552 if (current.actionId !== next.actionId) {
553 return result;
554 }
555 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
556 registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);
557 } else {
558 if (registry.get(stateAtom).actionId === next.actionId) {
559 registry.set(
560 stateAtom,
561 failVcsActionState(input.operation, next.actionId, Cause.squash(result.cause)),
562 );
563 }
564 }
565 return result;
566 },
567 resetError: (
568 registry: AtomRegistry.AtomRegistry,
569 target: VcsActionTarget,
570 operation: VcsActionOperation,
571 ): void => {
572 setState(registry, target, (current) =>
573 !current.isRunning && current.operation === operation ? EMPTY_VCS_ACTION_STATE : current,
574 );
575 },
576 };