1mod 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
27const START_WAIT: Duration = Duration::from_secs(30);
31
32const SUBSCRIPTION_BUFFER: usize = 1024;
35
36const OPERATIONS_LOOKED_AT: u32 = 16;
39
40type Result<T, E = ClientError> = std::result::Result<T, E>;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Accepted {
46 pub operation: OperationId,
48 pub run: RunName,
50 pub position: u32,
52}
53
54pub struct Client {
56 shared: Arc<Shared>,
57 reader: tokio::task::JoinHandle<()>,
58 paths: ServicePaths,
59 info: ServiceInfo,
60}
61
62struct 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
84fn 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
91async 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
108async 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 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 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 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 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 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 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 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 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 drop(waiting.send(reply));
239 }
240 }
241 replies.pending.lock().unwrap_or_else(PoisonError::into_inner).clear();
243 });
244 Client { shared, reader, paths, info }
245 }
246
247 #[must_use]
249 pub fn service(&self) -> &ServiceInfo {
250 &self.info
251 }
252
253 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 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 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 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 pub async fn down(&self, target: Target, options: OpOptions) -> Result<Accepted> {
312 self.submit(Command::Down { target, options }).await
313 }
314
315 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 pub async fn resume(&self, target: Target, options: OpOptions) -> Result<Accepted> {
330 self.submit(Command::Resume { target, options }).await
331 }
332
333 pub async fn update(&self, target: Target, options: OpOptions) -> Result<Accepted> {
339 self.submit(Command::Update { target, options }).await
340 }
341
342 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 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 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 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 pub async fn cancel(&self, operation: OperationId) -> Result<()> {
396 self.request(Command::Cancel { operation }).await.map(drop)
397 }
398
399 pub async fn status(&self, run: &RunName, target: Option<Target>) -> Result<Status> {
406 self.status_with(run, target, OpOptions::default()).await
407 }
408
409 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 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 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 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 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 pub async fn shutdown(&self) -> Result<()> {
483 self.request(Command::Shutdown).await.map(drop)
484 }
485
486 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 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 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 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 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 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
592pub(super) fn unexpected(reply: &Reply) -> ClientError {
594 ClientError::Protocol(format!("unexpected reply: {reply:?}"))
595}