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/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..6fc78576 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/MachineConnection+iOS.swift @@ -31,6 +31,8 @@ actor MachineConnection { private var generation = 0 private var tracker = HealthProbeTracker() private var timeouts = ProbeTimeoutPolicy() + /// A connect attempt is running; a nudge then lets it finish instead of starting another. + private var connectInFlight = false private let probeDeadline: TimeInterval init( @@ -106,6 +108,27 @@ 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; one that is + /// connecting keeps its attempt (only the backoff after it is reset), so a nudge never + /// abandons a login halfway. 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 if !connectInFlight { + 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 +198,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 @@ -184,17 +218,19 @@ actor MachineConnection { } if !(await session.isConnected) { report(.connecting) } do { + connectInFlight = true + defer { connectInFlight = false } try await session.connect() } catch let refusal as SSHTrustError { 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 +239,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 +263,7 @@ actor MachineConnection { } } guard isCurrent(generation) else { return } - report(.offline("SSH connection closed")) + report(.offline("SSH connection closed", cause: .network)) } } @@ -222,7 +271,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 +307,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 +322,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 +346,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 +354,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 +426,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/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..178af155 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. @@ -14,10 +16,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,12 +33,16 @@ 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::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; @@ -41,13 +52,26 @@ 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). #[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, }, @@ -56,9 +80,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 { @@ -71,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 { @@ -89,20 +118,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 { @@ -116,12 +165,96 @@ pub fn classify_exit(machine: &str, code: Option, stderr: Option) - } } -/// 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(true).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. - 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,8 +299,8 @@ 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()), @@ -177,6 +310,14 @@ pub async fn probe(connector: &SshRelayConnector) -> HealthProbe { 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 +535,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( @@ -423,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 @@ -518,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 } @@ -542,35 +750,85 @@ 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 { + legacy_relay: false + })); + 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 +839,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..095cc337 100644 --- a/apps/purepoint-windows/src-tauri/src/daemon/mod.rs +++ b/apps/purepoint-windows/src-tauri/src/daemon/mod.rs @@ -5,14 +5,17 @@ //! - `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 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..ed657026 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/daemon/mux.rs @@ -0,0 +1,924 @@ +//! 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 slot is for one SSH target: asked for a session to another host (the machine's +//! `ssh_host` was edited), it ends the session it has and forgets what it learned, and an +//! attempt still logging in to the old host is discarded when it finishes (MACH-013). +//! - 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, + // An early exit is an old `pu` only when it rejected the flag; a relay that started and + // printed something other than the hello is one too. A shell that could not run `pu` + // at all (PowerShell exits 1, "not recognized") is a failure the user must see. + Some(0 | 1) => { + rejected_flag || (handshake_said_unsupported && !stderr_says_missing(&lower)) + } + _ => false, + } +} + +/// How long a failed attempt answers `open` callers that arrive after it, instead of each of +/// them logging in again; the supervisor's probe (`fresh`) ignores it. +pub const FAILURE_HOLD: Duration = Duration::from_secs(5); + +/// The outcome of one attempt, shared by every caller that waited for it. +type Outcome = Result; + +/// What waiters of an attempt get once the slot was invalidated under it. +fn stale_attempt() -> DaemonError { + DaemonError::NotRunning("The machine's SSH host changed while connecting; try again".into()) +} + +/// stderr of a shell that found no `pu` to run. +fn stderr_says_missing(lower: &str) -> bool { + lower.contains("not recognized") + || lower.contains("not found") + || lower.contains("no such file") +} + +#[derive(Default)] +struct SlotState { + client: Option, + unsupported_at: Option, + /// The last failed attempt and when it ended. + failure: Option<(Instant, Outcome)>, + /// The attempt in progress, if any: every caller waits on it. + pending: Option>>, + /// The SSH target everything above was learned from. + host: Option, + /// Bumped whenever what the slot knows is thrown away: an attempt that began under an + /// older generation is stale, and its outcome is neither stored nor handed out. + generation: u64, +} + +impl SlotState { + /// Forget the session, the verdicts and the attempt in progress; the session to close. + fn invalidate(&mut self) -> Option { + self.generation += 1; + self.pending = None; + self.unsupported_at = None; + self.failure = None; + self.client.take() + } +} + +/// One machine's multiplexed session. +#[derive(Default)] +pub struct MuxSlot { + state: 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 was removed). An attempt in + /// progress is discarded when it finishes. + pub fn reset(&self) { + let client = { + let mut state = self.lock(); + state.host = None; + state.invalidate() + }; + if let Some(client) = client { + client.close(); + } + } + + /// The live session to `host`, or the outcome of establishing one with `spawn` (which + /// starts `ssh.exe` to `host` running the mux relay with stdin, stdout and stderr piped). + /// + /// A slot whose session (or attempt, or verdict) is for another host forgets it first: the + /// machine's `ssh_host` changed, and nothing learned from the old host applies. + /// + /// The attempt runs on its own task, so a caller that stops waiting (a connect timeout) + /// does not kill an ssh login halfway: the login finishes and the next caller finds its + /// session. Callers that arrive while an attempt runs wait for that attempt and share its + /// outcome. Unless `fresh`, a failed attempt also answers callers for [`FAILURE_HOLD`] + /// after it ended, so a burst of opens behind a refused login makes no logins of its own. + pub async fn session(self: &Arc, host: &str, fresh: bool, spawn: F) -> Outcome + where + F: FnOnce() -> Fut + Send + 'static, + Fut: std::future::Future> + Send + 'static, + { + self.session_with(host, fresh, async move { + match spawn().await { + Ok(child) => establish(child).await, + Err(error) => Err(error), + } + }) + .await + } + + /// [`session`](Self::session) with the attempt as a future (tests supply their own). + async fn session_with(self: &Arc, host: &str, fresh: bool, attempt: A) -> Outcome + where + A: std::future::Future + Send + 'static, + { + let mut stale = None; + let generation; + let pending = { + let mut state = self.lock(); + if state.host.as_deref() != Some(host) { + stale = state.invalidate(); + state.host = Some(host.to_owned()); + } + generation = state.generation; + match Self::known(&mut state, fresh, Instant::now()) { + Some(known) => Err(known), + None => Ok(match &state.pending { + Some(pending) => pending.clone(), + None => { + let (done, pending) = tokio::sync::watch::channel(None); + state.pending = Some(pending.clone()); + let slot = Arc::clone(self); + tokio::spawn(async move { + let outcome = slot.record(generation, attempt.await); + let _ = done.send(Some(outcome)); + }); + pending + } + }), + } + }; + if let Some(client) = stale { + client.close(); + } + let mut pending = match pending { + Ok(pending) => pending, + Err(known) => return known, + }; + loop { + if let Some(outcome) = pending.borrow_and_update().clone() { + // The slot may have been reset (or its host changed) after the attempt stored + // its outcome but before this waiter took it: that outcome is for what the slot + // no longer is, and a session in it was closed by the invalidation. + if self.lock().generation != generation { + return Err(stale_attempt()); + } + return outcome; + } + if pending.changed().await.is_err() { + // The attempt's task ended without an outcome (the runtime is shutting down). + return Err(DaemonError::Io( + "The SSH session attempt was abandoned".into(), + )); + } + } + } + + /// Store the outcome of the attempt begun under `generation` and end the attempt; returns + /// what its waiters get. A stale attempt (the slot was reset or its host changed meanwhile) + /// stores nothing, and its session is closed rather than handed out: it is to the old host. + fn record(&self, generation: u64, outcome: Outcome) -> Outcome { + let mut state = self.lock(); + if state.generation != generation { + drop(state); + if let Ok(Session::Ready(client)) = &outcome { + client.close(); + } + return Err(stale_attempt()); + } + state.pending = None; + match &outcome { + Ok(Session::Ready(client)) => { + state.client = Some(client.clone()); + state.unsupported_at = None; + state.failure = None; + } + Ok(Session::Unsupported) => { + state.client = None; + state.unsupported_at = Some(Instant::now()); + state.failure = None; + } + Ok(Session::Failed(_)) | Err(_) => { + state.client = None; + state.failure = Some((Instant::now(), outcome.clone())); + } + } + outcome + } + + /// A live session, a recent "unsupported" verdict or (unless `fresh`) a recent failure; + /// `None` when an attempt must be made. + fn known(state: &mut SlotState, fresh: bool, now: Instant) -> Option { + if let Some(client) = &state.client { + if !client.is_closed() { + return Some(Ok(Session::Ready(client.clone()))); + } + state.client = None; + } + if state + .unsupported_at + .is_some_and(|at| now.duration_since(at) < UNSUPPORTED_RETRY) + { + return Some(Ok(Session::Unsupported)); + } + if !fresh + && let Some((at, outcome)) = &state.failure + && now.duration_since(*at) < FAILURE_HOLD + { + return Some(outcome.clone()); + } + None + } + + 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) -> Outcome { + 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::*; + + const HOST: &str = "studio-mac"; + + #[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 = Arc::new(MuxSlot::default()); + let then = Instant::now(); + slot.lock().unsupported_at = Some(then); + + // when / then + assert_eq!(slot.mode_at(then), RelayMode::PerConnection); + assert!(matches!( + MuxSlot::known(&mut slot.lock(), false, Instant::now()), + Some(Ok(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 = Arc::new(MuxSlot::default()); + slot.lock().unsupported_at = Some(Instant::now()); + + // when + slot.reset(); + + // then + assert_eq!(slot.mode(), RelayMode::Unknown); + assert!(MuxSlot::known(&mut slot.lock(), false, Instant::now()).is_none()); + } + + /// A child with every stdio piped, running `cmd /C