1use std::net::{SocketAddr, ToSocketAddrs};
30use std::path::Path;
31use std::sync::atomic::{AtomicU64, Ordering};
32use std::time::Duration;
33
34use astrs_transport::{ConnectionCounters, FramedStream, HandshakeParams, LocalIdentity, initiate};
35use astrs_wire::{
36 AuthToken, ControlReply, ControlRequest, DataflowId, DataflowSummary, FeatureFlags, Frame,
37 FrameKind, FrameLimits, Role, SessionId, SubscriptionId,
38};
39use tokio::net::TcpStream;
40
41use crate::error::CliError;
42
43pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
49
50pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
57
58#[derive(Debug, Clone)]
60pub struct Endpoint {
61 pub addr: SocketAddr,
63 pub token: AuthToken,
65 pub display: String,
67}
68
69impl Endpoint {
70 #[must_use]
72 pub fn new(addr: SocketAddr, token: AuthToken) -> Self {
73 Self {
74 addr,
75 token,
76 display: addr.to_string(),
77 }
78 }
79}
80
81pub fn resolve_addr(argument: Option<&str>) -> Result<SocketAddr, CliError> {
94 let text = match argument {
95 Some(text) => text.to_owned(),
96 None => match std::env::var(crate::runtime_dir::ENV_COORDINATOR_ADDR) {
97 Ok(value) if !value.trim().is_empty() => value,
98 _ => format!("127.0.0.1:{}", default_port()),
99 },
100 };
101 resolve_text(&text)
102}
103
104#[must_use]
106pub fn default_port() -> u16 {
107 std::env::var(astrs_coordinator::ENV_COORDINATOR_PORT)
108 .ok()
109 .and_then(|value| value.trim().parse::<u16>().ok())
110 .unwrap_or(astrs_coordinator::DEFAULT_COORDINATOR_PORT)
111}
112
113pub fn resolve_text(text: &str) -> Result<SocketAddr, CliError> {
120 let trimmed = text.trim();
121 if trimmed.is_empty() {
122 return Err(CliError::BadAddress {
123 input: text.to_owned(),
124 reason: "the address is empty".to_owned(),
125 });
126 }
127 if let Ok(port) = trimmed.parse::<u16>() {
130 return Ok(SocketAddr::from(([127, 0, 0, 1], port)));
131 }
132 let candidate = if trimmed.contains(':') && !trimmed.ends_with(':') {
134 trimmed.to_owned()
135 } else {
136 format!("{}:{}", trimmed.trim_end_matches(':'), default_port())
137 };
138 let mut resolved = candidate
139 .to_socket_addrs()
140 .map_err(|error| CliError::BadAddress {
141 input: text.to_owned(),
142 reason: error.to_string(),
143 })?;
144 resolved.next().ok_or_else(|| CliError::BadAddress {
145 input: text.to_owned(),
146 reason: "the name resolved to no addresses".to_owned(),
147 })
148}
149
150pub fn endpoint(
164 coordinator: Option<&str>,
165 token: Option<&str>,
166 token_file: Option<&Path>,
167 working_dir: Option<&Path>,
168 require_token: bool,
169) -> Result<Endpoint, CliError> {
170 let addr = resolve_addr(coordinator)?;
171 let dir = crate::runtime_dir::working_dir(working_dir);
172 let found = crate::runtime_dir::find_token(token, token_file, &dir)?;
173 let token = match found {
174 Some((token, _)) => token,
175 None if require_token => {
176 return Err(CliError::NoToken {
177 env: crate::runtime_dir::ENV_TOKEN,
178 file: crate::runtime_dir::TOKEN_FILE,
179 });
180 }
181 None => AuthToken::ZERO,
185 };
186 Ok(Endpoint {
187 display: coordinator.map_or_else(|| addr.to_string(), ToOwned::to_owned),
188 addr,
189 token,
190 })
191}
192
193#[derive(Debug)]
198pub struct Client {
199 stream: FramedStream<TcpStream>,
201 session: SessionId,
203 display: String,
205}
206
207impl Client {
208 pub async fn connect(endpoint: &Endpoint) -> Result<Self, CliError> {
217 let raw = TcpStream::connect(endpoint.addr).await.map_err(|error| {
218 if matches!(
219 error.kind(),
220 std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::TimedOut
221 ) {
222 CliError::NoCluster {
223 detail: format!("nothing answered at {}: {error}", endpoint.display),
224 }
225 } else {
226 CliError::io(&endpoint.display, error)
227 }
228 })?;
229 let _ = raw.set_nodelay(true);
233
234 let mut stream =
235 FramedStream::new(raw, FrameLimits::network(), ConnectionCounters::shared());
236 let params = HandshakeParams::new(LocalIdentity::new(Role::Cli), endpoint.token.clone())
237 .with_features(FeatureFlags::EMPTY);
238 let handshake = initiate(&mut stream, ¶ms, HANDSHAKE_TIMEOUT).await?;
239 Ok(Self {
240 stream,
241 session: handshake.session.session_id,
242 display: endpoint.display.clone(),
243 })
244 }
245
246 #[must_use]
248 pub const fn session(&self) -> SessionId {
249 self.session
250 }
251
252 #[must_use]
254 pub fn display(&self) -> &str {
255 &self.display
256 }
257
258 pub async fn request(
271 &mut self,
272 label: &'static str,
273 request: &ControlRequest,
274 ) -> Result<ControlReply, CliError> {
275 self.stream.send_message(request).await?;
276 let reply = tokio::time::timeout(
277 REQUEST_TIMEOUT,
278 self.stream
279 .expect_message::<ControlReply>(FrameKind::ControlReply),
280 )
281 .await
282 .map_err(|_| astrs_transport::TransportError::Timeout {
283 operation: "control reply",
284 timeout: REQUEST_TIMEOUT,
285 })??;
286 match reply {
287 ControlReply::Error {
288 message, context, ..
289 } => Err(CliError::Refused {
290 request: label,
291 message: if context.is_empty() {
292 message
293 } else {
294 format!("{message} ({})", context.join("; "))
295 },
296 }),
297 other => Ok(other),
298 }
299 }
300
301 pub async fn request_ok(
308 &mut self,
309 label: &'static str,
310 request: &ControlRequest,
311 ) -> Result<(), CliError> {
312 match self.request(label, request).await? {
313 ControlReply::Ok => Ok(()),
314 other => Err(CliError::UnexpectedReply {
315 request: label,
316 reply: reply_name(&other),
317 }),
318 }
319 }
320
321 pub async fn next_frame(&mut self) -> Result<Option<Frame>, CliError> {
332 Ok(self.stream.recv_frame().await?)
333 }
334
335 pub async fn close(self) -> Result<(), CliError> {
343 let (_, mut writer) = self.stream.into_halves();
344 writer.shutdown().await?;
345 Ok(())
346 }
347
348 pub async fn list_dataflows(&mut self, all: bool) -> Result<Vec<DataflowSummary>, CliError> {
355 match self.request("list", &ControlRequest::List { all }).await? {
356 ControlReply::DataflowList { dataflows, .. } => Ok(dataflows),
357 other => Err(CliError::UnexpectedReply {
358 request: "list",
359 reply: reply_name(&other),
360 }),
361 }
362 }
363
364 pub async fn resolve(&mut self, reference: &DataflowRef) -> Result<DataflowId, CliError> {
379 let name = match reference {
380 DataflowRef::Id(id) => return Ok(*id),
381 DataflowRef::Name(name) => name.clone(),
382 };
383 let dataflows = self.list_dataflows(true).await?;
384 let matched: Vec<&DataflowSummary> = dataflows
385 .iter()
386 .filter(|summary| summary.name.as_deref() == Some(name.as_str()))
387 .collect();
388 match matched.as_slice() {
389 [one] => Ok(one.id),
390 [] => Err(CliError::UnknownDataflow {
391 reference: name,
392 reason: describe_known(&dataflows),
393 }),
394 many => Err(CliError::UnknownDataflow {
395 reference: name,
396 reason: format!(
397 "{} dataflows share that name; name one by id: {}",
398 many.len(),
399 many.iter()
400 .map(|summary| summary.id.to_string())
401 .collect::<Vec<_>>()
402 .join(", ")
403 ),
404 }),
405 }
406 }
407
408 pub async fn sole_dataflow(&mut self, all: bool) -> Result<DataflowId, CliError> {
421 let dataflows = self.list_dataflows(all).await?;
422 match dataflows.as_slice() {
423 [one] => Ok(one.id),
424 [] => Err(CliError::UnknownDataflow {
425 reference: "(none named)".to_owned(),
426 reason: "this cluster has no dataflow to act on".to_owned(),
427 }),
428 many => Err(CliError::UnknownDataflow {
429 reference: "(none named)".to_owned(),
430 reason: format!(
431 "{} dataflows are known, so one must be named: {}",
432 many.len(),
433 describe_known(&dataflows)
434 ),
435 }),
436 }
437 }
438}
439
440fn describe_known(dataflows: &[DataflowSummary]) -> String {
442 if dataflows.is_empty() {
443 return "this cluster knows no dataflows at all".to_owned();
444 }
445 let known: Vec<String> = dataflows
446 .iter()
447 .take(8)
448 .map(DataflowSummary::display_name)
449 .collect();
450 format!("known dataflows: {}", known.join(", "))
451}
452
453#[must_use]
467pub fn new_subscription_id() -> SubscriptionId {
468 static NEXT: AtomicU64 = AtomicU64::new(0);
471
472 let nanos = std::time::SystemTime::now()
473 .duration_since(std::time::UNIX_EPOCH)
474 .map_or(0, |since| {
475 u64::try_from(since.as_nanos()).unwrap_or(u64::MAX)
476 });
477 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
478 for part in [
479 u64::from(std::process::id()),
480 nanos,
481 NEXT.fetch_add(1, Ordering::Relaxed),
482 ] {
483 for byte in part.to_le_bytes() {
484 hash ^= u64::from(byte);
485 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
486 }
487 }
488 SubscriptionId::new(hash.max(1))
489}
490
491#[must_use]
497pub fn reply_name(reply: &ControlReply) -> &'static str {
498 match reply {
499 ControlReply::Ok => "Ok",
500 ControlReply::Error { .. } => "Error",
501 ControlReply::DataflowList { .. } => "DataflowList",
502 ControlReply::DataflowResult { .. } => "DataflowResult",
503 ControlReply::NodeInfo { .. } => "NodeInfo",
504 ControlReply::DaemonList { .. } => "DaemonList",
505 ControlReply::Logs { .. } => "Logs",
506 ControlReply::ParamValue { .. } => "ParamValue",
507 ControlReply::ParamList { .. } => "ParamList",
508 ControlReply::TraceData { .. } => "TraceData",
509 ControlReply::Refused(_) => "Refused",
510 ControlReply::Welcome(_) => "Welcome",
511 ControlReply::BuildStarted { .. } => "BuildStarted",
512 ControlReply::Started { .. } => "Started",
513 _ => "an unknown reply",
516 }
517}
518
519#[derive(Debug, Clone, PartialEq, Eq)]
527pub enum DataflowRef {
528 Id(DataflowId),
530 Name(String),
532}
533
534impl DataflowRef {
535 #[must_use]
537 pub fn parse(text: &str) -> Self {
538 text.trim()
539 .parse::<DataflowId>()
540 .map_or_else(|_| Self::Name(text.trim().to_owned()), Self::Id)
541 }
542
543 #[must_use]
545 pub const fn id(&self) -> Option<DataflowId> {
546 match self {
547 Self::Id(id) => Some(*id),
548 Self::Name(_) => None,
549 }
550 }
551}
552
553impl std::fmt::Display for DataflowRef {
554 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
555 match self {
556 Self::Id(id) => write!(f, "{id}"),
557 Self::Name(name) => f.write_str(name),
558 }
559 }
560}
561
562pub fn runtime() -> Result<tokio::runtime::Runtime, CliError> {
573 tokio::runtime::Builder::new_current_thread()
574 .enable_all()
575 .build()
576 .map_err(|source| CliError::io("tokio runtime", source))
577}
578
579#[cfg(test)]
580mod tests {
581 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
582
583 use super::*;
584
585 fn scratch(name: &str) -> std::path::PathBuf {
586 let dir =
587 std::env::temp_dir().join(format!("astrs-cli-client-{}-{name}", std::process::id()));
588 let _ = std::fs::remove_dir_all(&dir);
589 std::fs::create_dir_all(&dir).unwrap();
590 dir
591 }
592
593 #[test]
594 fn a_bare_port_means_loopback() {
595 let addr = resolve_text("7407").unwrap();
596 assert_eq!(addr, SocketAddr::from(([127, 0, 0, 1], 7407)));
597 }
598
599 #[test]
600 fn a_host_and_port_is_taken_as_written() {
601 let addr = resolve_text("127.0.0.1:9001").unwrap();
602 assert_eq!(addr.port(), 9001);
603 }
604
605 #[test]
606 fn a_bare_host_gets_the_default_port() {
607 let addr = resolve_text("127.0.0.1").unwrap();
608 assert_eq!(addr.port(), default_port());
609 }
610
611 #[test]
612 fn an_empty_address_is_refused_with_what_was_typed() {
613 let error = resolve_text(" ").unwrap_err();
614 match error {
615 CliError::BadAddress { input, .. } => assert_eq!(input, " "),
616 other => panic!("expected BadAddress, got {other}"),
617 }
618 }
619
620 #[test]
621 fn a_name_that_resolves_to_nothing_is_refused() {
622 let error = resolve_text("no-such-host.invalid:1").unwrap_err();
623 assert!(matches!(error, CliError::BadAddress { .. }), "{error}");
624 }
625
626 #[test]
627 fn a_mutating_verb_without_a_token_refuses_locally() {
628 let dir = scratch("no-token");
629 let error = endpoint(Some("127.0.0.1:1"), None, None, Some(&dir), true).unwrap_err();
630 match error {
631 CliError::NoToken { file, .. } => {
632 assert_eq!(file, crate::runtime_dir::TOKEN_FILE);
633 }
634 other => panic!("expected NoToken, got {other}"),
635 }
636 }
637
638 #[test]
639 fn a_probe_without_a_token_falls_back_to_the_zero_token() {
640 let dir = scratch("zero-token");
641 let endpoint = endpoint(Some("127.0.0.1:1"), None, None, Some(&dir), false).unwrap();
642 assert!(endpoint.token.is_zero());
643 }
644
645 #[test]
646 fn a_token_file_is_found_and_used() {
647 let dir = scratch("with-token");
648 let (token, _) = crate::runtime_dir::ensure_token_file(&dir).unwrap();
649 let endpoint = endpoint(Some("127.0.0.1:1"), None, None, Some(&dir), true).unwrap();
650 assert_eq!(endpoint.token, token);
651 }
652
653 #[test]
654 fn the_endpoint_remembers_how_the_address_was_typed() {
655 let dir = scratch("display");
656 let endpoint = endpoint(Some("7407"), None, None, Some(&dir), false).unwrap();
657 assert_eq!(endpoint.display, "7407");
658 assert_eq!(endpoint.addr.port(), 7407);
659 }
660
661 #[test]
662 fn a_dataflow_reference_is_an_id_or_a_name() {
663 let id = DataflowId::generate();
664 assert_eq!(DataflowRef::parse(&id.to_string()), DataflowRef::Id(id));
665 assert_eq!(
666 DataflowRef::parse(" my-flow "),
667 DataflowRef::Name("my-flow".to_owned())
668 );
669 assert_eq!(DataflowRef::parse(&id.to_string()).id(), Some(id));
670 assert!(DataflowRef::parse("my-flow").id().is_none());
671 }
672
673 #[test]
674 fn every_reply_variant_has_a_name() {
675 assert_eq!(reply_name(&ControlReply::Ok), "Ok");
676 assert_eq!(
677 reply_name(&ControlReply::Error {
678 code: astrs_wire::ErrorCode::Internal,
679 message: String::new(),
680 context: Vec::new(),
681 }),
682 "Error"
683 );
684 }
685
686 #[test]
687 fn connecting_to_nothing_says_to_run_astrs_up() {
688 let dir = scratch("no-cluster");
689 let endpoint = endpoint(Some("127.0.0.1:1"), None, None, Some(&dir), false).unwrap();
692 let runtime = runtime().unwrap();
693 let error = runtime.block_on(Client::connect(&endpoint)).unwrap_err();
694 let rendered = error.to_string();
695 match error {
696 CliError::NoCluster { detail } => assert!(detail.contains("127.0.0.1:1"), "{detail}"),
697 other => panic!("expected NoCluster, got {other}"),
698 }
699 assert!(rendered.contains("astrs up"), "{rendered}");
700 }
701}