use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use bytes::Bytes;
use tokio::sync::broadcast::{self, error::RecvError};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use shep_core::protocol::{BusEvent, encode_frame};
#[derive(Debug)]
pub(crate) struct PtyStream {
name: String,
chunks: broadcast::Receiver<Bytes>,
ending: Ending,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ending {
Open,
Closed,
Done,
}
impl PtyStream {
pub(crate) fn new(name: String, chunks: broadcast::Receiver<Bytes>) -> Self {
Self {
name,
chunks,
ending: Ending::Open,
}
}
pub(crate) async fn next(&mut self) -> Option<BusEvent> {
loop {
match self.ending {
Ending::Done => return None,
Ending::Closed => {
self.ending = Ending::Done;
return Some(BusEvent::PtyEnd {
name: self.name.clone(),
});
}
Ending::Open => {}
}
match self.chunks.recv().await {
Ok(chunk) => return Some(self.out(chunk.to_vec())),
Err(RecvError::Lagged(count)) => return Some(BusEvent::Dropped { count }),
Err(RecvError::Closed) => self.ending = Ending::Closed,
}
}
}
pub(crate) fn forward(mut self, out: mpsc::Sender<Bytes>) -> PtyWriter {
let ended = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&ended);
let task = tokio::spawn(async move {
while let Some(event) = self.next().await {
if matches!(event, BusEvent::PtyEnd { .. }) {
flag.store(true, Ordering::Release);
}
let Ok(frame) = encode_frame(&event) else {
return;
};
if out.send(frame).await.is_err() {
return;
}
}
});
PtyWriter { task, ended }
}
fn out(&self, data: Vec<u8>) -> BusEvent {
BusEvent::PtyOut {
name: self.name.clone(),
data,
}
}
}
#[derive(Debug)]
pub(crate) struct PtyWriter {
task: JoinHandle<()>,
ended: Arc<AtomicBool>,
}
impl PtyWriter {
pub(crate) fn is_live(&self) -> bool {
!self.ended.load(Ordering::Acquire) && !self.task.is_finished()
}
pub(crate) async fn finish(self) {
let _ = self.task.await;
}
pub(crate) fn abort(self) {
self.task.abort();
}
}