Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cfd7af1464 Handle child process unref result
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:10:53 +00:00
Cursor AgentandJulius Marminge 91263ff1bf Fix Effect test and catch helpers
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:08:22 +00:00
Cursor AgentandJulius Marminge cff8c10d13 Use Effect services for open and VCS config
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:07:39 +00:00
15 changed files with 277 additions and 323 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.23",
"version": "0.0.22",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.23",
"version": "0.0.22",
"license": "MIT",
"repository": {
"type": "git",
@@ -8,10 +8,7 @@ import * as Random from "effect/Random";
import { ServerConfig } from "../../config.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import {
ServerEnvironmentLabelCommandRunnerLive,
resolveServerEnvironmentLabel,
} from "./ServerEnvironmentLabel.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (process.platform) {
@@ -96,6 +93,4 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
} satisfies ServerEnvironmentShape;
});
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
Layer.provide(ServerEnvironmentLabelCommandRunnerLive),
);
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
@@ -1,43 +1,21 @@
import { assert, describe, it } from "@effect/vitest";
import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { vi } from "vitest";
import {
ServerEnvironmentLabelCommandError,
ServerEnvironmentLabelCommandRunner,
resolveServerEnvironmentLabel,
} from "./ServerEnvironmentLabel.ts";
vi.mock("../../processRunner.ts", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
const mockedRunProcess = vi.mocked(runProcess);
const NoopFileSystemLayer = FileSystem.layerNoop({});
const NoopCommandRunnerLayer = Layer.mock(ServerEnvironmentLabelCommandRunner)({});
interface CommandCall {
readonly command: string;
readonly args: readonly string[];
}
function commandRunnerLayer(input: {
readonly calls?: CommandCall[];
readonly run: (
command: string,
args: readonly string[],
) => Effect.Effect<
{ readonly stdout: string; readonly exitCode: number },
ServerEnvironmentLabelCommandError
>;
}) {
return Layer.mock(ServerEnvironmentLabelCommandRunner)({
run: (command, args) =>
Effect.gen(function* () {
input.calls?.push({ command, args });
return yield* input.run(command, args);
}),
});
}
function testLayer(commandLayer = NoopCommandRunnerLayer) {
return Layer.merge(NoopFileSystemLayer, commandLayer);
}
afterEach(() => {
mockedRunProcess.mockReset();
});
describe("resolveServerEnvironmentLabel", () => {
it.effect("uses hostname fallback regardless of launch mode", () =>
@@ -46,33 +24,34 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "macbook-pro",
}).pipe(Effect.provide(testLayer()));
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "macbook-pro");
expect(result).toBe("macbook-pro");
}),
);
it.effect("prefers the macOS ComputerName", () =>
Effect.gen(function* () {
const calls: CommandCall[] = [];
mockedRunProcess.mockResolvedValueOnce({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(
Effect.provide(
testLayer(
commandRunnerLayer({
calls,
run: () => Effect.succeed({ stdout: " Julius's MacBook Pro \n", exitCode: 0 }),
}),
),
),
);
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "Julius's MacBook Pro");
assert.deepEqual(calls, [{ command: "scutil", args: ["--get", "ComputerName"] }]);
expect(result).toBe("Julius's MacBook Pro");
expect(mockedRunProcess).toHaveBeenCalledWith(
"scutil",
["--get", "ComputerName"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -84,44 +63,43 @@ describe("resolveServerEnvironmentLabel", () => {
hostname: "buildbox",
}).pipe(
Effect.provide(
Layer.merge(
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
NoopCommandRunnerLayer,
),
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
),
);
assert.equal(result, "Build Agent 01");
expect(result).toBe("Build Agent 01");
expect(mockedRunProcess).not.toHaveBeenCalled();
}),
);
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
Effect.gen(function* () {
const calls: CommandCall[] = [];
mockedRunProcess.mockResolvedValueOnce({
stdout: "CI Runner\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: "runner-01",
}).pipe(
Effect.provide(
testLayer(
commandRunnerLayer({
calls,
run: () => Effect.succeed({ stdout: "CI Runner\n", exitCode: 0 }),
}),
),
),
);
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "CI Runner");
assert.deepEqual(calls, [{ command: "hostnamectl", args: ["--pretty"] }]);
expect(result).toBe("CI Runner");
expect(mockedRunProcess).toHaveBeenCalledWith(
"hostnamectl",
["--pretty"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -131,56 +109,43 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "JULIUS-LAPTOP",
}).pipe(Effect.provide(testLayer()));
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "JULIUS-LAPTOP");
expect(result).toBe("JULIUS-LAPTOP");
}),
);
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(
Effect.provide(
testLayer(
commandRunnerLayer({
run: (command, args) =>
Effect.fail(
new ServerEnvironmentLabelCommandError({
command,
args: [...args],
message: "spawn scutil ENOENT",
}),
),
}),
),
),
);
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "macbook-pro");
expect(result).toBe("macbook-pro");
}),
);
it.effect("falls back to the cwd basename when the hostname is blank", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: " ",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: " ",
}).pipe(
Effect.provide(
testLayer(
commandRunnerLayer({
run: () => Effect.succeed({ stdout: " ", exitCode: 0 }),
}),
),
),
);
}).pipe(Effect.provide(NoopFileSystemLayer));
assert.equal(result, "t3code");
expect(result).toBe("t3code");
}),
);
});
@@ -1,14 +1,9 @@
import * as OS from "node:os";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../../stream/collectUint8StreamText.ts";
import { runProcess } from "../../processRunner.ts";
interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
@@ -16,82 +11,12 @@ interface ResolveServerEnvironmentLabelInput {
readonly hostname?: string | null;
}
interface ServerEnvironmentLabelCommandResult {
readonly stdout: string;
readonly exitCode: number;
}
interface ServerEnvironmentLabelCommandRunnerShape {
readonly run: (
command: string,
args: readonly string[],
) => Effect.Effect<ServerEnvironmentLabelCommandResult, ServerEnvironmentLabelCommandError>;
}
export class ServerEnvironmentLabelCommandError extends Schema.TaggedErrorClass<ServerEnvironmentLabelCommandError>()(
"ServerEnvironmentLabelCommandError",
{
command: Schema.String,
args: Schema.Array(Schema.String),
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
export class ServerEnvironmentLabelCommandRunner extends Context.Service<
ServerEnvironmentLabelCommandRunner,
ServerEnvironmentLabelCommandRunnerShape
>()("t3/environment/Layers/ServerEnvironmentLabel/CommandRunner") {}
export const ServerEnvironmentLabelCommandRunnerLive = Layer.effect(
ServerEnvironmentLabelCommandRunner,
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return ServerEnvironmentLabelCommandRunner.of({
run: (command, args) =>
Effect.scoped(
Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(command, [...args], {
shell: process.platform === "win32",
}),
);
const [stdout, , exitCode] = yield* Effect.all(
[
collectUint8StreamText({ stream: child.stdout }),
collectUint8StreamText({ stream: child.stderr }),
child.exitCode,
],
{ concurrency: "unbounded" },
);
return {
stdout: stdout.text,
exitCode: Number(exitCode),
};
}).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentLabelCommandError({
command,
args: [...args],
message: `Failed to run friendly host label command: ${command}.`,
cause,
}),
),
),
),
});
}),
);
function normalizeLabel(value: string | null | undefined): Option.Option<string> {
function normalizeLabel(value: string | null | undefined): string | null {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? Option.some(trimmed) : Option.none();
return trimmed && trimmed.length > 0 ? trimmed : null;
}
function parseMachineInfoValue(raw: string, key: string): Option.Option<string> {
function parseMachineInfoValue(raw: string, key: string): string | null {
for (const line of raw.split(/\r?\n/g)) {
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
@@ -106,7 +31,7 @@ function parseMachineInfoValue(raw: string, key: string): Option.Option<string>
}
return normalizeLabel(value);
}
return Option.none();
return null;
}
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
@@ -115,26 +40,31 @@ const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
.exists("/etc/machine-info")
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return Option.none();
return null;
}
const raw = yield* fileSystem.readFileString("/etc/machine-info").pipe(Effect.option);
return Option.flatMap(raw, normalizeLabel);
return yield* fileSystem
.readFileString("/etc/machine-info")
.pipe(Effect.orElseSucceed(() => null));
});
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const commandRunner = yield* ServerEnvironmentLabelCommandRunner;
const result = yield* commandRunner.run(command, args).pipe(Effect.option);
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
if (Option.isNone(result) || result.value.exitCode !== 0) {
return Option.none();
if (!result || result.code !== 0) {
return null;
}
return normalizeLabel(result.value.stdout);
return normalizeLabel(result.stdout);
});
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
@@ -145,10 +75,10 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
}
if (platform === "linux") {
const machineInfo = yield* readLinuxMachineInfo();
if (Option.isSome(machineInfo)) {
const prettyHostname = parseMachineInfoValue(machineInfo.value, "PRETTY_HOSTNAME");
if (Option.isSome(prettyHostname)) {
const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
if (machineInfo) {
const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
if (prettyHostname) {
return prettyHostname;
}
}
@@ -156,7 +86,7 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
}
return Option.none();
return null;
});
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
@@ -164,14 +94,14 @@ export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironment
) {
const platform = input.platform ?? process.platform;
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
if (Option.isSome(friendlyHostLabel)) {
return friendlyHostLabel.value;
if (friendlyHostLabel) {
return friendlyHostLabel;
}
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
if (Option.isSome(hostname)) {
return hostname.value;
if (hostname) {
return hostname;
}
return Option.getOrElse(normalizeLabel(input.cwdBaseName), () => "T3 environment");
return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
});
+49 -3
View File
@@ -3,8 +3,12 @@ import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isCommandAvailable,
@@ -13,6 +17,22 @@ import {
resolveEditorLaunch,
} from "./open.ts";
function makeOpenProcessHandle(onUnref: Effect.Effect<void> = Effect.void) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.as(onUnref, Effect.void),
});
}
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
@@ -478,13 +498,36 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
it.effect("resolves when command can be spawned through ChildProcessSpawner", () =>
Effect.gen(function* () {
const commands: Array<ChildProcess.Command> = [];
let unrefCount = 0;
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({
spawn: (command) =>
Effect.sync(() => {
commands.push(command);
return makeOpenProcessHandle(
Effect.sync(() => {
unrefCount += 1;
}),
);
}),
});
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assertSuccess(result, undefined);
assert.equal(unrefCount, 1);
assert.lengthOf(commands, 1);
const command = commands[0] as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
assert.equal(command.command, process.execPath);
assert.deepEqual(command.args, ["-e", "process.exit(0)"]);
}),
);
@@ -493,7 +536,10 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
const result = yield* launchDetached({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(Effect.result);
}).pipe(
Effect.provide(Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({})),
Effect.result,
);
assert.equal(result._tag, "Failure");
}),
);
+31 -32
View File
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Open - Browser/editor launch service interface.
*
@@ -7,13 +6,12 @@
*
* @module Open
*/
import { spawn } from "node:child_process";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
// ==============================
// Definitions
@@ -191,38 +189,34 @@ export const launchDetached = (launch: EditorLaunch) =>
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
const isWin32 = process.platform === "win32";
child = spawn(
launch.command,
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
{
detached: true,
stdio: "ignore",
shell: isWin32,
},
const isWin32 = process.platform === "win32";
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
yield* Effect.scoped(
Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(
launch.command,
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
{
detached: true,
shell: isWin32,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
),
);
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
yield* Effect.asVoid(child.unref);
}),
).pipe(
Effect.mapError(
(cause) => new OpenError({ message: "failed to spawn detached process", cause }),
),
);
});
const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
@@ -234,7 +228,12 @@ const make = Effect.gen(function* () {
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
openInEditor: (input) =>
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchDetached(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
} satisfies OpenShape;
});
+42 -2
View File
@@ -41,8 +41,7 @@ describe("VcsProjectConfig", () => {
yield* fileSystem.makeDirectory(nested, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ vcs: { kind: "jj" } }),
'{"vcs":{"kind":"jj"}}',
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
@@ -53,6 +52,47 @@ describe("VcsProjectConfig", () => {
);
});
it.layer(TestLayer)("ignores malformed .t3code/vcs.json files", (it) => {
it.effect("returns auto for invalid JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{not json");
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
it.effect("returns auto for schema-invalid JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
'{"vcs":{"kind":"svn"}}',
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
+19 -30
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
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 Schema from "effect/Schema";
@@ -15,16 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(
Schema.fromJsonString(ProjectVcsConfig),
);
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -45,14 +40,8 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
}
const parseConfig = (raw: string): Option.Option<ProjectVcsConfigFile> =>
decodeProjectVcsConfigJson(raw);
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -63,12 +52,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
while (true) {
const candidate = path.join(current, ".t3code", "vcs.json");
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return candidate;
return Option.some(candidate);
}
const parent = path.dirname(current);
if (parent === current) {
return null;
return Option.none();
}
current = parent;
}
@@ -78,26 +67,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
configPath: string,
) {
const raw = yield* fileSystem.readFileString(configPath).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to read VCS project config", {
configPath,
error,
}).pipe(Effect.as(null)),
}).pipe(Effect.as(Option.none())),
),
);
if (raw === null) {
if (Option.isNone(raw)) {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
const parsed = parseConfig(raw.value);
if (Option.isNone(parsed)) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
return configuredKind(parsed.value);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -108,11 +98,10 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
}
const configPath = yield* findConfigPath(input.cwd);
if (configPath === null) {
return "auto";
}
return yield* readConfiguredKind(configPath);
return yield* Option.match(configPath, {
onNone: () => Effect.succeed("auto" as const),
onSome: readConfiguredKind,
});
});
return VcsProjectConfig.of({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.23",
"version": "0.0.22",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.23",
"version": "0.0.22",
"private": true,
"files": [
"dist"
+1 -1
View File
@@ -139,7 +139,7 @@ describe("ssh command", () => {
username: "julius",
port: 2222,
},
{ timeout: Duration.millis(1) },
{ timeoutMs: 1 },
),
),
);
+6 -13
View File
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
const encoder = new TextEncoder();
@@ -27,7 +27,7 @@ export interface RunSshCommandOptions extends SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeout?: Duration.Input;
readonly timeoutMs?: number;
}
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
@@ -132,10 +132,6 @@ function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
};
}
function resolveSshCommandTimeout(input: RunSshCommandOptions): Duration.Duration {
return Duration.fromInputUnsafe(input.timeout ?? DEFAULT_SSH_COMMAND_TIMEOUT);
}
function stdinStream(input: string | undefined) {
return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
}
@@ -174,12 +170,11 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
...(input.remoteCommandArgs ?? []),
];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const timeout = resolveSshCommandTimeout(input);
yield* Effect.logDebug("ssh.command.start", {
...sshTargetLogFields(target),
command: ["ssh", ...args],
hasStdin: input.stdin !== undefined,
timeoutMs: Duration.toMillis(timeout),
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
});
const child = yield* spawner
.spawn(
@@ -263,12 +258,10 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const timeout = resolveSshCommandTimeout(input);
const timeoutMs = Duration.toMillis(timeout);
return yield* Effect.scopedWith((commandScope) =>
runSshCommandInScope(target, input, commandScope),
).pipe(
Effect.timeoutOption(timeout),
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
@@ -276,7 +269,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
Effect.gen(function* () {
yield* Effect.logWarning("ssh.command.timedOut", {
...sshTargetLogFields(target),
timeoutMs,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
remoteCommandArgs: input.remoteCommandArgs ?? [],
preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined,
@@ -285,7 +278,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH command timed out after ${timeoutMs}ms.`,
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
});
}),
}),
+3 -3
View File
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
Effect.result(
waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/",
timeout: Duration.seconds(1),
interval: Duration.millis(100),
probeTimeout: Duration.millis(250),
timeoutMs: 1_000,
intervalMs: 100,
probeTimeoutMs: 250,
}),
),
);
+23 -26
View File
@@ -50,11 +50,11 @@ import {
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT = Duration.seconds(20);
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
const SSH_READY_TIMEOUT_MS = 20_000;
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
const REMOTE_READY_TIMEOUT_MS = 15_000;
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
@@ -686,9 +686,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
});
}
@@ -860,7 +860,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target),
timeout: Duration.seconds(10),
timeoutMs: 10_000,
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
@@ -870,19 +870,16 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
readonly baseUrl: string;
readonly timeout?: Duration.Input;
readonly interval?: Duration.Input;
readonly probeTimeout?: Duration.Input;
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly probeTimeoutMs?: number;
readonly path?: string;
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
const timeout = Duration.fromInputUnsafe(input.timeout ?? Duration.seconds(30));
const interval = Duration.fromInputUnsafe(input.interval ?? Duration.millis(100));
const probeTimeout = Duration.fromInputUnsafe(input.probeTimeout ?? SSH_READY_PROBE_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
const intervalMs = Duration.toMillis(interval);
const probeTimeoutMs = Duration.toMillis(probeTimeout);
const retryPolicy = Schedule.spaced(interval).pipe(
Schedule.take(Math.max(0, Math.ceil(timeoutMs / Math.max(intervalMs, 1)))),
const timeoutMs = input.timeoutMs ?? 30_000;
const intervalMs = input.intervalMs ?? 100;
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
);
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
const client = yield* HttpClient.HttpClient;
@@ -903,7 +900,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.gen(function* () {
attempt += 1;
const responseOption = yield* effect.pipe(
Effect.timeoutOption(probeTimeout),
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
Effect.mapError(
(cause) =>
new SshReadinessError({
@@ -956,7 +953,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
cause,
}),
),
Effect.timeoutOption(timeout),
Effect.timeoutOption(Duration.millis(timeoutMs)),
);
return yield* Option.match(result, {
@@ -1239,7 +1236,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
yield* Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeout: SSH_READY_TIMEOUT,
timeoutMs: SSH_READY_TIMEOUT_MS,
}),
exitFailure,
).pipe(
@@ -1299,7 +1296,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore),
),
@@ -1543,7 +1540,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
[
tunnelEntry.process.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
}),
stopRemoteServer(
tunnelEntry.target,
@@ -1597,7 +1594,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
remotePort: entry.remotePort,
});
const readinessExit = yield* Effect.exit(
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
);
if (Exit.isSuccess(readinessExit)) {
yield* Effect.logDebug("ssh.environment.tunnel.reused", {