use super::*;
pub(super) const CLIENT_QUEUE_LIMIT: usize = 4 * 1024 * 1024;
impl Outbox {
pub(super) fn new() -> Arc<Self> {
Arc::new(Self {
queue: Mutex::new(OutboxState::default()),
wake: std::sync::Condvar::new(),
})
}
pub(super) fn push(&self, frame: &[u8]) -> bool {
self.push_seq(frame).is_some()
}
pub(super) fn push_seq(&self, frame: &[u8]) -> Option<u64> {
let mut state = self.queue.lock().unwrap();
if state.dead {
return None;
}
let backlog = state.bytes;
state.bytes += frame.len();
state.pending.push_back(frame.to_vec());
state.queued += 1;
let seq = state.queued;
if backlog > CLIENT_QUEUE_LIMIT {
state.dead = true;
state.pending.clear();
state.bytes = 0;
self.wake.notify_all();
return None;
}
self.wake.notify_all();
Some(seq)
}
pub(super) fn mark_delivered(&self) {
self.queue.lock().unwrap().delivered += 1;
}
pub(super) fn delivered_through(&self, seq: u64) -> bool {
let state = self.queue.lock().unwrap();
state.dead || state.delivered >= seq
}
pub(super) fn close_when_drained(&self) {
let mut state = self.queue.lock().unwrap();
state.closing = true;
self.wake.notify_all();
}
pub(super) fn kill(&self) {
let mut state = self.queue.lock().unwrap();
state.dead = true;
state.pending.clear();
state.bytes = 0;
self.wake.notify_all();
}
#[cfg(test)]
pub(super) fn is_dead(&self) -> bool {
self.queue.lock().unwrap().dead
}
pub(super) fn pop_blocking(&self) -> Option<Vec<u8>> {
let mut state = self.queue.lock().unwrap();
loop {
if state.dead {
return None;
}
if let Some(frame) = state.pending.pop_front() {
state.bytes -= frame.len();
return Some(frame);
}
if state.closing {
return None;
}
state = self.wake.wait(state).unwrap();
}
}
}
pub(super) fn shutdown_now(fd: std::os::fd::RawFd) {
unsafe { libc::shutdown(fd, libc::SHUT_RDWR) };
}
pub(super) fn spawn_writer(
stream: Arc<Mutex<UnixStream>>,
outbox: Arc<Outbox>,
fd: std::os::fd::RawFd,
) {
std::thread::spawn(move || {
while let Some(frame) = outbox.pop_blocking() {
let ok = write_frame_bounded(
&mut stream.lock().unwrap(),
&frame,
Instant::now() + WRITE_FRAME_DEADLINE,
);
if !ok {
outbox.kill();
break;
}
outbox.mark_delivered();
}
shutdown_now(fd);
});
}