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

providerMaintenanceRunner.ts

473 lines16.5 KB

1import {
2 defaultInstanceIdForDriver,
3 ProviderDriverKind,
4 ServerProviderUpdateError,
5 type ProviderInstanceId,
6 type ServerProvider,
7 type ServerProviderUpdatedPayload,
8 type ServerProviderUpdateState,
9} from "@t3tools/contracts";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as Data from "effect/Data";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import { HttpClient } from "effect/unstable/http";
22import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23​
24import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
25import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
26import {
27 enrichProviderSnapshotWithVersionAdvisory,
28 type ProviderMaintenanceCommandAction,
29 ProviderVersionCache,
30} from "./providerMaintenance.ts";
31import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
32import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
33const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
34​
35const UPDATE_TIMEOUT_MS = 5 * 60_000;
36const UPDATE_OUTPUT_MAX_BYTES = 10_000;
37​
38export interface ProviderMaintenanceCommandResult {
39 readonly stdout: string;
40 readonly stderr: string;
41 readonly exitCode: number | null;
42 readonly timedOut: boolean;
43 readonly stdoutTruncated: boolean;
44 readonly stderrTruncated: boolean;
46​
47export interface ProviderMaintenanceRunnerShape {
48 readonly updateProvider: (
49 target:
50 | ProviderDriverKind
51 | {
52 readonly provider: ProviderDriverKind;
53 readonly instanceId?: ProviderInstanceId | undefined;
54 },
55 ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
57​
58export class ProviderMaintenanceRunner extends Context.Service<
59 ProviderMaintenanceRunner,
60 ProviderMaintenanceRunnerShape
61>()("t3/provider/providerMaintenanceRunner") {}
62​
63class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
64 readonly message: string;
65 readonly cause?: unknown;
66}> {}
67​
68interface VerifiedProviderRefresh {
69 readonly providers: ReadonlyArray<ServerProvider>;
70 readonly verifiedProviders: ReadonlyArray<ServerProvider>;
72​
73const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
74​
75const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
76 function* (input: {
77 readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
78 readonly command: string;
79 readonly args: ReadonlyArray<string>;
80 readonly env?: NodeJS.ProcessEnv;
81 }) {
82 const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
83 function* () {
84 // Resolve the executable for the host platform before spawning. On
85 // Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),
86 // which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);
87 // resolveSpawnCommand finds the real `.cmd` and routes it through the
88 // shell. On Linux/macOS (incl. the WSL backend) this is a no-op.
89 const resolved = yield* resolveSpawnCommand(input.command, input.args);
90 const child = yield* input.spawner
91 .spawn(
92 ChildProcess.make(resolved.command, resolved.args, {
93 shell: resolved.shell,
94 ...(input.env ? { env: input.env, extendEnv: true } : {}),
95 }),
96 )
97 .pipe(
98 Effect.mapError(
99 (cause) =>
100 new ProviderMaintenanceCommandError({
101 message: `Failed to run update command ${input.command}: ${cause.message}`,
102 cause,
103 }),
104 ),
105 );
106 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
107​
108 const [stdout, stderr, exitCode] = yield* Effect.all(
109 [
110 collectUint8StreamText({
111 stream: child.stdout,
112 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
113 }),
114 collectUint8StreamText({
115 stream: child.stderr,
116 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
117 }),
118 child.exitCode,
119 ],
120 { concurrency: "unbounded" },
121 ).pipe(
122 Effect.mapError(
123 (cause) =>
124 new ProviderMaintenanceCommandError({
125 message: cause instanceof Error ? cause.message : "Update command failed to run.",
126 cause,
127 }),
128 ),
129 );
130​
131 return {
132 stdout: stdout.text,
133 stderr: stderr.text,
134 exitCode: Number(exitCode),
135 timedOut: false,
136 stdoutTruncated: stdout.truncated,
137 stderrTruncated: stderr.truncated,
138 } satisfies ProviderMaintenanceCommandResult;
139 },
140 );
141​
142 return yield* collectCommandResult().pipe(
143 Effect.scoped,
144 Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
145 Effect.map((result) =>
146 Option.match(result, {
147 onSome: (value) => value,
148 onNone: () =>
149 ({
150 stdout: "",
151 stderr: "",
152 exitCode: null,
153 timedOut: true,
154 stdoutTruncated: false,
155 stderrTruncated: false,
156 }) satisfies ProviderMaintenanceCommandResult,
157 }),
158 ),
159 );
160 },
161);
162​
163function trimNullable(value: string): string | null {
164 const trimmed = value.trim();
165 return trimmed.length > 0 ? trimmed : null;
167​
168function truncateText(value: string, maxLength: number): string {
169 return value.length <= maxLength ? value : value.slice(0, maxLength);
171​
172function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
173 const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
174 if (!output) {
175 return null;
176 }
177 return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
179​
180function failureMessage(result: ProviderMaintenanceCommandResult): string {
181 if (result.timedOut) {
182 return "Update timed out.";
183 }
184 if (result.exitCode !== null && result.exitCode !== 0) {
185 return `Update command exited with code ${result.exitCode}.`;
186 }
187 return "Update command failed.";
189​
190function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
191 return provider?.versionAdvisory?.status === "behind_latest";
193​
194function isStillInstalled(provider: ServerProvider): boolean {
195 return provider.installed;
197​
198function makeUpdateState(input: {
199 readonly status: ServerProviderUpdateState["status"];
200 readonly startedAt: string | null;
201 readonly finishedAt: string | null;
202 readonly message: string | null;
203 readonly output?: string | null;
204}): ServerProviderUpdateState {
205 return {
206 status: input.status,
207 startedAt: input.startedAt,
208 finishedAt: input.finishedAt,
209 message: input.message,
210 output: input.output ?? null,
211 };
213​
214export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
215 const providerRegistry = yield* ProviderRegistry;
216 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
217 const httpClient = yield* HttpClient.HttpClient;
218 const versionCache = yield* ProviderVersionCache;
219 const runMaintenanceCommand = (update: ProviderMaintenanceCommandAction) =>
220 runProviderMaintenanceCommandWithSpawner({
221 spawner,
222 command: update.executable,
223 args: update.args,
224 ...(update.env ? { env: update.env } : {}),
225 });
226 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
227 makeAlreadyRunningError: () =>
228 new ServerProviderUpdateError({
229 provider: ProviderDriverKind.make("unknown"),
230 reason: "An update is already running for this provider.",
231 }),
232 });
233​
234 const verifyRefreshedProvider = (
235 provider: ProviderDriverKind,
236 maintenanceCapabilities: ProviderMaintenanceCapabilities,
237 instanceId: ProviderInstanceId,
238 ): Effect.Effect<VerifiedProviderRefresh> =>
239 providerRegistry.getProviders.pipe(
240 Effect.map((providers) => {
241 const instanceIds: Array<ProviderInstanceId> = [];
242 for (const candidate of providers) {
243 if (candidate.driver === provider && candidate.instanceId === instanceId) {
244 instanceIds.push(candidate.instanceId);
245 }
246 }
247 return instanceIds;
248 }),
249 Effect.flatMap((instanceIds) =>
250 instanceIds.length === 0
251 ? providerRegistry.refreshInstance(instanceId)
252 : Effect.forEach(
253 instanceIds,
254 (instanceId) => providerRegistry.refreshInstance(instanceId),
255 {
256 concurrency: "unbounded",
257 discard: true,
258 },
259 ).pipe(Effect.andThen(providerRegistry.getProviders)),
260 ),
261 Effect.flatMap((providers) => {
262 const refreshedProviders = providers.filter(
263 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
264 );
265 if (refreshedProviders.length === 0) {
266 return Effect.succeed<VerifiedProviderRefresh>({
267 providers,
268 verifiedProviders: [],
269 });
270 }
271 return Effect.forEach(
272 refreshedProviders,
273 (refreshedProvider) =>
274 enrichProviderSnapshotWithVersionAdvisory(
275 refreshedProvider,
276 maintenanceCapabilities,
277 ).pipe(
278 Effect.provideService(HttpClient.HttpClient, httpClient),
279 Effect.provideService(ProviderVersionCache, versionCache),
280 ),
281 {
282 concurrency: "unbounded",
283 },
284 ).pipe(
285 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
286 providers,
287 verifiedProviders,
288 })),
289 Effect.catchCause((cause) =>
290 Effect.logWarning("Provider post-update version verification failed", {
291 provider,
292 cause: Cause.pretty(cause),
293 }).pipe(
294 Effect.as<VerifiedProviderRefresh>({
295 providers,
296 verifiedProviders: refreshedProviders,
297 }),
298 ),
299 ),
300 );
301 }),
302 );
303​
304 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
305 "ProviderMaintenanceRunner.updateProvider",
306 )(function* (target) {
307 const provider = typeof target === "string" ? target : target.provider;
308 const instanceId =
309 typeof target === "string"
310 ? defaultInstanceIdForDriver(provider)
311 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
312 const targetKey = `instance:${instanceId}`;
313 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
314 instanceId,
315 provider,
316 );
317 const update = capabilities.update;
318 if (!update) {
319 return yield* new ServerProviderUpdateError({
320 provider,
321 reason: "This provider does not support one-click updates.",
322 });
323 }
324​
325 const setUpdateState = (state: ServerProviderUpdateState | null) =>
326 providerRegistry.setProviderMaintenanceActionState({
327 instanceId,
328 action: "update",
329 state,
330 });
331 const setQueuedState = setUpdateState(
332 makeUpdateState({
333 status: "queued",
334 startedAt: null,
335 finishedAt: null,
336 message: "Waiting for another provider update to finish.",
337 }),
338 ).pipe(Effect.asVoid);
339​
340 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
341 function* () {
342 const finish = (state: ServerProviderUpdateState) =>
343 setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
344 const startedAtRef = yield* Ref.make<string | null>(null);
345​
346 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
347 function* () {
348 const startedAt = yield* nowIso;
349 yield* Ref.set(startedAtRef, startedAt);
350 yield* setUpdateState(
351 makeUpdateState({
352 status: "running",
353 startedAt,
354 finishedAt: null,
355 message: "Updating provider.",
356 }),
357 );
358​
359 // The cached capabilities chose the lock; re-derive ownership
360 // now so the command that runs matches the executable as it is
361 // at click time, not as it was at the last health refresh.
362 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
363 instanceId,
364 provider,
365 { fresh: true },
366 );
367 if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
368 return yield* finish(
369 makeUpdateState({
370 status: "failed",
371 startedAt,
372 finishedAt: yield* nowIso,
373 message: "Provider installation changed. Refresh and try again.",
374 }),
375 );
376 }
377​
378 const result = yield* runMaintenanceCommand(fresh.update);
379 const finishedAt = yield* nowIso;
380 if (result.timedOut || result.exitCode !== 0) {
381 return yield* finish(
382 makeUpdateState({
383 status: "failed",
384 startedAt,
385 finishedAt,
386 message: failureMessage(result),
387 output: commandOutput(result),
388 }),
389 );
390 }
391​
392 // Homebrew's "latest" moves once the upgrade lands; read it again.
393 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
394 instanceId,
395 provider,
396 { fresh: true },
397 );
398 const { verifiedProviders } = yield* verifyRefreshedProvider(
399 provider,
400 verified,
401 instanceId,
402 );
403 // "Succeeded" needs the provider to still be installed: an
404 // installer that exits 0 and leaves the binary missing is not a
405 // success. A missing version alone is not held against it, since
406 // Cursor's `about` probe can fail transiently on a healthy binary.
407 const couldNotVerify =
408 verifiedProviders.length === 0 ||
409 verifiedProviders.some((verifiedProvider) => !isStillInstalled(verifiedProvider));
410 const stillOutdated = verifiedProviders.some((verifiedProvider) =>
411 isOutdatedProvider(verifiedProvider),
412 );
413 return yield* finish(
414 makeUpdateState({
415 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
416 startedAt,
417 finishedAt,
418 message: couldNotVerify
419 ? "Update command completed, but T3 Code could not verify the provider version."
420 : stillOutdated
421 ? "Update command completed, but T3 Code still detects an outdated provider version."
422 : "Provider updated.",
423 output: commandOutput(result),
424 }),
425 );
426 },
427 );
428​
429 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
430 function* (cause: Cause.Cause<unknown>) {
431 const failure = Cause.squash(cause);
432 const startedAt = yield* Ref.get(startedAtRef);
433 return yield* finish(
434 makeUpdateState({
435 status: "failed",
436 startedAt,
437 finishedAt: yield* nowIso,
438 message: failure instanceof Error ? failure.message : "Update command failed.",
439 output: null,
440 }),
441 );
442 },
443 );
444​
445 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
446 },
447 );
448​
449 return yield* commandCoordinator
450 .withCommandLock({
451 targetKey,
452 lockKey: update.lockKey,
453 onQueued: setQueuedState,
454 run: runProviderUpdate(),
455 })
456 .pipe(
457 Effect.mapError((error) =>
458 isServerProviderUpdateError(error)
459 ? new ServerProviderUpdateError({
460 provider,
461 reason: error.reason,
462 })
463 : error,
464 ),
465 );
466 });
467​
468 return ProviderMaintenanceRunner.of({
469 updateProvider,
470 });
471});
472​
473export const layer = Layer.effect(ProviderMaintenanceRunner, make());