use crate::{Bytes, Client, Error, EventStream, Result, StreamOptions, Workspace, proto};
use futures_core::Stream;
use std::{
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio_util::sync::CancellationToken;
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct TerminalOptions {
pub cols: u32,
pub rows: u32,
pub stream: StreamOptions,
}
impl Default for TerminalOptions {
fn default() -> Self {
Self {
cols: 80,
rows: 24,
stream: StreamOptions::default(),
}
}
}
impl TerminalOptions {
pub fn size(mut self, cols: u32, rows: u32) -> Self {
self.cols = cols;
self.rows = rows;
self
}
pub fn stream(mut self, stream: StreamOptions) -> Self {
self.stream = stream;
self
}
fn validate(self) -> Result<Self> {
if self.cols == 0 || self.rows == 0 {
return Err(Error::InvalidArgument(
"terminal dimensions must be positive".into(),
));
}
self.stream.validate()?;
Ok(self)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TerminalEvent {
Output(Bytes),
Resize {
cols: u32,
rows: u32,
},
Closed,
}
#[derive(Clone, Debug)]
pub struct Terminals {
workspace: Workspace,
}
impl Terminals {
pub(crate) fn new(workspace: Workspace) -> Self {
Self { workspace }
}
pub async fn create(&self, options: TerminalOptions) -> Result<Terminal> {
self.workspace
.client
.operation(self.workspace.client.default_timeout(), async {
let options = options.validate()?;
let response = self
.workspace
.client
.rpc(self.workspace.client.workspace_service().create_terminal(
proto::CreateTerminalRequest {
workspace_ref: Some(self.workspace.object()?),
cols: options.cols,
rows: options.rows,
},
))
.await?;
self.attach(&response.id, options.stream).await
})
.await
}
pub async fn attach(&self, id: &str, options: StreamOptions) -> Result<Terminal> {
crate::error::nonempty(id, "terminal ID")?;
let deadline = options.deadline()?;
let client = self.workspace.client.clone();
let rpc = client
.operation_until(deadline, async {
client
.rpc(
client
.workspace_service()
.listen_terminal(proto::ListenTerminalRequest { id: id.into() }),
)
.await
})
.await?;
let input = TerminalInput {
client: client.clone(),
id: Arc::from(id),
detached: CancellationToken::new(),
write_lock: Arc::new(tokio::sync::Mutex::new(())),
};
Ok(Terminal {
events: Some(crate::stream::rpc_stream(client, rpc, deadline)),
input,
})
}
pub async fn list(&self) -> Result<Vec<String>> {
Ok(self
.workspace
.client
.rpc(self.workspace.client.workspace_service().list_terminal(
proto::ListTerminalRequest {
workspace_ref: Some(self.workspace.object()?),
},
))
.await?
.items
.into_iter()
.map(|t| t.id)
.collect())
}
pub async fn remove(&self, id: &str) -> Result<()> {
crate::error::nonempty(id, "terminal ID")?;
self.workspace
.client
.rpc(
self.workspace
.client
.workspace_service()
.remove_terminal(proto::RemoveTerminalRequest { id: id.into() }),
)
.await?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct TerminalInput {
client: Client,
id: Arc<str>,
detached: CancellationToken,
write_lock: Arc<tokio::sync::Mutex<()>>,
}
impl TerminalInput {
pub fn id(&self) -> &str {
&self.id
}
pub async fn write(&self, data: impl AsRef<[u8]>) -> Result<()> {
self.client.operation(self.client.default_timeout(), async {
if self.detached.is_cancelled() {
return Err(Error::Protocol("terminal is detached or closed".into()));
}
let _guard = self.write_lock.lock().await;
for chunk in data.as_ref().chunks(32 * 1024) {
let mut service = self.client.workspace_service();
let request=proto::WriteTerminalDataRequest {id:self.id.to_string(),data:Bytes::copy_from_slice(chunk)};
tokio::select! {
biased;
_ = self.detached.cancelled() => return Err(Error::Protocol("terminal is detached or closed".into())),
result = self.client.rpc(service.write_terminal_data(request)) => {result?;}
}
}
Ok(())
}).await
}
pub async fn resize(&self, cols: u32, rows: u32) -> Result<()> {
if cols == 0 || rows == 0 {
return Err(Error::InvalidArgument(
"terminal dimensions must be positive".into(),
));
}
if self.detached.is_cancelled() {
return Err(Error::Protocol("terminal is detached or closed".into()));
}
self.client
.rpc(self.client.workspace_service().set_terminal_window_size(
proto::SetTerminalWindowSizeRequest {
id: self.id.to_string(),
cols,
rows,
},
))
.await?;
Ok(())
}
}
#[derive(Debug)]
#[must_use = "consume terminal events or keep the handle to write and resize"]
pub struct Terminal {
events: Option<EventStream<proto::ListenTerminalResponse>>,
input: TerminalInput,
}
impl Terminal {
pub fn id(&self) -> &str {
self.input.id()
}
pub fn input(&self) -> TerminalInput {
self.input.clone()
}
pub async fn write(&self, data: impl AsRef<[u8]>) -> Result<()> {
self.input.write(data).await
}
pub async fn resize(&self, cols: u32, rows: u32) -> Result<()> {
self.input.resize(cols, rows).await
}
pub fn detach(&mut self) {
self.events = None;
self.input.detached.cancel();
}
pub async fn remove(&mut self) -> Result<()> {
self.input
.client
.rpc(self.input.client.workspace_service().remove_terminal(
proto::RemoveTerminalRequest {
id: self.id().into(),
},
))
.await?;
self.detach();
Ok(())
}
}
impl Stream for Terminal {
type Item = Result<TerminalEvent>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
let Some(events) = self.events.as_mut() else {
return Poll::Ready(None);
};
let event = match Pin::new(events).poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(None) => {
self.detach();
return Poll::Ready(None);
}
Poll::Ready(Some(Err(e))) => {
self.detach();
return Poll::Ready(Some(Err(e)));
}
Poll::Ready(Some(Ok(msg))) => match msg.r#type {
Some(proto::listen_terminal_response::Type::Stdout(s)) => {
TerminalEvent::Output(s.data)
}
Some(proto::listen_terminal_response::Type::WindowSize(s)) => {
TerminalEvent::Resize {
cols: s.cols,
rows: s.rows,
}
}
Some(proto::listen_terminal_response::Type::Close(_)) => {
self.detach();
TerminalEvent::Closed
}
None => continue,
},
};
return Poll::Ready(Some(Ok(event)));
}
}
}
impl Drop for Terminal {
fn drop(&mut self) {
self.input.detached.cancel();
}
}