diff --git a/packages/provider-core/src/server/ProviderLatestVersions.test.ts b/packages/provider-core/src/server/ProviderLatestVersions.test.ts index eafdf4ac3dbc..b7b18e705933 100644 --- a/packages/provider-core/src/server/ProviderLatestVersions.test.ts +++ b/packages/provider-core/src/server/ProviderLatestVersions.test.ts @@ -28,13 +28,14 @@ describe("ProviderLatestVersions", () => { }), ); - it.effect("a waiting caller looks up again when the shared lookup is interrupted", () => + it.effect("interrupting the owner leaves the shared lookup running for its waiters", () => Effect.gen(function* () { const latestVersions = yield* ProviderLatestVersions.make(); + const release = yield* Deferred.make(); let lookups = 0; const lookup = Effect.suspend(() => { lookups += 1; - return lookups === 1 ? Effect.never : Effect.succeed("2.0.0"); + return Deferred.await(release).pipe(Effect.as("2.0.0")); }); const owner = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), { @@ -43,15 +44,15 @@ describe("ProviderLatestVersions", () => { const waiter = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), { startImmediately: true, }); - expect(lookups).toBe(1); yield* Fiber.interrupt(owner); + yield* Deferred.succeed(release, undefined); expect(yield* Fiber.join(waiter)).toBe("2.0.0"); expect(yield* latestVersions.cached("@example/cli", lookup)).toBe("2.0.0"); - expect(lookups).toBe(2); + expect(lookups).toBe(1); }), ); - it.effect("a caller interrupted while it claims the lookup frees the key", () => + it.effect("a caller interrupted while it claims the lookup still starts it", () => Effect.gen(function* () { const latestVersions = yield* ProviderLatestVersions.make(); let lookups = 0; @@ -73,12 +74,8 @@ describe("ProviderLatestVersions", () => { { startImmediately: true }, ); expect(Exit.hasInterrupts(yield* Fiber.await(owner))).toBe(true); - expect(lookups).toBe(0); - const next = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), { - startImmediately: true, - }); + expect(yield* latestVersions.cached("@example/cli", lookup)).toBe("2.0.0"); expect(lookups).toBe(1); - expect(yield* Fiber.join(next)).toBe("2.0.0"); }), ); it.effect("a waiting caller retries with its own lookup after the owner fails", () => diff --git a/packages/provider-core/src/server/ProviderLatestVersions.ts b/packages/provider-core/src/server/ProviderLatestVersions.ts index 92239311e4c4..b35b775a2dc0 100644 --- a/packages/provider-core/src/server/ProviderLatestVersions.ts +++ b/packages/provider-core/src/server/ProviderLatestVersions.ts @@ -4,6 +4,7 @@ import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -33,6 +34,7 @@ export class ProviderLatestVersions extends Context.Service< export const make = Effect.fn("ProviderLatestVersions.make")(function* ( seed: Iterable = [], ) { + const scope = yield* Effect.scope; const entries = yield* Ref.make( new Map( Array.from(seed, ([key, version]) => [key, { version, expiresAt: Number.MAX_SAFE_INTEGER }]), @@ -45,35 +47,38 @@ export const make = Effect.fn("ProviderLatestVersions.make")(function* ( const inFlight = yield* Deferred.make>(); // Replacing or invalidating this entry retires any lookup still in flight. const pending: Entry = { version: null, expiresAt: 0, inFlight }; - // Claim and cleanup registration must be atomic with respect to interruption. - return yield* Effect.acquireUseRelease( - Ref.modify(entries, (current) => { - const entry = current.get(key); - return !options?.fresh && entry && (entry.expiresAt > now || entry.inFlight) - ? [entry, current] - : [undefined, new Map(current).set(key, pending)]; + const settle = (exit: Exit.Exit) => { + const version = Exit.isSuccess(exit) ? Option.some(exit.value) : Option.none(); + return Ref.update(entries, (current) => { + if (current.get(key) !== pending) return current; + const next = new Map(current); + if (Option.isNone(version)) { + next.delete(key); + return next; + } + const ttl = version.value === null ? MISSING_TTL : FOUND_TTL; + return next.set(key, { version: version.value, expiresAt: now + Duration.toMillis(ttl) }); + }).pipe(Effect.andThen(Deferred.succeed(inFlight, version)), Effect.asVoid); + }; + // Claiming the key and starting its lookup must be atomic with respect to interruption. + return yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const existing = yield* Ref.modify(entries, (current) => { + const entry = current.get(key); + return !options?.fresh && entry && (entry.expiresAt > now || entry.inFlight) + ? [entry, current] + : [undefined, new Map(current).set(key, pending)]; + }); + if (!existing) { + // Interrupting a caller must not kill the lookup: a killed `npm view` leaves its + // partial download behind, and the next caller would start the download over. + const fiber = yield* restore(lookup).pipe(Effect.onExit(settle), Effect.forkIn(scope)); + return yield* restore(Fiber.join(fiber)); + } + if (!existing.inFlight) return existing.version; + const shared = yield* restore(Deferred.await(existing.inFlight)); + return Option.isSome(shared) ? shared.value : yield* restore(cached(key, lookup, options)); }), - (existing) => - Effect.gen(function* () { - if (!existing) return yield* lookup; - if (!existing.inFlight) return existing.version; - const shared = yield* Deferred.await(existing.inFlight); - return Option.isSome(shared) ? shared.value : yield* cached(key, lookup, options); - }), - (existing, exit) => { - if (existing) return Effect.void; - const version = Exit.isSuccess(exit) ? Option.some(exit.value) : Option.none(); - return Ref.update(entries, (current) => { - if (current.get(key) !== pending) return current; - const next = new Map(current); - if (Option.isNone(version)) { - next.delete(key); - return next; - } - const ttl = version.value === null ? MISSING_TTL : FOUND_TTL; - return next.set(key, { version: version.value, expiresAt: now + Duration.toMillis(ttl) }); - }).pipe(Effect.andThen(Deferred.succeed(inFlight, version)), Effect.asVoid); - }, ); }); return ProviderLatestVersions.of({ diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index f392f4b54696..21b1f4da5d1e 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -436,6 +436,83 @@ it.layer( { skip: !symlinksSupported || windowsHost }, ); + // A killed `npm view` leaves its partial packument in npm's cache tmp dir. + it.effect.skipIf(!symlinksSupported || windowsHost)( + "neither a refresh nor the probe timeout kills a slow npm version check or starts another download", + () => + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-interrupted-npm-view"); + const npmBinDir = NodePath.join(tempDir, "npm-bin"); + writeExecutable(NodePath.join(npmBinDir, "npm")); + const binaryPath = NodePath.join(tempDir, ".local/bin/native-package-tool"); + writeExecutable(binaryPath); + const spawned = yield* Deferred.make(); + const download = yield* Deferred.make(); + let spawns = 0; + let downloaded = false; + let killedMidDownload = 0; + const slowNpmView = ChildProcessSpawner.make(() => + Effect.sync(() => { + spawns++; + Deferred.doneUnsafe(spawned, Effect.void); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(spawns), + exitCode: Deferred.await(download).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + isRunning: Effect.succeed(true), + kill: () => + Effect.sync(() => { + if (!downloaded) killedMidDownload++; + }), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.fromEffect(Deferred.await(download)).pipe( + Stream.as('"1.2.0"'), + Stream.encodeText, + ), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ); + const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( + nativePackageToolUpdate, + { binaryPath, env: { PATH: "" } }, + ).pipe( + Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, slowNpmView), + ); + const check = enrichProviderSnapshotWithVersionAdvisory( + installedPackageToolProvider, + capabilities, + ); + + const first = yield* Effect.forkChild(check); + yield* Deferred.await(spawned); + // A provider refresh interrupts the enrichment still in flight. + yield* Fiber.interrupt(first); + const second = yield* Effect.forkChild(check); + yield* Effect.yieldNow; + // A slow registry outlasts the probe timeout. + yield* TestClock.adjust("1 minute"); + downloaded = true; + yield* Deferred.succeed(download, undefined); + const snapshot = yield* Fiber.join(second); + + expect(snapshot.versionAdvisory?.latestVersion).toBe("1.2.0"); + expect({ spawns, killedMidDownload }).toEqual({ spawns: 1, killedMidDownload: 0 }); + }).pipe( + Effect.provide(ProviderLatestVersions.layer), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => + Effect.die("a configured npm lookup must not fall back to public npm"), + ), + ), + ), + ); + it.effect.skipIf(windowsHost)( "does not offer a Vite+ update npm's release-age policy will not install", () => diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 583bb1e02111..18f18da5f63e 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -40,6 +40,9 @@ import * as ProviderLatestVersions from "./ProviderLatestVersions.ts"; const LATEST_VERSION_TIMEOUT_MS = 4_000; const PROBE_TIMEOUT_MS = 10_000; +// npm leaves a killed packument download in its cache's tmp dir, so registry probes are +// bounded by npm's own fetch-timeout instead of being killed. +const NPM_REGISTRY_PROBE_TIMEOUT = null; const PROBE_MAX_BYTES = 256 * 1_024; const WRAPPER_SCRIPT_MAX_BYTES = 16 * 1_024; const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings."; @@ -415,6 +418,7 @@ const runProbe = Effect.fn("runProbe")(function* ( args: ReadonlyArray, env: NodeJS.ProcessEnv, okExitCodes: ReadonlyArray = [0], + timeoutMs: number | null = PROBE_TIMEOUT_MS, ) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const collect = Effect.gen(function* () { @@ -441,8 +445,13 @@ const runProbe = Effect.fn("runProbe")(function* ( }); return yield* collect.pipe( Effect.scoped, - Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)), - Effect.map(Option.getOrNull), + (scoped) => + timeoutMs === null + ? scoped + : scoped.pipe( + Effect.timeoutOption(Duration.millis(timeoutMs)), + Effect.map(Option.getOrNull), + ), Effect.catchCause((cause) => Effect.logWarning("Maintenance probe failed", { command, @@ -537,6 +546,7 @@ const runNpmGlobalLatestVersions = Effect.fn("runNpmGlobalLatestVersions")(funct env, // npm outdated exits 1 when updates are available. [0, 1], + NPM_REGISTRY_PROBE_TIMEOUT, ); const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined; // npm prints failures such as an unreachable registry as `{"error": ...}`, also exiting 1. @@ -1315,6 +1325,8 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup npmPath, ["view", "--global", "--json", `${packageName}@latest`, "version"], env, + [0], + NPM_REGISTRY_PROBE_TIMEOUT, ).pipe( Effect.map((stdout) => { const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null;