mod console;
mod events;
mod home;
pub use console::HeldConsole;
use events::OperationEvents;
pub use events::{Followed, Subscription};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use isothrum_runner::{ErrorCode, ErrorReport, EventKind, InputVariable, Park, RunName, Status};
use tokio::sync::{mpsc, oneshot};
use crate::discovery::{ServiceInfo, ServicePaths};
use crate::error::ClientError;
use crate::proto::{Command, OpOptions, PROTOCOL, Reply, Request, Target};
use crate::v1::{Event, EventCursor, OperationId, OperationPhase, OperationRow, RunRow, is_outcome, phase_of};
use crate::wire::{Reader, Writer, connect, write_line};
use crate::{VERSION, replace, spawn};
const START_WAIT: Duration = Duration::from_secs(30);
const SUBSCRIPTION_BUFFER: usize = 1024;
const OPERATIONS_LOOKED_AT: u32 = 16;
type Result<T, E = ClientError> = std::result::Result<T, E>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Accepted {
pub operation: OperationId,
pub run: RunName,
pub position: u32,
}
pub struct Client {
shared: Arc<Shared>,
reader: tokio::task::JoinHandle<()>,
paths: ServicePaths,
info: ServiceInfo,
}
struct Shared {
writer: tokio::sync::Mutex<Writer>,
pending: Mutex<HashMap<u64, oneshot::Sender<Reply>>>,
next: AtomicU64,
}
impl Drop for Client {
fn drop(&mut self) {
self.reader.abort();
}
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("home", &self.paths.home())
.field("service", &self.info)
.finish_non_exhaustive()
}
}
fn resolve(home: &Path) -> PathBuf {
let absolute = std::path::absolute(home).unwrap_or_else(|_| home.to_path_buf());
std::fs::canonicalize(&absolute).unwrap_or(absolute)
}
async fn hello(endpoint: &str) -> Result<(Reader, Writer, Option<Reply>)> {
let (mut reader, mut writer) = connect(endpoint)
.await
.map_err(|e| ClientError::Unavailable(format!("the service at {endpoint} doesn't answer: {e}")))?;
write_line(
&mut writer,
&Request {
id: 0,
command: Command::Hello { protocol: PROTOCOL },
},
)
.await?;
let first = reader.next::<Reply>().await?;
Ok((reader, writer, first))
}
async fn open(paths: &ServicePaths) -> Result<(Reader, Writer, ServiceInfo)> {
let info = paths
.read_info()
.ok_or_else(|| ClientError::Unavailable(format!("no service runs for {}", paths.home().display())))?;
let (reader, writer, first) = hello(&info.endpoint).await?;
match first {
Some(Reply::Hello { protocol, version, .. }) if protocol == PROTOCOL => Ok((reader, writer, ServiceInfo { version, ..info })),
Some(Reply::Hello { protocol, version, .. }) => Err(ClientError::Protocol(format!(
"the service (Isothrum {version}) speaks protocol {protocol}, this client {PROTOCOL}: stop it to let this version start its own"
))),
Some(Reply::Error { report, .. }) => Err(ClientError::Protocol(report.message)),
Some(other) => Err(ClientError::Protocol(format!("expected the service's hello, got {other:?}"))),
None => Err(ClientError::closed()),
}
}
impl Client {
pub async fn connect(home: &Path, binary: Option<&Path>) -> Result<Client> {
let paths = ServicePaths::new(resolve(home));
match open(&paths).await {
Err(ClientError::Unavailable(_)) => {}
opened => return opened.map(|(r, w, info)| Client::over(paths, r, w, info)),
}
Client::start(paths, binary).await
}
pub async fn connect_exact(home: &Path, binary: Option<&Path>) -> Result<Client> {
let paths = ServicePaths::new(resolve(home));
let binary = spawn::binary(binary);
let _turn = replace::Turn::take(&paths).await?;
if let Some((r, w, info)) = replace::make_room(&paths, crate::build_of(&binary).as_deref()).await? {
return Ok(Client::over(paths, r, w, info));
}
let client = Client::start(paths, Some(&binary)).await?;
if client.info.version == VERSION {
return Ok(client);
}
if let Err(e) = client.request(Command::ShutdownIfIdle).await {
tracing::debug!(error = %e, "the service of another release just started couldn't be stopped");
}
Err(ClientError::Version {
client: VERSION.to_owned(),
service: client.info.version.clone(),
})
}
async fn start(paths: ServicePaths, binary: Option<&Path>) -> Result<Client> {
let binary = spawn::binary(binary);
let mut child = spawn::start(&binary, &paths).map_err(|e| ClientError::Unavailable(format!("{} couldn't be started: {e}", binary.display())))?;
let deadline = Instant::now() + START_WAIT;
let (opened, ended) = loop {
tokio::time::sleep(Duration::from_millis(50)).await;
let ended = child.try_wait().ok().flatten();
match open(&paths).await {
Err(ClientError::Unavailable(why)) if ended.is_none() && Instant::now() < deadline => {
tracing::trace!(%why, "waiting for the service");
}
opened => break (opened, ended),
}
};
std::thread::spawn(move || child.wait());
match opened {
Ok((r, w, info)) => Ok(Client::over(paths, r, w, info)),
Err(ClientError::Unavailable(why)) => Err(ClientError::Unavailable(format!(
"{why}; the service started from {} {}: {}",
binary.display(),
ended.map_or_else(|| "didn't answer".to_owned(), |status| format!("ended without answering ({status})")),
spawn::log_tail(&paths)
))),
Err(e) => Err(e),
}
}
pub async fn connect_running(home: &Path) -> Result<Client> {
let paths = ServicePaths::new(resolve(home));
let (r, w, info) = open(&paths).await?;
Ok(Client::over(paths, r, w, info))
}
fn over(paths: ServicePaths, mut reader: Reader, writer: Writer, info: ServiceInfo) -> Client {
let shared = Arc::new(Shared {
writer: tokio::sync::Mutex::new(writer),
pending: Mutex::default(),
next: AtomicU64::new(1),
});
let replies = Arc::clone(&shared);
let reader = tokio::spawn(async move {
while let Ok(Some(reply)) = reader.next::<Reply>().await {
let Some(id) = reply.id() else { continue };
let waiting = replies.pending.lock().unwrap_or_else(PoisonError::into_inner).remove(&id);
if let Some(waiting) = waiting {
drop(waiting.send(reply));
}
}
replies.pending.lock().unwrap_or_else(PoisonError::into_inner).clear();
});
Client { shared, reader, paths, info }
}
#[must_use]
pub fn service(&self) -> &ServiceInfo {
&self.info
}
pub async fn request(&self, command: Command) -> Result<Reply> {
let id = self.shared.next.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = oneshot::channel();
self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner).insert(id, tx);
let written = write_line(&mut *self.shared.writer.lock().await, &Request { id, command }).await;
if let Err(e) = written {
self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner).remove(&id);
return Err(e.into());
}
match rx.await.map_err(|_| ClientError::Unanswered)? {
Reply::Error { report, .. } => Err(ClientError::Refused(Box::new(report))),
reply => Ok(reply),
}
}
pub async fn submit(&self, command: Command) -> Result<Accepted> {
if command.op().is_none() {
return Err(ClientError::Protocol(format!("not an operation: {command:?}")));
}
match self.request(command).await? {
Reply::Accepted { operation, run, position, .. } => Ok(Accepted { operation, run, position }),
other => Err(unexpected(&other)),
}
}
pub async fn up(&self, target: Target, options: OpOptions) -> Result<Accepted> {
self.submit(Command::Up {
target,
options,
lifetime_s: None,
})
.await
}
pub async fn down(&self, target: Target, options: OpOptions) -> Result<Accepted> {
self.submit(Command::Down { target, options }).await
}
pub async fn park(&self, target: Target, options: OpOptions, mode: Park) -> Result<Accepted> {
self.submit(Command::Park { target, options, mode }).await
}
pub async fn resume(&self, target: Target, options: OpOptions) -> Result<Accepted> {
self.submit(Command::Resume { target, options }).await
}
pub async fn update(&self, target: Target, options: OpOptions) -> Result<Accepted> {
self.submit(Command::Update { target, options }).await
}
pub async fn retire(&self, target: Target, options: OpOptions, machine: String) -> Result<Accepted> {
self.submit(Command::Retire { target, options, machine }).await
}
pub async fn package(&self, target: Target, options: OpOptions, machine: String, output: std::path::PathBuf) -> Result<Accepted> {
self.submit(Command::Package {
target,
options,
machine,
output,
})
.await
}
pub async fn attach(&self, target: Target, options: OpOptions, machine: String) -> Result<Accepted> {
self.submit(Command::Attach { target, options, machine }).await
}
pub async fn exec(&self, target: Target, options: OpOptions, machine: String, argv: Vec<String>) -> Result<Accepted> {
self.submit(Command::Exec {
target,
options,
machine,
argv,
})
.await
}
pub async fn cancel(&self, operation: OperationId) -> Result<()> {
self.request(Command::Cancel { operation }).await.map(drop)
}
pub async fn status(&self, run: &RunName, target: Option<Target>) -> Result<Status> {
self.status_with(run, target, OpOptions::default()).await
}
pub async fn status_with(&self, run: &RunName, target: Option<Target>, options: OpOptions) -> Result<Status> {
let command = Command::Status {
run: run.clone(),
target,
options,
};
match self.request(command).await? {
Reply::Status { status, .. } => Ok(*status),
other => Err(unexpected(&other)),
}
}
pub async fn variables(&self, target: Target) -> Result<Vec<InputVariable>> {
match self.request(Command::Variables { target }).await? {
Reply::Variables { variables, .. } => Ok(variables),
other => Err(unexpected(&other)),
}
}
pub async fn list(&self) -> Result<Vec<RunRow>> {
match self.request(Command::List).await? {
Reply::Runs { runs, .. } => Ok(runs),
other => Err(unexpected(&other)),
}
}
pub(super) async fn dedicated(&self) -> Result<(Reader, Writer)> {
let (reader, writer, first) = hello(&self.info.endpoint).await?;
match first {
Some(Reply::Hello { .. }) => Ok((reader, writer)),
Some(Reply::Error { report, .. }) => Err(ClientError::Refused(Box::new(report))),
Some(other) => Err(unexpected(&other)),
None => Err(ClientError::closed()),
}
}
pub async fn operations(&self, run: &RunName, limit: u32) -> Result<Vec<OperationRow>> {
match self.request(Command::Operations { run: run.clone(), limit }).await? {
Reply::Operations { operations, .. } => Ok(operations),
other => Err(unexpected(&other)),
}
}
pub async fn shutdown(&self) -> Result<()> {
self.request(Command::Shutdown).await.map(drop)
}
pub async fn subscribe(&self, run: Option<RunName>, after: Option<EventCursor>) -> Result<Subscription> {
let (mut reader, mut writer) = self.dedicated().await?;
write_line(
&mut writer,
&Request {
id: 1,
command: Command::Subscribe { run, after },
},
)
.await?;
match reader.next::<Reply>().await? {
Some(Reply::Ok { id: 1 }) => {}
Some(Reply::Error { report, .. }) => return Err(ClientError::Refused(Box::new(report))),
Some(other) => return Err(unexpected(&other)),
None => return Err(ClientError::closed()),
}
let (tx, rx) = mpsc::channel(SUBSCRIPTION_BUFFER);
let task = tokio::spawn(async move {
let _writer = writer;
loop {
let item = match reader.next::<Reply>().await {
Ok(Some(Reply::Event { cursor, event })) => Ok((cursor, *event)),
Ok(Some(_)) => continue,
Ok(None) => Err(ClientError::closed()),
Err(e) => Err(ClientError::Io(e)),
};
let last = item.is_err();
if tx.send(item).await.is_err() || last {
return;
}
}
});
Ok(Subscription { rx, task })
}
pub async fn follow(&self, command: Command) -> Result<Followed> {
let run = command.target().and_then(|(target, _)| target.name.clone());
let events = self.subscribe(run, None).await?;
let accepted = self.submit(command).await?;
let events = OperationEvents::new(accepted.operation, events);
Ok(Followed { accepted, events })
}
pub async fn follow_again(&self, command: Command) -> Result<Followed> {
let (Some(op), Some(run)) = (command.op(), command.target().and_then(|(target, _)| target.name.clone())) else {
return self.follow(command).await;
};
let events = self.subscribe(Some(run.clone()), None).await?;
let rows = self.operations(&run, OPERATIONS_LOOKED_AT).await?;
let under_way = |r: &OperationRow| r.ended.is_none() && r.owner.pid == self.info.pid;
let Some(newest) = rows.first().filter(|r| r.op == op && under_way(r)) else {
drop(events);
return self.follow(command).await;
};
tracing::info!(operation = %newest.id, "the unanswered operation was queued: following it, not queuing it again");
let ahead = rows.iter().skip(1).filter(|r| under_way(r)).count();
let accepted = Accepted {
operation: newest.id,
run,
position: u32::try_from(ahead).unwrap_or(u32::MAX),
};
Ok(Followed {
events: OperationEvents::new(accepted.operation, events),
accepted,
})
}
pub async fn wait(&self, operation: OperationId) -> Result<Event> {
let events = self.subscribe(None, None).await?;
OperationEvents::new(operation, events).outcome().await
}
}
pub(super) fn unexpected(reply: &Reply) -> ClientError {
ClientError::Protocol(format!("unexpected reply: {reply:?}"))
}