Skip to main content

isothrum_client/
client.rs

1//! The client: one connection for requests and their replies, and one more per subscription.
2
3mod console;
4mod events;
5mod home;
6pub use console::HeldConsole;
7use events::OperationEvents;
8pub use events::{Followed, Subscription};
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11use std::pin::Pin;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, Mutex, PoisonError};
14use std::task::{Context, Poll};
15use std::time::{Duration, Instant};
16
17use isothrum_runner::{ErrorCode, ErrorReport, EventKind, InputVariable, Park, RunName, Status};
18use tokio::sync::{mpsc, oneshot};
19
20use crate::discovery::{ServiceInfo, ServicePaths};
21use crate::error::ClientError;
22use crate::proto::{Command, OpOptions, PROTOCOL, Reply, Request, Target};
23use crate::v1::{Event, EventCursor, OperationId, OperationPhase, OperationRow, RunRow, is_outcome, phase_of};
24use crate::wire::{Reader, Writer, connect, write_line};
25use crate::{VERSION, replace, spawn};
26
27/// How long a client waits for a service it started to answer: it connects as soon as the
28/// service does, so this only bounds a start that hangs. A binary's first run can take long on
29/// a loaded machine (macOS checks a new executable before it runs it).
30const START_WAIT: Duration = Duration::from_secs(30);
31
32/// How many of a subscription's events wait for their reader before the connection is read no
33/// further (the service then sends what was missed as it can).
34const SUBSCRIPTION_BUFFER: usize = 1024;
35
36/// How many of a run's newest operations [`Client::follow_again`] reads: the one it may follow,
37/// and those still ahead of it.
38const OPERATIONS_LOOKED_AT: u32 = 16;
39
40/// What `Client::connect` returns.
41type Result<T, E = ClientError> = std::result::Result<T, E>;
42
43/// An operation the service queued.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Accepted {
46    /// Its id.
47    pub operation: OperationId,
48    /// Its run.
49    pub run: RunName,
50    /// How many of the run's operations are ahead of it (0: it begins now).
51    pub position: u32,
52}
53
54/// A connection to a home's runner service.
55pub struct Client {
56    shared: Arc<Shared>,
57    reader: tokio::task::JoinHandle<()>,
58    paths: ServicePaths,
59    info: ServiceInfo,
60}
61
62/// What the requests share with the task reading their replies.
63struct Shared {
64    writer: tokio::sync::Mutex<Writer>,
65    pending: Mutex<HashMap<u64, oneshot::Sender<Reply>>>,
66    next: AtomicU64,
67}
68
69impl Drop for Client {
70    fn drop(&mut self) {
71        self.reader.abort();
72    }
73}
74
75impl std::fmt::Debug for Client {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("Client")
78            .field("home", &self.paths.home())
79            .field("service", &self.info)
80            .finish_non_exhaustive()
81    }
82}
83
84/// `home`, absolute, its links resolved when it exists: the same home reads the same from any
85/// client.
86fn resolve(home: &Path) -> PathBuf {
87    let absolute = std::path::absolute(home).unwrap_or_else(|_| home.to_path_buf());
88    std::fs::canonicalize(&absolute).unwrap_or(absolute)
89}
90
91/// A connection to the service at `endpoint`, its `hello` sent, and the service's first answer.
92async fn hello(endpoint: &str) -> Result<(Reader, Writer, Option<Reply>)> {
93    let (mut reader, mut writer) = connect(endpoint)
94        .await
95        .map_err(|e| ClientError::Unavailable(format!("the service at {endpoint} doesn't answer: {e}")))?;
96    write_line(
97        &mut writer,
98        &Request {
99            id: 0,
100            command: Command::Hello { protocol: PROTOCOL },
101        },
102    )
103    .await?;
104    let first = reader.next::<Reply>().await?;
105    Ok((reader, writer, first))
106}
107
108/// One connection to the service of `paths`, past its `hello`, and what the service says of
109/// itself (its version as its `hello` gives it).
110async fn open(paths: &ServicePaths) -> Result<(Reader, Writer, ServiceInfo)> {
111    let info = paths
112        .read_info()
113        .ok_or_else(|| ClientError::Unavailable(format!("no service runs for {}", paths.home().display())))?;
114    let (reader, writer, first) = hello(&info.endpoint).await?;
115    match first {
116        Some(Reply::Hello { protocol, version, .. }) if protocol == PROTOCOL => Ok((reader, writer, ServiceInfo { version, ..info })),
117        Some(Reply::Hello { protocol, version, .. }) => Err(ClientError::Protocol(format!(
118            "the service (Isothrum {version}) speaks protocol {protocol}, this client {PROTOCOL}: stop it to let this version start its own"
119        ))),
120        Some(Reply::Error { report, .. }) => Err(ClientError::Protocol(report.message)),
121        Some(other) => Err(ClientError::Protocol(format!("expected the service's hello, got {other:?}"))),
122        None => Err(ClientError::closed()),
123    }
124}
125
126impl Client {
127    /// Connects to `home`'s service, starting it (`isothrum serve --home <home> --detach`:
128    /// `binary` when given, else the `isothrum` beside this program, else the one on `PATH`)
129    /// when none answers, and waiting up to 30 seconds for it (less once it ended without answering).
130    ///
131    /// # Errors
132    ///
133    /// [`ClientError::Unavailable`] when none answers and none could be started (with the end of
134    /// its log); [`ClientError::Protocol`] when the service speaks another protocol.
135    pub async fn connect(home: &Path, binary: Option<&Path>) -> Result<Client> {
136        let paths = ServicePaths::new(resolve(home));
137        match open(&paths).await {
138            Err(ClientError::Unavailable(_)) => {}
139            opened => return opened.map(|(r, w, info)| Client::over(paths, r, w, info)),
140        }
141        Client::start(paths, binary).await
142    }
143
144    /// Connects to `home`'s service of this release ([`VERSION`]), protocol and build (of
145    /// `binary`: [`ServiceInfo::build`]): the one that runs when it is, else after replacing the one
146    /// of another release or build (stopped, or ended when it doesn't answer), else none; a service it then starts as [`Client::connect`] does
147    /// (`binary`: the `isothrum` of this release). How it replaces a service is in the crate's
148    /// documentation.
149    ///
150    /// # Errors
151    ///
152    /// [`ClientError::Busy`] when the service of another release has operations queued or
153    /// running: it is left running; [`ClientError::Version`] when the service started is another
154    /// release (`binary` isn't this one's); [`ClientError::Unavailable`] when the service couldn't
155    /// be stopped (it doesn't answer, and can't be told from another process, or doesn't end) or
156    /// none could be started; [`ClientError::Protocol`] when it refused to stop.
157    pub async fn connect_exact(home: &Path, binary: Option<&Path>) -> Result<Client> {
158        let paths = ServicePaths::new(resolve(home));
159        let binary = spawn::binary(binary);
160        let _turn = replace::Turn::take(&paths).await?;
161        if let Some((r, w, info)) = replace::make_room(&paths, crate::build_of(&binary).as_deref()).await? {
162            return Ok(Client::over(paths, r, w, info));
163        }
164        let client = Client::start(paths, Some(&binary)).await?;
165        if client.info.version == VERSION {
166            return Ok(client);
167        }
168        // Not this release's: it is left as it was found, with no service.
169        if let Err(e) = client.request(Command::ShutdownIfIdle).await {
170            tracing::debug!(error = %e, "the service of another release just started couldn't be stopped");
171        }
172        Err(ClientError::Version {
173            client: VERSION.to_owned(),
174            service: client.info.version.clone(),
175        })
176    }
177
178    /// Starts `binary`'s service for the home of `paths` (see [`Client::connect`]), and connects
179    /// to it.
180    async fn start(paths: ServicePaths, binary: Option<&Path>) -> Result<Client> {
181        let binary = spawn::binary(binary);
182        let mut child = spawn::start(&binary, &paths).map_err(|e| ClientError::Unavailable(format!("{} couldn't be started: {e}", binary.display())))?;
183        // Until it answers, hangs past START_WAIT, or ends without answering (a binary that
184        // refuses `serve`, a home it can't open): waiting START_WAIT out for that one cost every
185        // connection 30 s for an answer that never comes. Its end is read before the look, so
186        // the look after it ended still meets a service that answers (another client's, which
187        // took the home first and made this one end).
188        let deadline = Instant::now() + START_WAIT;
189        let (opened, ended) = loop {
190            tokio::time::sleep(Duration::from_millis(50)).await;
191            let ended = child.try_wait().ok().flatten();
192            match open(&paths).await {
193                Err(ClientError::Unavailable(why)) if ended.is_none() && Instant::now() < deadline => {
194                    tracing::trace!(%why, "waiting for the service");
195                }
196                opened => break (opened, ended),
197            }
198        };
199        // The service outlives this client; a thread reaps it should it end first.
200        std::thread::spawn(move || child.wait());
201        match opened {
202            Ok((r, w, info)) => Ok(Client::over(paths, r, w, info)),
203            Err(ClientError::Unavailable(why)) => Err(ClientError::Unavailable(format!(
204                "{why}; the service started from {} {}: {}",
205                binary.display(),
206                ended.map_or_else(|| "didn't answer".to_owned(), |status| format!("ended without answering ({status})")),
207                spawn::log_tail(&paths)
208            ))),
209            Err(e) => Err(e),
210        }
211    }
212
213    /// Connects to `home`'s service when one runs, starting none.
214    ///
215    /// # Errors
216    ///
217    /// [`ClientError::Unavailable`] when none answers.
218    pub async fn connect_running(home: &Path) -> Result<Client> {
219        let paths = ServicePaths::new(resolve(home));
220        let (r, w, info) = open(&paths).await?;
221        Ok(Client::over(paths, r, w, info))
222    }
223
224    /// The client over a connection past its `hello`.
225    fn over(paths: ServicePaths, mut reader: Reader, writer: Writer, info: ServiceInfo) -> Client {
226        let shared = Arc::new(Shared {
227            writer: tokio::sync::Mutex::new(writer),
228            pending: Mutex::default(),
229            next: AtomicU64::new(1),
230        });
231        let replies = Arc::clone(&shared);
232        let reader = tokio::spawn(async move {
233            while let Ok(Some(reply)) = reader.next::<Reply>().await {
234                let Some(id) = reply.id() else { continue };
235                let waiting = replies.pending.lock().unwrap_or_else(PoisonError::into_inner).remove(&id);
236                if let Some(waiting) = waiting {
237                    // A caller that gave up on its reply dropped its receiver: nothing to do.
238                    drop(waiting.send(reply));
239                }
240            }
241            // Every caller still waiting learns the connection ended.
242            replies.pending.lock().unwrap_or_else(PoisonError::into_inner).clear();
243        });
244        Client { shared, reader, paths, info }
245    }
246
247    /// What the service said of itself when it started.
248    #[must_use]
249    pub fn service(&self) -> &ServiceInfo {
250        &self.info
251    }
252
253    /// Sends `command`, and returns its reply (an error reply as [`ClientError::Refused`]).
254    ///
255    /// # Errors
256    ///
257    /// The service refused it, or the connection ended: before `command` was sent
258    /// ([`ClientError::Io`]), or after, unanswered ([`ClientError::Unanswered`]).
259    pub async fn request(&self, command: Command) -> Result<Reply> {
260        let id = self.shared.next.fetch_add(1, Ordering::Relaxed);
261        let (tx, rx) = oneshot::channel();
262        self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner).insert(id, tx);
263        let written = write_line(&mut *self.shared.writer.lock().await, &Request { id, command }).await;
264        if let Err(e) = written {
265            self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner).remove(&id);
266            return Err(e.into());
267        }
268        // Sent: an end of the connection now leaves unknown whether the service acted on it.
269        match rx.await.map_err(|_| ClientError::Unanswered)? {
270            Reply::Error { report, .. } => Err(ClientError::Refused(Box::new(report))),
271            reply => Ok(reply),
272        }
273    }
274
275    /// Queues the operation `command` asks for.
276    ///
277    /// # Errors
278    ///
279    /// The service refused it (the run can't be opened, another operation of the run is queued
280    /// or running: [`ErrorCode::Locked`], the service is
281    /// stopping), or `command` isn't an operation ([`ClientError::Protocol`]).
282    pub async fn submit(&self, command: Command) -> Result<Accepted> {
283        if command.op().is_none() {
284            return Err(ClientError::Protocol(format!("not an operation: {command:?}")));
285        }
286        match self.request(command).await? {
287            Reply::Accepted { operation, run, position, .. } => Ok(Accepted { operation, run, position }),
288            other => Err(unexpected(&other)),
289        }
290    }
291
292    /// Queues `up`.
293    ///
294    /// # Errors
295    ///
296    /// As [`Client::submit`].
297    pub async fn up(&self, target: Target, options: OpOptions) -> Result<Accepted> {
298        self.submit(Command::Up {
299            target,
300            options,
301            lifetime_s: None,
302        })
303        .await
304    }
305
306    /// Queues `down`.
307    ///
308    /// # Errors
309    ///
310    /// As [`Client::submit`].
311    pub async fn down(&self, target: Target, options: OpOptions) -> Result<Accepted> {
312        self.submit(Command::Down { target, options }).await
313    }
314
315    /// Queues `park`.
316    ///
317    /// # Errors
318    ///
319    /// As [`Client::submit`].
320    pub async fn park(&self, target: Target, options: OpOptions, mode: Park) -> Result<Accepted> {
321        self.submit(Command::Park { target, options, mode }).await
322    }
323
324    /// Queues `resume`.
325    ///
326    /// # Errors
327    ///
328    /// As [`Client::submit`].
329    pub async fn resume(&self, target: Target, options: OpOptions) -> Result<Accepted> {
330        self.submit(Command::Resume { target, options }).await
331    }
332
333    /// Queues `update`.
334    ///
335    /// # Errors
336    ///
337    /// As [`Client::submit`].
338    pub async fn update(&self, target: Target, options: OpOptions) -> Result<Accepted> {
339        self.submit(Command::Update { target, options }).await
340    }
341
342    /// Queues `retire` of `machine`.
343    ///
344    /// # Errors
345    ///
346    /// As [`Client::submit`].
347    pub async fn retire(&self, target: Target, options: OpOptions, machine: String) -> Result<Accepted> {
348        self.submit(Command::Retire { target, options, machine }).await
349    }
350
351    /// Queues `package` of `machine` into the box file `output`.
352    ///
353    /// # Errors
354    ///
355    /// As [`Client::submit`].
356    pub async fn package(&self, target: Target, options: OpOptions, machine: String, output: std::path::PathBuf) -> Result<Accepted> {
357        self.submit(Command::Package {
358            target,
359            options,
360            machine,
361            output,
362        })
363        .await
364    }
365
366    /// Queues `attach` of `machine`.
367    ///
368    /// # Errors
369    ///
370    /// As [`Client::submit`].
371    pub async fn attach(&self, target: Target, options: OpOptions, machine: String) -> Result<Accepted> {
372        self.submit(Command::Attach { target, options, machine }).await
373    }
374
375    /// Queues `exec` of `argv` in `machine`.
376    ///
377    /// # Errors
378    ///
379    /// As [`Client::submit`].
380    pub async fn exec(&self, target: Target, options: OpOptions, machine: String, argv: Vec<String>) -> Result<Accepted> {
381        self.submit(Command::Exec {
382            target,
383            options,
384            machine,
385            argv,
386        })
387        .await
388    }
389
390    /// Cancels `operation`: queued, it never begins; running, it is cut short.
391    ///
392    /// # Errors
393    ///
394    /// The service refused (an unknown or ended operation), or the connection ended.
395    pub async fn cancel(&self, operation: OperationId) -> Result<()> {
396        self.request(Command::Cancel { operation }).await.map(drop)
397    }
398
399    /// Run `run`'s status (`target`: where to open it, for a run not recorded yet; else as
400    /// recorded).
401    ///
402    /// # Errors
403    ///
404    /// The runner couldn't read it, or the connection ended.
405    pub async fn status(&self, run: &RunName, target: Option<Target>) -> Result<Status> {
406        self.status_with(run, target, OpOptions::default()).await
407    }
408
409    /// [`Client::status`], the read's tools given `options`' values and secrets (a Proxmox VE
410    /// module's API token, for its VMs' states on the server).
411    ///
412    /// # Errors
413    ///
414    /// As [`Client::status`]; `server_auth_failed` when a server refuses the credentials.
415    pub async fn status_with(&self, run: &RunName, target: Option<Target>, options: OpOptions) -> Result<Status> {
416        let command = Command::Status {
417            run: run.clone(),
418            target,
419            options,
420        };
421        match self.request(command).await? {
422            Reply::Status { status, .. } => Ok(*status),
423            other => Err(unexpected(&other)),
424        }
425    }
426
427    /// The input variables the Terraform folder `target` names declares (name, type, default,
428    /// sensitive), read from its files: a sensitive one is given as a secret, which no record
429    /// keeps.
430    ///
431    /// # Errors
432    ///
433    /// The folder isn't a Terraform module (`unsupported`, `project_invalid`), or the connection
434    /// ended.
435    pub async fn variables(&self, target: Target) -> Result<Vec<InputVariable>> {
436        match self.request(Command::Variables { target }).await? {
437            Reply::Variables { variables, .. } => Ok(variables),
438            other => Err(unexpected(&other)),
439        }
440    }
441
442    /// Every recorded run.
443    ///
444    /// # Errors
445    ///
446    /// The runner couldn't read them, or the connection ended.
447    pub async fn list(&self) -> Result<Vec<RunRow>> {
448        match self.request(Command::List).await? {
449            Reply::Runs { runs, .. } => Ok(runs),
450            other => Err(unexpected(&other)),
451        }
452    }
453
454    /// A connection of its own to the service, past its `hello`.
455    pub(super) async fn dedicated(&self) -> Result<(Reader, Writer)> {
456        let (reader, writer, first) = hello(&self.info.endpoint).await?;
457        match first {
458            Some(Reply::Hello { .. }) => Ok((reader, writer)),
459            Some(Reply::Error { report, .. }) => Err(ClientError::Refused(Box::new(report))),
460            Some(other) => Err(unexpected(&other)),
461            None => Err(ClientError::closed()),
462        }
463    }
464
465    /// Run `run`'s latest operations, newest first.
466    ///
467    /// # Errors
468    ///
469    /// The connection ended.
470    pub async fn operations(&self, run: &RunName, limit: u32) -> Result<Vec<OperationRow>> {
471        match self.request(Command::Operations { run: run.clone(), limit }).await? {
472            Reply::Operations { operations, .. } => Ok(operations),
473            other => Err(unexpected(&other)),
474        }
475    }
476
477    /// Stops the service: its operations are cancelled and their tools stopped.
478    ///
479    /// # Errors
480    ///
481    /// The connection ended before the service answered.
482    pub async fn shutdown(&self) -> Result<()> {
483        self.request(Command::Shutdown).await.map(drop)
484    }
485
486    /// The events after `after` (every one the service keeps when `None`), then the live ones, of
487    /// run `run` or of every run, on a connection of their own.
488    ///
489    /// # Errors
490    ///
491    /// The service refused, or doesn't answer.
492    pub async fn subscribe(&self, run: Option<RunName>, after: Option<EventCursor>) -> Result<Subscription> {
493        let (mut reader, mut writer) = self.dedicated().await?;
494        write_line(
495            &mut writer,
496            &Request {
497                id: 1,
498                command: Command::Subscribe { run, after },
499            },
500        )
501        .await?;
502        match reader.next::<Reply>().await? {
503            Some(Reply::Ok { id: 1 }) => {}
504            Some(Reply::Error { report, .. }) => return Err(ClientError::Refused(Box::new(report))),
505            Some(other) => return Err(unexpected(&other)),
506            None => return Err(ClientError::closed()),
507        }
508        let (tx, rx) = mpsc::channel(SUBSCRIPTION_BUFFER);
509        let task = tokio::spawn(async move {
510            // The writing half stays open as long as the subscription: closing it ends it.
511            let _writer = writer;
512            loop {
513                let item = match reader.next::<Reply>().await {
514                    Ok(Some(Reply::Event { cursor, event })) => Ok((cursor, *event)),
515                    Ok(Some(_)) => continue,
516                    Ok(None) => Err(ClientError::closed()),
517                    Err(e) => Err(ClientError::Io(e)),
518                };
519                let last = item.is_err();
520                if tx.send(item).await.is_err() || last {
521                    return;
522                }
523            }
524        });
525        Ok(Subscription { rx, task })
526    }
527
528    /// Queues the operation `command` asks for and follows it: its events, from its `queued` to
529    /// its `ended`. The subscription is open before the operation is queued, so none is missed.
530    ///
531    /// # Errors
532    ///
533    /// As [`Client::submit`] and [`Client::subscribe`].
534    pub async fn follow(&self, command: Command) -> Result<Followed> {
535        let run = command.target().and_then(|(target, _)| target.name.clone());
536        let events = self.subscribe(run, None).await?;
537        let accepted = self.submit(command).await?;
538        let events = OperationEvents::new(accepted.operation, events);
539        Ok(Followed { accepted, events })
540    }
541
542    /// Follows `command` once more, its first sending unanswered ([`ClientError::Unanswered`]):
543    /// the service may have queued it. When the run's newest operation is of `command`'s kind and
544    /// under way in this service (not ended, queued by this service's process), that one is
545    /// followed, from its `queued`: it is the first sending's, or another client's same operation,
546    /// which `command` would only have queued behind. Else `command` is queued anew
547    /// ([`Client::follow`]): a service that died with it took it along (one restarted since
548    /// recovers it as an operation of its own, under way, which is then the one followed). One
549    /// that already ended, and a target that doesn't name its run, are queued anew too: an
550    /// operation run twice brings the run to the same place.
551    ///
552    /// # Errors
553    ///
554    /// As [`Client::follow`], and the run's operations couldn't be read.
555    pub async fn follow_again(&self, command: Command) -> Result<Followed> {
556        let (Some(op), Some(run)) = (command.op(), command.target().and_then(|(target, _)| target.name.clone())) else {
557            return self.follow(command).await;
558        };
559        // Subscribed first, as `follow` is: no event of the operation found is missed.
560        let events = self.subscribe(Some(run.clone()), None).await?;
561        let rows = self.operations(&run, OPERATIONS_LOOKED_AT).await?;
562        let under_way = |r: &OperationRow| r.ended.is_none() && r.owner.pid == self.info.pid;
563        let Some(newest) = rows.first().filter(|r| r.op == op && under_way(r)) else {
564            drop(events);
565            return self.follow(command).await;
566        };
567        tracing::info!(operation = %newest.id, "the unanswered operation was queued: following it, not queuing it again");
568        let ahead = rows.iter().skip(1).filter(|r| under_way(r)).count();
569        let accepted = Accepted {
570            operation: newest.id,
571            run,
572            position: u32::try_from(ahead).unwrap_or(u32::MAX),
573        };
574        Ok(Followed {
575            events: OperationEvents::new(accepted.operation, events),
576            accepted,
577        })
578    }
579
580    /// Waits for operation `operation`'s last event: its `result`, or its `error` as
581    /// [`ClientError::Operation`] (a cancel before it began, as one of code `cancelled`).
582    ///
583    /// # Errors
584    ///
585    /// The operation failed, or the connection ended.
586    pub async fn wait(&self, operation: OperationId) -> Result<Event> {
587        let events = self.subscribe(None, None).await?;
588        OperationEvents::new(operation, events).outcome().await
589    }
590}
591
592/// A reply of a kind the request doesn't get.
593pub(super) fn unexpected(reply: &Reply) -> ClientError {
594    ClientError::Protocol(format!("unexpected reply: {reply:?}"))
595}