diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index 675e5ea7..f9d9156a 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -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, @@ -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; @@ -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({ @@ -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, }), @@ -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, @@ -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. */ @@ -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, diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index 54f1f4cf..909c94b6 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -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* () { diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 0eabe66e..525d35a1 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -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"; @@ -10,6 +11,7 @@ import { ModelsError, ProjectError, type ServerAdd, + ServersError, SettingsConflict, SettingsError, type ServerUpdate, @@ -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 = (change: Effect.Effect) => Effect.gen(function* () { @@ -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>) => + "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", {})); }), @@ -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; }), diff --git a/apps/server/src/health.ts b/apps/server/src/health.ts index e11e4982..8008e843 100644 --- a/apps/server/src/health.ts +++ b/apps/server/src/health.ts @@ -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), diff --git a/apps/server/src/reads.ts b/apps/server/src/reads.ts index 2b4f68f1..0e9c0b01 100644 --- a/apps/server/src/reads.ts +++ b/apps/server/src/reads.ts @@ -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") => diff --git a/apps/server/src/servers.ts b/apps/server/src/servers.ts index b5622839..9028c6be 100644 --- a/apps/server/src/servers.ts +++ b/apps/server/src/servers.ts @@ -1,4 +1,4 @@ -import { Clock, Config, Context, Effect, FileSystem, Layer, Schema, Stream, SubscriptionRef } from "effect"; +import { Clock, Config, Context, Effect, FileSystem, Layer, Option, Schema, Stream, SubscriptionRef } from "effect"; import { SqlClient } from "effect/sql"; /* @effect-diagnostics nodeBuiltinImport:off -- paths typed in Settings expand against the OS home directory. */ import os from "node:os"; @@ -7,10 +7,12 @@ import { type CliEnvVar, LOCAL_SERVER, PairingRefused, + RemoteServerStatus, type ServerAdd, ServersError, type ServerUpdate, } from "@codeworksh/contract"; +import type { Machine } from "@codeworksh/schema"; import { Pairing } from "./pairing.ts"; /** The same home the CLI resolves: CODEWORK_HOME_DIR, else ~/.codework. Only the built-in server falls back to it. */ @@ -29,35 +31,33 @@ export const splitArgs = (input: string) => [...input.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3] ?? ""); /** - * What a machine is called: the user's override, else the name its server reports, else where it is. - * The one rule every machine name shown goes through. + * What a machine is called: the user's override of a local one, else the label stored on a remote one, + * else the name its server reports, else where it is. The one rule every machine name shown goes through. */ export const nameOf = (machine: { readonly kind: string; readonly override: string | null; + readonly label: string | null; readonly host: string | null; readonly url: string | null; }) => machine.override ?? + machine.label ?? machine.host ?? (machine.kind === "remote" && machine.url !== null && URL.canParse(machine.url) ? new URL(machine.url).host : "This Machine"); -/** How a machine is named, as stored and as shown. */ -interface Naming { +/** A local server as stored. A `null` executable or home is the one found. An executable is a path, or a + * command whose first word is one (`node --conditions=development …/index.ts`, running from source). */ +export interface LocalRow { + readonly id: string; /** As shown: {@link nameOf}. */ readonly name: string; /** As its server last reported it. */ readonly host: string | null; /** As the user named it in Settings. */ readonly override: string | null; -} - -/** A local server as stored. A `null` executable or home is the one found. An executable is a path, or a - * command whose first word is one (`node --conditions=development …/index.ts`, running from source). */ -export interface LocalRow extends Naming { - readonly id: string; readonly kind: "local"; readonly executable: string | null; readonly home: string | null; @@ -66,10 +66,23 @@ export interface LocalRow extends Naming { readonly isDefault: boolean; } -/** A remote server as stored: where the app reaches it, and the session it paired for. */ -export interface RemoteRow extends Naming { +/** A remote server as stored: where the app reaches it, the session it paired for, and what it last reported. */ +export interface RemoteRow { readonly id: string; readonly kind: "remote"; + /** As shown: {@link nameOf}. */ + readonly name: string; + readonly host: string | null; + /** The label stored on the machine. */ + readonly label: string | null; + readonly version: string | null; + readonly seenAt: number | null; + /** Whether its sync connection is up now. */ + readonly online: boolean; + /** The machine's own id, as it last reported it. */ + readonly machineId: string | null; + /** The workspaces it is linked to, as it last reported them. */ + readonly workspaces: RemoteServerStatus["workspaces"]; readonly url: string; /** The session token its pairing gave; none once the server refused it, or on a row from before pairing. */ readonly token: string | null; @@ -78,6 +91,26 @@ export interface RemoteRow extends Naming { export type Row = LocalRow | RemoteRow; +/** What a server reports about itself; an absent one is left as stored. */ +export interface Facts { + readonly host?: string | null; + readonly label?: string | null; + readonly version?: string; + readonly machineId?: string | null; + readonly workspaces?: RemoteServerStatus["workspaces"]; +} + +/** What a remote machine's own record says about it: its label, its id and its links. */ +export const factsOf = (status: Machine.Status): Facts => ({ + label: status.givenName, + machineId: status.id, + workspaces: status.workspaces.map(({ id, keyId }) => ({ id, keyId })), +}); + +const Workspaces = Schema.fromJsonString(RemoteServerStatus.fields.workspaces); +const decodeWorkspaces = Schema.decodeUnknownOption(Workspaces); +const encodeWorkspaces = Schema.encodeSync(Workspaces); + const decodeEnv = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredEnv)); const fail = (message: string) => new ServersError({ message }); @@ -170,8 +203,10 @@ export class Service extends Context.Service< readonly homeChanges: Stream.Stream; /** Every server now, then again after each change to any of them. */ readonly watch: Stream.Stream>; - /** Stores the name a server reports, when it is not the one stored. */ - readonly setHost: (id: string, host: string | null) => Effect.Effect; + /** Stores what a server answered and when, and counts it online until {@link lost}. */ + readonly reached: (id: string, facts: Facts) => Effect.Effect; + /** Counts a server offline once its connection is gone; it was answering until then. */ + readonly lost: (id: string) => Effect.Effect; readonly add: (input: ServerAdd) => Effect.Effect; readonly update: (input: ServerUpdate) => Effect.Effect; /** Drops a remote server's session once the server refused it, unless the row paired again since. */ @@ -188,32 +223,59 @@ export const layer = Layer.effect( const fs = yield* FileSystem.FileSystem; const fallback = yield* cliHome.pipe(Effect.orDie); + // Ids whose sync connection is up: known only while this process runs. + const online = new Set(); + const list = sql< Omit & { kind: string; env: string; url: string | null; token: string | null; + label: string | null; + version: string | null; + seenAt: number | null; + identity: string | null; + workspaces: string | null; isDefault: number; } >` - SELECT id, kind, name AS override, host, executable, home, args, env, url, token, is_default FROM machine ORDER BY pos + SELECT id, kind, name AS override, host, label, version, seen_at, identity, workspaces, executable, home, args, + env, url, token, is_default + FROM machine ORDER BY pos `.pipe( Effect.flatMap((rows) => - Effect.forEach(rows, ({ kind, url, token, env, isDefault, ...row }) => { - const naming = { name: nameOf({ kind, url, ...row }), host: row.host, override: row.override }; - return kind === "remote" && url !== null - ? Effect.succeed({ id: row.id, kind, ...naming, url, token, isDefault: isDefault === 1 }) - : decodeEnv(env).pipe( - Effect.map((env): Row => ({ - ...row, - ...naming, - kind: "local", - env, + Effect.forEach( + rows, + ({ kind, url, token, env, isDefault, label, version, seenAt, identity, workspaces, ...row }) => { + const name = nameOf({ kind, url, label, ...row }); + return kind === "remote" && url !== null + ? Effect.succeed({ + id: row.id, + kind, + name, + host: row.host, + label, + version, + seenAt, + online: online.has(row.id), + machineId: identity, + workspaces: Option.getOrElse(decodeWorkspaces(workspaces), () => []), + url, + token, isDefault: isDefault === 1, - })), - ); - }), + }) + : decodeEnv(env).pipe( + Effect.map((env): Row => ({ + ...row, + name, + kind: "local", + env, + isDefault: isDefault === 1, + })), + ); + }, + ), ), Effect.orDie, ); @@ -276,7 +338,7 @@ export const layer = Layer.effect( const label = ((yield* list).find((row) => row.id === LOCAL_SERVER)?.host ?? os.hostname()).slice(0, 100); const device = yield* Pairing.exchange(url, code.trim(), label).pipe( Effect.timeout("10 seconds"), - Effect.mapError(() => fail("Couldn't pair with the server at that URL. Check the URL, then try again.")), + Effect.mapError(() => fail("No Machine answered at that address. Check it, then try again.")), ); if (device === undefined) return yield* new PairingRefused({ @@ -297,11 +359,24 @@ export const layer = Layer.effect( defaultHome, homeChanges: SubscriptionRef.changes(current).pipe(Stream.drop(1)), watch: SubscriptionRef.changes(machines), - setHost: Effect.fn("Servers.setHost")(function* (id, host) { - const changed = yield* sql` - UPDATE machine SET host = ${host} WHERE id = ${id} AND host IS NOT ${host} RETURNING id - `.pipe(Effect.orDie); - if (changed.length > 0) yield* announce; + reached: Effect.fn("Servers.reached")(function* (id, { machineId, workspaces, ...facts }) { + const seenAt = yield* Clock.currentTimeMillis; + const fields = { + ...facts, + ...(machineId === undefined ? {} : { identity: machineId }), + ...(workspaces === undefined ? {} : { workspaces: encodeWorkspaces(workspaces) }), + seenAt, + }; + yield* sql`UPDATE machine SET ${sql.update(fields)} WHERE id = ${id}`.pipe(Effect.orDie); + online.add(id); + yield* announce; + }), + + lost: Effect.fn("Servers.lost")(function* (id) { + if (!online.delete(id)) return; + const seenAt = yield* Clock.currentTimeMillis; + yield* sql`UPDATE machine SET seen_at = ${seenAt} WHERE id = ${id}`.pipe(Effect.orDie); + yield* announce; }), add: Effect.fn("Servers.add")(function* (input) { @@ -322,7 +397,7 @@ export const layer = Layer.effect( yield* sql`INSERT INTO machine ${sql.insert({ id, kind: input.kind, - name: override(input.name), + name: input.kind === "local" ? override(input.name) : null, ...route, namespace: "codework", pos: (last?.pos ?? 0) + 1, @@ -354,13 +429,14 @@ export const layer = Layer.effect( Effect.gen(function* () { const row = yield* get(id); const fields: Record = {}; - if (patch.name !== undefined) fields.name = override(patch.name); if (row.kind === "remote") { + if (patch.name !== undefined) return yield* fail("A paired Machine is renamed with its Label."); if ([patch.executable, patch.home, patch.args, patch.env].some((value) => value !== undefined)) return yield* fail("A remote server has no executable, home, arguments or variables."); if (patch.url !== undefined) fields.url = yield* chosenUrl(patch.url); if (session !== undefined) fields.token = session; } else { + if (patch.name !== undefined) fields.name = override(patch.name); if (patch.url !== undefined) return yield* fail("Only a remote server has a URL."); if (patch.executable !== undefined) fields.executable = yield* chosenCommand(fs, patch.executable); if (patch.args !== undefined) fields.args = patch.args.trim(); diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index df83337c..fe9360dd 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -6,6 +6,7 @@ import { Context, Deferred, Effect, + Exit, FiberHandle, FiberMap, FileSystem, @@ -340,10 +341,14 @@ export const layer = Layer.effect( * the store's line (by `boot`) comes back from zero with `reset`; a server older than boots is * read from zero only while its head is behind the cursor. */ - const connected = (machineId: string, client: Connection) => + const connected = (row: Servers.Row, client: Connection) => Effect.gen(function* () { + const machineId = row.id; const info = yield* client("server.info", {}); - yield* servers.setHost(machineId, info.host?.name ?? null); + // Only a remote machine is named by its label; one that fails to read its record still syncs, keeping the stored one. + const asked = row.kind === "remote" ? yield* Effect.exit(client("machine.info", {})) : undefined; + const own = asked !== undefined && Exit.isSuccess(asked) ? Servers.factsOf(asked.value) : {}; + yield* servers.reached(machineId, { host: info.host?.name ?? null, version: info.version, ...own }); const [machine] = yield* sql<{ storeId: string | null; cursor: number; @@ -502,12 +507,16 @@ export const layer = Layer.effect( if (clients.get(row.id) === client) clients.delete(row.id); }), ); + yield* Effect.addFinalizer(() => servers.lost(row.id)); yield* Effect.forkScoped(followUsage(row.id, client)); - yield* connected(row.id, client).pipe( + yield* connected(row, client).pipe( Effect.catchCause((cause) => - Effect.logWarning("Machine sync stopped; reconnecting", cause).pipe( - Effect.annotateLogs({ machineId: row.id }), - ), + servers + .lost(row.id) + .pipe( + Effect.andThen(Effect.logWarning("Machine sync stopped; reconnecting", cause)), + Effect.annotateLogs({ machineId: row.id }), + ), ), Effect.andThen(Effect.sleep("1 second")), Effect.forever, diff --git a/apps/server/test/__artifacts__/door.json b/apps/server/test/__artifacts__/door.json index d6307685..6924d351 100644 --- a/apps/server/test/__artifacts__/door.json +++ b/apps/server/test/__artifacts__/door.json @@ -22,12 +22,17 @@ "status": { "id": "", "kind": "remote", - "name": "Scripted", + "name": "Fixture", "host": "Fixture", - "override": "Scripted", + "label": null, "isDefault": false, "url": "", - "paired": true + "paired": true, + "online": true, + "seenAt": "