Skip to content
Open
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
54 changes: 40 additions & 14 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ export const ServerKind = Schema.Literals(["local", "remote"]);
/** The server the app always has, which cannot be removed. */
export const LOCAL_SERVER = "local";

/** How a server is named: the user's `override`, else the `host` name its server reports, else where it is. */
/** How a local server is named: the user's `override`, else the `host` name its server reports. */
const ServerNaming = {
/** As shown. */
name: Schema.String,
Expand Down Expand Up @@ -406,15 +406,33 @@ export const LocalServerStatus = Schema.Struct({
});
export type LocalServerStatus = typeof LocalServerStatus.Type;

/** A remote server: only where to reach it; it has no executable or home here. */
/**
* A paired machine: a server on another computer, reached with a pairing code. It has no executable or
* home here. Its hostname and label are the machine's own, as it last reported them.
*/
export const RemoteServerStatus = Schema.Struct({
id: Schema.String,
kind: Schema.Literal("remote"),
...ServerNaming,
/** As shown: its label, else its hostname, else where it is. */
name: Schema.String,
/** The computer's own name; none before the machine was ever reached. */
host: Schema.NullOr(Schema.String),
/** The friendly name stored on the machine; none when it has none. */
label: Schema.NullOr(Schema.String),
isDefault: Schema.Boolean,
url: Schema.String,
/** Whether this app holds a session on it; false once the server refuses it (revoked or lapsed): pair again. */
paired: Schema.Boolean,
/** Whether it is answering now. */
online: Schema.Boolean,
/** When it last answered, in epoch milliseconds; none before it ever did. */
seenAt: Schema.NullOr(Schema.Number),
/** The build it last reported; none before it was ever reached. */
version: Schema.NullOr(Schema.String),
/** The machine's own id, as it last reported it; none before it was reached or before its first connect. */
machineId: Schema.NullOr(Schema.String),
/** The workspaces it is linked to, each with the thumbprint of its key, as it last reported them. */
workspaces: Schema.Array(Schema.Struct({ id: Schema.String, keyId: Schema.String })),
});
export type RemoteServerStatus = typeof RemoteServerStatus.Type;

Expand All @@ -434,9 +452,9 @@ export const CliAction = Schema.Literals(["start", "restart", "stop"]);
export type CliAction = typeof CliAction.Type;

/**
* A new server. A local one needs a home of its own, since a home names one server; a remote one
* needs its WebSocket URL and a pairing code from `codework service pair` on that machine. A blank or
* absent `name` is no override.
* A new server. A local one needs a home of its own, since a home names one server; a blank or absent
* `name` is no override. A remote one needs its WebSocket URL and a pairing code from
* `codework service pair` on that machine; it is named by its own label.
*/
export const ServerAdd = Schema.Union([
Schema.Struct({
Expand All @@ -448,7 +466,6 @@ export const ServerAdd = Schema.Union([
}),
Schema.Struct({
kind: Schema.Literal("remote"),
name: Schema.optionalKey(Schema.String),
url: Schema.String,
code: Schema.String,
}),
Expand All @@ -458,7 +475,7 @@ export type ServerAdd = typeof ServerAdd.Type;
/**
* Changes to a server; an absent field is left as it is. A `null` path goes back to the one found;
* a blank `name` removes the override; `env` replaces every variable. `url` and `code` are for a remote
* server only, the rest but `name` for a local one; a `code` pairs again, at the new `url` when given.
* server only, the rest for a local one; a `code` pairs again, at the new `url` when given.
*/
export const ServerUpdate = Schema.Struct({
id: Schema.String,
Expand Down Expand Up @@ -844,17 +861,17 @@ export const Api = RpcGroup.make(
success: Machine.Status,
error: CodeworkUnavailable,
}),
/** Disconnects the default machine from a workspace. */
/** Disconnects the default machine, or the paired machine `serverId`, from a workspace. */
Rpc.make("machine.disconnect", {
payload: Machine.Disconnect,
payload: { ...Machine.Disconnect.fields, serverId: Schema.optionalKey(Schema.String) },
success: Machine.Disconnected,
error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]),
error: Schema.Union([CodeworkUnavailable, ServersError, Machine.ConnectError]),
}),
/** Connects the default machine to a workspace: the code to approve, then the link. */
/** Connects the default machine, or the paired machine `serverId`, to a workspace: the code to approve, then the link. */
Rpc.make("machine.connect", {
payload: { workspaceId: Schema.String },
payload: { workspaceId: Schema.String, serverId: Schema.optionalKey(Schema.String) },
success: Machine.ConnectEvent,
error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]),
error: Schema.Union([CodeworkUnavailable, ServersError, Machine.ConnectError]),
stream: true,
}),
/** The OS home directory, and the folder `host.create` makes projects in. */
Expand Down Expand Up @@ -1022,6 +1039,15 @@ export const Api = RpcGroup.make(
success: Schema.Void,
error: Schema.Union([ServersError, PairingRefused]),
}),
/**
* Sets the label stored on a paired machine, over its connection; an empty one clears it. Pairing is
* direct access to the machine, so this needs nothing more.
*/
Rpc.make("servers.label", {
payload: { id: Schema.String, label: Schema.String },
success: Schema.Void,
error: ServersError,
}),
/** The default server and the built-in one stay. */
Rpc.make("servers.remove", {
payload: ServerId,
Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,23 @@ const migrations = {
const sql = yield* SqlClient.SqlClient;
yield* sql`ALTER TABLE machine ADD COLUMN token TEXT`;
}),

// What a machine last reported over its connection, and when it last answered. A remote machine is
// named by the label stored on it, so `name` is a local machine's override only.
"202611200002_label": Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`ALTER TABLE machine ADD COLUMN label TEXT`;
yield* sql`ALTER TABLE machine ADD COLUMN version TEXT`;
yield* sql`ALTER TABLE machine ADD COLUMN seen_at INTEGER`;
yield* sql`UPDATE machine SET name = NULL WHERE kind = 'remote'`;
}),

// A remote machine's own id and the workspaces it is linked to (JSON), as it last reported them.
"202611210001_identity": Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`ALTER TABLE machine ADD COLUMN identity TEXT`;
yield* sql`ALTER TABLE machine ADD COLUMN workspaces TEXT`;
}),
};

const setup = Effect.gen(function* () {
Expand Down
99 changes: 89 additions & 10 deletions apps/server/src/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Codework as Client } from "@codeworksh/widget/backend";
import type * as Mirror from "@codeworksh/widget/codework";
import { Effect, Predicate, Stream } from "effect";
import { SqlClient } from "effect/sql";
Expand All @@ -10,6 +11,7 @@ import {
ModelsError,
ProjectError,
type ServerAdd,
ServersError,
SettingsConflict,
SettingsError,
type ServerUpdate,
Expand Down Expand Up @@ -84,6 +86,28 @@ export const layer = Contract.Api.toLayer(
).pipe(
Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))),
);
/**
* The connection to a paired machine, in the app's own words when there is none: refused once it is
* not paired any more, or not answering.
*/
const paired = Effect.fn("paired")(function* (id: string) {
const row = yield* servers.get(id);
if (row.kind !== "remote")
return yield* new ServersError({ message: "Only a paired Machine is reached here." });
if (row.token === null)
return yield* new ServersError({ message: `${row.name} is not paired any more. Pair it again.` });
const unanswered = new ServersError({ message: `${row.name} did not answer.` });
const client = yield* sync.client(id).pipe(Effect.mapError(() => unanswered));
return { client, unanswered };
});
/** Stores what a paired machine's own record says now, so a link or an unlink shows at once. */
const reread = (id: string, client: typeof Client.Service) =>
Codework.call((rpc) => rpc("machine.info", {})).pipe(
Effect.provideService(Client, client),
Effect.flatMap((status) => servers.reached(id, Servers.factsOf(status))),
Effect.andThen(health.check),
Effect.ignore,
);
// A changed default reconnects the app; the status read after waits for it to reach the server.
const changingDefault = <A, E, R>(change: Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
Expand Down Expand Up @@ -117,26 +141,52 @@ export const layer = Contract.Api.toLayer(
return yield* call((client) => client("machine.rename", { givenName }));
}),
// The CLI's own failure (not connected to that workspace) keeps its message.
"machine.disconnect": Effect.fn("machine.disconnect")(function* (input) {
const reply = yield* call((client) =>
"machine.disconnect": Effect.fn("machine.disconnect")(function* ({ serverId, ...input }) {
const disconnect = (client: typeof Client.Service) =>
client("machine.disconnect", input).pipe(
Effect.map((disconnected) => ({ disconnected })),
Effect.catchTag("Machine.ConnectError", (failed) => Effect.succeed({ failed })),
),
);
if (serverId === undefined) {
const reply = yield* call(disconnect);
return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected);
}
const { client, unanswered } = yield* paired(serverId);
const reply = yield* Codework.call(disconnect).pipe(
Effect.provideService(Client, client),
Effect.mapError(() => unanswered),
);
return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected);
if ("failed" in reply) return yield* reply.failed;
yield* servers.reached(serverId, Servers.factsOf(reply.disconnected.status));
yield* health.check;
return reply.disconnected;
}),
// The CLI's own connect failure (the relay unreachable, the code expired) keeps its message; only
// a dropped server reads as unavailable.
"machine.connect": ({ workspaceId }) =>
Codework.stream((client) =>
// a dropped server reads as unavailable, and a paired machine as not answering.
"machine.connect": ({ workspaceId, serverId }) => {
const connect = (client: typeof Client.Service) =>
client("machine.connect", { workspaceId }).pipe(
Stream.map((event) => ({ event })),
Stream.catchTag("Machine.ConnectError", (failed) => Stream.succeed({ failed })),
);
const unwrap = Stream.flatMap((item: Stream.Success<ReturnType<typeof connect>>) =>
"failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event),
);
if (serverId === undefined) return Codework.stream(connect).pipe(unwrap);
return Stream.unwrap(
paired(serverId).pipe(
Effect.map(({ client, unanswered }) =>
Codework.stream(connect).pipe(
Stream.provideService(Client, client),
Stream.mapError(() => unanswered),
unwrap,
// Stored before the link reaches the app, so the machine's status already shows it.
Stream.tap((event) => (event._tag === "Connected" ? reread(serverId, client) : Effect.void)),
),
),
),
).pipe(
Stream.flatMap((item) => ("failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event))),
),
);
},
"host.info": Effect.fn("host.info")(function* () {
return yield* call((client) => client("host.info", {}));
}),
Expand Down Expand Up @@ -225,7 +275,36 @@ export const layer = Contract.Api.toLayer(
yield* changingDefault(servers.update(input));
yield* health.check;
}),
"servers.label": Effect.fn("servers.label")(function* ({
id,
label,
}: {
readonly id: string;
readonly label: string;
}) {
const row = yield* servers.get(id);
if (row.kind !== "remote")
return yield* new ServersError({ message: "Only a paired Machine has a Label." });
const { client, unanswered } = yield* paired(id);
const status = yield* Codework.call((rpc) => rpc("machine.rename", { givenName: label.trim() })).pipe(
Effect.provideService(Client, client),
Effect.mapError(() => unanswered),
);
yield* servers.reached(id, { label: status.givenName });
yield* health.check;
}),
"servers.remove": Effect.fn("servers.remove")(function* ({ id }: { readonly id: string }) {
const row = yield* servers.get(id);
// Best effort: the row goes whether the machine answers or not.
if (row.kind === "remote" && row.token !== null)
yield* sync.client(id).pipe(
Effect.flatMap((client) =>
Codework.call((rpc) => rpc("device.leave", {}), { timeout: "3 seconds" }).pipe(
Effect.provideService(Client, client),
),
),
Effect.ignore,
);
yield* servers.remove(id);
yield* health.check;
}),
Expand Down
12 changes: 9 additions & 3 deletions apps/server/src/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,17 @@ export const layer = Layer.effect(

yield* check.pipe(Effect.forkScoped);

// A name a server reports, or a session it refused, reaches Settings without waiting for the next
// check; the app's own edits are checked by their handlers.
// A name a server reports, a remote one going on or offline, or a session it refused, reaches
// Settings without waiting for the next check; the app's own edits are checked by their handlers.
yield* servers.watch.pipe(
Stream.map((rows) =>
rows.map((row) => `${row.id}=${row.host} ${row.kind === "remote" && row.token === null}`).join("\n"),
rows
.map((row) =>
row.kind === "remote"
? `${row.id}=${row.host} ${row.label} ${row.version} ${row.seenAt} ${row.online} ${row.token === null} ${row.machineId} ${JSON.stringify(row.workspaces)}`
: `${row.id}=${row.host}`,
)
.join("\n"),
),
Stream.changes,
Stream.drop(1),
Expand Down
11 changes: 9 additions & 2 deletions apps/server/src/reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,22 @@ const model = (provider: string | null, id: string | null) =>

/** The machine columns a read selects to name it by {@link Servers.nameOf}. */
export const MACHINE =
"machine.kind AS machine_kind, machine.name AS machine_override, machine.host AS machine_host, machine.url AS machine_url";
"machine.kind AS machine_kind, machine.name AS machine_override, machine.label AS machine_label, machine.host AS machine_host, machine.url AS machine_url";
export interface MachineColumns {
readonly machineKind: string;
readonly machineOverride: string | null;
readonly machineLabel: string | null;
readonly machineHost: string | null;
readonly machineUrl: string | null;
}
export const machineName = (row: MachineColumns) =>
Servers.nameOf({ kind: row.machineKind, override: row.machineOverride, host: row.machineHost, url: row.machineUrl });
Servers.nameOf({
kind: row.machineKind,
override: row.machineOverride,
label: row.machineLabel,
host: row.machineHost,
url: row.machineUrl,
});

/** The machine filter of `sidebar.list`. */
const onMachines = (sql: SqlClient.SqlClient, machines: "default" | "all") =>
Expand Down
Loading