From 44ce930a75ddba3cd611f1646fd9e904cc7f7d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 14:52:06 +0100 Subject: [PATCH 1/6] feat(remote): the control executor on the target, and the viewer's controls A paired machine can now start, stop and restart a service on a target that allows it (PR 4c-2 of docs/remote-machines.md), through whoever owns the service there. Target: `control` and `control.status` in the remote actor. Checks 1 to 3 (pin and hello, share and control, a fresh lease) run in the actor; the executor in infrastructure/remote/control.rs runs 4 to 9 off it: request entries in services/requests//.json, published before anything changes and kept 24 h, with request_mismatch for another fingerprint; expiry, ids and profile, one control per service (busy), the state and configRev, then the owner. Who acts follows the contract's table: the app's bridge, a detached `localify dev ... --detach` started from the daemon's own canonical executable with the shell environment, or a refusal. A launch is followed to its record (dispatched, started, settled within 90 s); an unanswered bridge launch waits for its expiry and is reported from the record, never started again elsewhere. Legacy relaunch: the inventory names a proven legacy run of the app or of `dev --detach` with `legacyId`, and a restart with `expect.legacyId` relaunches it through its owner. `localify dev --replace-legacy` refuses under the run lock unless the record still names that legacy run, and the app bridge passes `replacesLegacy` on instead of refusing it. The inventory's controls now follow the switches and the app's presence, so a granted access request shows in the next snapshot. Viewer: `remote_control` streams sent, progress and the result, waits 120 s, and after a lost session reports unknown and asks control.status on a new session, never resending. The desktop DTO and its TypeScript mirror carry the stream; no screen uses it until PR 4d. --- desktop-ui/src/lib/util.remote.test.ts | 1 + desktop-ui/src/types/localify.ts | 46 +- docs/remote-machines.md | 12 +- src/application/inventory.rs | 90 +- src/cli/background.rs | 46 +- src/cli/services.rs | 16 +- src/daemon/mgmt_socket.rs | 44 +- src/daemon/remote/actor.rs | 75 +- src/daemon/remote/actor/control.rs | 208 +++++ src/daemon/remote/actor/target.rs | 20 +- src/daemon/remote/actor/viewer.rs | 71 +- src/daemon/remote/fake_relay.rs | 388 ++++++++- src/daemon/remote/local.rs | 123 ++- src/daemon/remote/mod.rs | 22 +- src/daemon/remote/tests.rs | 3 + src/daemon/remote/tests/access.rs | 59 ++ src/daemon/remote/tests/control.rs | 726 ++++++++++++++++ src/daemon/remote/viewing.rs | 240 ++++- src/desktop/app_bridge.rs | 43 +- src/desktop/dto.rs | 43 + src/desktop/remote.rs | 14 + src/desktop/run_pty.rs | 11 + src/infrastructure/app_bridge.rs | 4 +- src/infrastructure/inventory.rs | 140 ++- src/infrastructure/remote/control.rs | 1110 ++++++++++++++++++++++++ src/infrastructure/remote/mod.rs | 5 +- src/infrastructure/remote/requests.rs | 481 ++++++++++ src/infrastructure/remote/wire.rs | 297 ++++++- src/infrastructure/running_services.rs | 59 +- src/infrastructure/runs/output.rs | 41 + src/main.rs | 21 +- tests/remote_controls.rs | 524 +++++++++++ 32 files changed, 4858 insertions(+), 125 deletions(-) create mode 100644 src/daemon/remote/actor/control.rs create mode 100644 src/daemon/remote/tests/control.rs create mode 100644 src/infrastructure/remote/control.rs create mode 100644 src/infrastructure/remote/requests.rs create mode 100644 tests/remote_controls.rs diff --git a/desktop-ui/src/lib/util.remote.test.ts b/desktop-ui/src/lib/util.remote.test.ts index 7651f80..c7bc724 100644 --- a/desktop-ui/src/lib/util.remote.test.ts +++ b/desktop-ui/src/lib/util.remote.test.ts @@ -30,6 +30,7 @@ function status(overrides: Partial = {}): RemoteStatusDto { retryAt: null, settings: { share: false, control: false, backgroundStarts: false }, fingerprint: "1a2b 3c4d 5e6f 7a8b", + shellEnvironmentError: null, ...overrides, }; } diff --git a/desktop-ui/src/types/localify.ts b/desktop-ui/src/types/localify.ts index c9cb3da..18faa9c 100644 --- a/desktop-ui/src/types/localify.ts +++ b/desktop-ui/src/types/localify.ts @@ -1144,6 +1144,8 @@ export interface RemoteStatusDto { settings: RemoteSettingsDto; /** This machine's key, as four groups of four hex digits. */ fingerprint: string | null; + /** Why background starts run without the user's shell environment. */ + shellEnvironmentError: string | null; } export type RemoteMachineState = @@ -1205,7 +1207,47 @@ export type RemoteStreamRequest = | { kind: "pair"; machineId: string } | { kind: "watch"; machineId: string } | { kind: "follow"; machineId: string; runId: string; offset: number | null } - | { kind: "access"; machineId: string; wants: RemoteAccessWants }; + | { kind: "access"; machineId: string; wants: RemoteAccessWants } + /** Unused by the window until PR 4d adds the buttons. */ + | ({ kind: "control"; machineId: string } & RemoteControlRequest); + +/** + * A control, as the snapshot showed the service when the person clicked. + * Unused by the window until PR 4d. + */ +export interface RemoteControlRequest { + action: RemoteControlAction; + service: { projectId: string; environment: string | null; serviceId: string }; + /** Start only. Null: the effective default profile. */ + profile: string | null; + expect: { runId: string | null; configRev: string; legacyId?: string }; +} + +export type RemoteControlOutcome = + | "done" + | "starting" + | "refused" + | "conflict" + | "failed" + | "unknown"; + +/** + * What `remote_control` streams: `sent`, its progress, then its result. A + * lost session is `unknown`, followed by the result `control.status` gives, + * or `lost`. Unused by the window until PR 4d. + */ +export type RemoteControlEventDto = + | { event: "sent"; requestId: string } + | { event: "progress"; phase: "dispatched" | "started" } + | { + event: "result"; + outcome: RemoteControlOutcome; + code: string | null; + message: string; + runId: string | null; + } + | { event: "unknown"; code: string; message: string } + | { event: "lost"; code: string; message: string }; /** One line of a stream, or its end. */ export interface RemoteStreamPayload { @@ -1299,6 +1341,8 @@ export interface RemoteInventoryItemDto { startedAt: string; profile: string | null; profileDanger: boolean; + /** A legacy run whose PID is proven: what a relaunch names. */ + legacyId?: string; exit: { at: string; code: number | null } | null; } | null; process: "running" | "stopped"; diff --git a/docs/remote-machines.md b/docs/remote-machines.md index 8d5a555..ad13c79 100644 --- a/docs/remote-machines.md +++ b/docs/remote-machines.md @@ -559,7 +559,7 @@ From a record, a reconciler reports exactly one of: admitted and starting; admit ### Request entries -Every control from a peer leaves a request entry, `services/requests//.json`, published like a launch record before the target takes any step that changes something: before a dispatch, a plain stop, or the stop phase of a restart. It holds an immutable fingerprint of the control (its action, project, environment, service, profile and expected run and revision), and then links every outcome as it happens: the launch it dispatched (admitted, refused, expired, exited), and `stopped: {runId, at}` for a stop. Updates go through a temporary file renamed over the entry and never change the fingerprint. Entries are kept for 24 hours, so a stop's correlation survives a daemon restart as a start's does. +Every control from a peer leaves a request entry, `services/requests//.json`, published like a launch record before the target takes any step that changes something: before a dispatch, a plain stop, or the stop phase of a restart. It holds an immutable fingerprint of the control (its action, project, environment, service, profile and expected run and revision), and then links every outcome as it happens: the launch it dispatched (admitted, refused, expired, exited), and `stopped: {runId, at}` for a stop. Updates go through a temporary file renamed over the entry and never change the fingerprint. Entries are kept for 24 hours, so a stop's correlation survives a daemon restart as a start's does. Before it links a launch, the entry of a control the target still works on (a stop, or a restart's stop) reports `unknown`; one a daemon restart left with no outcome and no launch reports `failed`, and the viewer looks at the fresh snapshot. ### Target checks @@ -618,7 +618,7 @@ The desktop app listens on `/app-bridge/app-bridge.sock`, a Unix socke | `{"cmd": "launch", "launchId", "expiresAt", "service": {projectId, environment, serviceId}, "profile", "expectRev", "replaces", "replacesLegacy", "requestedBy": {machineId, name, requestId}}` | `{"ok": true, "data": {"accepted": true}}` once the run PTY is spawned, within 5 s | -`replaces` is the run id whose tab the new run takes, or `null` for a new tab; its dispatcher stopped that run first, and the app passes it to the executor as `--replace=`, so the new launch records that it replaced it (`replacedBy`) and starts nothing when someone else restarted the service in between. `replacesLegacy`, optional, is the `legacyId` of a relaunch: the app passes it to the executor as `--replace-legacy` and opens a new tab. Until PR 4c-2 adds `--replace-legacy` to the executor, the app refuses a non-null `replacesLegacy` with `unsupported`. `requestedBy` and `expectRev` are both set for a remote launch and both `null` for one of this machine's own, such as `localify dev --in-app`, which the app runs with `--launch-id`. The app refuses before it spawns anything, and only then: `bad_request` for a malformed request, an unknown field included, or an expiry more than 60 seconds ahead; `expired` once `expiresAt` has passed; `unknown_service` when the ids name nothing here; `unsupported` as above. Whatever stops the spawn itself is `conflict`, with its message. A dispatcher whose launch got no answer within 5 seconds, or lost the connection first, never sends it again and starts nothing in its place: it waits until the launch has expired, creates the `expired` record if none exists, and reports from the record (see "Reconciling"). Access requests do not use the bridge: they reach the app on `remote_events` (see "Asking for access"). The app spawns `localify dev` with `--remote-launch`, `--launch-expires`, `--expect-rev` and `--request` from the request, with the resolved shell environment, so the executor fences it and records who asked. Errors are `{"ok": false, "error": {"code", "message"}}`, with the codes of "Errors". The app opens the tab without taking focus and shows "Started by A" for 5 seconds. Stops need no bridge: the target signals the run itself, and the tab shows the exit. The app's own launch button and `dev --detach` pass launch ids the same way, and so does the app's restart, with `--replace=` for the run it stopped. `localify dev --in-app` uses the bridge when the app answers, keeping the deep link only to open an app that is not running (`localify://open/projects`), after which it waits up to 30 seconds for the bridge to answer and launches through it. Where the bridge is unavailable, it sends `localify://action/launch-service` as before the bridge, and waits for the run the app records. +`replaces` is the run id whose tab the new run takes, or `null` for a new tab; its dispatcher stopped that run first, and the app passes it to the executor as `--replace=`, so the new launch records that it replaced it (`replacedBy`) and starts nothing when someone else restarted the service in between. `replacesLegacy`, optional, is the `legacyId` of a relaunch, never sent with `replaces`: the app passes it to the executor as `--replace-legacy` and opens a new tab. `requestedBy` and `expectRev` are both set for a remote launch and both `null` for one of this machine's own, such as `localify dev --in-app`, which the app runs with `--launch-id`. The app refuses before it spawns anything, and only then: `bad_request` for a malformed request, an unknown field included, or an expiry more than 60 seconds ahead; `expired` once `expiresAt` has passed; `unknown_service` when the ids name nothing here. Whatever stops the spawn itself is `conflict`, with its message. A dispatcher whose launch got no answer within 5 seconds, or lost the connection first, never sends it again and starts nothing in its place: it waits until the launch has expired, creates the `expired` record if none exists, and reports from the record (see "Reconciling"). Access requests do not use the bridge: they reach the app on `remote_events` (see "Asking for access"). The app spawns `localify dev` with `--remote-launch`, `--launch-expires`, `--expect-rev` and `--request` from the request, with the resolved shell environment, so the executor fences it and records who asked. Errors are `{"ok": false, "error": {"code", "message"}}`, with the codes of "Errors". The app opens the tab without taking focus and shows "Started by A" for 5 seconds. Stops need no bridge: the target signals the run itself, and the tab shows the exit. The app's own launch button and `dev --detach` pass launch ids the same way, and so does the app's restart, with `--replace=` for the run it stopped. `localify dev --in-app` uses the bridge when the app answers, keeping the deep link only to open an app that is not running (`localify://open/projects`), after which it waits up to 30 seconds for the bridge to answer and launches through it. Where the bridge is unavailable, it sends `localify://action/launch-service` as before the bridge, and waits for the run the app records. ### State machine @@ -737,7 +737,7 @@ New management socket commands. The streaming ones keep the connection open and | Command | Answer | |---|---| -| `remote_status` | `{relay: "off" \| "connecting" \| "connected" \| "reconnecting" \| "blocked", blocked: {code, message} \| null, retryAt, settings, fingerprint}` | +| `remote_status` | `{relay: "off" \| "connecting" \| "connected" \| "reconnecting" \| "blocked", blocked: {code, message} \| null, retryAt, settings, fingerprint, shellEnvironmentError}`; `shellEnvironmentError` says why background starts run with the daemon's own environment, `null` otherwise | | `remote_machines` | the roster merged with pins, presence and sessions: `[{id, name, self, paired, state, version, fingerprint, proto}]`, `state` as in "Desktop app"; `proto` is the session version agreed from the authenticated `hello`s of the open session, `null` with no session | | `remote_settings {share?, control?, backgroundStarts?}` | the settings after the change | | `remote_pair {machineId}` | streaming: `code`, then `paired` or `cancelled` | @@ -747,14 +747,14 @@ New management socket commands. The streaming ones keep the connection open and | `remote_watch {machineId}` | streaming: `{event: "connecting"}`, `{event: "snapshot", machine, epoch, rev, truncated, items}` with every page of a revision, and `{event: "lost", code, message, retryIn}`, after which the daemon asks again by itself | | `remote_output_read {machineId, runId, offset, maxBytes}` | one `output.data` | | `remote_output_follow {machineId, runId, offset?, tail?}` | streaming `{event: "data", …output.data}`; the daemon acknowledges as the client reads. Without `offset`, from the last `tail` bytes (256 KiB by default). `{event: "ended", code, message}` when the follow stops before its run did: `gone` for a restart, a refusal, or a lost session | -| `remote_control {machineId, action, service, profile, expect}` | streaming: progress, then the result; the client waits up to 120 s, not the usual 2 | +| `remote_control {machineId, action, service, profile, expect}` | streaming: `{event: "sent", requestId}`, `{event: "progress", phase}`, then `{event: "result", outcome, code, message, runId}`; the client waits up to 120 s, not the usual 2. A session lost first, or no result in 120 s, gives `{event: "unknown", code, message}`, then the result `control.status` gives on a new session, or `{event: "lost", code, message}` when it cannot be had; the control is never sent again | | `remote_access {machineId, wants}` | viewer side, streaming: `{event: "waiting"}`, then `{event: "result", outcome}` with the outcomes of `access.result`, `{event: "error", code, message, retryAfter?}` for `not_shared`, `busy`, `too_many` or `unsupported`, or `{event: "lost"}` when the session ended first; closing the stream sends `access.cancel` | | `remote_access_suppressed` | target side: `[{machineId, name, since}]`, the peers whose requests are suppressed | | `remote_access_restore {machineId}` | target side: lets that peer ask again; `{ok}` | | `remote_access_answer {requestId, allow, suppress}` | target side, from the app's dialog: `{outcome}`, `granted` only when the request was still waiting and the settings unchanged (see "Asking for access") | | `remote_events {access?}` | streaming: pairing requests, access requests (`access_request {requestId, machineId, name, fingerprint, wants, expiresAt}`) and their end (`access_closed {requestId}`), presence, revocations; the app subscribes while it runs. Access events go only to a client subscribed with `access: true`, one that shows the access dialog, and "no app is subscribed" in "Asking for access" means none of those: until PR 4d, the app subscribes without it, so requests get `nobody` | -One local command serves this machine's own inventory: `inventory {have?}` answers the snapshot the relay will page (`schema`, `epoch`, `rev`, `pages`, `truncated`, `items`), or `{unchanged: true, epoch, rev}` when `have` names its revision. One snapshot is built at a time; a request that arrives during a build shares its result. Until PR 4c, every switch counts as off for `controls` and the app as absent there, so each control is refused with `control_disabled`, whatever `control` says; the inventory pages' `machine.settings` show the switches as set, and since PR 4b `machine.app`, like `app` in a target's `hello`, says whether the app's bridge answered the daemon's last `hello`, asked every 2 seconds. The local `inventory` command's `rev` counts its items only; the relay pages carry the revision of "Epoch and revision", which the summary moves too. The hidden `localify inventory [--have :]` prints it, for tests. +One local command serves this machine's own inventory: `inventory {have?}` answers the snapshot the relay will page (`schema`, `epoch`, `rev`, `pages`, `truncated`, `items`), or `{unchanged: true, epoch, rev}` when `have` names its revision. One snapshot is built at a time; a request that arrives during a build shares its result. Its `controls` follow the switches and the app as the relay pages do: `machine.app`, like `app` in a target's `hello`, says whether the app's bridge answered the daemon's last `hello`, asked every 2 seconds. The local `inventory` command's `rev` counts its items only; the relay pages carry the revision of "Epoch and revision", which the summary moves too. The hidden `localify inventory [--have :]` prints it, for tests. The daemon opens a session only when one of these asks for it, carries every request to one target over its one session, and closes it when the last one ends. `remote_machines` without a probe reads the roster from Localify Cloud at most every 30 seconds, so the app can poll it; a probe, a pairing, presence of a machine it does not know and a revocation read it at once. `public_refresh` also re-reads `/v1/me` for `remoteAccess`, so subscribing turns remote access on without a restart. @@ -808,7 +808,7 @@ localify restart --machine [--project ] [--env ] - **Resolving `--machine`:** an exact machine id; otherwise an exact name, ignoring case, among the active machines of the roster. Active names are unique, since a same-name sign-in replaces the older machine; a name that still matches two, differing only in case, is an error that lists both with their ids. A name of no active machine lists the roster. This machine's own id or name acts locally, as without `--machine`. - **Resolving a service:** there is no folder to read on another machine, so a service name must be unique on the target, or come with `--project`, and `--env` names a non-primary checkout. An ambiguous name lists the matches. - **What `--machine` refuses:** with `dev`, every option but `--project`, `--env` and `--profile`: no command after `--`, no `--detach`, `--in-app`, `--env-file`, `--confirm-profile` or `--domain`. The target decides where the service runs. -- **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev` and `--request` are hidden flags for dispatchers, documented here and not in `--help`. +- **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev`, `--request` and `--replace-legacy` are hidden flags for dispatchers, documented here and not in `--help`. - **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; `unknown` prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2. - `pair` and `remove` need a terminal: an agent cannot pair or remove machines. diff --git a/src/application/inventory.rs b/src/application/inventory.rs index a212af9..3bce195 100644 --- a/src/application/inventory.rs +++ b/src/application/inventory.rs @@ -75,6 +75,9 @@ pub struct RunFacts { pub profile: Option, pub profile_danger: bool, pub exit: Option, + /// A legacy run of the app or of `dev --detach` whose PID is proven: + /// `..`, what a relaunch names. + pub legacy_id: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -134,12 +137,20 @@ pub struct TargetSettings { pub background_starts: bool, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum AppPresence { Running, + #[default] Absent, } +/// What decides the controls of every service of the machine. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Switches { + pub settings: TargetSettings, + pub app: AppPresence, +} + /// What holds for every service of the machine. #[derive(Debug, Clone, Copy)] pub struct Context { @@ -190,6 +201,9 @@ pub struct RunView { pub started_at: String, pub profile: Option, pub profile_danger: bool, + /// A legacy run whose PID is proven: what a relaunch names. + #[serde(skip_serializing_if = "Option::is_none")] + pub legacy_id: Option, pub exit: Option, } @@ -289,7 +303,7 @@ pub struct Control { } impl Control { - const ALLOWED: Self = Self { + pub const ALLOWED: Self = Self { allowed: true, code: None, }; @@ -316,6 +330,21 @@ pub enum Refusal { Conflict, } +impl Refusal { + /// The code a refusal carries on the wire. + pub fn code(self) -> &'static str { + match self { + Self::ControlDisabled => "control_disabled", + Self::BackgroundDisabled => "background_disabled", + Self::NotOwned => "not_owned", + Self::LegacyRun => "legacy_run", + Self::OwnerGone => "owner_gone", + Self::RefusedProfile => "refused_profile", + Self::Conflict => "conflict", + } + } +} + /// One service's item. Each state is computed from its own source only. pub fn inventory_item(facts: ServiceFacts, context: &Context) -> InventoryItem { let process = process_state(facts.run.as_ref()); @@ -333,6 +362,7 @@ pub fn inventory_item(facts: ServiceFacts, context: &Context) -> InventoryItem { started_at: run.started_at, profile: run.profile, profile_danger: run.profile_danger, + legacy_id: run.legacy_id, exit: run.exit, }), project: facts.project, @@ -421,9 +451,22 @@ fn controls(facts: &ServiceFacts, owner: Option, context: &Context) -> Co let legacy_alive = facts .run .as_ref() - .is_some_and(|run| run.legacy && run.process != RunProcess::Stopped); - if legacy_alive { - return Controls::all(Control::refused(Refusal::LegacyRun)); + .filter(|run| run.legacy && run.process != RunProcess::Stopped); + if let Some(run) = legacy_alive { + // A proven legacy run of the app or of `dev --detach` is relaunched + // by a restart, under the checks of any restart. + let legacy = Control::refused(Refusal::LegacyRun); + let restart = match (&run.legacy_id, owner) { + (Some(_), Some(owner @ (Owner::App | Owner::Background))) => { + restart_control(owner, facts.profiles, context) + } + _ => legacy, + }; + return Controls { + start: legacy, + stop: legacy, + restart, + }; } let conflict = Control::refused(Refusal::Conflict); match owner { @@ -648,6 +691,7 @@ mod tests { profile: None, profile_danger: false, exit: None, + legacy_id: None, } } @@ -828,6 +872,42 @@ mod tests { assert_eq!(unproven.owner, Some(Owner::Unknown)); } + #[test] + fn a_proven_legacy_run_of_the_app_or_the_background_is_relaunched_by_a_restart() { + for origin in [RunOrigin::App, RunOrigin::Background] { + let proven = RunFacts { + legacy_id: Some("boot.42.7".into()), + origin, + ..legacy(RunProcess::Running) + }; + let item = item(with(Some(proven.clone()), true)); + assert_eq!(item.controls.restart, Control::ALLOWED, "{origin:?}"); + assert_eq!(item.controls.start, refused(Refusal::LegacyRun)); + assert_eq!(item.controls.stop, refused(Refusal::LegacyRun)); + assert_eq!(item.run.unwrap().legacy_id.as_deref(), Some("boot.42.7")); + + // The checks of any restart: the owner, and background starts. + let mut closed = Context { + app: AppPresence::Absent, + ..open() + }; + closed.settings.background_starts = false; + let expected = match origin { + RunOrigin::App => Refusal::OwnerGone, + _ => Refusal::BackgroundDisabled, + }; + let item = inventory_item(with(Some(proven), true), &closed); + assert_eq!(item.controls.restart, refused(expected)); + } + let in_a_terminal = RunFacts { + legacy_id: Some("boot.42.7".into()), + origin: RunOrigin::Terminal, + ..legacy(RunProcess::Running) + }; + let item = item(with(Some(in_a_terminal), true)); + assert_eq!(item.controls, Controls::all(refused(Refusal::LegacyRun))); + } + #[test] fn a_legacy_run_that_ended_can_be_started_again() { let item = item(with(Some(legacy(RunProcess::Stopped)), false)); diff --git a/src/cli/background.rs b/src/cli/background.rs index 31b3448..84fe449 100644 --- a/src/cli/background.rs +++ b/src/cli/background.rs @@ -203,7 +203,7 @@ fn stop_before_detaching( let approved = match replace { Replace::Approved(run_id) => Some(run_id.clone()), Replace::Yes => None, - Replace::Ask | Replace::No => return Ok(None), + Replace::Ask | Replace::Legacy(_) | Replace::No => return Ok(None), }; let launch = resolve_launch_target(target, config_path, ctx)?; let running = store @@ -236,7 +236,11 @@ fn foreground_args( in_service_command = true; push_dispatcher_args(&mut foreground, launch_id, dispatcher); } - let ours = arg == "--detach" || (named && is_replace_flag(&arg)); + // The dispatcher passes on the run it decided to replace: a caller's + // own `--replace=` comes back as that, and a bare `--replace` + // stays only for a caller's launch, whose executor then decides. + let replace = is_replace_flag(&arg) && (named || arg != "--replace"); + let ours = arg == "--detach" || replace; if in_service_command || !ours { foreground.push(arg); } @@ -1239,6 +1243,44 @@ mod tests { ); } + /// The daemon's detached restart passes the run it stopped, and a + /// relaunch the legacy run: each reaches the executor once. + #[test] + fn a_caller_s_run_to_replace_and_legacy_run_reach_the_executor_once() { + let launch_id = RunId::parse(ID).unwrap(); + let stopped = RunId::parse("-qAAAAAAAAAAAAAAAAAAAA").unwrap(); + let result = foreground_args( + args(&[ + "dev", + "web", + "--remote-launch=AAAAAAAAAAAAAAAAAAAAAA", + "--replace=-qAAAAAAAAAAAAAAAAAAAA", + "--detach", + ]) + .into_iter(), + &launch_id, + &Dispatcher::Caller { + replace: Some(stopped), + }, + ); + assert_eq!( + result, + args(&[ + "dev", + "web", + "--remote-launch=AAAAAAAAAAAAAAAAAAAAAA", + "--replace=-qAAAAAAAAAAAAAAAAAAAA" + ]) + ); + + let relaunch = foreground_args( + args(&["dev", "web", "--replace-legacy=boot.1.2", "--detach"]).into_iter(), + &launch_id, + &Dispatcher::Caller { replace: None }, + ); + assert_eq!(relaunch, args(&["dev", "web", "--replace-legacy=boot.1.2"])); + } + #[test] fn following_a_run_ends_cleanly_when_another_run_replaces_it() { use crate::infrastructure::running_services::NewRun; diff --git a/src/cli/services.rs b/src/cli/services.rs index b881819..a29fa8d 100644 --- a/src/cli/services.rs +++ b/src/cli/services.rs @@ -1205,6 +1205,10 @@ pub enum Replace { Yes, /// Stop that run only, which a person agreed to stop (`--replace=`). Approved(RunId), + /// Stop nothing, and start only while the record still names that legacy + /// run, which a remote relaunch's dispatcher stopped + /// (`--replace-legacy `). + Legacy(String), /// Leave it running, and start nothing. No, } @@ -1227,7 +1231,7 @@ impl Replace { match self { Self::Yes => Ok(true), Self::Approved(run_id) => Ok(running.run_id() == Some(run_id)), - Self::No => Ok(false), + Self::Legacy(_) | Self::No => Ok(false), Self::Ask => confirm_replace(running, &mut io::stdin().lock(), &mut io::stderr()), } } @@ -1271,6 +1275,16 @@ pub(crate) fn admit( Admission::Admitted(lock) => { // The record only changes under this lock now. let current = store.get(key)?; + if let Replace::Legacy(legacy_id) = &replace + && !current + .as_ref() + .is_some_and(|current| current.names_legacy(legacy_id)) + { + bail!( + "'{}' was started again by someone else since it was relaunched (legacy run {legacy_id}); nothing was started.", + key.service_id + ); + } let current = current.as_ref().and_then(RunningService::run_id); if let Some(chosen) = &chosen { match current { diff --git a/src/daemon/mgmt_socket.rs b/src/daemon/mgmt_socket.rs index 819be6d..46bca55 100644 --- a/src/daemon/mgmt_socket.rs +++ b/src/daemon/mgmt_socket.rs @@ -12,7 +12,10 @@ use tracing::{error, info, warn}; use super::lifecycle::ShutdownHandle; use super::public_tunnel::PublicTunnel; use super::remote::local::build_snapshot; -use super::remote::{AccessEvent, Asking, Failure, FollowEvent, Following, PairEvent, RemoteLink}; +use super::remote::{ + AccessEvent, Asking, ControlAsk, ControlEvent, Failure, FollowEvent, Following, PairEvent, + RemoteLink, +}; use super::router::SharedState; use crate::application::inventory::Have; use crate::infrastructure::cloud::credentials::CredentialsStore; @@ -96,6 +99,15 @@ enum MgmtCommand { machine_id: String, wants: AccessWants, }, + /// Streaming, as a viewer: starts, stops or restarts a service on + /// another machine, then its progress and result. The client waits up + /// to 120 s, not the usual 2. + #[serde(rename = "remote_control", rename_all = "camelCase")] + RemoteControl { + machine_id: String, + #[serde(flatten)] + ask: ControlAsk, + }, /// As a target, from the access dialog. #[serde(rename = "remote_access_answer", rename_all = "camelCase")] RemoteAccessAnswer { @@ -287,6 +299,10 @@ pub async fn serve( let asking = remote.access(&machine_id, wants).await; return stream_access(asking, reader, writer).await; } + Some(MgmtCommand::RemoteControl { machine_id, ask }) => { + let events = remote.control(&machine_id, ask); + return stream_control(events, reader, writer).await; + } Some(MgmtCommand::RemoteWatch { machine_id }) => { return stream_watch(&remote, &machine_id, reader, writer).await; } @@ -393,7 +409,7 @@ pub async fn serve( ) } Some(MgmtCommand::Inventory { have }) => { - inventory_answer(&inventory, &tunnel, have).await + inventory_answer(&inventory, &tunnel, remote.switches(), have).await } Some(command) => remote_answer(&remote, command).await, None => MgmtResponse::error(format!("Unknown command: {}", line.trim())), @@ -666,13 +682,35 @@ async fn stream_follow( } } +/// `remote_control`: one line per event, until the result. A client that +/// closes its end stops listening; the control goes on, on the target. +async fn stream_control( + mut events: mpsc::Receiver, + mut reader: BufReader, + mut writer: OwnedWriteHalf, +) { + loop { + tokio::select! { + _ = client_gone(&mut reader) => return, + event = events.recv() => { + let Some(event) = event else { return }; + let Ok(data) = serde_json::to_value(&event) else { return }; + if !write_line(&mut writer, &MgmtResponse::success(data)).await { + return; + } + } + } + } +} + /// A fresh snapshot of this machine. async fn inventory_answer( inventory: &Arc, tunnel: &PublicTunnel, + switches: crate::application::inventory::Switches, have: Option, ) -> MgmtResponse { - let snapshot = match build_snapshot(inventory, tunnel).await { + let snapshot = match build_snapshot(inventory, tunnel, switches).await { Ok(snapshot) => snapshot, Err(error) => return MgmtResponse::error(format!("{error:#}")), }; diff --git a/src/daemon/remote/actor.rs b/src/daemon/remote/actor.rs index 9b332f1..6cea60e 100644 --- a/src/daemon/remote/actor.rs +++ b/src/daemon/remote/actor.rs @@ -11,10 +11,11 @@ //! socket's requests (`viewer`). mod asking; +mod control; mod target; mod viewer; -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use std::sync::atomic::Ordering; use std::time::Duration; @@ -30,6 +31,7 @@ use tokio_tungstenite::tungstenite::Message; use tokio_util::sync::CancellationToken; use tracing::{debug, info, warn}; +use self::control::ControlEvent; use self::viewer::Tap; pub use self::viewer::{TapEvent, TapRequest, WINDOW}; use super::access::Waiting; @@ -50,7 +52,7 @@ use crate::infrastructure::remote::pairing::{Pairing, Step}; use crate::infrastructure::remote::store::{Pin, now_rfc3339}; use crate::infrastructure::remote::wire::{ AccessOutcome, AccessWants, ByeReason, DeclineReason, FrameKind, Hello, PresenceState, Purpose, - RelayFrame, Role, Send, SessionMessage, is_later_message, + RelayFrame, Role, Send, SessionMessage, unknown_control_field, }; /// A target handles at most this many handshakes at once. @@ -231,6 +233,13 @@ pub enum Command { Snapshot { result: Result, String>, }, + /// The control executor's progress or result for a viewer's control or + /// `control.status`, `re` in the session `key`. + ControlDone { + key: Key, + re: String, + event: ControlEvent, + }, } /// What this connection is for. @@ -299,6 +308,12 @@ struct Session { taps: HashMap, /// Target: the access request this viewer waits on. access: Option, + /// Target: the controls and `control.status`es of this viewer still + /// going, by id. + controls: HashSet, + /// Viewer: the target's clock as its `hello` gave it, and when it came, + /// so a control expires in the target's clock. + clock: Option, } impl Session { @@ -329,6 +344,8 @@ impl Session { served: target::Served::default(), taps: HashMap::new(), access: None, + controls: HashSet::new(), + clock: None, } } @@ -338,7 +355,11 @@ impl Session { /// Whether something still uses the session, so it is not idle. fn is_held(&self) -> bool { - if !self.taps.is_empty() || !self.served.is_empty() || self.access.is_some() { + if !self.taps.is_empty() + || !self.served.is_empty() + || self.access.is_some() + || !self.controls.is_empty() + { return true; } match &self.holder { @@ -1125,22 +1146,23 @@ impl Actor { .and_then(|t| t.as_str()) .unwrap_or_default() .to_string(); + // An argument a control never takes is refused, never dropped. + let unknown_field = (kind == "control") + .then(|| unknown_control_field(&value, agreed)) + .flatten(); + let greeted_target = self + .sessions + .get(key) + .is_some_and(|session| session.hello.is_some() && session.role == Role::Target); match serde_json::from_value::(value.clone()) { + Ok(SessionMessage::Control(control)) + if greeted_target && control.within_bounds() && unknown_field.is_some() => + { + let field = unknown_field.unwrap_or_default(); + self.refuse_argument(key, &control.id, &field); + } // A type of a later version than the session's is unknown here. Ok(message) if message.proto() <= agreed => self.on_session_message(key, message), - Err(_) if is_later_message(&kind) => { - let re = value - .get("id") - .and_then(|id| id.as_str()) - .map(str::to_string); - let answer = SessionMessage::Error { - re, - code: "unsupported".into(), - message: format!("This version of Localify does not handle {kind} yet."), - retry_after: None, - }; - self.send_message(key, &answer); - } Ok(_) | Err(_) => self.end( key, End::Error("bad_request", format!("Unknown message {kind}.")), @@ -1198,6 +1220,22 @@ impl Actor { { self.deliver(key, message); } + message @ (SessionMessage::ControlProgress { .. } + | SessionMessage::ControlResult(_)) + if role == Role::Viewer && purpose == Purpose::Session => + { + self.deliver(key, message); + } + SessionMessage::Control(control) + if role == Role::Target && purpose == Purpose::Session => + { + self.on_control(key, *control); + } + SessionMessage::ControlStatus { id, request_id } + if role == Role::Target && purpose == Purpose::Session => + { + self.on_control_status(key, id, request_id); + } SessionMessage::AccessRequest { id, wants } if role == Role::Target && purpose == Purpose::Session => { @@ -1284,6 +1322,10 @@ impl Actor { ); } let settings = hello.settings; + session.clock = + time::OffsetDateTime::parse(&hello.now, &time::format_description::well_known::Rfc3339) + .ok() + .map(|now| (now, Instant::now())); session.hello = Some(hello.clone()); session.proto = Some(agreed); let (role, purpose) = (session.role, session.purpose); @@ -1578,6 +1620,7 @@ impl Actor { Command::Untap { peer, id } => self.untap(&peer, &id), Command::Ack { peer, id, offset } => self.ack(&peer, &id, offset), Command::Snapshot { result } => self.on_snapshot(result), + Command::ControlDone { key, re, event } => self.on_control_done(&key, &re, event), Command::SettingsChanged { reply } => { self.reload_settings(); let _ = reply.send(()); diff --git a/src/daemon/remote/actor/control.rs b/src/daemon/remote/actor/control.rs new file mode 100644 index 0000000..cb1721c --- /dev/null +++ b/src/daemon/remote/actor/control.rs @@ -0,0 +1,208 @@ +//! The target's side of a control (`docs/remote-machines.md`, "Target +//! checks"): checks 1 to 3 here, on the actor's task, then the control +//! executor (`infrastructure::remote::control`) off it, through the +//! machine's [`LocalSource`]. Its progress and its result come back as +//! commands and go to the session that asked, while it is open; a session +//! that ended hears nothing, and its viewer asks `control.status` on its +//! next one. +//! +//! [`LocalSource`]: crate::daemon::remote::local::LocalSource + +use std::sync::Arc; + +use tokio::time::Instant; +use tracing::{info, warn}; + +use super::{Actor, Command, Key}; +use crate::application::inventory::Switches; +use crate::infrastructure::remote::control::Order; +use crate::infrastructure::remote::requests::Report; +use crate::infrastructure::remote::store::DEFAULT_SETTINGS; +use crate::infrastructure::remote::wire::{Control, ControlPhase, SessionMessage}; + +/// What the executor says about one control, back on the actor's task. +#[derive(Debug)] +pub enum ControlEvent { + Progress(ControlPhase), + Result(Report), +} + +impl Actor { + /// Whether `id` names a request of this session still going, whatever + /// its kind. + pub(super) fn id_in_use(&self, key: &Key, id: &str) -> bool { + self.sessions.get(key).is_some_and(|session| { + session.served.is_active(id) + || session.controls.contains(id) + || session + .access + .as_ref() + .is_some_and(|waiting| waiting.re == id) + }) + } + + /// A `control` that carries a field it may not: refused, never run. + pub(super) fn refuse_argument(&mut self, key: &Key, id: &str, field: &str) { + let report = Report::refused( + "refused_argument", + format!("A control from another machine never takes '{field}'."), + ); + self.send_message(key, &SessionMessage::ControlResult(report.answer(id))); + } + + /// `control`: checks 1 to 3, then the executor, off this task. + pub(super) fn on_control(&mut self, key: &Key, control: Control) { + let id = control.id.clone(); + if self.id_in_use(key, &id) { + let refusal = + SessionMessage::refusal(&id, "bad_request", "This request id is already in use."); + self.send_message(key, &refusal); + return; + } + // 1 is the session's: a pinned peer, past `hello`. 2: the switches. + let settings = self.shared.store.settings().unwrap_or(DEFAULT_SETTINGS); + let refusal = match (settings.share, settings.control) { + (false, _) => Some(("not_shared", "This machine doesn't share its projects.")), + (true, false) => Some(( + "control_disabled", + "This machine doesn't allow remote controls.", + )), + (true, true) => None, + }; + if let Some((code, message)) = refusal { + let report = Report::refused(code, message); + self.send_message(key, &SessionMessage::ControlResult(report.answer(&id))); + return; + } + let Some(session) = self.sessions.get_mut(key) else { + return; + }; + session.controls.insert(id.clone()); + let peer_name = self + .shared + .store + .pins() + .ok() + .and_then(|pins| pins.get(&key.0).map(|pin| pin.name.clone())) + .unwrap_or_else(|| key.0.clone()); + info!(peer = %key.0, action = control.action.as_str(), service = %control.service.service_id, "A paired machine asks for a control"); + let order = Order { + peer: key.0.clone(), + peer_name, + control, + }; + self.execute_control(key.clone(), id, order); + } + + /// Check 3, a fresh lease, then the executor on a blocking thread; its + /// progress and result come back as [`Command::ControlDone`]. + fn execute_control(&mut self, key: Key, id: String, order: Order) { + let lease = Arc::clone(&self.ctx.lease); + let source = Arc::clone(&self.ctx.source); + let shared = Arc::clone(&self.shared); + let commands = self.commands.clone(); + self.spawn(async move { + // 3: a fresh lease, asked for now, that still lists the viewer. + let fresh = lease.renew().await.is_ok() && lease.covers(&order.peer, Instant::now()); + let send = |event| { + let _ = commands.send(Command::ControlDone { + key: key.clone(), + re: id.clone(), + event, + }); + }; + if !fresh { + return send(ControlEvent::Result(Report::refused( + "unauthorized", + "Remote access is not available right now.", + ))); + } + let progress_commands = commands.clone(); + let (progress_key, progress_id) = (key.clone(), id.clone()); + let ran = tokio::task::spawn_blocking(move || { + let switches = || Switches { + settings: shared.store.settings().unwrap_or(DEFAULT_SETTINGS).into(), + app: source.app().into(), + }; + let mut progress = |phase| { + let _ = progress_commands.send(Command::ControlDone { + key: progress_key.clone(), + re: progress_id.clone(), + event: ControlEvent::Progress(phase), + }); + }; + source.control(&order, &switches, &mut progress) + }) + .await; + let report = ran.unwrap_or_else(|error| { + Report::refused("unavailable", format!("The control failed here: {error}")) + }); + send(ControlEvent::Result(report)); + }); + } + + /// `control.status`: the request's entry, off this task. + pub(super) fn on_control_status(&mut self, key: &Key, id: String, request_id: String) { + if self.id_in_use(key, &id) { + let refusal = + SessionMessage::refusal(&id, "bad_request", "This request id is already in use."); + self.send_message(key, &refusal); + return; + } + let Some(session) = self.sessions.get_mut(key) else { + return; + }; + session.controls.insert(id.clone()); + let source = Arc::clone(&self.ctx.source); + let commands = self.commands.clone(); + let (key, peer) = (key.clone(), key.0.clone()); + self.spawn(async move { + let report = + tokio::task::spawn_blocking(move || source.control_status(&peer, &request_id)) + .await + .unwrap_or_else(|error| { + Report::refused( + "unavailable", + format!("The request could not be read here: {error}"), + ) + }); + let _ = commands.send(Command::ControlDone { + key, + re: id, + event: ControlEvent::Result(report), + }); + }); + } + + /// The executor's news: to the session that asked, while it is open. + /// After a result, viewers that watch get the fresh snapshot. + pub(super) fn on_control_done(&mut self, key: &Key, re: &str, event: ControlEvent) { + let message = match event { + ControlEvent::Progress(phase) => SessionMessage::ControlProgress { + re: re.to_string(), + phase, + }, + ControlEvent::Result(report) => { + if let Some(session) = self.sessions.get_mut(key) { + session.controls.remove(re); + } + self.refresh_watchers(); + SessionMessage::ControlResult(report.answer(re)) + } + }; + if self.sessions.contains_key(key) && !self.send_message(key, &message) { + warn!(peer = %key.0, "Could not send a control's answer"); + } + } + + /// A control changed what runs: every watch hears it at once. + fn refresh_watchers(&mut self) { + let watched = self + .sessions + .values() + .any(|session| session.served.watches()); + if watched { + self.build_snapshot(); + } + } +} diff --git a/src/daemon/remote/actor/target.rs b/src/daemon/remote/actor/target.rs index 026f0c0..d26e00f 100644 --- a/src/daemon/remote/actor/target.rs +++ b/src/daemon/remote/actor/target.rs @@ -15,7 +15,7 @@ use std::time::Duration; use tokio::time::Instant; use super::{Actor, Command, End, Failure, Key}; -use crate::application::inventory::{Snapshot, pages}; +use crate::application::inventory::{Snapshot, Switches, pages}; use crate::daemon::remote::local::RunLookup; use crate::infrastructure::remote::store::DEFAULT_SETTINGS; use crate::infrastructure::remote::wire::{ @@ -107,6 +107,11 @@ impl Follow { } impl Served { + /// Whether the viewer watches the inventory. + pub(super) fn watches(&self) -> bool { + self.watch.is_some() + } + pub(super) fn is_empty(&self) -> bool { self.watch.is_none() && self.follows.is_empty() @@ -475,16 +480,25 @@ impl Actor { } /// Builds a snapshot off this task; one at a time. - fn build_snapshot(&mut self) { + pub(super) fn build_snapshot(&mut self) { if self.shelf.building { return; } self.shelf.building = true; let source = Arc::clone(&self.ctx.source); let commands = self.commands.clone(); + let switches = Switches { + settings: self + .shared + .store + .settings() + .unwrap_or(DEFAULT_SETTINGS) + .into(), + app: source.app().into(), + }; self.spawn(async move { let result = source - .snapshot() + .snapshot(switches) .await .map(Arc::new) .map_err(|error| format!("{error:#}")); diff --git a/src/daemon/remote/actor/viewer.rs b/src/daemon/remote/actor/viewer.rs index 4a8e78f..a760132 100644 --- a/src/daemon/remote/actor/viewer.rs +++ b/src/daemon/remote/actor/viewer.rs @@ -4,16 +4,24 @@ //! opens with the first request and closes with the last one. use std::collections::HashMap; +use std::time::Duration; use tokio::sync::mpsc; +use tokio::time::Instant; use super::{Actor, End, Failure, Holder, Key}; use crate::infrastructure::remote::wire::{ - AccessWants, ByeReason, Have, PROTO_ACCESS, Purpose, Role, SessionMessage, + AccessWants, ByeReason, Control, ControlAction, ControlExpect, ControlService, Have, + PROTO_ACCESS, Purpose, Role, SessionMessage, }; /// The window a viewer gives each follow. pub const WINDOW: u32 = 64 * 1024; +/// A control expires this long after it is sent, in the target's clock. +const CONTROL_EXPIRY: Duration = Duration::from_secs(30); + +/// The target's clock, as its `hello` gave it, and when it came. +pub type PeerClock = (time::OffsetDateTime, Instant); /// What a management socket client asked a target for. #[derive(Debug, Clone, PartialEq, Eq)] @@ -36,6 +44,19 @@ pub enum TapRequest { Access { wants: AccessWants, }, + /// Start, stop or restart one service. Its expiry is set when it is + /// sent, in the target's clock. + Control { + action: ControlAction, + service: ControlService, + profile: Option, + request_id: String, + expect: ControlExpect, + }, + /// What became of a control sent earlier, by its request id. + ControlStatus { + request_id: String, + }, } #[derive(Debug)] @@ -67,9 +88,27 @@ impl Tap { ) } - fn message(&self, id: &str) -> SessionMessage { + fn message(&self, id: &str, clock: Option<&PeerClock>) -> SessionMessage { let id = id.to_string(); match self.request.clone() { + TapRequest::Control { + action, + service, + profile, + request_id, + expect, + } => SessionMessage::Control(Box::new(Control { + id, + action, + service, + profile, + request_id, + expect, + expires_at: expiry(clock), + })), + TapRequest::ControlStatus { request_id } => { + SessionMessage::ControlStatus { id, request_id } + } TapRequest::Inventory { watch: true, have } => { SessionMessage::InventoryWatch { id, have } } @@ -103,8 +142,9 @@ impl Tap { /// The first session version that carries this request. fn proto(&self) -> u32 { - match self.request { + match &self.request { TapRequest::Access { .. } => PROTO_ACCESS, + TapRequest::Control { expect, .. } if expect.legacy_id.is_some() => PROTO_ACCESS, _ => 1, } } @@ -137,6 +177,10 @@ impl Tap { (SessionMessage::OutputData(data), TapRequest::Follow { .. }) => data.ended, (SessionMessage::OutputData(_), TapRequest::Read { .. }) => true, (SessionMessage::AccessResult { .. }, TapRequest::Access { .. }) => true, + ( + SessionMessage::ControlResult(_), + TapRequest::Control { .. } | TapRequest::ControlStatus { .. }, + ) => true, _ => false, } } @@ -160,13 +204,26 @@ fn answer_to(answer: &SessionMessage) -> Option<&str> { SessionMessage::InventoryPage { re, .. } | SessionMessage::InventoryUnchanged { re, .. } => Some(re), SessionMessage::OutputData(data) => Some(&data.re), - SessionMessage::Error { re: Some(re), .. } | SessionMessage::AccessResult { re, .. } => { - Some(re) - } + SessionMessage::Error { re: Some(re), .. } + | SessionMessage::AccessResult { re, .. } + | SessionMessage::ControlProgress { re, .. } => Some(re), + SessionMessage::ControlResult(result) => Some(&result.re), _ => None, } } +/// `expiresAt` for a control sent now: the target's clock as its `hello` +/// gave it, moved on by the time since, plus [`CONTROL_EXPIRY`]. +fn expiry(clock: Option<&PeerClock>) -> String { + let now = match clock { + Some((then, received)) => *then + received.elapsed(), + None => time::OffsetDateTime::now_utc(), + }; + (now + CONTROL_EXPIRY) + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_default() +} + impl Actor { /// This machine's session as a viewer of `peer`, open or opening. pub(super) fn viewer_session(&self, peer: &str) -> Option { @@ -301,7 +358,7 @@ impl Actor { return self.close_if_unused(key); } tap.sent = true; - let message = tap.message(id); + let message = tap.message(id, session.clock.as_ref()); self.send_message(key, &message); } diff --git a/src/daemon/remote/fake_relay.rs b/src/daemon/remote/fake_relay.rs index f3ffd4b..f71d53d 100644 --- a/src/daemon/remote/fake_relay.rs +++ b/src/daemon/remote/fake_relay.rs @@ -7,7 +7,7 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; use futures_util::{SinkExt, StreamExt}; use serde_json::{Value, json}; @@ -25,10 +25,21 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use super::local::{LocalSource, RunLookup, SnapshotFuture}; -use crate::application::inventory::{InventoryItem, Revisions}; +use crate::application::inventory::{ + Context, InventoryItem, Revisions, RunFacts, RunOrigin, RunProcess, ServiceFacts, Switches, + inventory_item, +}; +use crate::infrastructure::app_bridge::{BridgeError, Handoff, LaunchRequest}; +use crate::infrastructure::remote::control::{ + ControlRunner, ControlTimings, DetachedLaunch, Expected, Host, Look, Order, Spawned, +}; use crate::infrastructure::remote::noise::{Handshake, SessionContext, SessionId, StaticKeys}; +use crate::infrastructure::remote::requests::{Report, RequestEntries}; +use crate::infrastructure::remote::wire::ControlPhase; use crate::infrastructure::remote::wire::{AppPresence, FrameKind, Purpose, Send}; +use crate::infrastructure::running_services::ServiceKey; use crate::infrastructure::runs::RunId; +use crate::infrastructure::runs::launches::{LaunchReport, RefusalCode, unix_ms_now}; /// What the relay does with one frame. pub enum Route { @@ -738,10 +749,12 @@ pub fn opens(frame: &Send, purpose: Purpose) -> bool { } /// What a target shares in tests: the items its snapshots hold, numbered as -/// the daemon numbers them, and the output folders of its runs. +/// the daemon numbers them, or the services of its [`FakeHost`] projected +/// with the switches; the output folders of its runs; and its controls, run +/// by the real executor over the fake host, with request entries on disk. #[derive(Default)] pub struct FakeSource { - items: Mutex>, + items: Mutex>>, revisions: Mutex>, runs: Mutex>>, builds: AtomicUsize, @@ -749,16 +762,37 @@ pub struct FakeSource { build_ms: AtomicUsize, /// Whether the desktop app runs. app_running: AtomicBool, + host: OnceLock>, + runner: OnceLock, + /// Where request entries are kept: the daemon's `services/requests`. + requests: Mutex>, + scratch: OnceLock, +} + +/// The executor's delays, shortened. +pub fn fast_controls() -> ControlTimings { + ControlTimings { + dispatch_budget: std::time::Duration::from_millis(1500), + settle: std::time::Duration::from_millis(1000), + poll: std::time::Duration::from_millis(20), + ahead: std::time::Duration::from_secs(60), + } } impl FakeSource { + /// Keeps request entries in `dir`, as a daemon keeps them in its state + /// folder: a daemon started again on it finds them. + pub fn keep_requests_in(&self, dir: PathBuf) { + *self.requests.lock().unwrap() = Some(dir); + } + /// Each build takes this long, so requests pile up behind it. pub fn set_build_time(&self, ms: usize) { self.build_ms.store(ms, Ordering::SeqCst); } pub fn set_items(&self, items: Vec) { - *self.items.lock().unwrap() = items; + *self.items.lock().unwrap() = Some(items); } /// `run_id` is its service's last run, with its output in `dir`. @@ -776,12 +810,45 @@ impl FakeSource { pub fn builds(&self) -> usize { self.builds.load(Ordering::SeqCst) } + + /// The services the controls act on, and the snapshots show. + pub fn host(&self) -> Arc { + Arc::clone(self.host.get_or_init(|| { + Arc::new(FakeHost { + state: Mutex::new(HostState::default()), + }) + })) + } + + fn runner(&self) -> &ControlRunner { + self.runner.get_or_init(|| { + let dir = self.requests.lock().unwrap().clone().unwrap_or_else(|| { + self.scratch + .get_or_init(|| tempfile::tempdir().unwrap()) + .path() + .to_path_buf() + }); + let host: Arc = self.host(); + ControlRunner::new(host, RequestEntries::new(dir), fast_controls()) + }) + } } impl LocalSource for FakeSource { - fn snapshot(&self) -> SnapshotFuture { + fn snapshot(&self, switches: Switches) -> SnapshotFuture { self.builds.fetch_add(1, Ordering::SeqCst); - let items = self.items.lock().unwrap().clone(); + let items = self.items.lock().unwrap().clone().unwrap_or_else(|| { + let context = Context { + settings: switches.settings, + app: switches.app, + tunnel_connected: false, + }; + self.host() + .facts() + .into_iter() + .map(|facts| inventory_item(facts, &context)) + .collect() + }); let snapshot = self .revisions .lock() @@ -812,4 +879,311 @@ impl LocalSource for FakeSource { AppPresence::Absent } } + + fn control( + &self, + order: &Order, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report { + self.runner().run(order, switches, progress) + } + + fn control_status(&self, peer: &str, request_id: &str) -> Report { + self.runner().status(peer, request_id) + } + + fn shell_environment_failure(&self) -> Option { + None + } +} + +/// What the app bridge does with a launch. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Bridge { + #[default] + Accept, + /// Spawns the run, and the answer is lost. + Unanswered, + Absent, + Refuse(&'static str), +} + +/// One service on the fake target. +#[derive(Debug, Clone)] +pub struct FakeService { + pub facts: ServiceFacts, + /// The legacy run the service's record still names, proven or not. + pub record_names: Option, +} + +#[derive(Default)] +pub struct HostState { + pub services: Vec, + pub bridge: Bridge, + /// A started run exits at once with this code instead of listening. + pub exit_code: Option, + pub launches: HashMap, + /// What reached the app, and what was spawned detached. + pub handed: Vec, + pub detached: Vec, + pub stops: Vec, + /// Holds the next launch once it reached the host, until the test + /// sends or drops the other end. + pub hold: Option>, +} + +/// A target's services in memory: stops end their run, launches run +/// `localify dev`'s own checks under the lock (a run still live, or a +/// record that no longer names the legacy run relaunched, refuses), then +/// start a run that listens. +pub struct FakeHost { + state: Mutex, +} + +impl FakeHost { + pub fn state(&self) -> MutexGuard<'_, HostState> { + self.state.lock().unwrap() + } + + pub fn facts(&self) -> Vec { + self.state() + .services + .iter() + .map(|service| service.facts.clone()) + .collect() + } + + /// The facts of the service named `id`. + pub fn service(&self, id: &str) -> ServiceFacts { + self.state() + .services + .iter() + .find(|service| service.facts.service.id == id) + .map(|service| service.facts.clone()) + .unwrap() + } + + pub fn change(&self, id: &str, change: impl FnOnce(&mut FakeService)) { + let mut state = self.state(); + let service = state + .services + .iter_mut() + .find(|service| service.facts.service.id == id) + .unwrap(); + change(service); + } + + /// What `localify dev` does with a launch, under the service's lock. + fn start( + &self, + id: &RunId, + key: &ServiceKey, + origin: RunOrigin, + replaces_legacy: Option<&str>, + profile: Option, + ) { + let mut state = self.state(); + let exit_code = state.exit_code; + let Some(service) = state + .services + .iter_mut() + .find(|service| matches(service, key)) + else { + return; + }; + let live = service + .facts + .run + .as_ref() + .is_some_and(|run| run.process != RunProcess::Stopped); + let renamed = + replaces_legacy.is_some_and(|legacy| service.record_names.as_deref() != Some(legacy)); + let report = if live || renamed { + LaunchReport::Refused { + code: RefusalCode::Conflict, + message: "Someone else started it meanwhile.".into(), + } + } else { + service.record_names = None; + service.facts.run = Some(RunFacts { + run_id: Some(id.to_string()), + origin, + legacy: false, + has_stream: true, + process: if exit_code.is_some() { + RunProcess::Stopped + } else { + RunProcess::Running + }, + started_at: "2026-11-09T10:00:00Z".into(), + profile, + profile_danger: false, + exit: None, + legacy_id: None, + }); + service.facts.reachable = Some(exit_code.is_none()); + match exit_code { + Some(code) => LaunchReport::Exited { + code: Some(code), + signal: None, + reason: None, + }, + None => LaunchReport::Running, + } + }; + state.launches.insert(id.to_string(), report); + } +} + +fn matches(service: &FakeService, key: &ServiceKey) -> bool { + service.facts.project.id == key.project_id + && service.facts.service.id == key.service_id + && service.facts.environment.slug == key.environment +} + +/// Nothing to kill or reap. +struct NoProcess; + +impl Spawned for NoProcess { + fn settle(self: Box, _: bool) {} +} + +impl Host for FakeHost { + fn look( + &self, + wanted: &ServiceKey, + profile: Option<&str>, + legacy_id: Option<&str>, + ) -> anyhow::Result> { + let state = self.state(); + let Some(service) = state + .services + .iter() + .find(|service| matches(service, wanted)) + else { + return Ok(None); + }; + Ok(Some(Look { + facts: service.facts.clone(), + key: wanted.clone(), + profile_allowed: !matches!(profile, Some("prod" | "removed")), + names_legacy: legacy_id.is_some() && service.record_names.as_deref() == legacy_id, + })) + } + + fn stop(&self, key: &ServiceKey, expected: &Expected) -> Result<(), Report> { + let mut state = self.state(); + state.stops.push(expected.clone()); + let Some(service) = state + .services + .iter_mut() + .find(|service| matches(service, key)) + else { + return Err(Report::refused("conflict", "Gone.")); + }; + let run = service + .facts + .run + .as_mut() + .filter(|run| run.process != RunProcess::Stopped); + let Some(run) = run else { + return Err(Report::refused("conflict", "Nothing runs.")); + }; + match expected { + Expected::Run(run_id) if run.run_id.as_deref() != Some(run_id.as_str()) => { + return Err(Report::refused("conflict", "Another run.")); + } + Expected::Legacy(legacy_id) if service.record_names.as_deref() != Some(legacy_id) => { + return Err(Report::refused("conflict", "Another run.")); + } + Expected::Legacy(legacy_id) if run.legacy_id.as_deref() != Some(legacy_id) => { + return Err(Report::refused("legacy_run", "Not proven.")); + } + _ => {} + } + run.process = RunProcess::Stopped; + service.facts.reachable = Some(false); + Ok(()) + } + + fn launch_in_app(&self, request: &LaunchRequest) -> Handoff { + let (bridge, hold) = { + let mut state = self.state(); + state.handed.push(request.clone()); + (state.bridge, state.hold.take()) + }; + if let Some(hold) = hold { + let _ = hold.recv(); + } + let key = ServiceKey { + project_id: request.service.project_id.clone(), + environment: request.service.environment.clone(), + service_id: request.service.service_id.clone(), + }; + match bridge { + Bridge::Absent => return Handoff::Absent, + Bridge::Refuse(code) => { + return Handoff::Refused(BridgeError { + code: code.into(), + message: "Refused.".into(), + }); + } + Bridge::Accept | Bridge::Unanswered => self.start( + &request.launch_id, + &key, + RunOrigin::App, + request.replaces_legacy.as_deref(), + request.profile.clone(), + ), + } + match bridge { + Bridge::Unanswered => Handoff::Unanswered("The answer was lost.".into()), + _ => Handoff::Accepted, + } + } + + fn launch_detached(&self, launch: &DetachedLaunch) -> anyhow::Result> { + let hold = { + let mut state = self.state(); + state.detached.push(launch.clone()); + state.hold.take() + }; + if let Some(hold) = hold { + let _ = hold.recv(); + } + self.start( + &launch.launch_id, + &launch.key, + RunOrigin::Background, + launch.replaces_legacy.as_deref(), + launch.profile.clone(), + ); + Ok(Box::new(NoProcess)) + } + + fn report(&self, launch_id: &RunId, expires_at: Option) -> anyhow::Result { + let mut state = self.state(); + if let Some(report) = state.launches.get(launch_id.as_str()) { + return Ok(report.clone()); + } + if expires_at.is_some_and(|expires| unix_ms_now() >= expires) { + state + .launches + .insert(launch_id.to_string(), LaunchReport::Expired); + return Ok(LaunchReport::Expired); + } + Ok(LaunchReport::Unknown) + } + + fn listens(&self, port: u16) -> bool { + self.state() + .services + .iter() + .any(|service| service.facts.port == port && service.facts.reachable == Some(true)) + } + + fn last_lines(&self, _: &RunId, _: usize) -> String { + "the last line".into() + } } diff --git a/src/daemon/remote/local.rs b/src/daemon/remote/local.rs index c1d06d2..4113d70 100644 --- a/src/daemon/remote/local.rs +++ b/src/daemon/remote/local.rs @@ -1,7 +1,8 @@ -//! What this machine shows its paired machines as a target -//! (`docs/remote-machines.md`, "Inventory" and "Output"): its inventory -//! snapshot, and the output folder of a service's last run. The link asks -//! for them only while a viewer asks, and never sends a path or a record. +//! What this machine shows its paired machines as a target, and does for +//! them (`docs/remote-machines.md`, "Inventory", "Output" and "Controls"): +//! its inventory snapshot, the output folder of a service's last run, and +//! the control executor. The link asks for them only while a viewer asks, +//! and never sends a path or a record. use std::future::Future; use std::path::PathBuf; @@ -13,15 +14,21 @@ use std::time::Duration; use anyhow::Result; use tokio_util::sync::CancellationToken; -use crate::application::inventory::{Have, Snapshot}; +use crate::application::inventory::{Have, Snapshot, Switches}; use crate::daemon::public_tunnel::PublicTunnel; use crate::infrastructure::app_bridge; use crate::infrastructure::cloud::types::TunnelState; use crate::infrastructure::inventory::{LocalInventory, PublicFacts}; -use crate::infrastructure::remote::wire::{AppPresence, MachineSummary}; +use crate::infrastructure::remote::control::{ + ControlRunner, ControlTimings, LocalHost, Order, Reader, +}; +use crate::infrastructure::remote::requests::{Report, RequestEntries}; +use crate::infrastructure::remote::wire::{AppPresence, ControlPhase, MachineSummary}; use crate::infrastructure::running_services::RunningServiceStore; use crate::infrastructure::runs::RunId; +use crate::infrastructure::shell_env::user_shell; use localify::desktop::ProjectRootStore; +use localify::desktop::shell_environment::{ShellEnvironment, ShellEnvironmentState}; pub type SnapshotFuture = Pin> + Send>>; @@ -34,16 +41,31 @@ pub enum RunLookup { Unavailable(&'static str), } -/// The target's facts, as the link reads them. +/// The target's facts, as the link reads them, and what it does for a +/// viewer's control. pub trait LocalSource: Send + Sync { - /// A fresh snapshot of this machine's inventory. - fn snapshot(&self) -> SnapshotFuture; + /// A fresh snapshot of this machine's inventory, its controls decided by + /// `switches`. + fn snapshot(&self, switches: Switches) -> SnapshotFuture; /// The output folder of `run_id`, while it is its service's last run /// and has a stream. Reads the run records: quick, and blocking. fn run_output(&self, run_id: &RunId) -> Result>; /// Whether the desktop app runs, as its bridge's `hello` last said: /// never waits for the app. fn app(&self) -> AppPresence; + /// Runs a control from check 4 on (see `ControlRunner::run`). Blocks + /// for as long as the control takes. + fn control( + &self, + order: &Order, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report; + /// `control.status`: what became of a peer's request. Blocks. + fn control_status(&self, peer: &str, request_id: &str) -> Report; + /// Why background starts run without the user's shell environment, + /// when it could not be read. + fn shell_environment_failure(&self) -> Option; } /// How often [`AppSeen`] asks the app's bridge. @@ -90,28 +112,69 @@ impl AppSeen { } } -/// The daemon's own inventory, tunnel and run records. +/// The daemon's own inventory, tunnel and run records, and its controls. pub struct DaemonSource { inventory: Arc, tunnel: PublicTunnel, app: AppSeen, + controls: ControlRunner, + shell: Arc, } impl DaemonSource { + /// Resolves this executable once, canonical: a detached start runs it, + /// never a `localify` found on `PATH`. pub fn new(inventory: Arc, tunnel: PublicTunnel, app: AppSeen) -> Self { + let executable = LocalHost::own_executable(); + let shell = Arc::new(ShellEnvironment::new( + executable.clone().unwrap_or_default(), + user_shell(), + )); + let services_dir = inventory.services_dir(); + let host = LocalHost { + config_path: inventory.config_path().to_path_buf(), + data_dir: inventory.data_dir().to_path_buf(), + services_dir: services_dir.clone(), + executable, + environment: { + let shell = Arc::clone(&shell); + Arc::new(move || shell.environment()) + }, + installation: LocalHost::own_installation(), + project_roots: project_roots(), + }; + let controls = ControlRunner::new( + Arc::new(host), + RequestEntries::in_services_dir(&services_dir), + ControlTimings::default(), + ); Self { inventory, tunnel, app, + controls, + shell, } } } +/// The checkouts the app knows, as `localify dev` reads them. +fn project_roots() -> Reader> { + Arc::new(|| { + ProjectRootStore::new_default() + .and_then(|store| store.load()) + .unwrap_or_default() + .into_iter() + .map(|(project_id, root)| (project_id, PathBuf::from(root))) + .collect() + }) +} + impl LocalSource for DaemonSource { - fn snapshot(&self) -> SnapshotFuture { + fn snapshot(&self, switches: Switches) -> SnapshotFuture { let inventory = Arc::clone(&self.inventory); let tunnel = self.tunnel.clone(); - Box::pin(async move { build_snapshot(&inventory, &tunnel).await }) + Box::pin(async move { build_snapshot(&inventory, &tunnel, switches).await }) } fn run_output(&self, run_id: &RunId) -> Result> { @@ -122,6 +185,28 @@ impl LocalSource for DaemonSource { fn app(&self) -> AppPresence { self.app.get() } + + fn control( + &self, + order: &Order, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report { + self.controls.run(order, switches, progress) + } + + fn control_status(&self, peer: &str, request_id: &str) -> Report { + self.controls.status(peer, request_id) + } + + fn shell_environment_failure(&self) -> Option { + let status = self.shell.status(); + (status.state == ShellEnvironmentState::Failed).then(|| { + status + .reason + .unwrap_or_else(|| "Your shell's environment could not be read.".into()) + }) + } } /// Numbers what viewers are sent: a snapshot's items and the machine @@ -173,6 +258,7 @@ pub fn lookup(store: &RunningServiceStore, run_id: &RunId) -> Result, tunnel: &PublicTunnel, + switches: Switches, ) -> Result { let (urls, machine_id) = tunnel.known_urls(); let public = PublicFacts { @@ -181,17 +267,8 @@ pub async fn build_snapshot( tunnel_connected: tunnel.status().await.tunnel == TunnelState::Connected, }; let inventory = Arc::clone(inventory); - tokio::task::spawn_blocking(move || { - // The checkouts the app knows, as `localify dev` reads them. - let project_roots = ProjectRootStore::new_default() - .and_then(|store| store.load()) - .unwrap_or_default() - .into_iter() - .map(|(project_id, root)| (project_id, PathBuf::from(root))) - .collect(); - inventory.snapshot(&public, &project_roots) - }) - .await? + tokio::task::spawn_blocking(move || inventory.snapshot(&public, &project_roots()(), switches)) + .await? } #[cfg(test)] diff --git a/src/daemon/remote/mod.rs b/src/daemon/remote/mod.rs index ac3d2af..be2463c 100644 --- a/src/daemon/remote/mod.rs +++ b/src/daemon/remote/mod.rs @@ -43,7 +43,9 @@ use self::backoff::{Backoff, Ending, Next, Stop, random_fraction, up_to}; use self::lease::{LeaseError, LeaseKeeper}; use self::local::LocalSource; use self::machines::{Facts, MachineState, MachineView, RelayState, SessionState}; -pub use self::viewing::{AccessEvent, Asking, FollowEvent, Following, RemoteInventory}; +pub use self::viewing::{ + AccessEvent, Asking, ControlAsk, ControlEvent, FollowEvent, Following, RemoteInventory, +}; use crate::daemon::public_tunnel::Clocks; use crate::infrastructure::cloud::api::{CloudClient, RemoteAccount}; use crate::infrastructure::cloud::credentials::{CloudCredentials, CredentialsStore}; @@ -222,6 +224,9 @@ pub struct RemoteStatus { pub retry_at: Option, pub settings: TargetSettings, pub fingerprint: Option, + /// Why background starts run with the daemon's own environment: the + /// user's shell environment could not be read. + pub shell_environment_error: Option, } /// What the link knows, for the management socket. @@ -536,6 +541,21 @@ impl RemoteLink { retry_at: view.retry_at.clone(), settings: self.shared.store.settings().unwrap_or(DEFAULT_SETTINGS), fingerprint, + shell_environment_error: self.shared.source.shell_environment_failure(), + } + } + + /// The switches and the app, as this machine's own inventory decides its + /// controls with them. + pub fn switches(&self) -> crate::application::inventory::Switches { + crate::application::inventory::Switches { + settings: self + .shared + .store + .settings() + .unwrap_or(DEFAULT_SETTINGS) + .into(), + app: self.shared.source.app().into(), } } diff --git a/src/daemon/remote/tests.rs b/src/daemon/remote/tests.rs index 791523b..d6abc36 100644 --- a/src/daemon/remote/tests.rs +++ b/src/daemon/remote/tests.rs @@ -3,6 +3,7 @@ //! Viewing, and the PR 3 gate, are in `viewing`. mod access; +mod control; mod viewing; use std::sync::Arc; @@ -161,6 +162,8 @@ fn launch_with( }) .unwrap(); let source = Arc::new(FakeSource::default()); + // Where a daemon keeps them: one started again on this folder finds them. + source.keep_requests_in(dir.path().join("services").join("requests")); let shared: Arc = source.clone(); let link = RemoteLink::with_timings(dir.path(), shared, timings); // As `LOCALIFY_CLOUD_API` makes a `wrangler dev` trusted. diff --git a/src/daemon/remote/tests/access.rs b/src/daemon/remote/tests/access.rs index 4c174fd..70ddb41 100644 --- a/src/daemon/remote/tests/access.rs +++ b/src/daemon/remote/tests/access.rs @@ -271,6 +271,65 @@ async fn allow_turns_on_exactly_the_switches_asked_for() { } /// Access never turns `share` on. +/// The gate: with the app running on the target, `Allow` turns `control` +/// on, and the viewer's next snapshot allows controls. +#[tokio::test] +async fn the_next_snapshot_after_an_allow_allows_controls() { + use crate::application::inventory::{ + EnvironmentRef, ProfileChecks, ProjectRef, ServiceFacts, ServiceRef, + }; + use crate::daemon::remote::fake_relay::FakeService; + use crate::infrastructure::remote::wire::AppPresence; + + let cloud = FakeCloud::start().await; + let (a, b) = asker_and_target(&cloud, unlimited()).await; + b.source.set_app(AppPresence::Running); + b.source.host().state().services = vec![FakeService { + facts: ServiceFacts { + project: ProjectRef { + id: "app".into(), + name: "App".into(), + }, + environment: EnvironmentRef { + slug: None, + name: "Primary".into(), + primary: true, + branch: None, + }, + service: ServiceRef { + id: "web".into(), + name: "web".into(), + config_rev: "0123456789abcdef".into(), + }, + local_url: "https://web.localify".into(), + port: 4100, + reachable: Some(false), + run: None, + public_url: None, + profiles: ProfileChecks { + start: true, + restart: true, + }, + }, + record_names: None, + }]; + let start = |inventory: &crate::daemon::remote::RemoteInventory| { + inventory.items[0]["controls"]["start"].clone() + }; + let before = a.link.inventory("mB").await.unwrap(); + assert_eq!(start(&before)["code"], "control_disabled"); + + let mut events = app(&b); + let mut asking = ask(&a, AccessWants::Control).await; + let id = request_id(&dialog(&mut events.events).await); + b.link.answer_access(&id, true, false).await.unwrap(); + assert_eq!(answer(&mut asking).await, result(AccessOutcome::Granted)); + + let after = a.link.inventory("mB").await.unwrap(); + assert!(after.rev > before.rev); + assert_eq!(start(&after), serde_json::json!({ "allowed": true })); +} + #[tokio::test] async fn a_target_that_does_not_share_refuses_with_not_shared() { let cloud = FakeCloud::start().await; diff --git a/src/daemon/remote/tests/control.rs b/src/daemon/remote/tests/control.rs new file mode 100644 index 0000000..f6bff46 --- /dev/null +++ b/src/daemon/remote/tests/control.rs @@ -0,0 +1,726 @@ +//! Remote controls end to end, between daemons in this process and the fake +//! relay: the PR 4 gates of `docs/remote-machines.md` for the reconnect, the +//! dropped frame, request entries, restarts, convergence and the legacy +//! relaunch. The target runs the real control executor and keeps its +//! request entries on disk; only its services are in memory (`FakeHost`). +//! The same gates against real processes are in `tests/remote_controls.rs`. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use tokio::sync::mpsc; +use tokio::time::Instant; + +use super::{Daemon, connected, launch, pair, two, wait_until}; +use crate::application::inventory::{ + EnvironmentRef, ProfileChecks, ProjectRef, RunFacts, RunOrigin, RunProcess, ServiceFacts, + ServiceRef, +}; +use crate::daemon::remote::fake_relay::{Bridge, FakeCloud, FakeService, Route, is_message}; +use crate::daemon::remote::{ControlAsk, ControlEvent}; +use crate::infrastructure::remote::control::Expected; +use crate::infrastructure::remote::store::SettingsChange; +use crate::infrastructure::remote::wire::{ + AppPresence, ControlAction, ControlExpect, ControlOutcome, ControlPhase, ControlService, + ProtoRange, +}; +use crate::infrastructure::runs::RunId; + +const REV: &str = "0123456789abcdef"; +const RUN: &str = "RRRRRRRRRRRRRRRRRRRRRR"; +const LEGACY: &str = "boot.4242.77"; + +fn facts(run: Option) -> ServiceFacts { + let running = run + .as_ref() + .is_some_and(|run| run.process == RunProcess::Running); + ServiceFacts { + project: ProjectRef { + id: "app".into(), + name: "App".into(), + }, + environment: EnvironmentRef { + slug: None, + name: "Primary".into(), + primary: true, + branch: None, + }, + service: ServiceRef { + id: "web".into(), + name: "web".into(), + config_rev: REV.into(), + }, + local_url: "https://web.localify".into(), + port: 4100, + reachable: Some(running), + run, + public_url: None, + profiles: ProfileChecks { + start: true, + restart: true, + }, + } +} + +fn run(origin: RunOrigin) -> RunFacts { + RunFacts { + run_id: Some(RUN.into()), + origin, + legacy: false, + has_stream: true, + process: RunProcess::Running, + started_at: "2026-11-09T09:00:00Z".into(), + profile: None, + profile_danger: false, + exit: None, + legacy_id: None, + } +} + +/// A legacy run of `origin`; proven when `proven`. +fn legacy(origin: RunOrigin, proven: bool) -> RunFacts { + RunFacts { + run_id: None, + legacy: true, + has_stream: false, + legacy_id: proven.then(|| LEGACY.to_string()), + process: if proven { + RunProcess::Running + } else { + RunProcess::Unproven + }, + ..run(origin) + } +} + +fn service(run: Option) -> FakeService { + let record_names = run + .as_ref() + .filter(|run| run.legacy) + .map(|_| LEGACY.to_string()); + FakeService { + facts: facts(run), + record_names, + } +} + +fn ask(action: ControlAction, run_id: Option<&str>) -> ControlAsk { + ControlAsk { + action, + service: ControlService { + project_id: "app".into(), + environment: None, + service_id: "web".into(), + }, + profile: None, + expect: ControlExpect { + run_id: run_id.map(str::to_string), + config_rev: REV.into(), + legacy_id: None, + }, + } +} + +fn relaunch() -> ControlAsk { + let mut ask = ask(ControlAction::Restart, None); + ask.expect.legacy_id = Some(LEGACY.into()); + ask +} + +fn request_id(n: u8) -> String { + format!("{}{n:02}", "q".repeat(20)) +} + +async fn switches(daemon: &Daemon, background_starts: bool) { + daemon + .link + .change_settings(SettingsChange { + share: Some(true), + control: Some(true), + background_starts: Some(background_starts), + }) + .await + .unwrap(); +} + +/// A views B, paired, with B sharing and allowing controls, its app +/// running, and `web` in the state `run` says. +async fn controlled(cloud: &FakeCloud, run: Option) -> (Daemon, Daemon) { + let (a, b) = two(cloud).await; + pair(&a, &b).await; + switches(&b, false).await; + b.source.set_app(AppPresence::Running); + b.source.host().state().services = vec![service(run)]; + (a, b) +} + +/// Every event of a control, up to its last. +async fn events(mut events: mpsc::Receiver) -> Vec { + let mut seen = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let event = tokio::time::timeout_at(deadline, events.recv()) + .await + .expect("the control ended in time"); + let Some(event) = event else { return seen }; + let last = matches!( + event, + ControlEvent::Result { .. } | ControlEvent::Lost { .. } + ); + seen.push(event); + if last { + return seen; + } + } +} + +/// The outcome and code a control ended with. +fn ended(events: &[ControlEvent]) -> (ControlOutcome, Option) { + match events.last() { + Some(ControlEvent::Result { outcome, code, .. }) => (*outcome, code.clone()), + other => panic!("no result: {events:?} ({other:?})"), + } +} + +async fn control(a: &Daemon, ask: ControlAsk) -> Vec { + events(a.link.control("mB", ask)).await +} + +fn handed(b: &Daemon) -> usize { + b.source.host().state().handed.len() +} + +fn stops(b: &Daemon) -> Vec { + b.source.host().state().stops.clone() +} + +/// Holds B's next launch once it reached the app: dropping or sending on +/// the result lets it go on. +fn hold(b: &Daemon) -> std::sync::mpsc::Sender<()> { + let (release, held) = std::sync::mpsc::channel(); + b.source.host().state().hold = Some(held); + release +} + +// --- Who acts ------------------------------------------------------------------ + +#[tokio::test] +async fn a_restart_of_an_app_run_goes_through_the_app_and_takes_its_place() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(run(RunOrigin::App))).await; + + let seen = control(&a, ask(ControlAction::Restart, Some(RUN))).await; + + assert!(matches!(seen[0], ControlEvent::Sent { .. }), "{seen:?}"); + let phases: Vec = seen + .iter() + .filter_map(|event| match event { + ControlEvent::Progress { phase } => Some(*phase), + _ => None, + }) + .collect(); + assert_eq!(phases, [ControlPhase::Dispatched, ControlPhase::Started]); + assert_eq!(ended(&seen), (ControlOutcome::Done, None)); + let host = b.source.host(); + let state = host.state(); + assert_eq!(state.stops, [Expected::Run(RunId::parse(RUN).unwrap())]); + assert_eq!(state.handed.len(), 1); + assert_eq!( + state.handed[0].replaces.as_ref().map(RunId::as_str), + Some(RUN) + ); + let requester = state.handed[0].requested_by.clone().unwrap(); + assert_eq!( + (requester.machine_id.as_str(), requester.name.as_str()), + ("mA", "laptop") + ); + assert!(state.detached.is_empty(), "never a background start"); +} + +#[tokio::test] +async fn a_start_with_the_app_closed_runs_detached_only_with_background_starts() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, None).await; + b.source.set_app(AppPresence::Absent); + + let refused = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!( + ended(&refused), + (ControlOutcome::Refused, Some("background_disabled".into())) + ); + + switches(&b, true).await; + let started = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!(ended(&started), (ControlOutcome::Done, None)); + let host = b.source.host(); + let state = host.state(); + assert_eq!((state.handed.len(), state.detached.len()), (0, 1)); + assert_eq!(state.detached[0].request_id.len(), 22); +} + +/// An app that closed before the launch reached it, or refused it, never +/// gets a background start in its place. +#[tokio::test] +async fn an_app_that_closed_or_refused_a_start_gets_nothing_in_its_place() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, None).await; + switches(&b, true).await; + + b.source.host().state().bridge = Bridge::Absent; + let closed = control(&a, ask(ControlAction::Start, None)).await; + let Some(ControlEvent::Result { + outcome, message, .. + }) = closed.last() + else { + panic!("{closed:?}") + }; + assert_eq!(*outcome, ControlOutcome::Failed); + assert!(message.contains("Nothing was started"), "{message}"); + + b.source.host().state().bridge = Bridge::Refuse("unknown_service"); + let refused = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!( + ended(&refused), + (ControlOutcome::Refused, Some("unknown_service".into())) + ); + assert!(b.source.host().state().detached.is_empty()); +} + +/// The gate: a restart of a background run with `backgroundStarts` off is +/// refused, and the run keeps running. +#[tokio::test] +async fn a_background_restart_without_background_starts_is_refused_and_keeps_running() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(run(RunOrigin::Background))).await; + + let seen = control(&a, ask(ControlAction::Restart, Some(RUN))).await; + + assert_eq!( + ended(&seen), + (ControlOutcome::Refused, Some("background_disabled".into())) + ); + assert!(stops(&b).is_empty(), "nothing was stopped"); + let still = b.source.host().service("web").run.unwrap(); + assert_eq!(still.process, RunProcess::Running); + assert_eq!(still.run_id.as_deref(), Some(RUN)); +} + +#[tokio::test] +async fn controls_are_refused_while_the_switches_or_the_lease_say_no() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, None).await; + b.link + .change_settings(SettingsChange { + control: Some(false), + ..SettingsChange::default() + }) + .await + .unwrap(); + let off = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!( + ended(&off), + (ControlOutcome::Refused, Some("control_disabled".into())) + ); + + switches(&b, false).await; + // The target asks for a fresh lease before each control, and fails + // closed. + cloud.set_lease(402, 60); + let lapsed = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!( + ended(&lapsed), + (ControlOutcome::Refused, Some("unauthorized".into())) + ); + assert_eq!(handed(&b), 0); +} + +/// One control per service at a time on the target: another one waits for +/// nothing and is refused `busy`. +#[tokio::test] +async fn a_second_control_of_a_service_in_flight_is_busy() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(run(RunOrigin::App))).await; + let release = hold(&b); + + let first = a.link.control("mB", ask(ControlAction::Restart, Some(RUN))); + wait_until("the restart reached the app", || handed(&b) == 1).await; + let second = control(&a, ask(ControlAction::Restart, Some(RUN))).await; + release.send(()).unwrap(); + + assert_eq!( + ended(&second), + (ControlOutcome::Refused, Some("busy".into())) + ); + assert_eq!(ended(&events(first).await), (ControlOutcome::Done, None)); + assert_eq!(handed(&b), 1); +} + +// --- Reconnects, dropped frames, request entries ------------------------------ + +/// The gate: the viewer's socket is cut right after it sends a restart, +/// and the same control is sent again on a new session, with the same and +/// with a new `requestId`. The service restarted once; the same request +/// gets the report of the first restart, and the new one `conflict`. +#[tokio::test] +async fn a_reconnect_cannot_repeat_a_restart() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(run(RunOrigin::App))).await; + let release = hold(&b); + + let first = a + .link + .control_as("mB", ask(ControlAction::Restart, Some(RUN)), request_id(1)); + wait_until("the restart reached the app", || handed(&b) == 1).await; + cloud.close("mA", 1012, "restart"); + release.send(()).unwrap(); + let seen = events(first).await; + + // Lost with the socket, then reconciled on a new session. + assert!( + seen.iter() + .any(|event| matches!(event, ControlEvent::Unknown { .. })), + "{seen:?}" + ); + assert_eq!(ended(&seen), (ControlOutcome::Done, None)); + let ControlEvent::Result { + run_id: first_run, .. + } = seen.last().unwrap() + else { + unreachable!() + }; + + let same = events(a.link.control_as( + "mB", + ask(ControlAction::Restart, Some(RUN)), + request_id(1), + )) + .await; + assert_eq!(ended(&same), (ControlOutcome::Done, None)); + let ControlEvent::Result { + run_id: same_run, .. + } = same.last().unwrap() + else { + unreachable!() + }; + assert_eq!(same_run, first_run, "the report of the first restart"); + + let new = events(a.link.control_as( + "mB", + ask(ControlAction::Restart, Some(RUN)), + request_id(2), + )) + .await; + assert_eq!( + ended(&new), + (ControlOutcome::Conflict, Some("conflict".into())) + ); + assert_eq!(handed(&b), 1, "restarted once"); + assert_eq!(stops(&b).len(), 1); +} + +/// The gate: the relay drops the frame carrying a control's answer; the +/// viewer reconciles with `control.status` on a new session, gets the exact +/// outcome, and never sends the control again. +#[tokio::test] +async fn a_dropped_frame_during_a_control_is_reconciled_and_never_resent() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(run(RunOrigin::App))).await; + let release = hold(&b); + let armed = Arc::new(AtomicBool::new(false)); + let dropping = Arc::clone(&armed); + cloud.set_hook(Some(Box::new(move |from, frame| { + if from == "mB" && is_message(frame) && dropping.swap(false, Ordering::SeqCst) { + Route::Drop("unavailable") + } else { + Route::Forward + } + }))); + + let pending = a.link.control("mB", ask(ControlAction::Restart, Some(RUN))); + wait_until("the restart reached the app", || handed(&b) == 1).await; + // The next frame of B's carries what follows the dispatch. + armed.store(true, Ordering::SeqCst); + release.send(()).unwrap(); + let seen = events(pending).await; + + assert!( + seen.iter() + .any(|event| matches!(event, ControlEvent::Unknown { .. })), + "{seen:?}" + ); + assert_eq!(ended(&seen), (ControlOutcome::Done, None)); + assert_eq!(handed(&b), 1, "never sent again"); + assert_eq!(stops(&b).len(), 1); +} + +/// The gate: a stop whose answer was lost is still correlated by +/// `control.status` after the target's daemon restarts, and the same +/// request id with another action gets `request_mismatch` and runs nothing. +#[tokio::test] +async fn request_entries_survive_a_daemon_restart_and_a_mismatch_runs_nothing() { + let cloud = FakeCloud::start().await; + let a = super::daemon(&cloud, "mA", "laptop").await; + let token = cloud.add_machine("mB", "teo-mini"); + let b = connected(launch( + &cloud, + "mB", + "teo-mini", + &token, + tempfile::tempdir().unwrap(), + )) + .await; + wait_until("both see each other", || a.sees("mB") && b.sees("mA")).await; + pair(&a, &b).await; + switches(&b, false).await; + b.source.set_app(AppPresence::Running); + b.source.host().state().services = vec![service(Some(run(RunOrigin::App)))]; + + let stopped = events(a.link.control_as( + "mB", + ask(ControlAction::Stop, Some(RUN)), + request_id(7), + )) + .await; + assert_eq!(ended(&stopped), (ControlOutcome::Done, None)); + + // B's daemon starts again on the same folder. + let copy = tempfile::tempdir().unwrap(); + copy_dir(b.dir.path(), copy.path()); + drop(b); + let b = connected(launch(&cloud, "mB", "teo-mini", &token, copy)).await; + wait_until("A sees B again", || a.sees("mB")).await; + + let status = a.link.control_status("mB", &request_id(7)).await; + assert!( + matches!( + status, + ControlEvent::Result { + outcome: ControlOutcome::Done, + .. + } + ), + "{status:?}" + ); + let mismatch = events( + a.link + .control_as("mB", ask(ControlAction::Start, None), request_id(7)), + ) + .await; + assert_eq!( + ended(&mismatch), + (ControlOutcome::Refused, Some("request_mismatch".into())) + ); + let unknown = a.link.control_status("mB", &request_id(8)).await; + assert!( + matches!(&unknown, ControlEvent::Result { code: Some(code), .. } if code == "unknown_request"), + "{unknown:?}" + ); + assert!(stops(&b).is_empty() && handed(&b) == 0, "nothing ran"); +} + +/// The gate: launch A starts and exits, a local launch B then replaces the +/// service's record, and the bridge's answer about A was lost. The target +/// still reports A as admitted and exited, with its code. +#[tokio::test] +async fn a_lost_acknowledgement_is_reported_exactly() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, None).await; + { + let host = b.source.host(); + let mut state = host.state(); + state.bridge = Bridge::Unanswered; + state.exit_code = Some(3); + } + let pending = a.link.control("mB", ask(ControlAction::Start, None)); + wait_until("the start reached the app", || handed(&b) == 1).await; + // A local launch takes the service over meanwhile. + b.source.host().change("web", |web| { + web.facts.run = Some(RunFacts { + run_id: Some("LLLLLLLLLLLLLLLLLLLLLL".into()), + ..run(RunOrigin::Terminal) + }); + }); + let seen = events(pending).await; + + let Some(ControlEvent::Result { + outcome, + message, + run_id, + .. + }) = seen.last() + else { + panic!("no result: {seen:?}") + }; + assert_eq!(*outcome, ControlOutcome::Failed); + assert!(message.contains("exited with code 3"), "{message}"); + let launched = b.source.host().state().handed[0].launch_id.to_string(); + assert_eq!(run_id.as_deref(), Some(launched.as_str()), "launch A"); +} + +// --- Convergence --------------------------------------------------------------- + +/// The gate: while A watches, the service is started from a terminal, +/// stopped, and its config edited. Each shows within 12 seconds, and a +/// control built on the old state gets `conflict`. +#[tokio::test] +async fn external_starts_and_config_changes_converge_and_an_old_control_conflicts() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, None).await; + let mut watch = a.link.watch("mB"); + shows(&mut watch, |item| item["owner"].is_null()).await; + + // Started from a terminal. + b.source.host().change("web", |web| { + web.facts.run = Some(run(RunOrigin::Terminal)); + web.facts.reachable = Some(true); + }); + shows(&mut watch, |item| item["owner"] == "terminal").await; + let old_start = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!(ended(&old_start).0, ControlOutcome::Conflict); + + // Stopped with `localify stop`. + b.source.host().change("web", |web| { + if let Some(run) = web.facts.run.as_mut() { + run.process = RunProcess::Stopped; + } + web.facts.reachable = Some(false); + }); + shows(&mut watch, |item| item["process"] == "stopped").await; + + // Its config edited. + b.source.host().change("web", |web| { + web.facts.service.config_rev = "fedcba9876543210".into(); + }); + shows(&mut watch, |item| { + item["service"]["configRev"] == "fedcba9876543210" + }) + .await; + let old_rev = control(&a, ask(ControlAction::Start, None)).await; + assert_eq!(ended(&old_rev).0, ControlOutcome::Conflict); + assert_eq!(handed(&b), 0); +} + +/// Waits for a snapshot whose first item `wanted` accepts, 12 s at most. +async fn shows( + watch: &mut mpsc::Receiver, + wanted: fn(&serde_json::Value) -> bool, +) { + let deadline = Instant::now() + Duration::from_secs(12); + loop { + let event = tokio::time::timeout_at(deadline, watch.recv()) + .await + .expect("it converged within 12 seconds") + .unwrap(); + if let crate::daemon::remote::viewing::WatchEvent::Snapshot(snapshot) = event + && wanted(&snapshot.items[0]) + { + return; + } + } +} + +// --- Relaunching a legacy run ------------------------------------------------- + +#[tokio::test] +async fn a_proven_legacy_run_is_relaunched_through_its_owner() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(legacy(RunOrigin::App, true))).await; + + let seen = control(&a, relaunch()).await; + + assert_eq!(ended(&seen), (ControlOutcome::Done, None)); + let host = b.source.host(); + let state = host.state(); + assert_eq!(state.stops, [Expected::Legacy(LEGACY.into())]); + assert_eq!(state.handed[0].replaces_legacy.as_deref(), Some(LEGACY)); + assert_eq!(state.handed[0].replaces, None, "a new tab"); + let web = state.services[0].facts.run.clone().unwrap(); + assert!(!web.legacy && web.run_id.is_some() && web.has_stream); +} + +/// The gate's refusals: each before anything stops. +#[tokio::test] +async fn a_legacy_relaunch_is_refused_before_anything_stops() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(legacy(RunOrigin::App, false))).await; + + // Its PID is not proven. + let unproven = control(&a, relaunch()).await; + assert_eq!(ended(&unproven).1.as_deref(), Some("legacy_run")); + + // The record names another run. + b.source.host().state().services = vec![FakeService { + record_names: Some("boot.1.1".into()), + ..service(Some(legacy(RunOrigin::App, true))) + }]; + let renamed = control(&a, relaunch()).await; + assert_eq!(ended(&renamed).0, ControlOutcome::Conflict); + + // The app is gone for an app run; background starts are off for a + // background one. + b.source.host().state().services = vec![service(Some(legacy(RunOrigin::App, true)))]; + b.source.set_app(AppPresence::Absent); + let gone = control(&a, relaunch()).await; + assert_eq!(ended(&gone).1.as_deref(), Some("owner_gone")); + b.source.host().state().services = vec![service(Some(legacy(RunOrigin::Background, true)))]; + let background = control(&a, relaunch()).await; + assert_eq!(ended(&background).1.as_deref(), Some("background_disabled")); + + // A control on it that is not a relaunch. + let stop = control(&a, ask(ControlAction::Stop, None)).await; + assert_eq!(ended(&stop).1.as_deref(), Some("legacy_run")); + + assert!(stops(&b).is_empty(), "nothing was signalled"); +} + +/// The gate: a local launch that replaces the record between the stop and +/// the dispatch wins, and the relaunch gets `conflict`. +#[tokio::test] +async fn a_local_launch_between_the_stop_and_the_relaunch_wins() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(legacy(RunOrigin::App, true))).await; + let release = hold(&b); + + let pending = a.link.control("mB", relaunch()); + wait_until("the relaunch reached the app", || handed(&b) == 1).await; + b.source.host().change("web", |web| { + web.record_names = None; + web.facts.run = Some(run(RunOrigin::Terminal)); + }); + release.send(()).unwrap(); + let seen = events(pending).await; + + assert_eq!( + ended(&seen), + (ControlOutcome::Conflict, Some("conflict".into())) + ); + let web = b.source.host().service("web").run.unwrap(); + assert_eq!(web.origin, RunOrigin::Terminal, "the local launch stays"); +} + +/// A target of protocol 1 knows no `legacyId`: the viewer never sends one. +#[tokio::test] +async fn a_relaunch_is_never_sent_to_a_target_of_protocol_1() { + let cloud = FakeCloud::start().await; + let (a, b) = controlled(&cloud, Some(legacy(RunOrigin::App, true))).await; + b.link.speak(ProtoRange { min: 1, max: 1 }); + + let seen = control(&a, relaunch()).await; + + assert_eq!(ended(&seen).1.as_deref(), Some("unsupported")); + assert!(stops(&b).is_empty() && handed(&b) == 0); +} + +/// Copies a daemon's folder, as it is left on disk. +fn copy_dir(from: &std::path::Path, to: &std::path::Path) { + for entry in std::fs::read_dir(from).unwrap().flatten() { + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + std::fs::create_dir_all(&target).unwrap(); + copy_dir(&entry.path(), &target); + } else if entry.file_type().unwrap().is_file() { + std::fs::copy(entry.path(), &target).unwrap(); + } + } +} diff --git a/src/daemon/remote/viewing.rs b/src/daemon/remote/viewing.rs index bd4264b..aff3729 100644 --- a/src/daemon/remote/viewing.rs +++ b/src/daemon/remote/viewing.rs @@ -1,9 +1,9 @@ //! Viewing another machine (`docs/remote-machines.md`, "Daemon"): what //! `remote_inventory`, `remote_watch`, `remote_output_read`, -//! `remote_output_follow` and `remote_access` ask a target for, over the -//! actor's one session to it. Everything that came from the target is shown -//! as plain text: control characters and bidirectional overrides are removed -//! here again, whatever the target sent. +//! `remote_output_follow`, `remote_access` and `remote_control` ask a target +//! for, over the actor's one session to it. Everything that came from the +//! target is shown as plain text: control characters and bidirectional +//! overrides are removed here again, whatever the target sent. use std::time::Duration; @@ -13,8 +13,10 @@ use tokio::sync::{mpsc, oneshot}; use super::actor::WINDOW; use super::{Command, Failure, RemoteLink, TapEvent, TapRequest, lease_refused}; +use crate::infrastructure::launch_rev::random_bytes; use crate::infrastructure::remote::wire::{ - AccessOutcome, AccessWants, Have, MachineSummary, OutputData, SessionMessage, + AccessOutcome, AccessWants, ControlAction, ControlExpect, ControlOutcome, ControlPhase, + ControlService, Have, MachineSummary, OutputData, SessionMessage, }; use crate::infrastructure::runs::output::plain_line; @@ -25,6 +27,10 @@ const TAP_EVENTS: usize = 256; const ANSWER_WAIT: Duration = Duration::from_secs(30); /// A follow acknowledges what its client showed once this much is unacked. const ACK_EVERY: u64 = WINDOW as u64 / 4; +/// How long a control waits for its result before it is `unknown`. +pub const CONTROL_WAIT: Duration = Duration::from_secs(120); +/// How long an `unknown` control keeps asking `control.status`. +const STATUS_WAIT: Duration = Duration::from_secs(60); /// A target's whole inventory: every page of one revision. #[derive(Debug, Clone, PartialEq, Serialize)] @@ -106,6 +112,60 @@ pub enum AccessEvent { Lost { code: String, message: String }, } +/// What `remote_control` is asked for: a control, as the viewer saw the +/// service. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ControlAsk { + pub action: ControlAction, + pub service: ControlService, + #[serde(default)] + pub profile: Option, + pub expect: ControlExpect, +} + +/// What `remote_control` streams: `sent`, its progress, then its result. +/// A session lost before the result is `unknown`, and the result comes from +/// `control.status` on a new session when it can be had, or `lost` says it +/// could not. A control is never sent again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde( + tag = "event", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum ControlEvent { + /// On its way, with the request id that names it on the target. + Sent { + request_id: String, + }, + Progress { + phase: ControlPhase, + }, + Result { + outcome: ControlOutcome, + code: Option, + message: String, + run_id: Option, + }, + /// No result came: the session was lost, or 120 s passed. Checking. + Unknown { + code: String, + message: String, + }, + /// The outcome could not be learned; the next snapshot shows the state. + Lost { + code: String, + message: String, + }, +} + +impl ControlEvent { + fn is_last(&self) -> bool { + matches!(self, Self::Result { .. } | Self::Lost { .. }) + } +} + /// An access request this machine waits on. Dropping it sends /// `access.cancel` when the target still waits. pub struct Asking { @@ -163,6 +223,49 @@ fn lost(failure: Failure) -> AccessEvent { } } +/// What a target's answer to a control says, as plain text. +fn control_answer(answer: SessionMessage) -> ControlEvent { + match answer { + SessionMessage::ControlProgress { phase, .. } => ControlEvent::Progress { phase }, + SessionMessage::ControlResult(result) => ControlEvent::Result { + outcome: result.outcome, + code: result.code.map(|code| plain_line(&code)), + message: plain_line(&result.message), + run_id: result.run_id.map(|run_id| plain_line(&run_id)), + }, + // A refusal before the executor, `unsupported` among them. + other => { + let failure = answered_with(other); + let outcome = if failure.code == "conflict" { + ControlOutcome::Conflict + } else { + ControlOutcome::Refused + }; + ControlEvent::Result { + outcome, + code: Some(failure.code), + message: plain_line(&failure.message), + run_id: None, + } + } + } +} + +fn lost_control(failure: Failure) -> ControlEvent { + ControlEvent::Lost { + code: failure.code, + message: plain_line(&failure.message), + } +} + +/// 16 random bytes, base64url: names one control across sessions. +fn new_request_id() -> Result { + use base64::Engine; + let mut bytes = [0_u8; 16]; + random_bytes(&mut bytes).map_err(|error| Failure::new("internal", format!("{error:#}")))?; + Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)) +} + /// Pages of one revision, until they are all in. Pages of an older revision /// are dropped; a newer one starts over. #[derive(Default)] @@ -539,6 +642,133 @@ impl RemoteLink { }) } + /// `remote_control`: sends the control once, then streams its progress + /// and result. When the session is lost first, or no result comes in + /// [`CONTROL_WAIT`], it says `unknown` and asks `control.status` on a + /// new session, never sending the control again. + pub fn control(&self, peer: &str, ask: ControlAsk) -> mpsc::Receiver { + match new_request_id() { + Ok(request_id) => self.control_as(peer, ask, request_id), + Err(failure) => { + let (sender, receiver) = mpsc::channel(1); + let _ = sender.try_send(lost_control(failure)); + receiver + } + } + } + + /// [`RemoteLink::control`] under a given request id, as a viewer that + /// sends the same control again would. + pub(super) fn control_as( + &self, + peer: &str, + ask: ControlAsk, + request_id: String, + ) -> mpsc::Receiver { + let (sender, receiver) = mpsc::channel(8); + let link = self.clone(); + let peer = peer.to_string(); + tokio::spawn(async move { + let lost = link.control_once(&peer, ask, &request_id, &sender).await; + let Some(failure) = lost else { return }; + let unknown = ControlEvent::Unknown { + code: failure.code, + message: plain_line(&failure.message), + }; + if sender.send(unknown).await.is_err() { + return; + } + let ended = link.control_status(&peer, &request_id).await; + let _ = sender.send(ended).await; + }); + receiver + } + + /// Sends the control and streams what the target says, until its + /// result. Returns the failure when no result came. + async fn control_once( + &self, + peer: &str, + ask: ControlAsk, + request_id: &str, + sender: &mpsc::Sender, + ) -> Option { + let request = TapRequest::Control { + action: ask.action, + service: ask.service, + profile: ask.profile, + request_id: request_id.to_string(), + expect: ask.expect, + }; + let (id, mut events) = match self.tap(peer, request).await { + Ok(tap) => tap, + // Never sent: nothing to reconcile. + Err(failure) => { + let _ = sender.send(lost_control(failure)).await; + return None; + } + }; + let sent = ControlEvent::Sent { + request_id: request_id.to_string(), + }; + if sender.send(sent).await.is_err() { + self.untap(peer, &id); + return None; + } + let deadline = tokio::time::Instant::now() + CONTROL_WAIT; + let failure = loop { + let event = tokio::select! { + _ = sender.closed() => break None, + event = tokio::time::timeout_at(deadline, events.recv()) => event, + }; + let event = match event { + Err(_) => break Some(Failure::new("timeout", "No result came in 120 seconds.")), + Ok(None) => break Some(closed()), + Ok(Some(TapEvent::Ended(failure))) => break Some(failure), + Ok(Some(TapEvent::Answer(answer))) => control_answer(answer), + }; + let last = event.is_last(); + if sender.send(event).await.is_err() || last { + break None; + } + }; + self.untap(peer, &id); + failure + } + + /// `control.status` for `request_id`, on a session of its own, tried + /// again while the target cannot be reached, for [`STATUS_WAIT`] at most. + pub(super) async fn control_status(&self, peer: &str, request_id: &str) -> ControlEvent { + let deadline = tokio::time::Instant::now() + STATUS_WAIT; + let mut wait = Duration::from_millis(500); + loop { + let failure = match self.status_once(peer, request_id).await { + Ok(event) => return event, + Err(failure) => failure, + }; + if tokio::time::Instant::now() + wait >= deadline { + return lost_control(failure); + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(8)); + } + } + + async fn status_once(&self, peer: &str, request_id: &str) -> Result { + let request = TapRequest::ControlStatus { + request_id: request_id.to_string(), + }; + let (id, mut events) = self.tap(peer, request).await?; + let answer = tokio::time::timeout(ANSWER_WAIT, events.recv()).await; + self.untap(peer, &id); + match answer { + Ok(Some(TapEvent::Answer(answer))) => Ok(control_answer(answer)), + Ok(Some(TapEvent::Ended(failure))) => Err(failure), + Ok(None) => Err(closed()), + Err(_) => Err(Failure::new("timeout", "The machine did not answer.")), + } + } + /// `remote_output_read`: one bounded read. pub async fn read_output( &self, diff --git a/src/desktop/app_bridge.rs b/src/desktop/app_bridge.rs index 0d68d9b..68ed741 100644 --- a/src/desktop/app_bridge.rs +++ b/src/desktop/app_bridge.rs @@ -177,6 +177,7 @@ fn launch_in_tab( id: request.launch_id, expires_at: request.expires_at, replaces: request.replaces, + replaces_legacy: request.replaces_legacy, remote: match (&request.requested_by, request.expect_rev) { (Some(requester), Some(expect_rev)) => Some(RemoteLaunch { expect_rev, @@ -305,11 +306,18 @@ fn parse(line: &str) -> Result { /// Refuses what this app cannot run, before anything is spawned. fn validate(launch: &LaunchRequest, now: u64) -> Result<(), BridgeError> { - if launch.replaces_legacy.is_some() { - return Err(error( - "unsupported", - "This version of Localify cannot relaunch a run started before run PTYs. Update Localify.", - )); + if let Some(legacy_id) = &launch.replaces_legacy { + let shaped = (1..=128).contains(&legacy_id.len()) + && legacy_id.split('.').count() >= 3 + && legacy_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-.".contains(&byte)); + if !shaped || launch.replaces.is_some() || launch.requested_by.is_none() { + return Err(error( + "bad_request", + "replacesLegacy names a legacy run (..) for a remote relaunch, without replaces.", + )); + } } if launch.expires_at <= now { return Err(error( @@ -801,10 +809,17 @@ mod tests { local.requested_by = None; local.expect_rev = None; assert!(validate(&local, now).is_ok()); - assert_eq!( - refused(|request| request.replaces_legacy = Some("boot.1.2".into())), - "unsupported" - ); + let mut relaunch = launch(); + relaunch.replaces_legacy = Some("6E0C1F4A-0B6D-4C5E-9F3A-1D2B3C4D5E6F.42.7".into()); + assert!(validate(&relaunch, now).is_ok()); + for legacy_id in ["boot", "../x.1.2", ""] { + let mut request = launch(); + request.replaces_legacy = Some(legacy_id.into()); + assert_eq!(validate(&request, now).unwrap_err().code, "bad_request"); + } + let mut both = relaunch.clone(); + both.replaces = Some(RunId::generate().unwrap()); + assert_eq!(validate(&both, now).unwrap_err().code, "bad_request"); assert_eq!(refused(|request| request.expires_at = 1), "expired"); assert_eq!( refused(|request| request.expires_at = u64::MAX), @@ -842,16 +857,12 @@ mod tests { } #[test] - fn a_refused_legacy_relaunch_reaches_the_client_as_unsupported() { + fn a_legacy_relaunch_reaches_the_launcher() { let (_dir, bridge, launched) = bridge(); let mut request = launch(); request.replaces_legacy = Some("boot.1.2".into()); - let Handoff::Refused(refusal) = client::launch(bridge.path(), &request) else { - panic!("a legacy relaunch was not refused"); - }; - - assert_eq!(refusal.code, "unsupported"); - assert!(launched.lock().unwrap().is_empty()); + assert_eq!(client::launch(bridge.path(), &request), Handoff::Accepted); + assert_eq!(*launched.lock().unwrap(), vec![request]); } } diff --git a/src/desktop/dto.rs b/src/desktop/dto.rs index 5c29dbd..8db15ac 100644 --- a/src/desktop/dto.rs +++ b/src/desktop/dto.rs @@ -1757,4 +1757,47 @@ pub enum RemoteStreamRequest { machine_id: String, wants: RemoteAccessWants, }, + /// Starts, stops or restarts a service on another machine, as this + /// machine last saw it, then its progress and result. Closing the + /// stream stops listening; the control goes on there. Unused by the + /// window until PR 4d adds the buttons. + Control { + machine_id: String, + action: RemoteControlAction, + service: RemoteControlService, + /// Start only: a launch profile, `None` for the default. + #[serde(default)] + profile: Option, + expect: RemoteControlExpect, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RemoteControlAction { + Start, + Stop, + Restart, +} + +/// The service a control names, by its ids. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemoteControlService { + pub project_id: String, + /// `None` for the primary checkout. + #[serde(default)] + pub environment: Option, + pub service_id: String, +} + +/// What the snapshot showed when the person clicked. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemoteControlExpect { + pub run_id: Option, + pub config_rev: String, + /// A relaunch: the legacy run the snapshot showed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legacy_id: Option, } diff --git a/src/desktop/remote.rs b/src/desktop/remote.rs index 8599596..792a464 100644 --- a/src/desktop/remote.rs +++ b/src/desktop/remote.rs @@ -128,6 +128,20 @@ impl DesktopApi { "machineId": machine_id, "wants": wants, }), + RemoteStreamRequest::Control { + machine_id, + action, + service, + profile, + expect, + } => json!({ + "cmd": "remote_control", + "machineId": machine_id, + "action": action, + "service": service, + "profile": profile, + "expect": expect, + }), }; self.daemon()?.remote_stream(&command).map_err(daemon_error) } diff --git a/src/desktop/run_pty.rs b/src/desktop/run_pty.rs index c99a4f8..bc76b84 100644 --- a/src/desktop/run_pty.rs +++ b/src/desktop/run_pty.rs @@ -78,6 +78,10 @@ pub struct RunLaunch { /// replaced it, and starts nothing when someone else restarted the /// service meanwhile. pub replaces: Option, + /// The legacy run a remote relaunch replaces, which its dispatcher + /// stopped: `--replace-legacy=`. The executor starts only + /// while the service's record still names it. + pub replaces_legacy: Option, /// Set for a launch a paired machine asked for. pub remote: Option, } @@ -98,6 +102,7 @@ impl RunLaunch { id: RunId::generate()?, expires_at: dispatch_expiry(), replaces, + replaces_legacy: None, remote: None, }) } @@ -121,6 +126,9 @@ impl RunLaunch { if let Some(replaces) = &self.replaces { args.push(format!("--replace={replaces}")); } + if let Some(legacy_id) = &self.replaces_legacy { + args.push(format!("--replace-legacy={legacy_id}")); + } args.into_iter().map(OsString::from).collect() } } @@ -847,6 +855,7 @@ mod tests { id: id.clone(), expires_at: 42, replaces: Some(replaced.clone()), + replaces_legacy: None, remote: None, }; assert_eq!( @@ -863,6 +872,7 @@ mod tests { id, expires_at: 42, replaces: None, + replaces_legacy: Some("boot.42.7".into()), remote: Some(RemoteLaunch { expect_rev: "0123456789abcdef".into(), requested_by: RequestedBy::parse("machine-a:req-1").unwrap(), @@ -875,6 +885,7 @@ mod tests { "--expect-rev=0123456789abcdef", "--request=machine-a:req-1", "--launch-expires=42", + "--replace-legacy=boot.42.7", ] .map(OsString::from) ); diff --git a/src/infrastructure/app_bridge.rs b/src/infrastructure/app_bridge.rs index fdb9827..e2cbf04 100644 --- a/src/infrastructure/app_bridge.rs +++ b/src/infrastructure/app_bridge.rs @@ -86,8 +86,8 @@ pub struct LaunchRequest { /// `--replace=`, once its dispatcher stopped it. `None` opens a /// new tab. pub replaces: Option, - /// A legacy run's `legacyId`, for a relaunch. The executor does not take - /// `--replace-legacy` yet, so the app refuses one with `unsupported`. + /// A legacy run's `legacyId`, for a relaunch its dispatcher stopped it + /// for: `--replace-legacy`, in a new tab. #[serde(default)] pub replaces_legacy: Option, /// The paired machine that asked: a remote launch, run with diff --git a/src/infrastructure/inventory.rs b/src/infrastructure/inventory.rs index 2bb974d..3712651 100644 --- a/src/infrastructure/inventory.rs +++ b/src/infrastructure/inventory.rs @@ -19,9 +19,9 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use crate::application::inventory::{ - AppPresence, Context, EnvironmentRef, ProfileChecks, ProjectRef, PublicUrlFacts, - PublicUrlState as UrlState, Revisions, RunExit, RunFacts, RunOrigin, RunProcess, ServiceFacts, - ServiceRef, Snapshot, TargetSettings, inventory_item, + Context, EnvironmentRef, ProfileChecks, ProjectRef, PublicUrlFacts, PublicUrlState as UrlState, + Revisions, RunExit, RunFacts, RunOrigin, RunProcess, ServiceFacts, ServiceRef, Snapshot, + Switches, inventory_item, }; use crate::domain::RouteTarget; use crate::infrastructure::cloud::types::{PublicUrl, PublicUrlState}; @@ -124,6 +124,20 @@ impl LocalInventory { &self.data_dir } + /// The config the daemon loads. + pub fn config_path(&self) -> &Path { + &self.config_path + } + + /// Where the run records are: the user's own `services/` unless a test + /// gave another. + pub fn services_dir(&self) -> PathBuf { + self.services_dir + .clone() + .or_else(|| RunningServiceStore::default_dir().ok()) + .unwrap_or_default() + } + /// Reads run records from `dir` instead of the user's `services/`. #[cfg(test)] pub fn with_services_dir(mut self, dir: PathBuf) -> Self { @@ -134,14 +148,13 @@ impl LocalInventory { /// A fresh snapshot, numbered: the revision only moves when its content /// changed. One build runs at a time: a request that arrives during one /// waits for it and shares its snapshot. `project_roots` are the local - /// checkouts the app knows, as `localify dev` reads them. The control - /// executor comes with PR 4c, so until then every control is off, - /// whatever the `control` switch says, and the app counts as absent for - /// the controls; `machine.app` on the pages comes from the app bridge. + /// checkouts the app knows, as `localify dev` reads them; `switches`, the + /// target settings and whether the app runs, decide the controls. pub fn snapshot( &self, public: &PublicFacts, project_roots: &HashMap, + switches: Switches, ) -> Result { let seen = self.built.load(Ordering::SeqCst); let _building = lock(&self.building); @@ -150,7 +163,7 @@ impl LocalInventory { { return Ok(last); } - let snapshot = self.build(public, project_roots)?; + let snapshot = self.build(public, project_roots, switches)?; *lock(&self.last) = Some(snapshot.clone()); self.built.fetch_add(1, Ordering::SeqCst); Ok(snapshot) @@ -160,6 +173,7 @@ impl LocalInventory { &self, public: &PublicFacts, project_roots: &HashMap, + switches: Switches, ) -> Result { let config = ConfigStore::new(self.config_path.clone()).load()?; let store = match &self.services_dir { @@ -168,8 +182,8 @@ impl LocalInventory { }; let key = LaunchRevKey::load_or_create(&self.data_dir)?; let context = Context { - settings: TargetSettings::default(), - app: AppPresence::Absent, + settings: switches.settings, + app: switches.app, tunnel_connected: public.tunnel_connected, }; let observed = Observed { @@ -235,6 +249,73 @@ pub fn gather(observed: &Observed<'_>) -> Result> { .collect() } +/// One service as a control looks at it before it acts: its facts from the +/// same sources as a snapshot's, its own port alone probed, with its run +/// record and the launch profiles of its checkout. +pub struct Looked { + pub facts: ServiceFacts, + pub key: ServiceKey, + pub record: Option, + pub profiles: Result>, +} + +/// The service a control names, by its ids, with `environment` `None` for +/// the primary checkout; `None` when the config names no such service with +/// a proxy target. +pub fn look_up( + config: &Config, + store: &RunningServiceStore, + key: &LaunchRevKey, + project_roots: &HashMap, + wanted: &ServiceKey, +) -> Result> { + let Some(placed) = place_services(config, project_roots) + .into_iter() + .find(|placed| { + placed.service.project_id == wanted.project_id + && placed.service.id == wanted.service_id + && match &wanted.environment { + None => placed.environment.primary, + Some(slug) => placed.environment.slug == *slug, + } + }) + else { + return Ok(None); + }; + let probes = ProbeGauge::default(); + let reachable = probe_ports(BTreeSet::from([placed.port]), PROBE_DEADLINE, &probes) + .get(&placed.port) + .copied(); + let launch = DevLaunch::resolve(placed.service.clone(), placed.port); + let profiles = + load_profiles(profiles_root(&placed.service, launch.plan.as_ref().ok()).as_deref()); + let service_key = key_of(&placed); + let record = store.get(&service_key)?; + let public = PublicFacts::default(); + let observed = Observed { + config, + store, + key, + public: &public, + project_roots, + probes: &probes, + }; + let facts = service_facts( + placed, + reachable, + &launch, + &profiles, + record.as_ref(), + &observed, + )?; + Ok(Some(Looked { + facts, + key: service_key, + record, + profiles, + })) +} + /// Every service of the primary checkout, as `localify dev` runs it without /// `--env`, and the services each other environment maps, each with the /// local checkout the app knows when the config's is gone. @@ -369,6 +450,7 @@ fn run_facts( at: rfc3339(exit.at), code: exit.code, }), + legacy_id: record.legacy_id(), } } @@ -556,7 +638,9 @@ mod tests { use std::net::TcpListener; use super::*; - use crate::application::inventory::{OutputReason, Owner, ProcessState, Refusal}; + use crate::application::inventory::{ + AppPresence, OutputReason, Owner, ProcessState, Refusal, TargetSettings, + }; use crate::infrastructure::process; use crate::infrastructure::running_services::{RunIdentity, RunOutput}; use crate::infrastructure::runs::RunId; @@ -882,7 +966,11 @@ domain = "web.feature.localify" .with_services_dir(machine.path("services")); let snapshot = inventory - .snapshot(&PublicFacts::default(), &HashMap::new()) + .snapshot( + &PublicFacts::default(), + &HashMap::new(), + Switches::default(), + ) .unwrap(); assert_eq!(snapshot.items.len(), 2); @@ -891,9 +979,29 @@ domain = "web.feature.localify" && item.controls.restart.code == Some(Refusal::ControlDisabled) })); let again = inventory - .snapshot(&PublicFacts::default(), &HashMap::new()) + .snapshot( + &PublicFacts::default(), + &HashMap::new(), + Switches::default(), + ) .unwrap(); assert_eq!(again.rev, 1); + + // Turned on, with the app running: a start is allowed, and the + // revision moves with the controls. + let on = Switches { + settings: TargetSettings { + share: true, + control: true, + background_starts: false, + }, + app: AppPresence::Running, + }; + let allowed = inventory + .snapshot(&PublicFacts::default(), &HashMap::new(), on) + .unwrap(); + assert!(allowed.items.iter().all(|item| item.controls.start.allowed)); + assert_eq!(allowed.rev, 2); } #[test] @@ -1098,7 +1206,11 @@ target = "127.0.0.1:{port}" .map(|_| { scope.spawn(|| { inventory - .snapshot(&PublicFacts::default(), &HashMap::new()) + .snapshot( + &PublicFacts::default(), + &HashMap::new(), + Switches::default(), + ) .unwrap() }) }) diff --git a/src/infrastructure/remote/control.rs b/src/infrastructure/remote/control.rs new file mode 100644 index 0000000..4f37feb --- /dev/null +++ b/src/infrastructure/remote/control.rs @@ -0,0 +1,1110 @@ +//! The control executor on a target (`docs/remote-machines.md`, "Controls"; +//! ADR 0031): checks 4 to 9 of "Target checks", "Who acts", and the state +//! machine of one control, from its request entry to its result. The +//! daemon's actor makes checks 1 to 3 (the pin and `hello`, the switches, a +//! fresh lease) before it hands a control here, off its own task: everything +//! here blocks. +//! +//! What a control sees and does on this machine goes through [`Host`]: the +//! daemon's own config, run records, app bridge and executable +//! ([`LocalHost`]), or a fake in tests. The decisions, the request entries and +//! the timing are this module's, whatever the host. + +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::io; +use std::net::{Ipv4Addr, SocketAddr, TcpStream}; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread; +use std::time::{Duration, Instant}; + +use anyhow::{Context as _, Result, anyhow}; + +use super::requests::{ + Fingerprint, LinkedLaunch, Published, Report, RequestEntries, RequestEntry, Stopped, Via, +}; +use super::wire::{Control, ControlAction, ControlOutcome, ControlPhase}; +use crate::application::inventory::{ + AppPresence, Context, RunFacts, RunOrigin, RunProcess, ServiceFacts, Switches, inventory_item, +}; +use crate::branding::BRANDING; +use crate::infrastructure::app_bridge::{self, Handoff, LaunchRequest, Requester, ServiceRef}; +use crate::infrastructure::config::ConfigStore; +use crate::infrastructure::inventory::look_up; +use crate::infrastructure::launch_profiles::allowed_remotely; +use crate::infrastructure::launch_rev::LaunchRevKey; +use crate::infrastructure::process::NativeProcesses; +use crate::infrastructure::running_services::{ + RunningServiceStore, SERVICE_ORIGIN_ENV, ServiceKey, +}; +use crate::infrastructure::runs::RunId; +use crate::infrastructure::runs::launches::{ + ExitReason, LaunchReport, RefusalCode, reconcile, unix_ms_now, +}; +use crate::infrastructure::runs::output; +use crate::infrastructure::shell_env::Environment; + +/// How many of a failed run's last lines its result carries. +const FAILURE_LINES: usize = 40; + +const EXPIRED: &str = "The request took too long to reach this machine. Nothing was started."; +const BUSY: &str = "Something else is starting or stopping this service here."; +const CHANGED: &str = "The service changed since it was looked at."; + +/// The contract's delays. Tests shorten them. +#[derive(Debug, Clone, Copy)] +pub struct ControlTimings { + /// A launch expires this long after it is dispatched. + pub dispatch_budget: Duration, + /// A started run has this long, from its admission, to listen. + pub settle: Duration, + /// How often a launch's record and its port are looked at. + pub poll: Duration, + /// A control's `expiresAt` may be at most this far ahead. + pub ahead: Duration, +} + +impl Default for ControlTimings { + fn default() -> Self { + Self { + dispatch_budget: Duration::from_secs(15), + settle: Duration::from_secs(90), + poll: Duration::from_millis(250), + ahead: Duration::from_secs(60), + } + } +} + +/// A control from a peer, once the actor checked who sent it. +#[derive(Debug, Clone)] +pub struct Order { + /// The peer's machine id. + pub peer: String, + /// Its name as this machine pinned it, for "Started by" in the app. + pub peer_name: String, + pub control: Control, +} + +/// One service, as a control looks at it right before it acts. +#[derive(Debug, Clone)] +pub struct Look { + pub facts: ServiceFacts, + /// Its record's key: the environment's slug, the primary's included. + pub key: ServiceKey, + /// Whether the profile a start names may be launched remotely. + pub profile_allowed: bool, + /// Whether the service's record still names the legacy run the control + /// expects, proven or not. + pub names_legacy: bool, +} + +/// The run a stop ends, as the control expects it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Expected { + Run(RunId), + Legacy(String), +} + +/// A start the daemon spawns itself, with the app closed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DetachedLaunch { + pub launch_id: RunId, + /// Unix milliseconds. + pub expires_at: u64, + pub key: ServiceKey, + pub profile: Option, + pub expect_rev: String, + pub machine_id: String, + pub request_id: String, + pub replaces: Option, + pub replaces_legacy: Option, +} + +/// A detached start's process, until its launch is decided. +pub trait Spawned: Send { + /// Once the launch is decided: an `expired` one has its process's + /// session killed, an admitted one is left running. Either way the + /// process is reaped. + fn settle(self: Box, admitted: bool); +} + +/// What a control sees and does on this machine. +pub trait Host: Send + Sync { + /// The service `wanted` names, `environment` `None` for the primary + /// checkout, or `None` when the config has no such service. + fn look( + &self, + wanted: &ServiceKey, + profile: Option<&str>, + legacy_id: Option<&str>, + ) -> Result>; + /// Ends the run `expected` names, checked again right before it is + /// signalled, and returns once it has ended. A run that changed is + /// refused with its report. + fn stop(&self, key: &ServiceKey, expected: &Expected) -> Result<(), Report>; + /// Hands a launch to the app, once. + fn launch_in_app(&self, request: &LaunchRequest) -> Handoff; + fn launch_detached(&self, launch: &DetachedLaunch) -> Result>; + /// What happened to a launch, from its record. With `expires_at` + /// passed and no record, `expired` is published first. + fn report(&self, launch_id: &RunId, expires_at: Option) -> Result; + fn listens(&self, port: u16) -> bool; + /// The last lines a run printed, for a failure. + fn last_lines(&self, run_id: &RunId, count: usize) -> String; +} + +/// Runs the controls of this machine's peers, one per service at a time. +pub struct ControlRunner { + host: Arc, + entries: RequestEntries, + timings: ControlTimings, + /// The services with a control in flight. + busy: Mutex>, + /// The requests being worked on, by peer and request id. + working: Mutex>, +} + +/// What a control goes on to do once every check passed. +struct Plan { + stop: Option, + launch: Option, +} + +/// Where a launch went. +enum Handed { + App { unanswered: bool }, + Detached(Box), +} + +struct Dispatch { + via: Via, + profile: Option, + replaces: Option, + replaces_legacy: Option, +} + +impl ControlRunner { + pub fn new(host: Arc, entries: RequestEntries, timings: ControlTimings) -> Self { + Self { + host, + entries, + timings, + busy: Mutex::new(HashSet::new()), + working: Mutex::new(HashSet::new()), + } + } + + /// Runs one control, from check 4 on: a request already recorded is + /// never run again, and gets its report. `switches` reads the settings + /// and the app as they are now; `progress` hears `dispatched` and + /// `started`. Returns the result. + pub fn run( + &self, + order: &Order, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report { + let (peer, request_id) = (&order.peer, &order.control.request_id); + let fingerprint = Fingerprint::of(&order.control); + match self.entries.read(peer, request_id) { + Ok(Some(entry)) => return self.again(peer, request_id, &entry, &fingerprint), + Ok(None) => {} + Err(error) => return unavailable(&error), + } + // Published before anything changes, so every outcome from here on, + // a refusal included, is linked to it. + let entry = RequestEntry::new(fingerprint.clone(), unix_ms_now()); + let _working = Held::enter(&self.working, (peer.clone(), request_id.clone())); + match self.entries.publish(peer, request_id, &entry) { + Ok(Published::New) => {} + Ok(Published::Existing(entry)) => { + return self.again(peer, request_id, &entry, &fingerprint); + } + Err(error) => return unavailable(&error), + } + let report = self.fresh(order, switches, progress); + if report.is_final() { + let _ = self.entries.update(peer, request_id, |entry| { + entry.result = Some(report.clone()); + }); + } + report + } + + /// `control.status`: the entry's report, without running anything. + pub fn status(&self, peer: &str, request_id: &str) -> Report { + match self.entries.read(peer, request_id) { + Ok(Some(entry)) => self.report_entry(peer, request_id, &entry), + Ok(None) => Report::refused( + "unknown_request", + "This machine has no record of that request.", + ), + Err(error) => unavailable(&error), + } + } + + /// A request id that already has an entry: the same control gets its + /// report, another one `request_mismatch`. + fn again( + &self, + peer: &str, + request_id: &str, + entry: &RequestEntry, + fingerprint: &Fingerprint, + ) -> Report { + if entry.fingerprint != *fingerprint { + return Report::refused( + "request_mismatch", + "This request doesn't match the one this machine recorded.", + ); + } + self.report_entry(peer, request_id, entry) + } + + fn report_entry(&self, peer: &str, request_id: &str, entry: &RequestEntry) -> Report { + if let Some(result) = &entry.result { + return result.clone(); + } + if let Some(launch) = &entry.launch { + return self.launch_report(launch, &entry.fingerprint.service.service_id); + } + let working = lock(&self.working).contains(&(peer.to_string(), request_id.to_string())); + if working { + return Report::new( + ControlOutcome::Unknown, + None, + "This machine is still working on it.", + ); + } + match &entry.stopped { + Some(_) => Report::new(ControlOutcome::Done, None, "Stopped."), + None => Report::new( + ControlOutcome::Failed, + None, + "Localify restarted on this machine before the request finished. Look at the service, then try again.", + ), + } + } + + /// Checks 5 to 9, then who acts. + fn fresh( + &self, + order: &Order, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report { + let control = &order.control; + if let Err(report) = self.check_expiry(&control.expires_at) { + return report; + } + if let Err(report) = check_arguments(control) { + return report; + } + let wanted = ServiceKey { + project_id: control.service.project_id.clone(), + environment: control.service.environment.clone(), + service_id: control.service.service_id.clone(), + }; + let look = match self.host.look( + &wanted, + control.profile.as_deref(), + control.expect.legacy_id.as_deref(), + ) { + Ok(Some(look)) => look, + Ok(None) => { + return Report::refused( + "unknown_service", + "This service no longer exists on this machine.", + ); + } + Err(error) => return unavailable(&error), + }; + if control.action == ControlAction::Start && !look.profile_allowed { + return refused_profile(control.profile.as_deref()); + } + let Some(_busy) = Held::enter(&self.busy, look.key.clone()) else { + return Report::refused("busy", BUSY); + }; + if let Err(report) = state_matches(control, &look) { + return report; + } + let plan = match self.owner_allows(control, &look, switches()) { + Ok(plan) => plan, + Err(report) => return report, + }; + self.execute(order, &look, plan, switches, progress) + } + + /// Check 5: not past `expiresAt` in this machine's clock, and at most + /// 60 seconds ahead. + fn check_expiry(&self, expires_at: &str) -> Result<(), Report> { + let Some(expires) = rfc3339_ms(expires_at) else { + return Err(Report::refused( + "bad_request", + format!("'{expires_at}' is not an RFC 3339 time."), + )); + }; + let now = unix_ms_now(); + let ahead = u64::try_from(self.timings.ahead.as_millis()).unwrap_or(u64::MAX); + if now >= expires || expires > now.saturating_add(ahead) { + return Err(Report::refused("expired", EXPIRED)); + } + Ok(()) + } + + /// Check 9 and "Who acts": the owner allows it, the replacement of a + /// restart included, all decided before anything stops. + fn owner_allows( + &self, + control: &Control, + look: &Look, + switches: Switches, + ) -> Result { + let context = Context { + settings: switches.settings, + app: switches.app, + tunnel_connected: false, + }; + let controls = inventory_item(look.facts.clone(), &context).controls; + let allowed = match control.action { + ControlAction::Start => controls.start, + ControlAction::Stop => controls.stop, + ControlAction::Restart => controls.restart, + }; + if let Some(code) = allowed.code.filter(|_| !allowed.allowed) { + return Err(Report::refused(code.code(), refusal_message(code.code()))); + } + let run = look.facts.run.as_ref(); + let expected = match ( + &control.expect.legacy_id, + run.and_then(|run| run.run_id.as_ref()), + ) { + (Some(legacy_id), _) => Some(Expected::Legacy(legacy_id.clone())), + (None, Some(run_id)) => Some(Expected::Run( + RunId::parse(run_id).map_err(|error| unavailable(&error))?, + )), + (None, None) => None, + }; + Ok(plan(control, run, expected, switches.app)) + } + + fn execute( + &self, + order: &Order, + look: &Look, + plan: Plan, + switches: &dyn Fn() -> Switches, + progress: &mut dyn FnMut(ControlPhase), + ) -> Report { + let (peer, request_id) = (&order.peer, &order.control.request_id); + // A switch turned off since the checks: nothing new starts. + let now = switches().settings; + if !(now.share && now.control) { + return Report::refused("control_disabled", refusal_message("control_disabled")); + } + progress(ControlPhase::Dispatched); + if let Some(expected) = &plan.stop { + if let Err(report) = self.host.stop(&look.key, expected) { + return report; + } + let stopped = Stopped { + run_id: match expected { + Expected::Run(run_id) => Some(run_id.to_string()), + Expected::Legacy(_) => None, + }, + legacy_id: match expected { + Expected::Legacy(legacy_id) => Some(legacy_id.clone()), + Expected::Run(_) => None, + }, + at: unix_ms_now(), + }; + let _ = self.entries.update(peer, request_id, |entry| { + entry.stopped = Some(stopped); + }); + } + let Some(dispatch) = plan.launch else { + return Report::new(ControlOutcome::Done, None, "Stopped."); + }; + match self.dispatch(order, look, dispatch, progress) { + Ok(report) => report, + Err(error) => Report::new( + ControlOutcome::Failed, + None, + format!("The service could not be started: {error:#}"), + ), + } + } + + /// Hands the launch to its owner, with an id and an expiry fixed now, + /// then follows it: its decision, until the expiry at most, then its + /// settling. It is never handed to anyone else. + fn dispatch( + &self, + order: &Order, + look: &Look, + dispatch: Dispatch, + progress: &mut dyn FnMut(ControlPhase), + ) -> Result { + let control = &order.control; + let launch_id = RunId::generate()?; + let budget = u64::try_from(self.timings.dispatch_budget.as_millis()).unwrap_or(u64::MAX); + let expires_at = unix_ms_now().saturating_add(budget); + let linked = LinkedLaunch { + id: launch_id.clone(), + expires_at, + via: dispatch.via, + port: look.facts.port, + }; + self.entries + .update(&order.peer, &control.request_id, |entry| { + entry.launch = Some(linked.clone()); + })?; + let handed = match self.hand_off(order, look, dispatch, &linked)? { + Ok(handed) => handed, + Err(report) => return Ok(report), + }; + let (spawned, unanswered) = match handed { + Handed::App { unanswered } => (None, unanswered), + Handed::Detached(spawned) => (Some(spawned), false), + }; + let decision = if unanswered { + self.after_expiry(&linked.id, linked.expires_at) + } else { + self.decision(&linked.id, linked.expires_at) + }; + let admitted = matches!( + decision, + Ok(LaunchReport::Starting | LaunchReport::Running | LaunchReport::Exited { .. }) + | Ok(LaunchReport::Replaced { .. }) + ); + if let Some(spawned) = spawned { + spawned.settle(admitted); + } + match decision? { + LaunchReport::Starting | LaunchReport::Running => { + progress(ControlPhase::Started); + Ok(self.settle(&linked, &look.key.service_id)) + } + other => Ok(self.describe(other, &linked, &look.key.service_id)), + } + } + + /// Hands the launch to the app, or spawns it detached, once. A launch + /// that cannot have started is answered at once. + fn hand_off( + &self, + order: &Order, + look: &Look, + dispatch: Dispatch, + linked: &LinkedLaunch, + ) -> Result> { + let request_id = order.control.request_id.clone(); + if dispatch.via == Via::Background { + let spawned = self.host.launch_detached(&DetachedLaunch { + launch_id: linked.id.clone(), + expires_at: linked.expires_at, + key: look.key.clone(), + profile: dispatch.profile, + expect_rev: look.facts.service.config_rev.clone(), + machine_id: order.peer.clone(), + request_id, + replaces: dispatch.replaces, + replaces_legacy: dispatch.replaces_legacy, + })?; + return Ok(Ok(Handed::Detached(spawned))); + } + let request = LaunchRequest { + launch_id: linked.id.clone(), + expires_at: linked.expires_at, + service: ServiceRef { + project_id: look.key.project_id.clone(), + environment: look.key.environment.clone(), + service_id: look.key.service_id.clone(), + }, + profile: dispatch.profile, + expect_rev: Some(look.facts.service.config_rev.clone()), + replaces: dispatch.replaces, + replaces_legacy: dispatch.replaces_legacy, + requested_by: Some(Requester { + machine_id: order.peer.clone(), + name: order.peer_name.clone(), + request_id, + }), + }; + Ok(match self.host.launch_in_app(&request) { + Handoff::Accepted => Ok(Handed::App { unanswered: false }), + // It may have started: only the record can tell, once the + // launch has expired. + Handoff::Unanswered(_) => Ok(Handed::App { unanswered: true }), + Handoff::Absent => Err(app_closed(&look.key.service_id)), + Handoff::Refused(refusal) => Err(Report::refused(&refusal.code, refusal.message)), + }) + } + + /// The launch's decision, waiting for it until its expiry has passed, + /// when the reconciler's `expired` decides it if nothing else did. + fn decision(&self, launch_id: &RunId, expires_at: u64) -> Result { + loop { + match self.host.report(launch_id, None)? { + LaunchReport::Unknown if unix_ms_now() > expires_at => { + return self.host.report(launch_id, Some(expires_at)); + } + LaunchReport::Unknown => thread::sleep(self.timings.poll), + decided => return Ok(decided), + } + } + } + + /// A launch the app never answered: once its expiry has passed, its + /// record is decided, `expired` when nothing admitted it, and no run + /// with its id can start any more. + fn after_expiry(&self, launch_id: &RunId, expires_at: u64) -> Result { + loop { + let now = unix_ms_now(); + if now > expires_at { + return self.host.report(launch_id, Some(expires_at)); + } + thread::sleep(Duration::from_millis((expires_at - now + 1).min(250))); + } + } + + /// From its admission, a run has the settling time to listen: `done` + /// once it does, `failed` when it exits first, `starting` after that. + fn settle(&self, launch: &LinkedLaunch, service: &str) -> Report { + let deadline = Instant::now() + self.timings.settle; + loop { + if self.host.listens(launch.port) { + return started(service, &launch.id); + } + match self.host.report(&launch.id, None) { + Ok(LaunchReport::Starting | LaunchReport::Running | LaunchReport::Unknown) => {} + Ok(other) => return self.describe(other, launch, service), + Err(error) => return unavailable(&error), + } + if Instant::now() >= deadline { + return Report::new( + ControlOutcome::Starting, + None, + format!("Started {service} on this machine, not listening yet."), + ) + .with_run(Some(launch.id.to_string())); + } + thread::sleep(self.timings.poll); + } + } + + /// A linked launch, as its record says now. + fn launch_report(&self, launch: &LinkedLaunch, service: &str) -> Report { + match self.host.report(&launch.id, Some(launch.expires_at)) { + Ok(LaunchReport::Running) if self.host.listens(launch.port) => { + started(service, &launch.id) + } + Ok(report) => self.describe(report, launch, service), + Err(error) => unavailable(&error), + } + } + + /// What one launch report means for the control that dispatched it. + fn describe(&self, report: LaunchReport, launch: &LinkedLaunch, service: &str) -> Report { + let run = Some(launch.id.to_string()); + match report { + LaunchReport::Unknown => Report::new( + ControlOutcome::Unknown, + None, + "Its launch has no record yet.", + ) + .with_run(run), + LaunchReport::Starting | LaunchReport::Running => Report::new( + ControlOutcome::Starting, + None, + format!("Started {service} on this machine, not listening yet."), + ) + .with_run(run), + LaunchReport::Exited { + code, + signal, + reason, + } => { + let mut message = exited(service, code, signal, reason); + let lines = self.host.last_lines(&launch.id, FAILURE_LINES); + if !lines.trim().is_empty() { + message.push_str("\n\n"); + message.push_str(&lines); + } + Report::new(ControlOutcome::Failed, None, message).with_run(run) + } + LaunchReport::Replaced { by } => Report::refused( + "conflict", + format!("Another launch replaced {service} meanwhile."), + ) + .with_run(Some(by.to_string())), + LaunchReport::Refused { code, message } => Report::refused(refusal_code(code), message), + LaunchReport::Expired => match launch.via { + Via::App => app_closed(service), + Via::Background => Report::new(ControlOutcome::Failed, Some("expired"), EXPIRED), + }, + } + } +} + +/// Who acts, once the owner allowed it: a stop of the expected run, a +/// launch through the run's owner (the app, or the background), or both +/// for a restart, which keeps the run's profile. +fn plan( + control: &Control, + run: Option<&RunFacts>, + expected: Option, + app: AppPresence, +) -> Plan { + let via = |origin: Option| match origin { + Some(RunOrigin::Background) => Via::Background, + Some(RunOrigin::App) => Via::App, + _ if app == AppPresence::Running => Via::App, + _ => Via::Background, + }; + match control.action { + ControlAction::Stop => Plan { + stop: expected, + launch: None, + }, + ControlAction::Start => Plan { + stop: None, + launch: Some(Dispatch { + via: via(None), + profile: control.profile.clone(), + replaces: None, + replaces_legacy: None, + }), + }, + ControlAction::Restart => Plan { + launch: Some(Dispatch { + via: via(run.map(|run| run.origin)), + // A restart keeps the run's profile. + profile: run.and_then(|run| run.profile.clone()), + replaces: match &expected { + Some(Expected::Run(run_id)) => Some(run_id.clone()), + _ => None, + }, + replaces_legacy: control.expect.legacy_id.clone(), + }), + stop: expected, + }, + } +} + +/// Check 6, for what a control may name beyond the service: a profile only +/// for a start, and a legacy run only for a restart. +fn check_arguments(control: &Control) -> Result<(), Report> { + if control.action != ControlAction::Start && control.profile.is_some() { + return Err(Report::refused( + "refused_argument", + "A restart keeps the run's profile, and a stop takes none.", + )); + } + if control.action != ControlAction::Restart && control.expect.legacy_id.is_some() { + return Err(Report::refused( + "refused_argument", + "expect.legacyId names the legacy run a restart relaunches.", + )); + } + Ok(()) +} + +/// Check 8: for a start, nothing runs and the port is free; for a stop or a +/// restart, the running run is the one expected. A start or a restart also +/// needs the revision the viewer saw. +fn state_matches(control: &Control, look: &Look) -> Result<(), Report> { + let facts = &look.facts; + let live = facts + .run + .as_ref() + .filter(|run| run.process != RunProcess::Stopped); + let changed = |what: &str| Err(Report::refused("conflict", format!("{CHANGED} {what}"))); + match control.action { + ControlAction::Start if live.is_some() || facts.reachable == Some(true) => { + return changed("It is running already."); + } + ControlAction::Start => {} + ControlAction::Stop | ControlAction::Restart => { + if let Some(legacy_id) = &control.expect.legacy_id { + if control.expect.run_id.is_some() || !look.names_legacy { + return changed(&format!("It no longer runs legacy run {legacy_id}.")); + } + } else { + let current = live.map(|run| run.run_id.as_deref()); + if current != Some(control.expect.run_id.as_deref()) { + return changed("Another run is in place, or none."); + } + } + } + } + if control.action != ControlAction::Stop + && facts.service.config_rev != control.expect.config_rev + { + return changed("Its configuration or launch profiles changed."); + } + Ok(()) +} + +fn started(service: &str, launch_id: &RunId) -> Report { + Report::new( + ControlOutcome::Done, + None, + format!("{service} is running on this machine."), + ) + .with_run(Some(launch_id.to_string())) +} + +fn app_closed(service: &str) -> Report { + Report::new( + ControlOutcome::Failed, + None, + format!( + "The Localify app on this machine closed before starting {service}. Nothing was started." + ), + ) +} + +fn refused_profile(profile: Option<&str>) -> Report { + Report::refused( + "refused_profile", + format!( + "Profile '{}' cannot be started from another machine: it is dangerous, unknown or removed.", + profile.unwrap_or("default") + ), + ) +} + +fn unavailable(error: &dyn std::fmt::Display) -> Report { + Report::new( + ControlOutcome::Failed, + Some("unavailable"), + format!("This machine could not act on it: {error:#}"), + ) +} + +fn refusal_code(code: RefusalCode) -> &'static str { + match code { + RefusalCode::Conflict => "conflict", + RefusalCode::Expired => "expired", + RefusalCode::RefusedProfile => "refused_profile", + } +} + +fn refusal_message(code: &str) -> &'static str { + match code { + "control_disabled" => "This machine doesn't allow remote controls.", + "background_disabled" => { + "Localify isn't open on this machine, and it doesn't allow background starts." + } + "not_owned" => "This runs in a terminal on this machine. Stop it there.", + "legacy_run" => "Relaunch it on that machine to enable remote control.", + "owner_gone" => "Its app is gone: stop it, then start it again.", + "refused_profile" => { + "Its profile is dangerous, unknown or removed: start it on this machine." + } + _ => CHANGED, + } +} + +fn exited( + service: &str, + code: Option, + signal: Option, + reason: Option, +) -> String { + match (reason, code, signal) { + (Some(ExitReason::InterruptedBeforeRegistration), _, _) => { + format!("Localify stopped before {service} started; nothing ran.") + } + (Some(ExitReason::RegistrationFailed), _, _) => { + format!("{service} could not be recorded, so it did not start.") + } + (Some(ExitReason::NotStarted), _, _) => { + format!( + "{service} did not start: something failed before it ran, such as a profile source." + ) + } + (Some(ExitReason::Stopped), _, _) => format!("{service} was stopped."), + (Some(ExitReason::MaxDuration), _, _) => { + format!("{service} reached its profile's maximum duration.") + } + (Some(ExitReason::ExecutorLost), _, _) => { + format!("{service}'s localify dev died before it recorded how the service ended.") + } + (None, Some(code), _) => format!("{service} exited with code {code}."), + (None, None, Some(signal)) => format!("{service} was ended by signal {signal}."), + (None, None, None) => format!("{service} exited."), + } +} + +/// RFC 3339 as Unix milliseconds. +fn rfc3339_ms(text: &str) -> Option { + let at = + time::OffsetDateTime::parse(text, &time::format_description::well_known::Rfc3339).ok()?; + u64::try_from(at.unix_timestamp_nanos() / 1_000_000).ok() +} + +/// One member of a set, held until dropped; `None` while another holds it. +struct Held<'a, T: std::hash::Hash + Eq> { + set: &'a Mutex>, + member: Option, +} + +impl<'a, T: std::hash::Hash + Eq + Clone> Held<'a, T> { + fn enter(set: &'a Mutex>, member: T) -> Option { + let entered = lock(set).insert(member.clone()); + // Built only once in: dropping one removes its member. + entered.then(|| Self { + set, + member: Some(member), + }) + } +} + +impl Drop for Held<'_, T> { + fn drop(&mut self) { + if let Some(member) = self.member.take() { + lock(self.set).remove(&member); + } + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +// --- This machine --------------------------------------------------------- + +/// Reads something the daemon knows and this layer does not: the shell +/// environment, the checkouts the app knows. +pub type Reader = Arc T + Send + Sync>; + +/// The daemon's own config, run records, app bridge and executable. +pub struct LocalHost { + pub config_path: PathBuf, + pub data_dir: PathBuf, + pub services_dir: PathBuf, + /// This executable, canonicalized once at start: never looked up on + /// `PATH`. + pub executable: Result, + /// The user's shell environment, or the daemon's own when it could not + /// be read. + pub environment: Reader, + /// What selects this installation, which a run always gets whatever the + /// shell sets: `HOME`, the install profile, and `XDG_STATE_HOME`. + pub installation: Vec<(String, Option)>, + pub project_roots: Reader>, +} + +impl LocalHost { + fn store(&self) -> RunningServiceStore { + RunningServiceStore::new(self.services_dir.clone()) + } + + /// The executable a detached start runs: this process's own, canonical. + pub fn own_executable() -> Result { + std::env::current_exe() + .and_then(|path| path.canonicalize()) + .map_err(|error| format!("Failed to find this executable: {error}")) + } + + /// This process's own installation: what the daemon was started with. + pub fn own_installation() -> Vec<(String, Option)> { + ["HOME", BRANDING.profile_env(), "XDG_STATE_HOME"] + .into_iter() + .map(|key| (key.to_string(), std::env::var_os(key))) + .collect() + } + + /// The whole environment of a detached `localify dev`: the shell's, with + /// what selects this installation taken from [`LocalHost::installation`]. + fn detached_environment(&self) -> Vec<(OsString, OsString)> { + let mut environment: Vec<(OsString, OsString)> = (self.environment)(); + for (key, value) in &self.installation { + environment.retain(|(name, _)| name != key.as_str()); + if let Some(value) = value { + environment.push((key.into(), value.clone())); + } + } + environment.retain(|(name, _)| name != SERVICE_ORIGIN_ENV && name != "PWD"); + environment + } + + fn home(&self) -> Option { + self.installation + .iter() + .find(|(key, _)| key == "HOME") + .and_then(|(_, value)| value.clone()) + .map(PathBuf::from) + } +} + +impl Host for LocalHost { + fn look( + &self, + wanted: &ServiceKey, + profile: Option<&str>, + legacy_id: Option<&str>, + ) -> Result> { + let config = ConfigStore::new(self.config_path.clone()).load()?; + let key = LaunchRevKey::load_or_create(&self.data_dir)?; + let roots = (self.project_roots)(); + let Some(looked) = look_up(&config, &self.store(), &key, &roots, wanted)? else { + return Ok(None); + }; + let names_legacy = legacy_id.is_some_and(|legacy_id| { + looked + .record + .as_ref() + .is_some_and(|record| record.names_legacy(legacy_id)) + }); + Ok(Some(Look { + profile_allowed: allowed_remotely(&looked.profiles, profile), + names_legacy, + facts: looked.facts, + key: looked.key, + })) + } + + fn stop(&self, key: &ServiceKey, expected: &Expected) -> Result<(), Report> { + let store = self.store(); + let record = store + .get(key) + .map_err(|error| unavailable(&error))? + .ok_or_else(|| Report::refused("conflict", format!("{CHANGED} Nothing runs.")))?; + match expected { + Expected::Run(run_id) => { + if record.run_id() != Some(run_id) || !store.is_running(&record) { + return Err(Report::refused( + "conflict", + format!("{CHANGED} Run {run_id} is no longer the one running."), + )); + } + } + // Its identity again, right before it is signalled. + Expected::Legacy(legacy_id) => { + if !record.names_legacy(legacy_id) { + return Err(Report::refused( + "conflict", + format!("{CHANGED} It no longer runs legacy run {legacy_id}."), + )); + } + if record.legacy_id().as_deref() != Some(legacy_id) { + return Err(Report::refused("legacy_run", refusal_message("legacy_run"))); + } + } + } + store.stop(&record).map(|_| ()).map_err(|error| { + Report::new( + ControlOutcome::Failed, + None, + format!("It could not be stopped: {error:#}"), + ) + }) + } + + fn launch_in_app(&self, request: &LaunchRequest) -> Handoff { + app_bridge::launch(&app_bridge::socket_path(&self.data_dir), request) + } + + fn launch_detached(&self, launch: &DetachedLaunch) -> Result> { + let executable = self.executable.clone().map_err(|error| anyhow!(error))?; + let mut command = Command::new(executable); + command + .arg("--config") + .arg(&self.config_path) + .arg("dev") + .arg(&launch.key.service_id) + .arg("--project") + .arg(&launch.key.project_id); + if let Some(environment) = &launch.key.environment { + command.arg("--env").arg(environment); + } + if let Some(profile) = &launch.profile { + command.arg("--profile").arg(profile); + } + // Each id in one argument: a base64url id may start with `-`. + command + .arg(format!("--remote-launch={}", launch.launch_id)) + .arg(format!("--launch-expires={}", launch.expires_at)) + .arg(format!("--expect-rev={}", launch.expect_rev)) + .arg(format!( + "--request={}:{}", + launch.machine_id, launch.request_id + )); + if let Some(replaces) = &launch.replaces { + command.arg(format!("--replace={replaces}")); + } + if let Some(legacy_id) = &launch.replaces_legacy { + command.arg(format!("--replace-legacy={legacy_id}")); + } + let home = self.home(); + command + .arg("--detach") + .env_clear() + .envs(self.detached_environment()) + .current_dir( + home.filter(|home| home.is_dir()) + .unwrap_or_else(|| "/".into()), + ) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + // SAFETY: the closure runs in the child between fork and exec and only + // calls setsid, which is async-signal-safe and touches no memory. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command + .spawn() + .context("Failed to start localify dev in the background")?; + Ok(Box::new(DetachedChild(child))) + } + + fn report(&self, launch_id: &RunId, expires_at: Option) -> Result { + reconcile(&self.store(), &NativeProcesses, launch_id, expires_at) + } + + fn listens(&self, port: u16) -> bool { + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_ok() + } + + fn last_lines(&self, run_id: &RunId, count: usize) -> String { + output::tail_lines(&self.store().run_dir(run_id), count) + .map(|lines| lines.join("\n")) + .unwrap_or_default() + } +} + +/// `localify dev --detach`, the leader of its own session. +struct DetachedChild(Child); + +impl Spawned for DetachedChild { + fn settle(self: Box, admitted: bool) { + let mut child = self.0; + if !admitted && let Ok(pid) = i32::try_from(child.id()) { + // Its own session, so its process group is its PID. + // SAFETY: killpg only sends a signal; the group is the child's own. + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + // Reaped once it exits: `dev --detach` returns once the service + // listens, and at most after 90 seconds. + thread::spawn(move || { + let _ = child.wait(); + }); + } +} diff --git a/src/infrastructure/remote/mod.rs b/src/infrastructure/remote/mod.rs index 0fec884..3a9d87d 100644 --- a/src/infrastructure/remote/mod.rs +++ b/src/infrastructure/remote/mod.rs @@ -2,9 +2,12 @@ //! (`docs/remote-machines.md`, "Trust" and "Wire protocol"): the files under //! `/remote/`, the Noise handshake and transport, the pairing //! commitment and code, and the JSON frames on the relay and inside -//! sessions. The relay link itself runs in the daemon. +//! sessions; and on a target, the control executor and its request entries. +//! The relay link itself runs in the daemon. +pub mod control; pub mod noise; pub mod pairing; +pub mod requests; pub mod store; pub mod wire; diff --git a/src/infrastructure/remote/requests.rs b/src/infrastructure/remote/requests.rs new file mode 100644 index 0000000..b669644 --- /dev/null +++ b/src/infrastructure/remote/requests.rs @@ -0,0 +1,481 @@ +//! Request entries (`docs/remote-machines.md`, "Request entries"): every +//! control from a peer leaves `services/requests//.json`, +//! published before the target changes anything, with an immutable +//! fingerprint of what it asked. Each outcome is linked to it as it happens: +//! the launch it dispatched, the run it stopped, how it ended. A control that +//! comes back with the same request id is never run again: it gets the +//! entry's report, and `control.status` asks for that report on its own. +//! Entries are kept for 24 hours, so the answer survives a daemon restart. + +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use super::wire::{ + Control, ControlAction, ControlOutcome, ControlResult, ControlService, is_request_id, +}; +use crate::infrastructure::launch_rev::random_bytes; +use crate::infrastructure::runs::RunId; + +/// How long an entry answers for its request. +pub const RETENTION: Duration = Duration::from_secs(24 * 60 * 60); + +/// What a control asked, which no later update changes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Fingerprint { + pub action: ControlAction, + pub service: ControlService, + pub profile: Option, + pub expect_run_id: Option, + pub expect_config_rev: String, + pub expect_legacy_id: Option, +} + +impl Fingerprint { + pub fn of(control: &Control) -> Self { + Self { + action: control.action, + service: control.service.clone(), + profile: control.profile.clone(), + expect_run_id: control.expect.run_id.clone(), + expect_config_rev: control.expect.config_rev.clone(), + expect_legacy_id: control.expect.legacy_id.clone(), + } + } +} + +/// Who a launch was handed to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Via { + App, + Background, +} + +/// The launch a control dispatched, whose record says what became of it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LinkedLaunch { + pub id: RunId, + /// Unix milliseconds. + pub expires_at: u64, + pub via: Via, + /// The port its run listens on, which settling watches. + pub port: u16, +} + +/// The run a stop, or a restart's stop, ended. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Stopped { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legacy_id: Option, + /// Unix milliseconds. + pub at: u64, +} + +/// What a control's request came to, or where it stands: a `control.result` +/// without the request it answers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Report { + pub outcome: ControlOutcome, + pub code: Option, + pub message: String, + pub run_id: Option, +} + +impl Report { + pub fn new(outcome: ControlOutcome, code: Option<&str>, message: impl Into) -> Self { + Self { + outcome, + code: code.map(str::to_string), + message: message.into(), + run_id: None, + } + } + + /// A refusal with its code: `conflict` has an outcome of its own. + pub fn refused(code: &str, message: impl Into) -> Self { + let outcome = if code == "conflict" { + ControlOutcome::Conflict + } else { + ControlOutcome::Refused + }; + Self::new(outcome, Some(code), message) + } + + pub fn with_run(mut self, run_id: Option) -> Self { + self.run_id = run_id; + self + } + + /// Whether nothing can change it any more: `starting` and `unknown` + /// are worked out again each time. + pub fn is_final(&self) -> bool { + !matches!( + self.outcome, + ControlOutcome::Starting | ControlOutcome::Unknown + ) + } + + pub fn answer(&self, re: &str) -> ControlResult { + ControlResult { + re: re.to_string(), + outcome: self.outcome, + code: self.code.clone(), + message: self.message.clone(), + run_id: self.run_id.clone(), + } + } +} + +/// One control's entry. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestEntry { + pub fingerprint: Fingerprint, + /// Unix milliseconds. + pub at: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub launch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stopped: Option, + /// How it ended, once nothing can change it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +impl RequestEntry { + pub fn new(fingerprint: Fingerprint, at: u64) -> Self { + Self { + fingerprint, + at, + launch: None, + stopped: None, + result: None, + } + } +} + +/// What publishing an entry found. +#[derive(Debug)] +pub enum Published { + New, + /// The request already has one: this is it. + Existing(Box), +} + +/// `services/requests/`. +#[derive(Debug, Clone)] +pub struct RequestEntries { + dir: PathBuf, +} + +impl RequestEntries { + pub fn new(dir: PathBuf) -> Self { + Self { dir } + } + + /// `/requests`. + pub fn in_services_dir(services: &Path) -> Self { + Self::new(services.join("requests")) + } + + fn path(&self, peer: &str, request_id: &str) -> Result { + if !is_peer_id(peer) || !is_request_id(request_id) { + bail!("'{peer}:{request_id}' does not name a request."); + } + Ok(self.dir.join(peer).join(format!("{request_id}.json"))) + } + + /// The request's entry, while it is kept: an entry past its 24 hours + /// is no longer one, swept or not. + pub fn read(&self, peer: &str, request_id: &str) -> Result> { + let path = self.path(peer, request_id)?; + let content = match fs::read(&path) { + Ok(content) => content, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(error).with_context(|| format!("Failed to read '{}'", path.display())); + } + }; + if is_past_retention(&path) { + return Ok(None); + } + serde_json::from_slice(&content) + .map(Some) + .with_context(|| format!("'{}' is not a request entry", path.display())) + } + + /// Publishes the request's first entry, whole, or returns the one + /// already there: written to a temporary file, synced, then linked to + /// its name, which fails when an entry exists. Entries past their + /// retention are swept first, so an old one never stands in the way. + pub fn publish(&self, peer: &str, request_id: &str, entry: &RequestEntry) -> Result { + let _ = self.sweep(); + let path = self.path(peer, request_id)?; + let dir = path.parent().context("A request entry has a folder")?; + fs::create_dir_all(dir).with_context(|| format!("Failed to create '{}'", dir.display()))?; + let temporary = write_temporary(dir, request_id, entry)?; + let linked = fs::hard_link(&temporary, &path); + let _ = fs::remove_file(&temporary); + match linked { + Ok(()) => { + sync_dir(dir)?; + Ok(Published::New) + } + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { + match self.read(peer, request_id)? { + Some(existing) => Ok(Published::Existing(Box::new(existing))), + // Past its retention: replaced by this one. + None => { + fs::remove_file(&path) + .with_context(|| format!("Failed to remove '{}'", path.display()))?; + self.publish(peer, request_id, entry) + } + } + } + Err(error) => { + Err(error).with_context(|| format!("Failed to publish '{}'", path.display())) + } + } + } + + /// Links an outcome to the entry, through a temporary file renamed over + /// it. The fingerprint never changes; a result already there stands. + pub fn update( + &self, + peer: &str, + request_id: &str, + change: impl FnOnce(&mut RequestEntry), + ) -> Result { + let path = self.path(peer, request_id)?; + let Some(mut entry) = self.read(peer, request_id)? else { + bail!("Request {request_id} has no entry to update."); + }; + let (fingerprint, result) = (entry.fingerprint.clone(), entry.result.clone()); + change(&mut entry); + entry.fingerprint = fingerprint; + if result.is_some() { + entry.result = result; + } + let dir = path.parent().context("A request entry has a folder")?; + let temporary = write_temporary(dir, request_id, &entry)?; + fs::rename(&temporary, &path) + .with_context(|| format!("Failed to write '{}'", path.display()))?; + sync_dir(dir)?; + Ok(entry) + } + + /// Removes the entries past their retention. Returns how many went. + pub fn sweep(&self) -> Result { + let peers = match fs::read_dir(&self.dir) { + Ok(peers) => peers, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(0), + Err(error) => { + return Err(error) + .with_context(|| format!("Failed to read '{}'", self.dir.display())); + } + }; + let mut removed = 0; + for peer in peers.flatten() { + let Ok(entries) = fs::read_dir(peer.path()) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let stale = path + .extension() + .is_some_and(|extension| extension == "json") + && is_past_retention(&path) + || path.extension().is_some_and(|extension| extension == "tmp") + && is_older_than(&path, Duration::from_secs(3600)); + if stale && fs::remove_file(&path).is_ok() { + removed += 1; + } + } + } + Ok(removed) + } +} + +/// A machine id as a folder name: letters, digits, `-` and `_`. +fn is_peer_id(id: &str) -> bool { + (1..=64).contains(&id.len()) + && id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') +} + +fn is_past_retention(path: &Path) -> bool { + is_older_than(path, RETENTION) +} + +fn is_older_than(path: &Path, age: Duration) -> bool { + fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .is_ok_and(|modified| { + SystemTime::now() + .duration_since(modified) + .is_ok_and(|elapsed| elapsed >= age) + }) +} + +/// The entry, complete and synced, in a file of its own. +fn write_temporary(dir: &Path, request_id: &str, entry: &RequestEntry) -> Result { + let content = serde_json::to_vec_pretty(entry)?; + let mut suffix = [0_u8; 16]; + random_bytes(&mut suffix)?; + let suffix: String = suffix.iter().map(|byte| format!("{byte:02x}")).collect(); + let temporary = dir.join(format!("{request_id}.json.{suffix}.tmp")); + let mut file = File::create_new(&temporary) + .with_context(|| format!("Failed to create '{}'", temporary.display()))?; + if let Err(error) = file.write_all(&content).and_then(|()| file.sync_all()) { + let _ = fs::remove_file(&temporary); + return Err(error).with_context(|| format!("Failed to write '{}'", temporary.display())); + } + Ok(temporary) +} + +fn sync_dir(dir: &Path) -> Result<()> { + File::open(dir) + .and_then(|dir| dir.sync_all()) + .with_context(|| format!("Failed to sync '{}'", dir.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::infrastructure::remote::wire::ControlExpect; + + const REQUEST: &str = "AAAAAAAAAAAAAAAAAAAAAA"; + + fn control(action: ControlAction) -> Control { + Control { + id: "c1".into(), + action, + service: ControlService { + project_id: "app".into(), + environment: None, + service_id: "web".into(), + }, + profile: None, + request_id: REQUEST.into(), + expect: ControlExpect { + run_id: Some("BBBBBBBBBBBBBBBBBBBBBB".into()), + config_rev: "0123456789abcdef".into(), + legacy_id: None, + }, + expires_at: "2026-11-09T10:00:00Z".into(), + } + } + + fn entry(action: ControlAction) -> RequestEntry { + RequestEntry::new(Fingerprint::of(&control(action)), 1) + } + + #[test] + fn the_first_entry_of_a_request_stands() { + let dir = tempfile::tempdir().unwrap(); + let entries = RequestEntries::new(dir.path().to_path_buf()); + + assert!(matches!( + entries + .publish("mA", REQUEST, &entry(ControlAction::Restart)) + .unwrap(), + Published::New + )); + let Published::Existing(existing) = entries + .publish("mA", REQUEST, &entry(ControlAction::Stop)) + .unwrap() + else { + panic!("a second entry replaced the first"); + }; + assert_eq!(existing.fingerprint.action, ControlAction::Restart); + // Another peer's request of the same id is its own. + assert!(matches!( + entries + .publish("mB", REQUEST, &entry(ControlAction::Stop)) + .unwrap(), + Published::New + )); + } + + #[test] + fn updates_keep_the_fingerprint_and_the_first_result() { + let dir = tempfile::tempdir().unwrap(); + let entries = RequestEntries::new(dir.path().to_path_buf()); + entries + .publish("mA", REQUEST, &entry(ControlAction::Stop)) + .unwrap(); + + entries + .update("mA", REQUEST, |entry| { + entry.fingerprint.action = ControlAction::Start; + entry.result = Some(Report::new(ControlOutcome::Done, None, "Stopped.")); + }) + .unwrap(); + let updated = entries + .update("mA", REQUEST, |entry| { + entry.result = Some(Report::refused("conflict", "Late.")); + }) + .unwrap(); + + assert_eq!(updated.fingerprint.action, ControlAction::Stop); + assert_eq!(updated.result.unwrap().outcome, ControlOutcome::Done); + // Read back as a restarted daemon reads it. + let read = RequestEntries::new(dir.path().to_path_buf()) + .read("mA", REQUEST) + .unwrap() + .unwrap(); + assert_eq!(read.fingerprint.action, ControlAction::Stop); + } + + #[test] + fn names_that_are_not_ids_never_reach_the_file_system() { + let dir = tempfile::tempdir().unwrap(); + let entries = RequestEntries::new(dir.path().to_path_buf()); + + for (peer, request) in [ + ("..", REQUEST), + ("mA", "../../../etc/passwd"), + ("a/b", REQUEST), + ] { + assert!(entries.read(peer, request).is_err(), "{peer} {request}"); + assert!( + entries + .publish(peer, request, &entry(ControlAction::Stop)) + .is_err() + ); + } + } + + #[test] + fn an_entry_past_its_retention_is_no_longer_one() { + let dir = tempfile::tempdir().unwrap(); + let entries = RequestEntries::new(dir.path().to_path_buf()); + entries + .publish("mA", REQUEST, &entry(ControlAction::Stop)) + .unwrap(); + let path = dir.path().join("mA").join(format!("{REQUEST}.json")); + let old = SystemTime::now() - RETENTION - Duration::from_secs(1); + File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(old) + .unwrap(); + + assert!(entries.read("mA", REQUEST).unwrap().is_none()); + assert_eq!(entries.sweep().unwrap(), 1); + assert!(!path.exists()); + } +} diff --git a/src/infrastructure/remote/wire.rs b/src/infrastructure/remote/wire.rs index 71ec481..baebbd5 100644 --- a/src/infrastructure/remote/wire.rs +++ b/src/infrastructure/remote/wire.rs @@ -131,6 +131,16 @@ pub struct TargetSettings { pub background_starts: bool, } +impl From for crate::application::inventory::TargetSettings { + fn from(settings: TargetSettings) -> Self { + Self { + share: settings.share, + control: settings.control, + background_starts: settings.background_starts, + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Role { @@ -145,6 +155,15 @@ pub enum AppPresence { Absent, } +impl From for crate::application::inventory::AppPresence { + fn from(app: AppPresence) -> Self { + match app { + AppPresence::Running => Self::Running, + AppPresence::Absent => Self::Absent, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Hello { @@ -264,10 +283,147 @@ pub struct OutputData { pub interrupted: bool, } -/// The session messages this build handles. Controls (`control`, -/// `control.status`) come with a later version of the daemon and are -/// answered `unsupported` (see [`is_later_message`]). The access messages -/// belong to protocol 2 ([`SessionMessage::proto`]). +/// What a control asks a target to do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ControlAction { + Start, + Stop, + Restart, +} + +impl ControlAction { + pub fn as_str(self) -> &'static str { + match self { + Self::Start => "start", + Self::Stop => "stop", + Self::Restart => "restart", + } + } +} + +/// The service a control names, by its ids only. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ControlService { + pub project_id: String, + /// `None` for the primary checkout. + pub environment: Option, + pub service_id: String, +} + +/// What the viewer saw before it sent a control. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ControlExpect { + pub run_id: Option, + pub config_rev: String, + /// Protocol 2, restart only: the legacy run to relaunch. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legacy_id: Option, +} + +/// `control`: start, stop or restart one service, as the viewer saw it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Control { + pub id: String, + pub action: ControlAction, + pub service: ControlService, + /// Start only: a profile name, `None` for the effective default. + pub profile: Option, + /// 16 random bytes, base64url: names this control across sessions. + pub request_id: String, + pub expect: ControlExpect, + /// RFC 3339, in the target's clock. + pub expires_at: String, +} + +/// The fields a `control` may carry. Anything else is refused with +/// `refused_argument`, so no argument is ever silently dropped. +const CONTROL_FIELDS: &[&str] = &[ + "t", + "id", + "action", + "service", + "profile", + "requestId", + "expect", + "expiresAt", +]; +const CONTROL_SERVICE_FIELDS: &[&str] = &["projectId", "environment", "serviceId"]; + +/// The first field of a `control` that a session of version `proto` does +/// not know, if any: `expect.legacyId` belongs to protocol 2. +pub fn unknown_control_field(value: &serde_json::Value, proto: u32) -> Option { + let unknown = |value: Option<&serde_json::Value>, known: &[&str], prefix: &str| { + value + .and_then(serde_json::Value::as_object) + .and_then(|fields| { + fields + .keys() + .find(|field| !known.contains(&field.as_str())) + .map(|field| format!("{prefix}{field}")) + }) + }; + let expect: &[&str] = if proto >= PROTO_ACCESS { + &["runId", "configRev", "legacyId"] + } else { + &["runId", "configRev"] + }; + unknown(Some(value), CONTROL_FIELDS, "") + .or_else(|| unknown(value.get("service"), CONTROL_SERVICE_FIELDS, "service.")) + .or_else(|| unknown(value.get("expect"), expect, "expect.")) +} + +/// Whether `id` is 16 bytes in base64url, as a request id is: it names a +/// file on the target. +pub fn is_request_id(id: &str) -> bool { + id.len() == 22 + && id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') +} + +/// Where a control is on the target. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ControlPhase { + /// Handed to the app, or spawned detached; a stop's signal sent. + Dispatched, + /// Its launch record says `admitted`. + Started, +} + +/// How a control ended, or where it stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ControlOutcome { + Done, + /// Admitted and running, not listening yet. + Starting, + Refused, + Conflict, + Failed, + /// Only while the launch has no record and its expiry has not passed. + Unknown, +} + +/// `control.result`, answering a `control` or a `control.status`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ControlResult { + pub re: String, + pub outcome: ControlOutcome, + /// A code of "Errors" when the outcome is not `done`. + pub code: Option, + pub message: String, + /// The run now in place, when known. + pub run_id: Option, +} + +/// The session messages this build handles. The access messages and +/// `expect.legacyId` belong to protocol 2 ([`SessionMessage::proto`]). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "t", rename_all_fields = "camelCase")] pub enum SessionMessage { @@ -341,6 +497,14 @@ pub enum SessionMessage { OutputUnfollow { re: String }, #[serde(rename = "output.data")] OutputData(OutputData), + #[serde(rename = "control")] + Control(Box), + #[serde(rename = "control.status")] + ControlStatus { id: String, request_id: String }, + #[serde(rename = "control.progress")] + ControlProgress { re: String, phase: ControlPhase }, + #[serde(rename = "control.result")] + ControlResult(ControlResult), #[serde(rename = "access.request")] AccessRequest { id: String, wants: AccessWants }, #[serde(rename = "access.cancel")] @@ -396,6 +560,8 @@ impl SessionMessage { } Self::OutputFollow { id, window, .. } => id_ok(id) && (1..=MAX_WINDOW).contains(window), Self::OutputAck { re, .. } | Self::OutputUnfollow { re } => id_ok(re), + Self::Control(control) => control.within_bounds(), + Self::ControlStatus { id, request_id } => id_ok(id) && is_request_id(request_id), Self::AccessRequest { id, .. } => id_ok(id), Self::AccessCancel { re } => id_ok(re), Self::Keep { ids } => ids.len() <= 16 && ids.iter().all(|id| id_ok(id)), @@ -415,9 +581,29 @@ impl SessionMessage { } } -/// Message types of protocol 1 that this build does not handle yet. -pub fn is_later_message(t: &str) -> bool { - matches!(t, "control" | "control.status") +impl Control { + /// Ids and names of reasonable length, and a request id that is one. + pub fn within_bounds(&self) -> bool { + let short = |text: &str, max: usize| !text.is_empty() && text.len() <= max; + short(&self.id, MAX_ID) + && is_request_id(&self.request_id) + && short(&self.service.project_id, 128) + && short(&self.service.service_id, 128) + && self + .service + .environment + .as_deref() + .is_none_or(|slug| short(slug, 128)) + && self.profile.as_deref().is_none_or(|name| short(name, 64)) + && short(&self.expect.config_rev, 64) + && self.expect.run_id.as_deref().is_none_or(|id| short(id, 64)) + && self + .expect + .legacy_id + .as_deref() + .is_none_or(|id| short(id, 128)) + && short(&self.expires_at, 64) + } } #[cfg(test)] @@ -597,4 +783,101 @@ mod tests { assert!(AccessWants::BackgroundStarts.is_granted_by(&settings(true, true))); assert!(!AccessWants::Control.is_granted_by(&settings(false, false))); } + + fn control_json() -> serde_json::Value { + json!({ + "t": "control", "id": "c1", "action": "restart", + "service": {"projectId": "app", "environment": null, "serviceId": "web"}, + "profile": null, "requestId": "AAAAAAAAAAAAAAAAAAAAAA", + "expect": {"runId": "BBBBBBBBBBBBBBBBBBBBBB", "configRev": "0123456789abcdef"}, + "expiresAt": "2026-11-09T10:00:30Z" + }) + } + + #[test] + fn a_control_and_its_answers_read_as_the_contract_writes_them() { + let SessionMessage::Control(control) = serde_json::from_value(control_json()).unwrap() + else { + panic!("not a control"); + }; + assert_eq!(control.action, ControlAction::Restart); + assert!(control.within_bounds()); + assert_eq!( + serde_json::to_value(SessionMessage::Control(control)).unwrap(), + control_json() + ); + + let result = SessionMessage::ControlResult(ControlResult { + re: "c1".into(), + outcome: ControlOutcome::Refused, + code: Some("busy".into()), + message: "Busy.".into(), + run_id: None, + }); + assert_eq!( + serde_json::to_value(&result).unwrap(), + json!({"t": "control.result", "re": "c1", "outcome": "refused", "code": "busy", + "message": "Busy.", "runId": null}) + ); + let progress: SessionMessage = serde_json::from_value( + json!({"t": "control.progress", "re": "c1", "phase": "started"}), + ) + .unwrap(); + assert_eq!( + progress, + SessionMessage::ControlProgress { + re: "c1".into(), + phase: ControlPhase::Started + } + ); + let status: SessionMessage = serde_json::from_value( + json!({"t": "control.status", "id": "s1", "requestId": "AAAAAAAAAAAAAAAAAAAAAA"}), + ) + .unwrap(); + assert!(status.within_bounds()); + assert_eq!(status.proto(), 1); + } + + #[test] + fn a_control_field_the_session_does_not_know_is_named() { + assert_eq!(unknown_control_field(&control_json(), 2), None); + let mut command = control_json(); + command["command"] = json!(["rm", "-rf", "/"]); + assert_eq!( + unknown_control_field(&command, 2).as_deref(), + Some("command") + ); + let mut port = control_json(); + port["service"]["port"] = json!(22); + assert_eq!( + unknown_control_field(&port, 2).as_deref(), + Some("service.port") + ); + // `legacyId` is protocol 2's. + let mut relaunch = control_json(); + relaunch["expect"]["legacyId"] = json!("boot.1.2"); + assert_eq!(unknown_control_field(&relaunch, 2), None); + assert_eq!( + unknown_control_field(&relaunch, 1).as_deref(), + Some("expect.legacyId") + ); + } + + #[test] + fn a_request_id_is_sixteen_bytes_of_base64url_and_nothing_else() { + assert!(is_request_id("AAAAAAAAAAAAAAAAAAAAAA")); + assert!(is_request_id("-_AAAAAAAAAAAAAAAAAAAA")); + for id in [ + "", + "short", + "../../../../etc/passwd", + "AAAAAAAAAAAAAAAAAAAAA/", + ] { + assert!(!is_request_id(id), "{id}"); + } + let mut control = control_json(); + control["requestId"] = json!("../x"); + let message: SessionMessage = serde_json::from_value(control).unwrap(); + assert!(!message.within_bounds()); + } } diff --git a/src/infrastructure/running_services.rs b/src/infrastructure/running_services.rs index a332aa9..7ac3ab6 100644 --- a/src/infrastructure/running_services.rs +++ b/src/infrastructure/running_services.rs @@ -45,7 +45,7 @@ const STOP_TIMEOUT: Duration = Duration::from_secs(10); const TAIL_WINDOW: u64 = 1024 * 1024; /// Which service in which project environment. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ServiceKey { pub project_id: String, @@ -214,6 +214,56 @@ impl RunningService { }) } + /// What names a legacy run of the app or of `dev --detach` across PID + /// reuse, while its PID is proven: `..`. A + /// relaunch names it, and is checked against it before anything is + /// signalled. A terminal's legacy run has none: it is never relaunched. + pub fn legacy_id(&self) -> Option { + if !self.is_legacy() || self.origin == ServiceOrigin::Terminal { + return None; + } + match &self.run { + None => { + let identity = self.legacy_identity().ok()?; + let boot_id = process::boot_id()?; + Some(format!("{boot_id}.{}.{}", identity.pid, identity.start)) + } + Some(run) => self + .executor_runs() + .then(|| format!("{}.{}.{}", run.boot_id, self.pid, run.start)), + } + } + + /// Whether this record still names the legacy run `legacy_id` names, + /// even once that run stopped: a relaunch's executor checks it under the + /// run lock, so a local launch that took the service over in between + /// wins. A process that is gone cannot show its start any more, so a + /// record without a run id is matched on its boot and PID, and on its + /// start only while that process is still alive as the service. + pub fn names_legacy(&self, legacy_id: &str) -> bool { + let mut parts = legacy_id.rsplitn(3, '.'); + let (Some(start), Some(pid), Some(boot_id)) = (parts.next(), parts.next(), parts.next()) + else { + return false; + }; + let (Ok(start), Ok(pid)) = (start.parse::(), pid.parse::()) else { + return false; + }; + if !self.is_legacy() || self.origin == ServiceOrigin::Terminal || pid != self.pid { + return false; + } + match &self.run { + Some(run) => run.boot_id == boot_id && run.start == start, + None => { + let alive_as = match self.legacy_identity() { + Ok(identity) => identity.start == start, + Err(_) => true, + }; + process::boot_id().as_deref() == Some(boot_id) && alive_as + } + } + } + /// A legacy run is its executor, known by the start time `ps` printed. Its /// PID is that process only when the native start reads the same, to the /// second, unambiguously, and this boot began before the record was @@ -307,10 +357,15 @@ pub struct RunningServiceStore { impl RunningServiceStore { pub fn new_default() -> Result { + Ok(Self::new(Self::default_dir()?)) + } + + /// The user's own `services/`, in the state dir. + pub fn default_dir() -> Result { let dir = BRANDING .user_state_dir() .context("HOME is not set, so Localify cannot track running services.")?; - Ok(Self::new(dir.join("services"))) + Ok(dir.join("services")) } pub fn new(dir: PathBuf) -> Self { diff --git a/src/infrastructure/runs/output.rs b/src/infrastructure/runs/output.rs index c76e6e7..793906e 100644 --- a/src/infrastructure/runs/output.rs +++ b/src/infrastructure/runs/output.rs @@ -417,6 +417,47 @@ pub fn read(dir: &Path, offset: u64, max_bytes: usize) -> Result { read_with(dir, offset, max_bytes, SEGMENT_SIZE) } +/// How much of the end of a stream [`tail_lines`] reads. +const TAIL_BYTES: u64 = 64 * 1024; + +/// The last `count` lines of a run's stream, as plain text, within its last +/// 64 KiB: what a failed start shows. +pub fn tail_lines(dir: &Path, count: usize) -> Result> { + let (first, total) = extent(dir)?; + let mut offset = first.max(total.saturating_sub(TAIL_BYTES)); + // Started inside a line: its piece is dropped. + let mut skipping = offset > 0; + let mut lines = std::collections::VecDeque::new(); + let mut current = String::new(); + loop { + let chunk = read(dir, offset, 16 * 1024)?; + for line in chunk.lines { + if skipping { + skipping = line.cut; + continue; + } + current.push_str(&line.text); + if !line.cut { + lines.push_back(std::mem::take(&mut current)); + if lines.len() > count { + lines.pop_front(); + } + } + } + if chunk.next == offset { + break; + } + offset = chunk.next; + } + if !current.is_empty() { + lines.push_back(current); + if lines.len() > count { + lines.pop_front(); + } + } + Ok(lines.into()) +} + /// How many logical bytes the stream holds, and the first one still kept. pub fn extent(dir: &Path) -> Result<(u64, u64)> { let extent = Extent::of(dir, SEGMENT_SIZE)?; diff --git a/src/main.rs b/src/main.rs index 8c468a7..9ff111c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -299,6 +299,16 @@ enum Commands { #[arg(long, hide = true, value_name = "MACHINE:REQUEST")] request: Option, + /// For --remote-launch: a relaunch of the legacy run its dispatcher stopped. Starts only while the service's record still names that run. + #[arg( + long, + hide = true, + value_name = "LEGACY_ID", + requires = "remote_launch", + conflicts_with = "replace" + )] + replace_legacy: Option, + /// Temporary command override, passed after `--` #[arg(last = true, value_name = "COMMAND")] command: Vec, @@ -1331,6 +1341,7 @@ fn main() -> Result<()> { expect_rev, request, replace, + replace_legacy, .. } => { if !command.is_empty() @@ -1339,6 +1350,7 @@ fn main() -> Result<()> { || launch_expires.is_some() || expect_rev.is_some() || request.is_some() + || replace_legacy.is_some() || !launch_profile.env_file.is_empty() || launch_profile.confirm_profile.is_some() || launch_profile.no_masking @@ -1374,12 +1386,15 @@ fn main() -> Result<()> { expect_rev, request, replace, + replace_legacy, .. } => { // A remote launch has nobody at its terminal to ask, even in a - // run PTY: it stops only the run its dispatcher named. - let replace = match (&remote_launch, &replace) { - (Some(_), None) => cli::services::Replace::No, + // run PTY: it stops only the run its dispatcher named, and a + // relaunch stops nothing. + let replace = match (&remote_launch, &replace, replace_legacy) { + (_, _, Some(legacy_id)) => cli::services::Replace::Legacy(legacy_id), + (Some(_), None, None) => cli::services::Replace::No, _ => cli::services::Replace::for_launch(replace.as_ref().map(|id| id.as_deref()))?, }; exit_with(cli::services::run( diff --git a/tests/remote_controls.rs b/tests/remote_controls.rs new file mode 100644 index 0000000..ca0c2b0 --- /dev/null +++ b/tests/remote_controls.rs @@ -0,0 +1,524 @@ +//! The control executor against real processes (docs/remote-machines.md, +//! "Controls", and the PR 4 gates): the daemon's `LocalHost`, driven +//! directly, reads a real config and real run records, stops real runs and +//! starts the real `localify dev`, detached or through a stand-in for the +//! app's bridge. Everything lives in a temporary home, so an installed +//! Localify is never touched. The session around a control is tested in the +//! daemon (`src/daemon/remote/tests/control.rs`). + +use std::ffi::OsString; +use std::fs; +use std::io::{self, BufRead, BufReader, Write}; +use std::os::unix::fs::DirBuilderExt; +use std::os::unix::net::UnixListener; +use std::os::unix::process::CommandExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use localify::application::inventory::{AppPresence, Switches, TargetSettings}; +use localify::branding::BRANDING; +use localify::infrastructure::app_bridge::{self, LaunchRequest}; +use localify::infrastructure::process::{self, NativeProcesses}; +use localify::infrastructure::remote::control::{ + ControlRunner, ControlTimings, Host, LocalHost, Look, Order, +}; +use localify::infrastructure::remote::requests::{Report, RequestEntries}; +use localify::infrastructure::remote::wire::{ + Control, ControlAction, ControlExpect, ControlOutcome, ControlService, +}; +use localify::infrastructure::running_services::{RunOutput, RunningServiceStore, ServiceKey}; +use localify::infrastructure::runs::RunId; +use localify::infrastructure::runs::launches::{LaunchReport, reconcile}; + +struct Sandbox { + _dir: tempfile::TempDir, + root: PathBuf, + home: PathBuf, + config: PathBuf, + port: u16, +} + +impl Sandbox { + /// `web` runs `script`. + fn new(script: &str) -> Self { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let (home, app) = (root.join("home"), root.join("app")); + for folder in [&home, &app] { + fs::create_dir_all(folder).unwrap(); + } + let port = free_port(); + let config = root.join("config.toml"); + fs::write(&config, config_toml(&root, &app, port, script)).unwrap(); + Self { + _dir: dir, + root, + home, + config, + port, + } + } + + fn services_dir(&self) -> PathBuf { + if cfg!(target_os = "macos") { + self.home + .join("Library/Application Support") + .join(BRANDING.desktop_state_dir_name) + .join("services") + } else { + self.root.join("state").join(BRANDING.slug).join("services") + } + } + + fn store(&self) -> RunningServiceStore { + RunningServiceStore::new(self.services_dir()) + } + + fn environment(&self) -> Vec<(OsString, OsString)> { + vec![ + ("HOME".into(), self.home.clone().into()), + ("XDG_STATE_HOME".into(), self.root.join("state").into()), + ("PATH".into(), "/usr/bin:/bin".into()), + ] + } + + fn host(&self) -> LocalHost { + let environment = self.environment(); + LocalHost { + config_path: self.config.clone(), + data_dir: self.root.join("data"), + services_dir: self.services_dir(), + executable: Ok(PathBuf::from(env!("CARGO_BIN_EXE_localify"))), + environment: Arc::new(move || environment.clone()), + installation: vec![ + ("HOME".into(), Some(self.home.clone().into())), + (BRANDING.profile_env().into(), None), + ( + "XDG_STATE_HOME".into(), + Some(self.root.join("state").into()), + ), + ], + project_roots: Arc::new(Default::default), + } + } + + fn runner(&self, timings: ControlTimings) -> (Arc, ControlRunner) { + let host = Arc::new(self.host()); + let runner = ControlRunner::new( + host.clone(), + RequestEntries::in_services_dir(&self.services_dir()), + timings, + ); + (host, runner) + } + + /// `localify dev` for `web`, with the sandbox's environment. + fn localify(&self, args: &[&str]) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_localify")); + command + .arg("--config") + .arg(&self.config) + .args(args) + .current_dir(&self.home) + .env_clear() + .envs(self.environment()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command + } + + /// A background executor, in its own session, as `dev --detach` makes. + fn background(&self, args: &[&str]) -> Child { + let mut command = self.localify(args); + command.env("LOCALIFY_SERVICE_ORIGIN", "background"); + // SAFETY: only setsid runs between fork and exec; it is async-signal-safe. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + command.spawn().unwrap() + } + + fn look(&self, host: &LocalHost, legacy_id: Option<&str>) -> Look { + host.look(&primary(), None, legacy_id).unwrap().unwrap() + } + + fn report(&self, id: &RunId) -> LaunchReport { + reconcile(&self.store(), &NativeProcesses, id, None).unwrap() + } +} + +impl Drop for Sandbox { + fn drop(&mut self) { + for record in self.store().list().unwrap_or_default() { + let _ = self.store().stop(&record); + } + } +} + +fn primary() -> ServiceKey { + ServiceKey { + project_id: "app".into(), + environment: None, + service_id: "web".into(), + } +} + +fn order(action: ControlAction, look: &Look, request: &str) -> Order { + let run = look.facts.run.as_ref(); + let expires = SystemTime::now() + Duration::from_secs(30); + let expires = time::OffsetDateTime::from(expires) + .format(&time::format_description::well_known::Rfc3339) + .unwrap(); + Order { + peer: "machine-a".into(), + peer_name: "Machine A".into(), + control: Control { + id: "c1".into(), + action, + service: ControlService { + project_id: "app".into(), + environment: None, + service_id: "web".into(), + }, + profile: None, + request_id: format!("{request:q>22}"), + expect: ControlExpect { + run_id: run.and_then(|run| run.run_id.clone()), + config_rev: look.facts.service.config_rev.clone(), + legacy_id: run.and_then(|run| run.legacy_id.clone()), + }, + expires_at: expires, + }, + } +} + +fn switches(background_starts: bool, app: AppPresence) -> impl Fn() -> Switches { + move || Switches { + settings: TargetSettings { + share: true, + control: true, + background_starts, + }, + app, + } +} + +fn fast(budget: Duration) -> ControlTimings { + ControlTimings { + dispatch_budget: budget, + settle: Duration::from_secs(3), + poll: Duration::from_millis(50), + ahead: Duration::from_secs(60), + } +} + +fn wait_until(what: &str, mut check: impl FnMut() -> Option) -> T { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(found) = check() { + return found; + } + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + thread::sleep(Duration::from_millis(50)); + } +} + +/// The gate: a restart of a background run with `backgroundStarts` off is +/// refused, and the run keeps running. +#[test] +fn a_background_restart_without_background_starts_is_refused_and_it_keeps_running() { + let sandbox = Sandbox::new("exec sleep 300"); + let mut executor = sandbox.background(&["dev", "web", "--project", "app"]); + let (host, runner) = sandbox.runner(fast(Duration::from_secs(5))); + let look = wait_until("the background run", || { + Some(sandbox.look(&host, None)).filter(|look| look.facts.run.is_some()) + }); + + let report = runner.run( + &order(ControlAction::Restart, &look, "r1"), + &switches(false, AppPresence::Absent), + &mut |_| {}, + ); + + assert_eq!(report.outcome, ControlOutcome::Refused, "{report:?}"); + assert_eq!(report.code.as_deref(), Some("background_disabled")); + assert!(executor.try_wait().unwrap().is_none(), "it keeps running"); + let record = sandbox.store().get(&look.key).unwrap().unwrap(); + assert!(sandbox.store().is_running(&record)); + assert_eq!( + record.run_id().map(ToString::to_string), + look.facts.run.unwrap().run_id + ); +} + +/// The gate: a proven legacy run restarted with `expect.legacyId` ends and +/// is replaced by a run with a run id and a stream, started in the +/// background with `--replace-legacy`. +#[test] +fn a_proven_legacy_run_is_relaunched_in_the_background() { + let sandbox = Sandbox::new("exec sleep 300"); + let (host, runner) = sandbox.runner(fast(Duration::from_secs(10))); + let key = sandbox.look(&host, None).key; + let mut legacy = Command::new("sleep").arg("300").spawn().unwrap(); + write_legacy_record(&sandbox, &key, legacy.id()); + let look = sandbox.look(&host, None); + let legacy_id = look + .facts + .run + .as_ref() + .and_then(|run| run.legacy_id.clone()); + assert!( + legacy_id.is_some(), + "a proven legacy run: {:?}", + look.facts.run + ); + + let report = runner.run( + &order(ControlAction::Restart, &look, "r2"), + &switches(true, AppPresence::Absent), + &mut |_| {}, + ); + + assert!( + matches!( + report.outcome, + ControlOutcome::Done | ControlOutcome::Starting + ), + "{report:?}" + ); + assert!(legacy.wait().is_ok(), "the legacy run ended"); + let record = sandbox.store().get(&key).unwrap().unwrap(); + assert_eq!( + record.run_id().map(ToString::to_string), + report.run_id, + "replaced by the relaunch" + ); + assert_eq!(record.run.as_ref().unwrap().output, Some(RunOutput::Pipe)); +} + +/// The executor refuses a relaunch once the record names another run: a +/// local launch that came in between wins. +#[test] +fn a_relaunch_starts_nothing_once_another_launch_took_the_service_over() { + let sandbox = Sandbox::new("exec sleep 300"); + let (host, _) = sandbox.runner(fast(Duration::from_secs(10))); + let look = sandbox.look(&host, None); + let status = sandbox + .localify(&[ + "dev", + "web", + "--project", + "app", + "--remote-launch=AAAAAAAAAAAAAAAAAAAAAA", + &format!( + "--launch-expires={}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() + + 15_000 + ), + &format!("--expect-rev={}", look.facts.service.config_rev), + "--request=machine-a:req-1", + "--replace-legacy=boot.1.2", + ]) + .status() + .unwrap(); + + assert!(!status.success()); + let id = RunId::parse("AAAAAAAAAAAAAAAAAAAAAA").unwrap(); + let LaunchReport::Refused { message, .. } = sandbox.report(&id) else { + panic!("not refused: {:?}", sandbox.report(&id)); + }; + assert!(message.contains("someone else"), "{message}"); + assert!( + sandbox.store().get(&look.key).unwrap().is_none(), + "nothing ran" + ); +} + +/// The gate: launch A starts and exits, a local launch B then replaces the +/// service's record, and the bridge's answer about A was lost. The target +/// still reports A as admitted and exited, with its code. +#[test] +fn a_lost_acknowledgement_is_reported_exactly() { + let sandbox = Sandbox::new("echo a-ran; sleep 1; exit 3"); + let (host, runner) = sandbox.runner(fast(Duration::from_secs(12))); + let look = sandbox.look(&host, None); + let bridge = unanswering_app(&sandbox); + + let control = order(ControlAction::Start, &look, "r3"); + let ran = thread::scope(|scope| { + let running = scope.spawn(|| { + runner.run( + &control, + &switches(false, AppPresence::Running), + &mut |_| {}, + ) + }); + // The app spawned A, then closed the connection without a word. + let launch_a = bridge.join().unwrap(); + wait_until("A exited", || { + matches!(sandbox.report(&launch_a), LaunchReport::Exited { .. }).then_some(()) + }); + // A local launch B takes the service over. + let mut b = sandbox.background(&["dev", "web", "--project", "app", "--", "sleep", "300"]); + wait_until("B registered", || { + let record = sandbox.store().get(&look.key).ok()??; + (record.run_id() != Some(&launch_a)).then_some(()) + }); + let report = running.join().unwrap(); + let _ = b.kill(); + let _ = b.wait(); + (launch_a, report) + }); + let (launch_a, report): (RunId, Report) = ran; + + assert_eq!(report.outcome, ControlOutcome::Failed, "{report:?}"); + assert!( + report.message.contains("exited with code 3"), + "{}", + report.message + ); + assert_eq!(report.run_id.as_deref(), Some(launch_a.as_str())); + // And `control.status` says the same. + let status = runner.status("machine-a", &format!("{:q>22}", "r3")); + assert_eq!(status, report); +} + +/// The app's bridge, as an app that spawns the launch's `localify dev` and +/// closes the connection before it answers. Returns the launch's id. +fn unanswering_app(sandbox: &Sandbox) -> thread::JoinHandle { + let socket = app_bridge::socket_path(&sandbox.root.join("data")); + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(socket.parent().unwrap()) + .unwrap(); + let listener = UnixListener::bind(&socket).unwrap(); + let config = sandbox.config.clone(); + let environment = sandbox.environment(); + let home = sandbox.home.clone(); + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + BufReader::new(&stream).read_line(&mut line).unwrap(); + let mut request: serde_json::Value = serde_json::from_str(&line).unwrap(); + request.as_object_mut().unwrap().remove("cmd"); + let request: LaunchRequest = serde_json::from_value(request).unwrap(); + let requester = request.requested_by.clone().unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_localify")); + command + .arg("--config") + .arg(&config) + .args(["dev", "web", "--project", "app"]) + .arg(format!("--remote-launch={}", request.launch_id)) + .arg(format!("--launch-expires={}", request.expires_at)) + .arg(format!("--expect-rev={}", request.expect_rev.unwrap())) + .arg(format!( + "--request={}:{}", + requester.machine_id, requester.request_id + )) + .current_dir(&home) + .env_clear() + .envs(environment) + .env("LOCALIFY_SERVICE_ORIGIN", "background") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + // SAFETY: only setsid runs between fork and exec; it is async-signal-safe. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut executor = command.spawn().unwrap(); + thread::spawn(move || executor.wait()); + drop(stream); + request.launch_id + }) +} + +/// A record of `web` as a version without run ids left it for `pid`, run +/// by `dev --detach`. +fn write_legacy_record(sandbox: &Sandbox, key: &ServiceKey, pid: u32) { + let info = process::process_info(pid).unwrap(); + let record = serde_json::json!({ + "projectId": key.project_id, + "environment": key.environment, + "serviceId": key.service_id, + "pid": pid, + "processStartedAt": process::lstart_label(info.started_wall).unwrap(), + "url": "http://web.localify", + "port": sandbox.port, + "origin": "background", + "profile": null, + "startedAt": SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(), + "logFile": null, + "exit": null, + }); + let dir = sandbox.services_dir(); + fs::create_dir_all(&dir).unwrap(); + let name = format!( + "{}--{}--{}.json", + key.project_id, + key.environment.as_deref().unwrap_or("default"), + key.service_id + ); + let mut file = fs::File::create(dir.join(name)).unwrap(); + file.write_all(record.to_string().as_bytes()).unwrap(); +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() +} + +fn config_toml(root: &Path, app: &Path, port: u16, script: &str) -> String { + let script = script.replace('\\', "\\\\").replace('"', "\\\""); + format!( + r#"[paths] +data_dir = "{root}/data" +pid_file = "{root}/localify.pid" +log_file = "{root}/logs/localify.log" +certs_dir = "{root}/data/certs" +socket_path = "{root}/localify.sock" + +[domains."web.localify"] +pattern = "web.localify" +https_enabled = false +project = "app" + +[[domains."web.localify".routes]] +path = "/" +target = "127.0.0.1:{port}" + +[projects.app] +name = "app" +enabled = true +root_path = "{app}" + +[[projects.app.services]] +name = "web" +primary_domain = "web.localify" +command = ["sh", "-c", "{script}"] +"#, + root = root.display(), + app = app.display(), + ) +} From 4ece904fb798ad544661a0eaa78205a67d6c48e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 15:12:41 +0100 Subject: [PATCH 2/6] feat(remote): remote controls, quick actions and the access dialog in the app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app now starts, stops and restarts services on another machine, and answers access requests on this one (PR 4d of docs/remote-machines.md). Viewer: the remote chip's Start/Stop and the menu's Restart call `remote_control` with the snapshot's expect values (runId, configRev, and legacyId for a relaunch). A toast shows the progress ("Starting in the app on B…"), `unknown` as "Outcome unknown. Checking B…", then the result. One control per service at a time, and none while the session is down: the button is disabled with the connection state. Quick actions: a control that isn't allowed stays clickable and opens a card. control_disabled and background_disabled offer `Ask B` on protocol 2 (the `remote_access` stream, with Cancel, the outcomes and retryAfter) and always the command to run there; protocol 1 gets only the command. A legacy run with a legacyId, its Restart and Output's "Relaunch to share" go to `Relaunch on B` after the contract's confirmation; with controls off it asks for access first, then relaunches only if the snapshot still shows the same legacyId and configRev, and otherwise asks again. Other codes show their message. Target: the app subscribes to `remote_events` with `access: true` and shows the access dialog in the contract's words, one request at a time, with a system notification while the window isn't focused (tauri-plugin-notification). Focus lands on the dialog, not a button. Settings → Remote access: the control and background switches work, and suppressed machines are listed with `Allow requests again`. The "comes in a later version" texts and the disabled-only paths are gone. Pure logic is in lib/util.remote-controls.ts, with node tests. --- .../app/remote/remote-access-dialog.tsx | 89 ++++ .../components/app/remote/remote-controls.tsx | 426 ++++++++++++++++++ .../app/remote/remote-projects-view.tsx | 109 +++-- .../app/remote/remote-quick-action-card.tsx | 139 ++++++ .../app/remote/remote-service-chip.tsx | 168 +++++-- .../app/settings/settings-remote-access.tsx | 77 +++- desktop-ui/src/components/ui/popover.tsx | 7 +- desktop-ui/src/lib/queries/remote.queries.ts | 14 + .../src/lib/util.remote-controls.test.ts | 331 ++++++++++++++ desktop-ui/src/lib/util.remote-controls.ts | 305 +++++++++++++ .../src/lib/validators/validator.remote.ts | 16 + desktop-ui/src/providers/remote-provider.tsx | 90 +++- desktop-ui/src/types/localify.ts | 10 +- docs/remote-machines.md | 2 +- package.json | 1 + pnpm-lock.yaml | 10 + src-tauri/Cargo.lock | 134 +++++- src-tauri/Cargo.toml | 1 + src-tauri/capabilities/default.json | 1 + src-tauri/src/lib.rs | 1 + src/desktop/dto.rs | 3 +- 21 files changed, 1798 insertions(+), 136 deletions(-) create mode 100644 desktop-ui/src/components/app/remote/remote-access-dialog.tsx create mode 100644 desktop-ui/src/components/app/remote/remote-controls.tsx create mode 100644 desktop-ui/src/components/app/remote/remote-quick-action-card.tsx create mode 100644 desktop-ui/src/lib/util.remote-controls.test.ts create mode 100644 desktop-ui/src/lib/util.remote-controls.ts diff --git a/desktop-ui/src/components/app/remote/remote-access-dialog.tsx b/desktop-ui/src/components/app/remote/remote-access-dialog.tsx new file mode 100644 index 0000000..f51cb3d --- /dev/null +++ b/desktop-ui/src/components/app/remote/remote-access-dialog.tsx @@ -0,0 +1,89 @@ +"use client"; + +import { useRef, useState } from "react"; +import { toast } from "sonner"; + +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { accessRequestTitle } from "@/lib/util.remote-controls"; +import { useRemote } from "@/providers/remote-provider"; + +/** + * Another machine asks this Mac for remote controls (docs/remote-machines.md, "Asking for + * access", step 4). The switches are machine-wide, so the question says so. Only `Allow` or + * `Don't allow` answers it: Escape and a click outside leave it to expire. + */ +export function RemoteAccessDialog() { + const { access } = useRemote(); + if (!access) return null; + // A fresh dialog, and a cleared checkbox, for each request. + return ; +} + +function AccessRequestDialog() { + const { access, answerAccess } = useRemote(); + const [suppress, setSuppress] = useState(false); + const [answering, setAnswering] = useState(false); + // Focus lands on the dialog, not a button, so typing in a terminal can't answer it. + const popup = useRef(null); + if (!access) return null; + + const answer = (allow: boolean) => { + setAnswering(true); + void answerAccess(allow, suppress).catch((error: unknown) => { + setAnswering(false); + toast.error("Could not answer the request", { + description: error instanceof Error ? error.message : String(error), + }); + }); + }; + + return ( + undefined}> + + + {accessRequestTitle(access.name, access.fingerprint)} + }> +

+ Allow every paired machine to start, stop and restart services on this Mac, until you + turn it off in Settings? +

+ {access.wants === "backgroundStarts" ? ( +

…also when Localify is closed here, in the background.

+ ) : null} +
+ +
+ + + + +
+
+ ); +} diff --git a/desktop-ui/src/components/app/remote/remote-controls.tsx b/desktop-ui/src/components/app/remote/remote-controls.tsx new file mode 100644 index 0000000..8631839 --- /dev/null +++ b/desktop-ui/src/components/app/remote/remote-controls.tsx @@ -0,0 +1,426 @@ +"use client"; + +import { + createContext, + type PropsWithChildren, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { toast } from "sonner"; + +import type { + RemoteAccessEventDto, + RemoteAccessWants, + RemoteControlAction, + RemoteControlEventDto, + RemoteInventoryItemDto, +} from "@/types/localify"; + +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { openRemoteStream } from "@/lib/remote-stream"; +import { remoteErrorMessage, serviceKey } from "@/lib/util.remote"; +import { + type AccessView, + accessEventView, + type ControlPhase, + controlLostText, + controlProgressText, + controlRequest, + controlResultText, + quickAction, + type RelaunchConfirmation, + relaunchConfirmation, + relaunchStillConfirmed, +} from "@/lib/util.remote-controls"; + +/** After access is granted, how long a relaunch waits for the snapshot that allows it. */ +const GRANTED_SNAPSHOT_MS = 15_000; + +/** A control on its way to the target, one per service at a time, as the chip says it. */ +interface ControlInFlight { + text: string; +} + +/** The access request this Mac has open with the machine on screen, if any. */ +interface AccessRequestState { + wants: RemoteAccessWants; + view: AccessView; +} + +interface RemoteControlsValue { + machineName: string; + /** The session's protocol; null while none is open. */ + proto: number | null; + /** Why controls are off: the session is down, and nothing is queued. */ + down: string | null; + inFlight: (item: RemoteInventoryItemDto) => ControlInFlight | null; + run: (item: RemoteInventoryItemDto, action: RemoteControlAction) => void; + access: AccessRequestState | null; + ask: (wants: RemoteAccessWants) => void; + cancelAsk: () => void; + /** Forgets how the last request ended, once it was shown. */ + dismissAccess: () => void; + /** Opens the relaunch confirmation for a legacy run. */ + relaunch: (item: RemoteInventoryItemDto) => void; +} + +const RemoteControlsContext = createContext(null); + +interface RemoteControlsProviderProps { + machineId: string; + machineName: string; + proto: number | null; + down: string | null; + appRunning: boolean; + items: RemoteInventoryItemDto[]; +} + +/** A relaunch the person confirmed, waiting on access first. */ +interface PendingRelaunch { + key: string; + confirmed: RelaunchConfirmation; + wants: RemoteAccessWants; + /** Access was granted: go ahead once the snapshot allows the restart. */ + granted: boolean; +} + +/** + * Start, Stop and Restart of the machine on screen, its access request and the relaunch of + * legacy runs (docs/remote-machines.md, "Quick actions", "State machine", the viewer side). + */ +export function RemoteControlsProvider({ + machineId, + machineName, + proto, + down, + appRunning, + items, + children, +}: PropsWithChildren) { + const [controls, setControls] = useState>({}); + // Set at the click, before React renders: a second click finds it. + const busy = useRef(new Set()); + const [access, setAccess] = useState(null); + const closeAccess = useRef<(() => void) | null>(null); + // Counts asks: events of an ask replaced or cancelled since are dropped. + const askSeq = useRef(0); + const [confirming, setConfirming] = useState(null); + const [pending, setPending] = useState(null); + const live = useRef({ machineName, appRunning }); + live.current = { machineName, appRunning }; + + // A machine left on screen keeps nothing open with it. + useEffect( + () => () => { + askSeq.current += 1; + closeAccess.current?.(); + closeAccess.current = null; + }, + [machineId], + ); + + const run = useCallback( + ( + item: RemoteInventoryItemDto, + action: RemoteControlAction, + relaunch: RelaunchConfirmation | null = null, + ) => { + const key = serviceKey(item); + if (busy.current.has(key)) return; + busy.current.add(key); + const service = item.service.name; + const toastId = `remote-control:${machineId}:${key}`; + const progress = (phase: ControlPhase) => { + const { machineName: name, appRunning: app } = live.current; + const text = controlProgressText(action, phase, name, app); + setControls((current) => ({ ...current, [key]: { text } })); + toast.loading(text, { id: toastId }); + }; + const settle = (ok: boolean, text: string) => { + busy.current.delete(key); + setControls(({ [key]: _, ...rest }) => rest); + if (ok) toast.success(text, { id: toastId }); + else toast.error(text, { id: toastId }); + }; + progress("sent"); + let ended = false; + const onEvent = (event: RemoteControlEventDto) => { + const name = live.current.machineName; + switch (event.event) { + case "sent": + return; + case "progress": + progress(event.phase); + return; + case "unknown": + progress("unknown"); + return; + case "result": { + ended = true; + const view = controlResultText(event, action, service, name); + settle(view.ok, view.text); + return; + } + case "lost": + ended = true; + settle(false, controlLostText(name)); + return; + } + }; + void openRemoteStream( + { kind: "control", machineId, ...controlRequest(item, action, relaunch) }, + { + onData: onEvent, + onEnd: (error) => { + if (!ended) settle(false, error ?? controlLostText(live.current.machineName)); + }, + }, + ).catch((error: unknown) => + settle(false, error instanceof Error ? error.message : String(error)), + ); + }, + [machineId], + ); + + /** + * Asks the target for access. A card shows the request as it goes; a relaunch confirmed in + * its dialog has no card, so a toast shows it, with Cancel. + */ + const ask = useCallback( + (wants: RemoteAccessWants, inToast = false) => { + closeAccess.current?.(); + closeAccess.current = null; + const seq = ++askSeq.current; + const isLatest = () => seq === askSeq.current; + const toastId = `remote-access:${machineId}`; + const show = (view: AccessView) => { + setAccess({ wants, view }); + if (view.step === "waiting") { + if (inToast) { + toast.loading(view.text, { + id: toastId, + action: { label: "Cancel", onClick: () => cancelRef.current() }, + }); + } + } else if (view.ok) toast.success(view.text, { id: toastId }); + else if (inToast) toast.error(view.text, { id: toastId }); + }; + show(accessEventView({ event: "waiting" }, wants, live.current.machineName)); + let ended = false; + void openRemoteStream( + { kind: "access", machineId, wants }, + { + onData: (event) => { + if (!isLatest()) return; + const view = accessEventView(event, wants, live.current.machineName); + if (view.step === "ended") { + ended = true; + closeAccess.current = null; + setPending((current) => + current && event.event === "result" && event.outcome === "granted" + ? { ...current, granted: true } + : null, + ); + } + show(view); + }, + onEnd: (error) => { + if (!isLatest()) return; + closeAccess.current = null; + if (ended) return; + setPending(null); + show( + error + ? { step: "ended", ok: false, text: error } + : accessEventView( + { event: "lost", code: "closed", message: "" }, + wants, + live.current.machineName, + ), + ); + }, + }, + ) + .then((close) => { + if (ended || !isLatest()) close(); + else closeAccess.current = close; + }) + .catch((error: unknown) => { + if (!isLatest()) return; + setPending(null); + show({ + step: "ended", + ok: false, + text: error instanceof Error ? error.message : String(error), + }); + }); + }, + [machineId], + ); + + // Closing the stream sends `access.cancel`. + const cancelAsk = useCallback(() => { + askSeq.current += 1; + closeAccess.current?.(); + closeAccess.current = null; + setAccess(null); + setPending(null); + toast.dismiss(`remote-access:${machineId}`); + }, [machineId]); + const cancelRef = useRef(cancelAsk); + cancelRef.current = cancelAsk; + + const dismissAccess = useCallback( + () => setAccess((current) => (current?.view.step === "ended" ? null : current)), + [], + ); + + const confirmRelaunch = () => { + const item = confirming; + setConfirming(null); + const confirmed = item ? relaunchConfirmation(item) : null; + if (!item || !confirmed) return; + if (down) { + toast.error(down); + return; + } + const next = quickAction(item, "restart", proto, machineName); + if (next.kind !== "relaunch") { + toast.error(next.kind === "message" ? next.text : `${machineName} changed in the meantime.`); + return; + } + if (next.access) { + setPending({ key: serviceKey(item), confirmed, wants: next.access, granted: false }); + ask(next.access, true); + return; + } + run(item, "restart", confirmed); + }; + + // Once access is granted, the next snapshot carries the controls it allows. + useEffect(() => { + // Nothing is sent while the session is down; the timeout below gives up. + if (!pending?.granted || down) return; + const item = items.find((candidate) => serviceKey(candidate) === pending.key); + if (!item) { + setPending(null); + toast.error(`This service no longer exists on ${machineName}.`); + return; + } + const next = quickAction(item, "restart", proto, machineName); + if (next.kind === "relaunch" && next.access === null) { + setPending(null); + if (relaunchStillConfirmed(pending.confirmed, item)) run(item, "restart", pending.confirmed); + // It changed since the person confirmed: ask again. + else if (relaunchConfirmation(item)) setConfirming(item); + else toast.error(`${machineName} changed in the meantime.`); + return; + } + // A snapshot from before the grant: wait for the next one. + if (next.kind === "relaunch" && next.access === pending.wants) return; + setPending(null); + toast.error( + next.kind === "message" + ? next.text + : remoteErrorMessage( + item.controls.restart.code ?? "", + machineName, + `${machineName} changed in the meantime.`, + ), + ); + }, [items, pending, proto, machineName, run, down]); + + useEffect(() => { + if (!pending?.granted) return; + const timer = window.setTimeout(() => { + setPending(null); + toast.error(`${machineName} allowed it, but its new state didn't arrive. Try again.`); + }, GRANTED_SNAPSHOT_MS); + return () => window.clearTimeout(timer); + }, [pending?.granted, machineName]); + + const value = useMemo( + () => ({ + machineName, + proto, + down, + inFlight: (item) => controls[serviceKey(item)] ?? null, + run: (item, action) => run(item, action), + access, + // Asking from a card is not a relaunch's. + ask: (wants) => { + setPending(null); + ask(wants); + }, + cancelAsk, + dismissAccess, + relaunch: setConfirming, + }), + [machineName, proto, down, controls, run, access, ask, cancelAsk, dismissAccess], + ); + + return ( + + {children} + setConfirming(null)} + onConfirm={confirmRelaunch} + /> + + ); +} + +export function useRemoteControls(): RemoteControlsValue { + const context = useContext(RemoteControlsContext); + if (!context) throw new Error("useRemoteControls must be used inside RemoteControlsProvider"); + return context; +} + +/** The contract's confirmation before a legacy run is relaunched. */ +function RelaunchDialog({ + item, + machineName, + onCancel, + onConfirm, +}: { + item: RemoteInventoryItemDto | null; + machineName: string; + onCancel: () => void; + onConfirm: () => void; +}) { + return ( + (open ? undefined : onCancel())}> + + + Relaunch on {machineName} + + {item?.service.name} started before this version of Localify on {machineName}. Relaunch + it so its output and controls work here? It restarts with its configured command. + + + + + + + + + ); +} diff --git a/desktop-ui/src/components/app/remote/remote-projects-view.tsx b/desktop-ui/src/components/app/remote/remote-projects-view.tsx index 6018dd1..35a4103 100644 --- a/desktop-ui/src/components/app/remote/remote-projects-view.tsx +++ b/desktop-ui/src/components/app/remote/remote-projects-view.tsx @@ -16,10 +16,12 @@ import { serviceKey, serviceTone, } from "@/lib/util.remote"; +import { sessionDownReason } from "@/lib/util.remote-controls"; import { cn } from "@/lib/utils"; import { useRemote } from "@/providers/remote-provider"; import { useTerminal } from "@/providers/terminal-provider"; +import { RemoteControlsProvider } from "./remote-controls"; import { RemoteOutputPanel } from "./remote-output-panel"; import { RemoteServiceChip } from "./remote-service-chip"; import { useRemoteInventory } from "./use-remote-inventory"; @@ -47,6 +49,13 @@ export function RemoteProjectsView({ machine, query }: RemoteProjectsViewProps) const groups = useMemo(() => groupInventory(inventory?.items ?? [], query), [inventory, query]); const outputItem = inventory?.items.find((item) => serviceKey(item) === outputKey) ?? null; const outputShown = outputItem !== null; + // A control is sent only on an open session, never queued. + const down = sessionDownReason({ + machine: name, + machineLabel: describeMachine(machine).label, + phase: state.phase, + proto: machine.proto, + }); useEffect(() => { setOutputOpen(outputShown); return () => setOutputOpen(false); @@ -59,57 +68,67 @@ export function RemoteProjectsView({ machine, query }: RemoteProjectsViewProps) }; return ( -
- - You're viewing {name}. Its .localify URLs open only on {name}. - - - {state.phase === "lost" ? ( - - {remoteErrorMessage(state.code, name, state.message)} - {isFinalCode(state.code) ? null : ` Trying again in ${state.retryIn} s.`} + +
+ + You're viewing {name}. Its .localify URLs open only on {name}. - ) : null} - {inventory?.truncated ? ( - {name} has more services than fit here; some are left out. - ) : null} - - {!inventory && state.phase !== "lost" ? ( -
- - Connecting to {name}… -
- ) : null} + + {state.phase === "lost" ? ( + + {remoteErrorMessage(state.code, name, state.message)} + {isFinalCode(state.code) ? null : ` Trying again in ${state.retryIn} s.`} + + ) : null} + {inventory?.truncated ? ( + {name} has more services than fit here; some are left out. + ) : null} - {inventory && groups.length === 0 ? ( -

- {query ? "No service matches." : `${name} has no projects yet.`} -

- ) : null} + {!inventory && state.phase !== "lost" ? ( +
+ + Connecting to {name}… +
+ ) : null} - {groups.map((project) => ( - - ))} + {inventory && groups.length === 0 ? ( +

+ {query ? "No service matches." : `${name} has no projects yet.`} +

+ ) : null} - {outputItem ? ( - <> - {/* Keeps the last cards scrollable above the panel. */} -
- ( + setOutputKey(null)} + onOutput={showOutput} /> - - ) : null} -
+ ))} + + {outputItem ? ( + <> + {/* Keeps the last cards scrollable above the panel. */} +
+ setOutputKey(null)} + /> + + ) : null} +
+ ); } diff --git a/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx b/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx new file mode 100644 index 0000000..e7edf8e --- /dev/null +++ b/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx @@ -0,0 +1,139 @@ +"use client"; + +import { useEffect } from "react"; + +import type { RemoteControlAction, RemoteInventoryItemDto } from "@/types/localify"; + +import { CheckIcon, CopyIcon, SpinnerIcon } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; +import { remoteErrorMessage } from "@/lib/util.remote"; +import { accessCommand, type QuickAction } from "@/lib/util.remote-controls"; +import { cn } from "@/lib/utils"; + +import { useRemoteControls } from "./remote-controls"; + +/** + * Why a control is not allowed, and what fixes it (docs/remote-machines.md, "Quick actions"): + * ask the target, run a command there, or relaunch a legacy run. + */ +export function RemoteQuickActionCard({ + item, + action, + quick, + onDone, +}: { + item: RemoteInventoryItemDto; + action: RemoteControlAction; + quick: Exclude; + onDone: () => void; +}) { + const { machineName: name, access, ask, relaunch, dismissAccess } = useRemoteControls(); + // An answer shown here is not shown again in the next card. + useEffect(() => dismissAccess, [dismissAccess]); + const code = item.controls[quick.kind === "relaunch" ? "restart" : action].code ?? ""; + + switch (quick.kind) { + case "message": + return

{quick.text}

; + case "command": + return ( +
+

{remoteErrorMessage(code, name, "Not available.")}

+

Update Localify on {name} to ask from here.

+ +
+ ); + case "ask": + return ( +
+

{remoteErrorMessage(code, name, "Not available.")}

+ + {access?.view.step === "waiting" ? null : ( + + )} +

Or run this on {name}:

+ +
+ ); + case "relaunch": + return ( +
+

+ {item.service.name} started before this version of Localify on {name}. +

+ {quick.access ? ( +

+ {remoteErrorMessage(code, name, "")} Relaunching asks {name} for access first. +

+ ) : null} + + {access?.view.step === "waiting" ? null : ( + + )} +
+ ); + } +} + +/** The access request open with this machine: waiting with Cancel, or how it ended. */ +function AccessStatus() { + const { access, cancelAsk } = useRemoteControls(); + if (!access) return null; + const { view } = access; + if (view.step === "waiting") { + return ( +
+ + {view.text} + +
+ ); + } + return ( +

+ {view.text} +

+ ); +} + +function Command({ command }: { command: string }) { + const { copy, copied } = useCopyToClipboard(); + return ( +
+ + {command} + + +
+ ); +} diff --git a/desktop-ui/src/components/app/remote/remote-service-chip.tsx b/desktop-ui/src/components/app/remote/remote-service-chip.tsx index cc14fbd..e9c0e57 100644 --- a/desktop-ui/src/components/app/remote/remote-service-chip.tsx +++ b/desktop-ui/src/components/app/remote/remote-service-chip.tsx @@ -1,7 +1,7 @@ "use client"; import { useQuery } from "@tanstack/react-query"; -import { useState } from "react"; +import { useRef, useState } from "react"; import { toast } from "sonner"; import type { RemoteControlAction, RemoteInventoryItemDto } from "@/types/localify"; @@ -15,6 +15,7 @@ import { ExternalLinkIcon, PlayIcon, RefreshIcon, + SpinnerIcon, TerminalIcon, XIcon, } from "@/components/icons"; @@ -26,20 +27,18 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { Popover, PopoverContent } from "@/components/ui/popover"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; import { bootstrapQueries } from "@/lib/queries"; import { tauriClient } from "@/lib/tauri-client"; -import { - ownerLabel, - remoteErrorMessage, - remoteHost, - serviceChips, - serviceTone, -} from "@/lib/util.remote"; +import { ownerLabel, remoteHost, serviceChips, serviceTone } from "@/lib/util.remote"; +import { type QuickAction, quickAction } from "@/lib/util.remote-controls"; import { cn } from "@/lib/utils"; import { remoteToneDot } from "./machine-switcher"; +import { useRemoteControls } from "./remote-controls"; +import { RemoteQuickActionCard } from "./remote-quick-action-card"; interface RemoteServiceChipProps { item: RemoteInventoryItemDto; @@ -55,8 +54,22 @@ export function RemoteServiceChip({ item, machineName, onOutput }: RemoteService const { data: bootstrap } = useQuery(bootstrapQueries.read()); const { copy, copied } = useCopyToClipboard(); const [menuOpen, setMenuOpen] = useState(false); + const controls = useRemoteControls(); + const chip = useRef(null); + // The card of a control that is not allowed, under the chip. + const [card, setCard] = useState(null); + const toggle: RemoteControlAction = item.process === "running" ? "stop" : "start"; + const controlOff = controls.down ?? controls.inFlight(item)?.text ?? null; + const restart = quickAction(item, "restart", controls.proto, machineName); + const cardQuick = card ? quickAction(item, card, controls.proto, machineName) : null; + const press = (action: RemoteControlAction) => { + const quick = quickAction(item, action, controls.proto, machineName); + if (quick.kind === "run") controls.run(item, action); + // Restart of a legacy run goes straight to its confirmation. + else if (quick.kind === "relaunch" && action === "restart") controls.relaunch(item); + else setCard((current) => (current === action ? null : action)); + }; const tone = serviceTone(item); - const running = item.process === "running"; const publicUrl = item.publicUrl?.serving ? item.publicUrl.url : null; const host = remoteHost(item.localUrl); const outputReason = outputUnavailableMessage(item, machineName); @@ -76,6 +89,7 @@ export function RemoteServiceChip({ item, machineName, onOutput }: RemoteService return ( press(toggle)} /> + { + if (open) return; + // The chip's own buttons open and toggle the card, and its menu hands focus back + // to it: neither closes the card here. + const event = details.event; + const target = + details.reason === "focus-out" && event instanceof FocusEvent + ? event.relatedTarget + : event?.target; + const inChip = target instanceof Node && chip.current?.contains(target); + if (inChip && (details.reason === "outside-press" || details.reason === "focus-out")) { + return; + } + setCard(null); + }} + > + + {card && cardQuick && cardQuick.kind !== "run" ? ( + setCard(null)} + /> + ) : null} + + + - - - - Show output - {outputReason ? ( - {outputReason} - ) : null} - - + {outputRelaunch(item, restart) ? ( + press("restart")}> + + + Relaunch to share + {controlOff ?? outputReason} + + + ) : ( + + + + Show output + {outputReason ? ( + {outputReason} + ) : null} + + + )} {publicUrl ? ( void openPublicUrl(publicUrl)}> @@ -192,13 +253,13 @@ export function RemoteServiceChip({ item, machineName, onOutput }: RemoteService {copied ? "URL copied" : "Copy URL"} - + press("restart")}> - Restart - - {controlReason(item, "restart", machineName)} - + {restart.kind === "relaunch" ? `Relaunch on ${machineName}` : "Restart"} + {controlOff ? ( + {controlOff} + ) : null} @@ -213,54 +274,65 @@ const CONTROL_LABEL: Record = { restart: "Restart", }; -/** Why a control is unavailable. Remote controls come in a later version. */ -function controlReason( - item: RemoteInventoryItemDto, - action: RemoteControlAction, - machineName: string, -): string { - const code = item.controls[action].code; - return code - ? remoteErrorMessage(code, machineName, "Not available.") - : `${CONTROL_LABEL[action]} from another machine comes in a later version.`; -} - -/** Start or Stop, where this Mac's chips put Launch or Stop; disabled, saying why. */ +/** + * Start or Stop, where this Mac's chips put Launch or Stop. Disabled only while the session + * is down or a control of this service is on its way; a control that is not allowed opens a + * card that says why. + */ function ControlButton({ item, action, machineName, - className, + off, + pending, + onPress, }: { item: RemoteInventoryItemDto; action: RemoteControlAction; machineName: string; - className?: string; + /** Why it can't be pressed now. */ + off: string | null; + pending: boolean; + onPress: () => void; }) { + const label = `${CONTROL_LABEL[action]} ${item.service.name} on ${machineName}`; return ( + } /> - - {CONTROL_LABEL[action]}: {controlReason(item, action, machineName)} - + {off ?? label} ); } +/** Output's "Relaunch to share": a legacy run this viewer can relaunch from here. */ +function outputRelaunch(item: RemoteInventoryItemDto, restart: QuickAction): boolean { + return ( + !item.output.available && item.output.reason === "legacy_run" && restart.kind === "relaunch" + ); +} + /** The dot's tooltip in words, for the keyboard and screen readers. */ function statusSummary(item: RemoteInventoryItemDto): string { const owner = ownerLabel(item.owner); diff --git a/desktop-ui/src/components/app/settings/settings-remote-access.tsx b/desktop-ui/src/components/app/settings/settings-remote-access.tsx index d45aea5..9161ab5 100644 --- a/desktop-ui/src/components/app/settings/settings-remote-access.tsx +++ b/desktop-ui/src/components/app/settings/settings-remote-access.tsx @@ -33,8 +33,6 @@ import { useRemote } from "@/providers/remote-provider"; import { SettingsCard } from "./settings-card"; -const CONTROLS_LATER = "Comes with remote controls, in a later version."; - /** * Settings → Remote access (docs/remote-machines.md, "Desktop app"): what paired machines may * see and do here, all off by default, this Mac's fingerprint, and the paired machines. @@ -81,6 +79,7 @@ export const SettingsRemoteAccess = () => {
) : null} + ) : null} @@ -95,13 +94,11 @@ function UpgradeAction() { function Switches({ settings }: { settings: RemoteSettingsDto }) { const queryClient = useQueryClient(); const change = useMutation(remoteMutations.changeSettings(queryClient)); - const setShare = (share: boolean) => - change.mutate( - { share }, - { - onError: (error) => toast.error("Could not change sharing", { description: error.message }), - }, - ); + const set = (request: Partial) => + change.mutate(request, { + onError: (error) => + toast.error("Could not change remote access", { description: error.message }), + }); return (
@@ -109,20 +106,22 @@ function Switches({ settings }: { settings: RemoteSettingsDto }) { label="Share projects and output with paired machines" checked={settings.share} disabled={change.isPending} - onChange={setShare} + onChange={(share) => set({ share })} note="Output can contain secrets your services print, and what you type into service tabs." /> set({ control })} + note={settings.share ? undefined : "Needs sharing."} /> set({ backgroundStarts })} + note={settings.control ? undefined : "Needs remote controls."} />
); @@ -138,11 +137,11 @@ function SwitchRow({ label: string; checked: boolean; disabled?: boolean; - onChange?: (checked: boolean) => void; + onChange: (checked: boolean) => void; note?: ReactNode; }) { return ( - + {access.error ? ( +

+ Could not answer the request: {access.error} +

+ ) : null} - - diff --git a/desktop-ui/src/components/app/remote/remote-command.tsx b/desktop-ui/src/components/app/remote/remote-command.tsx new file mode 100644 index 0000000..1a8df75 --- /dev/null +++ b/desktop-ui/src/components/app/remote/remote-command.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { CheckIcon, CopyIcon } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; + +/** A command to run on the target, with a copy button. */ +export function RemoteCommand({ command }: { command: string }) { + const { copy, copied } = useCopyToClipboard(); + return ( +
+ + {command} + + +
+ ); +} diff --git a/desktop-ui/src/components/app/remote/remote-controls.tsx b/desktop-ui/src/components/app/remote/remote-controls.tsx index dbabed2..6990335 100644 --- a/desktop-ui/src/components/app/remote/remote-controls.tsx +++ b/desktop-ui/src/components/app/remote/remote-controls.tsx @@ -32,6 +32,7 @@ import { import { openRemoteStream } from "@/lib/remote-stream"; import { remoteErrorMessage, serviceKey } from "@/lib/util.remote"; import { + accessCommand, type AccessView, accessEventView, type ControlPhase, @@ -44,6 +45,9 @@ import { relaunchConfirmation, relaunchStillConfirmed, } from "@/lib/util.remote-controls"; +import { createStreamRegistry } from "@/lib/util.stream-registry"; + +import { RemoteCommand } from "./remote-command"; /** After access is granted, how long a relaunch waits for the snapshot that allows it. */ const GRANTED_SNAPSHOT_MS = 15_000; @@ -114,6 +118,8 @@ export function RemoteControlsProvider({ const [controls, setControls] = useState>({}); // Set at the click, before React renders: a second click finds it. const busy = useRef(new Set()); + // The control streams still open, closed when the machine leaves the screen. + const controlStreams = useRef(createStreamRegistry()); const [access, setAccess] = useState(null); const closeAccess = useRef<(() => void) | null>(null); // Counts asks: events of an ask replaced or cancelled since are dropped. @@ -123,10 +129,13 @@ export function RemoteControlsProvider({ const live = useRef({ machineName, appRunning }); live.current = { machineName, appRunning }; - // A machine left on screen keeps nothing open with it, its request's toast included: the - // request's events are dropped from here on, so nothing else would close it. + // A machine left on screen keeps nothing open with it, toasts included: the streams' + // events are dropped from here on, so nothing else would close them. useEffect( () => () => { + for (const key of controlStreams.current.closeAll()) { + toast.dismiss(controlToastId(machineId, key)); + } askSeq.current += 1; closeAccess.current?.(); closeAccess.current = null; @@ -145,7 +154,8 @@ export function RemoteControlsProvider({ if (busy.current.has(key)) return; busy.current.add(key); const service = item.service.name; - const toastId = `remote-control:${machineId}:${key}`; + const toastId = controlToastId(machineId, key); + const stream = controlStreams.current.add(key); const progress = (phase: ControlPhase) => { const { machineName: name, appRunning: app } = live.current; const text = controlProgressText(action, phase, name, app); @@ -153,14 +163,15 @@ export function RemoteControlsProvider({ toast.loading(text, { id: toastId }); }; const settle = (ok: boolean, text: string) => { + stream.ended(); busy.current.delete(key); setControls(({ [key]: _, ...rest }) => rest); if (ok) toast.success(text, { id: toastId }); else toast.error(text, { id: toastId }); }; progress("sent"); - let ended = false; const onEvent = (event: RemoteControlEventDto) => { + if (!stream.live()) return; const name = live.current.machineName; switch (event.event) { case "sent": @@ -172,13 +183,11 @@ export function RemoteControlsProvider({ progress("unknown"); return; case "result": { - ended = true; const view = controlResultText(event, action, service, name); settle(view.ok, view.text); return; } case "lost": - ended = true; settle(false, controlLostText(event.code, name)); return; } @@ -188,19 +197,24 @@ export function RemoteControlsProvider({ { onData: onEvent, onEnd: (error) => { - if (!ended) settle(false, error ?? controlLostText("closed", live.current.machineName)); + if (stream.live()) { + settle(false, error ?? controlLostText("closed", live.current.machineName)); + } }, }, - ).catch((error: unknown) => - settle(false, error instanceof Error ? error.message : String(error)), - ); + ) + .then(stream.opened) + .catch((error: unknown) => { + if (stream.live()) settle(false, error instanceof Error ? error.message : String(error)); + }); }, [machineId], ); /** * Asks the target for access. A card shows the request as it goes; a relaunch confirmed in - * its dialog has no card, so a toast shows it, with Cancel. + * its dialog has no card, so a toast shows it, with Cancel. When it ends without access, the + * toast stays, with the command to run on the target instead. */ const ask = useCallback( (wants: RemoteAccessWants, inToast = false) => { @@ -209,17 +223,35 @@ export function RemoteControlsProvider({ const seq = ++askSeq.current; const isLatest = () => seq === askSeq.current; const toastId = `remote-access:${machineId}`; + // Updating a toast keeps the options it had: each step sets them all. + const options = { + id: toastId, + action: undefined, + description: undefined, + duration: undefined, + }; const show = (view: AccessView) => { setAccess({ wants, view }); if (view.step === "waiting") { if (inToast) { toast.loading(view.text, { - id: toastId, + ...options, action: { label: "Cancel", onClick: () => cancelRef.current() }, }); } - } else if (view.ok) toast.success(view.text, { id: toastId }); - else if (inToast) toast.error(view.text, { id: toastId }); + } else if (view.ok) toast.success(view.text, options); + else if (inToast) { + toast.error(view.text, { + ...options, + duration: Number.POSITIVE_INFINITY, + description: ( +
+ Or run this on {live.current.machineName}: + +
+ ), + }); + } }; show(accessEventView({ event: "waiting" }, wants, live.current.machineName)); let ended = false; @@ -389,6 +421,10 @@ export function RemoteControlsProvider({ ); } +function controlToastId(machineId: string, key: string): string { + return `remote-control:${machineId}:${key}`; +} + export function useRemoteControls(): RemoteControlsValue { const context = useContext(RemoteControlsContext); if (!context) throw new Error("useRemoteControls must be used inside RemoteControlsProvider"); diff --git a/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx b/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx index e7edf8e..86beb70 100644 --- a/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx +++ b/desktop-ui/src/components/app/remote/remote-quick-action-card.tsx @@ -4,13 +4,13 @@ import { useEffect } from "react"; import type { RemoteControlAction, RemoteInventoryItemDto } from "@/types/localify"; -import { CheckIcon, CopyIcon, SpinnerIcon } from "@/components/icons"; +import { SpinnerIcon } from "@/components/icons"; import { Button } from "@/components/ui/button"; -import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; import { remoteErrorMessage } from "@/lib/util.remote"; import { accessCommand, type QuickAction } from "@/lib/util.remote-controls"; import { cn } from "@/lib/utils"; +import { RemoteCommand } from "./remote-command"; import { useRemoteControls } from "./remote-controls"; /** @@ -41,7 +41,7 @@ export function RemoteQuickActionCard({

{remoteErrorMessage(code, name, "Not available.")}

Update Localify on {name} to ask from here.

- +
); case "ask": @@ -60,7 +60,7 @@ export function RemoteQuickActionCard({ )}

Or run this on {name}:

- +
); case "relaunch": @@ -88,6 +88,12 @@ export function RemoteQuickActionCard({ Relaunch on {name} )} + {quick.access ? ( + <> +

Or run this on {name}:

+ + + ) : null} ); } @@ -118,22 +124,3 @@ function AccessStatus() {

); } - -function Command({ command }: { command: string }) { - const { copy, copied } = useCopyToClipboard(); - return ( -
- - {command} - - -
- ); -} diff --git a/desktop-ui/src/lib/util.remote-controls.test.ts b/desktop-ui/src/lib/util.remote-controls.test.ts index 016ff72..093c9e4 100644 --- a/desktop-ui/src/lib/util.remote-controls.test.ts +++ b/desktop-ui/src/lib/util.remote-controls.test.ts @@ -6,6 +6,11 @@ import type { RemoteInventoryItemDto } from "../types/localify.ts"; import { accessCommand, + type AccessPrompt, + accessPromptAdded, + accessPromptAnswering, + accessPromptClosed, + accessPromptFailed, accessRequestTitle, accessEventView, controlLostText, @@ -411,3 +416,42 @@ test("the access dialog names a peer by its fingerprint's first 8 characters", ( "teo-laptop (3F2A 91C0) asks for remote controls.", ); }); + +type Request = { requestId: string; name: string }; +const prompt = (requestId: string, more: Partial> = {}) => ({ + requestId, + name: "teo-laptop", + answering: false, + error: null, + ...more, +}); + +test("access requests queue once each, the first on screen", () => { + let queue: AccessPrompt[] = []; + queue = accessPromptAdded(queue, { requestId: "a", name: "teo-laptop" }); + queue = accessPromptAdded(queue, { requestId: "b", name: "teo-laptop" }); + queue = accessPromptAdded(queue, { requestId: "a", name: "teo-laptop" }); + assert.deepEqual(queue, [prompt("a"), prompt("b")]); +}); + +test("an answer on its way keeps the dialog, with its buttons off, until it is through", () => { + let queue = [prompt("a", { error: "The daemon is not running." }), prompt("b")]; + queue = accessPromptAnswering(queue, "a"); + assert.deepEqual(queue, [prompt("a", { answering: true }), prompt("b")]); + + queue = accessPromptClosed(queue, "a"); + assert.deepEqual(queue, [prompt("b")]); +}); + +test("an answer that failed lets the request be answered again, with the error", () => { + let queue = accessPromptAnswering([prompt("a")], "a"); + queue = accessPromptFailed(queue, "a", "The daemon is not running."); + assert.deepEqual(queue, [prompt("a", { error: "The daemon is not running." })]); +}); + +test("an answer that failed after access_closed doesn't bring the dialog back", () => { + let queue = accessPromptAnswering([prompt("a"), prompt("b")], "a"); + queue = accessPromptClosed(queue, "a"); + queue = accessPromptFailed(queue, "a", "The daemon is not running."); + assert.deepEqual(queue, [prompt("b")]); +}); diff --git a/desktop-ui/src/lib/util.remote-controls.ts b/desktop-ui/src/lib/util.remote-controls.ts index 68c7c8f..a9a9af1 100644 --- a/desktop-ui/src/lib/util.remote-controls.ts +++ b/desktop-ui/src/lib/util.remote-controls.ts @@ -357,3 +357,52 @@ export function accessRequestTitle(name: string, fingerprint: string): string { ? `${name} (${short}) asks for remote controls.` : `${name} asks for remote controls.`; } + +/** An access request on the target, as its dialog shows it. */ +export type AccessPrompt = R & { + /** The answer is on its way: the buttons are off. */ + answering: boolean; + /** Why the last answer could not be sent; the request still waits. */ + error: string | null; +}; + +/** A request the daemon sent, queued once. */ +export function accessPromptAdded( + queue: AccessPrompt[], + request: R, +): AccessPrompt[] { + if (queue.some((prompt) => prompt.requestId === request.requestId)) return queue; + return [...queue, { ...request, answering: false, error: null }]; +} + +/** A request answered, or closed by the daemon (`access_closed`): its dialog goes. */ +export function accessPromptClosed( + queue: AccessPrompt[], + requestId: string, +): AccessPrompt[] { + return queue.filter((prompt) => prompt.requestId !== requestId); +} + +/** The answer is sent: the dialog stays, with its buttons off, until it is through. */ +export function accessPromptAnswering( + queue: AccessPrompt[], + requestId: string, +): AccessPrompt[] { + return queue.map((prompt) => + prompt.requestId === requestId ? { ...prompt, answering: true, error: null } : prompt, + ); +} + +/** + * The answer could not be sent: the request can be answered again, with the error shown, as + * long as it still waits. One the daemon closed meanwhile stays gone. + */ +export function accessPromptFailed( + queue: AccessPrompt[], + requestId: string, + error: string, +): AccessPrompt[] { + return queue.map((prompt) => + prompt.requestId === requestId ? { ...prompt, answering: false, error } : prompt, + ); +} diff --git a/desktop-ui/src/lib/util.stream-registry.test.ts b/desktop-ui/src/lib/util.stream-registry.test.ts new file mode 100644 index 0000000..9fd9de4 --- /dev/null +++ b/desktop-ui/src/lib/util.stream-registry.test.ts @@ -0,0 +1,67 @@ +/// +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { createStreamRegistry } from "./util.stream-registry.ts"; + +test("closeAll closes the open streams, and their late events are dropped", () => { + const registry = createStreamRegistry(); + const closed: string[] = []; + const web = registry.add("web"); + const api = registry.add("api"); + web.opened(() => closed.push("web")); + api.opened(() => closed.push("api")); + + assert.deepEqual(registry.closeAll(), ["web", "api"]); + assert.deepEqual(closed, ["web", "api"]); + assert.equal(web.live(), false); + assert.equal(api.live(), false); + assert.equal(registry.size(), 0); +}); + +test("a stream whose opening resolves after closeAll is closed at once", () => { + const registry = createStreamRegistry(); + const web = registry.add("web"); + // Still opening: its key is returned, so its toast is dismissed. + assert.deepEqual(registry.closeAll(), ["web"]); + + let closed = 0; + web.opened(() => closed++); + assert.equal(closed, 1); + assert.equal(web.live(), false); + assert.equal(registry.size(), 0); +}); + +test("a stream that ended by itself is forgotten, not closed again", () => { + const registry = createStreamRegistry(); + let closed = 0; + const web = registry.add("web"); + web.opened(() => closed++); + web.ended(); + + assert.equal(web.live(), false); + assert.deepEqual(registry.closeAll(), []); + assert.equal(closed, 0); +}); + +test("a stream that ended before its opening resolved is closed when it does", () => { + const registry = createStreamRegistry(); + const web = registry.add("web"); + web.ended(); + let closed = 0; + web.opened(() => closed++); + assert.equal(closed, 1); + assert.equal(registry.size(), 0); +}); + +test("a newer stream of the same key is its own: the old one's end leaves it live", () => { + const registry = createStreamRegistry(); + const old = registry.add("web"); + old.ended(); + const fresh = registry.add("web"); + old.ended(); + + assert.equal(old.live(), false); + assert.equal(fresh.live(), true); + assert.equal(registry.size(), 1); +}); diff --git a/desktop-ui/src/lib/util.stream-registry.ts b/desktop-ui/src/lib/util.stream-registry.ts new file mode 100644 index 0000000..d5d764d --- /dev/null +++ b/desktop-ui/src/lib/util.stream-registry.ts @@ -0,0 +1,52 @@ +// The streams a component keeps open, so it closes them all when it goes. Pure, so it is +// tested without a window. + +/** One stream of the registry, from the moment it is asked for. */ +export interface StreamHandle { + /** False once the stream ended or the registry closed it: its events are dropped. */ + live(): boolean; + /** The stream opened: its closer is kept, or called at once when it is no longer live. */ + opened(close: () => void): void; + /** The stream ended by itself: it is forgotten, and its later events are dropped. */ + ended(): void; +} + +export interface StreamRegistry { + /** Registers a stream before it opens, so one whose opening resolves late is closed too. */ + add(key: string): StreamHandle; + /** Closes every live stream, and returns their keys. */ + closeAll(): string[]; + /** How many streams are live. */ + size(): number; +} + +export function createStreamRegistry(): StreamRegistry { + // A live stream's closer, null until it opened. + const streams = new Map void) | null }>(); + return { + add(key) { + const id = Symbol(key); + streams.set(id, { key, close: null }); + return { + live: () => streams.has(id), + opened(close) { + const stream = streams.get(id); + if (stream) stream.close = close; + else close(); + }, + ended() { + streams.delete(id); + }, + }; + }, + closeAll() { + const keys = [...streams.values()].map(({ key, close }) => { + close?.(); + return key; + }); + streams.clear(); + return keys; + }, + size: () => streams.size, + }; +} diff --git a/desktop-ui/src/providers/remote-provider.tsx b/desktop-ui/src/providers/remote-provider.tsx index 33d421f..782e372 100644 --- a/desktop-ui/src/providers/remote-provider.tsx +++ b/desktop-ui/src/providers/remote-provider.tsx @@ -31,7 +31,14 @@ import { remoteQueries } from "@/lib/queries"; import { openRemoteStream } from "@/lib/remote-stream"; import { tauriClient } from "@/lib/tauri-client"; import { pairingCancelledMessage } from "@/lib/util.remote"; -import { accessRequestTitle } from "@/lib/util.remote-controls"; +import { + type AccessPrompt, + accessPromptAdded, + accessPromptAnswering, + accessPromptClosed, + accessPromptFailed, + accessRequestTitle, +} from "@/lib/util.remote-controls"; /** How long the app waits before it listens to the daemon again. */ const EVENTS_RETRY_MS = 5000; @@ -79,8 +86,9 @@ interface RemoteContextValue { answerIncoming: (accept: boolean) => Promise; dismissIncoming: () => void; /** The access request on screen; the others wait their turn. */ - access: IncomingAccess | null; - answerAccess: (allow: boolean, suppress: boolean) => Promise; + access: AccessPrompt | null; + /** Answers the request on screen; a failure shows in its dialog, which stays. */ + answerAccess: (allow: boolean, suppress: boolean) => void; /** A remote service's output covers the bottom of the window, as the terminal does. */ outputOpen: boolean; setOutputOpen: (open: boolean) => void; @@ -95,7 +103,7 @@ export function RemoteProvider({ children }: PropsWithChildren) { const [outgoing, setOutgoing] = useState(null); const [incoming, setIncoming] = useState(null); const [outputOpen, setOutputOpen] = useState(false); - const [accessQueue, setAccessQueue] = useState([]); + const [accessQueue, setAccessQueue] = useState[]>([]); const access = accessQueue[0] ?? null; const closeOutgoing = useRef<(() => void) | null>(null); const incomingRef = useRef(incoming); @@ -134,18 +142,12 @@ export function RemoteProvider({ children }: PropsWithChildren) { return; case "access_request": { const { event: _, expiresAt: __, ...request } = event; - setAccessQueue((queue) => - queue.some((waiting) => waiting.requestId === request.requestId) - ? queue - : [...queue, request], - ); + setAccessQueue((queue) => accessPromptAdded(queue, request)); void notify(accessRequestTitle(request.name, request.fingerprint)); return; } case "access_closed": - setAccessQueue((queue) => - queue.filter((waiting) => waiting.requestId !== event.requestId), - ); + setAccessQueue((queue) => accessPromptClosed(queue, event.requestId)); return; case "presence": case "revoked": @@ -278,19 +280,31 @@ export function RemoteProvider({ children }: PropsWithChildren) { const accessRef = useRef(access); accessRef.current = access; + // Set at the click, before React renders: a second click finds it. + const answering = useRef(new Set()); + // The dialog stays until the answer is through or `access_closed` arrives: the daemon + // still waits when the answer could not be sent, and "Don't ask again" with it. const answerAccess = useCallback( - async (allow: boolean, suppress: boolean) => { + (allow: boolean, suppress: boolean) => { const current = accessRef.current; - if (!current) return; - setAccessQueue((queue) => queue.filter((waiting) => waiting.requestId !== current.requestId)); - const { outcome } = await tauriClient.answerRemoteAccess({ - requestId: current.requestId, - allow, - suppress, - }); - void queryClient.invalidateQueries({ queryKey: remoteQueries.all() }); - if (outcome === "granted") toast.success("Remote controls are on for every paired machine."); - else if (allow) toast.info("That request had already ended. Nothing changed."); + if (!current || answering.current.has(current.requestId)) return; + const { requestId } = current; + answering.current.add(requestId); + setAccessQueue((queue) => accessPromptAnswering(queue, requestId)); + void tauriClient + .answerRemoteAccess({ requestId, allow, suppress }) + .then(({ outcome }) => { + setAccessQueue((queue) => accessPromptClosed(queue, requestId)); + void queryClient.invalidateQueries({ queryKey: remoteQueries.all() }); + if (outcome === "granted") { + toast.success("Remote controls are on for every paired machine."); + } else if (allow) toast.info("That request had already ended. Nothing changed."); + }) + .catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + setAccessQueue((queue) => accessPromptFailed(queue, requestId, message)); + }) + .finally(() => answering.current.delete(requestId)); }, [queryClient], ); diff --git a/docs/remote-machines.md b/docs/remote-machines.md index e116233..ace106a 100644 --- a/docs/remote-machines.md +++ b/docs/remote-machines.md @@ -783,7 +783,7 @@ The daemon opens a session only when one of these asks for it, carries every req - **A remote machine's view** is the Projects screen of that machine, drawn like this Mac's and read-only: no editor, no domain or profile editing, no terminal. A banner says "You're viewing B. Its .localify URLs open only on B." Each project is a card like this Mac's: the primary checkout's services as domain chips, and each worktree folded under one line with its count of services that answer. A chip holds a dot (green once the service answers, amber while it starts, red after a failed exit, grey when stopped), the domain, the port, the public URL's globe, the launch profile, Start or Stop, and a menu with `Show output`, `Open public URL`, `Copy URL` and `Restart`. The dot's tooltip gives the owner ("In the app", "In the background", "In a terminal", "Unknown process") and the four states: Process, Port, Output, Public URL. The Start, Stop and Restart buttons follow `controls`. A control in flight shows its progress, and `unknown` shows "Outcome unknown. Checking B…". - **Quick actions:** a control that is not allowed stays clickable and opens a small card that says why and what fixes it, instead of a disabled button: - `control_disabled` or `background_disabled`, on a target whose session agreed on protocol 2 (`proto` in `remote_machines`): `Ask B`, which sends `access.request` and shows "Waiting for an answer on B…" with `Cancel`, then "B allowed remote controls.", "B didn't allow it.", "Nobody can answer on B: Localify isn't open there.", or the end's reason. `background_disabled` asks for `backgroundStarts`. So does `control_disabled` when the control would run in the background on B: a start while B's app is absent (`machine.app` is `absent`), or a restart of a background run. `backgroundStarts` turns `control` on too, so one request is enough; asking for `control` first would get `background_disabled` next, and a second request within 10 minutes gets `too_many`. Otherwise `control_disabled` asks for `control`. Below it, always, "Or run this on B:" with the command for the same switches, `localify machines settings --control on`, or `localify machines settings --control on --background-starts on`, and a copy button. On a target of protocol 1, only the command shows, under "Update Localify on B to ask from here." - - `legacy_run` on a run with `legacyId`, on protocol 2, Output's "Relaunch to share" for the same run, and `Restart` of a run with `legacyId` even when `controls.restart` allows it: `Relaunch on B`, always after a confirmation: "web started before this version of Localify on B. Relaunch it so its output and controls work here? It restarts with its configured command." When controls are off, the card asks for access first; once granted, it relaunches only if the snapshot still shows the same `legacyId` and `configRev` the person confirmed, and asks again otherwise. + - `legacy_run` on a run with `legacyId`, on protocol 2, Output's "Relaunch to share" for the same run, and `Restart` of a run with `legacyId` even when `controls.restart` allows it: `Relaunch on B`, always after a confirmation: "web started before this version of Localify on B. Relaunch it so its output and controls work here? It restarts with its configured command." When controls are off, the card asks for access first, and shows "Or run this on B:" with the command, as `Ask B` does; once granted, it relaunches only if the snapshot still shows the same `legacyId` and `configRev` the person confirmed, and asks again otherwise. A request that ends without access (`nobody`, `declined`, an error) leaves its reason on screen with the same command, until the person closes it. - `legacy_run` with no `legacyId`, or on protocol 1: "Relaunch it on B." (or "Update Localify on B."), with no action. So are `not_owned`, `owner_gone`, `refused_profile` and the others: the message, with no action. - **URLs:** a remote `.localify` URL is copied, never opened. Clicking the domain opens the output when it is shared, and copies the URL otherwise. When the service has a public URL that serves, its globe and `Open public URL` open it. - **Output** opens in a panel docked at the bottom, sized, coloured and resized like the terminal panel, titled with the project and service, "on B", with search, Follow / Pause and selectable text (see "Output"). The terminal panel holds this Mac's PTYs only, so remote output stays out of it; opening one closes the other. diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 15b35cd..61444de 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -13,7 +13,9 @@ "dialog:allow-message", "global-shortcut:allow-register", "global-shortcut:allow-unregister", - "notification:default", + "notification:allow-is-permission-granted", + "notification:allow-request-permission", + "notification:allow-notify", { "identifier": "opener:allow-open-url", "allow": [{ "url": "http://**" }, { "url": "https://**" }] From 99e4b85433002586c0562b8d859432e98eacde2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 17:09:10 +0100 Subject: [PATCH 6/6] fix(remote): close a control stream's transport once it settles The daemon can send a control's last event, then keep the stream open while it fetches a fresh snapshot. Settling only forgot the stream, so leaving the machine in that window left its reader running until EOF. Settling now closes the transport too; closing one already ended does nothing. --- desktop-ui/src/lib/util.stream-registry.test.ts | 7 +++++-- desktop-ui/src/lib/util.stream-registry.ts | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/desktop-ui/src/lib/util.stream-registry.test.ts b/desktop-ui/src/lib/util.stream-registry.test.ts index 9fd9de4..9731441 100644 --- a/desktop-ui/src/lib/util.stream-registry.test.ts +++ b/desktop-ui/src/lib/util.stream-registry.test.ts @@ -32,16 +32,19 @@ test("a stream whose opening resolves after closeAll is closed at once", () => { assert.equal(registry.size(), 0); }); -test("a stream that ended by itself is forgotten, not closed again", () => { +test("a stream that settled has its transport closed once, and is forgotten", () => { + // The daemon can send the last event, then keep the stream open while it fetches a + // snapshot: settling closes it, so leaving the machine finds nothing left open. const registry = createStreamRegistry(); let closed = 0; const web = registry.add("web"); web.opened(() => closed++); web.ended(); + assert.equal(closed, 1); assert.equal(web.live(), false); assert.deepEqual(registry.closeAll(), []); - assert.equal(closed, 0); + assert.equal(closed, 1); }); test("a stream that ended before its opening resolved is closed when it does", () => { diff --git a/desktop-ui/src/lib/util.stream-registry.ts b/desktop-ui/src/lib/util.stream-registry.ts index d5d764d..ea2da78 100644 --- a/desktop-ui/src/lib/util.stream-registry.ts +++ b/desktop-ui/src/lib/util.stream-registry.ts @@ -7,7 +7,10 @@ export interface StreamHandle { live(): boolean; /** The stream opened: its closer is kept, or called at once when it is no longer live. */ opened(close: () => void): void; - /** The stream ended by itself: it is forgotten, and its later events are dropped. */ + /** + * The stream settled (its last event came): it is forgotten, its later events are dropped, + * and its transport is closed, since the daemon may still hold it open after its last event. + */ ended(): void; } @@ -35,7 +38,9 @@ export function createStreamRegistry(): StreamRegistry { else close(); }, ended() { + const stream = streams.get(id); streams.delete(id); + stream?.close?.(); }, }; },