Skip to main content

astrs_cli/command/
client.rs

1//! The one connection every client verb shares: CLI → coordinator.
2//!
3//! ```text
4//!   astrs list / stop / logs -f / param … ─┐
5//!                                          ▼
6//!            TcpStream ─► FramedDuplex ─► initiate(Hello{role=Cli, token})
7//!                                          │
8//!            ControlRequest ───────────────┤  "stream 0"
9//!            ControlReply   ◄──────────────┤
10//!            Log / Data frames ◄───────────┘  pushed for a subscription
11//! ```
12//!
13//! Blueprint §16 in one place: the greeting carries [`Role::Cli`] and the
14//! 64-hex cluster token, and a coordinator that refuses either says why in a
15//! typed [`astrs_wire::Refused`] the transport turns into an error this
16//! module reports with the address that was dialled attached — "connection
17//! refused" without an address is the least useful error a CLI can print.
18//!
19//! # Why not `astrs_transport::backend::connect`
20//!
21//! That entry point returns a [`astrs_transport::Connection`] — a route
22//! multiplexer with per-route streams, credit and datagrams, built for the
23//! daemon↔daemon *data* plane. A CLI has exactly one logical stream (§6.4's
24//! "stream 0") and needs the raw request/reply frames on it, which is what
25//! [`astrs_transport::FramedDuplex`] plus [`astrs_transport::initiate`]
26//! give directly. Using the mux here would add a header to every frame the
27//! coordinator's CLI session does not speak.
28
29use 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
43/// How long the greeting has before a dial is called dead.
44///
45/// Matches `astrs-coordinator`'s own `DEFAULT_HANDSHAKE_TIMEOUT`: a CLI that
46/// waited longer than the server is willing to wait would report a timeout
47/// the server had already given up on.
48pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
49
50/// How long a single request waits for its reply before giving up.
51///
52/// Generous, because the requests behind it are not all cheap — `Start`
53/// waits for a placement decision, `Destroy` for a cluster-wide stop — but
54/// bounded, because a CLI that hangs forever on a wedged coordinator is
55/// indistinguishable from a CLI that crashed.
56pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
57
58/// Everything needed to reach one coordinator.
59#[derive(Debug, Clone)]
60pub struct Endpoint {
61    /// The resolved address.
62    pub addr: SocketAddr,
63    /// The token presented in the greeting.
64    pub token: AuthToken,
65    /// What the address was written as, for error messages.
66    pub display: String,
67}
68
69impl Endpoint {
70    /// An endpoint for `addr`, authenticating with `token`.
71    #[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
81/// Resolves a `--coordinator` argument (or its absence) into an address.
82///
83/// Accepts, in order of how often a user types them: nothing (loopback on
84/// the default port, or `ASTRS_COORDINATOR_ADDR`), a bare port (`7407`), a
85/// bare host (`10.0.0.4`, default port), and a full `host:port`. A name is
86/// resolved through [`ToSocketAddrs`], preferring the first address the
87/// resolver returns.
88///
89/// # Errors
90///
91/// [`CliError::BadAddress`] naming what was typed and why it could not be
92/// used.
93pub 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/// The coordinator port this machine defaults to (§24.2).
105#[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
113/// The resolution rules [`resolve_addr`] documents, without the environment
114/// lookup — the part worth testing directly.
115///
116/// # Errors
117///
118/// [`CliError::BadAddress`] when nothing resolves.
119pub 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    // A bare port: the shortest thing a user types for "the local one, but
128    // over there".
129    if let Ok(port) = trimmed.parse::<u16>() {
130        return Ok(SocketAddr::from(([127, 0, 0, 1], port)));
131    }
132    // A literal or a name, with or without a port.
133    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
150/// Builds the endpoint a client verb should dial from its flags.
151///
152/// `require_token` distinguishes the verbs that *mutate* a cluster (§16's
153/// "mutating verbs") from a bare probe: without a token the former refuses
154/// locally with [`CliError::NoToken`], naming every way one could be
155/// supplied, rather than dialling and being refused by the far end with a
156/// message about protocol details the user did not ask about.
157///
158/// # Errors
159///
160/// - [`CliError::BadAddress`] if the address cannot be resolved.
161/// - [`CliError::NoToken`] when `require_token` and none was found.
162/// - Whatever [`crate::runtime_dir::find_token`] returns.
163pub 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        // A development coordinator started without a token accepts the
182        // all-zero one; refusing to try would make `astrs list` useless
183        // against exactly the setup a first-time user has.
184        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/// One connected CLI session.
194///
195/// Owns the socket and nothing else: every verb drives it with
196/// [`Client::request`] and, for a subscription, [`Client::next_frame`].
197#[derive(Debug)]
198pub struct Client {
199    /// The framed socket.
200    stream: FramedStream<TcpStream>,
201    /// The session the coordinator assigned.
202    session: SessionId,
203    /// How the endpoint was named, for errors.
204    display: String,
205}
206
207impl Client {
208    /// Dials `endpoint` and greets it as [`Role::Cli`].
209    ///
210    /// # Errors
211    ///
212    /// - [`CliError::NoCluster`] if nothing is listening — the one failure a
213    ///   user hits constantly, reported as "start one with `astrs up`"
214    ///   rather than as a raw `ECONNREFUSED`.
215    /// - [`CliError::Transport`] for a refusal or a protocol failure.
216    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        // Nagle off: every frame this connection sends is a whole request or
230        // a whole reply, and waiting to coalesce them adds latency to every
231        // single CLI invocation for no bandwidth gain.
232        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, &params, HANDSHAKE_TIMEOUT).await?;
239        Ok(Self {
240            stream,
241            session: handshake.session.session_id,
242            display: endpoint.display.clone(),
243        })
244    }
245
246    /// The session the coordinator assigned this connection.
247    #[must_use]
248    pub const fn session(&self) -> SessionId {
249        self.session
250    }
251
252    /// How the endpoint was named, for a caller's own messages.
253    #[must_use]
254    pub fn display(&self) -> &str {
255        &self.display
256    }
257
258    /// Sends one request and waits for its [`ControlReply`].
259    ///
260    /// `label` names the verb in any error, so a failure reads
261    /// "the coordinator refused `list`" rather than naming a wire variant
262    /// the user never typed.
263    ///
264    /// # Errors
265    ///
266    /// - [`CliError::Transport`] if the socket fails or the reply does not
267    ///   arrive within [`REQUEST_TIMEOUT`].
268    /// - [`CliError::Refused`] if the coordinator answered
269    ///   [`ControlReply::Error`].
270    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    /// Sends one request and requires a plain [`ControlReply::Ok`].
302    ///
303    /// # Errors
304    ///
305    /// As [`Client::request`], plus [`CliError::UnexpectedReply`] when the
306    /// answer is neither `Ok` nor an error.
307    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    /// Waits for the next frame the coordinator *pushes* — a `Log` for an
322    /// open `LogSubscribe`, a `Data` for a topic tap.
323    ///
324    /// Returns `Ok(None)` when the coordinator closed the connection, which
325    /// is how a `logs -f` ends when the cluster goes down rather than an
326    /// error a user should see a backtrace-shaped message for.
327    ///
328    /// # Errors
329    ///
330    /// [`CliError::Transport`] if the socket fails.
331    pub async fn next_frame(&mut self) -> Result<Option<Frame>, CliError> {
332        Ok(self.stream.recv_frame().await?)
333    }
334
335    /// Closes the connection politely.
336    ///
337    /// # Errors
338    ///
339    /// [`CliError::Transport`] if the shutdown fails — reported rather than
340    /// swallowed so a caller that cares (a script asserting a clean
341    /// teardown) can, while every ordinary caller ignores it.
342    pub async fn close(self) -> Result<(), CliError> {
343        let (_, mut writer) = self.stream.into_halves();
344        writer.shutdown().await?;
345        Ok(())
346    }
347
348    /// Every dataflow the coordinator knows about.
349    ///
350    /// # Errors
351    ///
352    /// As [`Client::request`], plus [`CliError::UnexpectedReply`] when the
353    /// answer is not a `DataflowList`.
354    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    /// Turns a user-typed reference into the id every request but
365    /// `StopByName`/`RestartByName` needs.
366    ///
367    /// An id is taken as written — no round trip, so `astrs logs <uuid>`
368    /// works against a coordinator whose `List` is momentarily large. A name
369    /// costs one `List { all: true }`: names are not unique by construction
370    /// (nothing stops two runs sharing one), so an ambiguous name is refused
371    /// with the ids to choose between rather than resolved arbitrarily.
372    ///
373    /// # Errors
374    ///
375    /// - As [`Client::request`].
376    /// - [`CliError::UnknownDataflow`] when nothing matches, or when more
377    ///   than one dataflow answers to the same name.
378    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    /// The one dataflow a verb should act on when the user named none.
409    ///
410    /// Convenience with a hard edge: exactly one candidate is resolved, and
411    /// anything else is refused. Guessing between two running graphs is how
412    /// a CLI stops a robot's perception stack when the user meant to tail
413    /// its planner.
414    ///
415    /// # Errors
416    ///
417    /// - As [`Client::request`].
418    /// - [`CliError::UnknownDataflow`] when zero, or more than one, dataflow
419    ///   is known.
420    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
440/// A short "here is what does exist" list for an unresolved reference.
441fn 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/// Mints a subscription id no other client is likely to be using.
454///
455/// The coordinator's subscription registry is keyed by id across *every*
456/// connected session and an insert replaces whatever was there, so two CLIs
457/// that both picked [`SubscriptionId::FIRST`] would silently steal each
458/// other's stream. There is no server-side allocator to ask (the protocol
459/// has the client choose, §7.3), so the id is minted here from three things
460/// that cannot all coincide between two live invocations: this process's
461/// id, the nanoseconds since the epoch, and a per-process counter for the
462/// several subscriptions one invocation opens.
463///
464/// Never [`SubscriptionId::NONE`], which the protocol reserves for "no
465/// subscription".
466#[must_use]
467pub fn new_subscription_id() -> SubscriptionId {
468    /// The per-process sequence, so two subscriptions opened in the same
469    /// nanosecond still differ.
470    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/// The variant name of a reply, for [`CliError::UnexpectedReply`].
492///
493/// Spelled out rather than derived from `Debug` so an error message never
494/// prints a whole payload — a `Logs` reply's `Debug` form is thousands of
495/// lines of records.
496#[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        // `ControlReply` is `#[non_exhaustive]`: a variant added at the tail
514        // (§3, append-only evolution) must still be nameable here.
515        _ => "an unknown reply",
516    }
517}
518
519/// Resolves a user-typed dataflow reference — an id or a name.
520///
521/// A [`DataflowId`] is a UUID; anything that does not parse as one is taken
522/// as the `--name` a run was started under, which is what a user actually
523/// types. The two are kept apart here rather than at each call site because
524/// the wire protocol has *separate requests* for them
525/// ([`ControlRequest::Stop`] vs [`ControlRequest::StopByName`]).
526#[derive(Debug, Clone, PartialEq, Eq)]
527pub enum DataflowRef {
528    /// An explicit dataflow id.
529    Id(DataflowId),
530    /// A name given at `Start`.
531    Name(String),
532}
533
534impl DataflowRef {
535    /// Classifies one user-typed reference.
536    #[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    /// The id, when this reference is one.
544    #[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
562/// Builds a current-thread tokio runtime for one client verb.
563///
564/// Current-thread on purpose: a client verb is one socket and one
565/// request/reply at a time, and spinning up a thread pool to wait on a
566/// single `recv` is pure startup latency on a command a user runs
567/// interactively.
568///
569/// # Errors
570///
571/// [`CliError::Io`] if the runtime cannot be built.
572pub 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        // Port 1 on loopback: privileged, never bound by this test suite,
690        // and refused immediately rather than timing out.
691        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}