Skip to main content

rexec/
terminal.rs

1//! Terminal service for WebSocket connections to containers.
2
3use futures_util::{SinkExt, StreamExt};
4use std::sync::Arc;
5use tokio::sync::Mutex;
6use tokio_tungstenite::{
7    connect_async,
8    tungstenite::{
9        client::IntoClientRequest,
10        http::{header, HeaderValue},
11        Message,
12    },
13};
14
15use crate::client::ClientInner;
16use crate::error::{Error, Result};
17use crate::types::ResizeMessage;
18
19type WsStream = tokio_tungstenite::WebSocketStream<
20    tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
21>;
22
23/// WebSocket terminal connection to a container.
24pub struct Terminal {
25    ws: Arc<Mutex<WsStream>>,
26    closed: bool,
27}
28
29impl Terminal {
30    fn new(ws: WsStream) -> Self {
31        Self {
32            ws: Arc::new(Mutex::new(ws)),
33            closed: false,
34        }
35    }
36
37    /// Send data to the terminal.
38    ///
39    /// # Arguments
40    ///
41    /// * `data` - Data to send
42    pub async fn write(&mut self, data: &[u8]) -> Result<()> {
43        if self.closed {
44            return Err(Error::TerminalClosed);
45        }
46
47        let mut ws = self.ws.lock().await;
48        ws.send(Message::Binary(data.to_vec().into())).await?;
49        Ok(())
50    }
51
52    /// Send a string to the terminal.
53    pub async fn write_str(&mut self, data: &str) -> Result<()> {
54        self.write(data.as_bytes()).await
55    }
56
57    /// Read data from the terminal.
58    ///
59    /// # Returns
60    ///
61    /// Bytes received from the terminal, or `None` if connection closed.
62    pub async fn read(&mut self) -> Result<Option<Vec<u8>>> {
63        if self.closed {
64            return Err(Error::TerminalClosed);
65        }
66
67        // Skip control frames (ping/pong) until we get payload or close.
68        loop {
69            let mut ws = self.ws.lock().await;
70            let next = ws.next().await;
71            drop(ws);
72
73            match next {
74                Some(Ok(Message::Binary(data))) => return Ok(Some(data.to_vec())),
75                Some(Ok(Message::Text(text))) => return Ok(Some(text.as_bytes().to_vec())),
76                Some(Ok(Message::Close(_))) => {
77                    self.closed = true;
78                    return Ok(None);
79                }
80                Some(Ok(_)) => continue,
81                Some(Err(e)) => {
82                    self.closed = true;
83                    return Err(e.into());
84                }
85                None => {
86                    self.closed = true;
87                    return Ok(None);
88                }
89            }
90        }
91    }
92
93    /// Resize the terminal.
94    ///
95    /// # Arguments
96    ///
97    /// * `cols` - Number of columns
98    /// * `rows` - Number of rows
99    pub async fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
100        if self.closed {
101            return Err(Error::TerminalClosed);
102        }
103
104        let msg = ResizeMessage::new(cols, rows);
105        let json = serde_json::to_string(&msg)?;
106
107        let mut ws = self.ws.lock().await;
108        ws.send(Message::Text(json.into())).await?;
109        Ok(())
110    }
111
112    /// Check if the connection is closed.
113    pub fn is_closed(&self) -> bool {
114        self.closed
115    }
116
117    /// Close the terminal connection.
118    pub async fn close(&mut self) -> Result<()> {
119        if !self.closed {
120            self.closed = true;
121            let mut ws = self.ws.lock().await;
122            ws.close(None).await?;
123        }
124        Ok(())
125    }
126}
127
128/// Service for terminal WebSocket connections.
129pub struct TerminalService {
130    client: Arc<ClientInner>,
131}
132
133impl TerminalService {
134    pub(crate) fn new(client: Arc<ClientInner>) -> Self {
135        Self { client }
136    }
137
138    /// Connect to a container's terminal.
139    ///
140    /// # Arguments
141    ///
142    /// * `container_id` - Container ID
143    ///
144    /// # Example
145    ///
146    /// ```rust,no_run
147    /// # use rexec::RexecClient;
148    /// # async fn example() -> Result<(), rexec::Error> {
149    /// let client = RexecClient::new("https://example.com", "token");
150    /// let mut term = client.terminal().connect("container-id").await?;
151    ///
152    /// term.write(b"ls -la\n").await?;
153    ///
154    /// while let Some(data) = term.read().await? {
155    ///     print!("{}", String::from_utf8_lossy(&data));
156    /// }
157    /// # Ok(())
158    /// # }
159    /// ```
160    pub async fn connect(&self, container_id: &str) -> Result<Terminal> {
161        self.connect_with_size(container_id, 80, 24).await
162    }
163
164    /// Connect to a container's terminal with custom size.
165    ///
166    /// # Arguments
167    ///
168    /// * `container_id` - Container ID
169    /// * `cols` - Terminal width in columns
170    /// * `rows` - Terminal height in rows
171    pub async fn connect_with_size(
172        &self,
173        container_id: &str,
174        cols: u16,
175        rows: u16,
176    ) -> Result<Terminal> {
177        let ws_url = self.client.ws_url(&format!("/ws/terminal/{}", container_id))?;
178
179        let mut request = ws_url
180            .into_client_request()
181            .map_err(|e| Error::connection(e.to_string()))?;
182        request.headers_mut().insert(
183            header::AUTHORIZATION,
184            HeaderValue::from_str(&format!("Bearer {}", self.client.token))
185                .map_err(|e| Error::connection(e.to_string()))?,
186        );
187
188        let (ws, _) = connect_async(request)
189            .await
190            .map_err(|e| Error::connection(e.to_string()))?;
191
192        let mut terminal = Terminal::new(ws);
193
194        // Set initial size
195        terminal.resize(cols, rows).await?;
196
197        Ok(terminal)
198    }
199}