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

providerMaintenanceRunner.ts

590 lines21.8 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 Schedule from "effect/Schedule";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import { HttpClient } from "effect/http";
24import { ChildProcess, ChildProcessSpawner } from "effect/process";
25import * as NodeUtil from "node:util";
26​
27import * as ModelManifest from "./ModelManifest.ts";
28import { resolveProviderCompatibility } from "./providerCompatibility.ts";
29import * as ProviderRegistry from "./ProviderRegistry.ts";
30import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
31import {
32 enrichProviderSnapshotWithVersionAdvisory,
33 makeTargetedProviderUpdateAction,
34 resolveLatestProviderVersion,
35 type ProviderMaintenanceCommandAction,
36} from "@t3tools/provider-core/server/maintenanceResolver";
37import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
38import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
39import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
40const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
41​
42const UPDATE_TIMEOUT_MS = 5 * 60_000;
43const UPDATE_OUTPUT_MAX_BYTES = 10_000;
44// Every progress publish resends the provider list to each client, so the
45// installer's output is sampled rather than forwarded line by line.
46const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1);
47const UPDATE_PROGRESS_MAX_LENGTH = 200;
48// An installer may write for minutes without a line ending; only its tail matters.
49const UPDATE_PARTIAL_LINE_MAX_LENGTH = 4_096;
50​
51export interface ProviderMaintenanceCommandResult {
52 readonly stdout: string;
53 readonly stderr: string;
54 readonly exitCode: number | null;
55 readonly timedOut: boolean;
56 readonly stdoutTruncated: boolean;
57 readonly stderrTruncated: boolean;
59​
60export interface ProviderMaintenanceRunnerShape {
61 readonly updateProvider: (
62 target:
63 | ProviderDriverKind
64 | {
65 readonly provider: ProviderDriverKind;
66 readonly instanceId?: ProviderInstanceId | undefined;
67 readonly targetVersion?: string | undefined;
68 },
69 ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
71​
72export class ProviderMaintenanceRunner extends Context.Service<
73 ProviderMaintenanceRunner,
74 ProviderMaintenanceRunnerShape
75>()("t3/provider/providerMaintenanceRunner") {}
76​
77class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
78 readonly message: string;
79 readonly cause?: unknown;
80}> {}
81​
82interface VerifiedProviderRefresh {
83 readonly providers: ReadonlyArray<ServerProvider>;
84 readonly verifiedProviders: ReadonlyArray<ServerProvider>;
86​
87const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
88​
89const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
90 function* (input: {
91 readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
92 readonly command: string;
93 readonly args: ReadonlyArray<string>;
94 readonly env?: NodeJS.ProcessEnv;
95 readonly onProgress?: (line: string) => Effect.Effect<void>;
96 }) {
97 const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
98 function* () {
99 // On Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`), which a bare
100 // ChildProcess.spawn cannot launch (spawn npm ENOENT); resolveSpawnCommand finds the
101 // real `.cmd` and routes it through the shell.
102 const resolved = yield* resolveSpawnCommand(input.command, input.args);
103 const child = yield* input.spawner
104 .spawn(
105 ChildProcess.make(resolved.command, resolved.args, {
106 shell: resolved.shell,
107 ...(input.env ? { env: input.env, extendEnv: true } : {}),
108 }),
109 )
110 .pipe(
111 Effect.mapError(
112 (cause) =>
113 new ProviderMaintenanceCommandError({
114 message: `Failed to run update command ${input.command}: ${cause.message}`,
115 cause,
116 }),
117 ),
118 );
119 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
120​
121 const pendingProgress = yield* Ref.make<string | null>(null);
122 const onProgress = input.onProgress;
123 if (onProgress) {
124 yield* Ref.getAndSet(pendingProgress, null).pipe(
125 Effect.flatMap((line) => (line === null ? Effect.void : onProgress(line))),
126 Effect.repeat(Schedule.spaced(UPDATE_PROGRESS_INTERVAL)),
127 Effect.forkScoped,
128 );
129 }
130 const trackProgress = <E>(stream: Stream.Stream<Uint8Array, E>) => {
131 if (!onProgress) {
132 return stream;
133 }
134 const decoder = new TextDecoder();
135 let partialLine = "";
136 return stream.pipe(
137 Stream.tap((chunk) => {
138 const split = splitOutputLines(partialLine, decoder.decode(chunk, { stream: true }));
139 partialLine = split.partialLine;
140 const line =
141 toProgressLine(split.partialLine) ??
142 split.lines.map(toProgressLine).findLast((value) => value !== null);
143 return line ? Ref.set(pendingProgress, line) : Effect.void;
144 }),
145 );
146 };
147​
148 const [stdout, stderr, exitCode] = yield* Effect.all(
149 [
150 collectUint8StreamText({
151 stream: trackProgress(child.stdout),
152 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
153 }),
154 collectUint8StreamText({
155 stream: trackProgress(child.stderr),
156 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
157 }),
158 child.exitCode,
159 ],
160 { concurrency: "unbounded" },
161 ).pipe(
162 Effect.mapError(
163 (cause) =>
164 new ProviderMaintenanceCommandError({
165 message: cause instanceof Error ? cause.message : "Update command failed to run.",
166 cause,
167 }),
168 ),
169 );
170​
171 return {
172 stdout: stdout.text,
173 stderr: stderr.text,
174 exitCode: Number(exitCode),
175 timedOut: false,
176 stdoutTruncated: stdout.truncated,
177 stderrTruncated: stderr.truncated,
178 } satisfies ProviderMaintenanceCommandResult;
179 },
180 );
181​
182 return yield* collectCommandResult().pipe(
183 Effect.scoped,
184 Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
185 Effect.map((result) =>
186 Option.match(result, {
187 onSome: (value) => value,
188 onNone: () =>
189 ({
190 stdout: "",
191 stderr: "",
192 exitCode: null,
193 timedOut: true,
194 stdoutTruncated: false,
195 stderrTruncated: false,
196 }) satisfies ProviderMaintenanceCommandResult,
197 }),
198 ),
199 );
200 },
201);
202​
203export function splitOutputLines(
204 partialLine: string,
205 text: string,
206): { readonly lines: ReadonlyArray<string>; readonly partialLine: string } {
207 const parts = (partialLine + text).split(/\r\n|\r|\n/);
208 return { partialLine: (parts.pop() ?? "").slice(-UPDATE_PARTIAL_LINE_MAX_LENGTH), lines: parts };
210​
211export function toProgressLine(line: string): string | null {
212 const text = NodeUtil.stripVTControlCharacters(line).replace(/\s+/g, " ").trim();
213 if (text.length === 0) {
214 return null;
215 }
216 return text.length <= UPDATE_PROGRESS_MAX_LENGTH
217 ? text
218 : `${text.slice(0, UPDATE_PROGRESS_MAX_LENGTH - 1)}…`;
220​
221function describeCommand(command: ProviderMaintenanceCommandAction): string {
222 const executable = command.executable.split(/[\\/]/).pop() || command.executable;
223 return [executable, ...command.args].join(" ");
225​
226function trimNullable(value: string): string | null {
227 const trimmed = value.trim();
228 return trimmed.length > 0 ? trimmed : null;
230​
231function truncateText(value: string, maxLength: number): string {
232 return value.length <= maxLength ? value : value.slice(0, maxLength);
234​
235function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
236 const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
237 if (!output) {
238 return null;
239 }
240 return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
242​
243function failureMessage(result: ProviderMaintenanceCommandResult): string {
244 if (result.timedOut) {
245 return "Update timed out.";
246 }
247 if (result.exitCode !== null && result.exitCode !== 0) {
248 return `Update command exited with code ${result.exitCode}.`;
249 }
250 return "Update command failed.";
252​
253function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
254 return provider?.versionAdvisory?.status === "behind_latest";
256​
257function isStillInstalled(provider: ServerProvider): boolean {
258 return provider.installed;
260​
261function makeUpdateState(input: {
262 readonly status: ServerProviderUpdateState["status"];
263 readonly startedAt: string | null;
264 readonly finishedAt: string | null;
265 readonly message: string | null;
266 readonly output?: string | null;
267}): ServerProviderUpdateState {
268 return {
269 status: input.status,
270 startedAt: input.startedAt,
271 finishedAt: input.finishedAt,
272 message: input.message,
273 output: input.output ?? null,
274 };
276​
277/** @public Service construction is part of the canonical Effect module API. */
278export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
279 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
280 const manifestService = yield* ModelManifest.ModelManifest;
281 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
282 const httpClient = yield* HttpClient.HttpClient;
283 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
284 const runMaintenanceCommand = (
285 update: ProviderMaintenanceCommandAction,
286 onProgress: (line: string) => Effect.Effect<void>,
287 ) =>
288 runProviderMaintenanceCommandWithSpawner({
289 spawner,
290 command: update.executable,
291 args: update.args,
292 onProgress,
293 ...(update.env ? { env: update.env } : {}),
294 });
295 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
296 makeAlreadyRunningError: () =>
297 new ServerProviderUpdateError({
298 provider: ProviderDriverKind.make("unknown"),
299 reason: "An update is already running for this provider.",
300 }),
301 });
302​
303 const verifyRefreshedProvider = (
304 provider: ProviderDriverKind,
305 maintenanceCapabilities: ProviderMaintenanceCapabilities,
306 instanceId: ProviderInstanceId,
307 ): Effect.Effect<VerifiedProviderRefresh> =>
308 providerRegistry.getProviders.pipe(
309 Effect.map((providers) => {
310 const instanceIds: Array<ProviderInstanceId> = [];
311 for (const candidate of providers) {
312 if (candidate.driver === provider && candidate.instanceId === instanceId) {
313 instanceIds.push(candidate.instanceId);
314 }
315 }
316 return instanceIds;
317 }),
318 Effect.flatMap((instanceIds) =>
319 instanceIds.length === 0
320 ? providerRegistry.refreshInstance(instanceId)
321 : Effect.forEach(
322 instanceIds,
323 (instanceId) => providerRegistry.refreshInstance(instanceId),
324 {
325 concurrency: "unbounded",
326 discard: true,
327 },
328 ).pipe(Effect.andThen(providerRegistry.getProviders)),
329 ),
330 Effect.flatMap((providers) => {
331 const refreshedProviders = providers.filter(
332 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
333 );
334 if (refreshedProviders.length === 0) {
335 return Effect.succeed<VerifiedProviderRefresh>({
336 providers,
337 verifiedProviders: [],
338 });
339 }
340 return Effect.forEach(
341 refreshedProviders,
342 (refreshedProvider) =>
343 enrichProviderSnapshotWithVersionAdvisory(
344 refreshedProvider,
345 maintenanceCapabilities,
346 ).pipe(
347 Effect.provideService(HttpClient.HttpClient, httpClient),
348 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
349 ),
350 {
351 concurrency: "unbounded",
352 },
353 ).pipe(
354 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
355 providers,
356 verifiedProviders,
357 })),
358 Effect.catchCause((cause) =>
359 Effect.logWarning("Provider post-update version verification failed", {
360 provider,
361 cause: Cause.pretty(cause),
362 }).pipe(
363 Effect.as<VerifiedProviderRefresh>({
364 providers,
365 verifiedProviders: refreshedProviders,
366 }),
367 ),
368 ),
369 );
370 }),
371 );
372​
373 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
374 "ProviderMaintenanceRunner.updateProvider",
375 )(function* (target) {
376 const provider = typeof target === "string" ? target : target.provider;
377 const instanceId =
378 typeof target === "string"
379 ? defaultInstanceIdForDriver(provider)
380 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
381 const targetVersion = typeof target === "string" ? undefined : target.targetVersion;
382 const targetKey = `instance:${instanceId}`;
383 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
384 instanceId,
385 provider,
386 );
387 const update = capabilities.update;
388 if (!update) {
389 return yield* new ServerProviderUpdateError({
390 provider,
391 reason: "This provider does not support one-click updates.",
392 });
393 }
394​
395 const setUpdateState = (state: ServerProviderUpdateState | null) =>
396 providerRegistry.setProviderMaintenanceActionState({
397 instanceId,
398 action: "update",
399 state,
400 });
401 const setQueuedState = setUpdateState(
402 makeUpdateState({
403 status: "queued",
404 startedAt: null,
405 finishedAt: null,
406 message: "Waiting for another provider update to finish.",
407 }),
408 ).pipe(Effect.asVoid);
409​
410 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
411 function* () {
412 const finish = (state: ServerProviderUpdateState) =>
413 setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
414 const startedAtRef = yield* Ref.make<string | null>(null);
415​
416 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
417 function* () {
418 const startedAt = yield* nowIso;
419 yield* Ref.set(startedAtRef, startedAt);
420 const setRunningMessage = (message: string) =>
421 setUpdateState(
422 makeUpdateState({
423 status: "running",
424 startedAt,
425 finishedAt: null,
426 message,
427 }),
428 ).pipe(Effect.asVoid);
429 yield* setRunningMessage("Checking for the latest version");
430​
431 // The cached capabilities chose the lock; re-derive ownership
432 // now so the command that runs matches the executable as it is
433 // at click time, not as it was at the last health refresh.
434 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
435 instanceId,
436 provider,
437 { fresh: true },
438 );
439 if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
440 return yield* finish(
441 makeUpdateState({
442 status: "failed",
443 startedAt,
444 finishedAt: yield* nowIso,
445 message: "Provider installation changed. Refresh and try again.",
446 }),
447 );
448 }
449​
450 const manifest = yield* manifestService.current;
451 const candidateVersion =
452 targetVersion ??
453 (yield* resolveLatestProviderVersion(fresh).pipe(
454 Effect.provideService(HttpClient.HttpClient, httpClient),
455 Effect.provideService(
456 ProviderLatestVersions.ProviderLatestVersions,
457 latestVersions,
458 ),
459 ));
460 const advisory =
461 resolveProviderCompatibility(manifest.compatibility, provider, candidateVersion) ??
462 resolveProviderCompatibility(
463 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
464 provider,
465 candidateVersion,
466 );
467 const command =
468 targetVersion !== undefined
469 ? makeTargetedProviderUpdateAction(fresh, targetVersion)
470 : fresh.update;
471 const rejected =
472 targetVersion !== undefined
473 ? !command ||
474 advisory?.recommendedVersion !== targetVersion ||
475 advisory.status !== "supported"
476 : advisory?.status === "broken" || advisory?.status === "unsupported";
477 if (rejected || !command) {
478 return yield* finish(
479 makeUpdateState({
480 status: "failed",
481 startedAt,
482 finishedAt: yield* nowIso,
483 message:
484 targetVersion !== undefined
485 ? "This version is no longer recommended or this installer cannot install a specific version. Refresh provider settings."
486 : "The latest provider version is incompatible with this T3 Code release. Review provider settings.",
487 }),
488 );
489 }
490 yield* setRunningMessage(`Running ${describeCommand(command)}`);
491 const result = yield* runMaintenanceCommand(command, setRunningMessage);
492 const finishedAt = yield* nowIso;
493 if (result.timedOut || result.exitCode !== 0) {
494 return yield* finish(
495 makeUpdateState({
496 status: "failed",
497 startedAt,
498 finishedAt,
499 message: failureMessage(result),
500 output: commandOutput(result),
501 }),
502 );
503 }
504​
505 yield* setRunningMessage("Verifying the installed version");
506 // Homebrew's "latest" moves once the upgrade lands; read it again.
507 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
508 instanceId,
509 provider,
510 { fresh: true },
511 );
512 const { verifiedProviders } = yield* verifyRefreshedProvider(
513 provider,
514 verified,
515 instanceId,
516 );
517 // A missing version alone is not held against it, since Cursor's `about` probe can
518 // fail transiently on a healthy binary.
519 const couldNotVerify =
520 verifiedProviders.length === 0 ||
521 verifiedProviders.some(
522 (verifiedProvider) =>
523 !isStillInstalled(verifiedProvider) ||
524 (targetVersion !== undefined &&
525 verifiedProvider.version?.replace(/^v/, "") !== targetVersion),
526 );
527 const stillOutdated =
528 targetVersion === undefined &&
529 verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
530 return yield* finish(
531 makeUpdateState({
532 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
533 startedAt,
534 finishedAt,
535 message: couldNotVerify
536 ? "Update command completed, but T3 Code could not verify the provider version."
537 : stillOutdated
538 ? "Update command completed, but T3 Code still detects an outdated provider version."
539 : "Provider updated.",
540 output: commandOutput(result),
541 }),
542 );
543 },
544 );
545​
546 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
547 function* (cause: Cause.Cause<unknown>) {
548 const failure = Cause.squash(cause);
549 const startedAt = yield* Ref.get(startedAtRef);
550 return yield* finish(
551 makeUpdateState({
552 status: "failed",
553 startedAt,
554 finishedAt: yield* nowIso,
555 message: failure instanceof Error ? failure.message : "Update command failed.",
556 output: null,
557 }),
558 );
559 },
560 );
561​
562 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
563 },
564 );
565​
566 return yield* commandCoordinator
567 .withCommandLock({
568 targetKey,
569 lockKey: update.lockKey,
570 onQueued: setQueuedState,
571 run: runProviderUpdate(),
572 })
573 .pipe(
574 Effect.mapError((error) =>
575 isServerProviderUpdateError(error)
576 ? new ServerProviderUpdateError({
577 provider,
578 reason: error.reason,
579 })
580 : error,
581 ),
582 );
583 });
584​
585 return ProviderMaintenanceRunner.of({
586 updateProvider,
587 });
588});
589​
590export const layer = Layer.effect(ProviderMaintenanceRunner, make());