From 72fa49e1b4078a145eb837c2cd87ac27fd42628b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:13:05 +0000 Subject: [PATCH 01/21] docs(plans): machine connection hardening epic Plan to keep remote machines connected through blips, roaming and sleep on every client: per-machine multiplexed relay on Windows, retries gated on machine state, terminals that wait out outages, wake/network-change reconnects, tuned backoff, a readiness check, a guide, and fault-injection tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- docs/plans/machine-connection-hardening.md | 133 +++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 docs/plans/machine-connection-hardening.md diff --git a/docs/plans/machine-connection-hardening.md b/docs/plans/machine-connection-hardening.md new file mode 100644 index 00000000..6dcbb7ad --- /dev/null +++ b/docs/plans/machine-connection-hardening.md @@ -0,0 +1,133 @@ +# Machine Connection Hardening Epic + +**Status**: PLANNED +**Goal**: Remote machines stay connected through network blips, roaming and sleep on every client, and recover within seconds when a link really drops. + +## Overview + +Users see remote machines go offline and terminals die far more often than their network actually fails, and most often on Windows. Each Windows daemon connection is its own `ssh.exe` login, so one idle machine logs in many times a minute. On a blip every stream retries at the same moment, and sshd's `MaxStartups`, fail2ban or `ufw limit` then refuse the logins that should have repaired the connection. On every platform a terminal stops reconnecting after 20 attempts (about 30 s, and the count is never reset). Reconnects wait out a backoff of up to 60 s instead of reacting to wake and network changes. Fixing these turns most "disconnects" into short pauses, and ones that are left visibly recover by themselves. + +--- + +## Spec Decisions + +Record the hardening decisions in `docs/product/machines.md` (and `windows-app.md` WINAPP-013) before any code, so later tasks implement a SPECIFIED contract. + +**Requirements**: +- Given the multiplexed relay, should define its framing, versioning and fallback to the per-connection relay as new MACH decisions with Given/should requirements. +- Given the retry and wake rules below, should state them once as cross-platform requirements that the macOS, iPad and Windows tasks cite. + +--- + +## Failure Classification + +Classify every failed SSH attempt by its cause and show that cause on the machine, so users and later tasks can tell what is failing. + +**Requirements**: +- Given ssh stderr like `kex_exchange_identification: Connection closed by remote host` or `Connection reset by peer` before authentication, should report "the server refused the login (rate limit or MaxStartups)" rather than plain offline. +- Given a timeout, `Network is unreachable` or a DNS failure, should report the network as the cause. +- Given repeated failures, should keep a short per-machine connection log (time, cause, time to recover) that the user can open from the machine's menu. + +--- + +## Terminals Never Give Up While Their Agent Lives + +Change attach retry on macOS, iPad and Windows so a pane waits for its machine instead of spending a fixed retry budget. + +**Requirements**: +- Given an attach that succeeds after retrying, should reset its retry count. +- Given an attach failing because the machine's connection is down, should wait until the machine reports connected and then reattach, however long the outage lasts. +- Given a reattach, should keep replaying the daemon's buffer (`replay: snapshot`) so no output is lost across the gap. +- Given `AGENT_NOT_FOUND` or the stream closing on agent exit, should still end the session as today. + +--- + +## Retries Follow the Machine's State + +Make status, grid and project subscriptions, the project refresh and file and git requests for a remote machine pause while it is offline and resume together once it is back. + +**Requirements**: +- Given a machine that went offline, should stop its subscriptions' independent retries (today 0.5–5 s on Windows) and start no new SSH logins except the supervisor's. +- Given the machine reconnects, should resubscribe its streams with random jitter spread over about 1 s, not all at once. +- Given a local daemon, should keep its current retry behaviour. + +--- + +## Multiplexed Relay + +Add `pu daemon proxy --mux`, which carries many logical daemon connections over one stdio stream, so a Windows machine needs one long-lived `ssh.exe` instead of one per connection. + +**Requirements**: +- Given `--mux`, should exchange a version header, then carry length-prefixed frames to open, send data on, close and ping numbered channels, each channel bridged to its own `~/.pu/daemon.sock` connection. +- Given a channel's socket closing, should close only that channel and leave the others running. +- Given no daemon answering when a channel opens, should refuse that channel with the relay's "no daemon" status, not exit, and never start a daemon (MACH-003). +- Given a remote `pu` that predates `--mux`, should be detected from the header exchange so the client can fall back to the per-connection relay. +- Given a channel that stops reading, should apply backpressure to that channel only and never buffer without limit. + +--- + +## Windows Uses the Multiplexed Relay + +Give each Windows machine one supervised `ssh.exe --mux` session, and open every probe, request, subscription and attach for it as a channel on that session. + +**Requirements**: +- Given a connected machine, should hold exactly one `ssh.exe` for it, however many projects, panes and requests are open. +- Given no ping reply within 10 s twice in a row, should treat the session as dead, end `ssh.exe` and reconnect, rather than waiting for ssh's 45 s keepalive. +- Given a remote `pu` without `--mux`, should fall back to today's per-connection relay and say on the machine that upgrading PurePoint there improves reliability. +- Given `pu --machine` on Windows, should keep the per-connection relay, since each invocation is short-lived. + +--- + +## Reconnect on Wake and Network Change + +Reconnect immediately when the device wakes, its network changes or the app returns to the foreground, instead of waiting out the backoff. + +**Requirements**: +- Given a wake from sleep or a network path change (`NWPathMonitor` and `NSWorkspace.didWakeNotification` on macOS, `NWPathMonitor` on iPad, power-resume and network-change notifications on Windows), should reset the backoff and probe or reconnect every machine at once. +- Given a network change while a connection still looks alive, should probe it right away and replace it if the probe does not answer within the probe timeout. +- Given no usable network path, should show machines as waiting for the network and make no SSH attempts until one returns. + +--- + +## Backoff and SSH Option Tuning + +Retune reconnect pacing and SSH options consistently on every client. + +**Requirements**: +- Given repeated connect failures, should back off 1, 2, 4, 8, then every 15 s, with full random jitter, on macOS, iPad and Windows alike (macOS and Windows go up to 60 s today). +- Given a reconnect on macOS, should reuse the remote home directory resolved on the first connect rather than spending an extra SSH login on it each time. +- Given any SSH command, should pass `ConnectTimeout=10` and `TCPKeepAlive=yes` alongside `ServerAliveInterval=15` and `ServerAliveCountMax=3`. + +--- + +## Machine Readiness Check + +Add `pu doctor --machine `, also offered after Add Machine, to check the remote machine for settings that cause drops. + +**Requirements**: +- Given a reachable machine, should report its effective `MaxStartups`, `MaxSessions`, `ClientAliveInterval` (from `sshd -T` when readable), whether fail2ban, sshguard or a `ufw limit` rule covers ssh, and whether the machine sleeps when idle. +- Given a setting that will cause drops, should name the exact line to change and why, without changing anything itself. +- Given a check it cannot run without root, should say it was skipped instead of reporting it as passing. + +--- + +## Reliable Connections Guide + +Write `docs/guide/reliable-machine-connections.md`, covering a WireGuard overlay (Tailscale or plain WireGuard) for roaming, the sshd settings the readiness check recommends, and keeping the remote machine awake. + +**Requirements**: +- Given a user on changing networks, should explain that a stable overlay address lets SSH survive Wi-Fi roams and IP changes, and how to point `ssh_host` at it. +- Given a user who sees "the server refused the login", should lead them from that message to the sshd and fail2ban fix. + +--- + +## Fault-Injection Tests + +Add tests that run the relay and clients through a fault-injecting proxy and fake ssh (`PU_SSH`), so recovery is measured rather than assumed. + +**Requirements**: +- Given the link dropped for 2 s, 60 s and 10 min, should show every client recover its streams and terminals once the link returns, with terminals replayed rather than ended. +- Given a link that stops answering without closing, should replace the connection within the documented detection time. +- Given a server that refuses logins above a set rate, should show a Windows machine with many panes reconnect without tripping it. + +--- From 8c2b2159d3df6775a7991fdb4d2021d3623d5d14 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:34:05 +0000 Subject: [PATCH 02/21] =?UTF-8?q?docs(machines):=20specify=20connection=20?= =?UTF-8?q?hardening=20(MACH-013=20=E2=80=93=20MACH-019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Multiplexed relay for Windows, retries that follow machine state, attaches that wait out outages, event-driven reconnects with jittered backoff, ssh connect and TCP keepalive options, failure classification with a connection log, and pu doctor --machine. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- docs/product/machines.md | 59 ++++++++++++++++++++++++++++++++++++- docs/product/windows-app.md | 6 +++- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/product/machines.md b/docs/product/machines.md index 3066604d..9483536d 100644 --- a/docs/product/machines.md +++ b/docs/product/machines.md @@ -48,6 +48,13 @@ Alternative considered: a dedicated mTLS worker protocol with enrollment, ledger ! [MACH-010] On iPad, PurePoint stores one device SSH identity: an Ed25519 private key in the Keychain, device-only and never synchronized, generated on first launch or imported from an OpenSSH key. It also pins each machine's host key on first use, after explicit confirmation, and refuses a changed key until the pin is deliberately reset — iOS has no ssh agent, `~/.ssh` or `known_hosts`, so the app must hold the key and the trust MACH-001 leaves to the system. ! [MACH-011] On iPad, machines are registered in the app container's own `Application Support/PurePoint/machines.json` with the same schema, not synced with any Mac and without flock or `~/.ssh/config` — there is no shared home or CLI on iOS, and a Mac entry's ssh alias and key would not work from the iPad. ! [MACH-012] On Windows, a machine's daemon connection is one system `ssh.exe` (Win32-OpenSSH, or `PU_SSH`) per connection, running `pu daemon proxy` on the machine — Win32-OpenSSH has no `ControlMaster`, and a Unix-socket `-L` forward has no Windows endpoint to bind. The relay is the iPad's (MACH-009), and it still uses the user's own ssh config, agent and keys (MACH-001). The registry is `%USERPROFILE%\.pu\machines.json`, with the same schema, shared by the app and the CLI (MACH-008). See [windows-app.md](windows-app.md) WINAPP-013. +! [MACH-013] On Windows, the app carries all of a machine's daemon connections as channels of one multiplexed relay, `pu daemon proxy --mux`, over one long-lived `ssh.exe` per machine. A Windows client otherwise logs in over SSH for every probe, request and stream, and on a network blip every stream logs in again at once, tripping sshd `MaxStartups`, fail2ban, sshguard and `ufw limit`. The CLI keeps the per-connection relay (MACH-012), since each invocation is short-lived. A machine whose `pu` predates `--mux` falls back to the per-connection relay. +! [MACH-014] A client's work for a remote machine follows the machine's connection state. While the machine is not connected, its subscriptions, project refresh, file and git requests and attaches make no SSH attempts of their own: only the machine's supervisor reconnects. Once it is connected again, they resume with jitter. Independent retries multiply logins exactly when the server is most likely to refuse them. +! [MACH-015] An attach to an agent that still exists never gives up because a machine is unreachable. Its retry count resets after every successful attach, and a failure while its machine is not connected waits for the machine instead of using up retries. The daemon replays the agent's buffer on every attach (IPC-002), so no output is lost across the gap. +! [MACH-016] Reconnecting reacts to events as well as time. Waking from sleep, a network path change and returning to the foreground reset the reconnect backoff and probe or reconnect every machine at once. Reconnect backoff is 1, 2, 4, 8, then 15 s with equal jitter (a uniformly random delay between half and all of the step) on every client. +! [MACH-017] Every ssh command PurePoint runs passes `-o ConnectTimeout=10 -o TCPKeepAlive=yes`, and every long-lived one also passes `-o ServerAliveInterval=15 -o ServerAliveCountMax=3`. A dial to an unreachable host fails within 10 s, and a dead path is noticed even when ssh's own keepalive is blocked. +! [MACH-018] Every failed connection attempt is classified by cause (server refused the login, network, authentication, host key, `pu` missing, daemon stopped, other) from ssh's exit status and stderr. The machine shows that cause, and each client keeps an in-memory connection log of the last 50 drops and recoveries per machine. "Offline" alone does not tell a user whether to fix their network or their server. +! [MACH-019] `pu doctor --machine ` checks a machine for settings that cause drops and names the exact fix, changing nothing. Most remaining disconnects are caused by the server or the network, not by PurePoint. ## Requirements @@ -81,6 +88,24 @@ Alternative considered: a dedicated mTLS worker protocol with enrollment, ledger - Given the iPad machine registry, should read and write the `machines.json` schema in the app container, with atomic replacement, no flock, no `~/.ssh/config` and no sync. - Given Add Machine on iPad, should store `ssh_host` as `user@host` or `user@host:port`, since there are no ssh config aliases. +### Connection resilience (MACH-013 – MACH-019) + +- Given a Windows app connected to a machine whose `pu` supports `--mux`, should hold exactly one `ssh.exe` for that machine, however many projects, panes and requests are open. +- Given no `pong` within 10 s for two pings in a row on a multiplexed relay, should end that `ssh.exe` and reconnect, without waiting for ssh's own keepalive. +- Given a machine whose `pu` predates `--mux`, should fall back to one `ssh.exe` per connection and say on the machine that upgrading PurePoint there improves reliability. +- Given a channel whose consumer stops reading, should stop that channel's sender through its window and never buffer without limit, while the session's other channels keep flowing. +- Given a machine that went offline, should start no SSH logins for it except its supervisor's, until it reports connected again. +- Given a machine that reconnects, should resubscribe its streams and reattach its panes after a uniformly random delay of 0–1 s each. +- Given an attach that succeeds after retrying, should reset its retry count. +- Given an attach failing while its machine is not connected, should wait until the machine reports connected and reattach, however long the outage lasts. +- Given a wake from sleep, a network path change or the app returning to the foreground, should reset every machine's reconnect backoff and probe or reconnect it at once. +- Given no usable network path, should show machines as waiting for the network and make no SSH attempts until a path returns. +- Given consecutive connect failures, should wait 1, 2, 4, 8, then 15 s, each scaled by a uniformly random factor in [0.5, 1]. +- Given a reconnect on macOS or Linux, should reuse the remote home directory resolved on the first connect. +- Given ssh failing before authentication with `kex_exchange_identification`, `Connection closed by remote host` or `Connection reset by peer`, should report that the server refused the login (rate limit or `MaxStartups`), not merely offline. +- Given a machine with drops, should list in its connection log the time, cause and ssh message of each of the last 50 drops, and how long each took to recover. +- Given `pu doctor --machine `, should report what it found, a fix for each problem, and every check it skipped, and change nothing on either machine. + ## Sum Sheet Machine = SSH destination. Endpoint = forwarded socket (Mac, Linux) or exec relay per connection (iPad, Windows). Identity = (machine, root). Daemon owns work. Files and git over IPC. CLI targets explicitly. iPad keys and host pins live in the Keychain, and its registry lives in the container. @@ -99,6 +124,7 @@ Machine = SSH destination. Endpoint = forwarded socket (Mac, Linux) or exec rela ``` /usr/bin/ssh -N -T -o BatchMode=yes -o ExitOnForwardFailure=yes \ + -o ConnectTimeout=10 -o TCPKeepAlive=yes \ -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StreamLocalBindUnlink=yes \ -o ControlMaster=no -o ControlPath=none \ -L :/.pu/daemon.sock @@ -120,7 +146,35 @@ Keychain items, registry location and the overflow-connection rule are specified ### Windows relay (MACH-012) -The Windows app and `pu --machine` run `ssh.exe -T -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 ` per daemon connection (`pu --machine` also passes `-o ControlMaster=no -o ControlPath=none`, which matter only when `PU_SSH` or `PATH` names a non-Win32 ssh that multiplexes), where `` is the iPad relay command above for a Unix machine, or `pu daemon proxy` for a Windows machine. No `-L` forward, `forward.lock`, `cli-.sock` or stale-forward sweep exists on Windows. Exit codes are the relay's (0, 69, 1), plus 127 or 9009 when `pu` is missing. Full contract: [windows-app.md](windows-app.md) (Interfaces, Remote relay). +The Windows app and `pu --machine` run `ssh.exe -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 ` per daemon connection (the app only when the machine lacks the multiplexed relay, MACH-013) (`pu --machine` also passes `-o ControlMaster=no -o ControlPath=none`, which matter only when `PU_SSH` or `PATH` names a non-Win32 ssh that multiplexes), where `` is the iPad relay command above for a Unix machine, or `pu daemon proxy` for a Windows machine. No `-L` forward, `forward.lock`, `cli-.sock` or stale-forward sweep exists on Windows. Exit codes are the relay's (0, 69, 1), plus 127 or 9009 when `pu` is missing. Full contract: [windows-app.md](windows-app.md) (Interfaces, Remote relay). + +### Multiplexed relay (MACH-013) + +`pu daemon proxy --mux [--socket ]` carries any number of daemon connections over stdin and stdout. On a Unix machine it runs inside the same `/bin/sh` wrapper as the plain relay, with `exec pu daemon proxy --mux`. It never starts a daemon, writes diagnostics to stderr only and exits 0 when stdin closes. The implementation, server and client, is `pu_transport::mux`. + +**Handshake.** The relay first writes the line `PUMUX 1\n`. The client checks it, then writes `PUMUX 1\n` itself, and frames follow in both directions. A `pu` without `--mux` exits 2 before writing anything (clap usage error), and the client treats that, or any first line other than `PUMUX `, as no mux support and falls back to the per-connection relay. A relay that reads a client version other than `1` exits 1. Future versions bump ``, and a client may offer only a version the relay announced. + +**Frames.** Each frame is a 4-byte big-endian length (of everything after it), a 1-byte type, a 4-byte big-endian channel id and a payload. The length is at least 5 and at most 65 541 (64 KiB of payload). A frame outside those bounds, an unknown type, or a frame for an unknown channel other than a late `data`, `eof`, `close` or `window` for a channel that just closed, is a protocol error: the side that sees it ends the whole session. + +| Type | Name | Direction | Channel | Payload | +|---|---|---|---|---| +| 1 | `open` | client → relay | new id, nonzero, never reused in the session | none | +| 2 | `open_ok` | relay → client | the opened id | none | +| 3 | `open_fail` | relay → client | the refused id | 1-byte reason (1 = no daemon, 2 = too many channels, 3 = other), then a UTF-8 message | +| 4 | `data` | both | an open channel | 1 – 65 536 bytes | +| 5 | `eof` | both | an open channel | none: the sender writes no more data (half-close) | +| 6 | `close` | both | an open channel | none: the channel is gone; the receiver drops it and replies `close` unless it already sent one | +| 7 | `window` | both | an open channel | 4-byte big-endian credit increase | +| 8 | `ping` | both | 0 | 8 opaque bytes | +| 9 | `pong` | both | 0 | the `ping`'s 8 bytes | + +**Channels.** On `open` the relay connects to the daemon socket and answers `open_ok` or `open_fail`. Reason 1 matches the plain relay's exit 69, and the client reports it the same way (daemon stopped). A session holds at most 1024 open channels, the daemon's own connection limit (IPC-001). The daemon closing its side sends `eof`, then `close`. A client `eof` half-closes the daemon socket. A `close` from the client drops the daemon connection. + +**Flow control.** Each side may send at most 256 KiB of `data` on a channel beyond what the other side has granted with `window`. A receiver grants credit only as it delivers bytes onward (to the daemon socket, or to the channel's reader), so a stalled consumer stops only its own channel. Sending beyond the window is a protocol error. + +**Liveness.** The client sends `ping` every 5 s. Two pings in a row unanswered within 10 s each mean the session is dead: the client ends `ssh.exe`, fails every channel and reconnects through the supervisor. The relay exits after 60 s with nothing received on stdin, so a relay left by a vanished client does not keep holding daemon connections. + +**Windows client.** The app's per-machine session runs `ssh.exe -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ControlMaster=no -o ControlPath=none `, where `` is the wrapped command above for a Unix machine and `pu daemon proxy --mux` for a Windows machine. Every probe, request, subscription and attach for the machine is a channel. Opening a channel while the session is down waits for it, up to the request's own timeout. ### Daemon file and git requests (protocol version 9) @@ -178,4 +232,7 @@ The app then types the returned path, shell-escaped, into the agent's terminal w - **Two app instances, one machine** (macOS): the instance holding `~/.pu/machines//forward.lock` (flock) owns the forward; another instance follows that forward and never launches or ends one of its own. - **Remote layout changed elsewhere** (another Mac, or `pu grid` on the machine): layout saves are conditional on the document's modification time; on a conflict the app adopts the machine's document instead of overwriting it, and quitting only writes layouts with unsaved changes. - **Remote files the editor cannot save** (over the ~750 KB request limit) open read-only; files over the 1 MB read limit show why they cannot open. Local copies for other apps are limited to 8 MB, quarantined (Gatekeeper checks them before anything runs), and removed when the app quits. +- **Network change under a live connection**: TCP cannot follow an address change, so the connection dies even if ssh has not noticed yet. The path-change probe (MACH-016) replaces it at once instead of after keepalive (up to 45 s). A WireGuard overlay such as Tailscale gives each device a stable address, so short roams do not drop the connection at all (`docs/guide/reliable-machine-connections.md`). +- **Server refusing logins**: sshd `MaxStartups` (default `10:30:100`) randomly drops unauthenticated connections once 10 are in progress, and fail2ban, sshguard and `ufw limit` (6 connections per 30 s) ban the client. ssh then fails before authentication; PurePoint reports it as such (MACH-018) and `pu doctor --machine` names the setting. +- **Mux relay outlives its client**: a client that vanished without closing stdin (a killed `ssh.exe` whose sshd has not noticed yet) leaves the relay with no input; the 60 s input timeout ends it and its daemon connections. - **Slow or stalled links**: every remote file and git call runs off Swift's shared concurrency pool (a dedicated queue per git service and for host I/O), so a degraded machine cannot stall local projects. diff --git a/docs/product/windows-app.md b/docs/product/windows-app.md index ffd4b2fc..1be039e0 100644 --- a/docs/product/windows-app.md +++ b/docs/product/windows-app.md @@ -101,6 +101,7 @@ Not proven, and owned by later leaves: Codex hooks on Windows (source only, WIN- ! [WINAPP-012] `~/.pu` is `%USERPROFILE%\.pu`, and `pu.exe` and `pu-engine.exe` install to `%USERPROFILE%\.pu\bin`. App-private state (windows, selection, preferences) lives in the Tauri app data directory — this matches the README and the Unix layout, so docs, scripts and the remote start command stay the same (plan DEC-3). ! [WINAPP-013] Remote machines are reached by system `ssh.exe` running `pu daemon proxy` on the machine, one `ssh.exe` process per daemon connection — Win32-OpenSSH has no `ControlMaster`, and the Unix-socket `ssh -L` forward has no Windows endpoint to bind. The exec relay is the transport the iPad already uses (plan DEC-5, IPAD-004). +! [WINAPP-013a] The app carries a machine's daemon connections as channels of one multiplexed relay per machine (`pu daemon proxy --mux` over one long-lived `ssh.exe`), falling back to one `ssh.exe` per connection when the machine's `pu` predates `--mux` — one login per connection tripped servers' login rate limits (`machines.md` MACH-013). ! [WINAPP-014] Paths are stored without `\\?\` prefixes. They are canonicalized through `dunce`, with `\` separators, an uppercase drive letter and no trailing separator. Paths are compared case-insensitively — manifests, `.projects.json` and protocol payloads are shared with other clients and must not drift. NTFS directories are case-insensitive by default. @@ -216,6 +217,7 @@ The daemon side is `pu_core::fs_retry` plus `handle_delete_worktree`: it waits o - REQ-WINAPP-053: Given a daemon connection to a machine, should start `ssh.exe` (found with `which` under `System32\OpenSSH`, or `PU_SSH`) per the relay command in Interfaces, and frame NDJSON over its stdio exactly as over the pipe. - REQ-WINAPP-054: Given a relay that exits 69, should show the machine as daemon-stopped and offer Start daemon. Given exit 127 or 9009 (`pu` not found), should report that PurePoint must be installed on that machine. It should never start a daemon automatically (MACH-003). +- REQ-WINAPP-053a: Given a machine whose `pu` supports `--mux`, the app should carry every daemon connection to it as a channel of one `ssh.exe` running the multiplexed relay (`machines.md`, Multiplexed relay), and fall back to REQ-WINAPP-053 otherwise. - REQ-WINAPP-055: Given `pu --machine ` on Windows, should use the same relay, with no forward socket, `forward.lock` or stale-forward sweep compiled in. - REQ-WINAPP-056: Given the machine registry, should read and write `%USERPROFILE%\.pu\machines.json` with the `machines.md` schema, shared by the app and the CLI. Writes are private atomic replaces under an `fs4` lock on `machines.json.lock`. @@ -455,9 +457,11 @@ Admin requests go over the owner pipe as `POST /admin/v1` with the bearer token ### Remote relay (Windows client) ``` -ssh.exe -T -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 +ssh.exe -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 ``` +- The app runs this per connection only when the machine's `pu` lacks `--mux`. Otherwise it holds one multiplexed session per machine (`machines.md`, Multiplexed relay, MACH-013). + - `pu --machine` also passes `-o ControlMaster=no -o ControlPath=none` before ``, as on its other ssh commands: Win32-OpenSSH ignores connection sharing, but `PU_SSH` or `PATH` may name an ssh (Git for Windows, MSYS2) that honours a user's ControlMaster config. - Unix machine: `` is `/bin/sh -c 'PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH"; export PATH; exec pu daemon proxy'`, the same as the iPad. From 28d0407f72a4feaf7e37231c76b0e4bbcc0af4a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:36:34 +0000 Subject: [PATCH 03/21] feat(core): classify ssh failures by cause (MACH-018) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- crates/pu-core/src/lib.rs | 1 + crates/pu-core/src/ssh_failure.rs | 232 ++++++++++++++++++++++++++++++ 2 files changed, 233 insertions(+) create mode 100644 crates/pu-core/src/ssh_failure.rs diff --git a/crates/pu-core/src/lib.rs b/crates/pu-core/src/lib.rs index 362c28c3..6ac14c99 100644 --- a/crates/pu-core/src/lib.rs +++ b/crates/pu-core/src/lib.rs @@ -22,6 +22,7 @@ pub mod channel; pub mod read; pub mod signals; +pub mod ssh_failure; #[cfg(all(test, feature = "ts"))] mod ts_export; diff --git a/crates/pu-core/src/ssh_failure.rs b/crates/pu-core/src/ssh_failure.rs new file mode 100644 index 00000000..3e2aace9 --- /dev/null +++ b/crates/pu-core/src/ssh_failure.rs @@ -0,0 +1,232 @@ +//! Why an ssh connection attempt failed (MACH-018), from ssh's exit status and stderr. +//! +//! "Offline" alone does not tell a user whether to fix their network, their keys or their +//! server, so every client classifies a failure into one [`SshFailureCause`] and shows its +//! [`SshFailureCause::summary`]. The Swift clients mirror these rules +//! (`Services/SSH/SSHFailureCause.swift`); keep the two in step. + +use serde::{Deserialize, Serialize}; + +/// The cause of one failed connection attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SshFailureCause { + /// The server closed or reset the connection before authentication: sshd `MaxStartups`, + /// fail2ban, sshguard or a firewall rate limit refused the login. + ServerRefused, + /// The host could not be reached: timeout, no route, unreachable network, DNS failure, + /// connection refused (no sshd listening) or a link that dropped mid-session. + Network, + /// The server rejected every key (`Permission denied`). + Auth, + /// The host key is unknown or changed. + HostKey, + /// `pu` is not installed on the machine (exit 127 or 9009). + PuMissing, + /// The relay reached the machine but no daemon answers (exit 69). + DaemonStopped, + /// Anything else. + Other, +} + +/// stderr fragments, matched case-insensitively, in priority order. +const RULES: &[(&str, SshFailureCause)] = &[ + ("host key verification failed", SshFailureCause::HostKey), + ( + "remote host identification has changed", + SshFailureCause::HostKey, + ), + ("no matching host key type", SshFailureCause::HostKey), + ("permission denied", SshFailureCause::Auth), + ("too many authentication failures", SshFailureCause::Auth), + ("no supported authentication methods", SshFailureCause::Auth), + // An established session that dropped: the path, not the server's login limits. + ("client_loop", SshFailureCause::Network), + ( + "kex_exchange_identification", + SshFailureCause::ServerRefused, + ), + ( + "ssh_exchange_identification", + SshFailureCause::ServerRefused, + ), + ("connection closed by", SshFailureCause::ServerRefused), + ("exceeded maxstartups", SshFailureCause::ServerRefused), + ("could not resolve hostname", SshFailureCause::Network), + ("name or service not known", SshFailureCause::Network), + ("nodename nor servname", SshFailureCause::Network), + ("no such host is known", SshFailureCause::Network), + ("timed out", SshFailureCause::Network), + ("no route to host", SshFailureCause::Network), + ("network is unreachable", SshFailureCause::Network), + ("host is unreachable", SshFailureCause::Network), + ("connection refused", SshFailureCause::Network), + ("broken pipe", SshFailureCause::Network), + ("connection reset by peer", SshFailureCause::Network), + ("timeout, server", SshFailureCause::Network), + ("not responding", SshFailureCause::Network), +]; + +impl SshFailureCause { + /// Classify a finished ssh process. `exit` is its status (`None` when it was killed or + /// never started); `stderr` is what it wrote. + pub fn classify(exit: Option, stderr: &str) -> Self { + match exit { + Some(69) => return Self::DaemonStopped, + Some(127) | Some(9009) => return Self::PuMissing, + _ => {} + } + Self::from_stderr(stderr).unwrap_or(Self::Other) + } + + /// The cause named by an ssh error message, if any rule matches. + pub fn from_stderr(stderr: &str) -> Option { + let lower = stderr.to_ascii_lowercase(); + RULES + .iter() + .find(|(fragment, _)| lower.contains(fragment)) + .map(|&(_, cause)| cause) + } + + /// A short, user-facing explanation that says where to look. + pub fn summary(self) -> &'static str { + match self { + Self::ServerRefused => { + "The server refused the login (rate limit or MaxStartups). Run `pu doctor --machine` to check its sshd and fail2ban settings." + } + Self::Network => { + "The machine could not be reached over the network (or a firewall such as fail2ban dropped it)." + } + Self::Auth => "The server rejected the SSH key.", + Self::HostKey => "The machine's host key is unknown or changed.", + Self::PuMissing => "PurePoint is not installed on the machine.", + Self::DaemonStopped => "The machine is reachable but its daemon is stopped.", + Self::Other => "The SSH connection failed.", + } + } + + /// Whether retrying soon can help: false for causes that need the user to act. + pub fn is_transient(self) -> bool { + matches!(self, Self::ServerRefused | Self::Network | Self::Other) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_pre_auth_close_should_report_server_refused() { + // given + let samples = [ + "kex_exchange_identification: Connection closed by remote host\r\nConnection closed by 10.0.0.5 port 22", + "kex_exchange_identification: read: Connection reset by peer", + "ssh_exchange_identification: Connection closed by remote host", + ]; + + // when / then + for stderr in samples { + assert_eq!( + SshFailureCause::classify(Some(255), stderr), + SshFailureCause::ServerRefused, + "{stderr}" + ); + } + } + + #[test] + fn given_network_errors_should_report_network() { + // given + let samples = [ + "ssh: connect to host studio port 22: Operation timed out", + "ssh: connect to host 10.0.0.5 port 22: No route to host", + "ssh: connect to host 10.0.0.5 port 22: Network is unreachable", + "ssh: Could not resolve hostname studio: Name or service not known", + "ssh: connect to host studio port 22: Connection refused", + "Timeout, server studio not responding.", + "client_loop: send disconnect: Broken pipe", + "client_loop: send disconnect: Connection reset by peer", + "read: Connection reset by peer", + ]; + + // when / then + for stderr in samples { + assert_eq!( + SshFailureCause::classify(Some(255), stderr), + SshFailureCause::Network, + "{stderr}" + ); + } + } + + #[test] + fn given_auth_and_host_key_failures_should_name_them() { + assert_eq!( + SshFailureCause::classify(Some(255), "user@studio: Permission denied (publickey)."), + SshFailureCause::Auth + ); + assert_eq!( + SshFailureCause::classify(Some(255), "Host key verification failed."), + SshFailureCause::HostKey + ); + assert_eq!( + SshFailureCause::classify( + Some(255), + "@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@\nHost key verification failed." + ), + SshFailureCause::HostKey + ); + } + + #[test] + fn given_relay_exit_codes_should_win_over_stderr() { + assert_eq!( + SshFailureCause::classify(Some(69), "error: cannot connect to the daemon"), + SshFailureCause::DaemonStopped + ); + assert_eq!( + SshFailureCause::classify(Some(127), "sh: pu: not found"), + SshFailureCause::PuMissing + ); + assert_eq!( + SshFailureCause::classify(Some(9009), ""), + SshFailureCause::PuMissing + ); + } + + #[test] + fn given_unknown_message_should_report_other() { + assert_eq!( + SshFailureCause::classify(None, "something odd"), + SshFailureCause::Other + ); + assert_eq!(SshFailureCause::from_stderr(""), None); + } + + #[test] + fn given_causes_should_say_which_need_the_user() { + assert!(SshFailureCause::ServerRefused.is_transient()); + assert!(SshFailureCause::Network.is_transient()); + assert!(!SshFailureCause::Auth.is_transient()); + assert!(!SshFailureCause::HostKey.is_transient()); + assert!(!SshFailureCause::PuMissing.is_transient()); + assert!(!SshFailureCause::DaemonStopped.is_transient()); + } + + #[test] + fn given_server_refused_should_point_at_doctor() { + assert!( + SshFailureCause::ServerRefused + .summary() + .contains("pu doctor --machine") + ); + } + + #[test] + fn given_cause_should_serialize_snake_case() { + assert_eq!( + serde_json::to_string(&SshFailureCause::ServerRefused).unwrap(), + "\"server_refused\"" + ); + } +} From 587c3856675ccdf6040b31a513afd383232d1f74 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:52:00 +0000 Subject: [PATCH 04/21] Windows: gate remote retries on machine state; classify ssh failures - ssh: every command passes ConnectTimeout=10 and TCPKeepAlive=yes (MACH-017). - Probes classify offline verdicts with pu_core's SshFailureCause and carry the cause and its summary (MACH-018). - Per-machine connection gates (daemon::gate), set by the supervisor through machine_set_reachable: a closed gate refuses relay opens without running ssh, and status/grid subscriptions and attach sessions wait on it, resuming 0-1 s after it opens. A failure while the gate is open waits for the supervisor's next probe and raises machine-suspect so it probes now (MACH-014). - Attach resets its retry count after every attach_ready and uses no retries while its machine is down; a relay whose ssh exited 255 is a dropped link, not the agent exiting (MACH-015). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- apps/purepoint-windows/src-tauri/Cargo.toml | 2 + .../src-tauri/src/attach/session.rs | 112 +++++- .../src-tauri/src/attach/session_tests.rs | 118 ++++++ .../src-tauri/src/daemon/client.rs | 55 +++ .../src-tauri/src/daemon/gate.rs | 352 ++++++++++++++++++ .../src-tauri/src/daemon/machine.rs | 158 ++++++-- .../src-tauri/src/daemon/mod.rs | 2 + .../src-tauri/src/daemon/relay.rs | 158 +++++++- apps/purepoint-windows/src-tauri/src/lib.rs | 7 + .../src-tauri/src/subscriptions/grid.rs | 21 +- .../src-tauri/src/subscriptions/mod.rs | 45 ++- .../src-tauri/src/subscriptions/status.rs | 15 +- .../src-tauri/src/subscriptions/tests.rs | 83 +++++ 13 files changed, 1067 insertions(+), 61 deletions(-) create mode 100644 apps/purepoint-windows/src-tauri/src/daemon/gate.rs diff --git a/apps/purepoint-windows/src-tauri/Cargo.toml b/apps/purepoint-windows/src-tauri/Cargo.toml index ab567a94..94d3d55e 100644 --- a/apps/purepoint-windows/src-tauri/Cargo.toml +++ b/apps/purepoint-windows/src-tauri/Cargo.toml @@ -90,6 +90,8 @@ windows-sys = { version = "0.61", features = [ [dev-dependencies] tempfile = "3" +# Paused-clock tests of the machine gates and retry loops (MACH-014). +tokio = { version = "1", features = ["test-util"] } # Mock runtime for the updater tests (WIN-10.3): the plugin is built only from an app handle. tauri = { version = "~2.11", features = ["test"] } diff --git a/apps/purepoint-windows/src-tauri/src/attach/session.rs b/apps/purepoint-windows/src-tauri/src/attach/session.rs index 57a6029d..a2df58e2 100644 --- a/apps/purepoint-windows/src-tauri/src/attach/session.rs +++ b/apps/purepoint-windows/src-tauri/src/attach/session.rs @@ -6,12 +6,19 @@ //! [`AttachSink`]: PTY output as raw bytes, everything else as an [`AttachEvent`]. Input, //! `resize` and `claim_size` go out on the same connection. //! -//! Retries follow the Swift loop exactly: +//! Retries (MACH-015: a pane never gives up while its agent lives): //! - the daemon closing an attached stream means the agent exited ([`AttachEvent::Exited`]); -//! no reattach, since every attach replays the whole buffer again; +//! no reattach, since every attach replays the whole buffer again. On a machine, ssh dropping +//! the link is not that close: the relay reports it as an error (`relay_eof_error`); //! - `AGENT_NOT_FOUND` means the agent is gone ([`AttachEvent::Gone`]); //! - any other failure reconnects with [`Backoff::SWIFT`] (5 tries 100 ms apart, then 2 s, -//! 20 in all; like the Mac, the count is not reset by a successful attach). +//! 20 in all). Every successful attach (`attach_ready`) starts the count again, so only 20 +//! failures in a row end the session; +//! - on a machine's daemon the session follows the machine's gate (MACH-014, +//! `crate::daemon::gate`): it attaches only while the machine is connected, and a failure +//! while the machine is down uses up no retries. It waits, however long the outage lasts, +//! and reattaches a uniformly random 0–1 s after the machine is back. A failure while the +//! machine still looks up also waits for the supervisor's next probe before retrying. //! //! The ESC c rule: the daemon replays its buffer on every attach, so a terminal that already //! shows output gets [`AttachEvent::Reset`] right before the first replayed chunk. That holds @@ -32,6 +39,7 @@ use serde::Serialize; use tokio::sync::{mpsc, oneshot}; use crate::daemon::client::{BoxWrite, DaemonClient, DaemonError, parse, write_request}; +use crate::daemon::gate::MachineGate; /// What the session tells the view, besides output bytes. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -107,6 +115,36 @@ impl Backoff { } } +/// What the session does after a failed attach. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Next { + /// The machine is down: wait for it, using up no retry. + WaitForMachine, + /// Retry number `attempt` after `delay`. + Retry { attempt: u32, delay: Duration }, + /// The retries ran out. + GiveUp, +} + +/// The decision after a failed attempt (MACH-015). `retries` is the count before it, reset +/// when the attempt had attached; returns the new count and what to do. +pub fn after_failure( + backoff: &Backoff, + retries: u32, + attached: bool, + machine_down: bool, +) -> (u32, Next) { + let retries = if attached { 0 } else { retries }; + if machine_down { + return (retries, Next::WaitForMachine); + } + let attempt = retries + 1; + match backoff.delay(attempt) { + Some(delay) => (attempt, Next::Retry { attempt, delay }), + None => (attempt, Next::GiveUp), + } +} + /// How a pane opens its session. #[derive(Debug, Clone)] pub struct AttachOptions { @@ -270,25 +308,65 @@ struct Worker { impl Worker { async fn run(mut self) { + let gate = self.client.gate(); let mut retries = 0; + // The gate's confirmation count at the last failure (remote only). + let mut failed_at = None; loop { - let message = match self.attach_once().await { + if let Some(gate) = &gate + && !self.wait_for_machine(gate, failed_at.take()).await + { + return; + } + let mut attached = false; + let message = match self.attach_once(&mut attached).await { End::Closed => return, End::StreamEnded => return self.sink.event(AttachEvent::Exited), End::AgentGone => return self.sink.event(AttachEvent::Gone), End::Failed(message) => message, }; - retries += 1; - let Some(delay) = self.backoff.delay(retries) else { - return self.sink.event(AttachEvent::Failed { message }); - }; - self.sink.event(AttachEvent::Retrying { - attempt: retries, - delay_ms: delay.as_millis() as u64, - message, + let machine_down = gate.as_ref().is_some_and(|gate| { + let state = gate.state(); + failed_at = Some(state.confirmed); + !state.open }); - if !self.wait(delay).await { - return; + let (count, next) = after_failure(&self.backoff, retries, attached, machine_down); + retries = count; + match next { + Next::WaitForMachine => { + self.sink.event(AttachEvent::Retrying { + attempt: retries, + delay_ms: 0, + message: format!("{message} (waiting for the machine to reconnect)"), + }); + } + Next::GiveUp => return self.sink.event(AttachEvent::Failed { message }), + Next::Retry { attempt, delay } => { + self.sink.event(AttachEvent::Retrying { + attempt, + delay_ms: delay.as_millis() as u64, + message, + }); + if !self.wait(delay).await { + return; + } + } + } + } + } + + /// Wait until the machine's gate allows an attempt (plus the resume jitter), still taking + /// commands. False once the session is closed. + async fn wait_for_machine(&mut self, gate: &MachineGate, after: Option) -> bool { + let resume = gate.resume(after); + tokio::pin!(resume); + loop { + tokio::select! { + _ = &mut resume => return true, + command = self.commands.recv() => match command { + None => return false, + Some(command) => self.apply(command, None).await, + }, } } } @@ -360,8 +438,9 @@ impl Worker { } } - /// `runAttachLoop`: one connection, from `attach` to its end. - async fn attach_once(&mut self) -> End { + /// `runAttachLoop`: one connection, from `attach` to its end. `attached` is set once the + /// daemon accepted the attach. + async fn attach_once(&mut self, attached: &mut bool) -> End { // Dropping the session aborts this task, so a connect needs no close check. let (mut reader, mut writer) = match self.client.connect().await { Ok(halves) => halves, @@ -424,6 +503,7 @@ impl Worker { return End::Failed("Unexpected response during attach".into()); }; ready = true; + *attached = true; replay_remaining = buffered_bytes; self.sink.event(AttachEvent::AttachReady { buffered_bytes }); if buffered_bytes == 0 { diff --git a/apps/purepoint-windows/src-tauri/src/attach/session_tests.rs b/apps/purepoint-windows/src-tauri/src/attach/session_tests.rs index be84245b..80dda60f 100644 --- a/apps/purepoint-windows/src-tauri/src/attach/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/attach/session_tests.rs @@ -745,3 +745,121 @@ async fn given_real_daemon_should_stream_a_shell_and_apply_resizes() { .unwrap(); } } + +// MARK: - MACH-015: never give up while the agent lives + +#[test] +fn given_failures_should_count_reset_after_an_attach_and_wait_while_the_machine_is_down() { + let backoff = fast_backoff(2); + let retry = |attempt, delay| Next::Retry { + attempt, + delay: Duration::from_millis(delay), + }; + assert_eq!(after_failure(&backoff, 0, false, false), (1, retry(1, 10))); + assert_eq!(after_failure(&backoff, 1, false, false), (2, retry(2, 10))); + assert_eq!(after_failure(&backoff, 2, false, false), (3, Next::GiveUp)); + // An attempt that attached starts the count again. + assert_eq!(after_failure(&backoff, 2, true, false), (1, retry(1, 10))); + // The machine is down: no retry is used up, however many came before. + assert_eq!( + after_failure(&backoff, 2, false, true), + (2, Next::WaitForMachine) + ); + assert_eq!( + after_failure(&backoff, 2, true, true), + (0, Next::WaitForMachine) + ); +} + +#[tokio::test] +async fn given_an_attach_between_failures_should_start_the_retry_count_again() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let mut options = AttachOptions::new("ag-1", 80, 24); + options.backoff = fast_backoff(2); + let _session = AttachSession::start(daemon.client(), options, sink); + + // Two failures use up both retries... + for attempt in 1..=2u32 { + let (conn, _) = daemon.accept_attach("ag-1").await; + drop(conn); + assert!(matches!( + next_event(&mut seen).await, + AttachEvent::Retrying { attempt: n, .. } if n == attempt + )); + } + // ...then an attach succeeds and fails mid-stream: retry 1 again, not the end. + let (mut conn, _) = daemon.accept_attach("ag-1").await; + conn.send(&Response::AttachReady { buffered_bytes: 0 }) + .await; + conn.send(&Response::Error { + code: "INTERNAL".into(), + message: "boom".into(), + }) + .await; + assert_eq!( + next_event(&mut seen).await, + AttachEvent::AttachReady { buffered_bytes: 0 } + ); + assert_eq!(next_event(&mut seen).await, AttachEvent::Live); + assert!(matches!( + next_event(&mut seen).await, + AttachEvent::Retrying { attempt: 1, .. } + )); + let _ = daemon.accept_attach("ag-1").await; +} + +#[tokio::test] +async fn given_machine_down_should_wait_without_retrying_then_reattach_with_a_reset() { + let mut daemon = FakeDaemon::start(); + let gate = crate::daemon::gate::MachineGate::new("m1"); + gate.set_open(true); + let (client, connects) = crate::daemon::client::tests::gated_client(&daemon.socket, &gate); + let (sink, mut seen) = sink(); + let mut options = AttachOptions::new("ag-1", 80, 24); + options.backoff = fast_backoff(1); + let _session = AttachSession::start(client, options, sink); + + let (mut conn, _) = daemon.accept_attach("ag-1").await; + conn.send(&Response::AttachReady { buffered_bytes: 2 }) + .await; + conn.send(&output(b"hi")).await; + assert_eq!( + next_event(&mut seen).await, + AttachEvent::AttachReady { buffered_bytes: 2 } + ); + assert_eq!(next(&mut seen).await, Seen::Output(b"hi".to_vec())); + assert_eq!(next_event(&mut seen).await, AttachEvent::Live); + + // The supervisor reports the machine down, then the stream fails. + gate.set_open(false); + conn.send(&Response::Error { + code: "INTERNAL".into(), + message: "link".into(), + }) + .await; + let AttachEvent::Retrying { + attempt, delay_ms, .. + } = next_event(&mut seen).await + else { + panic!("expected a wait"); + }; + assert_eq!((attempt, delay_ms), (0, 0)); + daemon + .assert_no_connection(Duration::from_millis(500)) + .await; + assert_eq!(connects.load(std::sync::atomic::Ordering::SeqCst), 1); + + // Back: one reattach, whose replay resets the terminal first. + gate.set_open(true); + let (mut conn, _) = daemon.accept_attach("ag-1").await; + conn.send(&Response::AttachReady { buffered_bytes: 2 }) + .await; + conn.send(&output(b"hi")).await; + assert_eq!( + next_event(&mut seen).await, + AttachEvent::AttachReady { buffered_bytes: 2 } + ); + assert_eq!(next_event(&mut seen).await, AttachEvent::Reset); + assert_eq!(next(&mut seen).await, Seen::Output(b"hi".to_vec())); +} diff --git a/apps/purepoint-windows/src-tauri/src/daemon/client.rs b/apps/purepoint-windows/src-tauri/src/daemon/client.rs index 3f6eca32..5e2d31aa 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/client.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/client.rs @@ -24,6 +24,8 @@ use pu_core::protocol::{Request, Response}; use serde::Serialize; use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use super::gate::MachineGate; + /// One-shot requests time out after 30 s (REQ-WINAPP-059). pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); @@ -61,6 +63,10 @@ pub trait Connector: Send + Sync { fn open(&self) -> OpenFuture<'_>; /// Where this connector reaches, for logs and errors. fn describe(&self) -> String; + /// The machine's connection gate, for a remote daemon (MACH-014); the local one has none. + fn gate(&self) -> Option { + None + } } /// Why a daemon call failed. @@ -331,6 +337,11 @@ impl DaemonClient { self.connector.describe() } + /// The machine's connection gate: retry loops on a remote daemon wait on it (MACH-014). + pub fn gate(&self) -> Option { + self.connector.gate() + } + /// Send one request and read its reply, under [`timeout_for`] the request. pub async fn request(&self, request: &Request) -> Result { self.request_with_timeout(request, timeout_for(request)) @@ -433,6 +444,50 @@ pub(crate) mod tests { DaemonClient::local(socket).unwrap() } + /// A local daemon behind a machine gate, as `SshRelayConnector` gates a machine's + /// (MACH-014): a closed gate refuses without connecting. `connects` counts attempts that + /// reached the endpoint. + pub(crate) struct GatedLocal { + inner: LocalConnector, + gate: MachineGate, + pub(crate) connects: Arc, + } + + impl Connector for GatedLocal { + fn open(&self) -> OpenFuture<'_> { + Box::pin(async move { + if !self.gate.is_open() { + return Err(self.gate.closed_error()); + } + self.connects + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.inner.open().await + }) + } + + fn describe(&self) -> String { + format!("gated {}", self.inner.describe()) + } + + fn gate(&self) -> Option { + Some(self.gate.clone()) + } + } + + /// A client for `socket` behind `gate`, and its connect counter. + pub(crate) fn gated_client( + socket: &Path, + gate: &MachineGate, + ) -> (DaemonClient, Arc) { + let connects = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let connector = GatedLocal { + inner: LocalConnector::new(socket).unwrap(), + gate: gate.clone(), + connects: connects.clone(), + }; + (DaemonClient::new(Arc::new(connector)), connects) + } + #[tokio::test] async fn given_healthy_daemon_should_parse_its_health_report() { let tmp = tempfile::TempDir::new().unwrap(); diff --git a/apps/purepoint-windows/src-tauri/src/daemon/gate.rs b/apps/purepoint-windows/src-tauri/src/daemon/gate.rs new file mode 100644 index 00000000..9c9b8284 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/daemon/gate.rs @@ -0,0 +1,352 @@ +//! Each machine's connection gate (MACH-014, MACH-015): work for a remote machine follows the +//! machine's connection state instead of retrying on its own. +//! +//! The front end's supervisor (`MachineConnection`, `ui/src/services/machines.ts`) is the only +//! thing that decides whether a machine is reachable. It reports every change with +//! `machine_set_reachable` (open while the machine is connected with its daemon running). While a +//! machine's gate is closed: +//! +//! - [`super::relay::SshRelayConnector::open`] refuses at once with +//! [`DaemonError::NotRunning`], starting no `ssh.exe`, so one-shot requests (`machine_request`, +//! file and git host calls) fail fast instead of logging in; +//! - the remote retry loops (status and grid subscriptions, attach sessions) wait in +//! [`MachineGate::resume`] and start again a uniformly random 0–1 s after it opens, so a +//! reconnect does not log in every stream at the same instant. +//! +//! A failure while the gate is still open (the link dropped, but the supervisor has not probed +//! yet) also waits: [`MachineGate::suspect`] asks the supervisor to probe now (the +//! `machine-suspect` event, at most once per [`SUSPECT_INTERVAL`] per machine), and the loop +//! resumes only once a probe newer than its failed attempt has reached the daemon +//! ([`GateState::confirmed`]). One probe then answers for every stream on the machine. +//! +//! The registry is process-wide ([`registry`]): every connector for a machine (the shared +//! [`super::machine::MachineClients`] one, and the git host's own) sees the same gate. A machine +//! the supervisor has not reported yet is closed. The local daemon has no gate. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use tokio::sync::watch; + +use super::client::DaemonError; + +/// The longest resume jitter: streams resume spread over this much time (MACH-014). +pub const RESUME_JITTER_MAX: Duration = Duration::from_secs(1); +/// How often a machine may ask its supervisor for an early probe. +pub const SUSPECT_INTERVAL: Duration = Duration::from_secs(5); + +/// A machine's reported reachability. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct GateState { + /// The supervisor reports the machine connected with its daemon running. + pub open: bool, + /// Bumped by every probe that reached the daemon (and by opening the gate): a loop that + /// failed at `confirmed == n` retries once `confirmed > n`. + pub confirmed: u64, +} + +impl GateState { + /// Whether a loop whose last attempt failed at `after` (or that has not failed: `None`) + /// may try again. + pub fn allows(self, after: Option) -> bool { + self.open && after.is_none_or(|ticket| self.confirmed > ticket) + } +} + +/// The resume jitter for a uniform sample `unit` in [0, 1]: 0–1 s. +pub fn resume_delay(unit: f64) -> Duration { + RESUME_JITTER_MAX.mul_f64(if unit.is_finite() { + unit.clamp(0.0, 1.0) + } else { + 0.0 + }) +} + +/// A uniform sample in [0, 1) from the OS random source (through a v4 UUID's random bits). +pub fn random_unit() -> f64 { + const BITS: u32 = 53; + let random = uuid::Uuid::new_v4().as_u128() as u64 & ((1 << BITS) - 1); + random as f64 / (1u64 << BITS) as f64 +} + +type SuspectHook = Arc; + +struct Inner { + machine_id: String, + state: watch::Sender, + last_suspect: Mutex>, + on_suspect: Option, +} + +/// One machine's gate. Cheap to clone; clones share the state. +#[derive(Clone)] +pub struct MachineGate { + inner: Arc, +} + +impl std::fmt::Debug for MachineGate { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MachineGate") + .field("machine_id", &self.inner.machine_id) + .field("state", &self.state()) + .finish() + } +} + +impl MachineGate { + /// A closed gate for `machine_id` with no supervisor hook (tests). + pub fn new(machine_id: &str) -> Self { + Self::with_hook(machine_id, None) + } + + fn with_hook(machine_id: &str, on_suspect: Option) -> Self { + Self { + inner: Arc::new(Inner { + machine_id: machine_id.to_ascii_lowercase(), + state: watch::Sender::new(GateState::default()), + last_suspect: Mutex::new(None), + on_suspect, + }), + } + } + + pub fn machine_id(&self) -> &str { + &self.inner.machine_id + } + + pub fn state(&self) -> GateState { + *self.inner.state.borrow() + } + + pub fn is_open(&self) -> bool { + self.state().open + } + + /// The supervisor's verdict. Opening counts as a confirmation: it follows a probe that + /// reached the daemon. + pub fn set_open(&self, open: bool) { + self.inner.state.send_modify(|state| { + if open && !state.open { + state.confirmed += 1; + } + state.open = open; + }); + } + + /// A probe reached the machine's daemon. + pub fn confirm(&self) { + self.inner.state.send_modify(|state| state.confirmed += 1); + } + + /// The error a closed gate gives a connection attempt. + pub fn closed_error(&self) -> DaemonError { + DaemonError::NotRunning(format!( + "Machine {} is not connected; waiting for it to reconnect", + self.inner.machine_id + )) + } + + /// Ask the supervisor for an early probe, at most once per [`SUSPECT_INTERVAL`]. + pub fn suspect(&self) { + let Some(hook) = &self.inner.on_suspect else { + return; + }; + let now = Instant::now(); + { + let mut last = self + .inner + .last_suspect + .lock() + .unwrap_or_else(|p| p.into_inner()); + if last.is_some_and(|at| now.duration_since(at) < SUSPECT_INTERVAL) { + return; + } + *last = Some(now); + } + hook(&self.inner.machine_id); + } + + /// Wait until the gate allows an attempt (see [`GateState::allows`]); true when it had to + /// wait. + pub async fn wait(&self, after: Option) -> bool { + if self.state().allows(after) { + return false; + } + let mut rx = self.inner.state.subscribe(); + // The sender lives as long as `self`, so this only ends when the gate allows it. + let _ = rx.wait_for(|state| state.allows(after)).await; + true + } + + /// Before an attempt: wait while the gate does not allow one, then (only if it had to + /// wait) sleep the resume jitter, so the machine's streams do not all log in at once. + /// `after` is the [`GateState::confirmed`] the previous attempt failed at, if it failed; + /// a failure first asks the supervisor to probe. + pub async fn resume(&self, after: Option) { + if after.is_some() && !self.state().allows(after) { + self.suspect(); + } + if self.wait(after).await { + tokio::time::sleep(resume_delay(random_unit())).await; + } + } +} + +/// Every machine's gate, by lowercased id. +#[derive(Default)] +pub struct MachineGates { + gates: Mutex>, + on_suspect: OnceLock, +} + +impl MachineGates { + /// The gate for `machine_id`, created closed. + pub fn gate(&self, machine_id: &str) -> MachineGate { + let key = machine_id.to_ascii_lowercase(); + let hook = self.on_suspect.get().cloned(); + self.gates + .lock() + .unwrap_or_else(|p| p.into_inner()) + .entry(key) + .or_insert_with(|| MachineGate::with_hook(machine_id, hook)) + .clone() + } + + /// Where [`MachineGate::suspect`] goes (the app emits `machine-suspect`). Set once, before + /// any gate exists; later calls are ignored. + pub fn set_suspect_hook(&self, hook: impl Fn(&str) + Send + Sync + 'static) { + let _ = self.on_suspect.set(Arc::new(hook)); + } +} + +/// The process-wide registry. +pub fn registry() -> &'static MachineGates { + static GATES: OnceLock = OnceLock::new(); + GATES.get_or_init(MachineGates::default) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn given_samples_should_jitter_between_zero_and_one_second() { + assert_eq!(resume_delay(0.0), Duration::ZERO); + assert_eq!(resume_delay(0.5), Duration::from_millis(500)); + assert_eq!(resume_delay(1.0), Duration::from_secs(1)); + assert_eq!(resume_delay(7.0), Duration::from_secs(1)); + assert_eq!(resume_delay(-1.0), Duration::ZERO); + assert_eq!(resume_delay(f64::NAN), Duration::ZERO); + for _ in 0..100 { + let unit = random_unit(); + assert!((0.0..1.0).contains(&unit), "{unit}"); + } + } + + #[test] + fn given_gate_state_should_allow_only_open_and_newer_confirmations() { + let closed = GateState { + open: false, + confirmed: 3, + }; + let open = GateState { + open: true, + confirmed: 3, + }; + assert!(!closed.allows(None)); + assert!(open.allows(None)); + assert!(open.allows(Some(2))); + assert!(!open.allows(Some(3))); + assert!(!closed.allows(Some(2))); + } + + #[test] + fn given_opening_should_count_as_a_confirmation() { + let gate = MachineGate::new("M1"); + assert_eq!(gate.machine_id(), "m1"); + assert_eq!(gate.state(), GateState::default()); + gate.set_open(true); + assert_eq!( + gate.state(), + GateState { + open: true, + confirmed: 1 + } + ); + // Already open: no new confirmation. + gate.set_open(true); + gate.confirm(); + assert_eq!(gate.state().confirmed, 2); + gate.set_open(false); + assert!(!gate.is_open()); + assert!(matches!(gate.closed_error(), DaemonError::NotRunning(_))); + } + + #[test] + fn given_registry_should_share_one_gate_per_machine_in_any_case() { + let gates = MachineGates::default(); + gates.gate("ABC").set_open(true); + assert!(gates.gate("abc").is_open()); + assert!(!gates.gate("other").is_open()); + } + + #[test] + fn given_repeated_suspicion_should_ask_the_supervisor_once_per_interval() { + let gates = MachineGates::default(); + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + gates.set_suspect_hook(move |id| { + assert_eq!(id, "m1"); + counted.fetch_add(1, Ordering::SeqCst); + }); + let gate = gates.gate("m1"); + gate.suspect(); + gate.suspect(); + gates.gate("M1").suspect(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test(start_paused = true)] + async fn given_closed_gate_should_resume_after_it_opens_with_at_most_one_second_of_jitter() { + let gate = MachineGate::new("m1"); + let waiter = { + let gate = gate.clone(); + tokio::spawn(async move { + gate.resume(None).await; + tokio::time::Instant::now() + }) + }; + tokio::time::sleep(Duration::from_secs(30)).await; + assert!(!waiter.is_finished()); + let opened = tokio::time::Instant::now(); + gate.set_open(true); + let resumed = waiter.await.unwrap(); + assert!(resumed - opened <= RESUME_JITTER_MAX); + } + + #[tokio::test(start_paused = true)] + async fn given_open_gate_should_not_delay_a_first_attempt() { + let gate = MachineGate::new("m1"); + gate.set_open(true); + let before = tokio::time::Instant::now(); + gate.resume(None).await; + assert_eq!(tokio::time::Instant::now(), before); + } + + #[tokio::test(start_paused = true)] + async fn given_a_failure_while_open_should_wait_for_a_newer_probe() { + let gate = MachineGate::new("m1"); + gate.set_open(true); + let ticket = gate.state().confirmed; + let waiter = { + let gate = gate.clone(); + tokio::spawn(async move { gate.resume(Some(ticket)).await }) + }; + tokio::time::sleep(Duration::from_secs(5)).await; + assert!(!waiter.is_finished()); + gate.confirm(); + waiter.await.unwrap(); + } +} diff --git a/apps/purepoint-windows/src-tauri/src/daemon/machine.rs b/apps/purepoint-windows/src-tauri/src/daemon/machine.rs index 2cbbb033..4d7456dd 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/machine.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/machine.rs @@ -14,10 +14,15 @@ //! probe, and every remote request, subscription and fs stream uses it. //! - Start daemon runs the machine's start command with a 60 s limit; nothing else ever starts //! a remote daemon (MACH-003). +//! - An offline verdict carries its [`SshFailureCause`] and that cause's summary (MACH-018), +//! classified from ssh's exit status and stderr, for the machine row and its connection log. +//! - The supervisor reports its verdict with `machine_set_reachable`, which opens or closes the +//! machine's gate ([`super::gate`], MACH-014); a probe that reaches the daemon confirms it. //! //! Tauri surface (front end: `ui/src/services/machines.ts`): `machines_load`, `machines_add`, //! `machines_remove`, `machines_ssh_config`, `machine_request`, `machine_probe`, -//! `machine_start_daemon` and `machine_test_connection`. +//! `machine_set_reachable`, `machine_start_daemon` and `machine_test_connection`, and the +//! `machine-suspect` event (a remote stream failed: probe now). use std::collections::HashMap; use std::process::Stdio; @@ -26,11 +31,13 @@ use std::time::Duration; use pu_core::machines::{self, Machine}; use pu_core::protocol::{PROTOCOL_VERSION, Request, Response}; +use pu_core::ssh_failure::SshFailureCause; use serde::Serialize; use tauri::State; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use super::client::{DaemonClient, DaemonError, parse, timeout_for}; +use super::gate; use super::relay::{self, RemoteShell, SSH_CONNECT_FAILED, SshRelayConnector}; /// `pu daemon proxy`'s exit status when nothing listens on the machine's socket. @@ -41,6 +48,9 @@ pub const PROBE_TIMEOUT: Duration = Duration::from_secs(20); const EXIT_TIMEOUT: Duration = Duration::from_secs(5); /// Start daemon's limit (`docs/product/windows-app.md`, Remote relay). pub const START_TIMEOUT: Duration = Duration::from_secs(60); +/// Raised with the machine's id when a remote stream failed while its gate was open: the +/// supervisor probes now instead of at its next interval (`gate::MachineGate::suspect`). +pub const MACHINE_SUSPECT_EVENT: &str = "machine-suspect"; /// One `health` probe through the relay (Swift `HealthProbe`, plus what the relay's exit /// status says on Windows). @@ -56,9 +66,12 @@ pub enum HealthProbe { /// ssh reached the machine and `pu daemon proxy` found no daemon (exit 69). Stopped, /// ssh could not reach the machine (exit 255, or no ssh at all), or `pu` is not installed - /// there (exit 127 or 9009). + /// there (exit 127 or 9009). `reason` is ssh's own message, `cause` its classification and + /// `summary` what that cause means for the user (MACH-018). Offline { reason: String, + cause: SshFailureCause, + summary: String, }, /// No answer, an error, or the deadline passed: one failure, not yet a verdict. Failed { @@ -89,20 +102,40 @@ pub fn classify(response: Result) -> HealthProbe { } } -/// What a relay that closed without a reply means, from its exit status (the CLI's -/// `relay_exit_error`). -pub fn classify_exit(machine: &str, code: Option, stderr: Option) -> HealthProbe { +/// An offline verdict with `cause` and its summary. +pub fn offline(reason: String, cause: SshFailureCause) -> HealthProbe { + HealthProbe::Offline { + reason, + cause, + summary: cause.summary().to_owned(), + } +} + +/// An offline verdict from an error message alone (a failed shell probe, no ssh): classified +/// by the message's text, else [`SshFailureCause::Other`]. +pub fn offline_from_message(reason: String) -> HealthProbe { + let cause = SshFailureCause::from_stderr(&reason).unwrap_or(SshFailureCause::Other); + offline(reason, cause) +} + +/// What a relay that closed without a reply means, from its exit status and everything it +/// wrote to stderr (the CLI's `relay_exit_error`); the cause is [`SshFailureCause::classify`]'s. +pub fn classify_exit(machine: &str, code: Option, stderr: &str) -> HealthProbe { + let last = relay::last_line(stderr.as_bytes()); match code { Some(EXIT_NO_DAEMON) => HealthProbe::Stopped, - Some(127 | 9009) => HealthProbe::Offline { - reason: format!( + Some(127 | 9009) => offline( + format!( "PurePoint is not installed on {machine} (`pu` was not found there). Install it there and connect again." ), - }, - Some(SSH_CONNECT_FAILED) => HealthProbe::Offline { - reason: stderr.unwrap_or_else(|| "ssh exited with status 255".into()), - }, + SshFailureCause::PuMissing, + ), + Some(SSH_CONNECT_FAILED) => offline( + last.unwrap_or_else(|| "ssh exited with status 255".into()), + SshFailureCause::classify(code, stderr), + ), _ => { + let stderr = last; let status = code.map_or("no exit status".to_string(), |c| format!("exit {c}")); HealthProbe::Failed { reason: match stderr { @@ -121,7 +154,7 @@ pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { let (mut child, target) = match connector.spawn(Stdio::piped()).await { Ok(spawned) => spawned, // No ssh, an unknown machine, or the `uname -s` probe could not reach the host. - Err(DaemonError::NotRunning(reason)) => return HealthProbe::Offline { reason }, + Err(DaemonError::NotRunning(reason)) => return offline_from_message(reason), Err(error) => { return HealthProbe::Failed { reason: error.to_string(), @@ -166,17 +199,28 @@ pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { .await .ok() .and_then(Result::ok) - .and_then(|bytes| relay::last_line(&bytes)); - classify_exit(&target.name, code, stderr) + .unwrap_or_default(); + classify_exit(&target.name, code, &String::from_utf8_lossy(&stderr)) } Err(_) => HealthProbe::Failed { reason: format!("No reply within {} s", PROBE_TIMEOUT.as_secs()), }, }; let _ = child.start_kill(); + if reached_daemon(&result) { + connector.machine_gate().confirm(); + } result } +/// Whether a probe got an answer from the daemon (so streams waiting on the gate may retry). +pub fn reached_daemon(probe: &HealthProbe) -> bool { + matches!( + probe, + HealthProbe::Running | HealthProbe::Incompatible { .. } | HealthProbe::Busy + ) +} + /// Run the machine's start command over ssh; the error ssh gave, or none. pub async fn start_daemon(connector: &SshRelayConnector) -> Result<(), String> { let target = relay::machine_target(connector.machine()).map_err(|e| e.to_string())?; @@ -394,6 +438,13 @@ pub async fn machine_probe( Ok(probe(&connector).await) } +/// The supervisor's verdict on a machine (MACH-014): `reachable` while it reports the machine +/// connected with its daemon running. Opens or closes the machine's gate. +#[tauri::command] +pub fn machine_set_reachable(machine_id: String, reachable: bool) { + gate::registry().gate(&machine_id).set_open(reachable); +} + /// Start the machine's daemon (an explicit user action); the error, or null. #[tauri::command] pub async fn machine_start_daemon( @@ -542,35 +593,83 @@ mod tests { #[test] fn given_relay_exit_status_should_tell_stopped_from_offline() { - assert_eq!( - classify_exit("studio", Some(69), None), - HealthProbe::Stopped - ); + assert_eq!(classify_exit("studio", Some(69), ""), HealthProbe::Stopped); for code in [127, 9009] { - let HealthProbe::Offline { reason } = classify_exit("studio", Some(code), None) else { + let HealthProbe::Offline { reason, cause, .. } = + classify_exit("studio", Some(code), "") + else { panic!("{code} is offline"); }; assert!( reason.contains("PurePoint is not installed on studio"), "{reason}" ); + assert_eq!(cause, SshFailureCause::PuMissing); } assert_eq!( - classify_exit("studio", Some(255), Some("ssh: connect refused".into())), - HealthProbe::Offline { - reason: "ssh: connect refused".into() - } + classify_exit( + "studio", + Some(255), + "ssh: connect to host studio port 22: Connection refused\n" + ), + offline( + "ssh: connect to host studio port 22: Connection refused".into(), + SshFailureCause::Network + ) ); assert!(matches!( - classify_exit("studio", Some(1), None), + classify_exit("studio", Some(1), ""), HealthProbe::Failed { .. } )); assert!(matches!( - classify_exit("studio", None, None), + classify_exit("studio", None, ""), HealthProbe::Failed { .. } )); } + #[test] + fn given_a_refused_login_should_classify_from_all_of_stderr() { + // MACH-018: the kex line comes first; the last line alone is what the row shows. + let stderr = "kex_exchange_identification: read: Connection reset by peer\r\nConnection reset by 10.0.0.5 port 22\r\n"; + let HealthProbe::Offline { + reason, + cause, + summary, + } = classify_exit("studio", Some(255), stderr) + else { + panic!("255 is offline"); + }; + assert_eq!(reason, "Connection reset by 10.0.0.5 port 22"); + assert_eq!(cause, SshFailureCause::ServerRefused); + assert_eq!(summary, SshFailureCause::ServerRefused.summary()); + } + + #[test] + fn given_an_offline_message_should_classify_its_text() { + let HealthProbe::Offline { cause, .. } = + offline_from_message("Timed out reaching studio".into()) + else { + panic!("offline"); + }; + assert_eq!(cause, SshFailureCause::Network); + let HealthProbe::Offline { cause, .. } = + offline_from_message("Could not find ssh.exe; install the OpenSSH client".into()) + else { + panic!("offline"); + }; + assert_eq!(cause, SshFailureCause::Other); + } + + #[test] + fn given_probe_verdicts_should_confirm_only_answers_from_the_daemon() { + assert!(reached_daemon(&HealthProbe::Running)); + assert!(reached_daemon(&HealthProbe::Busy)); + assert!(reached_daemon(&HealthProbe::Incompatible { version: 2 })); + assert!(!reached_daemon(&HealthProbe::Stopped)); + assert!(!reached_daemon(&offline_from_message("x".into()))); + assert!(!reached_daemon(&HealthProbe::Failed { reason: "x".into() })); + } + #[test] fn given_probes_should_serialize_tagged_camel_case() { assert_eq!( @@ -581,5 +680,14 @@ mod tests { serde_json::to_value(HealthProbe::Stopped).unwrap(), serde_json::json!({ "kind": "stopped" }) ); + assert_eq!( + serde_json::to_value(offline("x".into(), SshFailureCause::ServerRefused)).unwrap(), + serde_json::json!({ + "kind": "offline", + "reason": "x", + "cause": "server_refused", + "summary": SshFailureCause::ServerRefused.summary(), + }) + ); } } diff --git a/apps/purepoint-windows/src-tauri/src/daemon/mod.rs b/apps/purepoint-windows/src-tauri/src/daemon/mod.rs index 99b3ce95..033b50f3 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/mod.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/mod.rs @@ -5,12 +5,14 @@ //! - `relay`: a machine's daemon over `ssh.exe … pu daemon proxy`, for remote projects. //! - `machine`: the machine registry, each machine's daemon client, its health probe and //! Start daemon (WIN-8.14). +//! - `gate`: each machine's connection gate, which remote retry loops wait on (MACH-014). //! //! Tauri surface (front end: `ui/src/services/daemon.ts`): commands `daemon_request`, //! `daemon_health` and `daemon_status`, and the `daemon-state` event carrying a //! [`lifecycle::ConnectionState`] on every change. pub mod client; +pub mod gate; pub mod lifecycle; pub mod machine; pub mod relay; diff --git a/apps/purepoint-windows/src-tauri/src/daemon/relay.rs b/apps/purepoint-windows/src-tauri/src/daemon/relay.rs index f0c884b1..4a64d5ea 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/relay.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/relay.rs @@ -4,11 +4,16 @@ //! "Remote relay (Windows client)" in `docs/product/windows-app.md`. //! //! This is the transport [`super::client::DaemonClient`] uses for every remote request and -//! stream. The machine's health probe, Start daemon and the relay's exit-code reporting are +//! stream. A connection opens only while the machine's gate ([`super::gate`]) is open: while the +//! supervisor reports the machine down, nothing but its own probe logs in (MACH-014). Every ssh +//! command passes `ConnectTimeout=10` and `TCPKeepAlive=yes` (MACH-017), so an unreachable host +//! fails within 10 s and a dead path is noticed even when ssh's own keepalive is blocked. The machine's health probe, Start daemon and the relay's exit-code reporting are //! `daemon/machine.rs` (WIN-8.14); the argv builders here mirror `pu --machine` //! (`crates/pu-cli/src/machine_target.rs`). use std::ffi::OsString; +use std::future::Future; +use std::io; use std::path::PathBuf; use std::pin::Pin; use std::process::Stdio; @@ -20,6 +25,7 @@ use tokio::io::{AsyncRead, ReadBuf}; use tokio::process::{Child, ChildStdout, Command}; use super::client::{BoxRead, BoxWrite, Connector, DaemonError, OpenFuture}; +use super::gate::{self, MachineGate}; /// The shell the relay runs in, detected once by probing `uname -s`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -106,6 +112,10 @@ pub fn ssh_destination(host: &str) -> String { } } +/// MACH-017: a dial to an unreachable host fails within 10 s, and TCP keepalive notices a dead +/// path even when ssh's own (`ServerAlive*`) is blocked. +const CONNECT_OPTIONS: [&str; 4] = ["-o", "ConnectTimeout=10", "-o", "TCPKeepAlive=yes"]; + /// Keeps a user's ControlMaster config from routing a call through (or parking it on) a /// shared master: Win32-OpenSSH ignores it, but `PU_SSH` or `PATH` may name an ssh (Git for /// Windows, MSYS2) that honours it. @@ -115,35 +125,39 @@ fn strings(args: &[&str]) -> Vec { args.iter().map(OsString::from).collect() } -/// `-T -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -/// -o ControlMaster=no -o ControlPath=none `: the relay's options. +/// `-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 +/// -o ServerAliveCountMax=3 -o ControlMaster=no -o ControlPath=none `: the relay's +/// options. pub fn ssh_args(host: &str) -> Vec { - let mut args = strings(&[ - "-T", - "-o", - "BatchMode=yes", + let mut args = strings(&["-T", "-o", "BatchMode=yes"]); + args.extend(strings(&CONNECT_OPTIONS)); + args.extend(strings(&[ "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", - ]); + ])); args.extend(strings(&NO_CONTROL_MASTER)); args.push(ssh_destination(host).into()); args } -/// `-T -o BatchMode=yes -o ControlMaster=no -o ControlPath=none 'uname -s'`. +/// `-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no +/// -o ControlPath=none 'uname -s'`. pub fn os_probe_args(host: &str) -> Vec { let mut args = strings(&["-T", "-o", "BatchMode=yes"]); + args.extend(strings(&CONNECT_OPTIONS)); args.extend(strings(&NO_CONTROL_MASTER)); args.push(ssh_destination(host).into()); args.push(OS_PROBE_COMMAND.into()); args } -/// `-o BatchMode=yes -o ControlMaster=no -o ControlPath=none `. +/// `-o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no +/// -o ControlPath=none `. pub fn start_args(host: &str, shell: RemoteShell) -> Vec { let mut args = strings(&["-o", "BatchMode=yes"]); + args.extend(strings(&CONNECT_OPTIONS)); args.extend(strings(&NO_CONTROL_MASTER)); args.push(ssh_destination(host).into()); args.push(shell.start_command().into()); @@ -217,13 +231,23 @@ pub async fn probe_shell(ssh: &PathBuf, host: &str) -> Result>, + gate: MachineGate, } impl SshRelayConnector { + /// A connector behind the machine's gate in the process-wide registry. pub fn new(machine: impl Into) -> Self { + let machine = machine.into(); + let gate = gate::registry().gate(&machine); + Self::with_gate(machine, gate) + } + + /// A connector behind `gate` (tests). + pub fn with_gate(machine: impl Into, gate: MachineGate) -> Self { Self { machine: machine.into(), shell: Mutex::new(None), + gate, } } @@ -246,7 +270,13 @@ impl SshRelayConnector { *self.shell.lock().unwrap_or_else(|p| p.into_inner()) = None; } - /// Start one relay process: ssh with piped stdio and stderr captured as `stderr`. + /// The machine's connection gate. + pub fn machine_gate(&self) -> &MachineGate { + &self.gate + } + + /// Start one relay process: ssh with piped stdio and stderr captured as `stderr`. Not + /// gated: the supervisor's probe uses it to find out whether the machine is back. pub async fn spawn(&self, stderr: Stdio) -> Result<(Child, MachineTarget), DaemonError> { let target = machine_target(&self.machine)?; let ssh = find_ssh().ok_or_else(|| { @@ -271,13 +301,18 @@ impl SshRelayConnector { impl Connector for SshRelayConnector { fn open(&self) -> OpenFuture<'_> { Box::pin(async move { + // MACH-014: while the supervisor reports the machine down, only its probe logs in. + if !self.gate.is_open() { + return Err(self.gate.closed_error()); + } let (mut child, _) = self.spawn(Stdio::null()).await?; let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else { return Err(DaemonError::Io("ssh has no stdio".into())); }; let read = RelayRead { stdout, - _child: child, + child: Some(child), + exit: None, }; Ok((Box::new(read) as BoxRead, Box::new(stdin) as BoxWrite)) }) @@ -286,12 +321,36 @@ impl Connector for SshRelayConnector { fn describe(&self) -> String { format!("machine {}", self.machine) } + + fn gate(&self) -> Option { + Some(self.gate.clone()) + } +} + +/// How long a relay whose stdout closed gets to report its exit status. +const RELAY_EXIT_WAIT: Duration = Duration::from_secs(2); + +/// What the end of a relay's stdout means, from ssh's exit status. The daemon closing the +/// stream ends `pu daemon proxy` cleanly, so it reads as end of file (an attach's agent exited); +/// ssh itself failing (exit 255: the link dropped) is an error, so the stream is retried rather +/// than taken for the daemon's own close (MACH-015). +pub fn relay_eof_error(code: Option) -> Option { + (code == Some(SSH_CONNECT_FAILED)).then(|| { + io::Error::new( + io::ErrorKind::ConnectionAborted, + "the SSH connection to the machine dropped", + ) + }) } -/// The relay's stdout. Owns the `ssh.exe` process, which ends when the connection drops. +type ExitFuture = Pin> + Send>>; + +/// The relay's stdout. Owns the `ssh.exe` process, which ends when the connection drops; at +/// end of file it waits (briefly) for ssh's exit status ([`relay_eof_error`]). struct RelayRead { stdout: ChildStdout, - _child: Child, + child: Option, + exit: Option, } impl AsyncRead for RelayRead { @@ -299,8 +358,28 @@ impl AsyncRead for RelayRead { mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, - ) -> Poll> { - Pin::new(&mut self.stdout).poll_read(cx, buf) + ) -> Poll> { + loop { + if let Some(exit) = self.exit.as_mut() { + let code = std::task::ready!(exit.as_mut().poll(cx)); + self.exit = None; + return Poll::Ready(relay_eof_error(code).map_or(Ok(()), Err)); + } + let before = buf.filled().len(); + std::task::ready!(Pin::new(&mut self.stdout).poll_read(cx, buf))?; + if buf.filled().len() > before || buf.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let Some(mut child) = self.child.take() else { + return Poll::Ready(Ok(())); + }; + self.exit = Some(Box::pin(async move { + match tokio::time::timeout(RELAY_EXIT_WAIT, child.wait()).await { + Ok(Ok(status)) => status.code(), + _ => None, + } + })); + } } } @@ -327,6 +406,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", @@ -378,6 +461,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ControlMaster=no", "-o", "ControlPath=none", @@ -398,6 +485,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ControlMaster=no", "-o", "ControlPath=none", @@ -423,6 +514,41 @@ mod tests { ); } + #[test] + fn given_every_ssh_command_should_bound_the_dial_and_keep_tcp_alive() { + // MACH-017 + for args in [ + text(ssh_args("studio")), + text(os_probe_args("studio")), + text(start_args("studio", RemoteShell::Unix)), + text(start_args("studio", RemoteShell::Windows)), + ] { + let joined = args.join(" "); + assert!(joined.contains("-o ConnectTimeout=10"), "{joined}"); + assert!(joined.contains("-o TCPKeepAlive=yes"), "{joined}"); + } + } + + #[test] + fn given_relay_end_should_tell_a_dropped_link_from_a_closed_stream() { + let dropped = relay_eof_error(Some(255)).unwrap(); + assert_eq!(dropped.kind(), io::ErrorKind::ConnectionAborted); + assert!(relay_eof_error(Some(0)).is_none()); + assert!(relay_eof_error(Some(1)).is_none()); + assert!(relay_eof_error(None).is_none()); + } + + #[tokio::test] + async fn given_closed_gate_should_refuse_to_open_without_running_ssh() { + let gate = MachineGate::new("m1"); + let connector = SshRelayConnector::with_gate("m1", gate.clone()); + assert!(connector.gate().is_some()); + let Err(error) = connector.open().await else { + panic!("a closed gate opens nothing"); + }; + assert_eq!(error, gate.closed_error()); + } + #[test] fn given_ssh_stderr_should_keep_its_last_line() { assert_eq!( diff --git a/apps/purepoint-windows/src-tauri/src/lib.rs b/apps/purepoint-windows/src-tauri/src/lib.rs index b1eda629..9d299939 100644 --- a/apps/purepoint-windows/src-tauri/src/lib.rs +++ b/apps/purepoint-windows/src-tauri/src/lib.rs @@ -138,6 +138,7 @@ pub fn run() { daemon::machine::machines_ssh_config, daemon::machine::machine_request, daemon::machine::machine_probe, + daemon::machine::machine_set_reachable, daemon::machine::machine_start_daemon, daemon::machine::machine_test_connection, installer::installer_status, @@ -205,6 +206,12 @@ pub fn run() { use tauri::Manager; create_main_window(app)?; { + // A remote stream that failed asks the machine's supervisor to probe now. + let handle = app.handle().clone(); + daemon::gate::registry().set_suspect_hook(move |machine_id| { + use tauri::Emitter; + let _ = handle.emit(daemon::machine::MACHINE_SUSPECT_EVENT, machine_id); + }); let daemon = daemon::DaemonState::for_app(app.handle()); daemon.start(); app.manage(daemon); diff --git a/apps/purepoint-windows/src-tauri/src/subscriptions/grid.rs b/apps/purepoint-windows/src-tauri/src/subscriptions/grid.rs index a45a26c0..7e095ace 100644 --- a/apps/purepoint-windows/src-tauri/src/subscriptions/grid.rs +++ b/apps/purepoint-windows/src-tauri/src/subscriptions/grid.rs @@ -5,12 +5,18 @@ //! written on the subscription's own connection; the daemon answers them on it (ignored) //! and rebroadcasts mutations as `grid_event` to every subscriber, this one included. //! Applying a command to the pane tree is the front end's (`WorkspaceRegistry`, WIN-6.4). +//! +//! On a machine's daemon the loop follows the machine's gate (MACH-014): it waits while the +//! machine is down, failures then do not count, and a stream that subscribed starts its retry +//! count again, so a long-running app is not worn down by outages. use std::sync::Arc; use pu_core::protocol::{GridCommand, Request, Response}; -use super::{Emit, Retries, RetryPolicy, SubscriptionEvent, SubscriptionKind, SubscriptionState}; +use super::{ + Emit, Gated, Retries, RetryPolicy, SubscriptionEvent, SubscriptionKind, SubscriptionState, +}; use super::{emit_state, next_reply}; use crate::daemon::client::{BoxWrite, DaemonClient, DaemonError, write_request}; @@ -44,9 +50,18 @@ pub async fn run( ) { let report = |state| emit_state(&emit, SubscriptionKind::Grid, Some(&project_root), state); let mut retries = Retries::new(policy); + let mut gated = Gated::new(&client); loop { - let error = stream(&client, &project_root, &emit, &writer).await; + gated.before_attempt().await; + let mut subscribed = false; + let error = stream(&client, &project_root, &emit, &writer, &mut subscribed).await; *writer.0.lock().await = None; + if !gated.failure_counts() { + continue; + } + if subscribed && gated.is_remote() { + retries = Retries::new(policy); + } if !retries.fail() { return report(SubscriptionState::Failed { message: error.to_string(), @@ -63,6 +78,7 @@ async fn stream( project_root: &str, emit: &Emit, writer: &GridWriter, + subscribed: &mut bool, ) -> DaemonError { let (mut reader, write) = match client.connect().await { Ok(connection) => connection, @@ -86,6 +102,7 @@ async fn stream( Ok(Err(error)) | Err(error) => return error, Ok(Ok(_)) => return DaemonError::Io("Unexpected response during grid subscribe".into()), } + *subscribed = true; emit_state( emit, SubscriptionKind::Grid, diff --git a/apps/purepoint-windows/src-tauri/src/subscriptions/mod.rs b/apps/purepoint-windows/src-tauri/src/subscriptions/mod.rs index 3a37e352..013f8210 100644 --- a/apps/purepoint-windows/src-tauri/src/subscriptions/mod.rs +++ b/apps/purepoint-windows/src-tauri/src/subscriptions/mod.rs @@ -16,7 +16,11 @@ //! //! A remote project's status and grid streams (WIN-8.14) run on its machine's daemon, through //! the ssh relay; their events carry the machine's id (`machineId`) beside the project root, -//! and the running streams are keyed by both. +//! and the running streams are keyed by both. They follow the machine's connection gate +//! (MACH-014, `crate::daemon::gate`): no attempt while the machine is down, a uniformly random +//! 0–1 s after it is back, and a failure while it is down does not count against the stream's +//! retries. A failure while it still looks up waits for the supervisor's next probe. A remote +//! grid stream that subscribed starts its retry count again. Local streams are unchanged. //! //! Tauri surface (front end: `ui/src/services/subscriptions.ts`): commands //! `subscriptions_start_project`, `subscriptions_stop_project`, @@ -43,6 +47,7 @@ use tokio::task::JoinHandle; use crate::daemon::DaemonState; use crate::daemon::client::{DaemonClient, DaemonError, LineReader, parse}; +use crate::daemon::gate::MachineGate; use crate::daemon::machine::MachineClients; pub const STATUS_EVENT: &str = "status-event"; @@ -297,6 +302,44 @@ impl Retries { } } +/// A remote stream's connection gate (MACH-014); a local stream has none and is unaffected. +struct Gated { + gate: Option, + /// The gate's confirmation count when the last attempt failed. + failed_at: Option, +} + +impl Gated { + fn new(client: &DaemonClient) -> Self { + Self { + gate: client.gate(), + failed_at: None, + } + } + + fn is_remote(&self) -> bool { + self.gate.is_some() + } + + /// Wait until the machine allows an attempt, plus the resume jitter if it had to wait. + async fn before_attempt(&mut self) { + if let Some(gate) = &self.gate { + gate.resume(self.failed_at.take()).await; + } + } + + /// Record a failed attempt; whether it counts against the stream's retries: not while + /// the machine is down, since then the machine failed, not the stream. + fn failure_counts(&mut self) -> bool { + let Some(gate) = &self.gate else { + return true; + }; + let state = gate.state(); + self.failed_at = Some(state.confirmed); + state.open + } +} + struct ProjectSubscriptions { status: JoinHandle<()>, grid: JoinHandle<()>, diff --git a/apps/purepoint-windows/src-tauri/src/subscriptions/status.rs b/apps/purepoint-windows/src-tauri/src/subscriptions/status.rs index 73a41c9a..d8c8bd0f 100644 --- a/apps/purepoint-windows/src-tauri/src/subscriptions/status.rs +++ b/apps/purepoint-windows/src-tauri/src/subscriptions/status.rs @@ -7,12 +7,16 @@ //! (alive, at its connection limit) is retried. An `error` reply to the subscribe, or any //! other reply, ends the loop as `failed`. //! +//! On a machine's daemon the loop follows the machine's gate (MACH-014): it waits while the +//! machine is down, and failures then count toward neither `daemon_lost` nor the retry limit. +//! //! Agent models are built from the raw payload by the front end (`DaemonWorkspaceService`). use pu_core::protocol::{Request, Response}; use super::{ - Emit, Failure, Retries, RetryPolicy, SubscriptionEvent, SubscriptionKind, SubscriptionState, + Emit, Failure, Gated, Retries, RetryPolicy, SubscriptionEvent, SubscriptionKind, + SubscriptionState, }; use super::{emit_state, next_reply}; use crate::daemon::client::{DaemonClient, DaemonError, write_request}; @@ -22,11 +26,20 @@ pub async fn run(client: DaemonClient, project_root: String, policy: RetryPolicy let report = |state| emit_state(&emit, SubscriptionKind::Status, Some(&project_root), state); let mut subscribed = false; let mut retries = Retries::new(policy); + let mut gated = Gated::new(&client); loop { + gated.before_attempt().await; let error = match stream(&client, &project_root, &emit, &mut subscribed).await { Failure::Fatal(message) => return report(SubscriptionState::Failed { message }), Failure::Retry(error) => error, }; + if !gated.failure_counts() { + // The machine is down: wait for it. An established stream is still lost. + if subscribed { + return report(SubscriptionState::DaemonLost); + } + continue; + } if !retries.fail() { return report(SubscriptionState::Failed { message: error.to_string(), diff --git a/apps/purepoint-windows/src-tauri/src/subscriptions/tests.rs b/apps/purepoint-windows/src-tauri/src/subscriptions/tests.rs index 8585f19f..e7be40ab 100644 --- a/apps/purepoint-windows/src-tauri/src/subscriptions/tests.rs +++ b/apps/purepoint-windows/src-tauri/src/subscriptions/tests.rs @@ -845,3 +845,86 @@ async fn given_a_reload_should_stop_every_subscription() { assert!(subscriptions.start_projects(&client, async {})); assert_eq!(subscriptions.stop_all(), 0); } + +// MARK: - Machine gates (MACH-014) + +mod gated { + use super::*; + use crate::daemon::client::tests::gated_client; + use crate::daemon::gate::MachineGate; + use std::sync::atomic::Ordering; + + #[tokio::test] + async fn given_machine_down_status_should_wait_without_connecting_then_subscribe() { + let tmp = tempfile::TempDir::new().unwrap(); + let socket = tmp.path().join("d.sock"); + let (server, _requests) = fake_daemon(&socket, vec![hold(&[STATUS_SUBSCRIBED])]); + let gate = MachineGate::new("m1"); + let (client, connects) = gated_client(&socket, &gate); + let (emit, mut events) = collector(); + let task = tokio::spawn(status::run( + client, + "/srv/app".into(), + fast(RetryPolicy::STATUS), + emit, + )); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(connects.load(Ordering::SeqCst), 0, "no attempt while down"); + assert!(events.try_recv().is_err(), "no retries while down"); + + gate.set_open(true); + assert_eq!(next_state(&mut events).await, SubscriptionState::Subscribed); + assert_eq!(connects.load(Ordering::SeqCst), 1); + task.abort(); + server.abort(); + } + + #[tokio::test] + async fn given_a_failure_while_up_grid_should_wait_for_the_next_probe() { + let tmp = tempfile::TempDir::new().unwrap(); + let gate = MachineGate::new("m1"); + gate.set_open(true); + let (client, connects) = gated_client(&tmp.path().join("none.sock"), &gate); + let (emit, mut events) = collector(); + let task = tokio::spawn(grid::run( + client, + "/srv/app".into(), + fast(RetryPolicy::GRID), + emit, + grid::GridWriter::default(), + )); + assert_eq!(retrying(&next_state(&mut events).await), Some(1)); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(connects.load(Ordering::SeqCst), 1, "waits for a probe"); + + // A probe reached the daemon: one more attempt, then it waits again. + gate.confirm(); + assert_eq!(retrying(&next_state(&mut events).await), Some(2)); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(connects.load(Ordering::SeqCst), 2); + + // The machine went down: nothing until it is back. + gate.set_open(false); + gate.confirm(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(connects.load(Ordering::SeqCst), 2); + task.abort(); + } + + #[test] + fn given_a_failure_while_down_should_not_count() { + let gate = MachineGate::new("m1"); + let tmp = tempfile::TempDir::new().unwrap(); + let (client, _) = gated_client(&tmp.path().join("none.sock"), &gate); + let mut gated = Gated::new(&client); + assert!(gated.is_remote()); + assert!(!gated.failure_counts()); + gate.set_open(true); + assert!(gated.failure_counts()); + assert_eq!(gated.failed_at, Some(1)); + + let mut local = Gated::new(&DaemonClient::local(&tmp.path().join("x.sock")).unwrap()); + assert!(!local.is_remote()); + assert!(local.failure_counts()); + } +} From 3f4149c2ec8155cdae55f9e6ae688ee4b93c9646 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:55:29 +0000 Subject: [PATCH 05/21] =?UTF-8?q?feat(cli):=20pu=20doctor=20--machine,=20s?= =?UTF-8?q?sh=20connect=20options=20and=20classified=20errors=20(MACH-017?= =?UTF-8?q?=20=E2=80=93=20MACH-019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every ssh command the CLI runs now passes ConnectTimeout=10 and TCPKeepAlive=yes. Failed ssh commands in --machine paths and `pu machine start` name their SshFailureCause after ssh's message. `pu doctor --machine ` reads the client's effective ssh options, times a BatchMode login, and runs one POSIX sh script on the machine that reports sshd -T settings, fail2ban, sshguard, ufw limit rules, sleep settings, and whether pu, `daemon proxy --mux` and the daemon are there. A pure evaluate() turns the report into ok / warn-with-fix / skipped findings; checks that need root and could not run are skipped, never passed. It changes nothing and exits non-zero only when the login fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- crates/pu-cli/src/commands/doctor.rs | 1304 +++++++++++++++++++++++ crates/pu-cli/src/commands/machine.rs | 50 +- crates/pu-cli/src/commands/mod.rs | 1 + crates/pu-cli/src/machine_target.rs | 162 ++- crates/pu-cli/src/main.rs | 26 + crates/pu-cli/tests/machines.rs | 239 ++++- crates/pu-cli/tests/machines_windows.rs | 48 +- 7 files changed, 1765 insertions(+), 65 deletions(-) create mode 100644 crates/pu-cli/src/commands/doctor.rs diff --git a/crates/pu-cli/src/commands/doctor.rs b/crates/pu-cli/src/commands/doctor.rs new file mode 100644 index 00000000..6345031b --- /dev/null +++ b/crates/pu-cli/src/commands/doctor.rs @@ -0,0 +1,1304 @@ +//! `pu doctor --machine ` (MACH-019): check a machine for the settings +//! that make connections drop, and name the exact fix for each. It changes +//! nothing on either machine. +//! +//! Three ssh commands run: `ssh -G` (this computer's effective options; it +//! never connects), a `BatchMode=yes … true` login that is timed, and one +//! login that runs [`REMOTE_SCRIPT`] under `/bin/sh` on the machine. The +//! script prints `key=value` lines; [`evaluate`] turns them into findings and +//! is pure, so the rules are tested against fixture output. + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::io::IsTerminal; +use std::path::Path; +use std::time::{Duration, Instant}; + +use owo_colors::OwoColorize; +use pu_core::machines::{self, Machine}; +use pu_core::ssh_failure::SshFailureCause; +use serde::Serialize; +use serde_json::json; + +use crate::error::CliError; +use crate::machine_target::{self, core_error}; + +/// A login slower than this is reported: every reconnect pays it. +pub const SLOW_LOGIN: Duration = Duration::from_secs(3); +const LOGIN_TIMEOUT: Duration = Duration::from_secs(30); +const SCRIPT_TIMEOUT: Duration = Duration::from_secs(60); +/// ssh's own failure status, as opposed to the remote command's. +const SSH_FAILED: i32 = 255; + +/// The remote command: the script arrives on stdin, so no quoting has to +/// survive the login shell (fish, csh, cmd.exe and PowerShell alike). On a +/// Windows machine it fails without output, which [`classify_remote`] reads +/// as "Windows". +pub const REMOTE_COMMAND: &str = "/bin/sh -s"; + +/// Prints one `key=value` per fact. Everything runs inside a function whose +/// stdin is `/dev/null`, so `sh` has read the whole script before any command +/// runs and no command can swallow the rest of it. `sudo -n` never prompts. +/// The `PATH` prefix is the start command's (machines.md), so `pu` resolves +/// the same way; `/usr/sbin` and `/sbin` are appended for `sshd` and `ufw`. +/// `pu daemon status` with an explicit `--socket` only asks the daemon: +/// unlike `pu health` it never starts one. +pub const REMOTE_SCRIPT: &str = r#"pu_doctor() { +PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH:/usr/sbin:/sbin" +export PATH +echo "doctor=1" +os=$(uname -s 2>/dev/null) +echo "os=$os" +case "$os" in + ''|MINGW*|MSYS*|CYGWIN*) return 0 ;; +esac +echo "client_addr=${SSH_CLIENT%% *}" +if out=$(sshd -T 2>/dev/null) && [ -n "$out" ]; then + echo "sshd_t=plain" +elif out=$(sudo -n sshd -T 2>/dev/null) && [ -n "$out" ]; then + echo "sshd_t=sudo" +else + out="" + echo "sshd_t=unavailable" +fi +printf '%s\n' "$out" | while read -r key value; do + case "$key" in + port|maxstartups|maxsessions|clientaliveinterval|clientalivecountmax|tcpkeepalive) + echo "sshd.$key=$value" ;; + esac +done +service_state() { + if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet "$1" 2>/dev/null; then + echo active + elif command -v pgrep >/dev/null 2>&1; then + if pgrep "$2" "$3" >/dev/null 2>&1; then echo active; else echo inactive; fi + elif command -v systemctl >/dev/null 2>&1; then + echo inactive + else + echo unknown + fi +} +echo "fail2ban=$(service_state fail2ban -f fail2ban-server)" +echo "sshguard=$(service_state sshguard -x sshguard)" +if [ "$os" = Linux ]; then + if ! command -v ufw >/dev/null 2>&1; then + echo "ufw=absent" + elif ufw_status=$(sudo -n ufw status 2>/dev/null); then + case "$ufw_status" in + *"Status: active"*) echo "ufw=active" ;; + *) echo "ufw=inactive" ;; + esac + printf '%s\n' "$ufw_status" | while read -r to rest; do + case " $rest " in + *" LIMIT "*) echo "ufw.limit=$to" ;; + esac + done + else + echo "ufw=needs_sudo" + fi +fi +case "$os" in + Darwin) + echo "sleep.pmset=$(pmset -g 2>/dev/null | awk '$1 == "sleep" { print $2; exit }')" ;; + Linux) + if command -v systemctl >/dev/null 2>&1; then + for target in sleep.target suspend.target hibernate.target hybrid-sleep.target; do + echo "sleep.target=$target $(systemctl is-enabled "$target" 2>/dev/null)" + done + fi ;; +esac +if pu_path=$(command -v pu 2>/dev/null); then + echo "pu=$pu_path" + if pu daemon proxy --help 2>&1 | grep -q -e '--mux'; then + echo "pu.mux=yes" + else + echo "pu.mux=no" + fi + case "$(pu --socket "$HOME/.pu/daemon.sock" daemon status 2>/dev/null)" in + "daemon running"*) echo "daemon=running" ;; + "daemon answered"*) echo "daemon=busy" ;; + "daemon not running"*) echo "daemon=stopped" ;; + *) echo "daemon=unknown" ;; + esac +else + echo "pu=missing" +fi +echo "done=1" +} +pu_doctor , +} + +impl RemoteFacts { + pub fn parse(stdout: &str) -> Self { + let entries = stdout + .lines() + .filter_map(|line| line.trim_end_matches('\r').split_once('=')) + .map(|(key, value)| (key.trim().to_string(), value.trim().to_string())) + .collect(); + RemoteFacts { entries } + } + + fn get(&self, key: &str) -> Option<&str> { + self.entries + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) + } + + fn all<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + self.entries + .iter() + .filter(move |(k, _)| k == key) + .map(|(_, v)| v.as_str()) + } +} + +/// How the timed `true` login went. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Login { + Ok { + elapsed: Duration, + }, + Failed { + cause: SshFailureCause, + message: String, + }, +} + +/// What the remote script reported. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Remote { + /// Not attempted: the login already failed. + NotRun, + /// ssh failed while running the script. + Failed { + cause: SshFailureCause, + message: String, + }, + /// No `/bin/sh` or no `uname`: sshd runs commands under cmd.exe or PowerShell. + Windows, + Unix(RemoteFacts), +} + +/// Everything `pu doctor` learned; [`evaluate`] judges it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + pub machine: String, + pub ssh_host: String, + /// `ssh -G` output by lowercase key, or why it could not run. + pub ssh_options: Result, String>, + pub login: Login, + pub remote: Remote, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Status { + Ok, + Warn, + /// The check could not run; never counted as passing. + Skipped, + /// The machine could not be reached, or the checks could not run on it. + Fail, +} + +impl Status { + fn label(self) -> &'static str { + match self { + Status::Ok => "ok", + Status::Warn => "warn", + Status::Skipped => "skip", + Status::Fail => "fail", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Finding { + pub check: String, + pub status: Status, + pub detail: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub fix: Option, +} + +impl Finding { + fn new(check: &str, status: Status, detail: impl Into) -> Self { + Finding { + check: check.to_string(), + status, + detail: detail.into(), + fix: None, + } + } + + fn ok(check: &str, detail: impl Into) -> Self { + Self::new(check, Status::Ok, detail) + } + + fn skipped(check: &str, reason: impl Into) -> Self { + Self::new(check, Status::Skipped, reason) + } + + fn warn(check: &str, detail: impl Into, fix: impl Into) -> Self { + Finding { + fix: Some(fix.into()), + ..Self::new(check, Status::Warn, detail) + } + } +} + +/// `ssh -G` prints `key value` lines with lowercase keys. +pub fn parse_ssh_options(stdout: &str) -> BTreeMap { + stdout + .lines() + .filter_map(|line| { + let line = line.trim(); + let (key, value) = line.split_once(char::is_whitespace)?; + Some((key.to_ascii_lowercase(), value.trim().to_string())) + }) + .collect() +} + +/// The remote script's outcome, from ssh's exit status and output. +pub fn classify_remote(code: Option, stdout: &str, stderr: &str) -> Remote { + let facts = RemoteFacts::parse(stdout); + if facts.get("doctor").is_some() { + let os = facts.get("os").unwrap_or(""); + return match machine_target::remote_os_from_probe(true, os) { + machine_target::RemoteOs::Unix => Remote::Unix(facts), + machine_target::RemoteOs::Windows => Remote::Windows, + }; + } + match code { + Some(SSH_FAILED) | None => Remote::Failed { + cause: SshFailureCause::classify(code, stderr), + message: one_line(stderr, code), + }, + // The login worked but `/bin/sh` did not run: cmd.exe or PowerShell. + Some(_) => Remote::Windows, + } +} + +fn one_line(stderr: &str, code: Option) -> String { + let message = stderr + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect::>() + .join("; "); + if !message.is_empty() { + return message; + } + code.map_or("ssh did not finish".to_string(), |c| { + format!("ssh exited with status {c}") + }) +} + +/// What to do about a login that failed for `cause`. +fn login_fix(cause: SshFailureCause, ssh_host: &str) -> String { + match cause { + SshFailureCause::ServerRefused => "Wait a minute and run this again: a fail2ban or sshguard ban, a `ufw limit` rule or sshd `MaxStartups` refused the login. If it keeps happening, check those on the machine from its console (docs/guide/reliable-machine-connections.md).".to_string(), + SshFailureCause::Network => format!( + "Check that the machine is on and awake, and that `{ssh_host}` resolves to an address this computer can reach. A Tailscale or WireGuard address stays the same on every network." + ), + SshFailureCause::Auth => format!( + "Make sure `ssh {ssh_host} true` logs in without a prompt: load your key with `ssh-add`, or add its public key to ~/.ssh/authorized_keys on the machine." + ), + SshFailureCause::HostKey => format!( + "Run `ssh {ssh_host}` once and confirm the host key. If the machine was reinstalled, remove the old key with `ssh-keygen -R ` first." + ), + _ => format!("Run `ssh -v {ssh_host} true` to see where the login stops."), + } +} + +/// How to make sshd pick up a config change on `os`. +fn sshd_reload(os: &str) -> &'static str { + if os == "Darwin" { + "macOS starts sshd for each connection, so new connections use it at once" + } else { + "then reload sshd: `sudo systemctl reload ssh` on Debian and Ubuntu, `sudo systemctl reload sshd` elsewhere" + } +} + +fn os_name(os: &str) -> &str { + match os { + "Darwin" => "macOS", + other => other, + } +} + +/// Judge a report. Every check that could not run is reported as skipped. +pub fn evaluate(report: &Report) -> Vec { + let mut findings = vec![client_options(report), login(report)]; + match &report.remote { + Remote::NotRun => findings.push(Finding::skipped( + "machine checks", + "not run: the login failed", + )), + Remote::Failed { cause, message } => findings.push(Finding { + fix: Some(login_fix(*cause, &report.ssh_host)), + ..Finding::new( + "machine checks", + Status::Fail, + format!("ssh failed while running them: {message} — {}", cause.summary()), + ) + }), + Remote::Windows => findings.push(Finding::skipped( + "machine checks", + format!( + "the machine runs Windows (no /bin/sh or uname): the sshd, firewall, sleep and pu checks need macOS or Linux. Check its daemon with `pu machine status {}`", + report.machine + ), + )), + Remote::Unix(facts) => findings.extend(machine_findings(&report.machine, facts)), + } + findings +} + +fn client_options(report: &Report) -> Finding { + const CHECK: &str = "ssh client"; + let options = match &report.ssh_options { + Ok(options) => options, + Err(reason) => return Finding::skipped(CHECK, format!("`ssh -G` failed: {reason}")), + }; + let shown: Vec = [ + ("serveraliveinterval", "ServerAliveInterval"), + ("serveralivecountmax", "ServerAliveCountMax"), + ("connecttimeout", "ConnectTimeout"), + ("tcpkeepalive", "TCPKeepAlive"), + ("controlmaster", "ControlMaster"), + ("controlpersist", "ControlPersist"), + ] + .iter() + .filter_map(|(key, name)| options.get(*key).map(|value| format!("{name} {value}"))) + .collect(); + let target = match (options.get("user"), options.get("hostname")) { + (Some(user), Some(host)) => { + let port = options.get("port").map_or("22", String::as_str); + format!("connects to {host} port {port} as {user}; ") + } + _ => String::new(), + }; + Finding::ok( + CHECK, + format!( + "{target}your config: {}. PurePoint passes its own ConnectTimeout, TCPKeepAlive, ServerAlive and ControlMaster options, so these only affect your other ssh sessions", + if shown.is_empty() { + "no keepalive or multiplexing options".to_string() + } else { + shown.join(", ") + } + ), + ) +} + +fn login(report: &Report) -> Finding { + const CHECK: &str = "login"; + match &report.login { + Login::Ok { elapsed } if *elapsed > SLOW_LOGIN => Finding::warn( + CHECK, + format!( + "logging in took {:.1} s; every reconnect pays this", + elapsed.as_secs_f64() + ), + "Slow logins usually come from reverse DNS or GSSAPI: set `UseDNS no` in /etc/ssh/sshd_config on the machine, and `GSSAPIAuthentication no` for this host in ~/.ssh/config.", + ), + Login::Ok { elapsed } => Finding::ok( + CHECK, + format!("logged in in {:.1} s", elapsed.as_secs_f64()), + ), + Login::Failed { cause, message } => Finding { + fix: Some(login_fix(*cause, &report.ssh_host)), + ..Finding::new( + CHECK, + Status::Fail, + format!("{message} — {}", cause.summary()), + ) + }, + } +} + +fn machine_findings(machine: &str, facts: &RemoteFacts) -> Vec { + let os = facts.get("os").unwrap_or(""); + let mut findings = vec![Finding::ok("remote OS", os_name(os))]; + findings.extend(sshd_findings(os, facts)); + let addr = facts + .get("client_addr") + .filter(|a| !a.is_empty()) + .unwrap_or(""); + findings.push(fail2ban(facts, addr)); + findings.push(sshguard(facts, addr)); + if os == "Linux" { + findings.push(ufw(facts)); + } + findings.push(sleep(os, facts)); + findings.extend(pu_findings(machine, facts)); + findings +} + +fn sshd_findings(os: &str, facts: &RemoteFacts) -> Vec { + if facts.get("sshd_t").is_none_or(|s| s == "unavailable") { + return vec![Finding::skipped( + "sshd settings", + "skipped (needs sudo): `sshd -T` failed as this user and `sudo -n` needs a password. To check by hand, run `sudo sshd -T | grep -Ei '^(maxstartups|maxsessions|clientalive|tcpkeepalive)'` on the machine", + )]; + } + let reload = sshd_reload(os); + let missing = |check: &str| Finding::skipped(check, "`sshd -T` did not report it"); + let mut findings = Vec::new(); + + findings.push(match facts.get("sshd.maxstartups") { + None => missing("sshd MaxStartups"), + Some(value) => max_startups(os, value, reload), + }); + + findings.push(match facts.get("sshd.maxsessions").map(str::parse::) { + Some(Ok(n)) if n < 10 => Finding::warn( + "sshd MaxSessions", + format!("MaxSessions {n}: the iPad app carries each daemon connection as a session on one SSH connection and needs extra logins past this"), + format!("Set `MaxSessions 10` in /etc/ssh/sshd_config; {reload}."), + ), + Some(Ok(n)) => Finding::ok("sshd MaxSessions", format!("MaxSessions {n}")), + _ => missing("sshd MaxSessions"), + }); + + let interval = facts + .get("sshd.clientaliveinterval") + .and_then(|v| v.parse::().ok()); + let count = facts.get("sshd.clientalivecountmax").unwrap_or("?"); + findings.push(match interval { + None => missing("sshd ClientAlive"), + Some(interval) if interval == 0 || interval > 60 => Finding::warn( + "sshd ClientAlive", + if interval == 0 { + "ClientAliveInterval 0: sshd never checks that a client is still there, and an idle connection sends nothing that keeps NAT and firewall state alive".to_string() + } else { + format!("ClientAliveInterval {interval}: an idle connection can be silent for longer than many NAT and firewall idle timeouts") + }, + format!("Set `ClientAliveInterval 15` and `ClientAliveCountMax 4` in /etc/ssh/sshd_config; {reload}."), + ), + Some(interval) => Finding::ok( + "sshd ClientAlive", + format!("ClientAliveInterval {interval}, ClientAliveCountMax {count}"), + ), + }); + + findings.push(match facts.get("sshd.tcpkeepalive") { + None => missing("sshd TCPKeepAlive"), + Some("no") => Finding::warn( + "sshd TCPKeepAlive", + "TCPKeepAlive no: the server never notices a client whose network went away", + format!("Set `TCPKeepAlive yes` in /etc/ssh/sshd_config; {reload}."), + ), + Some(value) => Finding::ok("sshd TCPKeepAlive", format!("TCPKeepAlive {value}")), + }); + findings +} + +/// `MaxStartups start[:rate:full]`: past `start` unauthenticated connections +/// sshd drops new ones at random, which a reconnect burst easily reaches. +fn max_startups(os: &str, value: &str, reload: &str) -> Finding { + const CHECK: &str = "sshd MaxStartups"; + const MIN_START: u32 = 30; + if os == "Darwin" { + return Finding::ok( + CHECK, + format!( + "MaxStartups {value} (macOS starts one sshd per connection, so it does not limit logins)" + ), + ); + } + let mut parts = value.split(':').map(str::parse::); + let (Some(Ok(start)), rate, full) = (parts.next(), parts.next(), parts.next()) else { + return Finding::skipped(CHECK, format!("could not read `MaxStartups {value}`")); + }; + if start >= MIN_START { + return Finding::ok(CHECK, format!("MaxStartups {value}")); + } + let rate = rate.and_then(Result::ok).unwrap_or(30); + let full = full.and_then(Result::ok).unwrap_or(100).max(100); + Finding::warn( + CHECK, + format!( + "MaxStartups {value}: once {start} logins are in progress sshd drops new ones, so a reconnect burst gets refused" + ), + format!("Set `MaxStartups {MIN_START}:{rate}:{full}` in /etc/ssh/sshd_config; {reload}."), + ) +} + +fn fail2ban(facts: &RemoteFacts, addr: &str) -> Finding { + const CHECK: &str = "fail2ban"; + match facts.get("fail2ban") { + Some("active") => Finding::warn( + CHECK, + "fail2ban is running: it bans an address after repeated failed or dropped logins, and a reconnect burst can trip it", + format!( + "Add this computer's address ({addr}) to `ignoreip` under `[DEFAULT]` in /etc/fail2ban/jail.local, e.g. `ignoreip = 127.0.0.1/8 ::1 {addr}` (on Tailscale, add 100.64.0.0/10 instead), then run `sudo systemctl restart fail2ban`." + ), + ), + Some("inactive") => Finding::ok(CHECK, "not running"), + _ => Finding::skipped( + CHECK, + "could not tell (no systemctl or pgrep on the machine)", + ), + } +} + +fn sshguard(facts: &RemoteFacts, addr: &str) -> Finding { + const CHECK: &str = "sshguard"; + match facts.get("sshguard") { + Some("active") => Finding::warn( + CHECK, + "sshguard is running: it blocks an address after repeated failed or dropped logins", + format!( + "Add {addr} to sshguard's whitelist file (WHITELIST_FILE in /etc/sshguard/sshguard.conf; /etc/sshguard/whitelist on Debian and Ubuntu), then run `sudo systemctl restart sshguard`." + ), + ), + Some("inactive") => Finding::ok(CHECK, "not running"), + _ => Finding::skipped( + CHECK, + "could not tell (no systemctl or pgrep on the machine)", + ), + } +} + +fn ufw(facts: &RemoteFacts) -> Finding { + const CHECK: &str = "ufw"; + match facts.get("ufw") { + Some("absent") => Finding::ok(CHECK, "not installed"), + Some("inactive") => Finding::ok(CHECK, "inactive"), + Some("active") => { + let port = facts.get("sshd.port").unwrap_or("22"); + // IPv4 and IPv6 rules print the same port: name each once. + let mut rules: Vec<&str> = Vec::new(); + for rule in facts.all("ufw.limit").filter(|r| is_ssh_rule(r, port)) { + if !rules.contains(&rule) { + rules.push(rule); + } + } + if rules.is_empty() { + return Finding::ok(CHECK, "active, with no limit rule on ssh"); + } + let commands: Vec = rules + .iter() + .map(|rule| format!("`sudo ufw allow {rule}` then `sudo ufw delete limit {rule}`")) + .collect(); + Finding::warn( + CHECK, + format!( + "a LIMIT rule covers ssh ({}): ufw denies an address that opens 6 connections within 30 s", + rules.join(", ") + ), + format!("Allow ssh instead of limiting it: {}.", commands.join("; ")), + ) + } + Some("needs_sudo") => Finding::skipped( + CHECK, + "skipped (needs sudo): `ufw status` needs root and `sudo -n` needs a password. To check by hand, run `sudo ufw status` on the machine and look for LIMIT on ssh", + ), + _ => Finding::skipped(CHECK, "the machine did not report it"), + } +} + +fn is_ssh_rule(rule: &str, port: &str) -> bool { + let rule = rule.to_ascii_lowercase(); + rule == port + || rule == format!("{port}/tcp") + || matches!(rule.as_str(), "openssh" | "ssh" | "ssh/tcp") +} + +const LINUX_SLEEP_TARGETS: &str = + "sleep.target suspend.target hibernate.target hybrid-sleep.target"; + +fn sleep(os: &str, facts: &RemoteFacts) -> Finding { + const CHECK: &str = "sleep"; + match os { + "Darwin" => match facts.get("sleep.pmset").map(str::parse::) { + Some(Ok(0)) => Finding::ok(CHECK, "system sleep is off (pmset sleep 0)"), + Some(Ok(minutes)) => Finding::warn( + CHECK, + format!( + "the Mac sleeps after {minutes} min idle, which drops every connection to it" + ), + "Run `sudo pmset -a sleep 0` on the machine (on a laptop, `sudo pmset -c sleep 0` keeps it awake only while charging).", + ), + _ => Finding::skipped(CHECK, "could not read `pmset -g`"), + }, + "Linux" => { + let targets: Vec<(&str, &str)> = facts + .all("sleep.target") + .filter_map(|line| { + let (target, state) = line.split_once(' ').unwrap_or((line, "")); + Some((target, state.trim())).filter(|(_, state)| !state.is_empty()) + }) + .collect(); + if targets.is_empty() { + return Finding::skipped( + CHECK, + "no systemd sleep targets to check; make sure the machine's power settings never suspend it", + ); + } + let unmasked: Vec = targets + .iter() + .filter(|(_, state)| *state != "masked") + .map(|(target, state)| format!("{target} ({state})")) + .collect(); + if unmasked.is_empty() { + Finding::ok(CHECK, "sleep and suspend are masked") + } else { + Finding::warn( + CHECK, + format!( + "the machine can still suspend ({}): a desktop idle timer or a closed lid drops every connection", + unmasked.join(", ") + ), + format!("Run `sudo systemctl mask {LINUX_SLEEP_TARGETS}` on the machine."), + ) + } + } + _ => Finding::skipped( + CHECK, + format!("no sleep check for {os}; make sure the machine never suspends"), + ), + } +} + +fn pu_findings(machine: &str, facts: &RemoteFacts) -> Vec { + match facts.get("pu") { + None => vec![Finding::skipped("pu", "the machine did not report it")], + Some("missing") => vec![ + Finding::warn( + "pu", + "`pu` is not on PATH on the machine (looked in ~/.pu/bin, ~/.cargo/bin and the login PATH)", + "Install PurePoint on the machine (docs/guide/linux-server.md), or put `pu` in ~/.pu/bin.", + ), + Finding::skipped("pu --mux", "needs `pu` on the machine"), + Finding::skipped("daemon", "needs `pu` on the machine"), + ], + Some(path) => { + let mux = match facts.get("pu.mux") { + Some("yes") => Finding::ok("pu --mux", "supports the multiplexed relay"), + Some(_) => Finding::warn( + "pu --mux", + "`pu` on the machine predates the multiplexed relay (`pu daemon proxy --mux`), so Windows clients log in once per stream", + format!( + "Upgrade PurePoint on {machine}; Windows clients then hold one ssh connection to it." + ), + ), + None => Finding::skipped("pu --mux", "the machine did not report it"), + }; + let daemon = match facts.get("daemon") { + Some("running") => Finding::ok("daemon", "running"), + Some("busy") => Finding::warn( + "daemon", + "the daemon answered but is at its connection limit", + "Close clients you are not using, then run this again.", + ), + Some("stopped") => Finding::warn( + "daemon", + "not running", + format!("Start it with `pu machine start {machine}`."), + ), + _ => Finding::skipped("daemon", "`pu daemon status` gave no answer"), + }; + vec![Finding::ok("pu", path), mux, daemon] + } + } +} + +/// The plain-text report, one finding per line with its fix beneath. +pub fn render(report: &Report, findings: &[Finding], color: bool) -> String { + let mut out = format!( + "Checking {} ({}). Nothing is changed on either machine.\n\n", + report.machine, report.ssh_host + ); + let width = findings.iter().map(|f| f.check.len()).max().unwrap_or(0); + for finding in findings { + let label = format!("{:<4}", finding.status.label()); + let label = if color { + match finding.status { + Status::Ok => label.green().to_string(), + Status::Warn => label.yellow().to_string(), + Status::Skipped => label.dimmed().to_string(), + Status::Fail => label.red().to_string(), + } + } else { + label + }; + out.push_str(&format!( + " {label} {: 0 { + summary.push(format!("{failed} failed")); + } + out.push_str(&format!("\n{}.\n", summary.join(", "))); + out +} + +pub fn to_json(report: &Report, findings: &[Finding]) -> serde_json::Value { + json!({ + "machine": report.machine, + "ssh_host": report.ssh_host, + "reachable": matches!(report.login, Login::Ok { .. }), + "findings": findings, + }) +} + +struct SshRun { + code: Option, + stdout: String, + stderr: String, + elapsed: Duration, +} + +async fn run_ssh( + args: Vec, + stdin: Option<&str>, + limit: Duration, +) -> Result { + use tokio::io::AsyncWriteExt; + let program = machine_target::ssh_program(); + let started = Instant::now(); + let mut child = tokio::process::Command::new(&program) + .args(args) + .stdin(if stdin.is_some() { + std::process::Stdio::piped() + } else { + std::process::Stdio::null() + }) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|e| { + CliError::Other(format!( + "failed to run {}: {e}", + Path::new(&program).display() + )) + })?; + let finished = async { + if let (Some(script), Some(mut pipe)) = (stdin, child.stdin.take()) { + // A remote that exits early (Windows) closes the pipe: not an error. + let _ = pipe.write_all(script.as_bytes()).await; + drop(pipe); + } + child.wait_with_output().await + }; + match tokio::time::timeout(limit, finished).await { + Ok(output) => { + let output = output?; + Ok(SshRun { + code: output.status.code(), + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + elapsed: started.elapsed(), + }) + } + Err(_) => Ok(SshRun { + code: None, + stdout: String::new(), + stderr: format!("timed out after {} s", limit.as_secs()), + elapsed: started.elapsed(), + }), + } +} + +/// Run the three ssh commands. Only failing to start ssh at all is an error. +async fn gather(machine: &Machine) -> Result { + let destination = machine_target::ssh_destination(&machine.ssh_host); + // `-G` only prints the effective config and never connects, so it gets no + // connect options: they would hide the user's own values. + let options = run_ssh( + vec!["-G".into(), destination.into()], + None, + Duration::from_secs(10), + ) + .await?; + let ssh_options = if options.code == Some(0) { + Ok(parse_ssh_options(&options.stdout)) + } else { + Err(one_line(&options.stderr, options.code)) + }; + + let attempt = run_ssh( + machine_target::batch_args(&machine.ssh_host, "true"), + None, + LOGIN_TIMEOUT, + ) + .await?; + // Any status but ssh's own 255 means the login worked: `true` is not a + // command on a Windows machine. + let login = match attempt.code { + Some(code) if code != SSH_FAILED => Login::Ok { + elapsed: attempt.elapsed, + }, + code => Login::Failed { + cause: SshFailureCause::classify(code, &attempt.stderr), + message: one_line(&attempt.stderr, code), + }, + }; + + let remote = if matches!(login, Login::Ok { .. }) { + let script = run_ssh( + machine_target::batch_args(&machine.ssh_host, REMOTE_COMMAND), + Some(REMOTE_SCRIPT), + SCRIPT_TIMEOUT, + ) + .await?; + classify_remote(script.code, &script.stdout, &script.stderr) + } else { + Remote::NotRun + }; + + Ok(Report { + machine: machine.name.clone(), + ssh_host: machine.ssh_host.clone(), + ssh_options, + login, + remote, + }) +} + +pub async fn run(machine: Option<&str>, json: bool) -> Result<(), CliError> { + let name = machine.ok_or_else(|| { + CliError::Other( + "`pu doctor` checks a registered machine: run `pu doctor --machine ` (see `pu machine list`)".into(), + ) + })?; + let machine = machine_target::find_machine(name)?; + machines::validate_ssh_host(&machine.ssh_host).map_err(core_error)?; + let report = gather(&machine).await?; + let findings = evaluate(&report); + if json { + println!( + "{}", + serde_json::to_string_pretty(&to_json(&report, &findings))? + ); + } else { + print!( + "{}", + render(&report, &findings, std::io::stdout().is_terminal()) + ); + } + match &report.login { + Login::Ok { .. } => Ok(()), + Login::Failed { cause, .. } => Err(CliError::Other(format!( + "machine {} ({}) could not be reached: {}", + machine.name, + machine.ssh_host, + cause.summary() + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const LINUX_NO_SUDO: &str = "doctor=1\nos=Linux\nclient_addr=192.0.2.7\nsshd_t=unavailable\nfail2ban=active\nsshguard=inactive\nufw=needs_sudo\nsleep.target=sleep.target static\nsleep.target=suspend.target static\nsleep.target=hibernate.target masked\nsleep.target=hybrid-sleep.target masked\npu=/home/me/.pu/bin/pu\npu.mux=no\ndaemon=running\ndone=1\n"; + + const LINUX_SUDO: &str = "doctor=1\nos=Linux\nclient_addr=192.0.2.7\nsshd_t=sudo\nsshd.port=22\nsshd.maxstartups=10:30:100\nsshd.maxsessions=10\nsshd.clientaliveinterval=0\nsshd.clientalivecountmax=3\nsshd.tcpkeepalive=yes\nfail2ban=inactive\nsshguard=inactive\nufw=active\nufw.limit=22/tcp\nufw.limit=22/tcp\nufw.limit=8080\nsleep.target=sleep.target masked\nsleep.target=suspend.target masked\nsleep.target=hibernate.target masked\nsleep.target=hybrid-sleep.target masked\npu=/home/me/.pu/bin/pu\npu.mux=yes\ndaemon=stopped\ndone=1\n"; + + const MAC: &str = "doctor=1\r\nos=Darwin\r\nclient_addr=100.101.102.103\r\nsshd_t=sudo\r\nsshd.maxstartups=10:30:100\r\nsshd.maxsessions=10\r\nsshd.clientaliveinterval=15\r\nsshd.clientalivecountmax=4\r\nsshd.tcpkeepalive=yes\r\nfail2ban=unknown\r\nsshguard=unknown\r\nsleep.pmset=10\r\npu=missing\r\ndone=1\r\n"; + + const SSH_G: &str = "host studio\nuser me\nhostname studio.example.ts.net\nport 22\nserveraliveinterval 0\nserveralivecountmax 3\nconnecttimeout none\ntcpkeepalive yes\ncontrolmaster false\ncontrolpersist no\n"; + + fn report(remote: Remote) -> Report { + Report { + machine: "studio".into(), + ssh_host: "me@studio".into(), + ssh_options: Ok(parse_ssh_options(SSH_G)), + login: Login::Ok { + elapsed: Duration::from_millis(400), + }, + remote, + } + } + + fn unix(stdout: &str) -> Report { + report(classify_remote(Some(0), stdout, "")) + } + + fn find<'a>(findings: &'a [Finding], check: &str) -> &'a Finding { + findings + .iter() + .find(|f| f.check == check) + .unwrap_or_else(|| panic!("no {check} finding in {findings:#?}")) + } + + #[test] + fn given_low_max_startups_should_recommend_30_30_100() { + // given + let findings = evaluate(&unix(LINUX_SUDO)); + + // when + let finding = find(&findings, "sshd MaxStartups"); + + // then + assert_eq!(finding.status, Status::Warn); + assert!( + finding + .fix + .as_deref() + .unwrap() + .starts_with("Set `MaxStartups 30:30:100` in /etc/ssh/sshd_config"), + "{finding:?}" + ); + } + + #[test] + fn given_max_startups_with_larger_values_should_keep_rate_and_full() { + let finding = max_startups("Linux", "20:50:200", "reload"); + assert_eq!( + finding.fix.as_deref(), + Some("Set `MaxStartups 30:50:200` in /etc/ssh/sshd_config; reload.") + ); + assert_eq!(max_startups("Linux", "30:30:100", "").status, Status::Ok); + assert_eq!(max_startups("Linux", "10", "").status, Status::Warn); + assert_eq!(max_startups("Darwin", "10:30:100", "").status, Status::Ok); + } + + #[test] + fn given_client_alive_interval_zero_should_recommend_15_and_4() { + // given + let findings = evaluate(&unix(LINUX_SUDO)); + + // when + let finding = find(&findings, "sshd ClientAlive"); + + // then + assert_eq!(finding.status, Status::Warn); + let fix = finding.fix.as_deref().unwrap(); + assert!( + fix.contains("`ClientAliveInterval 15` and `ClientAliveCountMax 4`"), + "{fix}" + ); + assert!(fix.contains("sudo systemctl reload ssh"), "{fix}"); + } + + #[test] + fn given_fail2ban_active_should_recommend_ignoreip_with_client_address() { + // given + let findings = evaluate(&unix(LINUX_NO_SUDO)); + + // when + let finding = find(&findings, "fail2ban"); + + // then + assert_eq!(finding.status, Status::Warn); + let fix = finding.fix.as_deref().unwrap(); + assert!( + fix.contains("`ignoreip = 127.0.0.1/8 ::1 192.0.2.7`"), + "{fix}" + ); + assert!(fix.contains("/etc/fail2ban/jail.local"), "{fix}"); + } + + #[test] + fn given_ufw_limit_on_ssh_should_recommend_allow_once_per_rule() { + // given + let findings = evaluate(&unix(LINUX_SUDO)); + + // when + let finding = find(&findings, "ufw"); + + // then + assert_eq!(finding.status, Status::Warn); + assert_eq!( + finding.fix.as_deref(), + Some( + "Allow ssh instead of limiting it: `sudo ufw allow 22/tcp` then `sudo ufw delete limit 22/tcp`." + ) + ); + } + + #[test] + fn given_ufw_limit_on_other_port_only_should_pass() { + let facts = + RemoteFacts::parse("ufw=active\nufw.limit=8080\nsshd.port=2222\nufw.limit=22\n"); + assert_eq!(ufw(&facts).status, Status::Ok); + let facts = RemoteFacts::parse("ufw=active\nufw.limit=OpenSSH\n"); + assert_eq!(ufw(&facts).status, Status::Warn); + } + + #[test] + fn given_mac_that_sleeps_should_recommend_pmset_sleep_0() { + // given + let findings = evaluate(&unix(MAC)); + + // when + let finding = find(&findings, "sleep"); + + // then + assert_eq!(finding.status, Status::Warn); + assert!( + finding + .fix + .as_deref() + .unwrap() + .starts_with("Run `sudo pmset -a sleep 0`"), + "{finding:?}" + ); + } + + #[test] + fn given_linux_with_unmasked_sleep_targets_should_recommend_masking_all_four() { + // given + let findings = evaluate(&unix(LINUX_NO_SUDO)); + + // when + let finding = find(&findings, "sleep"); + + // then + assert_eq!(finding.status, Status::Warn); + assert!( + finding + .detail + .contains("sleep.target (static), suspend.target (static)"), + "{finding:?}" + ); + assert_eq!( + finding.fix.as_deref(), + Some( + "Run `sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target` on the machine." + ) + ); + assert_eq!( + find(&evaluate(&unix(LINUX_SUDO)), "sleep").status, + Status::Ok + ); + } + + #[test] + fn given_pu_without_mux_should_recommend_upgrading_that_machine() { + // given + let findings = evaluate(&unix(LINUX_NO_SUDO)); + + // when + let finding = find(&findings, "pu --mux"); + + // then + assert_eq!(finding.status, Status::Warn); + assert_eq!( + finding.fix.as_deref(), + Some( + "Upgrade PurePoint on studio; Windows clients then hold one ssh connection to it." + ) + ); + assert_eq!(find(&findings, "daemon").status, Status::Ok); + } + + #[test] + fn given_checks_needing_root_should_be_skipped_never_passed() { + // given + let findings = evaluate(&unix(LINUX_NO_SUDO)); + + // then + for check in ["sshd settings", "ufw"] { + let finding = find(&findings, check); + assert_eq!(finding.status, Status::Skipped, "{finding:?}"); + assert!( + finding.detail.starts_with("skipped (needs sudo)"), + "{finding:?}" + ); + } + assert!(!findings.iter().any(|f| f.check == "sshd MaxStartups")); + } + + #[test] + fn given_missing_pu_should_warn_and_skip_what_needs_it() { + let findings = evaluate(&unix(MAC)); + assert_eq!(find(&findings, "pu").status, Status::Warn); + assert_eq!(find(&findings, "pu --mux").status, Status::Skipped); + assert_eq!(find(&findings, "daemon").status, Status::Skipped); + // fail2ban/sshguard could not be determined, and macOS has no ufw check. + assert_eq!(find(&findings, "fail2ban").status, Status::Skipped); + assert!(!findings.iter().any(|f| f.check == "ufw")); + assert_eq!(find(&findings, "remote OS").detail, "macOS"); + } + + #[test] + fn given_stopped_daemon_should_point_at_machine_start() { + let findings = evaluate(&unix(LINUX_SUDO)); + assert_eq!( + find(&findings, "daemon").fix.as_deref(), + Some("Start it with `pu machine start studio`.") + ); + } + + #[test] + fn given_windows_machine_should_skip_unix_checks_with_a_reason() { + // given: cmd.exe cannot run /bin/sh, so the script prints nothing + let remote = classify_remote( + Some(1), + "", + "'/bin/sh' is not recognized as an internal or external command", + ); + + // when + let findings = evaluate(&report(remote)); + + // then + let finding = find(&findings, "machine checks"); + assert_eq!(finding.status, Status::Skipped); + assert!(finding.detail.contains("runs Windows"), "{finding:?}"); + assert_eq!( + classify_remote(Some(0), "doctor=1\nos=MINGW64_NT-10.0\n", ""), + Remote::Windows + ); + } + + #[test] + fn given_ssh_failing_during_the_script_should_report_its_cause() { + let remote = classify_remote( + Some(255), + "", + "kex_exchange_identification: Connection closed by remote host", + ); + assert_eq!( + remote, + Remote::Failed { + cause: SshFailureCause::ServerRefused, + message: "kex_exchange_identification: Connection closed by remote host".into() + } + ); + let finding = find(&evaluate(&report(remote)), "machine checks").clone(); + assert_eq!(finding.status, Status::Fail); + } + + #[test] + fn given_failed_login_should_fail_with_cause_and_skip_machine_checks() { + // given + let mut failed = report(Remote::NotRun); + failed.login = Login::Failed { + cause: SshFailureCause::Auth, + message: "me@studio: Permission denied (publickey).".into(), + }; + + // when + let findings = evaluate(&failed); + + // then + let login = find(&findings, "login"); + assert_eq!(login.status, Status::Fail); + assert_eq!( + login.detail, + "me@studio: Permission denied (publickey). — The server rejected the SSH key." + ); + assert!(login.fix.as_deref().unwrap().contains("ssh-add")); + assert_eq!(find(&findings, "machine checks").status, Status::Skipped); + assert_eq!(to_json(&failed, &findings)["reachable"], false); + } + + #[test] + fn given_slow_login_should_warn() { + let mut slow = unix(LINUX_SUDO); + slow.login = Login::Ok { + elapsed: Duration::from_millis(5200), + }; + let finding = find(&evaluate(&slow), "login").clone(); + assert_eq!(finding.status, Status::Warn); + assert!(finding.detail.contains("5.2 s"), "{finding:?}"); + assert!(finding.fix.unwrap().contains("UseDNS no")); + } + + #[test] + fn given_ssh_g_output_should_show_effective_client_options() { + let finding = find(&evaluate(&unix(LINUX_SUDO)), "ssh client").clone(); + assert_eq!(finding.status, Status::Ok); + assert!( + finding.detail.starts_with( + "connects to studio.example.ts.net port 22 as me; your config: ServerAliveInterval 0, ServerAliveCountMax 3, ConnectTimeout none, TCPKeepAlive yes, ControlMaster false, ControlPersist no." + ), + "{finding:?}" + ); + let mut no_g = unix(LINUX_SUDO); + no_g.ssh_options = Err("ssh exited with status 255".into()); + assert_eq!(find(&evaluate(&no_g), "ssh client").status, Status::Skipped); + } + + #[test] + fn given_partial_script_output_should_skip_unreported_checks() { + let findings = evaluate(&unix("doctor=1\nos=Linux\n")); + for check in [ + "sshd settings", + "fail2ban", + "sshguard", + "ufw", + "sleep", + "pu", + ] { + assert_eq!(find(&findings, check).status, Status::Skipped, "{check}"); + } + } + + #[test] + fn given_findings_should_render_fixes_under_their_check() { + // given + let report = unix(LINUX_SUDO); + let findings = evaluate(&report); + + // when + let text = render(&report, &findings, false); + + // then + assert!( + text.starts_with( + "Checking studio (me@studio). Nothing is changed on either machine.\n\n" + ) + ); + assert!( + text.contains(" warn sshd MaxStartups MaxStartups 10:30:100: once 10 logins"), + "{text}" + ); + // 8 columns of status, then the 17-wide check column ("sshd TCPKeepAlive"). + assert!( + text.contains(&format!( + "\n{}fix: Set `MaxStartups 30:30:100`", + " ".repeat(8 + 17 + 2) + )), + "{text}" + ); + assert!(text.ends_with("ok, 4 to fix, 0 skipped.\n"), "{text}"); + } + + #[test] + fn given_remote_script_should_be_posix_sh() { + // `sh -n` parses without running anything. + if cfg!(windows) { + return; + } + let mut child = std::process::Command::new("/bin/sh") + .arg("-n") + .stdin(std::process::Stdio::piped()) + .spawn() + .unwrap(); + use std::io::Write; + child + .stdin + .take() + .unwrap() + .write_all(REMOTE_SCRIPT.as_bytes()) + .unwrap(); + assert!(child.wait().unwrap().success()); + } +} diff --git a/crates/pu-cli/src/commands/machine.rs b/crates/pu-cli/src/commands/machine.rs index e7c60835..01e4c4d9 100644 --- a/crates/pu-cli/src/commands/machine.rs +++ b/crates/pu-cli/src/commands/machine.rs @@ -186,12 +186,15 @@ async fn run_start(name: &str) -> Result<(), CliError> { machines::validate_ssh_host(&machine.ssh_host).map_err(core_error)?; let args = machine_target::start_command_args(&machine).await?; let program = machine_target::ssh_program(); + // stderr is captured to classify a failure, and echoed either way. let run = tokio::process::Command::new(&program) .args(args) .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::inherit()) + .stderr(std::process::Stdio::piped()) .kill_on_drop(true) - .status(); - let status = tokio::time::timeout(START_TIMEOUT, run) + .output(); + let output = tokio::time::timeout(START_TIMEOUT, run) .await .map_err(|_| { CliError::Other(format!( @@ -206,11 +209,44 @@ async fn run_start(name: &str) -> Result<(), CliError> { std::path::Path::new(&program).display() )) })?; - if !status.success() { - return Err(CliError::Other(format!( - "failed to start the daemon on {} ({status}) — is PurePoint installed there?", - machine.name - ))); + let stderr = String::from_utf8_lossy(&output.stderr); + if !output.status.success() { + return Err(start_failure(&machine.name, output.status.code(), &stderr)); } + eprint!("{stderr}"); Ok(()) } + +/// Why `pu machine start` failed: ssh's message and its cause (MACH-018). +fn start_failure(name: &str, code: Option, stderr: &str) -> CliError { + CliError::Other(format!( + "failed to start the daemon on {name}: {}", + machine_target::classified_ssh_detail(code, stderr) + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_failed_start_should_name_the_cause() { + // given + let missing = start_failure("studio", Some(127), "sh: 1: pu: not found\n"); + let refused = start_failure( + "studio", + Some(255), + "kex_exchange_identification: Connection closed by remote host", + ); + + // then + assert_eq!( + missing.to_string(), + "failed to start the daemon on studio: sh: 1: pu: not found — PurePoint is not installed on the machine." + ); + assert!( + refused.to_string().contains("The server refused the login"), + "{refused}" + ); + } +} diff --git a/crates/pu-cli/src/commands/mod.rs b/crates/pu-cli/src/commands/mod.rs index 733c3c75..916afbfd 100644 --- a/crates/pu-cli/src/commands/mod.rs +++ b/crates/pu-cli/src/commands/mod.rs @@ -6,6 +6,7 @@ pub mod clean; pub mod daemon; pub mod daemon_proxy; pub mod diff; +pub mod doctor; pub mod gate; pub mod grid; pub mod health; diff --git a/crates/pu-cli/src/machine_target.rs b/crates/pu-cli/src/machine_target.rs index 4ad12d8a..a92a7ac1 100644 --- a/crates/pu-cli/src/machine_target.rs +++ b/crates/pu-cli/src/machine_target.rs @@ -21,6 +21,7 @@ use std::time::Instant; use pu_core::machines::{self, Machine}; use pu_core::paths; +use pu_core::ssh_failure::SshFailureCause; use crate::daemon_ctrl::{self, HealthProbe}; use crate::error::CliError; @@ -106,9 +107,23 @@ pub fn ssh_destination(host: &str) -> String { /// parking it on) a shared master connection. const NO_CONTROL_MASTER: [&str; 4] = ["-o", "ControlMaster=no", "-o", "ControlPath=none"]; +/// On every ssh command (MACH-017): a dial to an unreachable host fails within +/// 10 s, and the kernel notices a dead path even when ssh's own keepalive is +/// blocked. +pub const CONNECT_OPTIONS: [&str; 4] = ["-o", "ConnectTimeout=10", "-o", "TCPKeepAlive=yes"]; + +/// On every long-lived ssh command: ssh gives up after 45 s of silence. +const SERVER_ALIVE: [&str; 4] = [ + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", +]; + #[cfg(unix)] pub fn home_query_args(host: &str) -> Vec { let mut args: Vec = vec!["-o".into(), "BatchMode=yes".into()]; + args.extend(CONNECT_OPTIONS.map(OsString::from)); args.extend(NO_CONTROL_MASTER.map(OsString::from)); args.extend([ssh_destination(host).into(), r#"printf %s "$HOME""#.into()]); args @@ -119,21 +134,20 @@ pub fn forward_args(local_socket: &Path, remote_home: &str, host: &str) -> Vec = vec!["-N".into(), "-T".into()]; - for option in [ - "BatchMode=yes", - "ExitOnForwardFailure=yes", - "ServerAliveInterval=15", - "ServerAliveCountMax=3", - "StreamLocalBindUnlink=yes", - // A user's ControlMaster config would otherwise hand the forward to a - // shared master that outlives this ssh process. - "ControlMaster=no", - "ControlPath=none", - ] { - args.push("-o".into()); - args.push(option.into()); - } + let mut args: Vec = vec![ + "-N".into(), + "-T".into(), + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "ExitOnForwardFailure=yes".into(), + ]; + args.extend(CONNECT_OPTIONS.map(OsString::from)); + args.extend(SERVER_ALIVE.map(OsString::from)); + args.extend(["-o".into(), "StreamLocalBindUnlink=yes".into()]); + // A user's ControlMaster config would otherwise hand the forward to a + // shared master that outlives this ssh process. + args.extend(NO_CONTROL_MASTER.map(OsString::from)); args.push("-L".into()); // One argv element, so a remote home with spaces survives intact. args.push(spec); @@ -142,7 +156,8 @@ pub fn forward_args(local_socket: &Path, remote_home: &str, host: &str) -> Vec Vec { - let mut args: Vec = NO_CONTROL_MASTER.map(OsString::from).into(); + let mut args: Vec = CONNECT_OPTIONS.map(OsString::from).into(); + args.extend(NO_CONTROL_MASTER.map(OsString::from)); args.extend([ssh_destination(host).into(), START_COMMAND.into()]); args } @@ -175,6 +190,31 @@ fn unreachable(machine: &Machine, detail: impl std::fmt::Display) -> CliError { )) } +/// ssh's message for a failed command, followed by what it means (MACH-018): +/// "offline" alone does not say whether to fix the network, keys or server. +pub fn classified_ssh_detail(code: Option, stderr: &str) -> String { + let message = stderr + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect::>() + .join("; "); + let message = if message.is_empty() { + code.map_or("ssh did not finish".to_string(), |c| { + format!("ssh exited with status {c}") + }) + } else { + message + }; + let cause = SshFailureCause::classify(code, stderr); + format!("{message} — {}", cause.summary()) +} + +/// An ssh command for `machine` failed before the remote command could run. +pub fn ssh_failed(machine: &Machine, code: Option, stderr: &str) -> CliError { + unreachable(machine, classified_ssh_detail(code, stderr)) +} + /// Resolve the remote user's `$HOME` (once per connection). #[cfg(unix)] pub async fn resolve_remote_home(machine: &Machine) -> Result { @@ -187,7 +227,7 @@ pub async fn resolve_remote_home(machine: &Machine) -> Result .output(); let output = tokio::time::timeout(HOME_QUERY_TIMEOUT, run) .await - .map_err(|_| unreachable(machine, "timed out"))? + .map_err(|_| ssh_failed(machine, None, "timed out"))? .map_err(|e| { CliError::Other(format!( "failed to run {}: {e}", @@ -196,11 +236,7 @@ pub async fn resolve_remote_home(machine: &Machine) -> Result })?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - let detail = match stderr.trim() { - "" => output.status.to_string(), - message => message.to_string(), - }; - return Err(unreachable(machine, detail)); + return Err(ssh_failed(machine, output.status.code(), &stderr)); } let home = String::from_utf8_lossy(&output.stdout) .trim_end_matches(['\r', '\n']) @@ -469,11 +505,7 @@ pub async fn open_forward(machine: &Machine) -> Result { use std::io::Read; let _ = pipe.read_to_string(&mut stderr); } - let detail = match stderr.trim() { - "" => format!("ssh exited ({status}) before the forward was ready"), - message => message.to_string(), - }; - return Err(unreachable(machine, detail)); + return Err(ssh_failed(machine, status.code(), &stderr)); } if Instant::now() >= deadline { return Err(unreachable( @@ -535,7 +567,8 @@ const OS_PROBE_COMMAND: &str = "uname -s"; #[cfg_attr(unix, allow(dead_code))] const SSH_FAILED: i32 = 255; -/// `ssh -T -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 +/// `ssh -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes +/// -o ServerAliveInterval=15 -o ServerAliveCountMax=3 /// -o ControlMaster=no -o ControlPath=none ` (machines.md, /// Windows relay). Win32-OpenSSH has no connection sharing, but the `ssh` on /// `PATH` may be another build (Git for Windows, MSYS2) honouring a user's @@ -546,15 +579,9 @@ pub fn relay_args(host: &str, os: RemoteOs) -> Vec { RemoteOs::Unix => UNIX_RELAY_COMMAND, RemoteOs::Windows => WINDOWS_RELAY_COMMAND, }; - let mut args: Vec = vec!["-T".into()]; - for option in [ - "BatchMode=yes", - "ServerAliveInterval=15", - "ServerAliveCountMax=3", - ] { - args.push("-o".into()); - args.push(option.into()); - } + let mut args: Vec = vec!["-T".into(), "-o".into(), "BatchMode=yes".into()]; + args.extend(CONNECT_OPTIONS.map(OsString::from)); + args.extend(SERVER_ALIVE.map(OsString::from)); args.extend(NO_CONTROL_MASTER.map(OsString::from)); args.extend([ssh_destination(host).into(), relay.into()]); args @@ -563,9 +590,16 @@ pub fn relay_args(host: &str, os: RemoteOs) -> Vec { /// `ssh -T -o BatchMode=yes 'uname -s'`, run once per connection. #[cfg_attr(unix, allow(dead_code))] pub fn os_probe_args(host: &str) -> Vec { + batch_args(host, OS_PROBE_COMMAND) +} + +/// `ssh -T -o BatchMode=yes` plus the connect and no-ControlMaster options, +/// running `command`: a short command that must never prompt. +pub fn batch_args(host: &str, command: &str) -> Vec { let mut args: Vec = vec!["-T".into(), "-o".into(), "BatchMode=yes".into()]; + args.extend(CONNECT_OPTIONS.map(OsString::from)); args.extend(NO_CONTROL_MASTER.map(OsString::from)); - args.extend([ssh_destination(host).into(), OS_PROBE_COMMAND.into()]); + args.extend([ssh_destination(host).into(), command.into()]); args } @@ -592,7 +626,8 @@ pub fn start_args_for(host: &str, os: RemoteOs) -> Vec { match os { RemoteOs::Unix => start_args(host), RemoteOs::Windows => { - let mut args: Vec = NO_CONTROL_MASTER.map(OsString::from).into(); + let mut args: Vec = CONNECT_OPTIONS.map(OsString::from).into(); + args.extend(NO_CONTROL_MASTER.map(OsString::from)); args.extend([ssh_destination(host).into(), WINDOWS_START_COMMAND.into()]); args } @@ -610,14 +645,7 @@ pub fn relay_exit_error(machine: &Machine, code: Option, stderr: &str) -> C "PurePoint is not installed on machine {} (`pu` was not found there) — install it there and retry", machine.name )), - Some(SSH_FAILED) => unreachable( - machine, - if stderr.is_empty() { - "ssh exited with status 255" - } else { - stderr - }, - ), + Some(SSH_FAILED) => ssh_failed(machine, code, stderr), _ => { let status = code.map_or("no exit status".to_string(), |c| format!("exit {c}")); let detail = if stderr.is_empty() { @@ -695,7 +723,7 @@ pub async fn probe_remote_os(machine: &Machine) -> Result { .output(); let output = tokio::time::timeout(HOME_QUERY_TIMEOUT, run) .await - .map_err(|_| unreachable(machine, "timed out"))? + .map_err(|_| ssh_failed(machine, None, "timed out"))? .map_err(|e| { CliError::Other(format!( "failed to run {}: {e}", @@ -704,11 +732,7 @@ pub async fn probe_remote_os(machine: &Machine) -> Result { })?; if output.status.code() == Some(SSH_FAILED) { let stderr = String::from_utf8_lossy(&output.stderr); - let detail = match stderr.trim() { - "" => output.status.to_string(), - message => message.to_string(), - }; - return Err(unreachable(machine, detail)); + return Err(ssh_failed(machine, output.status.code(), &stderr)); } Ok(remote_os_from_probe( output.status.success(), @@ -917,6 +941,10 @@ mod tests { "-o", "ExitOnForwardFailure=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", @@ -942,6 +970,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ControlMaster=no", "-o", "ControlPath=none", @@ -956,6 +988,10 @@ mod tests { assert_eq!( strings(start_args("studio")), vec![ + "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", "-o", "ControlMaster=no", "-o", @@ -1199,6 +1235,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", @@ -1221,6 +1261,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", @@ -1243,6 +1287,10 @@ mod tests { "-o", "BatchMode=yes", "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", + "-o", "ControlMaster=no", "-o", "ControlPath=none", @@ -1274,6 +1322,10 @@ mod tests { assert_eq!( strings(start_args_for("winbox", RemoteOs::Windows)), vec![ + "-o", + "ConnectTimeout=10", + "-o", + "TCPKeepAlive=yes", "-o", "ControlMaster=no", "-o", @@ -1304,7 +1356,9 @@ mod tests { } let message = relay_exit_error(&machine, Some(255), "Permission denied\r\n").to_string(); assert!( - message.contains("unreachable over ssh: Permission denied"), + message.contains( + "unreachable over ssh: Permission denied — The server rejected the SSH key." + ), "{message}" ); let message = relay_exit_error(&machine, Some(1), "boom").to_string(); diff --git a/crates/pu-cli/src/main.rs b/crates/pu-cli/src/main.rs index 10796eb9..0d31f54d 100644 --- a/crates/pu-cli/src/main.rs +++ b/crates/pu-cli/src/main.rs @@ -291,6 +291,12 @@ enum Commands { #[arg(long)] interval: Option, }, + /// Check a machine (`--machine `) for settings that drop connections; changes nothing + Doctor { + /// Output as JSON + #[arg(long)] + json: bool, + }, /// Manage machines reachable over SSH (use with --machine) Machine { #[command(subcommand)] @@ -817,6 +823,15 @@ async fn async_main() { if let Some(root) = &cli.project { commands::set_project_override(root.clone()); } + // `pu doctor --machine` checks the ssh path itself, so it needs no daemon + // endpoint: it must run (and explain) even when the forward cannot open. + if let Commands::Doctor { json } = cli.command { + if let Err(e) = commands::doctor::run(cli.machine.as_deref(), json).await { + eprintln!("error: {e}"); + std::process::exit(1); + } + return; + } let custom_socket = cli.socket.is_some() || cli.machine.is_some(); // Held until the command finishes: dropping it closes a private ssh forward. let mut endpoint = None; @@ -1107,6 +1122,7 @@ async fn async_main() { } => commands::diff::run(&socket, worktree, stat, json).await, Commands::Watch { interval } => commands::watch::run(&socket, interval).await, Commands::Machine { action } => commands::machine::run(action).await, + Commands::Doctor { .. } => unreachable!("pu doctor returns before connecting"), Commands::Clean { worktree, all, @@ -1318,6 +1334,16 @@ mod tests { } } + #[test] + fn given_doctor_should_take_the_global_machine_flag_and_json() { + // given / when + let cli = Cli::try_parse_from(["pu", "doctor", "--machine", "studio", "--json"]).unwrap(); + + // then + assert_eq!(cli.machine.as_deref(), Some("studio")); + assert!(matches!(cli.command, Commands::Doctor { json: true })); + } + #[test] fn given_local_file_commands_should_be_rejected_for_machines() { for (args, name) in [ diff --git a/crates/pu-cli/tests/machines.rs b/crates/pu-cli/tests/machines.rs index de3f676f..0549df53 100644 --- a/crates/pu-cli/tests/machines.rs +++ b/crates/pu-cli/tests/machines.rs @@ -16,6 +16,10 @@ if [ -n "$FAKE_SSH_FAIL" ]; then echo "ssh: Could not resolve hostname fakehost" >&2 exit 255 fi +if [ "$1" = "-G" ]; then + printf 'host fakehost\nuser me\nhostname fakehost.example\nport 22\nserveraliveinterval 0\nconnecttimeout none\ntcpkeepalive yes\ncontrolmaster false\ncontrolpersist no\n' + exit 0 +fi forward="" prev="" last="" @@ -32,6 +36,9 @@ fi case "$last" in *printf*) printf %s "$FAKE_REMOTE_HOME"; exit 0 ;; *"pu health"*) echo "remote daemon started"; exit 0 ;; + true) exit 0 ;; + "/bin/sh -s") + HOME="$FAKE_REMOTE_HOME" SSH_CLIENT="192.0.2.7 50000 22" exec /bin/sh -s ;; esac echo "unexpected ssh invocation: $*" >&2 exit 255 @@ -100,6 +107,7 @@ impl Env { .env_remove("PU_PROJECT_ROOT") .env_remove("PU_AGENT_ID") .env_remove("FAKE_SSH_FAIL") + .env_remove("FAKE_SUDO") .env_remove("FAKE_SSH_NO_FORWARD"); for (key, value) in extra_env { command.env(key, value); @@ -280,12 +288,12 @@ async fn given_running_remote_daemon_should_serve_commands_over_a_private_forwar let log = env.ssh_log(); assert!( log.contains( - "-o BatchMode=yes -o ControlMaster=no -o ControlPath=none fakehost printf %s \"$HOME\"" + "-o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none fakehost printf %s \"$HOME\"" ), "{log}" ); assert!( - log.contains("-o StreamLocalBindUnlink=yes -o ControlMaster=no -o ControlPath=none -L "), + log.contains("-N -T -o BatchMode=yes -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StreamLocalBindUnlink=yes -o ControlMaster=no -o ControlPath=none -L "), "{log}" ); assert!( @@ -533,3 +541,230 @@ async fn given_sigterm_should_close_the_private_forward() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } } + +/// Stand-ins for the machine's tools, in the remote `~/.pu/bin` (first on the +/// doctor script's `PATH`). `sudo -n` works only with `FAKE_SUDO`; `sshd -T` +/// and `ufw status` answer only under it. `pu` is this build's. +const REMOTE_TOOLS: &[(&str, &str)] = &[ + ("uname", "#!/bin/sh\necho Linux\n"), + ( + "sudo", + "#!/bin/sh\n[ \"$1\" = -n ] && shift\nif [ -z \"$FAKE_SUDO\" ]; then echo 'sudo: a password is required' >&2; exit 1; fi\nFAKE_ROOT=1 exec \"$@\"\n", + ), + ( + "sshd", + "#!/bin/sh\nif [ -z \"$FAKE_ROOT\" ]; then echo 'sshd: no hostkeys available -- exiting.' >&2; exit 1; fi\nprintf 'port 22\\nmaxstartups 10:30:100\\nmaxsessions 10\\nclientaliveinterval 0\\nclientalivecountmax 3\\ntcpkeepalive yes\\npermitrootlogin no\\n'\n", + ), + ( + "systemctl", + "#!/bin/sh\ncase \"$1 $2\" in\n 'is-active --quiet') [ \"$3\" = fail2ban ]; exit $? ;;\n is-enabled*) echo static; exit 0 ;;\nesac\nexit 1\n", + ), + ("pgrep", "#!/bin/sh\nexit 1\n"), + ( + "ufw", + "#!/bin/sh\nif [ -z \"$FAKE_ROOT\" ]; then echo 'ERROR: You need to be root to run this script' >&2; exit 1; fi\nprintf 'Status: active\\n\\nTo Action From\\n-- ------ ----\\n22/tcp LIMIT Anywhere\\n80/tcp ALLOW Anywhere\\n22/tcp (v6) LIMIT Anywhere (v6)\\n'\n", + ), +]; + +fn install_remote_tools(env: &Env) { + let bin = env.root.join("r").join(".pu").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + for (name, body) in REMOTE_TOOLS { + let path = bin.join(name); + std::fs::write(&path, body).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::os::unix::fs::symlink(env!("CARGO_BIN_EXE_pu"), bin.join("pu")).unwrap(); +} + +fn finding<'a>(report: &'a serde_json::Value, check: &str) -> &'a serde_json::Value { + report["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["check"] == check) + .unwrap_or_else(|| panic!("no {check} finding in {report:#}")) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_machine_without_sudo_doctor_should_report_fixes_and_skip_root_checks() { + // given + let env = Env::new(); + let _server = serve_remote_daemon(&env); + env.add_studio().await; + install_remote_tools(&env); + + // when + let report = env + .ok_json(&["doctor", "--machine", "studio", "--json"]) + .await; + + // then + assert_eq!(report["reachable"], true, "{report:#}"); + assert_eq!(finding(&report, "ssh client")["status"], "ok"); + assert_eq!(finding(&report, "login")["status"], "ok"); + assert_eq!(finding(&report, "remote OS")["detail"], "Linux"); + for check in ["sshd settings", "ufw"] { + let skipped = finding(&report, check); + assert_eq!(skipped["status"], "skipped", "{skipped}"); + assert!( + skipped["detail"] + .as_str() + .unwrap() + .starts_with("skipped (needs sudo)"), + "{skipped}" + ); + } + let fail2ban = finding(&report, "fail2ban"); + assert_eq!(fail2ban["status"], "warn"); + assert!( + fail2ban["fix"] + .as_str() + .unwrap() + .contains("ignoreip = 127.0.0.1/8 ::1 192.0.2.7"), + "{fail2ban}" + ); + assert_eq!(finding(&report, "sshguard")["status"], "ok"); + assert_eq!(finding(&report, "sleep")["status"], "warn"); + assert_eq!(finding(&report, "pu")["status"], "ok"); + assert_ne!(finding(&report, "pu --mux")["status"], "skipped"); + assert_eq!(finding(&report, "daemon")["status"], "ok", "{report:#}"); + + let log = env.ssh_log(); + assert!(log.contains("-G fakehost\n"), "{log}"); + assert!( + log.contains("-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none fakehost true\n"), + "{log}" + ); + assert!( + log.contains("-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none fakehost /bin/sh -s\n"), + "{log}" + ); + assert!(!env.engine_marker().exists(), "a local daemon was started"); + + // The text form says the same. + let output = env.pu(&["doctor", "--machine", "studio"], &[]).await; + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + eprintln!("{text}"); + assert!( + text.starts_with("Checking studio (fakehost). Nothing is changed on either machine."), + "{text}" + ); + assert!( + text.contains("fix: Add this computer's address (192.0.2.7)"), + "{text}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_machine_with_sudo_doctor_should_check_sshd_and_ufw() { + // given: no daemon on the machine + let env = Env::new(); + env.add_studio().await; + install_remote_tools(&env); + + // when + let output = env + .pu( + &["doctor", "--machine", "studio", "--json"], + &[("FAKE_SUDO", "1")], + ) + .await; + + // then + assert!(output.status.success()); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let max_startups = finding(&report, "sshd MaxStartups"); + assert_eq!(max_startups["status"], "warn"); + assert!( + max_startups["fix"] + .as_str() + .unwrap() + .starts_with("Set `MaxStartups 30:30:100`"), + "{max_startups}" + ); + assert_eq!(finding(&report, "sshd ClientAlive")["status"], "warn"); + assert_eq!(finding(&report, "sshd MaxSessions")["status"], "ok"); + assert_eq!(finding(&report, "sshd TCPKeepAlive")["status"], "ok"); + assert_eq!( + finding(&report, "ufw")["fix"], + "Allow ssh instead of limiting it: `sudo ufw allow 22/tcp` then `sudo ufw delete limit 22/tcp`." + ); + assert_eq!( + finding(&report, "daemon")["fix"], + "Start it with `pu machine start studio`." + ); + assert!(!env.engine_marker().exists(), "a local daemon was started"); + assert!( + !env.remote_socket.exists(), + "doctor started the remote daemon" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_unreachable_machine_doctor_should_exit_nonzero_with_the_cause() { + // given + let env = Env::new(); + env.add_studio().await; + + // when + let output = env + .pu( + &["doctor", "--machine", "studio", "--json"], + &[("FAKE_SSH_FAIL", "1")], + ) + .await; + + // then + assert!(!output.status.success()); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["reachable"], false); + let login = finding(&report, "login"); + assert_eq!(login["status"], "fail"); + assert!( + login["detail"] + .as_str() + .unwrap() + .contains("Could not resolve hostname fakehost — The machine could not be reached over the network"), + "{login}" + ); + assert_eq!(finding(&report, "machine checks")["status"], "skipped"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("machine studio (fakehost) could not be reached: The machine could not be reached over the network"), + "{stderr}" + ); + // Only `-G` and the login ran: no script after a failed login. + assert!(!env.ssh_log().contains("/bin/sh -s"), "{}", env.ssh_log()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_doctor_without_machine_should_explain_usage() { + let env = Env::new(); + let error = env.fails(&["doctor"]).await; + assert!(error.contains("pu doctor --machine "), "{error}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_unreachable_host_errors_should_name_the_cause() { + // given + let env = Env::new(); + env.add_studio().await; + + // when + let output = env + .pu( + &["--machine", "studio", "health"], + &[("FAKE_SSH_FAIL", "1")], + ) + .await; + + // then + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("ssh: Could not resolve hostname fakehost — The machine could not be reached over the network"), + "{stderr}" + ); +} diff --git a/crates/pu-cli/tests/machines_windows.rs b/crates/pu-cli/tests/machines_windows.rs index 5eb02782..1f7c7bd3 100644 --- a/crates/pu-cli/tests/machines_windows.rs +++ b/crates/pu-cli/tests/machines_windows.rs @@ -17,6 +17,9 @@ if defined FAKE_SSH_FAIL ( echo ssh: Could not resolve hostname fakehost 1>&2 exit /b 255 ) +echo %* | findstr /b /c:"-G " >nul && goto sshg +echo %* | findstr /c:"fakehost true" >nul && exit /b 0 +echo %* | findstr /c:"/bin/sh -s" >nul && goto nosh echo %* | findstr /c:"uname -s" >nul && goto uname echo %* | findstr /c:"daemon proxy" >nul && goto proxy echo %* | findstr /c:"pu health" >nul && goto health @@ -36,6 +39,14 @@ exit /b %ERRORLEVEL% :health echo remote daemon started exit /b 0 +:sshg +echo user me +echo hostname fakehost +echo serveraliveinterval 0 +exit /b 0 +:nosh +echo '/bin/sh' is not recognized as an internal or external command, 1>&2 +exit /b 1 "#; struct Env { @@ -232,13 +243,13 @@ async fn given_windows_machine_should_relay_commands_through_pu_daemon_proxy() { let log = env.ssh_log(); assert!( log.contains( - "-T -o BatchMode=yes -o ControlMaster=no -o ControlPath=none fakehost uname -s" + "-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none fakehost uname -s" ), "{log}" ); assert!( log.contains( - "-T -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ControlMaster=no -o ControlPath=none fakehost pu daemon proxy" + "-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ControlMaster=no -o ControlPath=none fakehost pu daemon proxy" ), "{log}" ); @@ -434,3 +445,36 @@ async fn given_localhost_sshd_should_add_probe_and_target_the_machine() { assert!(stderr.contains("daemon not running on local"), "{stderr}"); } } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_windows_machine_doctor_should_log_in_and_skip_unix_checks() { + // given + let env = Env::new(); + env.add_studio().await; + + // when + let report = env + .ok_json(&["doctor", "--machine", "studio", "--json"], &[]) + .await; + + // then + assert_eq!(report["reachable"], true, "{report}"); + let findings = report["findings"].as_array().unwrap(); + let status = |check: &str| { + findings + .iter() + .find(|f| f["check"] == check) + .map(|f| f["status"].clone()) + .unwrap_or_else(|| panic!("no {check} in {report}")) + }; + assert_eq!(status("ssh client"), "ok"); + assert_eq!(status("login"), "ok"); + assert_eq!(status("machine checks"), "skipped"); + let log = env.ssh_log(); + assert!( + log.contains( + "-T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none fakehost true" + ), + "{log}" + ); +} From 1b38cc4f3a42d93cc7a7ba299401191b07e7aef8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:57:40 +0000 Subject: [PATCH 06/21] feat(transport): multiplexed SSH relay, `pu daemon proxy --mux` (MACH-013) Add pu_transport::mux: a strict frame codec, the relay (`serve`, one daemon connection per channel, credit-based flow control, ping/pong, 60 s idle exit) and the client (`MuxClient` with per-channel `MuxReader`/`MuxWriter`, 5 s pings, two missed pings end the session). Platform-independent so the Windows app can use the client. `pu daemon proxy --mux` serves a session on stdin/stdout against the daemon socket; exit 0 on stdin close, 1 on a version or protocol error. Spec: channel ids now strictly increase, so "never opened" is any id above the highest seen and neither side remembers closed ids; frames of any type for an already-closed channel (including a late open_ok for an abandoned open) are ignored; ping/pong/window may jump queued data. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- crates/pu-cli/src/commands/daemon.rs | 10 +- crates/pu-cli/src/commands/daemon_proxy.rs | 26 +- crates/pu-cli/src/main.rs | 2 +- crates/pu-cli/tests/daemon_proxy.rs | 148 +++ crates/pu-transport/src/lib.rs | 2 + crates/pu-transport/src/mux/client.rs | 851 +++++++++++++++ crates/pu-transport/src/mux/frame.rs | 510 +++++++++ crates/pu-transport/src/mux/mod.rs | 153 +++ crates/pu-transport/src/mux/server.rs | 498 +++++++++ crates/pu-transport/src/mux/tests.rs | 1114 ++++++++++++++++++++ docs/guide/cli-reference.md | 3 + docs/product/cli.md | 8 +- docs/product/machines.md | 6 +- 13 files changed, 3321 insertions(+), 10 deletions(-) create mode 100644 crates/pu-transport/src/mux/client.rs create mode 100644 crates/pu-transport/src/mux/frame.rs create mode 100644 crates/pu-transport/src/mux/mod.rs create mode 100644 crates/pu-transport/src/mux/server.rs create mode 100644 crates/pu-transport/src/mux/tests.rs diff --git a/crates/pu-cli/src/commands/daemon.rs b/crates/pu-cli/src/commands/daemon.rs index f8886897..0d196943 100644 --- a/crates/pu-cli/src/commands/daemon.rs +++ b/crates/pu-cli/src/commands/daemon.rs @@ -33,7 +33,12 @@ pub enum DaemonAction { Uninstall, /// Relay stdin/stdout to the daemon socket for SSH clients; never starts /// the daemon - Proxy, + Proxy { + /// Carry many daemon connections as channels of one multiplexed + /// session (`PUMUX 1` handshake, then frames), for the Windows app + #[arg(long)] + mux: bool, + }, } pub async fn run(socket: &Path, custom_socket: bool, action: DaemonAction) -> Result<(), CliError> { @@ -70,7 +75,8 @@ pub async fn run(socket: &Path, custom_socket: bool, action: DaemonAction) -> Re } Ok(()) } - DaemonAction::Proxy => daemon_proxy::run(socket).await, + DaemonAction::Proxy { mux: false } => daemon_proxy::run(socket).await, + DaemonAction::Proxy { mux: true } => daemon_proxy::run_mux(socket).await, } } diff --git a/crates/pu-cli/src/commands/daemon_proxy.rs b/crates/pu-cli/src/commands/daemon_proxy.rs index ffe0b851..a449c6a0 100644 --- a/crates/pu-cli/src/commands/daemon_proxy.rs +++ b/crates/pu-cli/src/commands/daemon_proxy.rs @@ -1,10 +1,14 @@ //! `pu daemon proxy`: one daemon connection over stdin/stdout, for SSH exec //! channels (the iPad cannot forward a Unix socket). Stdout carries only //! daemon bytes; diagnostics go to stderr. Never starts a daemon (MACH-003). +//! +//! `pu daemon proxy --mux` carries many daemon connections as channels of one +//! multiplexed session (`pu_transport::mux`, MACH-013); stdout carries only +//! the hello line and frames. use std::path::Path; -use pu_transport::Stream; +use pu_transport::{Stream, mux}; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use crate::error::CliError; @@ -24,6 +28,26 @@ pub async fn run(socket: &Path) -> Result<(), CliError> { relay(stream, tokio::io::stdin(), tokio::io::stdout()).await } +/// Serve one multiplexed session on stdin/stdout, opening a daemon +/// connection per channel. Ends when stdin closes; a bad handshake, a +/// protocol error or 60 s with nothing received is an error (exit 1). +pub async fn run_mux(socket: &Path) -> Result<(), CliError> { + let endpoint = pu_transport::Endpoint::for_socket(socket) + .map_err(|e| CliError::Other(format!("pu daemon proxy --mux: {e}")))?; + let connect = move || { + let endpoint = endpoint.clone(); + async move { pu_transport::connect(&endpoint).await } + }; + mux::serve( + tokio::io::stdin(), + tokio::io::stdout(), + connect, + mux::ServerConfig::default(), + ) + .await + .map_err(|e| CliError::Other(format!("pu daemon proxy --mux: {e}"))) +} + async fn connect(socket: &Path) -> Result { crate::client::connect(socket).await.map_err(|e| { CliError::Other(format!( diff --git a/crates/pu-cli/src/main.rs b/crates/pu-cli/src/main.rs index 10796eb9..9c24f940 100644 --- a/crates/pu-cli/src/main.rs +++ b/crates/pu-cli/src/main.rs @@ -855,7 +855,7 @@ async fn async_main() { let proxy = matches!( cli.command, Commands::Daemon { - action: commands::daemon::DaemonAction::Proxy + action: commands::daemon::DaemonAction::Proxy { .. } } ); diff --git a/crates/pu-cli/tests/daemon_proxy.rs b/crates/pu-cli/tests/daemon_proxy.rs index bbef1d5c..2473b994 100644 --- a/crates/pu-cli/tests/daemon_proxy.rs +++ b/crates/pu-cli/tests/daemon_proxy.rs @@ -222,3 +222,151 @@ async fn given_real_daemon_should_relay_its_health_report() { assert!(output.status.success()); assert_eq!(output.stderr, b""); } + +// --- `pu daemon proxy --mux` ------------------------------------------------- + +use pu_transport::mux::{ClientConfig, MuxClient, OpenError}; + +fn spawn_engine(env: &Env) { + let registry = pu_core::paths::project_registry_path(&env.socket); + let engine = pu_engine::engine::Engine::with_project_registry(registry).unwrap(); + let server = pu_engine::ipc_server::IpcServer::bind(&env.socket, engine).unwrap(); + tokio::spawn(async move { + server.run().await.unwrap(); + }); +} + +fn spawn_mux(env: &Env) -> tokio::process::Child { + let mut command = env.proxy(&["--socket", env.socket.to_str().unwrap()]); + command.arg("--mux").kill_on_drop(true); + command.spawn().unwrap() +} + +async fn mux_session(child: &mut tokio::process::Child) -> MuxClient { + let stdout = child.stdout.take().unwrap(); + let stdin = child.stdin.take().unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + MuxClient::handshake(stdout, stdin, ClientConfig::default()), + ) + .await + .expect("no mux hello") + .unwrap() +} + +#[tokio::test] +async fn given_real_daemon_mux_should_carry_health_on_several_channels() { + // given + let env = Env::new(); + spawn_engine(&env); + let mut child = spawn_mux(&env); + let client = mux_session(&mut child).await; + + // when: several channels open at once, each sending health + let mut channels = Vec::new(); + for _ in 0..4 { + channels.push(client.open().await.unwrap()); + } + for (_, writer) in &mut channels { + writer.write_all(b"{\"type\":\"health\"}\n").await.unwrap(); + } + let mut replies = Vec::new(); + for (reader, _) in &mut channels { + let mut line = String::new(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + BufReader::new(reader).read_line(&mut line), + ) + .await + .expect("no health report") + .unwrap(); + replies.push(line); + } + + // then + assert_eq!(replies.len(), 4); + for line in &replies { + let reply: Response = serde_json::from_str(line.trim_end()).unwrap(); + assert!( + matches!(reply, Response::HealthReport { protocol_version, .. } if protocol_version == PROTOCOL_VERSION), + "{line}" + ); + } + drop(channels); + client.close(); + let output = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait_with_output()) + .await + .expect("relay did not exit after stdin closed") + .unwrap(); + assert_eq!(output.status.code(), Some(0)); + assert_eq!(output.stderr, b""); +} + +#[tokio::test] +async fn given_no_daemon_mux_should_refuse_channels_and_not_start_one() { + // given + let env = Env::new(); + let mut child = spawn_mux(&env); + let client = mux_session(&mut child).await; + + // when + let first = client.open().await; + let second = client.open().await; + + // then + assert!( + matches!(&first, Err(OpenError::NoDaemon(_))), + "{:?}", + first.err() + ); + assert!(matches!(second, Err(OpenError::NoDaemon(_)))); + assert!(!client.is_closed(), "the relay ended the session"); + client.close(); + let output = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait_with_output()) + .await + .expect("relay did not exit") + .unwrap(); + assert_eq!(output.status.code(), Some(0)); + assert!(!env.engine_marker().exists(), "relay started a daemon"); + assert!(!env.socket.exists()); +} + +#[tokio::test] +async fn given_wrong_client_version_mux_should_exit_1_with_only_hello_on_stdout() { + // given + let env = Env::new(); + let mut child = spawn_mux(&env); + + // when + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(b"PUMUX 2\n").await.unwrap(); + let output = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait_with_output()) + .await + .expect("relay did not exit") + .unwrap(); + + // then + assert_eq!(output.status.code(), Some(1)); + assert_eq!(output.stdout, b"PUMUX 1\n"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("version 2"), "{stderr}"); +} + +#[tokio::test] +async fn given_stdin_closed_after_hello_mux_should_exit_0() { + // given + let env = Env::new(); + let mut child = spawn_mux(&env); + + // when + drop(child.stdin.take()); + let output = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait_with_output()) + .await + .expect("relay did not exit") + .unwrap(); + + // then + assert_eq!(output.status.code(), Some(0)); + assert_eq!(output.stdout, b"PUMUX 1\n"); + assert_eq!(output.stderr, b""); +} diff --git a/crates/pu-transport/src/lib.rs b/crates/pu-transport/src/lib.rs index 95a8c3a3..74aac749 100644 --- a/crates/pu-transport/src/lib.rs +++ b/crates/pu-transport/src/lib.rs @@ -20,6 +20,8 @@ use std::task::{Context, Poll}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +pub mod mux; + #[cfg(unix)] mod unix; #[cfg(unix)] diff --git a/crates/pu-transport/src/mux/client.rs b/crates/pu-transport/src/mux/client.rs new file mode 100644 index 00000000..51e0877f --- /dev/null +++ b/crates/pu-transport/src/mux/client.rs @@ -0,0 +1,851 @@ +//! The client side of the multiplexed relay: one session per machine, any +//! number of channels, each an `AsyncRead` + `AsyncWrite` pair that stands in +//! for one daemon connection. + +use std::collections::{HashMap, VecDeque}; +use std::fmt; +use std::io; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, ReadBuf}; +use tokio::sync::{oneshot, watch}; +use tokio::task::AbortHandle; +use tokio::time::Instant; + +use super::frame::{self, Frame, FrameError}; +use super::{DEFAULT_WINDOW, HELLO, Outbox, VERSION}; + +/// Client settings. [`Default`] is the production contract. +#[derive(Debug, Clone)] +pub struct ClientConfig { + /// How often to ping the relay (5 s). + pub ping_interval: Duration, + /// How long each ping may go unanswered before it counts as missed (10 s). + pub ping_timeout: Duration, + /// Consecutive missed pings that end the session (2). 0 is treated as 1. + pub missed_pings_allowed: u32, + /// Per-channel credit in each direction (256 KiB). A protocol constant: + /// it must equal the relay's [`super::ServerConfig::initial_window`]. + pub initial_window: u32, +} + +impl Default for ClientConfig { + fn default() -> Self { + Self { + ping_interval: Duration::from_secs(5), + ping_timeout: Duration::from_secs(10), + missed_pings_allowed: 2, + initial_window: DEFAULT_WINDOW, + } + } +} + +/// Why [`MuxClient::handshake`] failed. +#[derive(Debug)] +pub enum HandshakeError { + /// The far side does not speak this mux version: it ended before the + /// hello (a `pu` without `--mux` exits 2 on the unknown flag), or its + /// first line is not `PUMUX 1`. Fall back to the per-connection relay. + Unsupported(String), + /// Reading the hello or writing ours failed. + Io(io::Error), +} + +impl fmt::Display for HandshakeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + HandshakeError::Unsupported(m) => write!(f, "multiplexed relay unsupported: {m}"), + HandshakeError::Io(e) => write!(f, "mux handshake failed: {e}"), + } + } +} + +impl std::error::Error for HandshakeError {} + +/// Why a session ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CloseReason { + /// The relay's output ended (ssh exited, or the relay did). + Eof, + /// The relay stopped answering pings. + PingTimeout, + /// The relay broke the frame protocol. + Protocol(String), + /// Reading from or writing to the relay failed. + Io(String), + /// [`MuxClient::close`] was called, or every handle was dropped. + Closed, +} + +impl fmt::Display for CloseReason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CloseReason::Eof => f.write_str("the relay closed the connection"), + CloseReason::PingTimeout => f.write_str("the relay stopped answering pings"), + CloseReason::Protocol(m) => write!(f, "mux protocol error: {m}"), + CloseReason::Io(m) => write!(f, "relay i/o failed: {m}"), + CloseReason::Closed => f.write_str("the mux session was closed"), + } + } +} + +/// Why [`MuxClient::open`] failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OpenError { + /// No daemon answered on the machine (`open_fail` reason 1; the plain + /// relay's exit 69): report "daemon stopped". + NoDaemon(String), + /// The session holds its maximum of channels (`open_fail` reason 2). + TooManyChannels(String), + /// The relay refused for another reason (`open_fail` reason 3 or unknown). + Refused(String), + /// The session ended before or while opening. + SessionClosed(CloseReason), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoDaemon(m) => write!(f, "no daemon: {m}"), + OpenError::TooManyChannels(m) => write!(f, "too many channels: {m}"), + OpenError::Refused(m) => write!(f, "channel refused: {m}"), + OpenError::SessionClosed(r) => write!(f, "{r}"), + } + } +} + +impl std::error::Error for OpenError {} + +/// One multiplexed session, typically over one `ssh.exe` running +/// `pu daemon proxy --mux`. +/// +/// A cheap, cloneable handle (`Send + Sync`). Each [`open`](Self::open) gives +/// a fresh channel that behaves like one daemon connection. When the session +/// ends (link EOF or error, missed pings, protocol error, [`close`](Self::close), +/// or the last handle being dropped), every open channel's reads and writes +/// fail with an io error and [`closed`](Self::closed) resolves. Dropping the +/// last `MuxClient` handle closes the session even while channels are open. +/// +/// Must be created inside a Tokio runtime: the session runs on one spawned task. +#[derive(Clone)] +pub struct MuxClient { + handle: Arc, +} + +struct Handle { + inner: Arc, +} + +impl Drop for Handle { + fn drop(&mut self) { + self.inner.end(CloseReason::Closed); + } +} + +struct Inner { + out: Outbox, + window: u64, + grant_threshold: u64, + state: Mutex, + /// Pings sent since the last pong, oldest first: (sequence, sent at). + pings: Mutex>, + closed_tx: watch::Sender>, + driver: Mutex>, +} + +struct State { + next_id: u32, + channels: HashMap, + closed: Option, +} + +struct Entry { + chan: Arc, + /// Set until `open_ok` or `open_fail` arrives. + pending: Option>>, +} + +struct Chan { + id: u32, + state: Mutex, +} + +struct ChanState { + /// Received bytes not yet read; the first chunk is consumed from `offset`. + chunks: VecDeque>, + offset: usize, + /// Bytes the relay may still send before it needs more credit. + recv_window: u64, + /// Bytes read but not yet granted back. + pending_grant: u64, + /// Credit for sending to the relay. + send_credit: u64, + remote_eof: bool, + remote_closed: bool, + local_eof: bool, + /// The session ended while this channel was open. + failed: Option, + reader_alive: bool, + writer_alive: bool, + /// The channel has left the session (a `close` was sent or received). + closed: bool, + read_waker: Option, + write_waker: Option, +} + +impl ChanState { + fn wake_all(&mut self) { + if let Some(w) = self.read_waker.take() { + w.wake(); + } + if let Some(w) = self.write_waker.take() { + w.wake(); + } + } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl MuxClient { + /// Run the client side of the handshake over a fresh relay stream (the + /// relay's stdout as `read`, its stdin as `write`) and start the session. + /// + /// Reads the relay's hello, then writes `PUMUX 1\n`. There is no timeout + /// here; wrap the call in one (ssh's own connect timeout normally bounds + /// it). On [`HandshakeError::Unsupported`], fall back to the + /// per-connection relay. + pub async fn handshake( + read: R, + write: W, + config: ClientConfig, + ) -> Result + where + R: AsyncRead + Send + Unpin + 'static, + W: AsyncWrite + Send + Unpin + 'static, + { + let mut read = BufReader::new(read); + let line = super::read_hello_line(&mut read) + .await + .map_err(HandshakeError::Io)?; + let Some(line) = line else { + return Err(HandshakeError::Unsupported( + "the relay ended before its hello (its `pu` may predate --mux)".into(), + )); + }; + match super::parse_hello(&line) { + Some(VERSION) => {} + Some(n) => { + return Err(HandshakeError::Unsupported(format!( + "the relay speaks mux version {n}, this client speaks {VERSION}" + ))); + } + None => { + return Err(HandshakeError::Unsupported(format!( + "the relay's first line is {line:?}, not a mux hello" + ))); + } + } + let mut write = write; + write.write_all(HELLO).await.map_err(HandshakeError::Io)?; + write.flush().await.map_err(HandshakeError::Io)?; + + let (out, rx) = Outbox::new(); + let window = u64::from(config.initial_window); + let inner = Arc::new(Inner { + out, + window, + grant_threshold: (window / 4).max(1), + state: Mutex::new(State { + next_id: 1, + channels: HashMap::new(), + closed: None, + }), + pings: Mutex::new(VecDeque::new()), + closed_tx: watch::Sender::new(None), + driver: Mutex::new(None), + }); + let driver = tokio::spawn(drive(Arc::clone(&inner), read, write, rx, config)); + *lock(&inner.driver) = Some(driver.abort_handle()); + // The driver may already have ended (the relay hung up at once). + if inner.is_closed() { + driver.abort(); + } + Ok(MuxClient { + handle: Arc::new(Handle { inner }), + }) + } + + /// Open a channel: one daemon connection on the machine. Waits for the + /// relay's answer (it connects to the daemon first). Cancelling the + /// returned future closes the channel. + pub async fn open(&self) -> Result<(MuxReader, MuxWriter), OpenError> { + let inner = &self.handle.inner; + let (tx, rx) = oneshot::channel(); + let chan = { + let mut state = lock(&inner.state); + if let Some(reason) = &state.closed { + return Err(OpenError::SessionClosed(reason.clone())); + } + let id = state.next_id; + if id == u32::MAX { + return Err(OpenError::Refused( + "this session has used every channel id".into(), + )); + } + state.next_id += 1; + let chan = Arc::new(Chan { + id, + state: Mutex::new(ChanState { + chunks: VecDeque::new(), + offset: 0, + recv_window: inner.window, + pending_grant: 0, + send_credit: inner.window, + remote_eof: false, + remote_closed: false, + local_eof: false, + failed: None, + reader_alive: true, + writer_alive: true, + closed: false, + read_waker: None, + write_waker: None, + }), + }); + state.channels.insert( + id, + Entry { + chan: Arc::clone(&chan), + pending: Some(tx), + }, + ); + inner.out.send(Frame::Open { id }); + chan + }; + let mut guard = OpenGuard { + inner, + chan: &chan, + armed: true, + }; + let answer = rx.await; + guard.armed = false; + drop(guard); + match answer { + Ok(Ok(())) => Ok(( + MuxReader { + inner: Arc::clone(inner), + chan: Arc::clone(&chan), + }, + MuxWriter { + inner: Arc::clone(inner), + chan, + }, + )), + Ok(Err(e)) => Err(e), + Err(_) => Err(OpenError::SessionClosed( + lock(&inner.state) + .closed + .clone() + .unwrap_or(CloseReason::Closed), + )), + } + } + + /// True once the session has ended. + pub fn is_closed(&self) -> bool { + self.handle.inner.is_closed() + } + + /// Resolve once the session has ended, with why. + pub async fn closed(&self) -> CloseReason { + let mut rx = self.handle.inner.closed_tx.subscribe(); + match rx.wait_for(Option::is_some).await { + Ok(reason) => reason.clone().unwrap_or(CloseReason::Closed), + Err(_) => CloseReason::Closed, + } + } + + /// End the session now: fail every channel and drop the relay stream + /// (which closes the relay's stdin, so it exits). + pub fn close(&self) { + self.handle.inner.end(CloseReason::Closed); + } +} + +impl fmt::Debug for MuxClient { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MuxClient") + .field("closed", &lock(&self.handle.inner.state).closed) + .finish() + } +} + +/// Closes a channel whose `open` was cancelled before it finished. +struct OpenGuard<'a> { + inner: &'a Arc, + chan: &'a Arc, + armed: bool, +} + +impl Drop for OpenGuard<'_> { + fn drop(&mut self) { + if !self.armed { + return; + } + lock(&self.chan.state).closed = true; + let removed = lock(&self.inner.state) + .channels + .remove(&self.chan.id) + .is_some(); + if removed { + // Any open_ok still in flight then arrives for a closed id and is ignored. + self.inner.out.send(Frame::Close { id: self.chan.id }); + } + } +} + +impl Inner { + fn is_closed(&self) -> bool { + lock(&self.state).closed.is_some() + } + + /// End the session once: fail every channel and pending open, publish + /// the reason and stop the driver (dropping the relay stream). + fn end(&self, reason: CloseReason) { + let entries = { + let mut state = lock(&self.state); + if state.closed.is_some() { + return; + } + state.closed = Some(reason.clone()); + std::mem::take(&mut state.channels) + }; + for entry in entries.into_values() { + if let Some(pending) = entry.pending { + let _ = pending.send(Err(OpenError::SessionClosed(reason.clone()))); + } + let mut chan = lock(&entry.chan.state); + chan.failed = Some(reason.clone()); + chan.closed = true; + chan.wake_all(); + } + self.closed_tx.send_replace(Some(reason)); + if let Some(driver) = lock(&self.driver).take() { + driver.abort(); + } + } + + /// The open channel `id`, `None` for one that already closed (a frame + /// that was in flight), or a protocol error for an id never opened or + /// still waiting for `open_ok`. + fn open_channel(&self, id: u32) -> Result>, String> { + let state = lock(&self.state); + match state.channels.get(&id) { + Some(entry) if entry.pending.is_some() => { + Err(format!("frame for channel {id} before its open_ok")) + } + Some(entry) => Ok(Some(Arc::clone(&entry.chan))), + None => Self::unknown(&state, id).map(|()| None), + } + } + + fn unknown(state: &State, id: u32) -> Result<(), String> { + if id != 0 && id < state.next_id { + Ok(()) + } else { + Err(format!("frame for channel {id}, which was never opened")) + } + } + + /// Apply one relay frame. + fn dispatch(&self, frame: Frame) -> Result<(), String> { + match frame { + Frame::Ping { data } => self.out.send(Frame::Pong { data }), + Frame::Pong { data } => { + let seq = u64::from_be_bytes(data); + let mut pings = lock(&self.pings); + if let Some(at) = pings.iter().position(|(s, _)| *s == seq) { + pings.drain(..=at); + } + } + Frame::Open { .. } => return Err("the relay sent open".into()), + Frame::OpenOk { id } => { + let mut state = lock(&self.state); + match state.channels.get_mut(&id) { + Some(entry) => match entry.pending.take() { + Some(pending) => { + let _ = pending.send(Ok(())); + } + None => return Err(format!("second open_ok for channel {id}")), + }, + None => Self::unknown(&state, id)?, + } + } + Frame::OpenFail { + id, + reason, + message, + } => { + let mut state = lock(&self.state); + let Some(entry) = state.channels.get_mut(&id) else { + return Self::unknown(&state, id); + }; + let Some(pending) = entry.pending.take() else { + return Err(format!("open_fail for open channel {id}")); + }; + state.channels.remove(&id); + let error = match reason { + frame::REASON_NO_DAEMON => OpenError::NoDaemon(message), + frame::REASON_TOO_MANY_CHANNELS => OpenError::TooManyChannels(message), + _ => OpenError::Refused(message), + }; + let _ = pending.send(Err(error)); + } + Frame::Data { id, bytes } => { + let Some(chan) = self.open_channel(id)? else { + return Ok(()); + }; + let mut cs = lock(&chan.state); + if cs.remote_eof { + return Err(format!("data on channel {id} after its eof")); + } + let len = bytes.len() as u64; + if len > cs.recv_window { + return Err(format!( + "channel {id} sent {len} bytes with only {} of window left", + cs.recv_window + )); + } + if cs.closed { + return Ok(()); + } + if cs.reader_alive { + cs.recv_window -= len; + cs.chunks.push_back(bytes); + if let Some(w) = cs.read_waker.take() { + w.wake(); + } + } else { + // Nobody will read it: discard, and keep the sender moving. + self.out.send(Frame::Window { + id, + credit: len as u32, + }); + } + } + Frame::Eof { id } => { + let Some(chan) = self.open_channel(id)? else { + return Ok(()); + }; + let mut cs = lock(&chan.state); + if cs.remote_eof { + return Err(format!("second eof on channel {id}")); + } + cs.remote_eof = true; + if let Some(w) = cs.read_waker.take() { + w.wake(); + } + } + Frame::Close { id } => { + let Some(chan) = self.open_channel(id)? else { + return Ok(()); + }; + lock(&self.state).channels.remove(&id); + let mut cs = lock(&chan.state); + cs.remote_closed = true; + cs.wake_all(); + if !cs.closed { + cs.closed = true; + self.out.send(Frame::Close { id }); + } + } + Frame::Window { id, credit } => { + let Some(chan) = self.open_channel(id)? else { + return Ok(()); + }; + let mut cs = lock(&chan.state); + cs.send_credit = cs.send_credit.saturating_add(u64::from(credit)); + if let Some(w) = cs.write_waker.take() { + w.wake(); + } + } + } + Ok(()) + } + + /// A half was dropped: once both are, the channel leaves the session. + fn release(&self, chan: &Chan, mut cs: std::sync::MutexGuard<'_, ChanState>) { + if cs.reader_alive || cs.writer_alive || cs.closed { + return; + } + cs.closed = true; + drop(cs); + lock(&self.state).channels.remove(&chan.id); + self.out.send(Frame::Close { id: chan.id }); + } +} + +/// The session task: read frames, write frames, ping. Whichever stops first +/// ends the session. +async fn drive( + inner: Arc, + mut read: BufReader, + write: W, + rx: super::OutboxRx, + config: ClientConfig, +) where + R: AsyncRead + Send + Unpin + 'static, + W: AsyncWrite + Send + Unpin + 'static, +{ + let reading = async { + loop { + match frame::read_frame(&mut read).await { + Ok(Some(frame)) => { + if let Err(m) = inner.dispatch(frame) { + return CloseReason::Protocol(m); + } + } + Ok(None) => return CloseReason::Eof, + Err(FrameError::Protocol(m)) => return CloseReason::Protocol(m), + Err(FrameError::Io(e)) => return CloseReason::Io(e.to_string()), + } + } + }; + let writing = async { + match super::write_loop(rx, write).await { + Ok(()) => CloseReason::Closed, + Err(e) => CloseReason::Io(e.to_string()), + } + }; + let reason = tokio::select! { + r = reading => r, + r = writing => r, + r = ping_loop(&inner, &config) => r, + }; + inner.end(reason); +} + +/// Ping every `ping_interval`; end the session once `missed_pings_allowed` +/// pings in a row have each gone `ping_timeout` without a pong. +async fn ping_loop(inner: &Inner, config: &ClientConfig) -> CloseReason { + let allowed = config.missed_pings_allowed.max(1) as usize; + let mut seq = 0u64; + let mut next_ping = Instant::now() + config.ping_interval; + loop { + // Every outstanding ping was sent after the last pong, so the + // session is dead once the `allowed`-th oldest has expired. + let deadline = |pings: &VecDeque<(u64, Instant)>| { + pings + .get(allowed - 1) + .map(|(_, sent)| *sent + config.ping_timeout) + }; + let dead_at = deadline(&lock(&inner.pings)); + let wake = dead_at.map_or(next_ping, |d| d.min(next_ping)); + tokio::time::sleep_until(wake).await; + let now = Instant::now(); + let mut pings = lock(&inner.pings); + if deadline(&pings).is_some_and(|d| d <= now) { + return CloseReason::PingTimeout; + } + if next_ping <= now { + pings.push_back((seq, now)); + inner.out.send(Frame::Ping { + data: seq.to_be_bytes(), + }); + seq += 1; + next_ping += config.ping_interval; + } + } +} + +/// The read half of a channel. EOF once the relay sends `eof` (the daemon +/// closed); an io error once the channel is reset or the session ends. +pub struct MuxReader { + inner: Arc, + chan: Arc, +} + +/// The write half of a channel. `poll_shutdown` sends `eof` (half-close); +/// writes wait for window credit, so a stalled daemon stalls only this +/// channel. +pub struct MuxWriter { + inner: Arc, + chan: Arc, +} + +impl MuxReader { + /// The channel id (nonzero, unique within the session). + pub fn id(&self) -> u32 { + self.chan.id + } +} + +impl MuxWriter { + /// The channel id (nonzero, unique within the session). + pub fn id(&self) -> u32 { + self.chan.id + } +} + +fn session_error(reason: &CloseReason) -> io::Error { + io::Error::new( + io::ErrorKind::ConnectionAborted, + format!("mux session ended: {reason}"), + ) +} + +impl AsyncRead for MuxReader { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let this = &*self; + let mut cs = lock(&this.chan.state); + if buf.remaining() == 0 { + return Poll::Ready(Ok(())); + } + if !cs.chunks.is_empty() { + let mut copied = 0usize; + while buf.remaining() > 0 { + let offset = cs.offset; + let Some(front) = cs.chunks.front() else { + break; + }; + let n = (front.len() - offset).min(buf.remaining()); + buf.put_slice(&front[offset..offset + n]); + copied += n; + if offset + n == front.len() { + cs.chunks.pop_front(); + cs.offset = 0; + } else { + cs.offset += n; + } + } + cs.pending_grant += copied as u64; + if cs.pending_grant >= this.inner.grant_threshold && !cs.closed { + let credit = cs.pending_grant; + cs.pending_grant = 0; + cs.recv_window += credit; + this.inner.out.send(Frame::Window { + id: this.chan.id, + credit: credit as u32, + }); + } + return Poll::Ready(Ok(())); + } + if cs.remote_eof { + return Poll::Ready(Ok(())); + } + if let Some(reason) = &cs.failed { + return Poll::Ready(Err(session_error(reason))); + } + if cs.remote_closed { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "the relay closed the channel", + ))); + } + cs.read_waker = Some(cx.waker().clone()); + Poll::Pending + } +} + +impl AsyncWrite for MuxWriter { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let this = &*self; + let mut cs = lock(&this.chan.state); + if let Some(reason) = &cs.failed { + return Poll::Ready(Err(session_error(reason))); + } + if cs.remote_closed || cs.closed { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "the channel is closed", + ))); + } + if cs.local_eof { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "write after shutdown", + ))); + } + if buf.is_empty() { + return Poll::Ready(Ok(0)); + } + if cs.send_credit == 0 { + cs.write_waker = Some(cx.waker().clone()); + return Poll::Pending; + } + let n = buf + .len() + .min(frame::MAX_PAYLOAD) + .min(usize::try_from(cs.send_credit).unwrap_or(usize::MAX)); + cs.send_credit -= n as u64; + this.inner.out.send(Frame::Data { + id: this.chan.id, + bytes: buf[..n].to_vec(), + }); + Poll::Ready(Ok(n)) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let cs = lock(&self.chan.state); + match &cs.failed { + Some(reason) => Poll::Ready(Err(session_error(reason))), + None => Poll::Ready(Ok(())), + } + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let this = &*self; + let mut cs = lock(&this.chan.state); + if let Some(reason) = &cs.failed { + return Poll::Ready(Err(session_error(reason))); + } + if !cs.local_eof && !cs.closed { + cs.local_eof = true; + this.inner.out.send(Frame::Eof { id: this.chan.id }); + } + Poll::Ready(Ok(())) + } +} + +impl Drop for MuxReader { + fn drop(&mut self) { + let mut cs = lock(&self.chan.state); + cs.reader_alive = false; + // Unread bytes are discarded; credit them so a writer-only user does + // not stall the daemon. + let unread: u64 = cs.chunks.iter().map(|c| c.len() as u64).sum::() - cs.offset as u64; + cs.chunks.clear(); + cs.offset = 0; + let credit = unread + cs.pending_grant; + cs.pending_grant = 0; + if credit > 0 && !cs.closed && cs.writer_alive { + cs.recv_window += credit; + self.inner.out.send(Frame::Window { + id: self.chan.id, + credit: credit as u32, + }); + } + self.inner.release(&self.chan, cs); + } +} + +impl Drop for MuxWriter { + fn drop(&mut self) { + let mut cs = lock(&self.chan.state); + cs.writer_alive = false; + self.inner.release(&self.chan, cs); + } +} diff --git a/crates/pu-transport/src/mux/frame.rs b/crates/pu-transport/src/mux/frame.rs new file mode 100644 index 00000000..d2b783f6 --- /dev/null +++ b/crates/pu-transport/src/mux/frame.rs @@ -0,0 +1,510 @@ +//! Frame codec for the multiplexed relay (`docs/product/machines.md`, +//! Multiplexed relay, MACH-013). +//! +//! A frame is a 4-byte big-endian length (of everything after it), a 1-byte +//! type, a 4-byte big-endian channel id and a payload. Decoding is strict: +//! a length outside `5..=65541`, an unknown type, a payload of the wrong size +//! for its type, or a channel id of the wrong kind is a protocol error. + +use std::fmt; +use std::io; + +use tokio::io::{AsyncRead, AsyncReadExt}; + +/// Largest `data` payload (64 KiB). +pub const MAX_PAYLOAD: usize = 64 * 1024; +/// Smallest frame length: type plus channel id. +pub const MIN_LEN: u32 = 5; +/// Largest frame length: type, channel id and a full payload. +pub const MAX_LEN: u32 = MIN_LEN + MAX_PAYLOAD as u32; + +pub const TYPE_OPEN: u8 = 1; +pub const TYPE_OPEN_OK: u8 = 2; +pub const TYPE_OPEN_FAIL: u8 = 3; +pub const TYPE_DATA: u8 = 4; +pub const TYPE_EOF: u8 = 5; +pub const TYPE_CLOSE: u8 = 6; +pub const TYPE_WINDOW: u8 = 7; +pub const TYPE_PING: u8 = 8; +pub const TYPE_PONG: u8 = 9; + +/// `open_fail` reason: no daemon answered (the plain relay's exit 69). +pub const REASON_NO_DAEMON: u8 = 1; +/// `open_fail` reason: the session already holds its maximum of channels. +pub const REASON_TOO_MANY_CHANNELS: u8 = 2; +/// `open_fail` reason: anything else. +pub const REASON_OTHER: u8 = 3; + +/// One decoded frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Frame { + Open { + id: u32, + }, + OpenOk { + id: u32, + }, + OpenFail { + id: u32, + reason: u8, + message: String, + }, + Data { + id: u32, + bytes: Vec, + }, + Eof { + id: u32, + }, + Close { + id: u32, + }, + Window { + id: u32, + credit: u32, + }, + Ping { + data: [u8; 8], + }, + Pong { + data: [u8; 8], + }, +} + +/// Why a frame could not be read. +#[derive(Debug)] +pub enum FrameError { + /// The stream failed, or ended inside a frame. + Io(io::Error), + /// The bytes are not a valid frame. + Protocol(String), +} + +impl fmt::Display for FrameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrameError::Io(e) => write!(f, "{e}"), + FrameError::Protocol(m) => write!(f, "protocol error: {m}"), + } + } +} + +impl std::error::Error for FrameError {} + +fn protocol(message: impl Into) -> FrameError { + FrameError::Protocol(message.into()) +} + +impl Frame { + /// The frame's type byte. + pub fn kind(&self) -> u8 { + match self { + Frame::Open { .. } => TYPE_OPEN, + Frame::OpenOk { .. } => TYPE_OPEN_OK, + Frame::OpenFail { .. } => TYPE_OPEN_FAIL, + Frame::Data { .. } => TYPE_DATA, + Frame::Eof { .. } => TYPE_EOF, + Frame::Close { .. } => TYPE_CLOSE, + Frame::Window { .. } => TYPE_WINDOW, + Frame::Ping { .. } => TYPE_PING, + Frame::Pong { .. } => TYPE_PONG, + } + } + + /// The frame's channel id (0 for `ping` and `pong`). + pub fn channel(&self) -> u32 { + match self { + Frame::Open { id } + | Frame::OpenOk { id } + | Frame::OpenFail { id, .. } + | Frame::Data { id, .. } + | Frame::Eof { id } + | Frame::Close { id } + | Frame::Window { id, .. } => *id, + Frame::Ping { .. } | Frame::Pong { .. } => 0, + } + } + + /// Append the encoded frame to `out`. An `open_fail` message is cut at a + /// character boundary to fit; `data` must hold 1 – 64 KiB. + pub fn encode(&self, out: &mut Vec) { + let start = out.len(); + out.extend_from_slice(&[0; 4]); + out.push(self.kind()); + out.extend_from_slice(&self.channel().to_be_bytes()); + match self { + Frame::OpenFail { + reason, message, .. + } => { + out.push(*reason); + let mut end = message.len().min(MAX_PAYLOAD - 1); + while !message.is_char_boundary(end) { + end -= 1; + } + out.extend_from_slice(&message.as_bytes()[..end]); + } + Frame::Data { bytes, .. } => { + debug_assert!(!bytes.is_empty() && bytes.len() <= MAX_PAYLOAD); + out.extend_from_slice(bytes); + } + Frame::Window { credit, .. } => out.extend_from_slice(&credit.to_be_bytes()), + Frame::Ping { data } | Frame::Pong { data } => out.extend_from_slice(data), + Frame::Open { .. } | Frame::OpenOk { .. } | Frame::Eof { .. } | Frame::Close { .. } => { + } + } + let len = (out.len() - start - 4) as u32; + out[start..start + 4].copy_from_slice(&len.to_be_bytes()); + } + + /// The encoded frame. + pub fn to_bytes(&self) -> Vec { + let mut out = Vec::new(); + self.encode(&mut out); + out + } + + /// Decode a frame body: everything after the length prefix. + pub fn decode(body: &[u8]) -> Result { + check_len(body.len() as u64)?; + let kind = body[0]; + let id = u32::from_be_bytes([body[1], body[2], body[3], body[4]]); + let payload = &body[5..]; + let need_channel = || { + if id == 0 { + Err(protocol(format!("frame type {kind} on channel 0"))) + } else { + Ok(()) + } + }; + let need_empty = || { + if payload.is_empty() { + Ok(()) + } else { + Err(protocol(format!( + "frame type {kind} carries {} payload bytes, expected none", + payload.len() + ))) + } + }; + let eight = || -> Result<[u8; 8], FrameError> { + if id != 0 { + return Err(protocol(format!("frame type {kind} on channel {id}"))); + } + payload.try_into().map_err(|_| { + protocol(format!( + "frame type {kind} carries {} payload bytes, expected 8", + payload.len() + )) + }) + }; + match kind { + TYPE_OPEN | TYPE_OPEN_OK | TYPE_EOF | TYPE_CLOSE => { + need_channel()?; + need_empty()?; + Ok(match kind { + TYPE_OPEN => Frame::Open { id }, + TYPE_OPEN_OK => Frame::OpenOk { id }, + TYPE_EOF => Frame::Eof { id }, + _ => Frame::Close { id }, + }) + } + TYPE_OPEN_FAIL => { + need_channel()?; + let Some((&reason, message)) = payload.split_first() else { + return Err(protocol("open_fail without a reason")); + }; + Ok(Frame::OpenFail { + id, + reason, + message: String::from_utf8_lossy(message).into_owned(), + }) + } + TYPE_DATA => { + need_channel()?; + if payload.is_empty() { + return Err(protocol("empty data frame")); + } + Ok(Frame::Data { + id, + bytes: payload.to_vec(), + }) + } + TYPE_WINDOW => { + need_channel()?; + let credit: [u8; 4] = payload.try_into().map_err(|_| { + protocol(format!( + "window frame carries {} payload bytes, expected 4", + payload.len() + )) + })?; + Ok(Frame::Window { + id, + credit: u32::from_be_bytes(credit), + }) + } + TYPE_PING => Ok(Frame::Ping { data: eight()? }), + TYPE_PONG => Ok(Frame::Pong { data: eight()? }), + other => Err(protocol(format!("unknown frame type {other}"))), + } + } +} + +fn check_len(len: u64) -> Result<(), FrameError> { + if len < u64::from(MIN_LEN) || len > u64::from(MAX_LEN) { + return Err(protocol(format!( + "frame length {len} outside {MIN_LEN}..={MAX_LEN}" + ))); + } + Ok(()) +} + +/// Read one frame. `Ok(None)` is a clean end of stream at a frame boundary; +/// a stream ending inside a frame is an `UnexpectedEof` io error. The length +/// is checked before the body is read, so a bad length never allocates. +pub async fn read_frame(read: &mut R) -> Result, FrameError> { + let mut len = [0u8; 4]; + let first = read.read(&mut len).await.map_err(FrameError::Io)?; + if first == 0 { + return Ok(None); + } + read.read_exact(&mut len[first..]) + .await + .map_err(FrameError::Io)?; + let len = u32::from_be_bytes(len); + check_len(u64::from(len))?; + let mut body = vec![0u8; len as usize]; + read.read_exact(&mut body).await.map_err(FrameError::Io)?; + Frame::decode(&body).map(Some) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all_types() -> Vec { + vec![ + Frame::Open { id: 1 }, + Frame::OpenOk { id: 2 }, + Frame::OpenFail { + id: 3, + reason: REASON_NO_DAEMON, + message: "no daemon at /x — é".into(), + }, + Frame::Data { + id: u32::MAX, + bytes: vec![7; MAX_PAYLOAD], + }, + Frame::Data { + id: 4, + bytes: vec![0], + }, + Frame::Eof { id: 5 }, + Frame::Close { id: 6 }, + Frame::Window { + id: 7, + credit: 256 * 1024, + }, + Frame::Ping { + data: [1, 2, 3, 4, 5, 6, 7, 8], + }, + Frame::Pong { data: [9; 8] }, + ] + } + + fn with_len(body: &[u8]) -> Vec { + let mut out = (body.len() as u32).to_be_bytes().to_vec(); + out.extend_from_slice(body); + out + } + + async fn read_one(bytes: &[u8]) -> Result, FrameError> { + let mut r = bytes; + read_frame(&mut r).await + } + + #[tokio::test] + async fn given_every_frame_type_should_round_trip() { + for frame in all_types() { + // given + let bytes = frame.to_bytes(); + + // when + let decoded = read_one(&bytes).await.unwrap(); + + // then + assert_eq!(decoded, Some(frame)); + } + } + + #[tokio::test] + async fn given_frames_back_to_back_should_read_each_then_clean_eof() { + // given + let mut bytes = Vec::new(); + for frame in all_types() { + frame.encode(&mut bytes); + } + let mut r = &bytes[..]; + + // when + let mut decoded = Vec::new(); + while let Some(frame) = read_frame(&mut r).await.unwrap() { + decoded.push(frame); + } + + // then + assert_eq!(decoded, all_types()); + } + + #[test] + fn given_frame_should_encode_big_endian_header() { + // given + let frame = Frame::Window { + id: 0x0102_0304, + credit: 0x0A0B_0C0D, + }; + + // when + let bytes = frame.to_bytes(); + + // then + assert_eq!( + bytes, + vec![0, 0, 0, 9, 7, 1, 2, 3, 4, 0x0A, 0x0B, 0x0C, 0x0D] + ); + } + + #[tokio::test] + async fn given_length_below_five_should_be_a_protocol_error() { + for len in 0u32..5 { + // given + let mut bytes = len.to_be_bytes().to_vec(); + bytes.extend_from_slice(&[TYPE_OPEN, 0, 0, 0, 1]); + + // when + let result = read_one(&bytes).await; + + // then + assert!( + matches!(result, Err(FrameError::Protocol(_))), + "len {len}: {result:?}" + ); + } + } + + #[tokio::test] + async fn given_length_above_65541_should_be_rejected_before_reading_body() { + // given: only the length, no body at all + let bytes = (MAX_LEN + 1).to_be_bytes(); + + // when + let result = read_one(&bytes).await; + + // then + assert!(matches!(result, Err(FrameError::Protocol(_))), "{result:?}"); + assert!(matches!( + read_one(&u32::MAX.to_be_bytes()).await, + Err(FrameError::Protocol(_)) + )); + } + + #[tokio::test] + async fn given_length_exactly_65541_should_decode() { + // given + let mut body = vec![TYPE_DATA, 0, 0, 0, 1]; + body.extend(std::iter::repeat_n(5u8, MAX_PAYLOAD)); + + // when + let result = read_one(&with_len(&body)).await; + + // then + assert!( + matches!(result, Ok(Some(Frame::Data { id: 1, ref bytes })) if bytes.len() == MAX_PAYLOAD) + ); + } + + #[tokio::test] + async fn given_unknown_type_should_be_a_protocol_error() { + for kind in [0u8, 10, 255] { + // given + let bytes = with_len(&[kind, 0, 0, 0, 1]); + + // when + let result = read_one(&bytes).await; + + // then + assert!( + matches!(result, Err(FrameError::Protocol(_))), + "type {kind}: {result:?}" + ); + } + } + + #[test] + fn given_wrong_payload_or_channel_should_be_a_protocol_error() { + // given + let bad: Vec> = vec![ + vec![TYPE_OPEN, 0, 0, 0, 0], // open on channel 0 + vec![TYPE_OPEN, 0, 0, 0, 1, 9], // open with payload + vec![TYPE_CLOSE, 0, 0, 0, 1, 9], // close with payload + vec![TYPE_DATA, 0, 0, 0, 1], // empty data + vec![TYPE_DATA, 0, 0, 0, 0, 1], // data on channel 0 + vec![TYPE_OPEN_FAIL, 0, 0, 0, 1], // open_fail without reason + vec![TYPE_WINDOW, 0, 0, 0, 1, 0, 0, 1], // short window + vec![TYPE_PING, 0, 0, 0, 0, 1, 2, 3], // short ping + vec![TYPE_PONG, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8], // pong on a channel + ]; + + for body in bad { + // when + let result = Frame::decode(&body); + + // then + assert!( + matches!(result, Err(FrameError::Protocol(_))), + "{body:?}: {result:?}" + ); + } + } + + #[tokio::test] + async fn given_stream_ending_inside_a_frame_should_be_unexpected_eof() { + // given + let bytes = Frame::Data { + id: 1, + bytes: vec![1; 100], + } + .to_bytes(); + + for cut in [2, 4, 7, 50] { + // when + let result = read_one(&bytes[..cut]).await; + + // then + assert!( + matches!(&result, Err(FrameError::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof), + "cut {cut}: {result:?}" + ); + } + } + + #[test] + fn given_oversized_open_fail_message_should_truncate_to_fit() { + // given + let frame = Frame::OpenFail { + id: 1, + reason: REASON_OTHER, + message: "é".repeat(MAX_PAYLOAD), + }; + + // when + let bytes = frame.to_bytes(); + + // then + let len = u32::from_be_bytes(bytes[..4].try_into().unwrap()); + assert!(len <= MAX_LEN); + assert!(matches!( + Frame::decode(&bytes[4..]), + Ok(Frame::OpenFail { message, .. }) if message.chars().all(|c| c == 'é') + )); + } +} diff --git a/crates/pu-transport/src/mux/mod.rs b/crates/pu-transport/src/mux/mod.rs new file mode 100644 index 00000000..a27bcb7e --- /dev/null +++ b/crates/pu-transport/src/mux/mod.rs @@ -0,0 +1,153 @@ +//! Multiplexed relay: many daemon connections as channels over one byte +//! stream (`pu daemon proxy --mux` over one long-lived `ssh.exe`). +//! +//! The wire contract is `docs/product/machines.md`, "Multiplexed relay +//! (MACH-013)". In short: +//! +//! - **Handshake.** The relay writes `PUMUX 1\n`; the client checks it and +//! writes `PUMUX 1\n` back. Frames follow in both directions. +//! - **Frames.** 4-byte big-endian length, 1-byte type, 4-byte big-endian +//! channel id, payload ([`frame`]). +//! - **Channels.** The client opens channels with increasing nonzero ids; +//! each is one daemon connection on the relay side. +//! - **Flow control.** 256 KiB of credit per channel and direction, granted +//! back with `window` frames as the receiver delivers bytes onward. +//! - **Liveness.** The client pings every 5 s and treats two pings in a row +//! unanswered within 10 s each as a dead session; the relay exits after +//! 60 s with nothing received. +//! +//! [`serve`] is the relay side, [`MuxClient`] the client side. Both are +//! generic over any `AsyncRead`/`AsyncWrite` pair and platform-independent. + +mod client; +pub mod frame; +mod server; + +#[cfg(test)] +mod tests; + +pub use client::{ + ClientConfig, CloseReason, HandshakeError, MuxClient, MuxReader, MuxWriter, OpenError, +}; +pub use server::{ServeError, ServerConfig, serve}; + +use std::io; + +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufWriter}; +use tokio::sync::mpsc; + +use frame::Frame; + +/// The protocol version this implementation speaks. +pub const VERSION: u32 = 1; +/// The hello line each side writes (`PUMUX 1\n`). +pub const HELLO: &[u8] = b"PUMUX 1\n"; +/// Credit each side starts with, per channel and direction (256 KiB). +pub const DEFAULT_WINDOW: u32 = 256 * 1024; +/// Most channels a session holds open at once (the daemon's own connection +/// limit, IPC-001). +pub const MAX_CHANNELS: usize = 1024; + +/// Longest hello line read before giving up on it. +const MAX_HELLO_LINE: usize = 64; + +/// Read the first line, byte by byte so nothing past it is consumed. +/// `Ok(None)` when the stream ends before a newline. A line longer than +/// [`MAX_HELLO_LINE`] is returned cut short (it cannot be a hello). +async fn read_hello_line(read: &mut R) -> io::Result> { + let mut line = Vec::new(); + loop { + let mut byte = [0u8; 1]; + if read.read(&mut byte).await? == 0 { + return Ok(None); + } + if byte[0] == b'\n' { + break; + } + line.push(byte[0]); + if line.len() >= MAX_HELLO_LINE { + break; + } + } + Ok(Some(String::from_utf8_lossy(&line).into_owned())) +} + +/// The version in a `PUMUX ` line (decimal digits only), if it is one. +fn parse_hello(line: &str) -> Option { + let digits = line.strip_prefix("PUMUX ")?; + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + digits.parse().ok() +} + +/// The sending side of a session's single writer. `ping`, `pong` and +/// `window` jump the queue (they carry no channel data, so reordering them is +/// safe), which keeps liveness and credit moving behind bulk data. Everything +/// else is sent in order, so a channel's `eof` and `close` follow its data. +#[derive(Clone)] +struct Outbox { + urgent: mpsc::UnboundedSender, + normal: mpsc::UnboundedSender, +} + +struct OutboxRx { + urgent: mpsc::UnboundedReceiver, + normal: mpsc::UnboundedReceiver, +} + +impl Outbox { + fn new() -> (Outbox, OutboxRx) { + let (urgent_tx, urgent_rx) = mpsc::unbounded_channel(); + let (normal_tx, normal_rx) = mpsc::unbounded_channel(); + ( + Outbox { + urgent: urgent_tx, + normal: normal_tx, + }, + OutboxRx { + urgent: urgent_rx, + normal: normal_rx, + }, + ) + } + + /// Queue a frame. Never blocks: `data` is bounded by the peer's window, + /// and control frames are small. + fn send(&self, frame: Frame) { + let queue = match frame { + Frame::Ping { .. } | Frame::Pong { .. } | Frame::Window { .. } => &self.urgent, + _ => &self.normal, + }; + // Fails only once the writer is gone, when the session is over. + let _ = queue.send(frame); + } +} + +/// Write queued frames until every sender is gone or the output fails, +/// flushing whenever the queues run dry. +async fn write_loop(mut rx: OutboxRx, output: W) -> io::Result<()> { + let mut output = BufWriter::with_capacity(frame::MAX_LEN as usize + 4, output); + let mut buf = Vec::with_capacity(frame::MAX_LEN as usize + 4); + loop { + let next = match rx.urgent.try_recv() { + Ok(frame) => Some(frame), + Err(_) => rx.normal.try_recv().ok(), + }; + let frame = match next { + Some(frame) => frame, + None => { + output.flush().await?; + tokio::select! { + biased; + Some(frame) = rx.urgent.recv() => frame, + Some(frame) = rx.normal.recv() => frame, + else => return Ok(()), + } + } + }; + buf.clear(); + frame.encode(&mut buf); + output.write_all(&buf).await?; + } +} diff --git a/crates/pu-transport/src/mux/server.rs b/crates/pu-transport/src/mux/server.rs new file mode 100644 index 00000000..dff4a5d7 --- /dev/null +++ b/crates/pu-transport/src/mux/server.rs @@ -0,0 +1,498 @@ +//! The relay side of the multiplexed relay: frames on stdin/stdout, one +//! daemon connection per channel. + +use std::collections::HashMap; +use std::fmt; +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadBuf}; +use tokio::sync::{Notify, mpsc}; +use tokio::task::AbortHandle; +use tokio::time::{Instant, Sleep}; + +use super::frame::{self, Frame, FrameError}; +use super::{DEFAULT_WINDOW, HELLO, MAX_CHANNELS, Outbox, VERSION}; + +/// Relay settings. [`Default`] is the production contract. +#[derive(Debug, Clone)] +pub struct ServerConfig { + /// Exit when nothing at all is received for this long (60 s), so a relay + /// left by a vanished client does not keep holding daemon connections. + pub idle_timeout: Duration, + /// Per-channel credit in each direction (256 KiB). Must equal the + /// client's [`super::ClientConfig::initial_window`]. + pub initial_window: u32, + /// Most channels open at once (1024); further `open`s get `open_fail` + /// reason 2. + pub max_channels: usize, +} + +impl Default for ServerConfig { + fn default() -> Self { + Self { + idle_timeout: Duration::from_secs(60), + initial_window: DEFAULT_WINDOW, + max_channels: MAX_CHANNELS, + } + } +} + +/// Why [`serve`] ended other than by input EOF. +#[derive(Debug)] +pub enum ServeError { + /// The client's hello was not `PUMUX 1`. + Version(String), + /// The client broke the frame protocol; the session was ended. + Protocol(String), + /// Nothing was received for [`ServerConfig::idle_timeout`]. + IdleTimeout, + /// Reading input or writing output failed. + Io(io::Error), +} + +impl fmt::Display for ServeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ServeError::Version(m) => write!(f, "unsupported mux handshake: {m}"), + ServeError::Protocol(m) => write!(f, "mux protocol error: {m}"), + ServeError::IdleTimeout => write!(f, "nothing received from the client; exiting"), + ServeError::Io(e) => write!(f, "{e}"), + } + } +} + +impl std::error::Error for ServeError {} + +/// Serve one mux session: write the hello, check the client's, then relay +/// frames until `input` ends (`Ok`), the client breaks the protocol, or +/// nothing arrives for `idle_timeout`. +/// +/// `connect` opens one daemon connection per channel (production passes the +/// daemon socket connect; tests inject fakes). Nothing but the hello line +/// and frames is ever written to `output`. Every daemon connection is +/// dropped before this returns. +pub async fn serve( + input: R, + output: W, + mut connect: C, + config: ServerConfig, +) -> Result<(), ServeError> +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, + C: FnMut() -> Fut, + Fut: Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let mut output = output; + output.write_all(HELLO).await.map_err(ServeError::Io)?; + output.flush().await.map_err(ServeError::Io)?; + + let mut input = BufReader::new(IdleReader::new(input, config.idle_timeout)); + let line = match super::read_hello_line(&mut input).await { + Ok(Some(line)) => line, + Ok(None) => return Ok(()), + Err(e) => return Err(read_error(e)), + }; + match super::parse_hello(&line) { + Some(VERSION) => {} + Some(n) => { + return Err(ServeError::Version(format!( + "client offered version {n}, this relay speaks {VERSION}" + ))); + } + None => { + return Err(ServeError::Version(format!( + "expected `PUMUX {VERSION}`, got {line:?}" + ))); + } + } + + let (out, rx) = Outbox::new(); + let session = Arc::new(Session { + channels: Mutex::new(HashMap::new()), + out, + window: u64::from(config.initial_window), + }); + let mut max_id = 0u32; + let reading = async { + loop { + let frame = match frame::read_frame(&mut input).await { + Ok(Some(frame)) => frame, + Ok(None) => return Ok(()), + Err(FrameError::Protocol(m)) => return Err(ServeError::Protocol(m)), + Err(FrameError::Io(e)) => return Err(read_error(e)), + }; + session.handle(frame, &mut max_id, &mut connect, &config)?; + } + }; + let result = tokio::select! { + r = reading => r, + r = super::write_loop(rx, output) => r.map_err(ServeError::Io), + }; + let channels = std::mem::take(&mut *session.channels.lock().unwrap()); + for channel in channels.into_values() { + channel.task.abort(); + } + result +} + +fn read_error(e: io::Error) -> ServeError { + if e.get_ref().is_some_and(|inner| inner.is::()) { + ServeError::IdleTimeout + } else { + ServeError::Io(e) + } +} + +struct Session { + channels: Mutex>, + out: Outbox, + window: u64, +} + +/// A channel as the frame reader sees it. Its task owns the daemon +/// connection; removing the entry is what ends a channel, and whoever +/// removes it decides which frames (if any) to send. +struct Channel { + to_daemon: mpsc::UnboundedSender, + /// Bytes the client may still send before it needs more credit. + recv_window: u64, + client_eof: bool, + /// Credit for sending daemon output to the client. + credit: Arc, + task: AbortHandle, +} + +enum Inbound { + Data(Vec), + Eof, +} + +fn protocol(message: String) -> Result<(), ServeError> { + Err(ServeError::Protocol(message)) +} + +impl Session { + /// Apply one client frame. Never waits: daemon writes happen in the + /// channel's task, bounded by the channel's window. + fn handle( + self: &Arc, + frame: Frame, + max_id: &mut u32, + connect: &mut C, + config: &ServerConfig, + ) -> Result<(), ServeError> + where + C: FnMut() -> Fut, + Fut: Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, + { + // A frame for a closed channel was in flight when it closed: ignore + // it. One for an id never opened is a protocol error. + let seen = *max_id; + let unknown = move |id: u32| -> Result<(), ServeError> { + if id <= seen { + Ok(()) + } else { + protocol(format!("frame for channel {id}, which was never opened")) + } + }; + let mut channels = self.channels.lock().unwrap(); + match frame { + Frame::Open { id } => { + if id <= *max_id { + return protocol(format!( + "open for channel {id}, not above every earlier id ({max_id})" + )); + } + *max_id = id; + if channels.len() >= config.max_channels { + self.out.send(Frame::OpenFail { + id, + reason: frame::REASON_TOO_MANY_CHANNELS, + message: format!( + "the session already holds {} channels", + config.max_channels + ), + }); + return Ok(()); + } + let (tx, rx) = mpsc::unbounded_channel(); + let credit = Arc::new(Credit::new(self.window)); + // The lock is held across the spawn so the task cannot look + // for its entry before it exists. + let task = tokio::spawn(channel_task( + Arc::clone(self), + id, + connect(), + rx, + Arc::clone(&credit), + )); + channels.insert( + id, + Channel { + to_daemon: tx, + recv_window: self.window, + client_eof: false, + credit, + task: task.abort_handle(), + }, + ); + Ok(()) + } + Frame::Data { id, bytes } => { + let Some(channel) = channels.get_mut(&id) else { + return unknown(id); + }; + if channel.client_eof { + return protocol(format!("data on channel {id} after its eof")); + } + let len = bytes.len() as u64; + if len > channel.recv_window { + return protocol(format!( + "channel {id} sent {len} bytes with only {} of window left", + channel.recv_window + )); + } + channel.recv_window -= len; + let _ = channel.to_daemon.send(Inbound::Data(bytes)); + Ok(()) + } + Frame::Eof { id } => { + let Some(channel) = channels.get_mut(&id) else { + return unknown(id); + }; + if channel.client_eof { + return protocol(format!("second eof on channel {id}")); + } + channel.client_eof = true; + let _ = channel.to_daemon.send(Inbound::Eof); + Ok(()) + } + Frame::Close { id } => { + let Some(channel) = channels.remove(&id) else { + // Our own close crossed the client's, or this replies to it. + return unknown(id); + }; + channel.task.abort(); + self.out.send(Frame::Close { id }); + Ok(()) + } + Frame::Window { id, credit } => { + let Some(channel) = channels.get_mut(&id) else { + return unknown(id); + }; + channel.credit.add(u64::from(credit)); + Ok(()) + } + Frame::Ping { data } => { + self.out.send(Frame::Pong { data }); + Ok(()) + } + Frame::Pong { .. } => Ok(()), + Frame::OpenOk { .. } | Frame::OpenFail { .. } => protocol(format!( + "client sent {}, which only the relay sends", + if matches!(frame, Frame::OpenOk { .. }) { + "open_ok" + } else { + "open_fail" + } + )), + } + } + + /// Remove a channel; true when this call removed it. + fn finish(&self, id: u32) -> bool { + self.channels.lock().unwrap().remove(&id).is_some() + } + + /// `n` bytes reached the daemon: give the client that much credit back. + fn grant(&self, id: u32, n: usize) { + let mut channels = self.channels.lock().unwrap(); + if let Some(channel) = channels.get_mut(&id) { + channel.recv_window += n as u64; + self.out.send(Frame::Window { + id, + credit: n as u32, + }); + } + } +} + +/// One channel: connect, then copy both ways within the windows. Ends with +/// `eof` + `close` when the daemon closes, `close` on a daemon error, or by +/// abort when the client closes the channel or the session ends. +async fn channel_task( + session: Arc, + id: u32, + connect: Fut, + mut from_client: mpsc::UnboundedReceiver, + credit: Arc, +) where + Fut: Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let stream = match connect.await { + Ok(stream) => stream, + Err(e) => { + if session.finish(id) { + session.out.send(Frame::OpenFail { + id, + reason: frame::REASON_NO_DAEMON, + message: format!("cannot connect to the daemon ({e})"), + }); + } + return; + } + }; + session.out.send(Frame::OpenOk { id }); + let (mut from_daemon, mut to_daemon) = tokio::io::split(stream); + + let upload = async { + while let Some(item) = from_client.recv().await { + match item { + Inbound::Data(bytes) => { + if to_daemon.write_all(&bytes).await.is_err() { + return; + } + session.grant(id, bytes.len()); + } + // A named pipe has no half-close; the daemon then just sees + // no more bytes, as with the plain relay. + Inbound::Eof => { + let _ = to_daemon.shutdown().await; + } + } + } + // The entry is gone, so this task is being aborted. + std::future::pending::<()>().await; + }; + let download = async { + let mut buf = vec![0u8; frame::MAX_PAYLOAD]; + loop { + let available = credit.available().await; + let want = available.min(frame::MAX_PAYLOAD as u64) as usize; + match from_daemon.read(&mut buf[..want]).await { + Ok(0) => return true, + Ok(n) => { + credit.consume(n as u64); + session.out.send(Frame::Data { + id, + bytes: buf[..n].to_vec(), + }); + } + Err(_) => return false, + } + } + }; + let daemon_eof = tokio::select! { + eof = download => eof, + () = upload => false, + }; + if session.finish(id) { + if daemon_eof { + session.out.send(Frame::Eof { id }); + } + session.out.send(Frame::Close { id }); + } +} + +/// Send credit for one channel, consumed by a single task. +struct Credit { + available: Mutex, + notify: Notify, +} + +impl Credit { + fn new(initial: u64) -> Self { + Self { + available: Mutex::new(initial), + notify: Notify::new(), + } + } + + fn add(&self, n: u64) { + let mut available = self.available.lock().unwrap(); + *available = available.saturating_add(n); + // A stored permit covers the case where the consumer is not yet waiting. + self.notify.notify_one(); + } + + /// Wait until some credit is available and return how much. + async fn available(&self) -> u64 { + loop { + let n = *self.available.lock().unwrap(); + if n > 0 { + return n; + } + self.notify.notified().await; + } + } + + fn consume(&self, n: u64) { + let mut available = self.available.lock().unwrap(); + *available -= n; + } +} + +/// Marks the io error an [`IdleReader`] returns when its timer fires. +#[derive(Debug)] +struct IdleElapsed; + +impl fmt::Display for IdleElapsed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("nothing received before the idle timeout") + } +} + +impl std::error::Error for IdleElapsed {} + +/// Fails a pending read once nothing has been received for `timeout`. +struct IdleReader { + inner: R, + timeout: Duration, + sleep: Pin>, +} + +impl IdleReader { + fn new(inner: R, timeout: Duration) -> Self { + Self { + inner, + timeout, + sleep: Box::pin(tokio::time::sleep(timeout)), + } + } +} + +impl AsyncRead for IdleReader { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let before = buf.filled().len(); + let this = &mut *self; + match Pin::new(&mut this.inner).poll_read(cx, buf) { + Poll::Ready(Ok(())) => { + if buf.filled().len() > before { + let deadline = Instant::now() + this.timeout; + this.sleep.as_mut().reset(deadline); + } + Poll::Ready(Ok(())) + } + Poll::Ready(Err(e)) => Poll::Ready(Err(e)), + Poll::Pending => match this.sleep.as_mut().poll(cx) { + Poll::Ready(()) => { + Poll::Ready(Err(io::Error::new(io::ErrorKind::TimedOut, IdleElapsed))) + } + Poll::Pending => Poll::Pending, + }, + } + } +} diff --git a/crates/pu-transport/src/mux/tests.rs b/crates/pu-transport/src/mux/tests.rs new file mode 100644 index 00000000..c06db214 --- /dev/null +++ b/crates/pu-transport/src/mux/tests.rs @@ -0,0 +1,1114 @@ +//! Session tests: a real client and server over in-memory pipes, against +//! fake daemons on the platform transport or in memory, plus fault +//! injection (blackholed and dropped links, idle input, protocol abuse). + +use std::io; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use tokio::io::{ + AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, DuplexStream, +}; +use tokio::task::JoinHandle; +use tokio::time::Instant; + +use super::frame::{self, Frame}; +use super::*; +use crate::{Endpoint, Listener}; + +const PIPE: usize = 64 * 1024; + +type ServeHandle = JoinHandle>; + +/// A fake daemon on the platform transport. Each connection's first line +/// picks its behaviour: +/// - `echo`: echo every later byte until EOF, +/// - `bye`: write `bye\n` and close, +/// - `flood`: write bytes until the write fails, +/// - `eat`: read to EOF, then reply `got \n` (needs a half-close), +/// - `hold`: keep the connection open and never read. +fn spawn_daemon(dir: &tempfile::TempDir) -> Endpoint { + let endpoint = Endpoint::for_socket(&dir.path().join("d.sock")).unwrap(); + let mut listener = Listener::bind(&endpoint).unwrap(); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + continue; + }; + tokio::spawn(daemon_connection(stream)); + } + }); + endpoint +} + +async fn daemon_connection(stream: S) { + let (reader, mut writer) = tokio::io::split(stream); + let mut reader = BufReader::new(reader); + let mut command = String::new(); + if reader.read_line(&mut command).await.unwrap_or(0) == 0 { + return; + } + match command.trim_end() { + "echo" => { + let _ = tokio::io::copy(&mut reader, &mut writer).await; + } + "bye" => { + let _ = writer.write_all(b"bye\n").await; + let _ = writer.shutdown().await; + } + "flood" => { + let chunk = vec![b'f'; 32 * 1024]; + while writer.write_all(&chunk).await.is_ok() {} + } + "eat" => { + let mut all = Vec::new(); + let _ = reader.read_to_end(&mut all).await; + let _ = writer + .write_all(format!("got {}\n", all.len()).as_bytes()) + .await; + let _ = writer.shutdown().await; + } + "hold" => std::future::pending::<()>().await, + other => panic!("unknown daemon command {other:?}"), + } +} + +fn socket_connect( + endpoint: Endpoint, +) -> impl FnMut() -> std::pin::Pin> + Send>> +{ + move || { + let endpoint = endpoint.clone(); + Box::pin(async move { crate::connect(&endpoint).await }) + } +} + +/// In-memory daemon connections with the same commands, for paused-time tests. +fn memory_connect() -> impl FnMut() -> std::future::Ready> { + || { + let (ours, theirs) = tokio::io::duplex(PIPE); + tokio::spawn(daemon_connection(theirs)); + std::future::ready(Ok(ours)) + } +} + +/// A server task and a connected client over in-memory pipes. +async fn session( + connect: C, + server: ServerConfig, + client: ClientConfig, +) -> (MuxClient, ServeHandle) +where + C: FnMut() -> Fut + Send + 'static, + Fut: std::future::Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let (client_io, server_io) = tokio::io::duplex(PIPE); + let (server_read, server_write) = tokio::io::split(server_io); + let serve = tokio::spawn(serve(server_read, server_write, connect, server)); + let (client_read, client_write) = tokio::io::split(client_io); + let client = MuxClient::handshake(client_read, client_write, client) + .await + .unwrap(); + (client, serve) +} + +/// A link between client and server that can stop delivering (both ways) +/// or be cut. +struct Link { + blackhole: Arc, + tasks: Vec>, +} + +impl Link { + fn blackhole(&self) { + self.blackhole.store(true, Ordering::SeqCst); + } + + fn cut(&self) { + for task in &self.tasks { + task.abort(); + } + } +} + +async fn forward( + mut from: R, + mut to: W, + blackhole: Arc, +) { + let mut buf = vec![0u8; 16 * 1024]; + loop { + let n = match from.read(&mut buf).await { + Ok(0) | Err(_) => break, + Ok(n) => n, + }; + if blackhole.load(Ordering::SeqCst) { + continue; + } + if to.write_all(&buf[..n]).await.is_err() { + break; + } + } + let _ = to.shutdown().await; +} + +async fn linked_session( + connect: C, + server: ServerConfig, + client: ClientConfig, +) -> (MuxClient, ServeHandle, Link) +where + C: FnMut() -> Fut + Send + 'static, + Fut: std::future::Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let (client_io, client_far) = tokio::io::duplex(PIPE); + let (server_far, server_io) = tokio::io::duplex(PIPE); + let blackhole = Arc::new(AtomicBool::new(false)); + let (cf_read, cf_write) = tokio::io::split(client_far); + let (sf_read, sf_write) = tokio::io::split(server_far); + let tasks = vec![ + tokio::spawn(forward(cf_read, sf_write, Arc::clone(&blackhole))), + tokio::spawn(forward(sf_read, cf_write, Arc::clone(&blackhole))), + ]; + let (server_read, server_write) = tokio::io::split(server_io); + let serve = tokio::spawn(serve(server_read, server_write, connect, server)); + let (client_read, client_write) = tokio::io::split(client_io); + let client = MuxClient::handshake(client_read, client_write, client) + .await + .unwrap(); + (client, serve, Link { blackhole, tasks }) +} + +async fn open_command(client: &MuxClient, command: &str) -> (MuxReader, MuxWriter) { + let (reader, mut writer) = client.open().await.unwrap(); + writer + .write_all(format!("{command}\n").as_bytes()) + .await + .unwrap(); + (reader, writer) +} + +async fn echo_once(client: &MuxClient, line: &str) -> String { + let (reader, mut writer) = open_command(client, "echo").await; + writer + .write_all(format!("{line}\n").as_bytes()) + .await + .unwrap(); + let mut reply = String::new(); + BufReader::new(reader).read_line(&mut reply).await.unwrap(); + reply +} + +/// The test plays the client by hand: returns its read and write ends after +/// the handshake. +async fn raw_client( + connect: C, + server: ServerConfig, +) -> ( + tokio::io::ReadHalf, + tokio::io::WriteHalf, + ServeHandle, +) +where + C: FnMut() -> Fut + Send + 'static, + Fut: std::future::Future> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let (client_io, server_io) = tokio::io::duplex(PIPE); + let (server_read, server_write) = tokio::io::split(server_io); + let serve = tokio::spawn(serve(server_read, server_write, connect, server)); + let (mut read, mut write) = tokio::io::split(client_io); + let mut hello = [0u8; 8]; + read.read_exact(&mut hello).await.unwrap(); + assert_eq!(&hello, HELLO); + write.write_all(HELLO).await.unwrap(); + (read, write, serve) +} + +async fn send(write: &mut (impl AsyncWrite + Unpin), frame: Frame) { + write.write_all(&frame.to_bytes()).await.unwrap(); +} + +async fn next_frame(read: &mut (impl AsyncRead + Unpin)) -> Frame { + frame::read_frame(read).await.unwrap().unwrap() +} + +fn small_window_server(window: u32) -> ServerConfig { + ServerConfig { + initial_window: window, + ..ServerConfig::default() + } +} + +fn small_window_client(window: u32) -> ClientConfig { + ClientConfig { + initial_window: window, + ..ClientConfig::default() + } +} + +// --- channels ------------------------------------------------------------- + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn given_200_concurrent_channels_should_echo_each_distinct_payload() { + // given + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + + // when + let mut tasks = tokio::task::JoinSet::new(); + for i in 0..200 { + let client = client.clone(); + tasks.spawn(async move { + let line = format!("payload-{i}-{}", "x".repeat(i * 37)); + let reply = echo_once(&client, &line).await; + (line, reply) + }); + } + + // then + let mut done = 0; + while let Some(result) = tasks.join_next().await { + let (line, reply) = result.unwrap(); + assert_eq!(reply, format!("{line}\n")); + done += 1; + } + assert_eq!(done, 200); + assert!(!client.is_closed()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn given_multi_mib_payload_should_round_trip_byte_for_byte() { + // given + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let payload: Vec = (0..8 * 1024 * 1024u32) + .map(|i| (i ^ (i >> 8) ^ (i >> 16)) as u8) + .collect(); + let (mut reader, mut writer) = open_command(&client, "echo").await; + + // when + let sent = payload.clone(); + let upload = tokio::spawn(async move { + writer.write_all(&sent).await.unwrap(); + writer + }); + let mut echoed = vec![0u8; payload.len()]; + reader.read_exact(&mut echoed).await.unwrap(); + + // then + let _writer = upload.await.unwrap(); + assert!(echoed == payload, "echoed bytes differ"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn given_unread_channel_should_not_block_another_channel() { + // given: a channel whose daemon floods it and whose reader is never read + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut flooded, _flood_writer) = open_command(&client, "flood").await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // when: another channel moves 2 MiB both ways + let busy = client.clone(); + let echoed = tokio::time::timeout(Duration::from_secs(20), async move { + let (mut reader, mut writer) = open_command(&busy, "echo").await; + let payload = vec![b'e'; 2 * 1024 * 1024]; + let sent = payload.clone(); + let upload = tokio::spawn(async move { writer.write_all(&sent).await.unwrap() }); + let mut got = vec![0u8; payload.len()]; + reader.read_exact(&mut got).await.unwrap(); + upload.await.unwrap(); + got == payload + }) + .await; + + // then + assert_eq!(echoed, Ok(true), "the echo channel stalled"); + let mut some = vec![0u8; 1024 * 1024]; + flooded.read_exact(&mut some).await.unwrap(); + assert!(some.iter().all(|&b| b == b'f')); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_no_daemon_open_should_fail_with_no_daemon_and_keep_session() { + // given + let dir = tempfile::tempdir().unwrap(); + let missing = Endpoint::for_socket(&dir.path().join("missing.sock")).unwrap(); + let (client, _serve) = session( + socket_connect(missing), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + + // when + let first = client.open().await; + let second = client.open().await; + + // then + assert!( + matches!(first, Err(OpenError::NoDaemon(ref m)) if m.contains("cannot connect")), + "{:?}", + first.err() + ); + assert!(matches!(second, Err(OpenError::NoDaemon(_)))); + assert!(!client.is_closed()); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_daemon_closes_should_give_reader_eof_and_leave_others_unaffected() { + // given + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut echo_reader, mut echo_writer) = open_command(&client, "echo").await; + let (mut bye_reader, mut bye_writer) = open_command(&client, "bye").await; + + // when + let mut bye = Vec::new(); + bye_reader.read_to_end(&mut bye).await.unwrap(); + + // then + assert_eq!(bye, b"bye\n"); + // the closed channel refuses writes once the close has arrived + let mut refused = false; + for _ in 0..50 { + if bye_writer.write_all(b"x").await.is_err() { + refused = true; + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(refused, "writes to a closed channel kept succeeding"); + echo_writer.write_all(b"still here\n").await.unwrap(); + let mut line = vec![0u8; 11]; + echo_reader.read_exact(&mut line).await.unwrap(); + assert_eq!(line, b"still here\n"); + assert_eq!(echo_once(&client, "new").await, "new\n"); +} + +// Needs a half-close, which named pipes do not have. +#[cfg(unix)] +#[tokio::test(flavor = "current_thread")] +async fn given_client_shutdown_should_half_close_daemon_and_still_get_reply() { + // given: a daemon that replies only after its peer half-closes + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut reader, mut writer) = open_command(&client, "eat").await; + writer.write_all(&[7u8; 100_000]).await.unwrap(); + + // when + writer.shutdown().await.unwrap(); + + // then + let mut reply = String::new(); + reader.read_to_string(&mut reply).await.unwrap(); + assert_eq!(reply, "got 100000\n"); + assert!(writer.write_all(b"late").await.is_err()); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_channel_limit_should_refuse_with_too_many_channels_until_one_closes() { + // given + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let config = ServerConfig { + max_channels: 3, + ..ServerConfig::default() + }; + let (client, _serve) = session(socket_connect(endpoint), config, ClientConfig::default()).await; + let mut open = Vec::new(); + for _ in 0..3 { + open.push(open_command(&client, "hold").await); + } + + // when + let refused = client.open().await; + drop(open.pop()); + let after_close = client.open().await; + + // then + assert!( + matches!(refused, Err(OpenError::TooManyChannels(_))), + "{:?}", + refused.err() + ); + assert!(after_close.is_ok(), "{:?}", after_close.err()); + assert!(!client.is_closed()); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_channel_ids_should_be_nonzero_and_never_reused() { + // given + let (client, _serve) = session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + + // when + let mut ids = Vec::new(); + for _ in 0..5 { + let (reader, writer) = client.open().await.unwrap(); + ids.push(reader.id()); + assert_eq!(reader.id(), writer.id()); + } + + // then + assert_eq!(ids, vec![1, 2, 3, 4, 5]); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_both_halves_dropped_should_close_the_daemon_connection() { + // given + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (client, _serve) = session( + socket_connect(endpoint), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + // The daemon's echo ends only when its connection is dropped. + let (reader, writer) = open_command(&client, "echo").await; + + // when + drop(reader); + drop(writer); + + // then: the session keeps working and the channel is gone + assert_eq!(echo_once(&client, "after").await, "after\n"); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_client_close_should_end_session_and_serve_should_return_ok() { + // given + let (client, serve) = session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut reader, mut writer) = open_command(&client, "hold").await; + + // when + client.close(); + + // then + assert_eq!(client.closed().await, CloseReason::Closed); + assert!(client.is_closed()); + assert!(reader.read(&mut [0u8; 8]).await.is_err()); + assert!(writer.write_all(b"x").await.is_err()); + assert!(matches!( + client.open().await, + Err(OpenError::SessionClosed(CloseReason::Closed)) + )); + let served = tokio::time::timeout(Duration::from_secs(5), serve) + .await + .unwrap() + .unwrap(); + assert!(served.is_ok(), "{served:?}"); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_last_handle_dropped_should_end_session() { + // given + let (client, serve) = session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut reader, _writer) = open_command(&client, "hold").await; + + // when + drop(client); + + // then + assert!(reader.read(&mut [0u8; 8]).await.is_err()); + let served = tokio::time::timeout(Duration::from_secs(5), serve) + .await + .unwrap() + .unwrap(); + assert!(served.is_ok(), "{served:?}"); +} + +// --- flow control --------------------------------------------------------- + +#[tokio::test(flavor = "current_thread")] +async fn given_client_sending_beyond_window_should_end_session_with_protocol_error() { + // given: a daemon connection that never reads, so no credit comes back + let held = || { + let (ours, theirs) = tokio::io::duplex(1); + tokio::spawn(async move { + let _theirs = theirs; + std::future::pending::<()>().await + }); + std::future::ready(Ok::<_, io::Error>(ours)) + }; + let (mut read, mut write, serve) = raw_client(held, small_window_server(1024)).await; + send(&mut write, Frame::Open { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 1 }); + + // when: the whole window, then one byte more + send( + &mut write, + Frame::Data { + id: 1, + bytes: vec![1; 1024], + }, + ) + .await; + send( + &mut write, + Frame::Data { + id: 1, + bytes: vec![1], + }, + ) + .await; + + // then + let served = tokio::time::timeout(Duration::from_secs(5), serve) + .await + .unwrap() + .unwrap(); + assert!( + matches!(served, Err(ServeError::Protocol(ref m)) if m.contains("window")), + "{served:?}" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_relay_sending_beyond_window_should_end_client_session_with_protocol_error() { + // given: a hand-played relay + let (client_io, relay_io) = tokio::io::duplex(PIPE); + let relay = tokio::spawn(async move { + let (mut read, mut write) = tokio::io::split(relay_io); + write.write_all(HELLO).await.unwrap(); + let mut hello = [0u8; 8]; + read.read_exact(&mut hello).await.unwrap(); + let Frame::Open { id } = next_frame(&mut read).await else { + panic!("expected open"); + }; + send(&mut write, Frame::OpenOk { id }).await; + send( + &mut write, + Frame::Data { + id, + bytes: vec![2; 1024], + }, + ) + .await; + send(&mut write, Frame::Data { id, bytes: vec![2] }).await; + // keep the pipe open + let _ = read.read_to_end(&mut Vec::new()).await; + }); + let (r, w) = tokio::io::split(client_io); + let client = MuxClient::handshake(r, w, small_window_client(1024)) + .await + .unwrap(); + let (mut reader, _writer) = client.open().await.unwrap(); + + // when + let reason = tokio::time::timeout(Duration::from_secs(5), client.closed()) + .await + .unwrap(); + + // then + assert!( + matches!(reason, CloseReason::Protocol(ref m) if m.contains("window")), + "{reason:?}" + ); + // bytes received in order are still readable, then the error + let mut buf = vec![0u8; 1024]; + reader.read_exact(&mut buf).await.unwrap(); + assert!(reader.read(&mut [0u8; 1]).await.is_err()); + relay.abort(); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_small_window_should_still_move_large_payload() { + // given: credit has to come back many times over + let (client, _serve) = session( + memory_connect(), + small_window_server(1000), + small_window_client(1000), + ) + .await; + let (mut reader, mut writer) = open_command(&client, "echo").await; + let payload: Vec = (0..300_000u32).map(|i| (i % 251) as u8).collect(); + + // when + let sent = payload.clone(); + let upload = tokio::spawn(async move { + writer.write_all(&sent).await.unwrap(); + writer + }); + let mut got = vec![0u8; payload.len()]; + reader.read_exact(&mut got).await.unwrap(); + + // then + let _writer = upload.await.unwrap(); + assert!(got == payload); +} + +// --- protocol abuse (relay side) ------------------------------------------ + +#[tokio::test(flavor = "current_thread")] +async fn given_reused_channel_id_should_end_serve_with_protocol_error() { + // given + let (mut read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + send(&mut write, Frame::Open { id: 5 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 5 }); + + // when + send(&mut write, Frame::Open { id: 5 }).await; + + // then + let served = serve.await.unwrap(); + assert!(matches!(served, Err(ServeError::Protocol(_))), "{served:?}"); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_frame_for_never_opened_channel_should_end_serve_with_protocol_error() { + // given + let (_read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + + // when + send( + &mut write, + Frame::Data { + id: 9, + bytes: vec![1], + }, + ) + .await; + + // then + let served = serve.await.unwrap(); + assert!(matches!(served, Err(ServeError::Protocol(_))), "{served:?}"); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_late_frames_for_closed_channel_should_be_ignored() { + // given + let (mut read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + send(&mut write, Frame::Open { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 1 }); + send(&mut write, Frame::Close { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::Close { id: 1 }); + + // when + send( + &mut write, + Frame::Data { + id: 1, + bytes: vec![1], + }, + ) + .await; + send(&mut write, Frame::Window { id: 1, credit: 10 }).await; + send(&mut write, Frame::Close { id: 1 }).await; + send(&mut write, Frame::Ping { data: [4; 8] }).await; + + // then: the session is alive and answers + assert_eq!(next_frame(&mut read).await, Frame::Pong { data: [4; 8] }); + assert!(!serve.is_finished()); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_garbage_frame_should_end_serve_with_protocol_error() { + // given + let (_read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + + // when: a frame length of 3 + write.write_all(&[0, 0, 0, 3, 1, 2, 3]).await.unwrap(); + + // then + let served = serve.await.unwrap(); + assert!(matches!(served, Err(ServeError::Protocol(_))), "{served:?}"); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_daemon_closing_should_send_eof_then_close() { + // given + let (mut read, mut write, _serve) = raw_client(memory_connect(), ServerConfig::default()).await; + send(&mut write, Frame::Open { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 1 }); + + // when + send( + &mut write, + Frame::Data { + id: 1, + bytes: b"bye\n".to_vec(), + }, + ) + .await; + + // then + let mut frames = Vec::new(); + loop { + let frame = next_frame(&mut read).await; + let done = frame == Frame::Close { id: 1 }; + if !matches!(frame, Frame::Window { .. }) { + frames.push(frame); + } + if done { + break; + } + } + assert_eq!( + frames, + vec![ + Frame::Data { + id: 1, + bytes: b"bye\n".to_vec() + }, + Frame::Eof { id: 1 }, + Frame::Close { id: 1 }, + ] + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_stdin_eof_serve_should_return_ok_and_drop_daemon_connections() { + // given: an open channel to an echo daemon + let dir = tempfile::tempdir().unwrap(); + let endpoint = spawn_daemon(&dir); + let (mut read, mut write, serve) = + raw_client(socket_connect(endpoint), ServerConfig::default()).await; + send(&mut write, Frame::Open { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 1 }); + + // when: stdin closes (a split half needs shutdown to signal EOF) + write.shutdown().await.unwrap(); + + // then + let served = tokio::time::timeout(Duration::from_secs(5), serve) + .await + .unwrap() + .unwrap(); + assert!(served.is_ok(), "{served:?}"); + let mut rest = Vec::new(); + read.read_to_end(&mut rest).await.unwrap(); +} + +// --- handshake ------------------------------------------------------------ + +#[tokio::test(flavor = "current_thread")] +async fn given_eof_before_hello_handshake_should_be_unsupported() { + // given: what an old `pu` writes to stdout before exiting 2 + let read: &[u8] = b""; + + // when + let result = MuxClient::handshake(read, tokio::io::sink(), ClientConfig::default()).await; + + // then + assert!( + matches!(result, Err(HandshakeError::Unsupported(_))), + "{result:?}" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_garbage_first_line_handshake_should_be_unsupported() { + for first in [ + &b"error: unexpected argument '--mux' found\n"[..], + b"PUMUX\n", + b"PUMUX x\n", + b"PUMUX 1 \n", + b"PUMUX 2\n", + b"pumux 1\n", + &[b'A'; 200][..], + ] { + // given + let (mut far, near) = tokio::io::duplex(PIPE); + far.write_all(first).await.unwrap(); + let (r, w) = tokio::io::split(near); + + // when + let result = MuxClient::handshake(r, w, ClientConfig::default()).await; + + // then + assert!( + matches!(result, Err(HandshakeError::Unsupported(_))), + "{:?}: {result:?}", + String::from_utf8_lossy(first) + ); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn given_relay_hello_handshake_should_answer_with_own_hello() { + // given + let (mut far, near) = tokio::io::duplex(PIPE); + far.write_all(HELLO).await.unwrap(); + let (r, w) = tokio::io::split(near); + + // when + let client = MuxClient::handshake(r, w, ClientConfig::default()) + .await + .unwrap(); + + // then + let mut hello = [0u8; 8]; + far.read_exact(&mut hello).await.unwrap(); + assert_eq!(&hello, HELLO); + assert!(!client.is_closed()); +} + +#[tokio::test(flavor = "current_thread")] +async fn given_client_version_2_serve_should_fail_with_version_error() { + for line in [&b"PUMUX 2\n"[..], b"hello\n"] { + // given + let (client_io, server_io) = tokio::io::duplex(PIPE); + let (sr, sw) = tokio::io::split(server_io); + let (mut read, mut write) = tokio::io::split(client_io); + + // when + write.write_all(line).await.unwrap(); + let served = serve(sr, sw, memory_connect(), ServerConfig::default()).await; + + // then + assert!(matches!(served, Err(ServeError::Version(_))), "{served:?}"); + let mut out = Vec::new(); + read.read_to_end(&mut out).await.unwrap(); + assert_eq!(out, HELLO, "the relay wrote more than its hello"); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn given_input_closed_before_client_hello_serve_should_return_ok() { + // given + let (sr, sw) = (tokio::io::empty(), tokio::io::sink()); + + // when + let served = serve(sr, sw, memory_connect(), ServerConfig::default()).await; + + // then + assert!(served.is_ok(), "{served:?}"); +} + +// --- liveness and link faults (virtual time) ------------------------------- + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_blackholed_link_should_end_with_ping_timeout_and_fail_channels() { + // given + let (client, _serve, link) = linked_session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let (mut reader, mut writer) = open_command(&client, "echo").await; + writer.write_all(b"ok\n").await.unwrap(); + let mut ok = [0u8; 3]; + reader.read_exact(&mut ok).await.unwrap(); + + // when + link.blackhole(); + let start = Instant::now(); + let reason = client.closed().await; + + // then + let elapsed = start.elapsed(); + assert_eq!(reason, CloseReason::PingTimeout); + assert!( + elapsed >= Duration::from_secs(15) && elapsed <= Duration::from_secs(21), + "took {elapsed:?}" + ); + let read = reader.read(&mut [0u8; 8]).await; + assert!( + matches!(&read, Err(e) if e.kind() == io::ErrorKind::ConnectionAborted), + "{read:?}" + ); + assert!(writer.write_all(b"x").await.is_err()); + assert!(matches!( + client.open().await, + Err(OpenError::SessionClosed(CloseReason::PingTimeout)) + )); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_blackholed_link_should_fail_a_pending_open() { + // given + let (client, _serve, link) = linked_session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + link.blackhole(); + + // when + let result = client.open().await; + + // then + assert!( + matches!( + result, + Err(OpenError::SessionClosed(CloseReason::PingTimeout)) + ), + "{:?}", + result.err() + ); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_answered_pings_should_keep_session_open_past_relay_idle_timeout() { + // given + let (client, serve) = session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + + // when: three minutes with no channel traffic at all + tokio::time::sleep(Duration::from_secs(180)).await; + + // then + assert!(!client.is_closed()); + assert!(!serve.is_finished()); + assert_eq!(echo_once(&client, "alive").await, "alive\n"); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_cut_link_should_fail_all_channels_and_resolve_closed() { + // given + let (client, _serve, link) = linked_session( + memory_connect(), + ServerConfig::default(), + ClientConfig::default(), + ) + .await; + let mut channels = Vec::new(); + for _ in 0..3 { + channels.push(open_command(&client, "hold").await); + } + + // when + link.cut(); + let reason = tokio::time::timeout(Duration::from_secs(1), client.closed()) + .await + .expect("closed() did not resolve"); + + // then + assert!( + matches!(reason, CloseReason::Eof | CloseReason::Io(_)), + "{reason:?}" + ); + for (reader, writer) in &mut channels { + assert!(reader.read(&mut [0u8; 8]).await.is_err()); + assert!(writer.write_all(b"x").await.is_err()); + } +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_nothing_received_serve_should_exit_after_60s() { + // given: a client that handshakes, opens a channel, then goes silent + let (mut read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + send(&mut write, Frame::Open { id: 1 }).await; + assert_eq!(next_frame(&mut read).await, Frame::OpenOk { id: 1 }); + let start = Instant::now(); + + // when + let served = serve.await.unwrap(); + + // then + let elapsed = start.elapsed(); + assert!(matches!(served, Err(ServeError::IdleTimeout)), "{served:?}"); + assert!( + elapsed >= Duration::from_secs(60) && elapsed < Duration::from_secs(61), + "took {elapsed:?}" + ); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_traffic_serve_idle_timer_should_restart() { + // given + let (mut read, mut write, serve) = raw_client(memory_connect(), ServerConfig::default()).await; + let start = Instant::now(); + + // when: a ping every 50 s keeps it alive past 60 s + for i in 0..3u8 { + tokio::time::sleep(Duration::from_secs(50)).await; + send(&mut write, Frame::Ping { data: [i; 8] }).await; + assert_eq!(next_frame(&mut read).await, Frame::Pong { data: [i; 8] }); + } + let served = serve.await.unwrap(); + + // then + assert!(matches!(served, Err(ServeError::IdleTimeout))); + let elapsed = start.elapsed(); + assert!( + elapsed >= Duration::from_secs(210) && elapsed < Duration::from_secs(211), + "took {elapsed:?}" + ); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn given_client_should_ping_every_5s() { + // given: a hand-played relay that records pings and answers none + let (client_io, relay_io) = tokio::io::duplex(PIPE); + let (mut read, mut write) = tokio::io::split(relay_io); + write.write_all(HELLO).await.unwrap(); + let (r, w) = tokio::io::split(client_io); + let client = MuxClient::handshake(r, w, ClientConfig::default()) + .await + .unwrap(); + let mut hello = [0u8; 8]; + read.read_exact(&mut hello).await.unwrap(); + let start = Instant::now(); + + // when + let mut at = Vec::new(); + while at.len() < 3 { + if let Ok(Some(Frame::Ping { .. })) = frame::read_frame(&mut read).await { + at.push(start.elapsed().as_secs()); + } else { + break; + } + } + + // then + assert_eq!(at, vec![5, 10, 15]); + assert_eq!(client.closed().await, CloseReason::PingTimeout); + assert_eq!(start.elapsed(), Duration::from_secs(20)); +} diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 5140893f..a0615ee5 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -189,10 +189,13 @@ pu daemon stop # stop; running agents are suspended and resume on next pu daemon status # health and service state pu daemon install [--now] # run as a user service (systemd on Linux, launchd on macOS); --now also starts it pu daemon uninstall # remove that service +pu daemon proxy [--mux] # relay stdin/stdout to the daemon for SSH clients (used by the apps) ``` `install` supervises the default socket (`~/.pu/daemon.sock`) only, so it can't be combined with `--socket`. The service restarts the daemon after a crash, but not after `pu daemon stop`. On Linux, also run `sudo loginctl enable-linger $USER` so it runs without a login session. See [Run PurePoint on a Linux server](linux-server.md). +`proxy` is what the iPad and Windows apps run over SSH; you don't run it yourself. It never starts the daemon. Plain `proxy` carries one daemon connection; `--mux` carries all of an app's connections to the machine over one SSH session, so a network blip doesn't make every pane log in again at once. + ## pulse Workspace pulse: agents, runtimes, and git stats at a glance. diff --git a/docs/product/cli.md b/docs/product/cli.md index 50d04864..32a984e5 100644 --- a/docs/product/cli.md +++ b/docs/product/cli.md @@ -49,7 +49,7 @@ Key behaviors: | `pu logs ` | `--tail ` (default 500), `--json` | Deprecated raw terminal diagnostic bytes | | `pu send [text]` | `--no-enter`, `--keys `, `--json` | Send text or control keys to agent terminal. Claude agents get screen-confirmed delivery (full text submitted as one turn, or non-zero exit); no nudge needed | | `pu health` | `--json` | Check daemon health | -| `pu daemon proxy` | honours global `--socket` | Relay stdin/stdout to the daemon socket as one connection, for SSH exec channels. Never starts the daemon (see below) | +| `pu daemon proxy` | `--mux`; honours global `--socket` | Relay stdin/stdout to the daemon socket as one connection, for SSH exec channels; `--mux` carries many connections as channels of one session. Never starts the daemon (see below) | | `pu pulse` | `--json` | Workspace overview (agents, runtimes, git stats) | | `pu diff` | `--worktree `, `--stat`, `--json` | Show git diffs across worktrees | | `pu watch` | `--interval ` (default 800) | Live TUI dashboard | @@ -148,8 +148,10 @@ Validation: `crates/pu-cli/tests/machines.rs` drives real CLI processes through See [Machines over SSH](machines.md) (MACH-003). Clients that cannot `ssh -L` a Unix socket (the iPad app) open an SSH exec channel running `pu daemon proxy`; each channel is exactly one daemon connection carrying newline-delimited JSON. - Connects to the daemon socket (`~/.pu/daemon.sock`, or `--socket`) and copies stdin to the socket and socket output to stdout byte-for-byte. Stdin EOF half-closes the socket's write side and the proxy keeps draining replies; the daemon closing the connection ends the proxy with exit 0, even while stdin is still open. Stdout is flushed before exit. -- Never starts a daemon: `daemon_ctrl::ensure_daemon` is not on this path. A missing or refusing socket exits 1 with ``error: cannot connect to the daemon at (); start it with `pu daemon start` `` on stderr. +- Never starts a daemon: `daemon_ctrl::ensure_daemon` is not on this path. A missing or refusing socket exits 69 (`EX_UNAVAILABLE`) with ``error: cannot connect to the daemon at (); start it with `pu daemon start` `` on stderr. - Stdout carries only daemon bytes. Every diagnostic goes to stderr, and the plugin freshness check is skipped so the proxy has no side work. - Implemented in `crates/pu-cli/src/commands/daemon_proxy.rs`. -Validation: unit tests in `daemon_proxy.rs` relay 256 KiB both ways through an echo daemon, check half-close draining and daemon-side close; `crates/pu-cli/tests/daemon_proxy.rs` runs the real binary against a fake protocol daemon and the in-process `pu-engine` daemon (a `{"type":"health"}` line yields exactly the health response line) and against a missing socket (non-zero exit, empty stdout, no daemon started). +`pu daemon proxy --mux` is the multiplexed relay the Windows app holds one of per machine (MACH-013; wire contract in [machines.md](machines.md), Multiplexed relay). It writes `PUMUX 1\n`, checks the client's `PUMUX 1\n`, then serves frames: each channel `open` connects to the daemon socket (`--socket` honoured) and fails with reason 1 when none answers, instead of exiting 69. Never starts a daemon; stdout carries only the hello and frames, diagnostics go to stderr. Exits 0 when stdin closes, 1 on a wrong client version, a protocol error, or 60 s with nothing received. Server and client are `pu_transport::mux` (`serve`, `MuxClient`). + +Validation: unit tests in `daemon_proxy.rs` relay 256 KiB both ways through an echo daemon, check half-close draining and daemon-side close; `crates/pu-cli/tests/daemon_proxy.rs` runs the real binary against a fake protocol daemon and the in-process `pu-engine` daemon (a `{"type":"health"}` line yields exactly the health response line) and against a missing socket (non-zero exit, empty stdout, no daemon started). For `--mux`, `crates/pu-transport/src/mux/` tests the codec bounds and a real client and server over in-memory pipes (200 concurrent channels, an 8 MiB round trip, an unread channel not blocking another, window overruns, channel limit, half-close, daemon close, and in virtual time a blackholed link ending in a ping timeout, a cut link, and the 60 s idle exit); `crates/pu-cli/tests/daemon_proxy.rs` runs the real `pu daemon proxy --mux` against the in-process daemon (four channels each get a health report), a missing daemon (`NoDaemon`, none started), a wrong client version (exit 1) and stdin closing (exit 0). diff --git a/docs/product/machines.md b/docs/product/machines.md index 9483536d..520bf23e 100644 --- a/docs/product/machines.md +++ b/docs/product/machines.md @@ -154,11 +154,11 @@ The Windows app and `pu --machine` run `ssh.exe -T -o BatchMode=yes -o ConnectTi **Handshake.** The relay first writes the line `PUMUX 1\n`. The client checks it, then writes `PUMUX 1\n` itself, and frames follow in both directions. A `pu` without `--mux` exits 2 before writing anything (clap usage error), and the client treats that, or any first line other than `PUMUX `, as no mux support and falls back to the per-connection relay. A relay that reads a client version other than `1` exits 1. Future versions bump ``, and a client may offer only a version the relay announced. -**Frames.** Each frame is a 4-byte big-endian length (of everything after it), a 1-byte type, a 4-byte big-endian channel id and a payload. The length is at least 5 and at most 65 541 (64 KiB of payload). A frame outside those bounds, an unknown type, or a frame for an unknown channel other than a late `data`, `eof`, `close` or `window` for a channel that just closed, is a protocol error: the side that sees it ends the whole session. +**Frames.** Each frame is a 4-byte big-endian length (of everything after it), a 1-byte type, a 4-byte big-endian channel id and a payload. The length is at least 5 and at most 65 541 (64 KiB of payload). A frame outside those bounds, an unknown type, a payload of the wrong size for its type, a frame sent in the wrong direction, or a frame for a channel id that was never opened is a protocol error: the side that sees it ends the whole session. A frame for a channel that already closed (any type, including an `open_ok` or `open_fail` answering an `open` the client abandoned with `close`) was in flight when it closed and is ignored. Because ids only increase, "never opened" is any id above the highest opened so far, and neither side has to remember closed ids. | Type | Name | Direction | Channel | Payload | |---|---|---|---|---| -| 1 | `open` | client → relay | new id, nonzero, never reused in the session | none | +| 1 | `open` | client → relay | new id, nonzero and greater than every id opened before in the session (so never reused) | none | | 2 | `open_ok` | relay → client | the opened id | none | | 3 | `open_fail` | relay → client | the refused id | 1-byte reason (1 = no daemon, 2 = too many channels, 3 = other), then a UTF-8 message | | 4 | `data` | both | an open channel | 1 – 65 536 bytes | @@ -172,7 +172,7 @@ The Windows app and `pu --machine` run `ssh.exe -T -o BatchMode=yes -o ConnectTi **Flow control.** Each side may send at most 256 KiB of `data` on a channel beyond what the other side has granted with `window`. A receiver grants credit only as it delivers bytes onward (to the daemon socket, or to the channel's reader), so a stalled consumer stops only its own channel. Sending beyond the window is a protocol error. -**Liveness.** The client sends `ping` every 5 s. Two pings in a row unanswered within 10 s each mean the session is dead: the client ends `ssh.exe`, fails every channel and reconnects through the supervisor. The relay exits after 60 s with nothing received on stdin, so a relay left by a vanished client does not keep holding daemon connections. +**Liveness.** The client sends `ping` every 5 s. Two pings in a row unanswered within 10 s each mean the session is dead: the client ends `ssh.exe`, fails every channel and reconnects through the supervisor. The relay exits (status 1) after 60 s with nothing received on stdin, so a relay left by a vanished client does not keep holding daemon connections. Both sides write `ping`, `pong` and `window` ahead of queued `data` (they carry no channel bytes, so reordering them is safe), so bulk data on a slow link cannot hold a `pong` past its timeout. **Windows client.** The app's per-machine session runs `ssh.exe -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ControlMaster=no -o ControlPath=none `, where `` is the wrapped command above for a Unix machine and `pu daemon proxy --mux` for a Windows machine. Every probe, request, subscription and attach for the machine is a channel. Opening a channel while the session is down waits for it, up to the request's own timeout. From b2ff663bab3b3c7cc8cc35627ae2585cfe03ede4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:58:12 +0000 Subject: [PATCH 07/21] =?UTF-8?q?docs:=20reliable=20machine=20connections?= =?UTF-8?q?=20guide=20and=20pu=20doctor=20(MACH-017=20=E2=80=93=20MACH-019?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New docs/guide/reliable-machine-connections.md: why connections drop, a Tailscale or WireGuard address for ssh_host, the sshd settings, fail2ban/sshguard/ufw exemptions, keeping machines awake, pu doctor, and what each connection-failure message means. Document pu doctor in the CLI reference and cli.md, the readiness check script contract and the new ssh options in machines.md, and link the guide from the indexes, the Linux server, Windows and troubleshooting guides. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- README.md | 1 + docs/README.md | 2 +- docs/guide/cli-reference.md | 18 +++ docs/guide/getting-started.md | 1 + docs/guide/linux-server.md | 2 + docs/guide/reliable-machine-connections.md | 165 +++++++++++++++++++++ docs/guide/troubleshooting.md | 4 + docs/guide/windows.md | 2 + docs/product/cli.md | 14 +- docs/product/machines.md | 14 +- 10 files changed, 220 insertions(+), 3 deletions(-) create mode 100644 docs/guide/reliable-machine-connections.md diff --git a/README.md b/README.md index 88b66ade..4521e227 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ Run `pu --help` for full usage. | [Templates & Definitions](https://purepoint.dev/docs/guide/workflows/templates-and-definitions) | Prompts, agent defs, swarm defs | | [Scheduling & Triggers](https://purepoint.dev/docs/guide/workflows/scheduling-and-triggers) | Schedules, triggers, git hooks | | [Linux Server](https://purepoint.dev/docs/guide/linux-server) | Run the daemon on a headless Linux server | +| [Reliable Machine Connections](docs/guide/reliable-machine-connections.md) | Stable addresses, sshd and firewall settings, `pu doctor --machine` | | [Windows](docs/guide/windows.md) | Install, daemon autostart, agents and troubleshooting on Windows | | [Troubleshooting](https://purepoint.dev/docs/guide/troubleshooting) | Common issues and solutions | | [Contributing](https://purepoint.dev/docs/contributing/overview) | Build, test, code style, architecture | diff --git a/docs/README.md b/docs/README.md index 6669385d..68869498 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,7 +2,7 @@ | Folder | What's in it | |---|---| -| [`guide/`](guide/) | User docs: getting started, CLI reference, configuration, workflows, troubleshooting. Published at [purepoint.dev/docs](https://purepoint.dev/docs/guide/getting-started). | +| [`guide/`](guide/) | User docs: getting started, CLI reference, configuration, workflows, troubleshooting, [Linux servers](guide/linux-server.md), [Windows](guide/windows.md) and [reliable machine connections](guide/reliable-machine-connections.md). Published at [purepoint.dev/docs](https://purepoint.dev/docs/guide/getting-started). | | [`contributing/`](contributing/) | Building, testing, code style and architecture overview for contributors. | | [`product/`](product/) | Product specs, one per domain. Start with [`cross-reference-matrix.md`](product/cross-reference-matrix.md). | | [`architecture/`](architecture/) | Daemon, IPC, storage, agent execution and distribution design. | diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 5140893f..ea47858d 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -30,6 +30,7 @@ | [`pu trigger`](#trigger) | Manage event-driven triggers | | [`pu gate`](#gate) | Evaluate git hook gates | | [`pu machine`](#machine) | Manage machines reachable over SSH (`--machine`) | +| [`pu doctor`](#doctor) | Check a machine for settings that drop connections | ## init @@ -382,3 +383,20 @@ pu --machine studio attach ag-xxx - Project commands need `--project` with the project's path on that machine; your current directory is not used. Agent commands find the agent by id on that machine. - `init`, `channel` and `gate` work on local files and cannot be used with `--machine`. - `PU_SSH` overrides the ssh binary (default `/usr/bin/ssh`). +- Every ssh command passes `-o ConnectTimeout=10 -o TCPKeepAlive=yes`. When one fails, the error gives ssh's message and what it means, e.g. "The server refused the login (rate limit or MaxStartups)". See [what the connection errors mean](reliable-machine-connections.md#what-the-connection-errors-mean). + +## doctor + +Check a registered machine for settings that make connections drop, and print the exact fix for each. It changes nothing on either machine. + +```sh +pu doctor --machine [--json] +``` + +- On this computer: the options your ssh config sets for the host (`ssh -G`), and how long a `BatchMode=yes` login takes (a warning above 3 s). +- On the machine, in one login: sshd's `MaxStartups`, `MaxSessions`, `ClientAliveInterval`/`ClientAliveCountMax` and `TCPKeepAlive` (from `sshd -T`), whether fail2ban or sshguard is running, any `ufw limit` rule on ssh, whether the machine can sleep (macOS `pmset`, Linux sleep targets), whether `pu` is installed and supports `pu daemon proxy --mux`, and whether the daemon answers. It never starts the daemon. +- Each line is `ok`, `warn` with a `fix:` line, or `skip` with the reason. `sshd -T` and `ufw status` need root; when `sudo -n` needs a password they are reported as `skipped (needs sudo)`, never as passing. +- A Windows machine has no `/bin/sh`, so only the checks on this computer and the login run. +- Exits 1 only when the login fails, after reporting why. `--json` prints `{ machine, ssh_host, reachable, findings: [{ check, status, detail, fix? }] }` with `status` one of `ok`, `warn`, `skipped`, `fail`. + +See [Reliable machine connections](reliable-machine-connections.md). diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 61f73ccd..accf9c5a 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -130,3 +130,4 @@ pu clean --all - [Templates and Definitions](workflows/templates-and-definitions.md) -- reusable prompts and agent types - [Scheduling and Triggers](workflows/scheduling-and-triggers.md) -- automate agent workflows - [Concepts](concepts.md) -- the mental model +- [Reliable Machine Connections](reliable-machine-connections.md) -- keep remote machines connected diff --git a/docs/guide/linux-server.md b/docs/guide/linux-server.md index 6c54ce1b..6f156d79 100644 --- a/docs/guide/linux-server.md +++ b/docs/guide/linux-server.md @@ -65,6 +65,8 @@ pu --machine server --project ~/src/my-repo status The client forwards its connection over SSH to `~/.pu/daemon.sock` on the server, using your own `~/.ssh/config`, keys and agent. It never starts the remote daemon on its own; if the daemon is stopped, run `pu machine start server`. In the PurePoint app, add the same machine from the sidebar footer; its projects then appear under MACHINES. +Run `pu doctor --machine server` once to check the server for settings that drop connections: sshd's `MaxStartups` and `ClientAliveInterval`, fail2ban, sshguard, `ufw limit` and sleep. It names the fix for each and changes nothing. If you connect from more than one network, give the server a stable address with Tailscale or WireGuard. See [Reliable machine connections](reliable-machine-connections.md). + ## 5. Pair a phone or iPad (optional) With phone access installed (step 1), the phone talks to this server directly over your tailnet. No Mac is involved. Both devices need [Tailscale](https://tailscale.com) connected. diff --git a/docs/guide/reliable-machine-connections.md b/docs/guide/reliable-machine-connections.md new file mode 100644 index 00000000..f31f2387 --- /dev/null +++ b/docs/guide/reliable-machine-connections.md @@ -0,0 +1,165 @@ +# Reliable Machine Connections + +PurePoint reaches other computers over SSH (see [Run PurePoint on a Linux server](linux-server.md) and [Remote machines on Windows](windows.md#remote-machines)). The machine's daemon owns its agents, so a dropped connection never stops remote work, and clients reconnect by themselves. Most connections that drop more often than expected do so because of the network or the server's SSH settings, not PurePoint. This guide covers both, and what to change. + +To check a machine, run: + +```sh +pu doctor --machine +``` + +It reports what it found and the exact fix for each problem, and it changes nothing on either machine. See [Check a machine](#check-a-machine-with-pu-doctor) below. + +## Why connections drop + +- **Your address changes.** A TCP connection is tied to the two addresses it was opened between. Moving from Wi-Fi to Ethernet, joining another network, or a VPN coming up gives your computer a new address, and every connection on the old one is dead, even before ssh notices. PurePoint reconnects, but the drop still happens. +- **Sleep.** A machine that sleeps stops answering. When the client is the one that slept, its connections are usually gone when it wakes. +- **Idle timeouts in NAT and firewalls.** Home routers, carrier NAT and cloud NAT gateways forget a connection that has been silent for a while (often a few minutes), then drop its packets. PurePoint's ssh commands send a keepalive every 15 s, and the server can send its own (`ClientAliveInterval`). +- **Server login limits.** A client that reconnects after a network blip opens several SSH logins at once. sshd's `MaxStartups` (default `10:30:100`) starts dropping new unauthenticated connections at random once 10 are in progress, and fail2ban, sshguard and `ufw limit` (6 connections in 30 s) ban an address that connects too often. The logins that should repair the connection are then refused. + +## Give every machine a stable address + +A WireGuard overlay gives each device an address that stays the same on every network. Roaming between networks then changes only the path underneath, and SSH over the overlay keeps working through short changes. It also removes the need to open SSH to the internet. + +### Tailscale + +[Tailscale](https://tailscale.com) is the easiest way: install it on your computer and on each machine, and sign in to the same tailnet on both. + +```sh +tailscale ip -4 # on the machine: its 100.x.y.z address +tailscale status # on your computer: both devices listed +``` + +With MagicDNS on, each machine is also reachable by name, e.g. `studio` or `studio..ts.net`. + +### Plain WireGuard + +Give each peer a fixed address in a private range (e.g. `10.8.0.0/24`), and set `PersistentKeepalive = 25` on the peer that sits behind NAT so the tunnel stays open while idle. Point SSH at the machine's tunnel address. + +### Point the machine at the overlay address + +`ssh_host` is whatever you pass to `pu machine add`. Use the overlay name or address: + +```sh +pu machine remove studio +pu machine add studio me@studio.example.ts.net +``` + +Or keep the machine's entry and change where its `~/.ssh/config` alias points: + +``` +Host studio + HostName studio.example.ts.net # or 100.x.y.z / 10.8.0.2 + User me +``` + +`pu doctor --machine studio` shows the host, port and user that ssh actually connects to (the `ssh client` line). + +## Server SSH settings + +Set these in `/etc/ssh/sshd_config` on the machine. For each keyword sshd uses the first value it reads, and on most distributions `sshd_config` includes `/etc/ssh/sshd_config.d/*.conf` at the top, so a file there (e.g. `/etc/ssh/sshd_config.d/purepoint.conf`) overrides the main file. + +``` +MaxStartups 30:30:100 +ClientAliveInterval 15 +ClientAliveCountMax 4 +TCPKeepAlive yes +``` + +- `MaxStartups 30:30:100` lets 30 logins be in progress before sshd starts dropping new ones, enough for a reconnect burst. macOS starts one sshd per connection, so it does not limit logins there. +- `ClientAliveInterval 15` with `ClientAliveCountMax 4` makes the server send a keepalive every 15 s, which keeps NAT state alive from its side too, and closes a session after a minute with no reply. +- `TCPKeepAlive yes` (the default) lets the server notice a client whose network went away. +- `MaxSessions` (default 10) limits how many sessions one SSH connection can carry. The iPad app carries each daemon connection as a session, and opens another connection past this limit. + +Check the effective values with `sudo sshd -T | grep -Ei '^(maxstartups|maxsessions|clientalive|tcpkeepalive)'`, then reload sshd: `sudo systemctl reload ssh` on Debian and Ubuntu, `sudo systemctl reload sshd` on most other distributions. On macOS, new connections use the change at once. + +If logins are slow (`pu doctor` warns when one takes more than 3 s), set `UseDNS no` in `sshd_config`, and `GSSAPIAuthentication no` for the host in your `~/.ssh/config`. Every reconnect pays for a slow login. + +## fail2ban, sshguard and ufw + +These protect SSH from password guessing, but they also ban a legitimate client that reconnects often. Keep them, and exempt your own devices. + +**fail2ban.** In `/etc/fail2ban/jail.local`, under `[DEFAULT]`, list your computer's address (or your overlay's range) in `ignoreip`, then restart fail2ban: + +```ini +[DEFAULT] +ignoreip = 127.0.0.1/8 ::1 100.64.0.0/10 +``` + +```sh +sudo systemctl restart fail2ban +sudo fail2ban-client status sshd # currently banned addresses +sudo fail2ban-client set sshd unbanip # lift a ban now +``` + +`100.64.0.0/10` is the range Tailscale uses. Use your WireGuard subnet, or a single address, otherwise. `pu doctor` prints the address the machine sees your computer connect from. + +**sshguard.** Add the address or range to its whitelist file (`WHITELIST_FILE` in `/etc/sshguard/sshguard.conf`; `/etc/sshguard/whitelist` on Debian and Ubuntu), then `sudo systemctl restart sshguard`. + +**ufw.** `ufw limit ssh` denies an address that opens 6 connections within 30 s. Replace the limit with an allow rule, adding the new rule before removing the old one so you are never locked out: + +```sh +sudo ufw allow 22/tcp +sudo ufw delete limit 22/tcp +``` + +Use the rule as `sudo ufw status` shows it (`22/tcp`, `OpenSSH`, or your SSH port). To keep a limit for everyone else, allow your overlay first: `sudo ufw allow from 100.64.0.0/10 to any port 22 proto tcp`. + +## Keep the machine awake + +A machine that sleeps drops every connection to it, and its agents stop until it wakes. + +- **macOS:** `sudo pmset -a sleep 0` turns off system sleep. On a laptop, `sudo pmset -c sleep 0` does so only while it is charging. The display can still sleep. Check with `pmset -g`. +- **Linux:** `sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target` stops the machine from suspending, whatever a desktop idle timer or a closed lid asks for. `sudo systemctl unmask …` undoes it. +- **Windows:** set **Settings → System → Power → Sleep** to **Never** when plugged in, or run `powercfg /change standby-timeout-ac 0`. + +## Check a machine with `pu doctor` + +```sh +pu doctor --machine studio +pu doctor --machine studio --json +``` + +It runs three ssh commands and changes nothing on either machine: + +1. `ssh -G ` shows the options your own ssh config sets for the host. PurePoint passes its own `ConnectTimeout`, `TCPKeepAlive`, `ServerAlive*` and `ControlMaster` options on its connections, so these only affect your other ssh sessions. +2. A timed `ssh -o BatchMode=yes true` login. If it fails, `pu doctor` reports why and exits with status 1. This is the only case where it exits non-zero. +3. One login running a `/bin/sh` script on the machine that reads `sshd -T`, whether fail2ban or sshguard are running, `ufw status`, the sleep settings, whether `pu` is on the `PATH` PurePoint uses, whether it supports `pu daemon proxy --mux`, and whether the daemon answers. It never starts the daemon. + +Each result is `ok`, `warn` with the fix beneath it, or `skip` with the reason. `sshd -T` and `ufw status` need root: `pu doctor` tries `sudo -n`, which never prompts, and if that needs a password the check is reported as `skipped (needs sudo)` rather than passing. Run the command it names on the machine yourself in that case. + +On a Windows machine, the checks of the machine itself are skipped: it has no `/bin/sh`. The client and login checks still run. + +Example: + +``` +Checking studio (me@studio). Nothing is changed on either machine. + + ok ssh client connects to studio.example.ts.net port 22 as me; your config: ... + ok login logged in in 0.4 s + ok remote OS Linux + warn sshd MaxStartups MaxStartups 10:30:100: once 10 logins are in progress sshd drops new ones, so a reconnect burst gets refused + fix: Set `MaxStartups 30:30:100` in /etc/ssh/sshd_config; then reload sshd: ... + warn fail2ban fail2ban is running: it bans an address after repeated failed or dropped logins, ... + fix: Add this computer's address (100.101.102.103) to `ignoreip` under `[DEFAULT]` in /etc/fail2ban/jail.local, ... + skip ufw skipped (needs sudo): `ufw status` needs root and `sudo -n` needs a password. ... + ok daemon running + +5 ok, 2 to fix, 1 skipped. +``` + +## What the connection errors mean + +When an ssh connection fails, PurePoint names the cause after ssh's own message, e.g. `machine studio (me@studio) is unreachable over ssh: kex_exchange_identification: Connection closed by remote host — The server refused the login (rate limit or MaxStartups). …` + +| Message | Cause | What to do | +|---|---|---| +| The server refused the login (rate limit or MaxStartups). | sshd closed or reset the connection before authentication: `MaxStartups`, fail2ban, sshguard or a firewall rate limit. | Raise `MaxStartups` and exempt your address from fail2ban, sshguard and `ufw limit` ([above](#fail2ban-sshguard-and-ufw)). If you are banned now, wait for the ban to expire or lift it from the machine's console. | +| The machine could not be reached over the network (or a firewall such as fail2ban dropped it). | A timeout, no route, a DNS failure, nothing listening on the SSH port, or a connection that dropped mid-session. fail2ban usually drops packets silently, so a ban can look like this too. | Check that the machine is on and awake and that `ssh_host` resolves. Use an overlay address ([above](#give-every-machine-a-stable-address)). If it started after many reconnects, check fail2ban. | +| The server rejected the SSH key. | `Permission denied`: no key the server accepts was offered. | `ssh true` must log in without a prompt. Load your key with `ssh-add`, or add its public key to `~/.ssh/authorized_keys` on the machine. | +| The machine's host key is unknown or changed. | The host is not in `known_hosts`, or its key changed. | Run `ssh ` once and confirm the key. If the machine was reinstalled, remove the old key with `ssh-keygen -R ` first. | +| PurePoint is not installed on the machine. | `pu` was not found there (exit 127, or 9009 on Windows). | Install PurePoint on the machine. `pu` must be in `~/.pu/bin`, `~/.cargo/bin` or on the login `PATH`. | +| The machine is reachable but its daemon is stopped. | The relay reached the machine but no daemon answers (exit 69). | `pu machine start `. | +| The SSH connection failed. | Anything else. | Run `ssh -v true` to see where it stops. | + +Every ssh command PurePoint runs passes `-o ConnectTimeout=10 -o TCPKeepAlive=yes`, so a dial to an unreachable host fails within 10 s. Long-lived connections also pass `-o ServerAliveInterval=15 -o ServerAliveCountMax=3`, so ssh gives up on a silent connection after 45 s and PurePoint reconnects. diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 39208049..5ef6ada8 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -104,6 +104,10 @@ PurePoint uses PTY-based terminal emulation. If output looks wrong: - Some TUI applications may not render correctly in all pane sizes - Try resizing the pane or detaching/reattaching +## Remote machine keeps disconnecting + +Run `pu doctor --machine `. It checks the machine's SSH server, firewall and sleep settings and names the fix for each, without changing anything. An error such as "The server refused the login (rate limit or MaxStartups)" names the cause; [Reliable machine connections](reliable-machine-connections.md#what-the-connection-errors-mean) explains each one. + ## Getting help - File issues at [github.com/2witstudios/purepoint/issues](https://github.com/2witstudios/purepoint/issues) diff --git a/docs/guide/windows.md b/docs/guide/windows.md index 051ac2db..d3c9567c 100644 --- a/docs/guide/windows.md +++ b/docs/guide/windows.md @@ -59,6 +59,8 @@ Windows has no `launchd` or `systemd`. Autostart uses your user's Run key, and a `pu machine add ` and the app's **Machines** section reach other computers over SSH with Windows' built-in OpenSSH client (`ssh.exe`). Each daemon connection runs `pu daemon proxy` on the remote host. Linux, macOS and Windows hosts all work, and the remote host must have PurePoint installed. Your `~\.ssh\config`, keys and agent are used as they are. Set `PU_SSH` to point at a different `ssh.exe`. +If a machine goes offline more often than your network does, run `pu doctor --machine `. It checks the machine's SSH server for login limits (`MaxStartups`, fail2ban, `ufw limit`) and sleep settings that drop connections, and names the fix for each. See [Reliable machine connections](reliable-machine-connections.md), which also covers a Tailscale or WireGuard address for machines you reach from changing networks. + ## Phone pairing With [Tailscale](https://tailscale.com) installed and connected: diff --git a/docs/product/cli.md b/docs/product/cli.md index 50d04864..098a9cb8 100644 --- a/docs/product/cli.md +++ b/docs/product/cli.md @@ -95,6 +95,7 @@ Key behaviors: | `pu machine remove ` | `--json` | Forget a machine; its daemon and agents keep running | | `pu machine status [name]` | `--json` | Probe machine daemons over SSH: `running`, `busy`, `stopped`, `incompatible` or `unreachable`. Never starts a daemon | | `pu machine start ` | — | Start a machine's daemon by running `pu health` there over ssh | +| `pu doctor --machine ` | `--json` | Check a machine for settings that drop connections and print a fix for each; changes nothing (MACH-019, see below) | | `pu phone install` / `uninstall` | `--now`, `--port` | Linux only: write, enable (and start) or remove the `pu-pointguard.service` user unit for the payload matching this `pu` (LPH-003). Uninstall keeps device trust | | `pu phone start` / `stop` / `restart` / `status` | `--force` (stop, restart), `--json` (status) | Service lifecycle. `stop`/`restart` ask the bridge to stop only while idle; `restart` moves to this `pu`'s payload and prunes older ones | | `pu phone run` | `--port` | Run the bridge in the foreground with an empty, explicit environment (hosts without systemd) | @@ -134,15 +135,26 @@ Conversation reads (protocol 8): `Read { project_root, agent_id, limit, since?, See [Machines over SSH](machines.md) (MACH-003, MACH-006, MACH-008). `pu --machine ` looks the name up case-insensitively in `~/.pu/machines.json` and talks to that machine's daemon: -- If the app's forward `~/.pu/machines//daemon.sock` answers `Health`, it is reused. Otherwise the CLI resolves the remote `$HOME` (`ssh -o BatchMode=yes 'printf %s "$HOME"'`), opens a private `ssh -N -L ~/.pu/machines//cli-.sock:/.pu/daemon.sock` forward, waits up to 10s for it, and kills ssh and removes the socket when the command ends. Sockets left by CLI processes that died are swept on the next run. +- If the app's forward `~/.pu/machines//daemon.sock` answers `Health`, it is reused. Otherwise the CLI resolves the remote `$HOME` (`ssh -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none 'printf %s "$HOME"'`), opens a private `ssh -N -L ~/.pu/machines//cli-.sock:/.pu/daemon.sock` forward, waits up to 10s for it, and kills ssh and removes the socket when the command ends. Sockets left by CLI processes that died are swept on the next run. - The daemon is never auto-started. A stopped daemon fails with ``daemon not running on ; start it with `pu machine start ` ``; a protocol mismatch or unreachable host fails too. No local daemon is ever started. - Local paths are never sent: project-scoped commands require `--project ` (`PU_PROJECT_ROOT` and cwd are ignored); agent-targeted commands (`status --agent`, `kill --agent`, `send`, `attach`, `read`, `logs`, `bench`, `play`) resolve the agent by id on that daemon. - `init`, `channel` and `gate` work on local files and reject `--machine`. `spawn --template` fetches the template from the machine's daemon (`GetTemplate`); `spawn --file` still reads the local file. `prompt list` never falls back to local templates. - The global plugin freshness check is skipped, as for `--socket`. - `PU_SSH` overrides the ssh binary (default `/usr/bin/ssh`); used by tests. +- Every ssh command passes `-o ConnectTimeout=10 -o TCPKeepAlive=yes`; the forward and the Windows relay also pass `-o ServerAliveInterval=15 -o ServerAliveCountMax=3` (MACH-017). An ssh failure is reported as `machine () is unreachable over ssh: — ` (MACH-018); `pu machine start` reports `failed to start the daemon on : — `. Validation: `crates/pu-cli/tests/machines.rs` drives real CLI processes through a fake `PU_SSH` against an in-process daemon, including a stopped daemon (no local daemon started, no sockets left) and an unreachable host. +## Machine readiness check (`pu doctor`) + +See [Machines over SSH](machines.md) (MACH-019) for the remote script's contract. `pu doctor --machine ` needs `--machine` (without it, it fails with a usage error) and opens no daemon endpoint: it runs before `--machine` connects, so it works when the forward cannot open. It runs `ssh -G `, a timed `ssh -T true` login, and, only if that login worked, one `ssh -T '/bin/sh -s'` with the check script on stdin. A pure `evaluate(report)` (`crates/pu-cli/src/commands/doctor.rs`) turns the results into findings, each `ok`, `warn` (with `fix`), `skipped` (with the reason) or `fail`. + +- Exit status is 1 only when the login fails (ssh exit 255 or timeout); the report is still printed, then `machine () could not be reached: `. +- `--json`: `{ machine, ssh_host, reachable, findings: [{ check, status, detail, fix? }] }`. +- A check that needs root and could not run through `sudo -n` is `skipped (needs sudo)`, never `ok`. A key the script did not print is `skipped`. + +Validation: unit tests in `doctor.rs` evaluate fixture outputs; `tests/machines.rs` runs the real script through the fake ssh against stand-in `sshd`, `sudo`, `systemctl`, `ufw` and this build's `pu`, with and without sudo, and against an unreachable host. + ## Daemon proxy (`pu daemon proxy`) See [Machines over SSH](machines.md) (MACH-003). Clients that cannot `ssh -L` a Unix socket (the iPad app) open an SSH exec channel running `pu daemon proxy`; each channel is exactly one daemon connection carrying newline-delimited JSON. diff --git a/docs/product/machines.md b/docs/product/machines.md index 9483536d..c109f22b 100644 --- a/docs/product/machines.md +++ b/docs/product/machines.md @@ -130,7 +130,7 @@ Machine = SSH destination. Endpoint = forwarded socket (Mac, Linux) or exec rela -L :/.pu/daemon.sock ``` -Remote home is resolved once per connection with `ssh -o BatchMode=yes -o ControlMaster=no -o ControlPath=none 'printf %s "$HOME"'`. Start daemon runs `ssh -o ControlMaster=no -o ControlPath=none ''`, where the start command (one argument) is exactly `/bin/sh -c 'PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH"; export PATH; exec pu health'`: `/bin/sh` makes it work whatever the remote login shell is (fish and csh can't parse the assignment), and the `PATH` prefix lets `pu` resolve (non-interactive SSH has a minimal `PATH`); `pu` then starts the `pu-engine` beside itself or in `~/.pu/bin`, never one found on `PATH`. It is given 60 s. The spawned daemon detaches into its own session with null stdio, so the SSH command returns and the daemon outlives it. `-o ControlMaster=no -o ControlPath=none` (on every ssh command) keeps a user's multiplexing config from routing a command through, or parking the forward on, a shared master that outlives it. +Remote home is resolved once per connection with `ssh -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none 'printf %s "$HOME"'`. Start daemon runs `ssh -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none ''`, where the start command (one argument) is exactly `/bin/sh -c 'PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH"; export PATH; exec pu health'`: `/bin/sh` makes it work whatever the remote login shell is (fish and csh can't parse the assignment), and the `PATH` prefix lets `pu` resolve (non-interactive SSH has a minimal `PATH`); `pu` then starts the `pu-engine` beside itself or in `~/.pu/bin`, never one found on `PATH`. It is given 60 s. The spawned daemon detaches into its own session with null stdio, so the SSH command returns and the daemon outlives it. `-o ControlMaster=no -o ControlPath=none` (on every ssh command) keeps a user's multiplexing config from routing a command through, or parking the forward on, a shared master that outlives it. ### iPad relay (MACH-009) @@ -218,6 +218,18 @@ The app then types the returned path, shell-escaped, into the agent's terminal w - `pu --machine ` — conflicts with `--socket`. On macOS and Linux it uses the app's live forward when its socket answers; otherwise opens a private `ssh -N -L` forward on `cli-.sock` for the invocation, records the ssh pid in `cli-.sock.pid`, and closes both on exit. SIGTERM, SIGHUP and SIGINT also close it before the CLI exits. Before opening one it sweeps files whose CLI pid is dead, sending SIGTERM to a recorded pid only if it is still an `ssh` process whose arguments contain `-L /cli-.sock:`. Never starts a daemon. Project-scoped commands require `--project `; agent-targeted commands resolve by id on that machine. On Windows it runs the Windows relay per connection instead, with no forward or sweep (MACH-012). - `pu machine list|add |remove |status []|start `. +- `pu doctor --machine [--json]` — the readiness check below (MACH-019). It opens no forward or relay; it exits 1 only when the login fails. +- A failed ssh command reports ssh's message followed by its cause's summary (MACH-018), e.g. `machine studio (me@studio) is unreachable over ssh: kex_exchange_identification: Connection closed by remote host — The server refused the login (rate limit or MaxStartups). …`. + +### Readiness check (MACH-019) + +`pu doctor --machine ` runs, from any client OS (the CLI's ssh, `PU_SSH` included): + +1. `ssh -G `: the client's effective `serveraliveinterval`, `serveralivecountmax`, `connecttimeout`, `tcpkeepalive`, `controlmaster`, `controlpersist` (and `hostname`, `port`, `user`). It never connects, so it gets no connect options. +2. `ssh -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none true`, timed. Any exit but 255 counts as a login (`true` is not a command on Windows). Over 3 s is a warning; a failure is reported with its cause and ends the check. +3. The same options with the remote command `/bin/sh -s` and the check script on stdin, so no quoting has to survive the login shell. The script runs inside a function with stdin from `/dev/null`, puts `$HOME/.pu/bin:$HOME/.cargo/bin` before `PATH` (as the start command does) and `/usr/sbin:/sbin` after it, and prints `key=value` lines: `doctor=1`, `os` (`uname -s`), `client_addr` (from `SSH_CLIENT`), `sshd_t` (`plain`, `sudo` or `unavailable`: `sshd -T`, then `sudo -n sshd -T`) with `sshd.port|maxstartups|maxsessions|clientaliveinterval|clientalivecountmax|tcpkeepalive`, `fail2ban` and `sshguard` (`active`, `inactive` or `unknown`, from `systemctl is-active` or `pgrep`), on Linux `ufw` (`absent`, `inactive`, `active` or `needs_sudo`, from `sudo -n ufw status`) with one `ufw.limit=` per LIMIT rule, `sleep.pmset` (macOS `pmset -g` sleep minutes) or `sleep.target= ` for `sleep`, `suspend`, `hibernate` and `hybrid-sleep`, `pu` (its path or `missing`), `pu.mux` (`yes` when `pu daemon proxy --help` mentions `--mux`), `daemon` (`running`, `busy`, `stopped` or `unknown`, from `pu --socket ~/.pu/daemon.sock daemon status`, which never starts a daemon, unlike `pu health`), and `done=1`. Output without `doctor=1` from a command that did not fail with 255 means a Windows machine, and the machine checks are skipped with that reason. + +Findings name the exact change: `MaxStartups` below 30 → `MaxStartups 30::` (not on macOS, whose launchd starts one sshd per connection); `ClientAliveInterval` 0 or above 60 → `ClientAliveInterval 15` and `ClientAliveCountMax 4`; `MaxSessions` below 10 → `MaxSessions 10`; `TCPKeepAlive no` → `yes`; fail2ban → the client's address in `ignoreip` in `/etc/fail2ban/jail.local`; sshguard → its whitelist; a `ufw` LIMIT rule on the ssh port, `ssh` or `OpenSSH` → `ufw allow` it, then delete the limit; macOS sleep → `sudo pmset -a sleep 0`; Linux sleep targets not masked → `sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target`; `pu` missing → install it; no `--mux` → upgrade PurePoint on that machine; daemon stopped → `pu machine start `. A check needing root that `sudo -n` could not run is `skipped (needs sudo)`, never passing. The user guide is `docs/guide/reliable-machine-connections.md`. ## Edge Cases From 5dc0bc5a5dfb39302bb884774ad6f2f71d34e05c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:00:06 +0000 Subject: [PATCH 08/21] =?UTF-8?q?feat(apple):=20harden=20machine=20connect?= =?UTF-8?q?ions=20(MACH-014=20=E2=80=93=20MACH-018)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ssh: every MachineSSH command passes ConnectTimeout=10 and TCPKeepAlive=yes (MACH-017). - Backoff: SSHReconnectBackoff (now shared by macOS and iPad) steps 1, 2, 4, 8, 15 s with equal jitter; the macOS forward supervisor uses it instead of its 2 → 60 s doubling (MACH-016). - Wake / network / foreground: MachineNetworkWatcher (NWPathMonitor on both platforms, NSWorkspace.didWakeNotification and app activation on the Mac) nudges every machine: the backoff resets, the supervisor's now interruptible waits end, a forward that is up is probed at once and replaced if it does not answer. With no usable path machines report "Waiting for network" and start no ssh. The iPad feeds path changes (and its return to the foreground) into reconnect-now and probe-after-foreground. - macOS reconnects reuse the remote home resolved on the first connect; the cache is cleared when the forward fails to come up. - SSHFailureCause mirrors crates/pu-core/src/ssh_failure.rs; offline states carry the cause and rows show its summary. MachineState keeps a 50-entry connection log, shown from the machine's new "Connection Log…" menu item on both platforms (MACH-018). - Attaches reset their retry count after every successful attach, and remote ones wait for their machine to report connected (plus 0–1 s jitter) instead of spending retries (MACH-015). Status, grid and projects subscriptions for a remote endpoint do the same (MACH-014). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- .../purepoint-macos/Models/ProjectKey.swift | 4 +- .../Services/DaemonAttachSession.swift | 90 +++++- .../Services/DaemonClient.swift | 3 + .../Services/DaemonGridSubscription.swift | 19 ++ .../Services/DaemonProjectsSubscription.swift | 18 ++ .../Services/DaemonStatusSubscription.swift | 19 ++ .../Services/MachineConnection+iOS.swift | 82 +++++- .../Services/MachineConnection.swift | 215 +++++++++++--- .../Services/MachineConnectivity.swift | 63 ++++ .../Services/MachineNetworkWatcher.swift | 86 ++++++ .../Services/SSH/SSHFailureCause.swift | 109 +++++++ .../Services/SSH/SSHMachineSession.swift | 31 -- .../Services/SSH/SSHReconnectBackoff.swift | 53 ++++ .../purepoint-macos/State/AppState.swift | 17 ++ .../State/MachineConnectionLog.swift | 76 +++++ .../purepoint-macos/State/MachineState.swift | 45 ++- .../Views/Sidebar/AddMachineSheet+iOS.swift | 4 +- .../Sidebar/MachineConnectionLogView.swift | 67 +++++ .../Sidebar/RemoteFolderPicker+iOS.swift | 2 +- .../Views/Sidebar/SidebarMenuModel.swift | 3 + .../Views/Sidebar/SidebarOutlineModel.swift | 2 +- ...SidebarOutlineViewController+Actions.swift | 6 +- ...rOutlineViewController+ConnectionLog.swift | 34 +++ .../SidebarOutlineViewController+iOS.swift | 2 +- .../SidebarOutlineViewController.swift | 2 +- .../MachineConnectionHardeningTests.swift | 275 ++++++++++++++++++ .../purepoint-macosTests/MachinesTests.swift | 42 ++- .../SSHMachineRegistryTests.swift | 7 +- .../SSHTransportTests.swift | 19 -- .../SidebarMenuModelTests.swift | 11 +- ...SidebarOutlineViewControllerIOSTests.swift | 2 +- docs/product/desktop-app.md | 2 +- 32 files changed, 1269 insertions(+), 141 deletions(-) create mode 100644 apps/purepoint-macos/purepoint-macos/Services/MachineConnectivity.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Services/MachineNetworkWatcher.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Services/SSH/SSHFailureCause.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Services/SSH/SSHReconnectBackoff.swift create mode 100644 apps/purepoint-macos/purepoint-macos/State/MachineConnectionLog.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Views/Sidebar/MachineConnectionLogView.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+ConnectionLog.swift create mode 100644 apps/purepoint-macos/purepoint-macosTests/MachineConnectionHardeningTests.swift diff --git a/apps/purepoint-macos/purepoint-macos/Models/ProjectKey.swift b/apps/purepoint-macos/purepoint-macos/Models/ProjectKey.swift index 8d6601a7..7dfcabba 100644 --- a/apps/purepoint-macos/purepoint-macos/Models/ProjectKey.swift +++ b/apps/purepoint-macos/purepoint-macos/Models/ProjectKey.swift @@ -101,10 +101,9 @@ nonisolated struct DaemonEndpoint: Hashable, Sendable { nonisolated(unsafe) private static var installedProvider: TransportProvider? } -#if os(iOS) nonisolated extension DaemonEndpoint { /// The endpoint a socket path names: a machine's when it is `MachinePaths.socketPath` for - /// that machine, otherwise the (unreachable) local one. + /// that machine, otherwise the local one (unreachable on iOS). init(socketPath: String) { let parts = socketPath.split(separator: "/") if parts.count >= 2, parts.last == "daemon.sock", let id = UUID(uuidString: String(parts[parts.count - 2])), @@ -116,7 +115,6 @@ nonisolated extension DaemonEndpoint { } } } -#endif /// Filesystem locations shared with the CLI (`crates/pu-core/src/paths.rs`). nonisolated enum MachinePaths { diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonAttachSession.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonAttachSession.swift index 812d2124..e8d12783 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonAttachSession.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonAttachSession.swift @@ -16,6 +16,8 @@ actor DaemonAttachSession { /// when the agent's process exits. Callers must not blindly reattach: each /// attach replays the agent's whole output buffer. private(set) var didStreamEnd = false + /// Attaches the daemon has confirmed (`attach_ready`); each one resets the retry count. + private var successfulAttaches = 0 private var onFirstOutput: (() -> Void)? /// Called on the main actor after each chunk of *live* output is fed to the terminal — /// never for the replay of the daemon's buffer that every attach starts with. @@ -51,13 +53,11 @@ actor DaemonAttachSession { func start() async { guard !stopped else { return } - let fastRetries = 5 - let fastDelay: UInt64 = 100_000_000 // 100ms - let slowDelay: UInt64 = 2_000_000_000 // 2s - var retries = 0 - let maxRetries = 20 + var policy = AttachRetryPolicy() + let machineId = client.machineId - while !stopped { + attaching: while !stopped { + let attachedBefore = successfulAttaches do { try await runAttachLoop() // Normal exit (agent completed) — don't reconnect @@ -79,24 +79,46 @@ actor DaemonAttachSession { // without spending retries while it is in the background. if await AppActivity.shared.isInBackground { await AppActivity.shared.untilForeground() - retries = 0 + policy.reset() continue } #endif - // Connection lost — attempt reconnect with backoff - retries += 1 - print("[DaemonAttach \(agentId.prefix(8))] retry \(retries): \(error.localizedDescription)") - guard !stopped, retries <= maxRetries else { break } - let delay = retries <= fastRetries ? fastDelay : slowDelay - do { - try await Task.sleep(nanoseconds: delay) - } catch { - break // CancellationError — exit immediately + let decision = policy.recordFailure( + attached: successfulAttaches != attachedBefore, + machineIsDown: MachineConnectivity.shared.shouldWait(forMachine: machineId)) + switch decision { + case .waitForMachine: + // The machine's connection is down: wait for it however long it takes, then + // reattach; the daemon replays the buffer, so nothing is lost (MACH-015). + print("[DaemonAttach \(agentId.prefix(8))] waiting for the machine: \(error.localizedDescription)") + guard let machineId, await waitForMachine(machineId) else { break attaching } + case .retry(let delay): + // Connection lost — attempt reconnect with backoff + print("[DaemonAttach \(agentId.prefix(8))] retry \(policy.retries): \(error.localizedDescription)") + guard !stopped else { break attaching } + do { + try await Task.sleep(for: delay) + } catch { + break attaching // CancellationError — exit immediately + } + case .giveUp: + break attaching } } } } + /// Wait until the machine reports connected, then a random 0–1 s so its panes do not all + /// reattach at once (MACH-014). False when stopped or cancelled meanwhile. + private func waitForMachine(_ machineId: UUID) async -> Bool { + while !stopped, !MachineConnectivity.shared.isConnected(machineId) { + do { try await Task.sleep(for: MachineConnectivity.pollInterval) } catch { return false } + } + guard !stopped else { return false } + do { try await Task.sleep(for: MachineConnectivity.resumeDelay()) } catch { return false } + return !stopped + } + /// Send terminal input to the daemon. Awaiting ensures actor serializes writes. func sendInput(_ data: Data) async { guard let conn = connection else { return } @@ -184,6 +206,7 @@ actor DaemonAttachSession { throw DaemonAttachError.unexpectedResponse } print("[DaemonAttach \(agentId.prefix(8))] attached successfully") + successfulAttaches += 1 let focused = await MainActor.run { guard let tv else { return false } @@ -337,6 +360,41 @@ actor DaemonAttachSession { } } +/// What an attach does after its connection failed (MACH-015). The retry count resets after +/// every successful attach, so a pane that keeps reattaching never runs out. A remote pane +/// whose machine is down waits for the machine instead of spending retries, however long the +/// outage lasts. A pane that cannot attach while its daemon is reachable still gives up after +/// `maxRetries`. +nonisolated struct AttachRetryPolicy: Sendable { + static let fastRetries = 5 + static let maxRetries = 20 + static let fastDelay: Duration = .milliseconds(100) + static let slowDelay: Duration = .seconds(2) + + enum Decision: Equatable, Sendable { + case retry(after: Duration) + case waitForMachine + case giveUp + } + + private(set) var retries = 0 + + /// `attached`: the failed run attached before it failed. `machineIsDown`: the pane is + /// remote and its machine does not report connected. + mutating func recordFailure(attached: Bool, machineIsDown: Bool) -> Decision { + if attached { retries = 0 } + if machineIsDown { return .waitForMachine } + retries += 1 + guard retries <= Self.maxRetries else { return .giveUp } + return .retry(after: retries <= Self.fastRetries ? Self.fastDelay : Self.slowDelay) + } + + /// Start counting again (the iPad app came back from the background). + mutating func reset() { + retries = 0 + } +} + enum DaemonAttachError: Error, LocalizedError { case attachFailed(String) case unexpectedResponse diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonClient.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonClient.swift index 85da7d66..3abf874e 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonClient.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonClient.swift @@ -36,6 +36,9 @@ nonisolated final class DaemonClient: @unchecked Sendable { #endif } + /// The machine this client's daemon runs on, nil for the local daemon. + var machineId: UUID? { DaemonEndpoint(socketPath: socketPath).machineId } + /// Send a single request and return the response. /// Cancellation-aware: cancelling the task aborts a pending connect and closes the /// stream, which completes any pending receive with an error instead of leaving the diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonGridSubscription.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonGridSubscription.swift index b4358a60..6abf7d06 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonGridSubscription.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonGridSubscription.swift @@ -44,6 +44,14 @@ actor DaemonGridSubscription { continue } #endif + // A remote machine that is down: only its supervisor reconnects. Resubscribe + // once it is back, without spending retries (MACH-014). + if let machineId = client.machineId, MachineConnectivity.shared.shouldWait(forMachine: machineId) { + guard await waitForMachine(machineId) else { break } + retries = 0 + backoff = 500_000_000 + continue + } retries += 1 guard !stopped, retries <= maxRetries else { break } do { @@ -74,6 +82,17 @@ actor DaemonGridSubscription { // MARK: - Private + /// Wait until the machine reports connected, then a random 0–1 s so its streams do not + /// all resubscribe at once (MACH-014). False when stopped or cancelled meanwhile. + private func waitForMachine(_ machineId: UUID) async -> Bool { + while !stopped, !MachineConnectivity.shared.isConnected(machineId) { + do { try await Task.sleep(for: MachineConnectivity.pollInterval) } catch { return false } + } + guard !stopped else { return false } + do { try await Task.sleep(for: MachineConnectivity.resumeDelay()) } catch { return false } + return !stopped + } + private func runSubscriptionLoop() async throws { let reg = self.registry diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonProjectsSubscription.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonProjectsSubscription.swift index 47fb4a24..46185447 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonProjectsSubscription.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonProjectsSubscription.swift @@ -34,6 +34,13 @@ actor DaemonProjectsSubscription { continue } #endif + // A remote machine that is down: only its supervisor reconnects. Resubscribe + // once it is back (MACH-014). + if let machineId = client.machineId, MachineConnectivity.shared.shouldWait(forMachine: machineId) { + guard await waitForMachine(machineId) else { return } + backoff = Self.initialBackoff + continue + } } guard !stopped else { return } do { try await Task.sleep(nanoseconds: backoff) } catch { return } @@ -47,6 +54,17 @@ actor DaemonProjectsSubscription { connection = nil } + /// Wait until the machine reports connected, then a random 0–1 s so its streams do not + /// all resubscribe at once (MACH-014). False when stopped or cancelled meanwhile. + private func waitForMachine(_ machineId: UUID) async -> Bool { + while !stopped, !MachineConnectivity.shared.isConnected(machineId) { + do { try await Task.sleep(for: MachineConnectivity.pollInterval) } catch { return false } + } + guard !stopped else { return false } + do { try await Task.sleep(for: MachineConnectivity.resumeDelay()) } catch { return false } + return !stopped + } + private func run(onChange: @escaping @MainActor ([String]) -> Void) async throws { let (conn, reader) = try await client.connect() // Stopped while connecting: nothing else would ever close this connection. diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonStatusSubscription.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonStatusSubscription.swift index 50fe9c35..858f2f13 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonStatusSubscription.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonStatusSubscription.swift @@ -57,6 +57,14 @@ actor DaemonStatusSubscription { continue } #endif + // A remote machine that is down: only its supervisor reconnects. Resubscribe + // once it is back, instead of retrying or declaring its daemon lost (MACH-014). + if let machineId = client.machineId, MachineConnectivity.shared.shouldWait(forMachine: machineId) { + guard await waitForMachine(machineId) else { break } + retries = 0 + backoff = 500_000_000 + continue + } retries += 1 guard !stopped, retries <= maxRetries else { break } if subscribed || retries == Self.retriesBeforeDaemonLost, let onDaemonLost { @@ -82,6 +90,17 @@ actor DaemonStatusSubscription { // MARK: - Private + /// Wait until the machine reports connected, then a random 0–1 s so its streams do not + /// all resubscribe at once (MACH-014). False when stopped or cancelled meanwhile. + private func waitForMachine(_ machineId: UUID) async -> Bool { + while !stopped, !MachineConnectivity.shared.isConnected(machineId) { + do { try await Task.sleep(for: MachineConnectivity.pollInterval) } catch { return false } + } + guard !stopped else { return false } + do { try await Task.sleep(for: MachineConnectivity.resumeDelay()) } catch { return false } + return !stopped + } + private func runSubscriptionLoop( onEvent: @escaping @MainActor ([WorktreeModel], [AgentModel]) -> Void ) async throws { diff --git a/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift b/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift index 1c3f8f09..23732893 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift @@ -106,6 +106,26 @@ actor MachineConnection { await probeAndReport(afterForeground: true) } + /// A network path change (MACH-016): forget the backoff and act now. A session that is up + /// is probed at once, as after the foreground, and replaced if that probe times out; one + /// that is down, waiting out its backoff or the network, connects again now. A supervisor + /// stopped for a host-key decision stays stopped. + func nudge() async { + guard supervisor != nil else { return } + await session.resetBackoff() + let isConnected = await session.isConnected + // A disconnect may have run meanwhile; it must not be undone. + guard supervisor != nil else { return } + if isConnected { + // Without a path a probe can only time out; the supervisor waits for one instead. + guard NetworkPathStatus.shared.isSatisfied else { return } + await probeAndReport(afterForeground: true) + } else { + stopSupervising() + connect() + } + } + /// Probe now rather than at the next interval — after Start daemon, for instance. func refreshNow() async { guard supervisor != nil, await session.isConnected else { return } @@ -175,6 +195,17 @@ actor MachineConnection { Task { await self?.primaryDropped() } } while isCurrent(generation) { + if !NetworkPathStatus.shared.isSatisfied, !(await session.isConnected) { + // No usable path: no connect until one returns (MACH-016). The path change + // nudges this connection, which restarts the supervisor at once. + report(.waitingForNetwork) + while isCurrent(generation), !NetworkPathStatus.shared.isSatisfied { + try? await Task.sleep(for: .seconds(1)) + } + guard isCurrent(generation) else { return } + await session.resetBackoff() + continue + } // As on the Mac, a machine whose last attempt failed reads Offline while it waits // out the backoff, and Connecting only once the next attempt starts. let retryDelay = await session.pendingRetryDelay @@ -189,12 +220,12 @@ actor MachineConnection { guard isCurrent(generation) else { return } // Never retried on its own: the user confirms, compares or resets. onTrust(refusal) - report(.offline(refusal.localizedDescription)) + report(.offline(refusal.localizedDescription, cause: .hostKey)) supervisor = nil return } catch { guard isCurrent(generation) else { return } - report(.offline(error.localizedDescription)) + report(.offline(error.localizedDescription, cause: SSHFailureCause.of(error))) // The session paces the next attempt (backoff); a short pause keeps a cancelled // sleep from spinning. try? await Task.sleep(for: .milliseconds(100)) @@ -203,8 +234,21 @@ actor MachineConnection { guard isCurrent(generation) else { return } onTrust(nil) tracker = HealthProbeTracker() + var afterPathReturned = false while isCurrent(generation), await session.isConnected { - let conclusive = await probeAndReport() + if !NetworkPathStatus.shared.isSatisfied { + // Probes cannot pass without a path and would replace a connection that + // may survive a short gap; wait for the path, then probe at once. + report(.waitingForNetwork) + while isCurrent(generation), !NetworkPathStatus.shared.isSatisfied { + guard await session.isConnected else { break } + try? await Task.sleep(for: .seconds(1)) + } + afterPathReturned = true + continue + } + let conclusive = await probeAndReport(afterForeground: afterPathReturned) + afterPathReturned = false guard isCurrent(generation) else { return } // An inconclusive probe (BUSY, or a failure short of the limit) retries soon. let seconds = conclusive ? 10 : 2 @@ -214,7 +258,7 @@ actor MachineConnection { } } guard isCurrent(generation) else { return } - report(.offline("SSH connection closed")) + report(.offline("SSH connection closed", cause: .network)) } } @@ -222,7 +266,7 @@ actor MachineConnection { /// waiting out a probe or its interval, so it reconnects (with the session's backoff). private func primaryDropped() async { guard supervisor != nil, !(await session.isConnected) else { return } - report(.offline("SSH connection closed")) + report(.offline("SSH connection closed", cause: .network)) stopSupervising() connect() } @@ -258,8 +302,8 @@ actor MachineConnection { tracker = HealthProbeTracker() report(.connected(.stopped)) return true - case .unusable(let message): - report(.offline(message)) + case .unusable(let message, let cause): + report(.offline(message, cause: cause)) return true case .timedOut: return false @@ -273,7 +317,7 @@ actor MachineConnection { case timedOut /// SSH works but the relay cannot serve: `pu` missing, a failing relay, or a login /// shell that writes to stdout. - case unusable(String) + case unusable(String, SSHFailureCause) } private func probe() async -> Probe { @@ -297,7 +341,7 @@ actor MachineConnection { switch outcome { case .success(.unknown(type: "parse_error")): return .unusable( - "Unexpected output from the login shell on \(machine). Make sure your shell startup files print nothing for non-interactive sessions.") + "Unexpected output from the login shell on \(machine). Make sure your shell startup files print nothing for non-interactive sessions.", .other) case .success(let response): return .health(MachineHealth.classify(response)) case .failure(DaemonClientError.notRunning): @@ -305,7 +349,7 @@ actor MachineConnection { case .failure(DaemonClientError.requestTimeout), .failure(DaemonClientError.connectTimeout): return .timedOut case .failure(let error as SSHTransportError): - return .unusable(error.localizedDescription) + return .unusable(error.localizedDescription, SSHFailureCause.of(error)) case .failure: return .health(.failed) } @@ -377,4 +421,22 @@ nonisolated struct UnusableDestinationConnector: SSHConnector { throw SSHTransportError.unsupportedDestination(machine: machine.name) } } + +nonisolated extension SSHFailureCause { + /// The cause of a failed iPad connect or relay (MACH-018). Citadel reports what OpenSSH + /// prints as typed errors; the relay's exit status and stderr go through `classify`. + static func of(_ error: Error) -> SSHFailureCause { + if error is SSHTrustError { return .hostKey } + guard let error = error as? SSHTransportError else { + return classify(exit: nil, stderr: error.localizedDescription) + } + switch error { + case .authenticationFailed: return .auth + case .puNotInstalled: return .puMissing + case .relayFailed(_, let status, let detail): return classify(exit: status, stderr: detail) + case .connectFailed(_, let detail): return classify(exit: nil, stderr: detail) + case .unsupportedDestination: return .other + } + } +} #endif diff --git a/apps/purepoint-macos/purepoint-macos/Services/MachineConnection.swift b/apps/purepoint-macos/purepoint-macos/Services/MachineConnection.swift index 41c57b74..a617c967 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/MachineConnection.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/MachineConnection.swift @@ -49,10 +49,23 @@ nonisolated struct HealthProbeTracker: Sendable { nonisolated enum MachineConnectionState: Equatable, Sendable { case disconnected case connecting + /// No usable network path: no SSH attempt is made until one returns (MACH-016). + case waitingForNetwork case connected(DaemonAvailability) - case offline(String) + /// The last attempt failed, or the connection dropped: ssh's own words and their cause + /// (MACH-018). + case offline(String, cause: SSHFailureCause = .other) var isDaemonRunning: Bool { self == .connected(.running) } + + /// Why the machine is offline, for its row: the cause's summary, then what ssh said. An + /// unclassified failure shows ssh's words alone. + var offlineDescription: String? { + guard case .offline(let detail, let cause) = self else { return nil } + if detail.isEmpty { return cause.summary } + if cause == .other { return detail } + return cause.summary + " " + detail + } } /// Resumes a continuation exactly once, whichever of exit, deadline or launch failure is first. @@ -93,19 +106,26 @@ nonisolated enum MachineSSH { /// otherwise park the call on a shared master that outlives it. static let noMultiplexing = ["-o", "ControlMaster=no", "-o", "ControlPath=none"] - /// `ssh -o BatchMode=yes -o ControlMaster=no -o ControlPath=none 'printf %s "$HOME"'` + /// Every ssh call gives up dialing an unreachable host after 10 s and keeps TCP keepalive + /// on, so a dead path is noticed even when ssh's own keepalive is blocked (MACH-017). + static let connectOptions = ["-o", "ConnectTimeout=10", "-o", "TCPKeepAlive=yes"] + + /// `ssh -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no + /// -o ControlPath=none 'printf %s "$HOME"'` static func resolveHomeArguments(sshHost: String) -> [String] { - ["-o", "BatchMode=yes"] + noMultiplexing + [destination(sshHost), "printf %s \"$HOME\""] + ["-o", "BatchMode=yes"] + connectOptions + noMultiplexing + [destination(sshHost), "printf %s \"$HOME\""] } - /// `ssh -N -T -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 - /// -o ServerAliveCountMax=3 -o StreamLocalBindUnlink=yes -o ControlMaster=no - /// -o ControlPath=none -L :/.pu/daemon.sock ` + /// `ssh -N -T -o BatchMode=yes -o ExitOnForwardFailure=yes -o ConnectTimeout=10 + /// -o TCPKeepAlive=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 + /// -o StreamLocalBindUnlink=yes -o ControlMaster=no -o ControlPath=none + /// -L :/.pu/daemon.sock ` static func forwardArguments(localSocket: String, remoteHome: String, sshHost: String) -> [String] { [ "-N", "-T", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", + ] + connectOptions + [ "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "-o", "StreamLocalBindUnlink=yes", @@ -121,9 +141,10 @@ nonisolated enum MachineSSH { static let startDaemonCommand = "/bin/sh -c 'PATH=\"$HOME/.pu/bin:$HOME/.cargo/bin:$PATH\"; export PATH; exec pu health'" - /// `ssh -o ControlMaster=no -o ControlPath=none ''` + /// `ssh -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ControlMaster=no -o ControlPath=none + /// ''` static func startDaemonArguments(sshHost: String) -> [String] { - noMultiplexing + [destination(sshHost), startDaemonCommand] + connectOptions + noMultiplexing + [destination(sshHost), startDaemonCommand] } struct Output: Sendable { @@ -200,12 +221,12 @@ nonisolated enum MachineSSH { } } - /// The remote user's home, resolved once per connection. + /// The remote user's home. A connection resolves it on its first connect and reuses it. static func resolveHome(sshHost: String, processes: OneShotProcesses? = nil) async throws -> String { let output = await run(resolveHomeArguments(sshHost: sshHost), timeout: 20, processes: processes) let home = output.stdout.trimmingCharacters(in: .whitespacesAndNewlines) guard output.status == 0, home.hasPrefix("/") else { - throw MachineConnectionError.ssh(sshErrorMessage(output)) + throw MachineConnectionError.ssh(sshErrorMessage(output), cause: failureCause(output)) } return home } @@ -215,14 +236,26 @@ nonisolated enum MachineSSH { if !message.isEmpty { return message.components(separatedBy: .newlines).last ?? message } return output.status == 0 ? "ssh returned no home directory" : "ssh exited with status \(output.status)" } + + /// Why a one-shot ssh call failed (MACH-018). A negative status is a launch failure or a + /// kill after the deadline, which leave no exit status. + static func failureCause(_ output: Output) -> SSHFailureCause { + SSHFailureCause.classify(exit: output.status >= 0 ? Int(output.status) : nil, stderr: output.stderr) + } } nonisolated enum MachineConnectionError: LocalizedError { - case ssh(String) + case ssh(String, cause: SSHFailureCause) var errorDescription: String? { switch self { - case .ssh(let message): message + case .ssh(let message, _): message + } + } + + var cause: SSHFailureCause { + switch self { + case .ssh(_, let cause): cause } } } @@ -421,9 +454,13 @@ nonisolated final class ForwardProcessHandle: @unchecked Sendable { /// One machine's SSH forward: `~/.pu/machines//daemon.sock` → remote `~/.pu/daemon.sock`. /// -/// Keeps the forward up with backoff while connected, probes the daemon with `health` (and -/// never starts it — MACH-003), and closes the forward on disconnect, removal or quit. The -/// remote daemon and its agents keep running regardless (MACH-004). +/// Keeps the forward up with backoff while connected (`SSHReconnectBackoff`, MACH-016), probes +/// the daemon with `health` (and never starts it — MACH-003), and closes the forward on +/// disconnect, removal or quit. The remote daemon and its agents keep running regardless +/// (MACH-004). A wake, a network path change or the app becoming active (`nudge`) cuts every +/// wait short: the backoff starts over, a forward that is up is probed at once and replaced if +/// it does not answer. With no usable network path it reports waiting for the network and +/// starts no ssh. actor MachineConnection { let machine: Machine let endpoint: DaemonEndpoint @@ -436,6 +473,16 @@ actor MachineConnection { private var lastReported: MachineConnectionState = .disconnected private var generation = 0 private var tracker = HealthProbeTracker() + private var backoff = SSHReconnectBackoff() + /// The remote home resolved on the first successful connect; reconnects reuse it rather + /// than spending an ssh login on it each time. Cleared when the forward fails to come up, + /// so a wrong value heals on the next attempt. + private var remoteHome: String? + /// Bumped by `nudge`; a supervisor waiting in `pause` returns when it changes. + private var nudges = 0 + + /// How finely the supervisor's waits notice a nudge. + private static let pauseStep: Duration = .milliseconds(250) init(machine: Machine, onState: @escaping @Sendable (MachineConnectionState) -> Void) { self.machine = machine @@ -447,6 +494,8 @@ actor MachineConnection { func connect() { guard supervisor == nil else { return } + // The user's Connect: start at once. + backoff.recordSuccess() generation += 1 let current = generation supervisor = Task { await self.supervise(generation: current) } @@ -477,6 +526,15 @@ actor MachineConnection { forwardLock.release() } + /// A wake from sleep, a network path change or the app becoming active (MACH-016): forget + /// the backoff and end whatever wait the supervisor is in, so it reconnects now, or, with + /// the forward up, probes it now and replaces it if that probe fails. + func nudge() { + guard supervisor != nil else { return } + backoff.recordSuccess() + nudges += 1 + } + /// Probe now rather than at the next interval — after Start daemon, for instance. func refreshNow() async { guard supervisor != nil, FileManager.default.fileExists(atPath: endpoint.socketPath) else { return } @@ -499,10 +557,19 @@ actor MachineConnection { !Task.isCancelled && generation == self.generation } + /// How long a wait with nothing to time out (no network path) lasts before it looks again; + /// a nudge or the awaited change ends it sooner. + private static let idleWait: TimeInterval = 3600 + private func supervise(generation: Int) async { - var backoff: UInt64 = 2 while isCurrent(generation) { _ = try? MachinePaths.ensureDirectory(machineId: machine.id) + guard NetworkPathStatus.shared.isSatisfied else { + // No usable path: start no ssh until one returns (MACH-016). + report(.waitingForNetwork) + await pause(seconds: Self.idleWait, generation: generation) { !NetworkPathStatus.shared.isSatisfied } + continue + } if !forwardLock.tryAcquire() { // Another PurePoint instance owns this machine's forward: use it, never end it. await followSharedForward(generation: generation) @@ -510,62 +577,134 @@ actor MachineConnection { } report(.connecting) do { - let home = try await MachineSSH.resolveHome(sshHost: machine.sshHost, processes: oneShots) + let home: String + if let remoteHome { + home = remoteHome + } else { + home = try await MachineSSH.resolveHome(sshHost: machine.sshHost, processes: oneShots) + } guard isCurrent(generation) else { return } let stderr = try launchForward(remoteHome: home) guard await waitForSocket() else { guard isCurrent(generation) else { return } + // The home may be what is wrong (or it changed): resolve it again next time. + remoteHome = nil + let status = exitStatus() stopForward() try? await Task.sleep(for: .milliseconds(200)) - let message = stderr.text.trimmingCharacters(in: .whitespacesAndNewlines) + let message = Self.lastLine(stderr.text) throw MachineConnectionError.ssh( - message.isEmpty ? "SSH forward did not start" : message.components(separatedBy: .newlines).last ?? message) + message.isEmpty ? "SSH forward did not start" : message, + cause: SSHFailureCause.classify(exit: status, stderr: stderr.text)) } - backoff = 2 + remoteHome = home + backoff.recordSuccess() tracker = HealthProbeTracker() - while isCurrent(generation), process?.isRunning == true { - let availability = tracker.record(await probe()) - guard isCurrent(generation) else { return } - if let availability { report(.connected(availability)) } - // An inconclusive probe (BUSY, or a failure short of the limit) retries soon. - let seconds = availability == nil ? 2 : 10 - for _ in 0.. Bool { + var afterNudge = false + while isCurrent(generation), process?.isRunning == true { + if !NetworkPathStatus.shared.isSatisfied { + // Probes cannot pass without a path and would read as a stopped daemon. + report(.waitingForNetwork) + await pause(seconds: Self.idleWait, generation: generation) { + !NetworkPathStatus.shared.isSatisfied && self.process?.isRunning == true + } + afterNudge = true + continue + } + let result = await probe() + guard isCurrent(generation) else { return false } + if afterNudge, result == .failed, lastReported != .connected(.stopped) { + // Up but silent after a wake or a network change: TCP cannot follow an address + // change, so replace it now rather than after ssh's keepalive (MACH-016). + stopForward() + return true + } + let availability = tracker.record(result) + if let availability { report(.connected(availability)) } + // An inconclusive probe (BUSY, or a failure short of the limit) retries soon. + let seconds: TimeInterval = availability == nil ? 2 : 10 + afterNudge = await pause(seconds: seconds, generation: generation) { self.process?.isRunning == true } + } + return false + } + /// Probe the forward another instance owns until this one can take the lock (that /// instance quit or disconnected) or the user disconnects. private func followSharedForward(generation: Int) async { tracker = HealthProbeTracker() while isCurrent(generation) { if forwardLock.tryAcquire() { return } - if FileManager.default.fileExists(atPath: endpoint.socketPath) { + if !NetworkPathStatus.shared.isSatisfied { + report(.waitingForNetwork) + } else if FileManager.default.fileExists(atPath: endpoint.socketPath) { let availability = tracker.record(await probe()) guard isCurrent(generation) else { return } if let availability { report(.connected(availability)) } } else { report(.connecting) } - for _ in 0..<5 where isCurrent(generation) { - try? await Task.sleep(for: .seconds(1)) - } + await pause(seconds: 5, generation: generation) } } + /// Wait up to `seconds` in short steps, ending early when a nudge arrives, `condition` + /// turns false or the supervisor is superseded. Returns true when a nudge ended it. + @discardableResult + private func pause(seconds: TimeInterval, generation: Int, while condition: () -> Bool = { true }) async -> Bool { + let start = nudges + let deadline = ContinuousClock.now + .seconds(seconds) + while isCurrent(generation), nudges == start, condition(), ContinuousClock.now < deadline { + try? await Task.sleep(for: Self.pauseStep) + } + return nudges != start + } + + /// The forward's exit status once it has exited on its own, nil while it runs or after a + /// signal. + private func exitStatus() -> Int? { + guard let process, !process.isRunning, process.terminationReason == .exit else { return nil } + return Int(process.terminationStatus) + } + + /// Why an established forward ended (MACH-018). ssh's words decide when they name a cause; + /// otherwise a link that dropped is the network. + nonisolated static func dropCause(exit: Int?, stderr: String) -> SSHFailureCause { + let cause = SSHFailureCause.classify(exit: exit, stderr: stderr) + return cause == .other ? .network : cause + } + + nonisolated static func lastLine(_ text: String) -> String { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.components(separatedBy: .newlines).last ?? trimmed + } + private func launchForward(remoteHome: String) throws -> OutputCollector { stopForward() // A forward left by a crashed or force-quit run would hold the socket. diff --git a/apps/purepoint-macos/purepoint-macos/Services/MachineConnectivity.swift b/apps/purepoint-macos/purepoint-macos/Services/MachineConnectivity.swift new file mode 100644 index 00000000..0c11b8e2 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Services/MachineConnectivity.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Whether the device has a usable network path, from `MachineNetworkWatcher`'s +/// `NWPathMonitor`. Machine supervisors read it before every SSH attempt: with no path they +/// report the machine as waiting for the network and make no attempt (MACH-016). It reads +/// satisfied until the monitor says otherwise. +nonisolated final class NetworkPathStatus: @unchecked Sendable { + static let shared = NetworkPathStatus() + + private let lock = NSLock() + private var satisfied = true + + var isSatisfied: Bool { lock.withLock { satisfied } } + + func update(satisfied value: Bool) { + lock.withLock { satisfied = value } + } +} + +/// Which machines currently report a running daemon, readable from any actor. A remote +/// machine's streams (status, grid and project subscriptions, terminal attaches) that fail +/// while it is not connected wait here for it to come back instead of retrying on their own, +/// so only the machine's supervisor logs in over SSH during an outage (MACH-014, MACH-015). +/// `MachineState` keeps it current. +nonisolated final class MachineConnectivity: @unchecked Sendable { + static let shared = MachineConnectivity() + + /// How often a waiting stream checks whether its machine is back. + static let pollInterval: Duration = .milliseconds(200) + /// The most a stream waits, once its machine is back, before reconnecting: each picks a + /// uniformly random delay up to this, so a machine's streams do not all resubscribe at once. + static let maxResumeDelayMilliseconds = 1000 + + private let lock = NSLock() + private var connected: Set = [] + + func isConnected(_ machineId: UUID) -> Bool { + lock.withLock { connected.contains(machineId) } + } + + func setConnected(_ isConnected: Bool, machineId: UUID) { + lock.withLock { + if isConnected { + connected.insert(machineId) + } else { + connected.remove(machineId) + } + } + } + + /// Whether a stream to `machineId` that just failed should wait for its machine rather + /// than retry: it is remote and its machine is not connected. A local stream (nil) keeps + /// its own retries. + func shouldWait(forMachine machineId: UUID?) -> Bool { + guard let machineId else { return false } + return !isConnected(machineId) + } + + /// The jitter before a waiting stream reconnects (0–1 s). + static func resumeDelay() -> Duration { + .milliseconds(Int.random(in: 0...maxResumeDelayMilliseconds)) + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Services/MachineNetworkWatcher.swift b/apps/purepoint-macos/purepoint-macos/Services/MachineNetworkWatcher.swift new file mode 100644 index 00000000..8e5b0bf3 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Services/MachineNetworkWatcher.swift @@ -0,0 +1,86 @@ +import Foundation +import Network + +#if os(macOS) +import AppKit +#endif + +/// Tells the machine connections when waiting out their reconnect backoff is pointless +/// (MACH-016): a network path change (`NWPathMonitor`) on both platforms, and on the Mac also +/// waking from sleep and the app becoming active. The iPad's return to the foreground already +/// probes every machine (`AppState.refreshAfterBackground`). It also keeps +/// `NetworkPathStatus` current, so no SSH attempt starts while there is no usable path. +@MainActor +final class MachineNetworkWatcher { + /// Path updates often come in bursts (an interface going down, then another taking over); + /// one nudge follows the last of them. + private static let pathSettleDelay: Duration = .milliseconds(500) + + private let monitor = NWPathMonitor() + private let queue = DispatchQueue(label: "com.purepoint.machine-network-watcher") + private let onChange: @MainActor () -> Void + private var hasInitialPath = false + private var pendingPathChange: Task? + private var workspaceObservers: [any NSObjectProtocol] = [] + private var appObservers: [any NSObjectProtocol] = [] + private var isStarted = false + + init(onChange: @escaping @MainActor () -> Void) { + self.onChange = onChange + } + + func start() { + guard !isStarted else { return } + isStarted = true + monitor.pathUpdateHandler = { @Sendable [weak self] path in + let satisfied = path.status == .satisfied + // Updated here, before any hop, so a supervisor never starts an attempt on a path + // that is already gone. + NetworkPathStatus.shared.update(satisfied: satisfied) + Task { @MainActor in self?.pathChanged() } + } + monitor.start(queue: queue) + #if os(macOS) + workspaceObservers.append( + NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didWakeNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.onChange() } + }) + appObservers.append( + NotificationCenter.default.addObserver( + forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.onChange() } + }) + #endif + } + + func stop() { + guard isStarted else { return } + isStarted = false + monitor.pathUpdateHandler = nil + monitor.cancel() + pendingPathChange?.cancel() + pendingPathChange = nil + #if os(macOS) + for observer in workspaceObservers { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + #endif + for observer in appObservers { NotificationCenter.default.removeObserver(observer) } + workspaceObservers.removeAll() + appObservers.removeAll() + } + + /// The first update is the path at start, not a change. + private func pathChanged() { + guard hasInitialPath else { + hasInitialPath = true + return + } + pendingPathChange?.cancel() + pendingPathChange = Task { [weak self] in + do { try await Task.sleep(for: Self.pathSettleDelay) } catch { return } + self?.onChange() + } + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHFailureCause.swift b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHFailureCause.swift new file mode 100644 index 00000000..1b9d7275 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHFailureCause.swift @@ -0,0 +1,109 @@ +import Foundation + +/// Why an ssh connection attempt failed (MACH-018), from ssh's exit status and stderr. +/// +/// "Offline" alone does not tell a user whether to fix their network, their keys or their +/// server, so every failure is classified into one cause and the machine shows its `summary`. +/// Mirrors `crates/pu-core/src/ssh_failure.rs` exactly: the same causes, the same stderr +/// fragments in the same order, the same exit-code precedence and the same summaries. Keep the +/// two in step. +nonisolated enum SSHFailureCause: String, CaseIterable, Hashable, Sendable { + /// The server closed or reset the connection before authentication: sshd `MaxStartups`, + /// fail2ban, sshguard or a firewall rate limit refused the login. + case serverRefused = "server_refused" + /// The host could not be reached: timeout, no route, unreachable network, DNS failure, + /// connection refused (no sshd listening) or a link that dropped mid-session. + case network + /// The server rejected every key (`Permission denied`). + case auth + /// The host key is unknown or changed. + case hostKey = "host_key" + /// `pu` is not installed on the machine (exit 127 or 9009). + case puMissing = "pu_missing" + /// The relay reached the machine but no daemon answers (exit 69). + case daemonStopped = "daemon_stopped" + /// Anything else. + case other + + /// stderr fragments, matched case-insensitively, in priority order. + static let rules: [(fragment: String, cause: SSHFailureCause)] = [ + ("host key verification failed", .hostKey), + ("remote host identification has changed", .hostKey), + ("no matching host key type", .hostKey), + ("permission denied", .auth), + ("too many authentication failures", .auth), + ("no supported authentication methods", .auth), + // An established session that dropped: the path, not the server's login limits. + ("client_loop", .network), + ("kex_exchange_identification", .serverRefused), + ("ssh_exchange_identification", .serverRefused), + ("connection closed by", .serverRefused), + ("exceeded maxstartups", .serverRefused), + ("could not resolve hostname", .network), + ("name or service not known", .network), + ("nodename nor servname", .network), + ("no such host is known", .network), + ("timed out", .network), + ("no route to host", .network), + ("network is unreachable", .network), + ("host is unreachable", .network), + ("connection refused", .network), + ("broken pipe", .network), + ("connection reset by peer", .network), + ("timeout, server", .network), + ("not responding", .network), + ] + + /// Classify a finished ssh process. `exit` is its status (nil when it was killed or never + /// started); `stderr` is what it wrote. + static func classify(exit: Int?, stderr: String) -> SSHFailureCause { + switch exit { + case 69?: return .daemonStopped + case 127?, 9009?: return .puMissing + default: break + } + return fromStderr(stderr) ?? .other + } + + /// The cause named by an ssh error message, if any rule matches. + static func fromStderr(_ stderr: String) -> SSHFailureCause? { + let lower = stderr.lowercased() + return rules.first { lower.contains($0.fragment) }?.cause + } + + /// A short, user-facing explanation that says where to look. + var summary: String { + switch self { + case .serverRefused: + "The server refused the login (rate limit or MaxStartups). Run `pu doctor --machine` to check its sshd and fail2ban settings." + case .network: + "The machine could not be reached over the network (or a firewall such as fail2ban dropped it)." + case .auth: "The server rejected the SSH key." + case .hostKey: "The machine's host key is unknown or changed." + case .puMissing: "PurePoint is not installed on the machine." + case .daemonStopped: "The machine is reachable but its daemon is stopped." + case .other: "The SSH connection failed." + } + } + + /// A few words for the connection log. + var label: String { + switch self { + case .serverRefused: "Server refused" + case .network: "Network" + case .auth: "Authentication" + case .hostKey: "Host key" + case .puMissing: "PurePoint missing" + case .daemonStopped: "Daemon stopped" + case .other: "Other" + } + } + + /// Whether retrying soon can help: false for causes that need the user to act. + var isTransient: Bool { + switch self { + case .serverRefused, .network, .other: true + case .auth, .hostKey, .puMissing, .daemonStopped: false + } + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHMachineSession.swift b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHMachineSession.swift index d34c7329..df7958ad 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHMachineSession.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHMachineSession.swift @@ -44,37 +44,6 @@ nonisolated protocol SSHConnector: Sendable { func connect(onDisconnect: @escaping @Sendable () -> Void) async throws -> any SSHExecConnection } -// MARK: - Backoff - -/// Reconnect pacing after failed connects: 1, 2, 4, 8, 16, then every 30 s. A success resets it. -nonisolated struct SSHReconnectBackoff: Sendable { - static let schedule: [TimeInterval] = [1, 2, 4, 8, 16, 30] - - private(set) var failures = 0 - private(set) var notBefore: Date? - - static func delay(afterFailures failures: Int) -> TimeInterval { - guard failures > 0 else { return 0 } - return schedule[min(failures, schedule.count) - 1] - } - - mutating func recordFailure(at now: Date) { - failures += 1 - notBefore = now.addingTimeInterval(Self.delay(afterFailures: failures)) - } - - mutating func recordSuccess() { - failures = 0 - notBefore = nil - } - - /// Seconds until the next connect may start. - func remainingDelay(at now: Date) -> TimeInterval { - guard let notBefore else { return 0 } - return max(0, notBefore.timeIntervalSince(now)) - } -} - // MARK: - Session /// A channel opened through a machine session, with the hook that hands its slot back. diff --git a/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHReconnectBackoff.swift b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHReconnectBackoff.swift new file mode 100644 index 00000000..d0cecae3 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Services/SSH/SSHReconnectBackoff.swift @@ -0,0 +1,53 @@ +import Foundation + +/// Reconnect pacing after failed connects, on the Mac and the iPad alike (MACH-016): 1, 2, 4, +/// 8, then every 15 s, each step scaled by a uniformly random factor in [0.5, 1] (equal +/// jitter), so clients that lost the same link do not all log in again at the same moment. A +/// success resets it, and so do a wake, a network path change and a return to the foreground. +nonisolated struct SSHReconnectBackoff: Sendable { + static let schedule: [TimeInterval] = [1, 2, 4, 8, 15] + /// Each delay is its step times a factor in this range. + static let jitterRange: ClosedRange = 0.5...1 + + private(set) var failures = 0 + private(set) var notBefore: Date? + private let jitter: @Sendable () -> Double + + /// `jitter` supplies the factor for each delay; tests pin it. + init(jitter: @escaping @Sendable () -> Double = { Double.random(in: 0.5...1) }) { + self.jitter = jitter + } + + /// The step after `failures` consecutive failures, before jitter (0 for none). + static func step(afterFailures failures: Int) -> TimeInterval { + guard failures > 0 else { return 0 } + return schedule[min(failures, schedule.count) - 1] + } + + /// The step scaled by `factor`, which is clamped to `jitterRange`. + static func delay(afterFailures failures: Int, factor: Double) -> TimeInterval { + step(afterFailures: failures) * min(max(factor, jitterRange.lowerBound), jitterRange.upperBound) + } + + /// Count a failed connect and return how long to wait before the next one. + @discardableResult + mutating func recordFailure(at now: Date) -> TimeInterval { + failures += 1 + let delay = Self.delay(afterFailures: failures, factor: jitter()) + notBefore = now.addingTimeInterval(delay) + return delay + } + + /// A connect succeeded, or something happened that makes waiting pointless (a wake, a + /// network change, the user's Connect): the next connect may start at once. + mutating func recordSuccess() { + failures = 0 + notBefore = nil + } + + /// Seconds until the next connect may start. + func remainingDelay(at now: Date) -> TimeInterval { + guard let notBefore else { return 0 } + return max(0, notBefore.timeIntervalSince(now)) + } +} diff --git a/apps/purepoint-macos/purepoint-macos/State/AppState.swift b/apps/purepoint-macos/purepoint-macos/State/AppState.swift index 70410c79..d157c176 100644 --- a/apps/purepoint-macos/purepoint-macos/State/AppState.swift +++ b/apps/purepoint-macos/purepoint-macos/State/AppState.swift @@ -114,6 +114,9 @@ final class AppState { @ObservationIgnored private var binaryWatcher: ManifestWatcher? #endif @ObservationIgnored private var machineRegistryWatcher: MachineRegistryWatcher? + /// Wake, network path and app-activation events that make every machine reconnect or + /// probe at once (MACH-016). + @ObservationIgnored private var machineNetworkWatcher: MachineNetworkWatcher? #if os(macOS) /// Follows the local daemon's registered projects, which decide this Mac's sidebar. @ObservationIgnored private var localProjectsSubscription: DaemonProjectsSubscription? @@ -523,6 +526,7 @@ final class AppState { FileIOService.removeLocalCopies() reloadMachines() startMachineRegistryWatcher() + startMachineNetworkWatcher() } /// Re-read `~/.pu/machines.json` and diff against the current machines: connect any new @@ -566,6 +570,17 @@ final class AppState { } } + /// Tell every machine when a wake, a network path change or the app becoming active + /// makes waiting out its reconnect backoff pointless. + private func startMachineNetworkWatcher() { + guard machineNetworkWatcher == nil else { return } + let watcher = MachineNetworkWatcher { [weak self] in + for machine in self?.machines ?? [] { machine.networkChanged() } + } + watcher.start() + machineNetworkWatcher = watcher + } + /// The registry update takes a file lock shared with `pu machine`, so it runs off the /// main thread. @discardableResult @@ -778,6 +793,8 @@ final class AppState { binaryWatcher = nil machineRegistryWatcher?.stop() machineRegistryWatcher = nil + machineNetworkWatcher?.stop() + machineNetworkWatcher = nil FileIOService.removeLocalCopies() // Block until daemon RPCs complete (macOS terminates shortly after willTerminate) diff --git a/apps/purepoint-macos/purepoint-macos/State/MachineConnectionLog.swift b/apps/purepoint-macos/purepoint-macos/State/MachineConnectionLog.swift new file mode 100644 index 00000000..a3e441fb --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/State/MachineConnectionLog.swift @@ -0,0 +1,76 @@ +import Foundation + +/// One failure in a machine's connection log: when it happened, its cause and ssh's words, and +/// how long the machine took to connect again (MACH-018). +nonisolated struct MachineConnectionLogEntry: Identifiable, Equatable, Sendable { + let id: Int + let time: Date + let cause: SSHFailureCause + let message: String + /// The same failure again, before the machine recovered. + var repeats = 0 + /// How long after `time` the machine connected again; nil while it is still down, or when + /// the outage ended without a recovery (the user disconnected). + var recoveredAfter: TimeInterval? + /// The machine has not connected again since, and the user has not disconnected it. + var isOpen = true +} + +/// A machine's in-memory connection log: the last 50 failures and their recoveries, oldest +/// first (MACH-018). Each distinct failure of an outage is an entry (a dropped link, then the +/// server refusing the reconnects, say); the same failure repeated only counts again. +nonisolated struct MachineConnectionLog: Equatable, Sendable { + static let capacity = 50 + + private(set) var entries: [MachineConnectionLogEntry] = [] + private var nextId = 0 + + var newestFirst: [MachineConnectionLogEntry] { entries.reversed() } + + /// Whether the machine is down since the newest entry. + var isDown: Bool { entries.last?.isOpen == true } + + /// A failed attempt or a dropped connection. + mutating func recordFailure(cause: SSHFailureCause, message: String, at time: Date) { + if let last = entries.indices.last, entries[last].isOpen, entries[last].cause == cause, + entries[last].message == message + { + entries[last].repeats += 1 + return + } + nextId += 1 + entries.append(MachineConnectionLogEntry(id: nextId, time: time, cause: cause, message: message)) + if entries.count > Self.capacity { entries.removeFirst(entries.count - Self.capacity) } + } + + /// The machine connected again: every failure of the outage is recovered. + mutating func recordRecovery(at time: Date) { + for index in entries.indices where entries[index].isOpen { + entries[index].isOpen = false + entries[index].recoveredAfter = max(0, time.timeIntervalSince(entries[index].time)) + } + } + + /// The user disconnected: the outage ends without a recovery. + mutating func recordEnded() { + for index in entries.indices where entries[index].isOpen { + entries[index].isOpen = false + } + } + + /// The log's words for an entry's outcome. + static func outcome(of entry: MachineConnectionLogEntry) -> String { + if let recoveredAfter = entry.recoveredAfter { return "Recovered after " + duration(recoveredAfter) } + return entry.isOpen ? "Not recovered yet" : "Disconnected before recovering" + } + + /// "<1 s", "12 s", "3 min 4 s", "2 h 5 min". + static func duration(_ seconds: TimeInterval) -> String { + guard seconds >= 1 else { return "<1 s" } + let total = Int(seconds.rounded()) + if total < 60 { return "\(total) s" } + if total < 3600 { return total % 60 == 0 ? "\(total / 60) min" : "\(total / 60) min \(total % 60) s" } + let minutes = (total % 3600) / 60 + return minutes == 0 ? "\(total / 3600) h" : "\(total / 3600) h \(minutes) min" + } +} diff --git a/apps/purepoint-macos/purepoint-macos/State/MachineState.swift b/apps/purepoint-macos/purepoint-macos/State/MachineState.swift index b942df97..4f493e2a 100644 --- a/apps/purepoint-macos/purepoint-macos/State/MachineState.swift +++ b/apps/purepoint-macos/purepoint-macos/State/MachineState.swift @@ -10,6 +10,8 @@ final class MachineState: Identifiable { private let machineId: UUID nonisolated var id: UUID { machineId } private(set) var state: MachineConnectionState = .disconnected + /// The last 50 failures and recoveries, for the machine's Connection Log (MACH-018). + private(set) var connectionLog = MachineConnectionLog() private(set) var projects: [ProjectState] = [] /// The latest failure of an explicit action (start daemon, project discovery). var actionError: String? @@ -124,6 +126,7 @@ final class MachineState: Identifiable { return switch state { case .disconnected: "Disconnected" case .connecting: "Connecting…" + case .waitingForNetwork: "Waiting for network" case .connected(.running): projects.isEmpty ? "Connected" : "\(projects.count) project\(projects.count == 1 ? "" : "s")" case .connected(.stopped): "Daemon stopped" @@ -155,7 +158,7 @@ final class MachineState: Identifiable { isUserDisconnecting = true stopRefreshing() let savers = removeAllProjects(keepingUnsaved: keepUnsaved) - state = .disconnected + setState(.disconnected) let connection = self.connection! let previous = disconnectTask disconnectTask = Task { @@ -173,7 +176,7 @@ final class MachineState: Identifiable { isUserDisconnecting = true stopRefreshing() for saver in removeAllProjects(keepingUnsaved: false) { saver.flush(until: deadline) } - state = .disconnected + setState(.disconnected) let connection = self.connection! connection.terminateForQuit() Task { await connection.disconnect() } @@ -279,19 +282,47 @@ final class MachineState: Identifiable { } } - /// Back from the background: check the SSH connection still answers, and replace it if - /// not (`MachineConnection.checkAfterForeground`). + /// Back from the background: as after a network change (MACH-016), forget the backoff and + /// check the SSH connection still answers, replacing it if not, or connect again now if it + /// is down (`MachineConnection.nudge`). func checkAfterForeground() { - let connection = self.connection! - Task { await connection.checkAfterForeground() } + networkChanged() } #endif + /// A wake from sleep, a network path change or the app becoming active (MACH-016): the + /// connection skips its backoff and reconnects, or probes its link now. + func networkChanged() { + guard !isUserDisconnecting, state != .disconnected else { return } + let connection = self.connection! + Task { await connection.nudge() } + } + + /// Every state change goes through here: it keeps the connection log and the state the + /// machine's streams wait on (`MachineConnectivity`) in step with `state`. + private func setState(_ newState: MachineConnectionState) { + state = newState + MachineConnectivity.shared.setConnected(newState.isDaemonRunning, machineId: machineId) + let now = Date() + switch newState { + case .offline(let detail, let cause): + connectionLog.recordFailure(cause: cause, message: detail, at: now) + case .waitingForNetwork: + connectionLog.recordFailure(cause: .network, message: "No usable network path", at: now) + case .connected: + connectionLog.recordRecovery(at: now) + case .disconnected: + connectionLog.recordEnded() + case .connecting: + break + } + } + private func apply(_ newState: MachineConnectionState) { // Reports still in flight from a connection the user closed must not reopen it. if isUserDisconnecting, newState != .disconnected { return } let wasRunning = state.isDaemonRunning - state = newState + setState(newState) if newState.isDaemonRunning { if !wasRunning { startRefreshing() } } else { diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/AddMachineSheet+iOS.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/AddMachineSheet+iOS.swift index e4aa790b..150c3e89 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/AddMachineSheet+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/AddMachineSheet+iOS.swift @@ -357,7 +357,7 @@ struct MachineRowSummary: View { } .padding(.leading, 20) } - if case .offline(let reason) = machine.state { + if let reason = machine.state.offlineDescription { Text(reason).font(.system(size: 10)).foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } @@ -381,7 +381,7 @@ struct MachineRowSummary: View { case .connected(.running): .green case .connected(.stopped): .orange case .connected(.incompatible): .red - case .connecting: .yellow + case .connecting, .waitingForNetwork: .yellow case .offline: .red case .disconnected: Color(uiColor: .tertiaryLabel) } diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/MachineConnectionLogView.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/MachineConnectionLogView.swift new file mode 100644 index 00000000..ed463643 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/MachineConnectionLogView.swift @@ -0,0 +1,67 @@ +import SwiftUI + +/// A machine's Connection Log (MACH-018): its last 50 drops and failed attempts, newest first, +/// each with its cause, ssh's message and how long the machine took to recover. Opened from +/// the machine's sidebar menu on both platforms; it follows the log as it changes. +struct MachineConnectionLogView: View { + let machine: MachineState + /// Set by the presenting controller, which dismisses the sheet. + var onClose: () -> Void = {} + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Connection Log \u{2014} \(machine.machine.name)").font(.headline) + Text("Drops and failed connection attempts since PurePoint started, newest first.") + .font(.system(size: 11)).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + if machine.connectionLog.entries.isEmpty { + Text("No drops so far.") + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + List(machine.connectionLog.newestFirst) { entry in + MachineConnectionLogRow(entry: entry) + } + } + HStack { + Spacer() + Button("Done") { onClose() } + .keyboardShortcut(.defaultAction) + } + } + .padding(16) + .frame(minWidth: 480, idealWidth: 560, minHeight: 320, idealHeight: 420) + } +} + +private struct MachineConnectionLogRow: View { + let entry: MachineConnectionLogEntry + + var body: some View { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 8) { + Text(entry.time, format: .dateTime.month().day().hour().minute().second()) + .monospacedDigit() + Text(entry.cause.label).fontWeight(.semibold) + if entry.repeats > 0 { + Text("\u{00D7}\(entry.repeats + 1)").foregroundStyle(.secondary) + } + Spacer() + Text(MachineConnectionLog.outcome(of: entry)) + .foregroundStyle(entry.recoveredAfter == nil ? Color.orange : Color.secondary) + } + .font(.system(size: 12)) + Text(entry.cause.summary) + .font(.system(size: 11)) + .fixedSize(horizontal: false, vertical: true) + if !entry.message.isEmpty { + Text(entry.message) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(.vertical, 2) + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/RemoteFolderPicker+iOS.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/RemoteFolderPicker+iOS.swift index 77c3068b..11b80fc1 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/RemoteFolderPicker+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/RemoteFolderPicker+iOS.swift @@ -109,7 +109,7 @@ struct RemoteFolderPicker: View { case .connected(.running): .systemGreen case .connected(.stopped): .systemOrange case .connected(.incompatible): .systemRed - case .connecting: .systemYellow + case .connecting, .waitingForNetwork: .systemYellow case .offline: .systemRed case .disconnected: .tertiaryLabelColor } diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarMenuModel.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarMenuModel.swift index b639e94c..80928cb7 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarMenuModel.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarMenuModel.swift @@ -12,6 +12,7 @@ enum SidebarMenuAction: Equatable { case startDaemon case showHiddenProjects case dismissMachineError + case showConnectionLog case removeMachine case renameWorkspace case killWorkspace @@ -69,6 +70,7 @@ enum SidebarMenus { if machine.actionError != nil { actions.append(("Dismiss Error", .dismissMachineError)) } + actions.append(("Connection Log", .showConnectionLog)) actions.append(("Remove Machine", .removeMachine)) return actions } @@ -90,6 +92,7 @@ enum SidebarMenus { if machine.actionError != nil { entries.append(.action("Dismiss Error", .dismissMachineError)) } + entries.append(.action("Connection Log\u{2026}", .showConnectionLog)) entries.append(.separator) entries.append(.action("Remove Machine\u{2026}", .removeMachine)) return entries diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineModel.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineModel.swift index 34c2b187..c528e4ab 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineModel.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineModel.swift @@ -302,7 +302,7 @@ extension MachineConnectionState { case .connected(.running): .systemGreen case .connected(.stopped): .systemOrange case .connected(.incompatible): .systemRed - case .connecting: .systemYellow + case .connecting, .waitingForNetwork: .systemYellow case .offline: .systemRed case .disconnected: .tertiaryLabelColor } diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+Actions.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+Actions.swift index 4fb2c9a3..fc6b8ecb 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+Actions.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+Actions.swift @@ -1,8 +1,8 @@ import Foundation // What the sidebar's menu actions do, shared by the Mac controller and its iPad twin. Each -// platform supplies `showConfirmation(_:action:)` and `beginRename(_:)`; everything else here -// is the same on both. +// platform supplies `showConfirmation(_:action:)`, `showConnectionLog(_:)` and +// `beginRename(_:)`; everything else here is the same on both. @MainActor extension SidebarOutlineViewController { @@ -19,6 +19,8 @@ extension SidebarOutlineViewController { machine.showHiddenProjects() case (.dismissMachineError, .machine(let machine)): machine.actionError = nil + case (.showConnectionLog, .machine(let machine)): + showConnectionLog(machine) case (.removeMachine, .machine(let machine)): confirmRemove(machine) case (.renameWorkspace, .workspace): diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+ConnectionLog.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+ConnectionLog.swift new file mode 100644 index 00000000..d04514c3 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+ConnectionLog.swift @@ -0,0 +1,34 @@ +import SwiftUI + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +// The machine menu's Connection Log (MACH-018): the shared `MachineConnectionLogView`, as a +// sheet on the Mac window and a form sheet on the iPad. + +@MainActor +extension SidebarOutlineViewController { + #if os(macOS) + func showConnectionLog(_ machine: MachineState) { + let host = NSHostingController(rootView: MachineConnectionLogView(machine: machine)) + host.rootView.onClose = { [weak self, weak host] in + guard let self, let host else { return } + self.dismiss(host) + } + presentAsSheet(host) + } + #else + func showConnectionLog(_ machine: MachineState) { + let host = UIHostingController(rootView: MachineConnectionLogView(machine: machine)) + host.rootView.onClose = { [weak host] in host?.dismiss(animated: true) } + host.modalPresentationStyle = .formSheet + + var presenter: UIViewController = view.window?.rootViewController ?? self + while let presented = presenter.presentedViewController { presenter = presented } + presenter.present(host, animated: true) + } + #endif +} diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+iOS.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+iOS.swift index 129bf614..117693b4 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController+iOS.swift @@ -473,7 +473,7 @@ class SidebarOutlineViewController: UIViewController { stack.addArrangedSubview(content.spacer()) stack.addArrangedSubview(status) var tooltip = "\(machine.machine.name) (\(machine.machine.sshHost)): \(machine.statusText)" - if case .offline(let reason) = machine.state { tooltip += " — " + reason } + if let reason = machine.state.offlineDescription { tooltip += " — " + reason } if let error = machine.actionError { let warning = content.symbolIcon("exclamationmark.triangle.fill", description: "Error", pointSize: 10) warning.tintColor = .systemOrange diff --git a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController.swift b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController.swift index d334b884..37d612ed 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Sidebar/SidebarOutlineViewController.swift @@ -408,7 +408,7 @@ class SidebarOutlineViewController: NSViewController, NSOutlineViewDataSource, N stack.addArrangedSubview(spacerView()) stack.addArrangedSubview(status) var tooltip = "\(machine.machine.name) (\(machine.machine.sshHost)): \(machine.statusText)" - if case .offline(let reason) = machine.state { tooltip += " — " + reason } + if let reason = machine.state.offlineDescription { tooltip += " — " + reason } if let error = machine.actionError { let warning = makeSymbolIcon("exclamationmark.triangle.fill", description: "Error", pointSize: 10) warning.contentTintColor = .systemOrange diff --git a/apps/purepoint-macos/purepoint-macosTests/MachineConnectionHardeningTests.swift b/apps/purepoint-macos/purepoint-macosTests/MachineConnectionHardeningTests.swift new file mode 100644 index 00000000..36b4738b --- /dev/null +++ b/apps/purepoint-macos/purepoint-macosTests/MachineConnectionHardeningTests.swift @@ -0,0 +1,275 @@ +import Foundation +import Testing + +@testable import PurePoint + +// Connection hardening (MACH-014 – MACH-018) shared by the Mac and the iPad. Runs in both test +// targets. + +// MARK: - Failure classification (MACH-018) + +/// The cases of `crates/pu-core/src/ssh_failure.rs`, so the two classifiers stay in step. +struct SSHFailureCauseTests { + @Test func givenPreAuthCloseShouldReportServerRefused() { + // given + let samples = [ + "kex_exchange_identification: Connection closed by remote host\r\nConnection closed by 10.0.0.5 port 22", + "kex_exchange_identification: read: Connection reset by peer", + "ssh_exchange_identification: Connection closed by remote host", + ] + + // when / then + for stderr in samples { + #expect(SSHFailureCause.classify(exit: 255, stderr: stderr) == .serverRefused, "\(stderr)") + } + } + + @Test func givenNetworkErrorsShouldReportNetwork() { + // given + let samples = [ + "ssh: connect to host studio port 22: Operation timed out", + "ssh: connect to host 10.0.0.5 port 22: No route to host", + "ssh: connect to host 10.0.0.5 port 22: Network is unreachable", + "ssh: Could not resolve hostname studio: Name or service not known", + "ssh: connect to host studio port 22: Connection refused", + "Timeout, server studio not responding.", + "client_loop: send disconnect: Broken pipe", + "client_loop: send disconnect: Connection reset by peer", + "read: Connection reset by peer", + ] + + // when / then + for stderr in samples { + #expect(SSHFailureCause.classify(exit: 255, stderr: stderr) == .network, "\(stderr)") + } + } + + @Test func givenAuthAndHostKeyFailuresShouldNameThem() { + #expect(SSHFailureCause.classify(exit: 255, stderr: "user@studio: Permission denied (publickey).") == .auth) + #expect(SSHFailureCause.classify(exit: 255, stderr: "Host key verification failed.") == .hostKey) + #expect( + SSHFailureCause.classify( + exit: 255, + stderr: "@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@\nHost key verification failed.") + == .hostKey) + } + + @Test func givenRelayExitCodesShouldWinOverStderr() { + #expect(SSHFailureCause.classify(exit: 69, stderr: "error: cannot connect to the daemon") == .daemonStopped) + #expect(SSHFailureCause.classify(exit: 127, stderr: "sh: pu: not found") == .puMissing) + #expect(SSHFailureCause.classify(exit: 9009, stderr: "") == .puMissing) + } + + @Test func givenUnknownMessageShouldReportOther() { + #expect(SSHFailureCause.classify(exit: nil, stderr: "something odd") == .other) + #expect(SSHFailureCause.fromStderr("") == nil) + } + + @Test func givenCausesShouldSayWhichNeedTheUser() { + #expect(SSHFailureCause.serverRefused.isTransient) + #expect(SSHFailureCause.network.isTransient) + #expect(!SSHFailureCause.auth.isTransient) + #expect(!SSHFailureCause.hostKey.isTransient) + #expect(!SSHFailureCause.puMissing.isTransient) + #expect(!SSHFailureCause.daemonStopped.isTransient) + } + + @Test func givenServerRefusedShouldPointAtDoctor() { + #expect(SSHFailureCause.serverRefused.summary.contains("pu doctor --machine")) + } + + @Test func givenCauseShouldUseTheRustNames() { + #expect(SSHFailureCause.allCases.map(\.rawValue) == [ + "server_refused", "network", "auth", "host_key", "pu_missing", "daemon_stopped", "other", + ]) + } + + @Test func givenOfflineStateShouldDescribeTheCauseThenSSHsWords() { + let refused = MachineConnectionState.offline("Connection closed by 10.0.0.5 port 22", cause: .serverRefused) + #expect(refused.offlineDescription == SSHFailureCause.serverRefused.summary + " Connection closed by 10.0.0.5 port 22") + #expect(MachineConnectionState.offline("odd").offlineDescription == "odd") + #expect(MachineConnectionState.offline("", cause: .network).offlineDescription == SSHFailureCause.network.summary) + #expect(MachineConnectionState.connecting.offlineDescription == nil) + } +} + +// MARK: - Backoff (MACH-016) + +struct SSHReconnectBackoffTests { + @Test func givenConsecutiveFailuresShouldStepOneTwoFourEightThenFifteen() { + #expect((0...8).map { SSHReconnectBackoff.step(afterFailures: $0) } == [0, 1, 2, 4, 8, 15, 15, 15, 15]) + } + + @Test func givenJitterShouldScaleEachStepBetweenHalfAndAll() { + #expect(SSHReconnectBackoff.delay(afterFailures: 4, factor: 0.5) == 4) + #expect(SSHReconnectBackoff.delay(afterFailures: 5, factor: 1) == 15) + // Out-of-range factors are clamped to equal jitter's [0.5, 1]. + #expect(SSHReconnectBackoff.delay(afterFailures: 3, factor: 0.1) == 2) + #expect(SSHReconnectBackoff.delay(afterFailures: 3, factor: 3) == 4) + } + + @Test func givenRandomJitterShouldStayInRange() { + var backoff = SSHReconnectBackoff() + let start = Date(timeIntervalSince1970: 0) + for failures in 1...20 { + let delay = backoff.recordFailure(at: start) + let step = SSHReconnectBackoff.step(afterFailures: failures) + #expect(delay >= step * 0.5 && delay <= step, "\(delay) for step \(step)") + } + } + + @Test func givenFailuresShouldDelayAndSuccessShouldReset() { + let start = Date(timeIntervalSince1970: 0) + var backoff = SSHReconnectBackoff(jitter: { 0.75 }) + #expect(backoff.remainingDelay(at: start) == 0) + #expect(backoff.recordFailure(at: start) == 0.75) + #expect(backoff.recordFailure(at: start) == 1.5) + #expect(backoff.remainingDelay(at: start) == 1.5) + #expect(backoff.remainingDelay(at: start + 1) == 0.5) + backoff.recordSuccess() + #expect(backoff.remainingDelay(at: start) == 0) + #expect(backoff.failures == 0) + } +} + +// MARK: - Connection log (MACH-018) + +struct MachineConnectionLogTests { + private let start = Date(timeIntervalSince1970: 1_000_000) + + @Test func givenMoreThanFiftyFailuresShouldKeepTheLastFifty() { + // given + var log = MachineConnectionLog() + + // when + for index in 0..<60 { + log.recordFailure(cause: .network, message: "drop \(index)", at: start + Double(index)) + log.recordRecovery(at: start + Double(index) + 0.5) + } + + // then + #expect(log.entries.count == MachineConnectionLog.capacity) + #expect(log.entries.first?.message == "drop 10") + #expect(log.newestFirst.first?.message == "drop 59") + #expect(log.newestFirst.last?.message == "drop 10") + } + + @Test func givenTheSameFailureAgainShouldCountItOnce() { + var log = MachineConnectionLog() + log.recordFailure(cause: .network, message: "timed out", at: start) + log.recordFailure(cause: .network, message: "timed out", at: start + 2) + log.recordFailure(cause: .serverRefused, message: "kex_exchange_identification", at: start + 4) + #expect(log.entries.map(\.cause) == [.network, .serverRefused]) + #expect(log.entries[0].repeats == 1) + #expect(log.isDown) + } + + @Test func givenRecoveryShouldRecordHowLongEachFailureTook() { + var log = MachineConnectionLog() + log.recordFailure(cause: .network, message: "timed out", at: start) + log.recordFailure(cause: .serverRefused, message: "kex", at: start + 4) + log.recordRecovery(at: start + 10) + #expect(log.entries.map(\.recoveredAfter) == [10, 6]) + #expect(!log.isDown) + #expect(MachineConnectionLog.outcome(of: log.entries[0]) == "Recovered after 10 s") + // A later recovery does not touch closed entries. + log.recordRecovery(at: start + 100) + #expect(log.entries.map(\.recoveredAfter) == [10, 6]) + // The same failure after a recovery is a new drop. + log.recordFailure(cause: .network, message: "timed out", at: start + 200) + #expect(log.entries.count == 3) + } + + @Test func givenUserDisconnectShouldEndTheOutageWithoutRecovery() { + var log = MachineConnectionLog() + log.recordFailure(cause: .auth, message: "Permission denied", at: start) + #expect(MachineConnectionLog.outcome(of: log.entries[0]) == "Not recovered yet") + log.recordEnded() + log.recordRecovery(at: start + 5) + #expect(log.entries[0].recoveredAfter == nil) + #expect(MachineConnectionLog.outcome(of: log.entries[0]) == "Disconnected before recovering") + } + + @Test func givenDurationsShouldReadNaturally() { + #expect(MachineConnectionLog.duration(0.4) == "<1 s") + #expect(MachineConnectionLog.duration(12) == "12 s") + #expect(MachineConnectionLog.duration(120) == "2 min") + #expect(MachineConnectionLog.duration(184) == "3 min 4 s") + #expect(MachineConnectionLog.duration(7500) == "2 h 5 min") + } +} + +// MARK: - Retries follow the machine (MACH-014, MACH-015) + +struct AttachRetryPolicyTests { + @Test func givenRepeatedFailuresShouldRetryFastThenSlowThenGiveUp() { + var policy = AttachRetryPolicy() + let decisions = (0..<21).map { _ in policy.recordFailure(attached: false, machineIsDown: false) } + #expect(decisions.prefix(5).allSatisfy { $0 == .retry(after: AttachRetryPolicy.fastDelay) }) + #expect(decisions[5..<20].allSatisfy { $0 == .retry(after: AttachRetryPolicy.slowDelay) }) + #expect(decisions[20] == .giveUp) + } + + @Test func givenAnAttachThatSucceededShouldResetTheRetryCount() { + var policy = AttachRetryPolicy() + for _ in 0..<19 { _ = policy.recordFailure(attached: false, machineIsDown: false) } + #expect(policy.retries == 19) + // It attached, then the stream failed: counting starts over. + #expect(policy.recordFailure(attached: true, machineIsDown: false) == .retry(after: AttachRetryPolicy.fastDelay)) + #expect(policy.retries == 1) + } + + @Test func givenTheMachineIsDownShouldWaitWithoutSpendingRetries() { + var policy = AttachRetryPolicy() + for _ in 0..<100 { + #expect(policy.recordFailure(attached: false, machineIsDown: true) == .waitForMachine) + } + #expect(policy.retries == 0) + // A success before the outage still resets the count. + for _ in 0..<5 { _ = policy.recordFailure(attached: false, machineIsDown: false) } + #expect(policy.recordFailure(attached: true, machineIsDown: true) == .waitForMachine) + #expect(policy.retries == 0) + } +} + +struct MachineConnectivityTests { + private let machineId = UUID(uuidString: "6F1C2B3A-1111-4222-8333-944455556666")! + + @Test func givenLocalStreamShouldKeepItsOwnRetries() { + #expect(!MachineConnectivity().shouldWait(forMachine: nil)) + } + + @Test func givenRemoteStreamShouldWaitOnlyWhileItsMachineIsDown() { + let connectivity = MachineConnectivity() + #expect(connectivity.shouldWait(forMachine: machineId)) + connectivity.setConnected(true, machineId: machineId) + #expect(!connectivity.shouldWait(forMachine: machineId)) + #expect(connectivity.shouldWait(forMachine: UUID())) + connectivity.setConnected(false, machineId: machineId) + #expect(connectivity.shouldWait(forMachine: machineId)) + } + + @Test func givenResumeDelayShouldStayWithinOneSecond() { + for _ in 0..<50 { + let delay = MachineConnectivity.resumeDelay() + #expect(delay >= .zero && delay <= .seconds(1)) + } + } + + @Test func givenClientShouldKnowItsMachine() { + #expect(DaemonEndpoint.machine(machineId).makeClient().machineId == machineId) + #expect(DaemonClient(socketPath: "/tmp/elsewhere/daemon.sock", transport: NeverTransport()).machineId == nil) + #expect(DaemonClient(transport: NeverTransport()).machineId == nil) + } +} + +/// A transport for clients that are only inspected, never used. +private struct NeverTransport: DaemonTransport { + func openStream(cancellable: Bool) async throws -> any DaemonByteStream { + throw DaemonClientError.notRunning + } + + func openBlockingStream(timeout: TimeInterval) throws -> any DaemonBlockingByteStream { + throw DaemonClientError.notRunning + } +} diff --git a/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift index 2664b50d..4d6419c3 100644 --- a/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift @@ -160,7 +160,8 @@ struct MachineSSHTests { #expect( MachineSSH.resolveHomeArguments(sshHost: "studio") == [ - "-o", "BatchMode=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", "studio", + "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "TCPKeepAlive=yes", + "-o", "ControlMaster=no", "-o", "ControlPath=none", "studio", "printf %s \"$HOME\"", ]) } @@ -173,6 +174,8 @@ struct MachineSSHTests { "-N", "-T", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", + "-o", "ConnectTimeout=10", + "-o", "TCPKeepAlive=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "-o", "StreamLocalBindUnlink=yes", @@ -187,11 +190,48 @@ struct MachineSSHTests { #expect( MachineSSH.startDaemonArguments(sshHost: "studio") == [ + "-o", "ConnectTimeout=10", "-o", "TCPKeepAlive=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", "studio", #"/bin/sh -c 'PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH"; export PATH; exec pu health'"#, ]) } + /// MACH-017: every ssh command dials with a 10 s limit and TCP keepalive. + @Test func givenAnySSHCommandShouldPassConnectTimeoutAndTCPKeepAlive() { + let commands = [ + MachineSSH.resolveHomeArguments(sshHost: "studio"), + MachineSSH.forwardArguments(localSocket: "/l", remoteHome: "/h", sshHost: "studio"), + MachineSSH.startDaemonArguments(sshHost: "studio"), + ] + for arguments in commands { + let options = stride(from: 0, to: arguments.count - 1, by: 1) + .filter { arguments[$0] == "-o" } + .map { arguments[$0 + 1] } + #expect(options.contains("ConnectTimeout=10"), "\(arguments)") + #expect(options.contains("TCPKeepAlive=yes"), "\(arguments)") + } + } + + @Test func givenForwardEndingShouldNameTheCause() { + // A link that dropped with nothing classifiable said is the network. + #expect(MachineConnection.dropCause(exit: 255, stderr: "") == .network) + #expect( + MachineConnection.dropCause(exit: 255, stderr: "client_loop: send disconnect: Broken pipe") == .network) + #expect( + MachineConnection.dropCause(exit: 255, stderr: "kex_exchange_identification: Connection closed by remote host") + == .serverRefused) + #expect(MachineConnection.dropCause(exit: 255, stderr: "user@studio: Permission denied (publickey).") == .auth) + } + + @Test func givenOneShotSSHFailureShouldClassifyItsOutput() { + #expect( + MachineSSH.failureCause(.init(status: 255, stdout: "", stderr: "ssh: Could not resolve hostname studio: nodename nor servname provided, or not known")) + == .network) + // A kill after the deadline has no exit status; its message still names the cause. + #expect(MachineSSH.failureCause(.init(status: -1, stdout: "", stderr: "ssh timed out after 20 s")) == .network) + #expect(MachineSSH.failureCause(.init(status: 127, stdout: "", stderr: "")) == .puMissing) + } + @Test func givenHostWithPortShouldUseTheSSHURIForm() { #expect(MachineSSH.destination("jane@studio:2222") == "ssh://jane@studio:2222") #expect(MachineSSH.destination("studio:22") == "ssh://studio:22") diff --git a/apps/purepoint-macos/purepoint-macosTests/SSHMachineRegistryTests.swift b/apps/purepoint-macos/purepoint-macosTests/SSHMachineRegistryTests.swift index 9c32bcfe..93098ebf 100644 --- a/apps/purepoint-macos/purepoint-macosTests/SSHMachineRegistryTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/SSHMachineRegistryTests.swift @@ -125,12 +125,13 @@ private final class Reports: @unchecked Sendable { let (connection, reports) = connection(connector, name: "build-box") await connection.connect() await eventually { if case .offline = reports.last { true } else { false } } - guard case .offline(let message) = reports.last else { + guard case .offline(let message, let cause) = reports.last else { Issue.record("expected offline, got \(String(describing: reports.last))") return } #expect(message.contains("build-box")) #expect(message.contains("not installed")) + #expect(cause == .puMissing) await connection.disconnect() } @@ -168,7 +169,7 @@ private final class Reports: @unchecked Sendable { #expect(connector.attempts == 2) #expect(connector.all[0].isClosed) #expect(!reports.all.contains(.connected(.stopped))) - #expect(reports.all.contains(.offline("SSH connection closed"))) + #expect(reports.all.contains(.offline("SSH connection closed", cause: .network))) // The new connection answers: the machine is back. relay.silent = false await waitFor(seconds: 10) { reports.last == .connected(.running) } @@ -211,7 +212,7 @@ private final class Reports: @unchecked Sendable { await eventually { reports.last == .connected(.running) } connector.all[0].drop() await waitFor(seconds: 5) { connector.attempts == 2 && reports.last == .connected(.running) } - #expect(reports.all.contains(.offline("SSH connection closed"))) + #expect(reports.all.contains(.offline("SSH connection closed", cause: .network))) #expect(reports.last == .connected(.running)) await connection.disconnect() } diff --git a/apps/purepoint-macos/purepoint-macosTests/SSHTransportTests.swift b/apps/purepoint-macos/purepoint-macosTests/SSHTransportTests.swift index 5b1dc66e..c30ce837 100644 --- a/apps/purepoint-macos/purepoint-macosTests/SSHTransportTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/SSHTransportTests.swift @@ -206,25 +206,6 @@ func eventually(_ condition: () async -> Bool) async { // MARK: - Backoff and errors -struct SSHReconnectBackoffTests { - @Test func scheduleDoublesToThirtySeconds() { - #expect((0...8).map { SSHReconnectBackoff.delay(afterFailures: $0) } == [0, 1, 2, 4, 8, 16, 30, 30, 30]) - } - - @Test func failuresDelayAndSuccessResets() { - let start = Date(timeIntervalSince1970: 0) - var backoff = SSHReconnectBackoff() - #expect(backoff.remainingDelay(at: start) == 0) - backoff.recordFailure(at: start) - backoff.recordFailure(at: start) - #expect(backoff.remainingDelay(at: start) == 2) - #expect(backoff.remainingDelay(at: start + 1.5) == 0.5) - backoff.recordSuccess() - #expect(backoff.remainingDelay(at: start) == 0) - #expect(backoff.failures == 0) - } -} - struct SSHRelayErrorTests { @Test func relayEndsMapToUnixSocketErrors() { func map(_ end: SSHExecEnd) -> Error { SSHRelayErrors.error(for: end, machine: "studio") } diff --git a/apps/purepoint-macos/purepoint-macosTests/SidebarMenuModelTests.swift b/apps/purepoint-macos/purepoint-macosTests/SidebarMenuModelTests.swift index 26ca8662..ccc2e03d 100644 --- a/apps/purepoint-macos/purepoint-macosTests/SidebarMenuModelTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/SidebarMenuModelTests.swift @@ -71,12 +71,17 @@ struct SidebarMenuModelTests { == ["Kill All Agents (1)", "-", "Delete Worktree\u{2026}"]) #expect(titles(SidebarMenus.contextMenu(for: nodes[0].children[0].children[0])) == ["Rename\u{2026}", "-", "Kill Agent"]) #expect(SidebarMenus.contextMenu(for: nodes[1]).isEmpty) - #expect(titles(SidebarMenus.contextMenu(for: nodes[2])) == ["Connect", "-", "Remove Machine\u{2026}"]) + #expect( + titles(SidebarMenus.contextMenu(for: nodes[2])) + == ["Connect", "Connection Log\u{2026}", "-", "Remove Machine\u{2026}"]) machine.actionError = "ssh failed" - #expect(titles(SidebarMenus.contextMenu(for: nodes[2])) == ["Connect", "Dismiss Error", "-", "Remove Machine\u{2026}"]) #expect( - SidebarMenus.machineAccessibilityActions(machine).map(\.name) == ["Connect", "Dismiss Error", "Remove Machine"]) + titles(SidebarMenus.contextMenu(for: nodes[2])) + == ["Connect", "Dismiss Error", "Connection Log\u{2026}", "-", "Remove Machine\u{2026}"]) + #expect( + SidebarMenus.machineAccessibilityActions(machine).map(\.name) + == ["Connect", "Dismiss Error", "Connection Log", "Remove Machine"]) } @Test func givenDeadAgentsShouldOfferOnlyTheDestructiveRowActions() { diff --git a/apps/purepoint-macos/purepoint-macosTests/SidebarOutlineViewControllerIOSTests.swift b/apps/purepoint-macos/purepoint-macosTests/SidebarOutlineViewControllerIOSTests.swift index 9b5987d9..e72dd34e 100644 --- a/apps/purepoint-macos/purepoint-macosTests/SidebarOutlineViewControllerIOSTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/SidebarOutlineViewControllerIOSTests.swift @@ -124,7 +124,7 @@ struct SidebarOutlineViewControllerIOSTests { #expect(header.accessibilityLabel == "Machines") let row = try #require(controller.outlineView.cellForItem(at: IndexPath(item: 1, section: 0))) #expect(row.accessibilityLabel?.hasPrefix("studio (me@studio): ") == true) - #expect(row.accessibilityCustomActions?.map(\.name) == ["Connect", "Remove Machine"]) + #expect(row.accessibilityCustomActions?.map(\.name) == ["Connect", "Connection Log", "Remove Machine"]) } @Test func givenARowTheUserClosedShouldStayClosedWhenAnUnrelatedRefreshRebuildsTheTree() throws { diff --git a/docs/product/desktop-app.md b/docs/product/desktop-app.md index a32e75a5..7b4a4061 100644 --- a/docs/product/desktop-app.md +++ b/docs/product/desktop-app.md @@ -39,7 +39,7 @@ Desktop App ! [APP-017] Sidebar row expansion. The sidebar keeps which rows the user closed and replays it after every refresh instead of reopening the whole tree. The outline view (APP-006) allocates new node objects on every data change and AppKit tracks expansion by node identity, so a rebuild forgets every row — and a global "everything open" restore then lets any unrelated refresh (an unread count, an agent status, the 30 s machine inventory) discard what the user closed. Closed rows are recorded outside the tree under an identity that carries every ancestor's scope, so a row is never confused with a same-id row under another project or on another machine. Every row that is not recorded closed is open, so a row appearing for the first time opens as before; closing a row keeps its own rows' state, and opening one brings them back. The closed rows persist in UserDefaults as `PurePointSidebarExpansion` across launches, and a row that no longer exists is dropped so it cannot return in an old state. A row inside a closed section has no row of its own, so a selection for one first opens that section's ancestors. -! [APP-016] Machines over SSH ([machines.md](machines.md)). Below the local projects the sidebar shows a "MACHINES" section header and one row per machine registered in `~/.pu/machines.json` (shared with `pu machine`): a status dot, the machine name and its state — Connecting, project count when connected, Daemon stopped, Incompatible (protocol N), Offline or Disconnected. Each machine row nests the projects its daemon has registered (`inventory`, refreshed on connect and every 30 s), rendered with the same project/worktree/workspace rows as local projects. The machine context menu offers Connect/Disconnect, Start Daemon (only when connected with the daemon stopped; never automatic) and Remove Machine (closes the forward and forgets it; nothing on the machine changes). The footer's machine button opens Add Machine: name, SSH host (with `Host` aliases from `~/.ssh/config`, wildcards skipped) and Test Connection. Remote projects have full parity through their daemon endpoint and a project host: status, attach, spawn, worktrees, grid commands, channel, files (browse, preview, edit, save with conflict rejection), git/gh review and workspace layouts (`.pu/workspaces.json` on the machine). Identity is `(machine, root)`: local keys keep their bare-root form for persisted state, remote keys are `machine::`. Local-only actions adapt: Reveal in Finder becomes Open Local Copy (fetched to a private temp file), and Remove Project only hides a remote project in this app. Agents Hub, Schedule, Triggers and agent settings stay scoped to the local daemon. Disconnecting or quitting closes the SSH forward and leaves remote agents running. +! [APP-016] Machines over SSH ([machines.md](machines.md)). Below the local projects the sidebar shows a "MACHINES" section header and one row per machine registered in `~/.pu/machines.json` (shared with `pu machine`): a status dot, the machine name and its state — Connecting, Waiting for network (no usable network path, MACH-016), project count when connected, Daemon stopped, Incompatible (protocol N), Offline (with the classified cause, MACH-018) or Disconnected. Each machine row nests the projects its daemon has registered (`inventory`, refreshed on connect and every 30 s), rendered with the same project/worktree/workspace rows as local projects. The machine context menu offers Connect/Disconnect, Start Daemon (only when connected with the daemon stopped; never automatic), Connection Log… (the last 50 drops and failed attempts, newest first, with cause, ssh message and time to recover; MACH-018) and Remove Machine (closes the forward and forgets it; nothing on the machine changes). The footer's machine button opens Add Machine: name, SSH host (with `Host` aliases from `~/.ssh/config`, wildcards skipped) and Test Connection. Remote projects have full parity through their daemon endpoint and a project host: status, attach, spawn, worktrees, grid commands, channel, files (browse, preview, edit, save with conflict rejection), git/gh review and workspace layouts (`.pu/workspaces.json` on the machine). Identity is `(machine, root)`: local keys keep their bare-root form for persisted state, remote keys are `machine::`. Local-only actions adapt: Reveal in Finder becomes Open Local Copy (fetched to a private temp file), and Remove Project only hides a remote project in this app. Agents Hub, Schedule, Triggers and agent settings stay scoped to the local daemon. Disconnecting or quitting closes the SSH forward and leaves remote agents running. ! [APP-015] Root checkout and worktree changes review use the workspace right-sidebar visual design for a resizable, hideable, searchable list of every changed file. Selecting any file reveals its inline diff in the middle view, independent of scroll position. Branch Changes, Uncommitted (separate Staged/Unstaged/Untracked identities), selected commits, and selected PRs share this behavior. Files with more than 200 changed lines, and untracked files whose counts are not yet known, start collapsed. Bodies load only for visible expanded files, with selectable pages of at most 200 lines and a 32 KB text budget, previous/next navigation, and access to the complete disk-backed patch. Retain one page body per mounted card and lightweight disk checkpoints for previous-page navigation; release bodies when collapsed or off screen. Very long individual lines are shortened only in the preview. Overview refreshes read metadata instead of all patch bodies; immutable branch comparisons are cached by resolved revisions. GitHub lookups run separately from local Git work, and PR patches load only in their review context. Workspace files-sidebar inline expansion remains as defined in APP-010. From 34874b78703f59de2140315d01d274c24828ba43 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:06:32 +0000 Subject: [PATCH 09/21] Windows: event-driven reconnects, jittered backoff and a connection log - MachineConnection backs off 1, 2, 4, 8, then 15 s with equal jitter, and resets and probes at once on online, navigator.connection change, foreground, focus and wake from sleep (timer drift). Without a network the machine shows "Waiting for network" and nothing is tried (MACH-016). Decision logic is in model/machineConnectionPolicy.ts; device events in services/networkMonitor.ts. - The supervisor reports reachability to the backend gate (machine_set_reachable) before the app sees a connected state, and probes at once on machine-suspect (MACH-014). The project refresh starts 0-1 s after the daemon is back. - Offline states carry the ssh failure cause and summary; the machine row names actionable causes, and a Connection Log... dialog lists the last 50 drops and recoveries per machine, newest first (MACH-018). - windows-app.md: document the gate, suspect event, backoff and log. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- .../ui/src/model/machine.test.ts | 10 + .../purepoint-windows/ui/src/model/machine.ts | 26 +- .../src/model/machineConnectionPolicy.test.ts | 146 ++++++++++ .../ui/src/model/machineConnectionPolicy.ts | 198 ++++++++++++++ .../ui/src/model/sidebarItem.ts | 12 +- .../ui/src/model/sidebarMenu.test.ts | 9 +- .../ui/src/model/sidebarMenu.ts | 4 + .../ui/src/services/machines.ts | 174 +++++++++++- .../ui/src/services/networkMonitor.test.ts | 117 ++++++++ .../ui/src/services/networkMonitor.ts | 131 +++++++++ .../ui/src/state/appState.ts | 3 + .../ui/src/state/machineState.test.ts | 254 ++++++++++++++++-- .../ui/src/state/machineState.ts | 43 ++- .../src/views/sidebar/ConnectionLogDialog.tsx | 103 +++++++ .../sidebar/SidebarOutlineViewController.tsx | 7 +- .../ui/src/views/sidebar/SidebarView.tsx | 17 +- .../ui/src/views/sidebar/machineSheets.ts | 11 +- .../src/views/sidebar/machineViews.test.tsx | 42 +++ .../ui/src/views/sidebar/sidebar.css | 47 ++++ .../src/views/sidebar/sidebarMenus.test.tsx | 4 + .../sidebar/sidebarOutlineViewCallbacks.ts | 4 + .../sidebarOutlineViewControllerActions.ts | 3 + docs/product/windows-app.md | 7 + 23 files changed, 1328 insertions(+), 44 deletions(-) create mode 100644 apps/purepoint-windows/ui/src/model/machineConnectionPolicy.test.ts create mode 100644 apps/purepoint-windows/ui/src/model/machineConnectionPolicy.ts create mode 100644 apps/purepoint-windows/ui/src/services/networkMonitor.test.ts create mode 100644 apps/purepoint-windows/ui/src/services/networkMonitor.ts create mode 100644 apps/purepoint-windows/ui/src/views/sidebar/ConnectionLogDialog.tsx diff --git a/apps/purepoint-windows/ui/src/model/machine.test.ts b/apps/purepoint-windows/ui/src/model/machine.test.ts index c466ed1c..ffc247bb 100644 --- a/apps/purepoint-windows/ui/src/model/machine.test.ts +++ b/apps/purepoint-windows/ui/src/model/machine.test.ts @@ -128,6 +128,16 @@ describe('machine status', () => { expect(machineStatusText({ kind: 'disconnected' }, 0)).toBe('Disconnected'); expect(machineStatusText({ kind: 'connecting' }, 0)).toBe('Connecting…'); expect(machineStatusText({ kind: 'offline', reason: 'x' }, 2)).toBe('Offline'); + // MACH-018: the row names a cause the user can act on; a network failure is plain offline. + expect(machineStatusText({ kind: 'offline', reason: 'x', cause: 'network' }, 0)).toBe( + 'Offline', + ); + expect(machineStatusText({ kind: 'offline', reason: 'x', cause: 'server_refused' }, 0)).toBe( + 'Login refused', + ); + expect(machineStatusText({ kind: 'offline', reason: 'x', waitingForNetwork: true }, 0)).toBe( + 'Waiting for network', + ); expect(machineStatusText(running, 0)).toBe('Connected'); expect(machineStatusText(running, 1)).toBe('1 project'); expect(machineStatusText(running, 3)).toBe('3 projects'); diff --git a/apps/purepoint-windows/ui/src/model/machine.ts b/apps/purepoint-windows/ui/src/model/machine.ts index 3dcf33b0..27a16da2 100644 --- a/apps/purepoint-windows/ui/src/model/machine.ts +++ b/apps/purepoint-windows/ui/src/model/machine.ts @@ -14,6 +14,7 @@ // (`machines_ssh_config`); the parser is here. import type { DaemonAvailability, MachineConnectionState } from './sidebarItem.ts'; +import { type SshFailureCause, causeLabel } from './machineConnectionPolicy.ts'; /** A machine in `machines.json` (Swift `Machine`). */ export interface Machine { @@ -180,14 +181,20 @@ export function suggestedMachineName(alias: string): string { /** * One relayed `health` (the backend's `machine_probe`). Windows adds what the relay's exit status - * says: `stopped` (exit 69, no daemon) and `offline` (ssh failed, or no `pu` there). + * says: `stopped` (exit 69, no daemon) and `offline` (ssh failed, or no `pu` there), with the + * failure's cause and that cause's summary (MACH-018). */ export type HealthProbe = | { readonly kind: 'running' } | { readonly kind: 'incompatible'; readonly version: number } | { readonly kind: 'busy' } | { readonly kind: 'stopped' } - | { readonly kind: 'offline'; readonly reason: string } + | { + readonly kind: 'offline'; + readonly reason: string; + readonly cause?: SshFailureCause; + readonly summary?: string; + } | { readonly kind: 'failed'; readonly reason: string }; /** Probes that only count toward a verdict (Swift's `HealthProbe` cases). */ @@ -240,7 +247,11 @@ export function machineStatusText(state: MachineConnectionState, projectCount: n case 'connecting': return 'Connecting…'; case 'offline': - return 'Offline'; + if (state.waitingForNetwork === true) return 'Waiting for network'; + // The machine shows why (MACH-018); a network failure is plain offline. + return state.cause === undefined || state.cause === 'network' || state.cause === 'other' + ? 'Offline' + : causeLabel(state.cause); case 'connected': switch (state.daemon.kind) { case 'running': @@ -260,7 +271,14 @@ export function connectionStatesEqual( b: MachineConnectionState, ): boolean { if (a.kind !== b.kind) return false; - if (a.kind === 'offline' && b.kind === 'offline') return a.reason === b.reason; + if (a.kind === 'offline' && b.kind === 'offline') { + return ( + a.reason === b.reason && + a.cause === b.cause && + a.summary === b.summary && + (a.waitingForNetwork ?? false) === (b.waitingForNetwork ?? false) + ); + } if (a.kind === 'connected' && b.kind === 'connected') { const [x, y] = [a.daemon, b.daemon]; if (x.kind === 'incompatible' || y.kind === 'incompatible') { diff --git a/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.test.ts b/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.test.ts new file mode 100644 index 00000000..95cad0a3 --- /dev/null +++ b/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.test.ts @@ -0,0 +1,146 @@ +// The connection supervision rules (machines.md MACH-014 – MACH-018). +import { describe, expect, it } from 'vitest'; +import { + CONNECTION_LOG_LIMIT, + type ConnectionLogEntry, + causeLabel, + dropOf, + formatRecovery, + isReachable, + isWakeFromSleep, + networkEventFor, + nextConnectionLog, + reconnectDelayMs, + resumeDelayMs, + triggerProbesNow, +} from './machineConnectionPolicy'; +import type { MachineConnectionState } from './sidebarItem'; + +const RUNNING: MachineConnectionState = { kind: 'connected', daemon: { kind: 'running' } }; +const STOPPED: MachineConnectionState = { kind: 'connected', daemon: { kind: 'stopped' } }; +const REFUSED: MachineConnectionState = { + kind: 'offline', + reason: 'kex_exchange_identification: Connection closed by remote host', + cause: 'server_refused', +}; +const NETWORK: MachineConnectionState = { kind: 'offline', reason: 'timed out', cause: 'network' }; + +describe('reconnectDelayMs', () => { + it('given consecutive failures, should step 1, 2, 4, 8, then 15 s', () => { + const top = () => 1; + expect([1, 2, 3, 4, 5, 6, 50].map((n) => reconnectDelayMs(n, top))).toEqual([ + 1_000, 2_000, 4_000, 8_000, 15_000, 15_000, 15_000, + ]); + }); + + it('given the random sample, should scale each step by a factor in [0.5, 1]', () => { + expect(reconnectDelayMs(1, () => 0)).toBe(500); + expect(reconnectDelayMs(5, () => 0.5)).toBe(11_250); + expect(reconnectDelayMs(5, () => 0)).toBe(7_500); + // Out-of-range samples are clamped; a broken one waits the full step. + expect(reconnectDelayMs(2, () => 7)).toBe(2_000); + expect(reconnectDelayMs(2, () => Number.NaN)).toBe(2_000); + expect(reconnectDelayMs(0, () => 1)).toBe(1_000); + }); + + it('given the resume jitter, should spread over 0–1 s', () => { + expect(resumeDelayMs(() => 0)).toBe(0); + expect(resumeDelayMs(() => 0.25)).toBe(250); + expect(resumeDelayMs(() => 1)).toBe(1_000); + expect(resumeDelayMs(() => Number.NaN)).toBe(0); + }); +}); + +describe('device events', () => { + it('given each signal, should say whether it reconnects or waits for the network', () => { + expect(networkEventFor('offline', true)).toEqual({ kind: 'offline' }); + expect(networkEventFor('online', true)).toEqual({ kind: 'trigger', trigger: 'online' }); + expect(networkEventFor('connection-change', false)).toEqual({ + kind: 'trigger', + trigger: 'network-change', + }); + expect(networkEventFor('visibility', true)).toEqual({ kind: 'trigger', trigger: 'foreground' }); + expect(networkEventFor('visibility', false)).toBeNull(); + expect(networkEventFor('focus', true)).toEqual({ kind: 'trigger', trigger: 'focus' }); + expect(networkEventFor('wake', true)).toEqual({ kind: 'trigger', trigger: 'wake' }); + }); + + it('given a late timer tick, should read it as a wake from sleep', () => { + expect(isWakeFromSleep(0, 5_000)).toBe(false); + expect(isWakeFromSleep(0, 20_000)).toBe(false); + expect(isWakeFromSleep(0, 20_001)).toBe(true); + expect(isWakeFromSleep(10_000, 3_600_000)).toBe(true); + }); + + it('given focus soon after a probe, should not probe again; other triggers always do', () => { + expect(triggerProbesNow('focus', null, 0)).toBe(true); + expect(triggerProbesNow('focus', 1_000, 2_500)).toBe(false); + expect(triggerProbesNow('foreground', 1_000, 3_000)).toBe(true); + for (const trigger of ['online', 'network-change', 'wake'] as const) { + expect(triggerProbesNow(trigger, 1_000, 1_001)).toBe(true); + } + }); + + it('given a state, should open the gate only while the daemon runs', () => { + expect(isReachable(RUNNING)).toBe(true); + expect(isReachable(STOPPED)).toBe(false); + expect(isReachable({ kind: 'connected', daemon: { kind: 'incompatible', version: 2 } })).toBe( + false, + ); + expect(isReachable(NETWORK)).toBe(false); + expect(isReachable({ kind: 'connecting' })).toBe(false); + expect(isReachable({ kind: 'disconnected' })).toBe(false); + }); +}); + +describe('connection log', () => { + it('given a drop and a recovery, should record the cause, message and time to recover', () => { + let log: readonly ConnectionLogEntry[] = []; + log = nextConnectionLog(log, RUNNING, REFUSED, 1_000); + expect(log).toEqual([{ at: 1_000, cause: 'server_refused', message: REFUSED.reason }]); + // Down for the same cause: no new entry. + expect(nextConnectionLog(log, REFUSED, { ...REFUSED, reason: 'again' }, 2_000)).toBe(log); + // Down for another cause: a new drop. + log = nextConnectionLog(log, REFUSED, NETWORK, 3_000); + expect(log.map((entry) => entry.cause)).toEqual(['server_refused', 'network']); + log = nextConnectionLog(log, NETWORK, RUNNING, 5_500); + expect(log[1]?.recoveredAfterMs).toBe(2_500); + expect(log[0]?.recoveredAfterMs).toBeUndefined(); + // Already recovered: nothing changes. + expect(nextConnectionLog(log, NETWORK, RUNNING, 9_000)).toBe(log); + }); + + it('given a stopped daemon or no network, should log them as drops', () => { + expect(dropOf(STOPPED)).toMatchObject({ cause: 'daemon_stopped' }); + expect( + dropOf({ kind: 'offline', reason: 'x', cause: 'other', waitingForNetwork: true }), + ).toMatchObject({ cause: 'network' }); + expect(dropOf({ kind: 'offline', reason: 'x' })).toEqual({ cause: 'other', message: 'x' }); + expect(dropOf(RUNNING)).toBeNull(); + expect(dropOf({ kind: 'connecting' })).toBeNull(); + }); + + it('given a connect after the user disconnected, should not count it as a recovery', () => { + const log = nextConnectionLog([], RUNNING, REFUSED, 1_000); + expect(nextConnectionLog(log, { kind: 'connecting' }, RUNNING, 9_000)).toBe(log); + }); + + it('given more than the limit, should keep the newest 50', () => { + let log: readonly ConnectionLogEntry[] = []; + for (let i = 0; i < CONNECTION_LOG_LIMIT + 5; i++) { + log = nextConnectionLog(log, RUNNING, NETWORK, i); + log = nextConnectionLog(log, NETWORK, RUNNING, i); + } + expect(log).toHaveLength(CONNECTION_LOG_LIMIT); + expect(log[0]?.at).toBe(5); + }); + + it('given durations and causes, should describe them', () => { + expect(formatRecovery(2_340)).toBe('2.3 s'); + expect(formatRecovery(42_000)).toBe('42 s'); + expect(formatRecovery(250_000)).toBe('4 min 10 s'); + expect(formatRecovery(3_900_000)).toBe('1 h 5 min'); + expect(causeLabel('server_refused')).toBe('Login refused'); + expect(causeLabel('pu_missing')).toBe('PurePoint not installed'); + }); +}); diff --git a/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.ts b/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.ts new file mode 100644 index 00000000..3498d198 --- /dev/null +++ b/apps/purepoint-windows/ui/src/model/machineConnectionPolicy.ts @@ -0,0 +1,198 @@ +// The pure rules of a machine's connection supervision (machines.md MACH-014 – MACH-018): reconnect +// pacing, which device events reconnect at once, wake-from-sleep detection, and the per-machine +// connection log. `MachineConnection` (services/machines.ts) and `LiveMachineState` +// (state/machineState.ts) apply them; the device events come from services/networkMonitor.ts. + +import type { MachineConnectionState } from './sidebarItem.ts'; + +/** Why a connection attempt failed: `pu_core::ssh_failure::SshFailureCause`, snake_case. */ +export type SshFailureCause = + 'server_refused' | 'network' | 'auth' | 'host_key' | 'pu_missing' | 'daemon_stopped' | 'other'; + +/** A short name for the cause, for the machine row and the connection log. */ +export function causeLabel(cause: SshFailureCause): string { + switch (cause) { + case 'server_refused': + return 'Login refused'; + case 'network': + return 'Network'; + case 'auth': + return 'SSH key rejected'; + case 'host_key': + return 'Host key changed'; + case 'pu_missing': + return 'PurePoint not installed'; + case 'daemon_stopped': + return 'Daemon stopped'; + case 'other': + return 'Connection failed'; + } +} + +// MARK: - Reconnect backoff (MACH-016) + +/** The reconnect steps: 1, 2, 4, 8, then every 15 s. */ +export const RECONNECT_STEPS_MS: readonly number[] = [1_000, 2_000, 4_000, 8_000, 15_000]; + +/** + * The wait after `failures` consecutive failed connects (1-based): its step scaled by a uniformly + * random factor in [0.5, 1] ("equal jitter"), so machines and clients do not retry in lockstep. + * `random` returns a sample in [0, 1). + */ +export function reconnectDelayMs(failures: number, random: () => number): number { + const index = Math.min(Math.max(failures, 1), RECONNECT_STEPS_MS.length) - 1; + const step = RECONNECT_STEPS_MS[index] ?? 15_000; + const sample = random(); + const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1) : 1; + return Math.round(step * (0.5 + 0.5 * unit)); +} + +/** The resume jitter after a machine reconnects (MACH-014): uniform 0–1 s. */ +export const RESUME_JITTER_MAX_MS = 1_000; + +export function resumeDelayMs(random: () => number): number { + const sample = random(); + const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1) : 0; + return Math.round(RESUME_JITTER_MAX_MS * unit); +} + +// MARK: - Device events (MACH-016) + +/** Something that should reset the backoff and probe every machine now. */ +export type ReconnectTrigger = 'online' | 'network-change' | 'foreground' | 'focus' | 'wake'; + +/** What the network monitor reports. */ +export type NetworkEvent = + { readonly kind: 'offline' } | { readonly kind: 'trigger'; readonly trigger: ReconnectTrigger }; + +/** A DOM event the monitor listens for, plus the timer's wake detection. */ +export type DeviceSignal = + 'online' | 'offline' | 'connection-change' | 'visibility' | 'focus' | 'wake'; + +/** What a device signal means, given whether the page is visible; null when it means nothing. */ +export function networkEventFor(signal: DeviceSignal, visible: boolean): NetworkEvent | null { + switch (signal) { + case 'offline': + return { kind: 'offline' }; + case 'online': + return { kind: 'trigger', trigger: 'online' }; + case 'connection-change': + return { kind: 'trigger', trigger: 'network-change' }; + case 'visibility': + return visible ? { kind: 'trigger', trigger: 'foreground' } : null; + case 'focus': + return { kind: 'trigger', trigger: 'focus' }; + case 'wake': + return { kind: 'trigger', trigger: 'wake' }; + } +} + +/** + * While the PC has no network a machine re-checks `navigator.onLine` this often, in case the + * `online` event was missed; nothing is sent meanwhile. + */ +export const NETWORK_RECHECK_MS = 30_000; + +/** The wake detector's tick, and how late a tick must be to mean the device slept. */ +export const WAKE_CHECK_INTERVAL_MS = 5_000; +export const WAKE_DRIFT_THRESHOLD_MS = 20_000; + +/** A tick that arrives this late means timers were suspended: the device slept. */ +export function isWakeFromSleep(previousTickMs: number, nowMs: number): boolean { + return nowMs - previousTickMs > WAKE_DRIFT_THRESHOLD_MS; +} + +/** + * Returning to the window (focus, foreground) only probes when the last probe started at least + * this long ago; it fires on every Alt+Tab, and one probe per machine per switch is plenty. A + * network change, coming online and waking always probe. + */ +export const FOREGROUND_PROBE_MIN_INTERVAL_MS = 2_000; + +export function triggerProbesNow( + trigger: ReconnectTrigger, + lastProbeStartedMs: number | null, + nowMs: number, +): boolean { + if (trigger !== 'focus' && trigger !== 'foreground') return true; + return ( + lastProbeStartedMs === null || nowMs - lastProbeStartedMs >= FOREGROUND_PROBE_MIN_INTERVAL_MS + ); +} + +// MARK: - Reachability (MACH-014) + +/** + * Whether the backend may open connections to the machine (`machine_set_reachable`): while it is + * connected and its daemon runs. A stopped or incompatible daemon gets no requests, and an + * offline machine only the supervisor's probe may try. + */ +export function isReachable(state: MachineConnectionState): boolean { + return state.kind === 'connected' && state.daemon.kind === 'running'; +} + +// MARK: - Connection log (MACH-018) + +/** One drop, and how long it took to recover once it did. */ +export interface ConnectionLogEntry { + /** When the drop was seen (ms since the epoch). */ + readonly at: number; + readonly cause: SshFailureCause; + /** ssh's own message, or what the app saw. */ + readonly message: string; + /** Set once the machine is back. */ + readonly recoveredAfterMs?: number; +} + +export const CONNECTION_LOG_LIMIT = 50; + +/** The cause and message of a state that counts as a drop, or null for a healthy one. */ +export function dropOf( + state: MachineConnectionState, +): { readonly cause: SshFailureCause; readonly message: string } | null { + if (state.kind === 'offline') { + if (state.waitingForNetwork === true) { + return { cause: 'network', message: 'This PC has no network connection.' }; + } + return { cause: state.cause ?? 'other', message: state.reason }; + } + if (state.kind === 'connected' && state.daemon.kind === 'stopped') { + return { cause: 'daemon_stopped', message: 'The daemon on the machine is not running.' }; + } + return null; +} + +/** + * The log after the machine moved from `previous` to `next` at `now` (oldest first, at most + * {@link CONNECTION_LOG_LIMIT}). Going down, or down for another cause, adds a drop; coming back + * from a drop (the daemon running again) records how long it took. Connecting after the user + * disconnected is not a recovery. + */ +export function nextConnectionLog( + log: readonly ConnectionLogEntry[], + previous: MachineConnectionState, + next: MachineConnectionState, + now: number, +): readonly ConnectionLogEntry[] { + const drop = dropOf(next); + if (drop !== null) { + const before = dropOf(previous); + if (before !== null && before.cause === drop.cause) return log; + const added = [...log, { at: now, cause: drop.cause, message: drop.message }]; + return added.slice(-CONNECTION_LOG_LIMIT); + } + if (!isReachable(next) || dropOf(previous) === null) return log; + const last = log.at(-1); + if (last === undefined || last.recoveredAfterMs !== undefined) return log; + return [...log.slice(0, -1), { ...last, recoveredAfterMs: Math.max(0, now - last.at) }]; +} + +/** "2.3 s", "4 min 10 s", "1 h 5 min": how long a recovery took. */ +export function formatRecovery(ms: number): string { + if (ms < 10_000) return `${(ms / 1000).toFixed(1)} s`; + const seconds = Math.round(ms / 1000); + if (seconds < 60) return `${String(seconds)} s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${String(minutes)} min ${String(seconds % 60)} s`; + return `${String(Math.floor(minutes / 60))} h ${String(minutes % 60)} min`; +} diff --git a/apps/purepoint-windows/ui/src/model/sidebarItem.ts b/apps/purepoint-windows/ui/src/model/sidebarItem.ts index 2d7a5d5a..c315df9a 100644 --- a/apps/purepoint-windows/ui/src/model/sidebarItem.ts +++ b/apps/purepoint-windows/ui/src/model/sidebarItem.ts @@ -8,6 +8,7 @@ import type { AgentModel, WorktreeModel } from './workspaceModel.ts'; import { type Workspace, containersEqual, isPointGuard, worktreeContainer } from './workspace.ts'; import { lastPathComponent, parseProjectKey } from './projectKey.ts'; +import type { SshFailureCause } from './machineConnectionPolicy.ts'; // MARK: - Nav items @@ -113,7 +114,16 @@ export type MachineConnectionState = | { readonly kind: 'disconnected' } | { readonly kind: 'connecting' } | { readonly kind: 'connected'; readonly daemon: DaemonAvailability } - | { readonly kind: 'offline'; readonly reason: string }; + | { + readonly kind: 'offline'; + /** ssh's own message, or what the app saw. */ + readonly reason: string; + /** Why the last attempt failed (MACH-018), and what that means for the user. */ + readonly cause?: SshFailureCause; + readonly summary?: string; + /** This PC has no network: nothing is tried until it has (MACH-016). */ + readonly waitingForNetwork?: boolean; + }; export function isDaemonRunning(state: MachineConnectionState): boolean { return state.kind === 'connected' && state.daemon.kind === 'running'; diff --git a/apps/purepoint-windows/ui/src/model/sidebarMenu.test.ts b/apps/purepoint-windows/ui/src/model/sidebarMenu.test.ts index add9b087..4ba88378 100644 --- a/apps/purepoint-windows/ui/src/model/sidebarMenu.test.ts +++ b/apps/purepoint-windows/ui/src/model/sidebarMenu.test.ts @@ -55,7 +55,12 @@ describe('SidebarMenuModelTests', () => { 'Kill Agent', ]); expect(contextMenu(row(nodes[1]))).toEqual([]); - expect(titles(contextMenu(row(nodes[2])))).toEqual(['Connect', '-', 'Remove Machine…']); + expect(titles(contextMenu(row(nodes[2])))).toEqual([ + 'Connect', + 'Connection Log…', + '-', + 'Remove Machine…', + ]); // `machine.actionError = "ssh failed"`: a new snapshot, so a rebuilt tree. const failed = { ...machine, actionError: 'ssh failed' }; @@ -63,12 +68,14 @@ describe('SidebarMenuModelTests', () => { expect(titles(contextMenu(row(rebuilt[2])))).toEqual([ 'Connect', 'Dismiss Error', + 'Connection Log…', '-', 'Remove Machine…', ]); expect(machineAccessibilityActions(failed).map((action) => action.name)).toEqual([ 'Connect', 'Dismiss Error', + 'Connection Log', 'Remove Machine', ]); }); diff --git a/apps/purepoint-windows/ui/src/model/sidebarMenu.ts b/apps/purepoint-windows/ui/src/model/sidebarMenu.ts index de0452e5..6d5861ba 100644 --- a/apps/purepoint-windows/ui/src/model/sidebarMenu.ts +++ b/apps/purepoint-windows/ui/src/model/sidebarMenu.ts @@ -33,6 +33,7 @@ export type SidebarMenuAction = | { readonly kind: 'startDaemon'; readonly machineId: string } | { readonly kind: 'showHiddenProjects'; readonly machineId: string } | { readonly kind: 'dismissMachineError'; readonly machineId: string } + | { readonly kind: 'showConnectionLog'; readonly machineId: string } | { readonly kind: 'removeMachine'; readonly machineId: string } | { readonly kind: 'renameWorkspace'; readonly workspaceId: string } | { @@ -148,6 +149,7 @@ export function machineAccessibilityActions( if (machine.actionError !== null) { actions.push({ name: 'Dismiss Error', action: { kind: 'dismissMachineError', machineId } }); } + actions.push({ name: 'Connection Log', action: { kind: 'showConnectionLog', machineId } }); actions.push({ name: 'Remove Machine', action: { kind: 'removeMachine', machineId } }); return actions; } @@ -175,6 +177,8 @@ function machineMenu(machine: MachineSnapshot): SidebarMenuEntry[] { if (machine.actionError !== null) { entries.push(item('Dismiss Error', { kind: 'dismissMachineError', machineId })); } + // MACH-018: the last drops and recoveries, and why each happened. + entries.push(item('Connection Log…', { kind: 'showConnectionLog', machineId })); entries.push(SEPARATOR); entries.push(item('Remove Machine…', { kind: 'removeMachine', machineId })); return entries; diff --git a/apps/purepoint-windows/ui/src/services/machines.ts b/apps/purepoint-windows/ui/src/services/machines.ts index a0d98e92..05b334eb 100644 --- a/apps/purepoint-windows/ui/src/services/machines.ts +++ b/apps/purepoint-windows/ui/src/services/machines.ts @@ -11,10 +11,22 @@ // instances each probe on their own. // - A probe's relay exit status is definitive where the Mac has to infer: exit 69 reports the // daemon stopped at once, and ssh failing (or no `pu` on the machine) reports offline with the -// reason. Other failures still count toward `HealthProbeTracker`'s verdict. -// - Offline retries back off from 2 s to 60 s, as the Mac's forward does. +// reason, its cause and the cause's summary (MACH-018). Other failures still count toward +// `HealthProbeTracker`'s verdict. +// +// Connection hardening (machines.md MACH-014, MACH-016): +// - Offline retries wait 1, 2, 4, 8, then 15 s, each scaled by a random factor in [0.5, 1]. +// - Coming online, a network change, the window returning to the foreground or gaining focus, and +// waking from sleep (services/networkMonitor.ts) reset that backoff and probe at once. While the +// PC has no network the machine shows as waiting for it, and nothing is probed. +// - Every change of whether the machine is reachable (connected, daemon running) is reported to +// the backend (`machine_set_reachable`), whose subscriptions, attaches and requests for the +// machine wait while it is not; a connected state reaches the app only once the backend knows, +// so nothing asked of the machine afterwards is refused. A remote stream failing while the +// machine looks up raises `machine-suspect`, which probes now. import { invoke } from '@tauri-apps/api/core'; +import { listen } from '@tauri-apps/api/event'; import type { Request, Response } from '../protocol'; import type { DaemonAvailability, MachineConnectionState } from '../model/sidebarItem'; import { @@ -23,7 +35,15 @@ import { type Machine, connectionStatesEqual, } from '../model/machine'; +import { + NETWORK_RECHECK_MS, + isReachable, + reconnectDelayMs, + triggerProbesNow, + type NetworkEvent, +} from '../model/machineConnectionPolicy'; import type { DaemonRequester } from './daemonConnection'; +import { type NetworkMonitor, sharedNetworkMonitor } from './networkMonitor'; import { onMachinesChanged, unwatch, watchMachines } from './watchers'; // MARK: - Backend commands @@ -79,11 +99,37 @@ export interface MachineBackend { probe(machineId: string): Promise; /** The error Start daemon met, or null. */ startDaemon(machineId: string): Promise; + /** Open or close the machine's gate (MACH-014). */ + setReachable?(machineId: string, reachable: boolean): Promise; + /** Call `listener` when a remote stream failed while the machine looked up; returns unlisten. */ + onSuspect?(machineId: string, listener: () => void): () => void; } +/** Raised by the backend with a machine's id: probe it now (`daemon/gate.rs`). */ +export const MACHINE_SUSPECT_EVENT = 'machine-suspect'; + export const tauriMachineBackend: MachineBackend = { probe: (machineId) => invoke('machine_probe', { machineId }), startDaemon: (machineId) => invoke('machine_start_daemon', { machineId }), + setReachable: (machineId, reachable) => + invoke('machine_set_reachable', { machineId, reachable }).then(() => undefined), + onSuspect: (machineId, listener) => { + let stopped = false; + let stop: (() => void) | null = null; + void listen(MACHINE_SUSPECT_EVENT, (event) => { + if (event.payload.toLowerCase() === machineId.toLowerCase()) listener(); + }).then( + (unlisten) => { + if (stopped) unlisten(); + else stop = unlisten; + }, + () => {}, + ); + return () => { + stopped = true; + stop?.(); + }; + }, }; /** Watch `machines.json`; resolves the function that stops watching. */ @@ -107,13 +153,24 @@ export interface MachineConnectionOptions { readonly backend?: MachineBackend; /** Resolves after `ms`, or early when `signal` aborts. */ readonly sleep?: (ms: number, signal: AbortSignal) => Promise; + /** Coming online, network changes, focus and wake (MACH-016). */ + readonly network?: NetworkMonitor; + /** A uniform sample in [0, 1) for the backoff's jitter. */ + readonly random?: () => number; + readonly now?: () => number; } /** Probe intervals (Swift `MachineConnection.supervise`). */ export const PROBE_INTERVAL_MS = 10_000; export const INCONCLUSIVE_PROBE_INTERVAL_MS = 2_000; -export const OFFLINE_BACKOFF_INITIAL_MS = 2_000; -export const OFFLINE_BACKOFF_MAX_MS = 60_000; + +/** The offline state while this PC has no network. */ +export const WAITING_FOR_NETWORK: MachineConnectionState = { + kind: 'offline', + reason: 'This PC has no network connection.', + cause: 'network', + waitingForNetwork: true, +}; function abortableSleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { @@ -148,10 +205,22 @@ export class MachineConnection { private readonly onState: (state: MachineConnectionState) => void; private readonly backend: MachineBackend; private readonly sleep: (ms: number, signal: AbortSignal) => Promise; + private readonly network: NetworkMonitor; + private readonly random: () => number; + private readonly now: () => number; private generation = 0; private running = false; private lastReported: MachineConnectionState = { kind: 'disconnected' }; private wake: AbortController | null = null; + /** A device event asked for the backoff to start over. */ + private resetBackoff = false; + private lastProbeStartedMs: number | null = null; + /** What the backend was last told (null: nothing yet, so the first report syncs it). */ + private reportedReachable: boolean | null = null; + private gateUpdate: Promise = Promise.resolve(); + /** Bumped by every report, so a connected state held for the gate update can be superseded. */ + private reportToken = 0; + private stopListening: (() => void) | null = null; constructor( machine: Machine, @@ -162,6 +231,9 @@ export class MachineConnection { this.onState = onState; this.backend = options.backend ?? tauriMachineBackend; this.sleep = options.sleep ?? abortableSleep; + this.network = options.network ?? sharedNetworkMonitor(); + this.random = options.random ?? Math.random; + this.now = options.now ?? Date.now; } get isSupervising(): boolean { @@ -172,16 +244,46 @@ export class MachineConnection { if (this.running) return; this.running = true; this.generation += 1; + this.listen(); void this.supervise(this.generation); } disconnect(): void { this.running = false; this.generation += 1; + this.stopListening?.(); + this.stopListening = null; this.wake?.abort(); this.report({ kind: 'disconnected' }); } + private listen(): void { + this.stopListening?.(); + const stopNetwork = this.network.subscribe((event) => { + this.handleNetworkEvent(event); + }); + const stopSuspect = this.backend.onSuspect?.(this.machine.id, () => { + // Only while it looks up: offline, the backoff already decides when to try. + if (this.lastReported.kind === 'connected') this.refreshNow(); + }); + this.stopListening = () => { + stopNetwork(); + stopSuspect?.(); + }; + } + + /** MACH-016: device events reset the backoff and probe at once. */ + private handleNetworkEvent(event: NetworkEvent): void { + if (!this.running) return; + if (event.kind === 'offline') { + // The loop sees `isOnline` false and waits for the network. + this.wake?.abort(); + return; + } + this.resetBackoff = true; + if (triggerProbesNow(event.trigger, this.lastProbeStartedMs, this.now())) this.wake?.abort(); + } + /** Probe now rather than at the next interval — after Start daemon, for instance. */ refreshNow(): void { this.wake?.abort(); @@ -205,10 +307,22 @@ export class MachineConnection { } private async supervise(generation: number): Promise { - let backoff = OFFLINE_BACKOFF_INITIAL_MS; + let failures = 0; let tracker = new HealthProbeTracker(); this.report({ kind: 'connecting' }); while (this.isCurrent(generation)) { + if (this.resetBackoff) { + this.resetBackoff = false; + failures = 0; + } + if (!this.network.isOnline) { + // No network: nothing to try until it is back (an `online` event wakes this early). + tracker = new HealthProbeTracker(); + this.report(WAITING_FOR_NETWORK); + await this.pause(NETWORK_RECHECK_MS); + continue; + } + this.lastProbeStartedMs = this.now(); let probe: HealthProbe; try { probe = await this.backend.probe(this.machine.id); @@ -219,11 +333,16 @@ export class MachineConnection { let delay: number; if (probe.kind === 'offline') { tracker = new HealthProbeTracker(); - this.report({ kind: 'offline', reason: probe.reason }); - delay = backoff; - backoff = Math.min(backoff * 2, OFFLINE_BACKOFF_MAX_MS); + this.report({ + kind: 'offline', + reason: probe.reason, + ...(probe.cause === undefined ? {} : { cause: probe.cause }), + ...(probe.summary === undefined ? {} : { summary: probe.summary }), + }); + failures += 1; + delay = reconnectDelayMs(failures, this.random); } else { - backoff = OFFLINE_BACKOFF_INITIAL_MS; + failures = 0; let availability: DaemonAvailability | null; if (probe.kind === 'stopped') { tracker = new HealthProbeTracker(); @@ -235,16 +354,43 @@ export class MachineConnection { // An inconclusive probe (BUSY, or a failure short of the limit) retries soon. delay = availability === null ? INCONCLUSIVE_PROBE_INTERVAL_MS : PROBE_INTERVAL_MS; } - const wake = new AbortController(); - this.wake = wake; - await this.sleep(delay, wake.signal); - if (this.wake === wake) this.wake = null; + await this.pause(delay); } } + /** Sleep `ms`, or until `refreshNow` or a device event wakes the loop. */ + private async pause(ms: number): Promise { + const wake = new AbortController(); + this.wake = wake; + await this.sleep(ms, wake.signal); + if (this.wake === wake) this.wake = null; + } + private report(state: MachineConnectionState): void { if (connectionStatesEqual(state, this.lastReported)) return; this.lastReported = state; - this.onState(state); + this.reportToken += 1; + const token = this.reportToken; + const reachable = isReachable(state); + if (reachable !== this.reportedReachable) { + this.reportedReachable = reachable; + this.gateUpdate = this.updateGate(reachable); + } + if (!reachable) { + this.onState(state); + return; + } + // MACH-014: the backend's gate opens first, so what the app then asks of the machine passes. + void this.gateUpdate.then(() => { + if (token === this.reportToken) this.onState(state); + }); + } + + private async updateGate(reachable: boolean): Promise { + try { + await this.backend.setReachable?.(this.machine.id, reachable); + } catch (error) { + console.warn('PurePoint: could not report the machine state', error); + } } } diff --git a/apps/purepoint-windows/ui/src/services/networkMonitor.test.ts b/apps/purepoint-windows/ui/src/services/networkMonitor.test.ts new file mode 100644 index 00000000..12ee38ca --- /dev/null +++ b/apps/purepoint-windows/ui/src/services/networkMonitor.test.ts @@ -0,0 +1,117 @@ +// The device events that reconnect machines (machines.md MACH-016). +import { describe, expect, it } from 'vitest'; +import type { NetworkEvent } from '../model/machineConnectionPolicy'; +import { BrowserNetworkMonitor, type NetworkEnvironment } from './networkMonitor'; + +class Target { + readonly handlers = new Map void>>(); + addEventListener(type: string, listener: () => void) { + const set = this.handlers.get(type) ?? new Set(); + set.add(listener); + this.handlers.set(type, set); + } + removeEventListener(type: string, listener: () => void) { + this.handlers.get(type)?.delete(listener); + } + fire(type: string) { + for (const listener of this.handlers.get(type) ?? []) listener(); + } + get count(): number { + return [...this.handlers.values()].reduce((sum, set) => sum + set.size, 0); + } +} + +function environment() { + const win = new Target(); + const doc = Object.assign(new Target(), { visibilityState: 'visible' }); + const connection = new Target(); + const nav = { onLine: true, connection }; + const clock = { now: 0 }; + let tick: (() => void) | null = null; + const env: NetworkEnvironment = { + window: win, + document: doc, + navigator: nav, + now: () => clock.now, + setInterval: (callback) => { + tick = callback; + return 1; + }, + clearInterval: () => { + tick = null; + }, + }; + return { + env, + win, + doc, + nav, + connection, + clock, + tick: () => { + tick?.(); + }, + ticking: () => tick !== null, + }; +} + +describe('BrowserNetworkMonitor', () => { + it('given device events, should report each as a reconnect or an offline', () => { + const e = environment(); + const monitor = new BrowserNetworkMonitor(e.env); + const events: NetworkEvent[] = []; + const stop = monitor.subscribe((event) => events.push(event)); + e.win.fire('offline'); + e.win.fire('online'); + e.win.fire('focus'); + e.connection.fire('change'); + e.doc.fire('visibilitychange'); + e.doc.visibilityState = 'hidden'; + e.doc.fire('visibilitychange'); + expect(events).toEqual([ + { kind: 'offline' }, + { kind: 'trigger', trigger: 'online' }, + { kind: 'trigger', trigger: 'focus' }, + { kind: 'trigger', trigger: 'network-change' }, + { kind: 'trigger', trigger: 'foreground' }, + ]); + stop(); + }); + + it('given a timer tick far later than due, should report a wake from sleep', () => { + const e = environment(); + const monitor = new BrowserNetworkMonitor(e.env); + const events: NetworkEvent[] = []; + const stop = monitor.subscribe((event) => events.push(event)); + e.clock.now = 5_000; + e.tick(); + expect(events).toEqual([]); + e.clock.now = 65_000; + e.tick(); + expect(events).toEqual([{ kind: 'trigger', trigger: 'wake' }]); + stop(); + }); + + it('given its last listener leaving, should stop listening; it reads onLine', () => { + const e = environment(); + const monitor = new BrowserNetworkMonitor(e.env); + const first = monitor.subscribe(() => {}); + const second = monitor.subscribe(() => {}); + expect(e.win.count).toBe(3); + expect(e.ticking()).toBe(true); + first(); + expect(e.win.count).toBe(3); + second(); + expect(e.win.count + e.doc.count + e.connection.count).toBe(0); + expect(e.ticking()).toBe(false); + expect(monitor.isOnline).toBe(true); + e.nav.onLine = false; + expect(monitor.isOnline).toBe(false); + }); + + it('given no browser, should report online and nothing else', () => { + const monitor = new BrowserNetworkMonitor(null); + expect(monitor.isOnline).toBe(true); + monitor.subscribe(() => {})(); + }); +}); diff --git a/apps/purepoint-windows/ui/src/services/networkMonitor.ts b/apps/purepoint-windows/ui/src/services/networkMonitor.ts new file mode 100644 index 00000000..656a3b90 --- /dev/null +++ b/apps/purepoint-windows/ui/src/services/networkMonitor.ts @@ -0,0 +1,131 @@ +// The device events that reconnect machines at once (machines.md MACH-016): coming online, a +// network change (`navigator.connection`, which WebView2 has as Chromium does), the window +// returning to the foreground or gaining focus, and waking from sleep, which no web event reports: +// a timer that fires far later than it was due means the device slept. Going offline is reported +// too, so machines wait for the network instead of trying. +// +// One monitor serves every machine; it listens only while something subscribes. What each signal +// means is `networkEventFor` (model/machineConnectionPolicy.ts). + +import { + type DeviceSignal, + type NetworkEvent, + WAKE_CHECK_INTERVAL_MS, + isWakeFromSleep, + networkEventFor, +} from '../model/machineConnectionPolicy'; + +/** What `MachineConnection` asks of the network. */ +export interface NetworkMonitor { + /** False only when the browser knows there is no network (`navigator.onLine`). */ + readonly isOnline: boolean; + /** Listen for events; returns the function that stops listening. */ + subscribe(listener: (event: NetworkEvent) => void): () => void; +} + +interface Listenable { + addEventListener(type: string, listener: () => void): void; + removeEventListener(type: string, listener: () => void): void; +} + +/** The browser surface the monitor uses (tests stand in). */ +export interface NetworkEnvironment { + readonly window: Listenable; + readonly document: Listenable & { readonly visibilityState: string }; + readonly navigator: { readonly onLine: boolean; readonly connection?: Listenable }; + now(): number; + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +} + +function browserEnvironment(): NetworkEnvironment | null { + if (typeof window === 'undefined' || typeof document === 'undefined') return null; + const nav = navigator as Navigator & { readonly connection?: Listenable }; + return { + window, + document, + navigator: nav, + now: () => Date.now(), + setInterval: (callback, ms) => setInterval(callback, ms), + clearInterval: (handle) => { + clearInterval(handle as ReturnType); + }, + }; +} + +export class BrowserNetworkMonitor implements NetworkMonitor { + private readonly env: NetworkEnvironment | null; + private readonly listeners = new Set<(event: NetworkEvent) => void>(); + private stop: (() => void) | null = null; + + constructor(env: NetworkEnvironment | null = browserEnvironment()) { + this.env = env; + } + + get isOnline(): boolean { + return this.env?.navigator.onLine ?? true; + } + + subscribe(listener: (event: NetworkEvent) => void): () => void { + this.listeners.add(listener); + if (this.stop === null) this.start(); + return () => { + this.listeners.delete(listener); + if (this.listeners.size === 0) { + this.stop?.(); + this.stop = null; + } + }; + } + + private emit(signal: DeviceSignal): void { + const event = networkEventFor(signal, this.env?.document.visibilityState !== 'hidden'); + if (event === null) return; + for (const listener of [...this.listeners]) listener(event); + } + + private start(): void { + const env = this.env; + if (env === null) { + this.stop = () => {}; + return; + } + const on = (target: Listenable, type: string, signal: DeviceSignal) => { + const handler = () => { + this.emit(signal); + }; + target.addEventListener(type, handler); + return () => { + target.removeEventListener(type, handler); + }; + }; + const stops = [ + on(env.window, 'online', 'online'), + on(env.window, 'offline', 'offline'), + on(env.window, 'focus', 'focus'), + on(env.document, 'visibilitychange', 'visibility'), + ]; + if (env.navigator.connection !== undefined) { + stops.push(on(env.navigator.connection, 'change', 'connection-change')); + } + let lastTick = env.now(); + const timer = env.setInterval(() => { + const now = env.now(); + const slept = isWakeFromSleep(lastTick, now); + lastTick = now; + if (slept) this.emit('wake'); + }, WAKE_CHECK_INTERVAL_MS); + this.stop = () => { + env.clearInterval(timer); + for (const stop of stops) stop(); + }; + } +} + +let shared: BrowserNetworkMonitor | null = null; + +/** The app's monitor, made on first use. */ +export function sharedNetworkMonitor(): NetworkMonitor { + shared ??= new BrowserNetworkMonitor(); + return shared; +} diff --git a/apps/purepoint-windows/ui/src/state/appState.ts b/apps/purepoint-windows/ui/src/state/appState.ts index 16ad48fb..4b5331b5 100644 --- a/apps/purepoint-windows/ui/src/state/appState.ts +++ b/apps/purepoint-windows/ui/src/state/appState.ts @@ -25,6 +25,7 @@ import { createStore, type StoreApi } from 'zustand/vanilla'; import type { Machine } from '../model/machine'; +import type { ConnectionLogEntry } from '../model/machineConnectionPolicy'; import { type AgentModel, agentSignalPresentation, isAgentAlive } from '../model/workspaceModel'; import { makeSignalAlertAgent, type SignalAlertAgent } from '../model/agentSignalPolicy'; import { @@ -100,6 +101,8 @@ export interface MachineState { readonly unsavedFileNames?: readonly string[]; /** Swift `unsavedFileNames(in:)`. */ unsavedFileNamesIn?(project: ProjectState): string[]; + /** The last drops and recoveries, oldest first (machines.md MACH-018). */ + readonly connectionLog?: readonly ConnectionLogEntry[]; } /** The machine registry and how machine states are made (Swift `MachineRegistryStore`). */ diff --git a/apps/purepoint-windows/ui/src/state/machineState.test.ts b/apps/purepoint-windows/ui/src/state/machineState.test.ts index 6f6e7cc6..82785474 100644 --- a/apps/purepoint-windows/ui/src/state/machineState.test.ts +++ b/apps/purepoint-windows/ui/src/state/machineState.test.ts @@ -4,7 +4,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Request, Response } from '../protocol'; import type { HealthProbe, Machine } from '../model/machine'; import type { MachineConnectionState } from '../model/sidebarItem'; -import { MachineConnection, type MachineBackend } from '../services/machines'; +import { MachineConnection, WAITING_FOR_NETWORK, type MachineBackend } from '../services/machines'; +import type { NetworkEvent } from '../model/machineConnectionPolicy'; +import type { NetworkMonitor } from '../services/networkMonitor'; import { MemoryStorage } from '../model/sidebarFixtures'; import { LiveMachineState, @@ -124,10 +126,14 @@ function setup() { sleep: () => new Promise(() => {}), log: () => {}, }, + resumeDelayMs: () => 0, + now: () => clock.now, }); return { machine, daemon, connection, storage, appState, subscriptions }; } +const clock = { now: 1_000_000 }; + const live: LiveMachineState[] = []; afterEach(() => { for (const machine of live.splice(0)) machine.disconnect(); @@ -237,6 +243,72 @@ describe('LiveMachineState', () => { expect(t.machine.actionError).toBeNull(); }); + it('given drops and recoveries, should keep a connection log', async () => { + const t = setup(); + live.push(t.machine); + t.machine.connect(); + clock.now = 1_000; + t.connection.onState(RUNNING); + expect(t.machine.connectionLog).toEqual([]); + clock.now = 2_000; + t.connection.onState({ + kind: 'offline', + reason: 'Connection closed by 10.0.0.5 port 22', + cause: 'server_refused', + }); + clock.now = 3_000; + // Still down for the same cause: the same drop. + t.connection.onState({ kind: 'offline', reason: 'again', cause: 'server_refused' }); + clock.now = 6_500; + t.connection.onState(RUNNING); + expect(t.machine.connectionLog).toEqual([ + { + at: 2_000, + cause: 'server_refused', + message: 'Connection closed by 10.0.0.5 port 22', + recoveredAfterMs: 4_500, + }, + ]); + await settle(); + }); + + it('given a reconnect, should start the project refresh after the resume jitter', async () => { + const daemon = new FakeDaemon(); + daemon.roots = ['/srv/app']; + let onState: (state: MachineConnectionState) => void = () => {}; + const machine = new LiveMachineState({ + machine: MACHINE, + owner: owner(), + storage: new MemoryStorage(), + makeClient: () => ({ send: daemon.send }), + makeConnection: (_machine, report) => { + onState = report; + return new FakeConnection(); + }, + projectEnvironment: { + startSubscriptions: () => Promise.resolve(), + stopSubscriptions: () => Promise.resolve(true), + sleep: () => new Promise(() => {}), + log: () => {}, + }, + resumeDelayMs: () => 40, + }); + live.push(machine); + const inventories = () => daemon.requests.filter((r) => r.type === 'inventory').length; + machine.connect(); + onState(RUNNING); + await settle(); + expect(inventories()).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(inventories()).toBe(1); + // Going offline before the jitter ran cancels it. + onState({ kind: 'offline', reason: 'x' }); + onState(RUNNING); + onState({ kind: 'offline', reason: 'y' }); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(inventories()).toBe(1); + }); + it('given an explicit disconnect, should stay disconnected at the next launch', async () => { const t = setup(); live.push(t.machine); @@ -253,15 +325,48 @@ describe('LiveMachineState', () => { }); }); +class FakeNetwork implements NetworkMonitor { + isOnline = true; + private readonly listeners = new Set<(event: NetworkEvent) => void>(); + get listening(): number { + return this.listeners.size; + } + subscribe(listener: (event: NetworkEvent) => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + emit(event: NetworkEvent): void { + for (const listener of this.listeners) listener(event); + } +} + describe('MachineConnection', () => { - function connection(probes: HealthProbe[]) { + function connection(probes: HealthProbe[], options: { random?: () => number } = {}) { const states: MachineConnectionState[] = []; const delays: number[] = []; + const gate: boolean[] = []; + let probeCount = 0; + let suspect: (() => void) | null = null; let wake: (() => void) | null = null; + const now = { ms: 0 }; const backend: MachineBackend = { - probe: () => Promise.resolve(probes.shift() ?? { kind: 'running' }), + probe: () => { + probeCount += 1; + return Promise.resolve(probes.shift() ?? { kind: 'running' }); + }, startDaemon: () => Promise.resolve(null), + setReachable: (_id, reachable) => { + gate.push(reachable); + return Promise.resolve(); + }, + onSuspect: (_id, listener) => { + suspect = listener; + return () => { + suspect = null; + }; + }, }; + const network = new FakeNetwork(); const subject = new MachineConnection( MACHINE, (state) => { @@ -269,10 +374,16 @@ describe('MachineConnection', () => { }, { backend, - sleep: (ms) => { + network, + random: options.random ?? (() => 1), + now: () => now.ms, + sleep: (ms, signal) => { delays.push(ms); return new Promise((resolve) => { wake = resolve; + signal.addEventListener('abort', () => { + resolve(); + }); }); }, }, @@ -284,30 +395,140 @@ describe('MachineConnection', () => { next?.(); await settle(); }; - return { subject, states, delays, step }; + return { + subject, + states, + delays, + gate, + network, + now, + step, + probes: () => probeCount, + suspect: () => { + suspect?.(); + }, + }; } it('given relay verdicts, should report connecting, then each state, and back off offline', async () => { + const offline: HealthProbe = { + kind: 'offline', + reason: 'kex_exchange_identification: Connection closed by remote host', + cause: 'server_refused', + summary: 'The server refused the login.', + }; + const c = connection([offline, offline, { kind: 'stopped' }, { kind: 'running' }]); + c.subject.connect(); + await c.step(); + await c.step(); + await c.step(); + await settle(); + expect(c.states).toEqual([{ kind: 'connecting' }, offline, STOPPED, RUNNING]); + expect(c.delays.slice(0, 4)).toEqual([1_000, 2_000, 10_000, 10_000]); + c.subject.disconnect(); + expect(c.states.at(-1)).toEqual({ kind: 'disconnected' }); + }); + + it('given consecutive offline probes, should wait 1, 2, 4, 8, then 15 s with equal jitter', async () => { + const offline: HealthProbe = { kind: 'offline', reason: 'ssh: timed out', cause: 'network' }; + const full = connection(Array(7).fill(offline)); + full.subject.connect(); + for (let i = 0; i < 6; i++) await full.step(); + expect(full.delays.slice(0, 6)).toEqual([1_000, 2_000, 4_000, 8_000, 15_000, 15_000]); + full.subject.disconnect(); + + const half = connection(Array(3).fill(offline), { random: () => 0 }); + half.subject.connect(); + for (let i = 0; i < 2; i++) await half.step(); + expect(half.delays.slice(0, 3)).toEqual([500, 1_000, 2_000]); + half.subject.disconnect(); + }); + + it('given the machine reachable, should open the backend gate before reporting it', async () => { const c = connection([ - { kind: 'offline', reason: 'ssh: Could not resolve hostname' }, - { kind: 'offline', reason: 'ssh: Could not resolve hostname' }, - { kind: 'stopped' }, + { kind: 'running' }, + { kind: 'offline', reason: 'x', cause: 'network' }, { kind: 'running' }, ]); c.subject.connect(); + await settle(); + // Connecting closes the gate (whatever a reloaded page left), running opens it first. + expect(c.gate).toEqual([false, true]); + expect(c.states).toEqual([{ kind: 'connecting' }, RUNNING]); await c.step(); + expect(c.gate).toEqual([false, true, false]); + await c.step(); + expect(c.gate).toEqual([false, true, false, true]); + c.subject.disconnect(); + expect(c.gate.at(-1)).toBe(false); + }); + + it('given a network change, should reset the backoff and probe at once', async () => { + const offline: HealthProbe = { kind: 'offline', reason: 'x', cause: 'network' }; + const c = connection([offline, offline, offline, offline]); + c.subject.connect(); await c.step(); await c.step(); await settle(); - expect(c.states).toEqual([ - { kind: 'connecting' }, - { kind: 'offline', reason: 'ssh: Could not resolve hostname' }, - STOPPED, - RUNNING, - ]); - expect(c.delays.slice(0, 4)).toEqual([2_000, 4_000, 10_000, 10_000]); + expect(c.delays).toEqual([1_000, 2_000, 4_000]); + expect(c.probes()).toBe(3); + // Sleeping 4 s: a network change wakes it now, and the backoff starts over. + c.network.emit({ kind: 'trigger', trigger: 'network-change' }); + await settle(); + expect(c.probes()).toBe(4); + expect(c.delays.at(-1)).toBe(1_000); + c.subject.disconnect(); + expect(c.network.listening).toBe(0); + }); + + it('given focus right after a probe, should not probe again', async () => { + const c = connection([{ kind: 'running' }]); + c.subject.connect(); + await settle(); + expect(c.probes()).toBe(1); + c.now.ms = 500; + c.network.emit({ kind: 'trigger', trigger: 'focus' }); + await settle(); + expect(c.probes()).toBe(1); + c.now.ms = 5_000; + c.network.emit({ kind: 'trigger', trigger: 'foreground' }); + await settle(); + expect(c.probes()).toBe(2); + c.subject.disconnect(); + }); + + it('given no network, should wait for it without probing', async () => { + const c = connection([]); + c.network.isOnline = false; + c.subject.connect(); + await settle(); + expect(c.probes()).toBe(0); + expect(c.states.at(-1)).toEqual(WAITING_FOR_NETWORK); + // A missed `online` event: the periodic re-check still probes nothing while offline. + await c.step(); + expect(c.probes()).toBe(0); + c.network.isOnline = true; + c.network.emit({ kind: 'trigger', trigger: 'online' }); + await settle(); + expect(c.probes()).toBe(1); + expect(c.states.at(-1)).toEqual(RUNNING); + c.network.isOnline = false; + c.network.emit({ kind: 'offline' }); + await settle(); + expect(c.states.at(-1)).toEqual(WAITING_FOR_NETWORK); + expect(c.gate.at(-1)).toBe(false); + c.subject.disconnect(); + }); + + it('given a failing remote stream while connected, should probe now', async () => { + const c = connection([{ kind: 'running' }, { kind: 'running' }]); + c.subject.connect(); + await settle(); + expect(c.probes()).toBe(1); + c.suspect(); + await settle(); + expect(c.probes()).toBe(2); c.subject.disconnect(); - expect(c.states.at(-1)).toEqual({ kind: 'disconnected' }); }); it('given failed probes, should keep the last state until three in a row', async () => { @@ -333,6 +554,7 @@ describe('MachineConnection', () => { const states: MachineConnectionState[] = []; const subject = new MachineConnection(MACHINE, (s) => states.push(s), { backend, + network: new FakeNetwork(), sleep: () => new Promise(() => {}), }); subject.connect(); diff --git a/apps/purepoint-windows/ui/src/state/machineState.ts b/apps/purepoint-windows/ui/src/state/machineState.ts index 3b61a20f..bc35beb8 100644 --- a/apps/purepoint-windows/ui/src/state/machineState.ts +++ b/apps/purepoint-windows/ui/src/state/machineState.ts @@ -19,6 +19,11 @@ // unsaved file names come from the registry's file tabs only. // - Preferences (hidden projects, user-disconnected machines) live in the webview's // `localStorage` under the Mac's `UserDefaults` keys. +// - The project refresh starts a uniformly random 0–1 s after the daemon is back (MACH-014), so +// a reconnect does not ask everything of the machine at once; it never runs while the machine +// is not connected. +// - The machine keeps an in-memory connection log of its last 50 drops and recoveries (MACH-018), +// which the sidebar's Connection Log dialog lists. import { createStore, type StoreApi } from 'zustand/vanilla'; import { @@ -27,6 +32,11 @@ import { connectionStatesEqual, machineStatusText, } from '../model/machine'; +import { + type ConnectionLogEntry, + nextConnectionLog, + resumeDelayMs, +} from '../model/machineConnectionPolicy'; import { ProjectOrderSaver, movingProject, sortedByProjectOrder } from '../model/projectOrder'; import { type MachineConnectionState, @@ -82,6 +92,8 @@ export interface MachineStateFields { * before the first inventory reply and for a machine with nothing registered. */ readonly hasLoadedProjects: boolean; + /** The last drops and recoveries, oldest first (MACH-018). */ + readonly connectionLog: readonly ConnectionLogEntry[]; } export interface LiveMachineStateOptions { @@ -96,6 +108,9 @@ export interface LiveMachineStateOptions { readonly projectEnvironment?: Partial; /** How often the project list is re-read while the daemon is up. */ readonly refreshIntervalMs?: number; + /** The wait before the first refresh once the daemon is up (default: uniform 0–1 s). */ + readonly resumeDelayMs?: () => number; + readonly now?: () => number; } /** How often the project list is re-read while the daemon is up (Swift `refreshInterval`). */ @@ -170,6 +185,9 @@ export class LiveMachineState implements MachineState { private connectionGeneration = 0; private hiddenRoots: Set; private refreshTimer: ReturnType | null = null; + private refreshStart: ReturnType | null = null; + private readonly resumeDelay: () => number; + private readonly now: () => number; private isUserDisconnecting = false; /** Bumped by each local move, so a project list fetched before it can't undo it. */ private orderRevision = 0; @@ -184,6 +202,8 @@ export class LiveMachineState implements MachineState { options.makeConnection ?? ((machine, onState) => new MachineConnection(machine, onState)); this.projectEnvironment = options.projectEnvironment; this.refreshIntervalMs = options.refreshIntervalMs ?? PROJECT_REFRESH_INTERVAL_MS; + this.resumeDelay = options.resumeDelayMs ?? (() => resumeDelayMs(Math.random)); + this.now = options.now ?? Date.now; this.client = this.makeClient(options.machine.id); this.hiddenRoots = new Set(readList(this.storage, hiddenKey(options.machine.id))); this.store = createStore()(() => ({ @@ -194,6 +214,7 @@ export class LiveMachineState implements MachineState { isStartingDaemon: false, hiddenCountRevision: 0, hasLoadedProjects: false, + connectionLog: [], })); this.connection = this.newConnection(); this.orderSaver = new ProjectOrderSaver(async (roots) => { @@ -248,6 +269,11 @@ export class LiveMachineState implements MachineState { return this.s.hasLoadedProjects; } + /** The last drops and recoveries, oldest first. */ + get connectionLog(): readonly ConnectionLogEntry[] { + return this.s.connectionLog; + } + get isConnectedOrConnecting(): boolean { return this.state.kind !== 'disconnected'; } @@ -374,7 +400,8 @@ export class LiveMachineState implements MachineState { if (this.isUserDisconnecting && next.kind !== 'disconnected') return; if (connectionStatesEqual(next, this.state)) return; const wasRunning = isDaemonRunning(this.state); - this.set({ state: next }); + const connectionLog = nextConnectionLog(this.s.connectionLog, this.state, next, this.now()); + this.set({ state: next, ...(connectionLog === this.s.connectionLog ? {} : { connectionLog }) }); if (isDaemonRunning(next)) { if (!wasRunning) this.startRefreshing(); return; @@ -390,13 +417,21 @@ export class LiveMachineState implements MachineState { private startRefreshing(): void { this.stopRefreshing(); - void this.refreshProjects(); - this.refreshTimer = setInterval(() => { + const begin = () => { + this.refreshStart = null; void this.refreshProjects(); - }, this.refreshIntervalMs); + this.refreshTimer = setInterval(() => { + void this.refreshProjects(); + }, this.refreshIntervalMs); + }; + const delay = this.resumeDelay(); + if (delay <= 0) begin(); + else this.refreshStart = setTimeout(begin, delay); } private stopRefreshing(): void { + if (this.refreshStart !== null) clearTimeout(this.refreshStart); + this.refreshStart = null; if (this.refreshTimer !== null) clearInterval(this.refreshTimer); this.refreshTimer = null; } diff --git a/apps/purepoint-windows/ui/src/views/sidebar/ConnectionLogDialog.tsx b/apps/purepoint-windows/ui/src/views/sidebar/ConnectionLogDialog.tsx new file mode 100644 index 00000000..1fe24184 --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/sidebar/ConnectionLogDialog.tsx @@ -0,0 +1,103 @@ +// A machine's connection log (machines.md MACH-018): the last 50 drops this app saw, newest first, +// each with its time, cause, ssh's message and how long the machine took to come back. The +// machine's context menu opens it (Connection Log…). The log is in memory only (`LiveMachineState`) +// and starts empty at launch. + +import { useEffect, useId, useRef } from 'react'; +import { useStore } from 'zustand'; +import { + type ConnectionLogEntry, + causeLabel, + formatRecovery, +} from '../../model/machineConnectionPolicy.ts'; +import type { MachineState } from '../../state/appState.ts'; +import { useAppState } from '../shell/appContext.ts'; + +/** Entries newest first. */ +export function newestFirst(log: readonly ConnectionLogEntry[]): ConnectionLogEntry[] { + return [...log].reverse(); +} + +function when(at: number): string { + const date = new Date(at); + const today = new Date(); + const sameDay = date.toDateString() === today.toDateString(); + return sameDay + ? date.toLocaleTimeString() + : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`; +} + +export function ConnectionLogDialog({ + machine, + onDismiss, +}: { + machine: MachineState; + onDismiss: () => void; +}) { + const titleId = useId(); + const close = useRef(null); + useEffect(() => { + close.current?.focus(); + }, []); + const app = useAppState(); + // A machine change bumps the revision: re-read the log, so the dialog follows new drops. + useStore(app.store, (state) => state.projectRevision); + const entries = newestFirst(machine.connectionLog ?? []); + + return ( +
{ + if (event.target === event.currentTarget) onDismiss(); + }} + > +
{ + if (event.key === 'Escape') { + event.stopPropagation(); + onDismiss(); + } + }} + > +

+ Connection Log for {machine.machine.name} +

+ {entries.length === 0 ? ( +

+ No drops since PurePoint started. Drops and how long each took to recover are listed + here. +

+ ) : ( +
    + {entries.map((entry, index) => ( +
  1. +
    + {causeLabel(entry.cause)} + +
    +
    {entry.message}
    +
    + {entry.recoveredAfterMs === undefined + ? 'Not recovered yet' + : `Recovered after ${formatRecovery(entry.recoveredAfterMs)}`} +
    +
  2. + ))} +
+ )} +
+ +
+
+
+ ); +} diff --git a/apps/purepoint-windows/ui/src/views/sidebar/SidebarOutlineViewController.tsx b/apps/purepoint-windows/ui/src/views/sidebar/SidebarOutlineViewController.tsx index 1e1cbc47..b444b19f 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/SidebarOutlineViewController.tsx +++ b/apps/purepoint-windows/ui/src/views/sidebar/SidebarOutlineViewController.tsx @@ -171,6 +171,8 @@ export interface SidebarOutlineCallbacks { readonly onDisconnectMachine?: (machineId: string) => void; readonly onShowHiddenProjects?: (machineId: string) => void; readonly onDismissMachineError?: (machineId: string) => void; + /** A machine's Connection Log… (MACH-018). */ + readonly onShowConnectionLog?: (machineId: string) => void; } export interface SidebarOutlineViewControllerProps extends SidebarOutlineCallbacks { @@ -467,7 +469,10 @@ function cellFor({ case 'machine': { const machine = node.machine; let tooltip = `${machine.name} (${machine.sshHost}): ${machine.statusText}`; - if (machine.state.kind === 'offline') tooltip += ' — ' + machine.state.reason; + if (machine.state.kind === 'offline') { + tooltip += ' — ' + machine.state.reason; + if (machine.state.summary !== undefined) tooltip += '\n' + machine.state.summary; + } if (machine.actionError !== null) tooltip += '\n' + machine.actionError; return { label: tooltip, diff --git a/apps/purepoint-windows/ui/src/views/sidebar/SidebarView.tsx b/apps/purepoint-windows/ui/src/views/sidebar/SidebarView.tsx index 59233c1c..7f8600d8 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/SidebarView.tsx +++ b/apps/purepoint-windows/ui/src/views/sidebar/SidebarView.tsx @@ -21,6 +21,7 @@ import { useAppState } from '../shell/appContext.ts'; import { SidebarFooter } from './SidebarFooter.tsx'; import { AddMachineSheet } from './AddMachineSheet.tsx'; import { RemoteFolderPicker } from './RemoteFolderPicker.tsx'; +import { ConnectionLogDialog } from './ConnectionLogDialog.tsx'; import { useMachineSheets } from './machineSheets.ts'; import { SidebarOutlineView } from './SidebarOutlineView.tsx'; import type { @@ -108,16 +109,21 @@ export function SidebarView({ selection, onSelectionChange, expansionStore }: Si ); } -/** Add Machine and the remote folder picker, when one is up (WIN-8.14). */ +/** Add Machine, the remote folder picker and a connection log, when one is up (WIN-8.14). */ function MachineSheets() { const app = useAppState(); const addMachine = useMachineSheets((state) => state.addMachine); const pickerMachineId = useMachineSheets((state) => state.folderPickerMachineId); + const logMachineId = useMachineSheets((state) => state.connectionLogMachineId); const machines = useStore(app.store, (state) => state.machines); const pickerMachine = pickerMachineId === null ? undefined : machines.find((machine) => machine.machine.id === pickerMachineId); + const logMachine = + logMachineId === null + ? undefined + : machines.find((machine) => machine.machine.id === logMachineId); return ( <> {addMachine && ( @@ -136,6 +142,15 @@ function MachineSheets() { }} /> )} + {logMachine !== undefined && ( + { + useMachineSheets.getState().openConnectionLog(null); + }} + /> + )} ); } diff --git a/apps/purepoint-windows/ui/src/views/sidebar/machineSheets.ts b/apps/purepoint-windows/ui/src/views/sidebar/machineSheets.ts index cd5ca794..f7f81bd9 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/machineSheets.ts +++ b/apps/purepoint-windows/ui/src/views/sidebar/machineSheets.ts @@ -1,22 +1,29 @@ -// Which machine sheet is up (WIN-8.14): Add Machine (Swift `SidebarFooter.showAddMachine`) and -// the remote folder picker a machine row's add button opens. +// Which machine sheet is up (WIN-8.14): Add Machine (Swift `SidebarFooter.showAddMachine`), the +// remote folder picker a machine row's add button opens, and a machine's connection log (MACH-018). import { create } from 'zustand'; interface MachineSheetsState { readonly addMachine: boolean; /** The machine whose folders the picker browses; null while it is closed. */ readonly folderPickerMachineId: string | null; + /** The machine whose connection log is open; null while it is closed. */ + readonly connectionLogMachineId: string | null; showAddMachine(show: boolean): void; openFolderPicker(machineId: string | null): void; + openConnectionLog(machineId: string | null): void; } export const useMachineSheets = create()((set) => ({ addMachine: false, folderPickerMachineId: null, + connectionLogMachineId: null, showAddMachine: (show) => { set({ addMachine: show }); }, openFolderPicker: (machineId) => { set({ folderPickerMachineId: machineId }); }, + openConnectionLog: (machineId) => { + set({ connectionLogMachineId: machineId }); + }, })); diff --git a/apps/purepoint-windows/ui/src/views/sidebar/machineViews.test.tsx b/apps/purepoint-windows/ui/src/views/sidebar/machineViews.test.tsx index fdf3cf49..f7325c93 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/machineViews.test.tsx +++ b/apps/purepoint-windows/ui/src/views/sidebar/machineViews.test.tsx @@ -8,6 +8,7 @@ import { AppStateContext } from '../shell/appContext.ts'; import { makeTestApp } from '../shell/testApp.ts'; import { AddMachineSheet } from './AddMachineSheet.tsx'; import { RemoteFolderPicker } from './RemoteFolderPicker.tsx'; +import { ConnectionLogDialog } from './ConnectionLogDialog.tsx'; import { SidebarOutlineViewController } from './SidebarOutlineViewController.tsx'; describe('AddMachineSheet', () => { @@ -144,3 +145,44 @@ describe('RemoteFolderPicker', () => { expect(openProject).toHaveBeenCalledWith('/home/me/app'); }); }); + +describe('ConnectionLogDialog', () => { + function renderLog(connectionLog: MachineState['connectionLog']) { + const machine = { + machine: { id: 'm1', name: 'studio', sshHost: 'studio' }, + connectionLog, + } as unknown as MachineState; + const onDismiss = vi.fn(); + render( + + + , + ); + return onDismiss; + } + + it('given drops, should list them newest first with cause, message and recovery', () => { + const onDismiss = renderLog([ + { at: 1_000, cause: 'network', message: 'ssh: timed out', recoveredAfterMs: 2_500 }, + { at: 9_000, cause: 'server_refused', message: 'Connection closed by 10.0.0.5' }, + ]); + expect(screen.getByRole('dialog')).toHaveAccessibleName('Connection Log for studio'); + const items = screen.getAllByRole('listitem'); + expect(items.map((item) => item.querySelector('.connection-log-cause')?.textContent)).toEqual([ + 'Login refused', + 'Network', + ]); + expect(items[0]).toHaveTextContent('Connection closed by 10.0.0.5'); + expect(items[0]).toHaveTextContent('Not recovered yet'); + expect(items[1]).toHaveTextContent('Recovered after 2.5 s'); + expect(screen.getByRole('button', { name: 'Close' })).toHaveFocus(); + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }); + expect(onDismiss).toHaveBeenCalled(); + }); + + it('given no drops, should say so', () => { + renderLog([]); + expect(screen.queryAllByRole('listitem')).toEqual([]); + expect(screen.getByText(/No drops since PurePoint started/)).toBeInTheDocument(); + }); +}); diff --git a/apps/purepoint-windows/ui/src/views/sidebar/sidebar.css b/apps/purepoint-windows/ui/src/views/sidebar/sidebar.css index 27a1a886..668690c5 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/sidebar.css +++ b/apps/purepoint-windows/ui/src/views/sidebar/sidebar.css @@ -532,6 +532,53 @@ font: 12px var(--pp-font-ui); } +/* A machine's connection log (MACH-018): drops, newest first. */ +.connection-log { + width: min(520px, calc(100vw - 32px)); +} + +.connection-log-list { + max-height: 320px; + margin: 0 0 16px; + padding: 0; + overflow: auto; + list-style: none; + border: 1px solid var(--menu-border); + border-radius: 4px; + background: var(--pp-system-control-background); +} + +.connection-log-entry { + padding: 6px 8px; + font: 12px var(--pp-font-ui); + line-height: 1.4; +} + +.connection-log-entry + .connection-log-entry { + border-top: 1px solid var(--menu-border); +} + +.connection-log-heading { + display: flex; + align-items: baseline; + gap: 8px; +} + +.connection-log-cause { + flex: 1; + font-weight: 600; +} + +.connection-log-time, +.connection-log-recovery { + color: var(--secondary-text); + font-size: 11px; +} + +.connection-log-message { + overflow-wrap: anywhere; +} + /* Context menus and the worktree add menu (WIN-7.8): the menu bar's dropdown, at the pointer. */ .sidebar-context-menu { position: fixed; diff --git a/apps/purepoint-windows/ui/src/views/sidebar/sidebarMenus.test.tsx b/apps/purepoint-windows/ui/src/views/sidebar/sidebarMenus.test.tsx index 34f2ccbd..3635f435 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/sidebarMenus.test.tsx +++ b/apps/purepoint-windows/ui/src/views/sidebar/sidebarMenus.test.tsx @@ -233,6 +233,7 @@ describe('sidebar context menus', () => { onConnectMachine: vi.fn(), onShowHiddenProjects: vi.fn(), onDismissMachineError: vi.fn(), + onShowConnectionLog: vi.fn(), onRemoveMachine: vi.fn(), }; const view = renderOutline({ @@ -265,6 +266,9 @@ describe('sidebar context menus', () => { openMenu(key); choose('Dismiss Error'); expect(callbacks.onDismissMachineError).toHaveBeenCalledWith(machine.id); + openMenu(key); + choose('Connection Log…'); + expect(callbacks.onShowConnectionLog).toHaveBeenCalledWith(machine.id); // Unsaved files make Disconnect ask first. openMenu(key); choose('Disconnect'); diff --git a/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewCallbacks.ts b/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewCallbacks.ts index a1dbfe27..8c081b2b 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewCallbacks.ts +++ b/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewCallbacks.ts @@ -158,5 +158,9 @@ export function wireCallbacks( onDismissMachineError: (machineId) => { machine(machineId)?.dismissError(); }, + + onShowConnectionLog: (machineId) => { + useMachineSheets.getState().openConnectionLog(machineId); + }, }; } diff --git a/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewControllerActions.ts b/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewControllerActions.ts index 4aa313ef..7bba38f7 100644 --- a/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewControllerActions.ts +++ b/apps/purepoint-windows/ui/src/views/sidebar/sidebarOutlineViewControllerActions.ts @@ -136,6 +136,9 @@ export function performSidebarMenuAction( case 'dismissMachineError': callbacks.onDismissMachineError?.(action.machineId); return; + case 'showConnectionLog': + callbacks.onShowConnectionLog?.(action.machineId); + return; case 'removeMachine': { const machine = findMachine(nodes, action.machineId); if (machine === null) return; diff --git a/docs/product/windows-app.md b/docs/product/windows-app.md index 1be039e0..870190d8 100644 --- a/docs/product/windows-app.md +++ b/docs/product/windows-app.md @@ -468,6 +468,13 @@ ssh.exe -T -o BatchMode=yes -o ConnectTimeout=10 -o TCPKeepAlive=yes -o ServerAl - Windows machine (detected once per connection by the start probe: `uname -s` exits non-zero or prints nothing): `` is `pu daemon proxy`. Windows sshd builds the session environment from the user's registry `PATH`, which includes `%USERPROFILE%\.pu\bin`. - Exit 0 means a normal close, 69 means no daemon, and 127 or 9009 means `pu` is missing. - Start daemon runs the machine's start command (`machines.md`, or `pu health` on a Windows machine) with a 60 s limit. +- The probe and the start command pass `-o ConnectTimeout=10 -o TCPKeepAlive=yes` too (MACH-017). A relay whose stdout closes while ssh exits 255 is a dropped link, reported as an error, not as the daemon closing the stream, so an attach reattaches instead of ending as exited. +- Connection resilience (MACH-014 – MACH-018), per machine: + - The front end's supervisor (`MachineConnection`, `ui/src/services/machines.ts`) is the only thing that decides reachability. It reports every change with the `machine_set_reachable { machineId, reachable }` command: reachable while the machine is connected with its daemon running. A connected state reaches the rest of the app only after that call returns. + - The backend keeps one gate per machine (`src-tauri/src/daemon/gate.rs`, a process-wide registry of `tokio::sync::watch` states, closed until first reported). While it is closed, opening a relay connection fails at once with no `ssh.exe`, so requests, file and git calls fail fast, and status and grid subscriptions and attach sessions wait without spending retries. Once it opens each resumes after a uniformly random 0–1 s, and the project refresh likewise. + - A remote stream that fails while the gate is still open waits for a probe that reached the daemon after its failure, and raises `machine-suspect` (the machine's id; at most once per 5 s per machine), on which the supervisor probes at once. + - Offline verdicts carry `cause` (`pu_core::ssh_failure::SshFailureCause`) and its `summary`. The machine row names causes the user can act on, and its context menu's Connection Log… lists the last 50 drops in memory, newest first. + - Offline backoff is 1, 2, 4, 8, then 15 s, each scaled by a random factor in [0.5, 1]. Coming online, `navigator.connection` changes, the window returning to the foreground or gaining focus (at most one probe per 2 s), and a wake from sleep (a 5 s timer seen more than 20 s late) reset it and probe at once. While `navigator.onLine` is false the machine shows "Waiting for network" and nothing is tried. ### App layout (`apps/purepoint-windows`) From 666df0356e34b0fdb69082dbfcd592e3e5406a06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:17:02 +0000 Subject: [PATCH 10/21] feat(win-app): one multiplexed ssh.exe per machine (MACH-013, WINAPP-013a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every daemon connection to a machine - probes, requests, subscriptions, attaches and the git host's calls - is now a channel of one long-lived `ssh.exe … pu daemon proxy --mux` per machine, shared through a process-wide slot registry. The machine probe establishes and re-establishes the session, so a connected machine costs one SSH login however much is open, and a blip no longer makes every stream log in. A machine whose pu predates --mux (exit 2 before the hello) falls back to one ssh.exe per connection for 10 minutes before --mux is tried again; its probe reports legacyRelay and the machine's tooltip suggests upgrading PurePoint there. Handshake failures classify like relay exits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ3HndJSt7rnbKNeNjR --- .../src-tauri/src/daemon/machine.rs | 181 ++++++- .../src-tauri/src/daemon/mod.rs | 1 + .../src-tauri/src/daemon/mux.rs | 478 ++++++++++++++++++ .../src-tauri/src/daemon/relay.rs | 182 ++++++- .../ui/src/model/machine.test.ts | 29 ++ .../purepoint-windows/ui/src/model/machine.ts | 17 +- .../ui/src/model/sidebarItem.ts | 3 +- .../ui/src/services/machines.ts | 8 +- .../sidebar/SidebarOutlineViewController.tsx | 4 + docs/product/windows-app.md | 8 +- 10 files changed, 881 insertions(+), 30 deletions(-) create mode 100644 apps/purepoint-windows/src-tauri/src/daemon/mux.rs diff --git a/apps/purepoint-windows/src-tauri/src/daemon/machine.rs b/apps/purepoint-windows/src-tauri/src/daemon/machine.rs index 4d7456dd..c52b2db1 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/machine.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/machine.rs @@ -2,8 +2,10 @@ //! (WIN-8.14): machines reachable over SSH, through the `ssh.exe` exec relay ([`super::relay`]). //! //! The Mac keeps one `ssh -L` forward per machine and probes the daemon through it. Windows has -//! no forward (WINAPP-013): every connection is its own relay, so a probe is one relayed -//! `health` whose exit status tells the states apart (REQ-WINAPP-054): a reply is a running (or +//! no forward (WINAPP-013). A probe is one `health` on a channel of the machine's multiplexed +//! session ([`super::mux`], MACH-013), which it establishes when there is none; for a machine +//! whose `pu` lacks `--mux` it is one relay process. Either way the relay's exit status tells the +//! states apart (REQ-WINAPP-054), or, on a session, the channel's refusal: a reply is a running (or //! incompatible) daemon, exit 69 is no daemon (stopped), 127 or 9009 is no `pu` on the machine, //! and 255 is ssh itself failing (offline). The front end's `MachineConnection` //! (`ui/src/services/machines.ts`) runs the supervision loop and the probe tracker on top. @@ -38,7 +40,9 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use super::client::{DaemonClient, DaemonError, parse, timeout_for}; use super::gate; +use super::mux::{HandshakeFailure, Session}; use super::relay::{self, RemoteShell, SSH_CONNECT_FAILED, SshRelayConnector}; +use pu_transport::mux::OpenError; /// `pu daemon proxy`'s exit status when nothing listens on the machine's socket. pub const EXIT_NO_DAEMON: i32 = 69; @@ -57,7 +61,17 @@ pub const MACHINE_SUSPECT_EVENT: &str = "machine-suspect"; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum HealthProbe { - Running, + /// The daemon answered. `legacy_relay`: the machine's `pu` predates `pu daemon proxy --mux`, + /// so every connection is its own SSH login; upgrading PurePoint there makes the machine + /// more reliable (MACH-013). + Running { + #[serde( + rename = "legacyRelay", + default, + skip_serializing_if = "std::ops::Not::not" + )] + legacy_relay: bool, + }, Incompatible { version: u32, }, @@ -84,7 +98,9 @@ pub fn classify(response: Result) -> HealthProbe { match response { Ok(Response::HealthReport { protocol_version, .. - }) if protocol_version == PROTOCOL_VERSION => HealthProbe::Running, + }) if protocol_version == PROTOCOL_VERSION => HealthProbe::Running { + legacy_relay: false, + }, Ok(Response::HealthReport { protocol_version, .. }) => HealthProbe::Incompatible { @@ -149,8 +165,92 @@ pub fn classify_exit(machine: &str, code: Option, stderr: &str) -> HealthPr } } -/// Probe the machine's daemon with one relayed `health`. Never starts anything. +/// Probe the machine's daemon with one `health`. Never starts anything. +/// +/// It goes through the machine's multiplexed session (MACH-013), establishing it if there is +/// none, so a probe of a connected machine costs no SSH login, and the probe is what brings a +/// dropped session back. A machine whose `pu` lacks `--mux` is probed with one relay process, +/// as before, and the verdict says so (`legacy_relay`). pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { + let result = match connector.mux_session().await { + Ok(Session::Ready(client)) => probe_channel(&client).await, + Ok(Session::Unsupported) => match probe_per_connection(connector).await { + HealthProbe::Running { .. } => HealthProbe::Running { legacy_relay: true }, + other => other, + }, + Ok(Session::Failed(failure)) => { + let name = relay::machine_target(connector.machine()) + .map(|target| target.name) + .unwrap_or_else(|_| connector.machine().to_owned()); + handshake_probe(&name, &failure) + } + // No ssh, an unknown machine, or the `uname -s` probe could not reach the host. + Err(DaemonError::NotRunning(reason)) => offline_from_message(reason), + Err(error) => HealthProbe::Failed { + reason: error.to_string(), + }, + }; + if reached_daemon(&result) { + connector.machine_gate().confirm(); + } + result +} + +/// What a session that never sent its hello says about the machine: the relay's exit status +/// and stderr classify it as for a per-connection relay; a timeout is one failed probe. +pub fn handshake_probe(machine: &str, failure: &HandshakeFailure) -> HealthProbe { + if failure.timed_out { + return HealthProbe::Failed { + reason: format!( + "No reply within {} s", + super::mux::HANDSHAKE_TIMEOUT.as_secs() + ), + }; + } + classify_exit(machine, failure.code, &failure.stderr) +} + +/// One `health` on a channel of the machine's session. +async fn probe_channel(client: &pu_transport::mux::MuxClient) -> HealthProbe { + let mut line = serde_json::to_string(&Request::Health).unwrap_or_default(); + line.push('\n'); + let reply = async { + let (read, mut write) = client.open().await.map_err(ChannelProbe::Open)?; + write + .write_all(line.as_bytes()) + .await + .map_err(|_| ChannelProbe::Closed)?; + write.flush().await.map_err(|_| ChannelProbe::Closed)?; + let mut reader = BufReader::new(read); + let mut text = String::new(); + match reader.read_line(&mut text).await { + Ok(0) | Err(_) => Err(ChannelProbe::Closed), + Ok(_) => Ok(text), + } + }; + match tokio::time::timeout(PROBE_TIMEOUT, reply).await { + Ok(Ok(text)) => classify(parse(text.trim_end().as_bytes())), + Ok(Err(ChannelProbe::Open(OpenError::NoDaemon(_)))) => HealthProbe::Stopped, + Ok(Err(ChannelProbe::Open(error))) => HealthProbe::Failed { + reason: relay::open_error(error).to_string(), + }, + Ok(Err(ChannelProbe::Closed)) => HealthProbe::Failed { + reason: "The daemon closed the connection without a reply".into(), + }, + Err(_) => HealthProbe::Failed { + reason: format!("No reply within {} s", PROBE_TIMEOUT.as_secs()), + }, + } +} + +/// Why a probe on a channel got no reply line. +enum ChannelProbe { + Open(OpenError), + Closed, +} + +/// One `health` through its own relay process (a machine without `--mux`). +async fn probe_per_connection(connector: &SshRelayConnector) -> HealthProbe { let (mut child, target) = match connector.spawn(Stdio::piped()).await { Ok(spawned) => spawned, // No ssh, an unknown machine, or the `uname -s` probe could not reach the host. @@ -207,9 +307,6 @@ pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { }, }; let _ = child.start_kill(); - if reached_daemon(&result) { - connector.machine_gate().confirm(); - } result } @@ -217,7 +314,7 @@ pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { pub fn reached_daemon(probe: &HealthProbe) -> bool { matches!( probe, - HealthProbe::Running | HealthProbe::Incompatible { .. } | HealthProbe::Busy + HealthProbe::Running { .. } | HealthProbe::Incompatible { .. } | HealthProbe::Busy ) } @@ -474,6 +571,61 @@ mod tests { const ID: &str = "6f1c2b3a-1111-4222-8333-944455556666"; + #[test] + fn given_failed_handshake_should_classify_like_a_relay_exit() { + // given + let refused = HandshakeFailure { + code: Some(255), + stderr: "kex_exchange_identification: Connection closed by remote host".into(), + timed_out: false, + }; + let missing = HandshakeFailure { + code: Some(127), + stderr: "sh: 1: exec: pu: not found".into(), + timed_out: false, + }; + let slow = HandshakeFailure { + code: None, + stderr: String::new(), + timed_out: true, + }; + + // when / then + assert!(matches!( + handshake_probe("studio", &refused), + HealthProbe::Offline { + cause: SshFailureCause::ServerRefused, + .. + } + )); + assert!(matches!( + handshake_probe("studio", &missing), + HealthProbe::Offline { + cause: SshFailureCause::PuMissing, + .. + } + )); + assert!(matches!( + handshake_probe("studio", &slow), + HealthProbe::Failed { .. } + )); + } + + #[test] + fn given_legacy_relay_should_serialize_the_flag_only_when_set() { + assert_eq!( + serde_json::to_string(&HealthProbe::Running { + legacy_relay: false + }) + .unwrap(), + r#"{"kind":"running"}"# + ); + assert_eq!( + serde_json::to_string(&HealthProbe::Running { legacy_relay: true }).unwrap(), + r#"{"kind":"running","legacyRelay":true}"# + ); + } + #[test] fn given_cli_registry_should_decode() { // MachinesTests.givenCLIRegistryShouldDecode @@ -569,7 +721,12 @@ mod tests { projects: vec![], agent_count: 0, }; - assert_eq!(classify(Ok(report(PROTOCOL_VERSION))), HealthProbe::Running); + assert_eq!( + classify(Ok(report(PROTOCOL_VERSION))), + HealthProbe::Running { + legacy_relay: false + } + ); assert_eq!( classify(Ok(report(2))), HealthProbe::Incompatible { version: 2 } @@ -662,7 +819,9 @@ mod tests { #[test] fn given_probe_verdicts_should_confirm_only_answers_from_the_daemon() { - assert!(reached_daemon(&HealthProbe::Running)); + assert!(reached_daemon(&HealthProbe::Running { + legacy_relay: false + })); assert!(reached_daemon(&HealthProbe::Busy)); assert!(reached_daemon(&HealthProbe::Incompatible { version: 2 })); assert!(!reached_daemon(&HealthProbe::Stopped)); diff --git a/apps/purepoint-windows/src-tauri/src/daemon/mod.rs b/apps/purepoint-windows/src-tauri/src/daemon/mod.rs index 033b50f3..095cc337 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/mod.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/mod.rs @@ -15,6 +15,7 @@ pub mod client; pub mod gate; pub mod lifecycle; pub mod machine; +pub mod mux; pub mod relay; use std::sync::Arc; diff --git a/apps/purepoint-windows/src-tauri/src/daemon/mux.rs b/apps/purepoint-windows/src-tauri/src/daemon/mux.rs new file mode 100644 index 00000000..34863bd7 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/daemon/mux.rs @@ -0,0 +1,478 @@ +//! One multiplexed relay per machine (MACH-013, WINAPP-013a): a long-lived +//! `ssh.exe … pu daemon proxy --mux` whose stdio carries every daemon connection to the +//! machine as a channel ([`pu_transport::mux`]). Without it each connection is its own SSH +//! login, and a network blip makes every stream log in at once, which trips sshd +//! `MaxStartups`, fail2ban and `ufw limit`. +//! +//! - [`registry`] holds one [`MuxSlot`] per machine id, shared by every connector for that +//! machine (the daemon client's and the git host's), so the machine has one `ssh.exe`. +//! - A slot establishes its session on first use, one attempt at a time: callers that arrive +//! while it is logging in wait for that attempt instead of starting their own. +//! - A session that ends (the relay's ping went unanswered, ssh exited, the link dropped) is +//! dropped; the next use establishes a new one. The machine's probe is such a use, so the +//! supervisor is what reconnects, and streams wait at the machine's gate meanwhile (MACH-014). +//! - A machine whose `pu` predates `--mux` (it exits 2 on the unknown flag before writing the +//! hello) is remembered as [`RelayMode::PerConnection`] for [`UNSUPPORTED_RETRY`], and its +//! connections fall back to one `ssh.exe` each (REQ-WINAPP-053). + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use pu_transport::mux::{ClientConfig, HandshakeError, MuxClient}; +use serde::Serialize; +use tokio::io::AsyncReadExt; +use tokio::process::Child; + +use super::client::DaemonError; + +/// How long establishing a session may take: the ssh login plus the relay's hello. +pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(20); +/// How long a machine without `--mux` keeps the per-connection relay before `--mux` is tried +/// again (the user may have upgraded PurePoint there meanwhile). +pub const UNSUPPORTED_RETRY: Duration = Duration::from_secs(600); +/// How much of ssh's stderr a session keeps: enough for its reason to fail. +const STDERR_KEEP: usize = 16 * 1024; +/// How long a relay that failed its handshake gets to report its exit status. +const EXIT_WAIT: Duration = Duration::from_secs(5); +/// How long the stderr reader gets to finish after the relay exited. +const STDERR_WAIT: Duration = Duration::from_millis(500); + +/// How a machine's daemon connections travel, as far as the app knows. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RelayMode { + /// No session has been tried yet. + Unknown, + /// One `ssh.exe` per machine, every connection a channel. + Mux, + /// The machine's `pu` lacks `--mux`: one `ssh.exe` per connection. + PerConnection, +} + +/// A relay that could not complete the handshake. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HandshakeFailure { + /// ssh's exit status, if it exited. + pub code: Option, + /// What it wrote to stderr (the last [`STDERR_KEEP`] bytes). + pub stderr: String, + /// No hello within [`HANDSHAKE_TIMEOUT`]. + pub timed_out: bool, +} + +/// What asking a slot for its session gave. +#[derive(Clone)] +pub enum Session { + /// A live session. + Ready(MuxClient), + /// The machine's `pu` has no `--mux`: use the per-connection relay. + Unsupported, + /// ssh or the relay failed before the hello: the machine is unreachable, `pu` is missing, + /// or the login was refused. Classified by the caller from `code` and `stderr`. + Failed(HandshakeFailure), +} + +/// Whether a relay that never sent its hello is an old `pu` (fall back) rather than a failure. +/// An old `pu` rejects `--mux` as a usage error (clap exits 2, naming the argument); a relay +/// that started but spoke something else (exit 0 or 1 after a non-`PUMUX` line) is no mux +/// either. ssh failing (255), `pu` missing (127, 9009), a kill or a timeout are failures. +pub fn is_unsupported(handshake_said_unsupported: bool, code: Option, stderr: &str) -> bool { + let lower = stderr.to_ascii_lowercase(); + let rejected_flag = lower.contains("--mux") + && (lower.contains("unexpected argument") + || lower.contains("unrecognized") + || lower.contains("found argument")); + match code { + Some(2) => true, + Some(0 | 1) => rejected_flag || handshake_said_unsupported, + _ => false, + } +} + +#[derive(Default)] +struct SlotState { + client: Option, + unsupported_at: Option, +} + +/// One machine's multiplexed session. +#[derive(Default)] +pub struct MuxSlot { + state: Mutex, + /// Held while a session is being established, so only one login runs at a time. + establishing: tokio::sync::Mutex<()>, +} + +impl MuxSlot { + /// How this machine's connections travel now. + pub fn mode(&self) -> RelayMode { + self.mode_at(Instant::now()) + } + + fn mode_at(&self, now: Instant) -> RelayMode { + let state = self.lock(); + if state.client.as_ref().is_some_and(|c| !c.is_closed()) { + RelayMode::Mux + } else if state + .unsupported_at + .is_some_and(|at| now.duration_since(at) < UNSUPPORTED_RETRY) + { + RelayMode::PerConnection + } else if state.unsupported_at.is_some() || state.client.is_some() { + // A session existed (or the fallback expired): the next use tries `--mux` again. + RelayMode::Mux + } else { + RelayMode::Unknown + } + } + + /// End the session and forget what was learned (the machine's host changed). + pub fn reset(&self) { + let client = { + let mut state = self.lock(); + state.unsupported_at = None; + state.client.take() + }; + if let Some(client) = client { + client.close(); + } + } + + /// The live session, or the result of establishing one with `spawn` (which starts + /// `ssh.exe` running the mux relay with stdin, stdout and stderr piped). + pub async fn session(&self, spawn: F) -> Result + where + F: FnOnce() -> Fut, + Fut: std::future::Future>, + { + if let Some(known) = self.known() { + return Ok(known); + } + let _one_at_a_time = self.establishing.lock().await; + // Someone else may have finished establishing while this caller waited. + if let Some(known) = self.known() { + return Ok(known); + } + let child = spawn().await?; + let session = establish(child).await?; + let mut state = self.lock(); + match &session { + Session::Ready(client) => { + state.client = Some(client.clone()); + state.unsupported_at = None; + } + Session::Unsupported => { + state.client = None; + state.unsupported_at = Some(Instant::now()); + } + Session::Failed(_) => state.client = None, + } + Ok(session) + } + + /// A live session, or a recent "unsupported" verdict; `None` when one must be established. + fn known(&self) -> Option { + let mut state = self.lock(); + if let Some(client) = &state.client { + if !client.is_closed() { + return Some(Session::Ready(client.clone())); + } + state.client = None; + } + state + .unsupported_at + .filter(|at| at.elapsed() < UNSUPPORTED_RETRY) + .map(|_| Session::Unsupported) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, SlotState> { + self.state.lock().unwrap_or_else(|p| p.into_inner()) + } +} + +/// Run the handshake over a freshly spawned relay. On success a task owns the `ssh.exe` +/// process from then on: it ends the process when the session ends, and ends the session +/// when the process exits. +async fn establish(mut child: Child) -> Result { + let (Some(stdin), Some(stdout), Some(stderr)) = + (child.stdin.take(), child.stdout.take(), child.stderr.take()) + else { + let _ = child.start_kill(); + return Err(DaemonError::Io("ssh has no stdio".into())); + }; + // ssh's stderr is read for the session's whole life (a pipe nobody reads would block ssh) + // and its tail kept: it is why a session failed. + let tail = Arc::new(Mutex::new(Vec::::new())); + let reader_tail = Arc::clone(&tail); + let stderr_task = tokio::spawn(async move { + let mut stderr = stderr; + let mut chunk = [0u8; 4096]; + loop { + match stderr.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + let mut tail = reader_tail.lock().unwrap_or_else(|p| p.into_inner()); + tail.extend_from_slice(&chunk[..n]); + let excess = tail.len().saturating_sub(STDERR_KEEP); + tail.drain(..excess); + } + } + } + }); + let handshake = tokio::time::timeout( + HANDSHAKE_TIMEOUT, + MuxClient::handshake(stdout, stdin, ClientConfig::default()), + ) + .await; + let (said_unsupported, timed_out) = match handshake { + Ok(Ok(client)) => { + supervise(child, client.clone()); + return Ok(Session::Ready(client)); + } + Ok(Err(HandshakeError::Unsupported(_))) => (true, false), + Ok(Err(HandshakeError::Io(_))) => (false, false), + Err(_) => { + let _ = child.start_kill(); + (false, true) + } + }; + let code = match tokio::time::timeout(EXIT_WAIT, child.wait()).await { + Ok(Ok(status)) => status.code(), + _ => { + let _ = child.start_kill(); + None + } + }; + let _ = tokio::time::timeout(STDERR_WAIT, stderr_task).await; + let stderr = { + let tail = tail.lock().unwrap_or_else(|p| p.into_inner()); + String::from_utf8_lossy(&tail).into_owned() + }; + if !timed_out && is_unsupported(said_unsupported, code, &stderr) { + return Ok(Session::Unsupported); + } + Ok(Session::Failed(HandshakeFailure { + code, + stderr, + timed_out, + })) +} + +/// Tie the session's life to the `ssh.exe` that carries it. +fn supervise(mut child: Child, client: MuxClient) { + tokio::spawn(async move { + tokio::select! { + _ = client.closed() => { + let _ = child.start_kill(); + } + _ = child.wait() => { + client.close(); + } + } + // Reap it either way. + let _ = child.wait().await; + }); +} + +/// Every machine's slot, by lowercased machine id. +#[derive(Default)] +pub struct MuxSlots { + slots: Mutex>>, +} + +impl MuxSlots { + /// The slot for `machine_id`, created on first use. + pub fn slot(&self, machine_id: &str) -> Arc { + let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner()); + Arc::clone(slots.entry(machine_id.to_ascii_lowercase()).or_default()) + } +} + +/// The process-wide slots. +pub fn registry() -> &'static MuxSlots { + static SLOTS: OnceLock = OnceLock::new(); + SLOTS.get_or_init(MuxSlots::default) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_old_pu_usage_error_should_fall_back() { + // given: clap's reply to an unknown flag + let stderr = + "error: unexpected argument '--mux' found\n\nUsage: pu daemon proxy [OPTIONS]\n"; + + // when / then + assert!(is_unsupported(true, Some(2), stderr)); + assert!(is_unsupported(true, Some(2), "")); + assert!(is_unsupported(false, Some(1), stderr)); + } + + #[test] + fn given_relay_speaking_something_else_should_fall_back() { + assert!(is_unsupported(true, Some(0), "")); + assert!(is_unsupported( + true, + Some(1), + "pu daemon proxy --mux: unsupported version" + )); + } + + #[test] + fn given_ssh_or_pu_failures_should_not_fall_back() { + // given: ssh failing, `pu` missing, a kill + let cases = [ + ( + Some(255), + "ssh: connect to host studio port 22: Connection timed out", + ), + ( + Some(255), + "kex_exchange_identification: Connection closed by remote host", + ), + (Some(127), "sh: 1: exec: pu: not found"), + ( + Some(9009), + "'pu' is not recognized as an internal or external command", + ), + (Some(69), "error: cannot connect to the daemon"), + (None, ""), + ]; + + // when / then + for (code, stderr) in cases { + assert!(!is_unsupported(true, code, stderr), "{code:?} {stderr}"); + } + } + + #[test] + fn given_fresh_slot_should_report_unknown_mode() { + assert_eq!(MuxSlot::default().mode(), RelayMode::Unknown); + } + + #[test] + fn given_unsupported_verdict_should_report_per_connection_until_it_expires() { + // given + let slot = MuxSlot::default(); + let then = Instant::now(); + slot.lock().unsupported_at = Some(then); + + // when / then + assert_eq!(slot.mode_at(then), RelayMode::PerConnection); + assert!(matches!(slot.known(), Some(Session::Unsupported))); + assert_eq!( + slot.mode_at(then + UNSUPPORTED_RETRY + Duration::from_secs(1)), + RelayMode::Mux + ); + } + + #[test] + fn given_reset_should_forget_the_fallback() { + // given + let slot = MuxSlot::default(); + slot.lock().unsupported_at = Some(Instant::now()); + + // when + slot.reset(); + + // then + assert_eq!(slot.mode(), RelayMode::Unknown); + assert!(slot.known().is_none()); + } + + /// A child with every stdio piped, running `cmd /C