TypeScript
fix(connect): a quit mid-download no longer wedges the relay client install (#22747)
jooyyy.eth3776dfb4ea6a
diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.tsindex 0a987832ff7..d2719c9ac33 100644--- a/packages/shared/src/relayClient.test.ts+++ b/packages/shared/src/relayClient.test.ts@@ -1,6 +1,7 @@import { sha256 } from "@noble/hashes/sha2";import * as NodeServices from "@effect/platform-node/NodeServices";import { describe, expect, it } from "@effect/vitest";+import * as Clock from "effect/Clock";import * as ConfigProvider from "effect/ConfigProvider";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -8,9 +9,11 @@ import * as Fiber from "effect/Fiber";import * as Hex from "effect/encoding/Hex";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";import * as PlatformError from "effect/PlatformError";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import { HttpClient, HttpClientResponse } from "effect/http";import { ChildProcess, ChildProcessSpawner } from "effect/process";import * as HostProcess from "./HostProcess.ts";@@ -156,12 +159,12 @@ describe("RelayClient", () => {const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(Effect.provideService(FileSystem.FileSystem, {...fileSystem,- writeFileString: (path, contents, options) =>+ rename: (from, to) =>fileSystem- .writeFileString(path, contents, options)+ .rename(from, to).pipe(Effect.tapError(() =>- path === lockPath ? Deferred.succeed(contended, undefined) : Effect.void,+ to === lockPath ? Deferred.succeed(contended, undefined) : Effect.void,),),}),@@ -183,6 +186,135 @@ describe("RelayClient", () => {),);+ it.effect.each(["live owner", "recent legacy"] as const)("keeps a lock with a %s", (kind) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });+ const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;+ const owner = `${process.pid}-still-running`;+ yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {+ recursive: true,+ });+ if (kind === "live owner") {+ yield* fileSystem.makeDirectory(lockPath);+ yield* fileSystem.writeFileString(`${lockPath}/${owner}`, "");+ } else {+ yield* fileSystem.writeFileString(lockPath, "");+ }+ const written = yield* fileSystem.stat(lockPath);+ yield* TestClock.setTime(+ Option.getOrThrow(written.mtime).getTime() + (kind === "live owner" ? 3_600_000 : 6_000),+ );+ const waiting = yield* Deferred.make<void>();+ const clock = yield* Clock.Clock;+ const manager = yield* RelayClient.makeCloudflaredRelayClient({+ baseDir,+ releaseAsset: testReleaseAsset,+ });+ const installing = yield* manager.install.pipe(+ Effect.provideService(Clock.Clock, {+ ...clock,+ sleep: () => Deferred.succeed(waiting, undefined).pipe(Effect.andThen(Effect.never)),+ }),+ Effect.forkChild,+ );+ yield* Deferred.await(waiting);+ yield* Fiber.interrupt(installing);+ if (kind === "live owner") {+ expect(yield* fileSystem.readDirectory(lockPath)).toEqual([owner]);+ } else {+ expect(yield* fileSystem.readFileString(lockPath)).toBe("");+ }+ }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),+ );++ it.effect.skipIf(windowsHost)("replaces an install lock left by an exited installer", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-cloudflared-test-",+ });+ const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;+ yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {+ recursive: true,+ });+ yield* fileSystem.makeDirectory(lockPath);+ yield* fileSystem.writeFileString(`${lockPath}/2147483647-exited-installer`, "");+ const manager = yield* RelayClient.makeCloudflaredRelayClient({+ baseDir,+ releaseAsset: testReleaseAsset,+ });++ expect(yield* manager.install).toMatchObject({ status: "available" });+ expect(yield* fileSystem.exists(lockPath)).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),+ );++ it.effect.skipIf(windowsHost)("replaces an empty install lock left by an exited installer", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-cloudflared-test-",+ });+ const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;+ yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {+ recursive: true,+ });+ yield* fileSystem.writeFileString(lockPath, "");+ const written = yield* fileSystem.stat(lockPath);+ const mtime = Option.getOrThrow(written.mtime).getTime();+ // File mtimes use wall time; advance the test clock past legacy expiry.+ yield* TestClock.setTime(mtime + 60 * 60 * 1_000);+ const manager = yield* RelayClient.makeCloudflaredRelayClient({+ baseDir,+ releaseAsset: testReleaseAsset,+ });++ expect(yield* manager.install).toMatchObject({ status: "available" });+ expect(yield* fileSystem.exists(lockPath)).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),+ );++ it.effect("keeps a replacement lock when a stale contender resumes cleanup", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });+ const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;+ const abandoned = "2147483647-exited-installer";+ const replacement = `${process.pid}-replacement`;+ yield* fileSystem.makeDirectory(lockPath, { recursive: true });+ yield* fileSystem.writeFileString(`${lockPath}/${abandoned}`, "");+ const checked = yield* Deferred.make<void>();+ let replaced = false;+ const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(+ Effect.provideService(FileSystem.FileSystem, {+ ...fileSystem,+ readDirectory: (path) =>+ fileSystem.readDirectory(path).pipe(+ Effect.tap((entries) =>+ Effect.gen(function* () {+ if (path !== lockPath) return;+ if (replaced) {+ expect(entries).toEqual([replacement]);+ yield* Deferred.succeed(checked, undefined);+ return;+ }+ replaced = true;+ yield* fileSystem.rename(lockPath, `${lockPath}.old`);+ yield* fileSystem.makeDirectory(lockPath);+ yield* fileSystem.writeFileString(`${lockPath}/${replacement}`, "");+ }),+ ),+ ),+ }),+ );+ const installing = yield* manager.install.pipe(Effect.forkChild);+ yield* Deferred.await(checked);+ yield* Fiber.interrupt(installing);+ expect(yield* fileSystem.readDirectory(lockPath)).toEqual([replacement]);+ }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),+ );+it.effect("releases the install lock when a download is cancelled", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;@@ -232,12 +364,12 @@ describe("RelayClient", () => {}).pipe(Effect.provideService(FileSystem.FileSystem, {...fileSystem,- writeFileString: (path, contents, options) =>+ rename: (from, to) =>fileSystem- .writeFileString(path, contents, options)+ .rename(from, to).pipe(Effect.tap(() =>- path === lockPath && pauseWrite+ to === lockPath && pauseWrite? Deferred.succeed(acquired, undefined).pipe(Effect.andThen(Deferred.await(completeWrite)),)diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.tsindex 5933ea7e6a0..e56ef42ee1a 100644--- a/packages/shared/src/relayClient.ts+++ b/packages/shared/src/relayClient.ts@@ -1,3 +1,5 @@+// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.remove cannot remove an empty directory nonrecursively.+import * as NodeFSP from "node:fs/promises";import * as Cache from "effect/Cache";import * as Clock from "effect/Clock";import type {@@ -16,7 +18,7 @@ import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";-import * as PlatformError from "effect/PlatformError";+import type * as PlatformError from "effect/PlatformError";import * as Schedule from "effect/Schedule";import * as Semaphore from "effect/Semaphore";import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";@@ -115,7 +117,8 @@ const CLOUDFLARED_RELEASE_ASSETS: Readonly<const INSTALL_LOCK_RETRY_COUNT = 100;const INSTALL_LOCK_RETRY_DELAY = "100 millis";-const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;+// Legacy locks have no owner; allow both ten-minute download stages and the install tail.+const INSTALL_LOCK_LEGACY_STALE_MS = 30 * 60 * 1_000;const VERSION_PROBE_TIMEOUT = "10 seconds";const ACTIVATE_RETRY_COUNT = 40;@@ -194,8 +197,30 @@ class VersionProbeKey extends Data.Class<{readonly mtimeMillis: number;}> {}-function isAlreadyExists(error: PlatformError.PlatformError): boolean {- return error.reason._tag === "AlreadyExists";+function isLockContention(error: PlatformError.PlatformError): boolean {+ const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;+ return (+ error.reason._tag === "AlreadyExists" ||+ error.reason._tag === "BadResource" ||+ code === "ENOTEMPTY" ||+ isWindowsRenameLock(error)+ );+}++function parseLockOwnerPid(owner: string): number | null {+ const separator = owner.indexOf("-");+ if (separator <= 0) return null;+ const pid = Number(owner.slice(0, separator));+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;+}++function processIsAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as { readonly code?: unknown }).code !== "ESRCH";+ }}const wrapInstallFailure =@@ -456,25 +481,65 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(functionreturn bytes;});+ const removeEmptyLock = (lockPath: string) =>+ Effect.tryPromise(() => NodeFSP.rmdir(lockPath)).pipe(Effect.ignore);++ const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (+ lockPath: string,+ owner: string,+ ) {+ yield* fileSystem.remove(path.join(lockPath, owner), { force: true }).pipe(Effect.ignore);+ // A replacement contains a different owner entry, so rmdir cannot remove it.+ yield* removeEmptyLock(lockPath);+ });+const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (lockPath: string,) {+ const owner = `${process.pid}-${yield* crypto.randomUUIDv4()}`;+ const candidate = yield* Effect.acquireRelease(+ fileSystem.makeTempDirectory({ directory: path.dirname(lockPath), prefix: ".lock-" }),+ (directory) =>+ fileSystem.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore),+ );+ yield* fileSystem.writeFileString(path.join(candidate, owner), "");for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {const acquired = yield* Effect.acquireRelease(- fileSystem.writeFileString(lockPath, "", { flag: "wx" }),- () => fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore),+ // Publish a populated directory atomically, with no ownerless acquisition window.+ fileSystem.rename(candidate, lockPath),+ () => releaseOwnedLock(lockPath, owner),).pipe(Effect.as(true),- Effect.catchIf(isAlreadyExists, () => Effect.succeed(false)),+ Effect.catchIf(isLockContention, () => Effect.succeed(false)),);if (acquired) return;- const now = yield* Clock.currentTimeMillis;const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);- const mtime = Option.flatMap(lockInfo, (info) => info.mtime);- if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {- yield* fileSystem.remove(lockPath, { force: true });- continue;+ if (Option.isNone(lockInfo)) continue;+ if (lockInfo.value.type === "Directory") {+ const owners = yield* fileSystem+ .readDirectory(lockPath)+ .pipe(Effect.orElseSucceed(() => []));+ let recovered = owners.length === 0;+ for (const entry of owners) {+ const pid = parseLockOwnerPid(entry);+ if (pid !== null && !processIsAlive(pid)) {+ yield* releaseOwnedLock(lockPath, entry);+ recovered = true;+ }+ }+ if (recovered) {+ yield* removeEmptyLock(lockPath);+ continue;+ }+ } else {+ const now = yield* Clock.currentTimeMillis;+ const mtime = lockInfo.value.mtime;+ if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_LEGACY_STALE_MS) {+ // Nonrecursive removal also refuses a populated directory that replaced this file.+ yield* fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore);+ continue;+ }}yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);}