1use 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
23pub 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 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 pub async fn write_str(&mut self, data: &str) -> Result<()> {
54 self.write(data.as_bytes()).await
55 }
56
57 pub async fn read(&mut self) -> Result<Option<Vec<u8>>> {
63 if self.closed {
64 return Err(Error::TerminalClosed);
65 }
66
67 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 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 pub fn is_closed(&self) -> bool {
114 self.closed
115 }
116
117 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
128pub 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 pub async fn connect(&self, container_id: &str) -> Result<Terminal> {
161 self.connect_with_size(container_id, 80, 24).await
162 }
163
164 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 terminal.resize(cols, rows).await?;
196
197 Ok(terminal)
198 }
199}