use crate::Runtime;
use crate::actor::{Actor, ActorContext, ActorError, ActorId};
use crate::error::RuntimeError;
use crate::resource::ResourceHandle;
use crossbeam_channel::{Receiver, Sender, bounded};
use std::io::{Read, Write};
use std::net::TcpStream as StdTcpStream;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
#[derive(Debug)]
pub enum NetMessage {
Data(Vec<u8>),
Closed,
Error(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NetWrite {
Data(Vec<u8>),
Close,
}
pub enum NetConnectionMessage {
Incoming(NetMessage),
Outgoing(NetWrite),
Shutdown,
}
#[derive(Debug)]
pub struct NetConnectionHandle {
pub actor_id: ActorId,
pub writer_tx: Sender<NetWrite>,
pub shutdown: Arc<AtomicBool>,
}
impl ResourceHandle for NetConnectionHandle {
fn resource_type(&self) -> &str {
"NetConnection"
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl NetConnectionHandle {
pub fn send(&self, bytes: Vec<u8>) -> Result<(), RuntimeError> {
self.writer_tx
.try_send(NetWrite::Data(bytes))
.map_err(|e| match e {
crossbeam_channel::TrySendError::Full(_) => {
RuntimeError::MailboxFull(self.actor_id)
}
crossbeam_channel::TrySendError::Disconnected(_) => RuntimeError::RuntimeStopped,
})
}
pub fn close(&self) -> Result<(), RuntimeError> {
let _ = self.writer_tx.try_send(NetWrite::Close);
self.shutdown.store(true, Ordering::SeqCst);
Ok(())
}
}
#[allow(dead_code)]
pub struct NetConnection {
stream: Arc<std::sync::Mutex<Option<StdTcpStream>>>,
handler: ActorId,
reader_handle: Option<std::thread::JoinHandle<()>>,
writer_shutdown: Arc<AtomicBool>,
writer_handle: Option<std::thread::JoinHandle<()>>,
}
impl NetConnection {
pub fn new(
runtime: &Runtime,
stream: StdTcpStream,
handler: ActorId,
_handler_tx: Sender<NetConnectionMessage>,
) -> Result<Self, RuntimeError> {
let stream_arc: Arc<std::sync::Mutex<Option<StdTcpStream>>> =
Arc::new(std::sync::Mutex::new(Some(stream)));
let writer_shutdown = Arc::new(AtomicBool::new(false));
let reader_stream = {
let guard = stream_arc.lock().unwrap();
guard
.as_ref()
.unwrap()
.try_clone()
.map_err(|_e| RuntimeError::RuntimeStopped)?
};
let handler_for_reader = handler;
let stream_for_reader = Arc::clone(&stream_arc);
let runtime_clone = runtime.sender();
let reader_handle = std::thread::spawn(move || {
let stream_guard = stream_for_reader.lock().unwrap();
let mut stream = stream_guard.as_ref().unwrap();
let mut buf = vec![0u8; 4096];
loop {
match stream.read(&mut buf) {
Ok(0) => {
let _ = runtime_clone.send(handler_for_reader, NetMessage::Closed);
break;
}
Ok(n) => {
let data = buf[..n].to_vec();
if runtime_clone
.send(handler_for_reader, NetMessage::Data(data))
.is_err()
{
break;
}
}
Err(e) => {
let _ = runtime_clone
.send(handler_for_reader, NetMessage::Error(e.to_string()));
break;
}
}
}
});
let _writer_tx: Sender<NetWrite> = bounded(1000).0;
let writer_rx: Receiver<NetWrite> = bounded(1000).1;
let writer_stream = {
let guard = stream_arc.lock().unwrap();
guard
.as_ref()
.unwrap()
.try_clone()
.map_err(|_e| RuntimeError::RuntimeStopped)?
};
let shutdown_clone = writer_shutdown.clone();
let writer_handle = std::thread::spawn(move || {
let mut stream = writer_stream;
loop {
if shutdown_clone.load(Ordering::SeqCst) {
break;
}
match writer_rx.recv_timeout(Duration::from_millis(50)) {
Ok(NetWrite::Data(bytes)) => {
if stream.write_all(&bytes).is_err() || stream.flush().is_err() {
break;
}
}
Ok(NetWrite::Close) => {
let _ = stream.shutdown(std::net::Shutdown::Both);
break;
}
Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
continue;
}
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
break;
}
}
}
});
let _ = reader_stream;
Ok(Self {
stream: stream_arc,
handler,
reader_handle: Some(reader_handle),
writer_shutdown,
writer_handle: Some(writer_handle),
})
}
pub fn handle(&self) -> Sender<NetWrite> {
unimplemented!("use NetConnectionHandle for writes")
}
}
impl Actor for NetConnection {
type Message = NetConnectionMessage;
fn handle(
&mut self,
msg: NetConnectionMessage,
_ctx: &mut ActorContext,
) -> Result<(), ActorError> {
match msg {
NetConnectionMessage::Incoming(net_msg) => {
let _ = net_msg;
}
NetConnectionMessage::Outgoing(write) => {
let _ = write;
}
NetConnectionMessage::Shutdown => {
self.writer_shutdown.store(true, Ordering::SeqCst);
if let Some(h) = self.writer_handle.take() {
let _ = h.join();
}
if let Some(h) = self.reader_handle.take() {
let _ = h.join();
}
}
}
Ok(())
}
}