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