1
//! Client side of a TUI session over a real ssh connection, for the daemon's tests.
2

            
3
use crate::eval_subsystem_tests::TrustingClient;
4
use russh::client::{self, Handle};
5
use russh::keys::{PrivateKey, PrivateKeyWithHashAlg};
6
use russh::{Channel, ChannelMsg};
7
use std::net::SocketAddr;
8
use std::sync::Arc;
9
use std::time::Duration;
10

            
11
const STEP: Duration = Duration::from_secs(15);
12

            
13
pub(crate) struct TuiSession {
14
    pub(crate) handle: Handle<TrustingClient>,
15
    pub(crate) channel: Channel<client::Msg>,
16
    seen: Vec<u8>,
17
}
18

            
19
impl TuiSession {
20
13
    pub(crate) async fn open(
21
13
        addr: SocketAddr,
22
13
        key: PrivateKey,
23
13
        (cols, rows): (u32, u32),
24
13
        (width, height): (u32, u32),
25
13
    ) -> anyhow::Result<Self> {
26
        let mut handle =
27
13
            client::connect(Arc::new(client::Config::default()), addr, TrustingClient).await?;
28
13
        let auth = handle
29
13
            .authenticate_publickey("eval-e2e", PrivateKeyWithHashAlg::new(Arc::new(key), None))
30
13
            .await?;
31
13
        anyhow::ensure!(auth.success(), "publickey auth was refused");
32
13
        let channel = handle.channel_open_session().await?;
33
13
        channel
34
13
            .request_pty(true, "xterm-kitty", cols, rows, width, height, &[])
35
13
            .await?;
36
13
        channel.request_shell(true).await?;
37
13
        Ok(Self {
38
13
            handle,
39
13
            channel,
40
13
            seen: Vec::new(),
41
13
        })
42
13
    }
43

            
44
11
    pub(crate) fn forget(&mut self) {
45
11
        self.seen.clear();
46
11
    }
47

            
48
267
    pub(crate) fn seen(&self) -> String {
49
267
        String::from_utf8_lossy(&self.seen).into_owned()
50
267
    }
51

            
52
    /// Reads the channel until `done` holds for what it has sent since `forget`.
53
29
    pub(crate) async fn read_until(&mut self, done: impl Fn(&str) -> bool) -> anyhow::Result<()> {
54
29
        let wait = async {
55
259
            while !done(&self.seen()) {
56
230
                match self.channel.wait().await {
57
230
                    Some(ChannelMsg::Data { data }) => self.seen.extend_from_slice(&data),
58
                    Some(_) => {}
59
                    None => anyhow::bail!("the channel closed"),
60
                }
61
            }
62
29
            Ok(())
63
29
        };
64
29
        match tokio::time::timeout(STEP, wait).await {
65
29
            Ok(result) => result,
66
            Err(_) => anyhow::bail!("no progress: {:?}", self.tail()),
67
        }
68
29
    }
69

            
70
    /// Reads until the daemon closes the channel; what it sent stays in `seen`.
71
3
    pub(crate) async fn read_to_end(&mut self) -> anyhow::Result<()> {
72
3
        let wait = async {
73
29
            while let Some(msg) = self.channel.wait().await {
74
26
                if let ChannelMsg::Data { data } = msg {
75
23
                    self.seen.extend_from_slice(&data);
76
3
                }
77
            }
78
3
        };
79
3
        tokio::time::timeout(STEP, wait)
80
3
            .await
81
            .map_err(|_| anyhow::anyhow!("the channel stayed open: {:?}", self.tail()))
82
3
    }
83

            
84
    fn tail(&self) -> String {
85
        let text = self.seen();
86
        let skip = text.chars().count().saturating_sub(600);
87
        text.chars().skip(skip).collect()
88
    }
89
}