Open History to see the last commit
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;
45}
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>;
56}
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>;
71}
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;
166}
167
168function truncateText(value: string, maxLength: number): string {
169 return value.length <= maxLength ? value : value.slice(0, maxLength);
170}
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);
178}
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.";
188}
189
190function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
191 return provider?.versionAdvisory?.status === "behind_latest";
192}
193
194function isStillInstalled(provider: ServerProvider): boolean {
195 return provider.installed;
196}
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 };
212}
213
214/** @public Service construction is part of the canonical Effect module API. */
215export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
216 const providerRegistry = yield* ProviderRegistry;
217 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
218 const httpClient = yield* HttpClient.HttpClient;
219 const versionCache = yield* ProviderVersionCache;
220 const runMaintenanceCommand = (update: ProviderMaintenanceCommandAction) =>
221 runProviderMaintenanceCommandWithSpawner({
222 spawner,
223 command: update.executable,
224 args: update.args,
225 ...(update.env ? { env: update.env } : {}),
226 });
227 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
228 makeAlreadyRunningError: () =>
229 new ServerProviderUpdateError({
230 provider: ProviderDriverKind.make("unknown"),
231 reason: "An update is already running for this provider.",
232 }),
233 });
234
235 const verifyRefreshedProvider = (
236 provider: ProviderDriverKind,
237 maintenanceCapabilities: ProviderMaintenanceCapabilities,
238 instanceId: ProviderInstanceId,
239 ): Effect.Effect<VerifiedProviderRefresh> =>
240 providerRegistry.getProviders.pipe(
241 Effect.map((providers) => {
242 const instanceIds: Array<ProviderInstanceId> = [];
243 for (const candidate of providers) {
244 if (candidate.driver === provider && candidate.instanceId === instanceId) {
245 instanceIds.push(candidate.instanceId);
246 }
247 }
248 return instanceIds;
249 }),
250 Effect.flatMap((instanceIds) =>
251 instanceIds.length === 0
252 ? providerRegistry.refreshInstance(instanceId)
253 : Effect.forEach(
254 instanceIds,
255 (instanceId) => providerRegistry.refreshInstance(instanceId),
256 {
257 concurrency: "unbounded",
258 discard: true,
259 },
260 ).pipe(Effect.andThen(providerRegistry.getProviders)),
261 ),
262 Effect.flatMap((providers) => {
263 const refreshedProviders = providers.filter(
264 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
265 );
266 if (refreshedProviders.length === 0) {
267 return Effect.succeed<VerifiedProviderRefresh>({
268 providers,
269 verifiedProviders: [],
270 });
271 }
272 return Effect.forEach(
273 refreshedProviders,
274 (refreshedProvider) =>
275 enrichProviderSnapshotWithVersionAdvisory(
276 refreshedProvider,
277 maintenanceCapabilities,
278 ).pipe(
279 Effect.provideService(HttpClient.HttpClient, httpClient),
280 Effect.provideService(ProviderVersionCache, versionCache),
281 ),
282 {
283 concurrency: "unbounded",
284 },
285 ).pipe(
286 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
287 providers,
288 verifiedProviders,
289 })),
290 Effect.catchCause((cause) =>
291 Effect.logWarning("Provider post-update version verification failed", {
292 provider,
293 cause: Cause.pretty(cause),
294 }).pipe(
295 Effect.as<VerifiedProviderRefresh>({
296 providers,
297 verifiedProviders: refreshedProviders,
298 }),
299 ),
300 ),
301 );
302 }),
303 );
304
305 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
306 "ProviderMaintenanceRunner.updateProvider",
307 )(function* (target) {
308 const provider = typeof target === "string" ? target : target.provider;
309 const instanceId =
310 typeof target === "string"
311 ? defaultInstanceIdForDriver(provider)
312 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
313 const targetKey = `instance:${instanceId}`;
314 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
315 instanceId,
316 provider,
317 );
318 const update = capabilities.update;
319 if (!update) {
320 return yield* new ServerProviderUpdateError({
321 provider,
322 reason: "This provider does not support one-click updates.",
323 });
324 }
325
326 const setUpdateState = (state: ServerProviderUpdateState | null) =>
327 providerRegistry.setProviderMaintenanceActionState({
328 instanceId,
329 action: "update",
330 state,
331 });
332 const setQueuedState = setUpdateState(
333 makeUpdateState({
334 status: "queued",
335 startedAt: null,
336 finishedAt: null,
337 message: "Waiting for another provider update to finish.",
338 }),
339 ).pipe(Effect.asVoid);
340
341 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
342 function* () {
343 const finish = (state: ServerProviderUpdateState) =>
344 setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
345 const startedAtRef = yield* Ref.make<string | null>(null);
346
347 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
348 function* () {
349 const startedAt = yield* nowIso;
350 yield* Ref.set(startedAtRef, startedAt);
351 yield* setUpdateState(
352 makeUpdateState({
353 status: "running",
354 startedAt,
355 finishedAt: null,
356 message: "Updating provider.",
357 }),
358 );
359
360 // The cached capabilities chose the lock; re-derive ownership
361 // now so the command that runs matches the executable as it is
362 // at click time, not as it was at the last health refresh.
363 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
364 instanceId,
365 provider,
366 { fresh: true },
367 );
368 if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
369 return yield* finish(
370 makeUpdateState({
371 status: "failed",
372 startedAt,
373 finishedAt: yield* nowIso,
374 message: "Provider installation changed. Refresh and try again.",
375 }),
376 );
377 }
378
379 const result = yield* runMaintenanceCommand(fresh.update);
380 const finishedAt = yield* nowIso;
381 if (result.timedOut || result.exitCode !== 0) {
382 return yield* finish(
383 makeUpdateState({
384 status: "failed",
385 startedAt,
386 finishedAt,
387 message: failureMessage(result),
388 output: commandOutput(result),
389 }),
390 );
391 }
392
393 // Homebrew's "latest" moves once the upgrade lands; read it again.
394 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
395 instanceId,
396 provider,
397 { fresh: true },
398 );
399 const { verifiedProviders } = yield* verifyRefreshedProvider(
400 provider,
401 verified,
402 instanceId,
403 );
404 // "Succeeded" needs the provider to still be installed: an
405 // installer that exits 0 and leaves the binary missing is not a
406 // success. A missing version alone is not held against it, since
407 // Cursor's `about` probe can fail transiently on a healthy binary.
408 const couldNotVerify =
409 verifiedProviders.length === 0 ||
410 verifiedProviders.some((verifiedProvider) => !isStillInstalled(verifiedProvider));
411 const stillOutdated = verifiedProviders.some((verifiedProvider) =>
412 isOutdatedProvider(verifiedProvider),
413 );
414 return yield* finish(
415 makeUpdateState({
416 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
417 startedAt,
418 finishedAt,
419 message: couldNotVerify
420 ? "Update command completed, but T3 Code could not verify the provider version."
421 : stillOutdated
422 ? "Update command completed, but T3 Code still detects an outdated provider version."
423 : "Provider updated.",
424 output: commandOutput(result),
425 }),
426 );
427 },
428 );
429
430 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
431 function* (cause: Cause.Cause<unknown>) {
432 const failure = Cause.squash(cause);
433 const startedAt = yield* Ref.get(startedAtRef);
434 return yield* finish(
435 makeUpdateState({
436 status: "failed",
437 startedAt,
438 finishedAt: yield* nowIso,
439 message: failure instanceof Error ? failure.message : "Update command failed.",
440 output: null,
441 }),
442 );
443 },
444 );
445
446 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
447 },
448 );
449
450 return yield* commandCoordinator
451 .withCommandLock({
452 targetKey,
453 lockKey: update.lockKey,
454 onQueued: setQueuedState,
455 run: runProviderUpdate(),
456 })
457 .pipe(
458 Effect.mapError((error) =>
459 isServerProviderUpdateError(error)
460 ? new ServerProviderUpdateError({
461 provider,
462 reason: error.reason,
463 })
464 : error,
465 ),
466 );
467 });
468
469 return ProviderMaintenanceRunner.of({
470 updateProvider,
471 });
472});
473
474export const layer = Layer.effect(ProviderMaintenanceRunner, make());