Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ export const LocalServerStatus = Schema.Struct({
home: Schema.Struct({ path: Schema.String, custom: Schema.Boolean, fallback: Schema.NullOr(Schema.String) }),
/** None when no `codework` was found. */
cli: Schema.NullOr(CliInstall),
/** Newest published CLI version for this app's channel when known, null otherwise. */
latestCliVersion: Schema.NullOr(Schema.String),
server: CliServer,
/** Extra arguments for `codework service start` and `restart`, as typed. */
args: Schema.String,
Expand Down
49 changes: 44 additions & 5 deletions apps/server/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export const statuses = Effect.gen(function* () {
isDefault: row.isDefault,
home,
cli,
latestCliVersion: null,
server,
args: row.args,
env: row.env.map(({ name, sensitive, value }) =>
Expand Down Expand Up @@ -244,14 +245,51 @@ const installScript = Config.String("CODEWORK_INSTALL_SCRIPT").pipe(
Effect.orDie,
);

const channel = Config.String("CODEWORK_CHANNEL").pipe(Config.withDefault("latest"), Effect.orDie);

// Overridable for tests; set to empty string to skip the network check.
const releaseUrl = Config.String("CODEWORK_RELEASE_URL").pipe(Config.option, Effect.orDie);

const parseReleaseVersion = (text: string | null) => /cli@v(\d+\.\d+\.\d+\S*)/.exec(text ?? "")?.[1] ?? null;

/** Newest published CLI version for this app's channel, or null when offline or unreachable. */
export const latestVersion = Effect.gen(function* () {
const override = yield* releaseUrl;
if (Option.isSome(override) && override.value === "") return null;
const currentChannel = yield* channel;
const isDev = currentChannel === "dev" || currentChannel === "canary";
const url = Option.getOrElse(override, () =>
isDev
? "https://api.github.com/repos/codeworksh/codework/releases/tags/devel"
: "https://github.com/codeworksh/codework/releases/latest",
);
return yield* Effect.tryPromise(async () => {
if (isDev) {
const response = await fetch(url, {
headers: { accept: "application/vnd.github+json", "user-agent": "codework" },
signal: AbortSignal.timeout(5_000),
});
if (!response.ok) return null;
const body = (await response.json()) as { readonly name?: unknown };
return typeof body.name === "string" ? parseReleaseVersion(body.name) : null;
}
const response = await fetch(url, {
method: "HEAD",
redirect: "manual",
signal: AbortSignal.timeout(5_000),
});
return parseReleaseVersion(response.headers.get("location"));
}).pipe(Effect.orElseSucceed(() => null));
});

/**
* Installs codework the way the install command does, into the install script's folder, then starts
* `row`. The shell's startup file is left alone: the app finds the binary in that folder by itself.
* A development or canary build of the app installs the newest development build.
* or restarts `row`. The shell's startup file is left alone: the app finds the binary in that folder
* by itself. A development or canary build of the app installs the newest development build.
*/
export const install = Effect.fn("Cli.install")(function* (row: Servers.LocalRow) {
const url = yield* installScript;
const channel = yield* Config.String("CODEWORK_CHANNEL").pipe(Config.withDefault("latest"), Effect.orDie);
const currentChannel = yield* channel;
const script = yield* Effect.tryPromise({
try: () =>
fetch(url).then((response) => {
Expand All @@ -267,12 +305,13 @@ export const install = Effect.fn("Cli.install")(function* (row: Servers.LocalRow
: `Couldn't download the installer: ${error instanceof Error ? error.message : String(error)}`,
}),
});
const flags = ["--no-modify-path", ...(channel === "dev" || channel === "canary" ? ["--dev"] : [])];
const flags = ["--no-modify-path", ...(currentChannel === "dev" || currentChannel === "canary" ? ["--dev"] : [])];
const { output, code } = yield* run("sh", ["-c", script, "install", ...flags], "300 seconds", {
CODEWORK_INSTALL_DIR: yield* installDir,
}).pipe(Effect.mapError((error) => new ServersError({ message: `Couldn't install codework: ${error.message}` })));
if (code !== 0) return yield* new ServersError({ message: `Couldn't install codework: ${reason(output, code)}` });
yield* service(row, "start");
const home = (yield* Servers.Service).homeOf(row).path;
yield* service(row, Option.isSome(yield* liveAt(home)) ? "restart" : "start");
});

export * as Cli from "./cli.ts";
47 changes: 37 additions & 10 deletions apps/server/src/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import { Sync } from "./sync.ts";
const EVERY = Duration.seconds(5);
// A round trip slower than this is no answer.
const TIMED_OUT = Duration.seconds(2);
// Latest published CLI version is cached in memory so checks never hammer GitHub.
const RELEASE_TTL_MS = Duration.toMillis(Duration.hours(1));
const RELEASE_RETRY_MS = Duration.toMillis(Duration.minutes(5));

const decodeHealth = Schema.decodeUnknownOption(ServerHealth);
const store = { package: "@codeworksh/server", key: "health" };
Expand Down Expand Up @@ -60,34 +63,58 @@ export const layer = Layer.effect(
);
// In memory only: a round trip is as old as the check that took it.
const trips = new Map<string, number | null>();
let latestCliVersion: string | null = null;
let latestCheckedAt = 0;
// A machine not answering now has no round trip, whatever the last timing said.
const answering = (status: ServerStatus) =>
status.kind === "remote" ? status.online : status.server._tag === "Running";
const withTrips = (statuses: ReadonlyArray<ServerStatus>) =>
statuses.map((status) => ({ ...status, rtt: answering(status) ? (trips.get(status.id) ?? null) : null }));
const withMeasured = (statuses: ReadonlyArray<ServerStatus>) =>
statuses.map((status) =>
status.kind === "local"
? { ...status, rtt: answering(status) ? (trips.get(status.id) ?? null) : null, latestCliVersion }
: { ...status, rtt: answering(status) ? (trips.get(status.id) ?? null) : null },
);
const timings = yield* Queue.sliding<void>(1);

// A check never waits on a round trip: one to a machine that just stopped takes the whole timeout.
// The statuses go out with the last ones known, and again once timed if any moved.
// A check never waits on a round trip or GitHub release lookup: a slow or offline host must not
// delay statuses. They go out with the last values known, and again once measured if any moved.
const check = lock.withPermits(1)(
Cli.statuses.pipe(
Effect.provideContext(context),
Effect.flatMap((statuses) => SubscriptionRef.set(current, withTrips(statuses))),
Effect.flatMap((statuses) => SubscriptionRef.set(current, withMeasured(statuses))),
Effect.andThen(Queue.offer(timings, undefined)),
),
);

const refreshLatest = Effect.gen(function* () {
const ttl = latestCliVersion === null ? RELEASE_RETRY_MS : RELEASE_TTL_MS;
if (latestCheckedAt !== 0 && Date.now() - latestCheckedAt < ttl) return false;
latestCheckedAt = Date.now();
const next = yield* Cli.latestVersion;
if (next === null || next === latestCliVersion) return false;
latestCliVersion = next;
return true;
});

const time = Effect.gen(function* () {
const statuses = yield* SubscriptionRef.get(current);
if (statuses === undefined) return;
const timed = yield* Effect.forEach(
statuses,
(status) => Effect.map(roundTrip(status.id), (rtt) => [status.id, rtt] as const),
const [timed, releaseMoved] = yield* Effect.all(
[
Effect.forEach(
statuses,
(status) => Effect.map(roundTrip(status.id), (rtt) => [status.id, rtt] as const),
{
concurrency: "unbounded",
},
),
refreshLatest,
],
{ concurrency: "unbounded" },
);
const moved = timed.some(([id, rtt]) => (trips.get(id) ?? null) !== rtt);
const moved = releaseMoved || timed.some(([id, rtt]) => (trips.get(id) ?? null) !== rtt);
for (const [id, rtt] of timed) trips.set(id, rtt);
if (moved) yield* SubscriptionRef.update(current, (now) => (now === undefined ? now : withTrips(now)));
if (moved) yield* SubscriptionRef.update(current, (now) => (now === undefined ? now : withMeasured(now)));
});

// The default server alone is cheap to ask; only a change is worth a full check. Unless `asked`,
Expand Down
45 changes: 36 additions & 9 deletions apps/web/src/settings/machines/local.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ import { defaultServerAtom, INSTALL } from "../../kernel/servers";
import { useMachineAtom } from "../../shell/connect";
import { Group, Placeholder, quietField, Row, SavingInput, Section } from "../blocks";
import { StatusDot } from "../controls";
import { Badge, Install, LaunchCommand, SettingInput, stateOf, tilde, useConfigure, useServerAction } from "./service";
import {
Badge,
Install,
LaunchCommand,
SettingInput,
stateOf,
tilde,
useConfigure,
useServerAction,
versionOf,
} from "./service";
import { Variables } from "./variables";
import {
linkText,
Expand Down Expand Up @@ -130,6 +140,7 @@ function Identity({
const [error, setError] = useState<string | null>(null);
const hostname = identity?.localHostName ?? status.host;
const { cli } = status;
const { running, installed, shown, update } = versionOf(status);
// The last identity stays on show once the server stops, but only a running one can take a new label.
const editable = identity !== undefined && status.server._tag === "Running";
return (
Expand Down Expand Up @@ -192,9 +203,26 @@ function Identity({
<Badge tone="muted">{identity === undefined ? "Unknown" : "Not Assigned"}</Badge>
)}
</Row>
<Row title="Version">
{cli !== null && "version" in cli ? (
<span className="font-mono text-xs text-ink-muted tabular-nums">v{cli.version}</span>
<Row
title="Version"
description={
[
running !== undefined && installed !== undefined && running !== installed
? `CLI v${installed} installed · restarting launches v${installed}`
: undefined,
update !== undefined ? `v${update} available` : undefined,
]
.filter(Boolean)
.join(" · ") || undefined
}
>
{shown !== undefined ? (
<span className="flex items-center gap-2">
<span className="font-mono text-xs text-ink-muted tabular-nums">v{shown}</span>
{update !== undefined && (
<Install id={status.id} idle="Update Now" working="Updating…" variant="secondary" />
)}
</span>
) : (
<Badge tone="muted">{cli === null ? "Not Installed" : "Unknown"}</Badge>
)}
Expand Down Expand Up @@ -279,16 +307,15 @@ function WorkspaceLink({

/** Where the server is, or why it isn't there, in a line. */
function whereOf({ cli, server }: LocalServerStatus) {
const host = server._tag === "Stopped" ? "" : new URL(server.url).host;
if (server._tag === "Running") return `${host} · pid ${server.pid}`;
if (server._tag === "Incompatible")
return `Another build answers at ${host}. Update the CLI, or run a server built with this app`;
if (cli === null) return "No codework found on your login shell’s PATH. Install it, or enter its path below";
if ("failure" in cli) return cli.failure;
const host = server._tag === "Stopped" ? "" : new URL(server.url).host;
switch (server._tag) {
case "Running":
return `${host} · pid ${server.pid}`;
case "Unreachable":
return `Registered at ${host} (pid ${server.pid}) but not answering`;
case "Incompatible":
return `Another build answers at ${host}. Update the CLI, or run a server built with this app`;
case "Stopped":
return "Once started, it keeps running after the app quits";
}
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/settings/machines/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { defaultServerAtom } from "../../kernel/servers";
import { useMachineAtom } from "../../shell/connect";
import { Group, Page, Placeholder, Section } from "../blocks";
import { Done, EmptyState, SeenStatus, StatusDot } from "../controls";
import { stateOf } from "./service";
import { stateOf, versionOf } from "./service";
import { CheckAgain, HealthInterval } from "./health";
import { isPlain, PairDialog } from "./pair";
import {
Expand Down Expand Up @@ -96,7 +96,7 @@ function ThisMachine({ workspace }: { readonly workspace: Relay.Workspace | unde
</Section>
);
}
const { cli } = status;
const version = versionOf(status).shown;
const { tone, text } = stateOf(status);
return (
<Section title="This Machine" description="The computer this app runs on">
Expand All @@ -107,7 +107,7 @@ function ThisMachine({ workspace }: { readonly workspace: Relay.Workspace | unde
// As a paired row reads: its link first, so the list shows a machine still to link.
description={[
workspace === undefined ? undefined : linkText(membership, workspace),
cli !== null && "version" in cli ? `v${cli.version}` : undefined,
version === undefined ? undefined : `v${version}`,
]
.filter(Boolean)
.join(" · ")}
Expand Down
66 changes: 59 additions & 7 deletions apps/web/src/settings/machines/service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,58 @@ export function useServerAction() {
return { running, error, act };
}

const parseSemver = (version: string) => {
const match = /^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/.exec(version.trim());
if (match === null) return undefined;
return {
core: [Number(match[1]), Number(match[2]), Number(match[3])] as const,
pre: match[4],
};
};

/** Whether `candidate` is strictly newer than `current` (semver core + prerelease). */
function isNewerVersion(candidate: string, current: string): boolean {
const a = parseSemver(candidate);
const b = parseSemver(current);
if (a === undefined || b === undefined) return false;
for (let i = 0; i < 3; i++) {
if (a.core[i]! !== b.core[i]!) return a.core[i]! > b.core[i]!;
}
if (a.pre === b.pre) return false;
if (a.pre === undefined) return true;
if (b.pre === undefined) return false;
return a.pre.localeCompare(b.pre, "en", { numeric: true }) > 0;
}

/** The running server's version when one answers, else the installed CLI's, plus any available update. */
export function versionOf({ cli, latestCliVersion, server }: LocalServerStatus): {
readonly running: string | undefined;
readonly installed: string | undefined;
readonly shown: string | undefined;
readonly update: string | undefined;
} {
const running = "version" in server ? server.version : undefined;
const installed = cli !== null && "version" in cli ? cli.version : undefined;
const update =
installed !== undefined &&
cli !== null &&
!cli.custom &&
latestCliVersion !== null &&
isNewerVersion(latestCliVersion, installed)
? latestCliVersion
: undefined;
return { running, installed, shown: running ?? installed, update };
}

/** A server's state in a few words, as its row in the list reads it. */
export function stateOf({ cli, server }: LocalServerStatus): { tone: Tone; text: string } {
if (server._tag === "Running") return { tone: "success", text: "Running" };
if (server._tag === "Incompatible") return { tone: "danger", text: "Incompatible Version" };
if (cli === null) return { tone: "warning", text: "Not Installed" };
if ("failure" in cli) return { tone: "danger", text: "Won’t Start" };
switch (server._tag) {
case "Running":
return { tone: "success", text: "Running" };
case "Unreachable":
return { tone: "warning", text: "Not Answering" };
case "Incompatible":
return { tone: "danger", text: "Incompatible Version" };
case "Stopped":
return { tone: "muted", text: "Stopped" };
}
Expand Down Expand Up @@ -142,15 +183,26 @@ export function SettingInput({
);
}

/** Runs the install command for the user, then starts this server; the status shows the result. */
export function Install({ id }: { id: string }) {
/** Runs the install command for the user, then starts or restarts this server; the status shows the result. */
export function Install({
id,
idle = "Install CodeWork",
working = "Installing…",
variant,
}: {
readonly id: string;
readonly idle?: string;
readonly working?: string;
readonly variant?: "default" | "secondary";
}) {
const install = useAtomSet(installAtom, { mode: "promise" });
const [installing, setInstalling] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<span className="flex flex-col items-start gap-1">
<Button
size="sm"
variant={variant}
disabled={installing}
onClick={() => {
setInstalling(true);
Expand All @@ -160,7 +212,7 @@ export function Install({ id }: { id: string }) {
.finally(() => setInstalling(false));
}}
>
{installing ? "Installing…" : "Install CodeWork"}
{installing ? working : idle}
</Button>
{error !== null && <span className="text-sm text-destructive">{error}</span>}
</span>
Expand Down
Loading