use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::sync::Notify;
pub const MAX_CLOSE_REASON_LEN: usize = 123;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CloseCode(u16);
impl CloseCode {
pub const NORMAL: Self = Self(1000);
pub const GOING_AWAY: Self = Self(1001);
pub const POLICY_VIOLATION: Self = Self(1008);
pub const fn new(code: u16) -> Option<Self> {
match code {
1000..=1003 | 1007..=1013 | 3000..=4999 => Some(Self(code)),
_ => None,
}
}
pub const fn as_u16(self) -> u16 {
self.0
}
}
impl From<CloseCode> for u16 {
fn from(code: CloseCode) -> u16 {
code.0
}
}
impl fmt::Display for CloseCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug)]
enum State {
Open,
Requested(CloseCode, String),
Ended,
}
#[derive(Debug)]
pub(super) struct Shared {
state: Mutex<State>,
changed: Notify,
}
impl Shared {
pub(super) fn new() -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(State::Open),
changed: Notify::new(),
})
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn requested_now(&self) -> Option<(CloseCode, String)> {
match &*self.lock() {
State::Requested(code, reason) => Some((*code, reason.clone())),
State::Open | State::Ended => None,
}
}
pub(super) async fn requested(&self) -> (CloseCode, String) {
loop {
let changed = self.changed.notified();
if let Some(requested) = self.requested_now() {
return requested;
}
changed.await;
}
}
pub(super) fn end(&self) {
*self.lock() = State::Ended;
}
}
#[derive(Debug, Clone)]
pub struct CloseHandle {
shared: Arc<Shared>,
}
impl CloseHandle {
pub(super) fn new(shared: Arc<Shared>) -> Self {
Self { shared }
}
pub fn close(&self, code: CloseCode, reason: impl Into<String>) -> bool {
let mut state = self.shared.lock();
if !matches!(*state, State::Open) {
return false;
}
*state = State::Requested(code, truncate_reason(reason.into()));
drop(state);
self.shared.changed.notify_waiters();
true
}
}
fn truncate_reason(mut reason: String) -> String {
if reason.len() > MAX_CLOSE_REASON_LEN {
let mut end = MAX_CLOSE_REASON_LEN;
while !reason.is_char_boundary(end) {
end -= 1;
}
reason.truncate(end);
}
reason
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_sendable_codes_are_made() {
for ok in [
1000, 1001, 1002, 1003, 1007, 1008, 1011, 1012, 1013, 3000, 4999,
] {
assert_eq!(CloseCode::new(ok).map(CloseCode::as_u16), Some(ok), "{ok}");
}
for bad in [
0,
999,
1004,
1005,
1006,
1014,
1015,
1016,
2999,
5000,
u16::MAX,
] {
assert_eq!(CloseCode::new(bad), None, "{bad}");
}
assert_eq!(CloseCode::POLICY_VIOLATION.as_u16(), 1008);
assert_eq!(CloseCode::GOING_AWAY.as_u16(), 1001);
assert_eq!(CloseCode::NORMAL.as_u16(), 1000);
assert_eq!(CloseCode::POLICY_VIOLATION.to_string(), "1008");
}
#[test]
fn reason_is_cut_to_123_bytes_on_a_char_boundary() {
assert_eq!(MAX_CLOSE_REASON_LEN, 125 - 2);
let fits = "a".repeat(123);
assert_eq!(truncate_reason(fits.clone()), fits);
assert_eq!(truncate_reason("a".repeat(124)), fits);
let straddles = format!("{}é", "a".repeat(122));
assert_eq!(straddles.len(), 124);
assert_eq!(truncate_reason(straddles), "a".repeat(122));
let wide = "\u{1F512}".repeat(40);
assert_eq!(truncate_reason(wide), "\u{1F512}".repeat(30));
}
#[test]
fn first_close_wins_and_none_after_the_end() {
let shared = Shared::new();
let a = CloseHandle::new(Arc::clone(&shared));
let b = a.clone();
assert!(a.close(CloseCode::POLICY_VIOLATION, "expired"));
assert!(!b.close(CloseCode::GOING_AWAY, "shutdown"));
assert!(matches!(
&*shared.lock(),
State::Requested(CloseCode::POLICY_VIOLATION, r) if r == "expired"
));
shared.end();
assert!(!a.close(CloseCode::NORMAL, ""));
let ended = Shared::new();
ended.end();
assert!(!CloseHandle::new(ended).close(CloseCode::NORMAL, ""));
}
#[tokio::test]
async fn requested_wakes_on_close() {
let shared = Shared::new();
let handle = CloseHandle::new(Arc::clone(&shared));
let waiter = tokio::spawn({
let shared = Arc::clone(&shared);
async move { shared.requested().await }
});
tokio::task::yield_now().await;
assert!(handle.close(CloseCode::POLICY_VIOLATION, "bye"));
let got = tokio::time::timeout(std::time::Duration::from_secs(5), waiter)
.await
.expect("woken")
.unwrap();
assert_eq!(got, (CloseCode::POLICY_VIOLATION, "bye".to_owned()));
}
}