Fix dev sharing across hosted and restarted servers
This commit is contained in:
8 files changed
+185
-62
No files matched your search
+20
-12
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -19,7 +20,12 @@ import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
|
||||
import {
|
||||
claimDevShareLease,
|
||||
cleanupOwnedDevShare,
|
||||
type DevShareError,
|
||||
shareDevServer,
|
||||
} from "./lib/dev-share.ts";
|
||||
import { loadRepoEnv } from "./lib/public-config.ts";
|
||||
|
||||
Object.assign(process.env, loadRepoEnv());
|
||||
@@ -723,6 +729,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
"[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
|
||||
);
|
||||
} else {
|
||||
const path = yield* Path.Path;
|
||||
// acquireRelease, not share-then-addFinalizer: the mapping outlives this
|
||||
// process (and reboots), so the cleanup has to be registered atomically
|
||||
// with creating it. An interrupt landing in between would otherwise
|
||||
@@ -736,23 +743,24 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
//
|
||||
// A tailnet that isn't up shouldn't stop the dev server from starting —
|
||||
// warn, and carry on serving locally.
|
||||
const shared = yield* Effect.acquireRelease(
|
||||
shareDevServer({ webPort: sharedWebPort }),
|
||||
() =>
|
||||
// Serve config outlives this process, so a cleanup that did not
|
||||
// take leaves a tailnet URL pointing at a port nothing serves.
|
||||
unshareDevServer(sharedWebPort).pipe(
|
||||
const shared = yield* Effect.gen(function* () {
|
||||
const lease = yield* claimDevShareLease({
|
||||
leasePath: path.join(baseDir, "dev-share", `${String(sharedWebPort)}.owner`),
|
||||
ownerId: `${String(process.pid)}:${NodeCrypto.randomUUID()}`,
|
||||
webPort: sharedWebPort,
|
||||
});
|
||||
return yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>
|
||||
cleanupOwnedDevShare(lease).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.cleared
|
||||
result.status !== "failed"
|
||||
? Effect.void
|
||||
: Effect.logWarning(
|
||||
`[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
|
||||
result.explanation ? `: ${result.explanation}` : ""
|
||||
}. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
|
||||
`[dev-runner] could not safely clean up the tailnet mapping for port ${String(sharedWebPort)}: ${result.explanation}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
);
|
||||
}).pipe(
|
||||
Effect.tapError((error: DevShareError) =>
|
||||
Effect.logWarning(
|
||||
`[dev-runner] could not share on the tailnet: ${error.message}${
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
claimDevShareLease,
|
||||
cleanupOwnedDevShare,
|
||||
type DevShareError,
|
||||
DevServeFailedError,
|
||||
shareDevServer,
|
||||
@@ -27,11 +31,17 @@ const encode = (value: string) => Stream.make(new TextEncoder().encode(value));
|
||||
* test set the outcome of the `off` (pre-clear) and `serve` calls separately —
|
||||
* they are the same subcommand and are told apart by the trailing `off`.
|
||||
*/
|
||||
const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallResult }) =>
|
||||
const spawnerLayer = (input: {
|
||||
readonly off?: CallResult;
|
||||
readonly serve?: CallResult;
|
||||
readonly onOff?: Effect.Effect<void>;
|
||||
readonly calls?: Array<ReadonlyArray<string>>;
|
||||
}) =>
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
|
||||
input.calls?.push(args);
|
||||
const result: CallResult = args.includes("status")
|
||||
? { exitCode: 0 }
|
||||
: args.includes("off")
|
||||
@@ -41,7 +51,9 @@ const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallR
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
exitCode: (args.includes("off") ? (input.onOff ?? Effect.void) : Effect.void).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
@@ -176,3 +188,52 @@ describe("shareDevServer", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("dev share cleanup ownership", (it) => {
|
||||
it.effect("restores a newer runner's mapping when ownership changes during cleanup", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 };
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* claimDevShareLease(oldLease);
|
||||
const result = yield* cleanupOwnedDevShare(oldLease).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
calls,
|
||||
onOff: fileSystem.writeFileString(leasePath, "new-runner").pipe(Effect.orDie),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(result.status, "restored");
|
||||
assert.isTrue(calls.some((args) => args.includes("off")));
|
||||
assert.isTrue(calls.some((args) => args.includes("http://127.0.0.1:5788")));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the mapping alone when a newer runner already owns it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 };
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* claimDevShareLease(oldLease);
|
||||
yield* claimDevShareLease({ ...oldLease, ownerId: "new-runner" });
|
||||
const result = yield* cleanupOwnedDevShare(oldLease).pipe(
|
||||
Effect.provide(spawnerLayer({ calls })),
|
||||
);
|
||||
|
||||
assert.equal(result.status, "superseded");
|
||||
assert.isEmpty(calls);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -22,6 +22,9 @@ import {
|
||||
type TailscaleStderrDiagnostic,
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -110,10 +113,24 @@ export class DevServeFailedError extends Schema.TaggedErrorClass<DevServeFailedE
|
||||
}
|
||||
}
|
||||
|
||||
export class DevShareLeaseClaimError extends Schema.TaggedErrorClass<DevShareLeaseClaimError>()(
|
||||
"DevShareLeaseClaimError",
|
||||
{ leasePath: Schema.String, cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `could not claim cleanup ownership at ${this.leasePath}`;
|
||||
}
|
||||
|
||||
get hint(): string {
|
||||
return "Check that the dev data directory is writable.";
|
||||
}
|
||||
}
|
||||
|
||||
export const DevShareError = Schema.Union([
|
||||
TailscaleUnavailableError,
|
||||
TailnetNameMissingError,
|
||||
DevServeFailedError,
|
||||
DevShareLeaseClaimError,
|
||||
]);
|
||||
export type DevShareError = typeof DevShareError.Type;
|
||||
export const isDevShareError = Schema.is(DevShareError);
|
||||
@@ -163,6 +180,81 @@ export interface DevShareResult {
|
||||
readonly host: string;
|
||||
}
|
||||
|
||||
export interface DevShareLease {
|
||||
readonly leasePath: string;
|
||||
readonly ownerId: string;
|
||||
readonly webPort: number;
|
||||
}
|
||||
|
||||
export const claimDevShareLease = Effect.fn("devShare.claimDevShareLease")(function* (
|
||||
lease: DevShareLease,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.makeDirectory(path.dirname(lease.leasePath), { recursive: true }).pipe(
|
||||
Effect.andThen(fileSystem.writeFileString(lease.leasePath, lease.ownerId)),
|
||||
Effect.mapError((cause) => new DevShareLeaseClaimError({ leasePath: lease.leasePath, cause })),
|
||||
);
|
||||
return lease;
|
||||
});
|
||||
|
||||
export type DevShareCleanupResult =
|
||||
| { readonly status: "cleared" | "superseded" | "restored" }
|
||||
| { readonly status: "failed"; readonly explanation: string };
|
||||
|
||||
/**
|
||||
* Clears only the mapping this runner owns. If a successor claims the lease
|
||||
* while `tailscale serve off` is in flight, restore the same port mapping so
|
||||
* the old finalizer cannot silently disconnect the new runner.
|
||||
*/
|
||||
export const cleanupOwnedDevShare = Effect.fn("devShare.cleanupOwnedDevShare")(function* (
|
||||
lease: DevShareLease,
|
||||
): Effect.fn.Return<
|
||||
DevShareCleanupResult,
|
||||
never,
|
||||
FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const readOwner = fileSystem
|
||||
.readFileString(lease.leasePath)
|
||||
.pipe(Effect.option, Effect.map(Option.getOrUndefined));
|
||||
const ownerBefore = yield* readOwner;
|
||||
if (ownerBefore !== lease.ownerId) {
|
||||
return { status: "superseded" };
|
||||
}
|
||||
|
||||
const result = yield* unshareDevServer(lease.webPort);
|
||||
if (!result.cleared) {
|
||||
return {
|
||||
status: "failed",
|
||||
explanation:
|
||||
result.explanation ??
|
||||
`could not remove the tailnet mapping for port ${String(lease.webPort)}`,
|
||||
};
|
||||
}
|
||||
|
||||
const ownerAfter = yield* readOwner;
|
||||
if (ownerAfter === lease.ownerId) {
|
||||
return { status: "cleared" };
|
||||
}
|
||||
|
||||
return yield* ensureTailscaleServe({
|
||||
localPort: lease.webPort,
|
||||
servePort: lease.webPort,
|
||||
}).pipe(
|
||||
Effect.as({ status: "restored" } as const),
|
||||
Effect.catch((cause: TailscaleCommandError) =>
|
||||
Effect.succeed({
|
||||
status: "failed",
|
||||
explanation:
|
||||
explainCommandFailure(cause) ??
|
||||
`a newer runner claimed port ${String(lease.webPort)}, but its mapping could not be restored`,
|
||||
} as const),
|
||||
),
|
||||
Effect.uninterruptible,
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Publishes `webPort` on the tailnet at the same port number and returns the
|
||||
* resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.
|
||||
|
||||
Reference in new issue
Block a user