use std::fmt;
#[cfg(feature = "pairing-code")]
use std::sync::atomic::AtomicU32;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{anyhow, bail, Context, Result};
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
#[cfg(feature = "pairing-code")]
use crate::config::CodeFormat;
use crate::config::{ClientConfig, StoredPsk, VolumePolicy};
use crate::pairing::{load_or_draw_pairing_psk, PairingPsk};
use crate::session::{self, Carried, Transport};
use crate::sink::{AudioFormat, Sink};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const INITIAL_BACKOFF: Duration = Duration::from_secs(1);
pub const DEFAULT_PAIRING_TIMEOUT: Duration = Duration::from_secs(120);
pub(crate) const MAX_VOLUME: u8 = 100;
pub const NORMAL_PLAYBACK_SPEED: u32 = 1_000;
#[must_use]
pub fn clamp_volume(current: u8, requested: u8) -> u8 {
clamp_volume_with(VolumePolicy::default(), current, requested)
}
#[must_use]
pub fn clamp_volume_with(policy: VolumePolicy, current: u8, requested: u8) -> u8 {
let threshold = policy.threshold.min(MAX_VOLUME);
let max_step = policy.max_step.min(MAX_VOLUME);
let current = current.min(MAX_VOLUME);
let requested = requested.min(MAX_VOLUME);
if requested <= threshold {
return requested;
}
let applied = requested.min(current.saturating_add(max_step));
if policy.threshold_floor {
applied.max(threshold)
} else {
applied
}
}
pub(crate) fn check_reported_level(level: u8) -> Result<()> {
if level > MAX_VOLUME {
bail!(
"the reported level {level} is outside the 0-{MAX_VOLUME} range the protocol defines"
);
}
Ok(())
}
#[must_use]
pub fn next_backoff(previous: Duration, connected: bool, max: Duration) -> Duration {
let next = if connected || previous.is_zero() {
INITIAL_BACKOFF
} else {
previous.saturating_mul(2)
};
next.min(max)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamEndReason {
End,
RoleRemoved,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PairingRequiredReason {
CredentialMismatch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PairingFailure {
AttemptTimeout,
MethodNotSupported,
PairingCodeMismatch,
UserCancelled,
ConcurrentAttempt,
Unrecognised(String),
}
impl PairingFailure {
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::AttemptTimeout => "attempt_timeout",
Self::MethodNotSupported => "method_not_supported",
Self::PairingCodeMismatch => "pairing_code_mismatch",
Self::UserCancelled => "user_cancelled",
Self::ConcurrentAttempt => "concurrent_attempt",
Self::Unrecognised(reason) => reason,
}
}
pub(crate) fn from_wire(reason: &str) -> Self {
match reason {
"attempt_timeout" => Self::AttemptTimeout,
"method_not_supported" => Self::MethodNotSupported,
"pairing_code_mismatch" => Self::PairingCodeMismatch,
"user_cancelled" => Self::UserCancelled,
"concurrent_attempt" => Self::ConcurrentAttempt,
other => Self::Unrecognised(other.to_owned()),
}
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
Connected {
server_id: String,
encrypted: bool,
},
Disconnected {
reason: String,
retry_in: Duration,
},
StreamStart {
format: AudioFormat,
},
StreamEnd {
reason: StreamEndReason,
},
StreamClear {
from_timestamp: Option<i64>,
},
Track {
title: String,
artist: String,
album: String,
album_artist: String,
artwork_url: String,
progress_ms: Option<u64>,
duration_ms: Option<u64>,
playback_speed: u32,
},
State(PlaybackState),
Volume {
requested: u8,
applied: u8,
muted: Option<bool>,
},
Paired {
server_id: String,
},
Unpaired {
server_id: String,
},
PairingRequired {
server_id: String,
reason: PairingRequiredReason,
},
PairingFailed {
reason: PairingFailure,
},
#[cfg(feature = "pairing-code")]
PairingCode {
code: String,
format: CodeFormat,
round: u32,
},
}
impl fmt::Debug for Event {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Connected {
server_id,
encrypted,
} => formatter
.debug_struct("Connected")
.field("server_id", server_id)
.field("encrypted", encrypted)
.finish(),
Self::Disconnected { reason, retry_in } => formatter
.debug_struct("Disconnected")
.field("reason", reason)
.field("retry_in", retry_in)
.finish(),
Self::StreamStart { format } => formatter
.debug_struct("StreamStart")
.field("format", format)
.finish(),
Self::StreamEnd { reason } => formatter
.debug_struct("StreamEnd")
.field("reason", reason)
.finish(),
Self::StreamClear { from_timestamp } => formatter
.debug_struct("StreamClear")
.field("from_timestamp", from_timestamp)
.finish(),
Self::Track {
title,
artist,
album,
album_artist,
artwork_url,
progress_ms,
duration_ms,
playback_speed,
} => formatter
.debug_struct("Track")
.field("title", title)
.field("artist", artist)
.field("album", album)
.field("album_artist", album_artist)
.field("artwork_url", artwork_url)
.field("progress_ms", progress_ms)
.field("duration_ms", duration_ms)
.field("playback_speed", playback_speed)
.finish(),
Self::State(state) => formatter.debug_tuple("State").field(state).finish(),
Self::Volume {
requested,
applied,
muted,
} => formatter
.debug_struct("Volume")
.field("requested", requested)
.field("applied", applied)
.field("muted", muted)
.finish(),
Self::Paired { server_id } => formatter
.debug_struct("Paired")
.field("server_id", server_id)
.finish(),
Self::Unpaired { server_id } => formatter
.debug_struct("Unpaired")
.field("server_id", server_id)
.finish(),
Self::PairingRequired { server_id, reason } => formatter
.debug_struct("PairingRequired")
.field("server_id", server_id)
.field("reason", reason)
.finish(),
Self::PairingFailed { reason } => formatter
.debug_struct("PairingFailed")
.field("reason", reason)
.finish(),
#[cfg(feature = "pairing-code")]
Self::PairingCode { format, round, .. } => formatter
.debug_struct("PairingCode")
.field("code", &"<redacted>")
.field("format", format)
.field("round", round)
.finish(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlaybackState {
pub supported_commands: Vec<String>,
pub volume: Option<u8>,
pub muted: Option<bool>,
}
#[derive(Debug)]
pub struct ClientHandle {
task: Option<JoinHandle<Result<()>>>,
control: ControlHandle,
shutdown: Option<oneshot::Sender<()>>,
}
impl ClientHandle {
#[must_use]
pub fn control(&self) -> ControlHandle {
self.control.clone()
}
pub async fn finished(mut self) -> Result<()> {
let task = self.task.take().expect("the handle owns its task");
task.await.context("the connection task panicked")?
}
}
impl Drop for ClientHandle {
fn drop(&mut self) {
if self.task.is_some() {
if let Some(shutdown) = self.shutdown.take() {
let _ = shutdown.send(());
}
}
}
}
#[derive(Debug, Clone)]
pub struct ControlHandle {
commands: mpsc::UnboundedSender<ControlRequest>,
volume: Arc<AtomicU8>,
}
impl ControlHandle {
pub async fn play(&self) -> Result<()> {
self.transport("play").await
}
pub async fn pause(&self) -> Result<()> {
self.transport("pause").await
}
pub async fn next(&self) -> Result<()> {
self.transport("next").await
}
pub async fn previous(&self) -> Result<()> {
self.transport("previous").await
}
pub async fn set_volume(&self, level: u8) -> Result<u8> {
self.send(ControlAction::Volume(level)).await
}
pub async fn report_volume(&self, level: u8) -> Result<()> {
check_reported_level(level)?;
self.send(ControlAction::ReportVolume(level))
.await
.map(|_level| ())
}
pub async fn set_muted(&self, muted: bool) -> Result<()> {
self.send(ControlAction::Mute(muted)).await.map(|_level| ())
}
#[must_use]
pub fn volume(&self) -> u8 {
self.volume.load(Ordering::Relaxed)
}
#[cfg(feature = "pairing-code")]
pub async fn open_pairing_window(&self) -> Result<()> {
self.send(ControlAction::OpenPairingWindow)
.await
.map(|_level| ())
}
#[cfg(feature = "pairing-code")]
pub async fn release_holdback(&self) -> Result<()> {
self.send(ControlAction::ReleaseHoldback)
.await
.map(|_level| ())
}
async fn transport(&self, command: &'static str) -> Result<()> {
self.send(ControlAction::Transport(command))
.await
.map(|_level| ())
}
async fn send(&self, action: ControlAction) -> Result<u8> {
let (reply, response) = oneshot::channel();
self.commands
.send(ControlRequest { action, reply })
.map_err(|_| anyhow!("the connection has ended"))?;
response
.await
.map_err(|_| anyhow!("the connection ended before it answered"))?
}
}
#[derive(Debug)]
pub(crate) enum ControlAction {
Transport(&'static str),
Volume(u8),
ReportVolume(u8),
Mute(bool),
#[cfg(feature = "pairing-code")]
OpenPairingWindow,
#[cfg(feature = "pairing-code")]
ReleaseHoldback,
}
pub(crate) struct ControlRequest {
pub(crate) action: ControlAction,
pub(crate) reply: oneshot::Sender<Result<u8>>,
}
#[derive(Debug)]
pub struct EventStream {
events: mpsc::UnboundedReceiver<Event>,
}
impl EventStream {
pub async fn next(&mut self) -> Option<Event> {
self.events.recv().await
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Client;
impl Client {
pub async fn connect(
config: ClientConfig,
sink: Box<dyn Sink>,
) -> Result<(ClientHandle, EventStream)> {
connect(config, sink).await
}
pub async fn connect_with_psks(
config: ClientConfig,
sink: Box<dyn Sink>,
psks: Vec<StoredPsk>,
) -> Result<(ClientHandle, EventStream)> {
connect_with_psks(config, sink, psks).await
}
}
pub async fn connect(
config: ClientConfig,
sink: Box<dyn Sink>,
) -> Result<(ClientHandle, EventStream)> {
connect_with_psks(config, sink, Vec::new()).await
}
pub async fn connect_with_psks(
config: ClientConfig,
sink: Box<dyn Sink>,
psks: Vec<StoredPsk>,
) -> Result<(ClientHandle, EventStream)> {
config.validate()?;
let endpoint = endpoint(&config.server)?;
let pairing = match config.storage.as_deref() {
Some(storage) => Some(load_or_draw_pairing_psk(storage)?),
None => None,
};
let (events, receiver) = mpsc::unbounded_channel();
let (commands, control) = mpsc::unbounded_channel();
let (shutdown, shutdown_rx) = oneshot::channel();
let reported_volume = Arc::new(AtomicU8::new(config.volume));
#[cfg(feature = "pairing-code")]
let failed_rounds = Arc::new(AtomicU32::new(0));
let carried = Carried {
sink,
control: Some(control),
volume: config.volume,
muted: config.muted,
active_roles: Vec::new(),
#[cfg(feature = "pairing-code")]
failed_rounds: Arc::clone(&failed_rounds),
};
let connection = Connection {
endpoint,
config,
psks,
pairing,
events: events.clone(),
reported_volume: Arc::clone(&reported_volume),
#[cfg(feature = "pairing-code")]
failed_rounds,
};
let task = tokio::spawn(async move {
tokio::select! {
result = serve_until_dropped(connection, carried) => result,
_ = shutdown_rx => Ok(()),
}
});
let handle = ClientHandle {
task: Some(task),
control: ControlHandle {
commands,
volume: reported_volume,
},
shutdown: Some(shutdown),
};
Ok((handle, EventStream { events: receiver }))
}
async fn open(endpoint: &str) -> Result<Transport> {
tokio::time::timeout(CONNECT_TIMEOUT, Transport::connect(endpoint))
.await
.with_context(|| format!("timed out connecting to {endpoint}"))?
}
struct Connection {
endpoint: String,
config: ClientConfig,
psks: Vec<StoredPsk>,
pairing: Option<PairingPsk>,
events: mpsc::UnboundedSender<Event>,
reported_volume: Arc<AtomicU8>,
#[cfg(feature = "pairing-code")]
failed_rounds: Arc<AtomicU32>,
}
impl Connection {
fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
}
enum Wakeup {
Control(Option<ControlRequest>),
Deadline,
Closed,
}
#[cfg(feature = "pairing-code")]
fn refuse(connection: &Connection, carried: &Carried, request: ControlRequest) {
if matches!(request.action, ControlAction::ReleaseHoldback) {
connection.failed_rounds.store(0, Ordering::SeqCst);
let _ = request.reply.send(Ok(carried.volume));
return;
}
let _ = request
.reply
.send(Err(anyhow!("no connection is established")));
}
#[cfg(not(feature = "pairing-code"))]
fn refuse(request: ControlRequest) {
let _ = request
.reply
.send(Err(anyhow!("no connection is established")));
}
async fn wait_before_retry(
connection: &Connection,
carried: &mut Carried,
delay: Duration,
) -> bool {
let deadline = tokio::time::Instant::now() + delay;
loop {
if connection.events.is_closed() {
return false;
}
let control = &mut carried.control;
let wakeup = tokio::select! {
biased;
request = async {
match control {
Some(receiver) => receiver.recv().await,
None => std::future::pending().await,
}
} => Wakeup::Control(request),
() = tokio::time::sleep_until(deadline) => Wakeup::Deadline,
() = connection.events.closed() => Wakeup::Closed,
};
match wakeup {
Wakeup::Control(Some(request)) => {
#[cfg(feature = "pairing-code")]
refuse(connection, carried, request);
#[cfg(not(feature = "pairing-code"))]
refuse(request);
}
Wakeup::Control(None) => *control = None,
Wakeup::Deadline => return true,
Wakeup::Closed => return false,
}
}
}
async fn serve_until_dropped(connection: Connection, mut carried: Carried) -> Result<()> {
let mut delay = INITIAL_BACKOFF;
loop {
let transport = match open(&connection.endpoint).await {
Ok(transport) => transport,
Err(error) => {
delay = next_backoff(delay, false, connection.config.max_backoff);
connection.emit(Event::Disconnected {
reason: format!("cannot connect to {}: {error:#}", connection.endpoint),
retry_in: delay,
});
if !wait_before_retry(&connection, &mut carried, delay).await {
return Ok(());
}
continue;
}
};
let attempt = session::attempt(
transport,
&connection.config,
&connection.events,
&connection.psks,
connection.pairing,
&connection.reported_volume,
carried,
)
.await;
carried = attempt.carried;
let flush_error = carried.sink.flush().err().map(|error| {
error.context("the audio sink rejected a flush after the connection ended")
});
let fatal = attempt.sink_failed || flush_error.is_some();
delay = if fatal {
Duration::ZERO
} else {
next_backoff(delay, attempt.connected, connection.config.max_backoff)
};
connection.emit(Event::Disconnected {
reason: attempt.ending.reason(),
retry_in: delay,
});
if attempt.sink_failed {
return match attempt.ending {
session::Ending::Failed(error) => Err(error),
session::Ending::Closed | session::Ending::Unpaired => {
Err(anyhow!("the audio sink failed"))
}
};
}
if let Some(error) = flush_error {
return Err(error);
}
if !wait_before_retry(&connection, &mut carried, delay).await {
return Ok(());
}
}
}
fn split_marker(value: &str) -> (&str, &str) {
match value.find(['?', '#']) {
Some(index) => value.split_at(index),
None => (value, ""),
}
}
fn endpoint(server: &str) -> Result<String> {
let server = server.trim();
if server.is_empty() {
bail!("the server address is empty");
}
if server.starts_with("wss://") {
bail!("TLS is not supported by this build; use a ws:// address or host:port");
}
if let Some(rest) = server.strip_prefix("ws://") {
if rest.is_empty() {
bail!("the WebSocket address {server:?} names no host");
}
let (before_marker, after_marker) = split_marker(rest);
let Some((authority, path)) = before_marker.split_once('/') else {
if before_marker.is_empty() {
bail!("the WebSocket address {server:?} names no host");
}
return Ok(format!("ws://{before_marker}/sendspin{after_marker}"));
};
if authority.is_empty() {
bail!("the WebSocket address {server:?} names no host");
}
if path.is_empty() {
return Ok(format!("ws://{authority}/sendspin{after_marker}"));
}
return Ok(format!("ws://{before_marker}{after_marker}"));
}
if server.contains("://") {
bail!("unsupported URL scheme in {server:?}; use ws:// or host:port");
}
let (before_marker, after_marker) = split_marker(server);
if before_marker.is_empty() {
bail!("the server address is empty");
}
Ok(format!("ws://{before_marker}/sendspin{after_marker}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "pairing-code")]
#[test]
fn the_pairing_code_event_formats_without_its_code() {
for (code, format) in [
("482913".to_owned(), CodeFormat::Digits),
(
"SP:1QJOHGMGBXP55Y6KMJD3KOYR9F6OWYD6QQPIKEFY".to_owned(),
CodeFormat::QrCode,
),
] {
let event = Event::PairingCode {
code: code.clone(),
format,
round: 3,
};
let text = format!("{event:?}");
assert!(text.contains("code: \"<redacted>\""), "got: {text}");
assert!(
!text.contains(&code),
"the code must never reach a log line: {text}"
);
assert!(
text.contains(&format!("format: {format:?}")),
"the format is not secret: {text}"
);
assert!(text.contains("round: 3"), "the round is not secret: {text}");
}
}
#[test]
fn the_record_lifecycle_events_format_their_server_id() {
let server_id = "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned();
let unpaired = format!(
"{:?}",
Event::Unpaired {
server_id: server_id.clone(),
}
);
assert!(
unpaired.contains(&format!("Unpaired {{ server_id: \"{server_id}\" }}")),
"got: {unpaired}"
);
let required = format!(
"{:?}",
Event::PairingRequired {
server_id: server_id.clone(),
reason: PairingRequiredReason::CredentialMismatch,
}
);
assert!(required.contains(&server_id), "got: {required}");
assert!(
required.contains("CredentialMismatch"),
"the reason is what the host acts on: {required}"
);
assert!(
!required.contains("<redacted>"),
"neither event carries a secret, so neither redacts a field: {required}"
);
}
#[test]
fn an_event_still_formats_its_readable_fields() {
let text = format!(
"{:?}",
Event::Disconnected {
reason: "the server closed the connection".to_owned(),
retry_in: Duration::from_secs(2),
}
);
assert!(
text.contains("Disconnected { reason: \"the server closed the connection\""),
"got: {text}"
);
assert!(text.contains("retry_in: 2s"), "got: {text}");
}
#[test]
fn every_abort_reason_round_trips_through_the_wire_spelling() {
for (wire, reason) in [
("attempt_timeout", PairingFailure::AttemptTimeout),
("method_not_supported", PairingFailure::MethodNotSupported),
("pairing_code_mismatch", PairingFailure::PairingCodeMismatch),
("user_cancelled", PairingFailure::UserCancelled),
("concurrent_attempt", PairingFailure::ConcurrentAttempt),
] {
assert_eq!(reason.as_str(), wire);
assert_eq!(PairingFailure::from_wire(wire), reason);
}
assert_eq!(
PairingFailure::from_wire("future_reason"),
PairingFailure::Unrecognised("future_reason".to_owned())
);
assert_eq!(
PairingFailure::Unrecognised("future_reason".to_owned()).as_str(),
"future_reason"
);
}
#[test]
fn a_bare_address_gets_the_default_websocket_endpoint() {
assert_eq!(
endpoint("192.0.2.10:8927").unwrap(),
"ws://192.0.2.10:8927/sendspin"
);
assert_eq!(
endpoint(" 192.0.2.10:8927 ").unwrap(),
"ws://192.0.2.10:8927/sendspin"
);
assert_eq!(
endpoint("ws://example.test:1").unwrap(),
"ws://example.test:1/sendspin"
);
assert_eq!(
endpoint("ws://example.test:1/").unwrap(),
"ws://example.test:1/sendspin"
);
assert_eq!(
endpoint("ws://example.test:1/player").unwrap(),
"ws://example.test:1/player"
);
}
#[test]
fn a_query_or_fragment_stays_after_the_default_path() {
assert_eq!(
endpoint("ws://example.test:1?token=1").unwrap(),
"ws://example.test:1/sendspin?token=1"
);
assert_eq!(
endpoint("ws://example.test:1#frag").unwrap(),
"ws://example.test:1/sendspin#frag"
);
assert_eq!(
endpoint("ws://example.test:1/?token=1").unwrap(),
"ws://example.test:1/sendspin?token=1"
);
assert_eq!(
endpoint("ws://example.test:1/player?token=1").unwrap(),
"ws://example.test:1/player?token=1"
);
assert_eq!(
endpoint("example.test:1?token=1").unwrap(),
"ws://example.test:1/sendspin?token=1"
);
}
#[test]
fn an_address_this_build_cannot_use_is_rejected() {
for server in [
"",
" ",
"wss://example.test",
"https://example.test",
"ws://",
"ws://?token=1",
"ws://#fragment",
"ws:///player",
"?token=1",
"#fragment",
] {
assert!(
endpoint(server).is_err(),
"{server:?} must not be turned into a cleartext endpoint"
);
}
}
use crate::test_support::NullSink;
fn connection_at(endpoint: &str, events: mpsc::UnboundedSender<Event>) -> Connection {
Connection {
endpoint: endpoint.to_owned(),
config: ClientConfig {
server: endpoint.to_owned(),
player_name: "Test player".to_owned(),
device_info: None,
identity: crate::Identity::generate(),
storage: None,
audio_mode: crate::AudioMode::Passthrough,
volume: 42,
muted: false,
volume_policy: VolumePolicy::default(),
max_backoff: Duration::from_secs(30),
pairing_timeout: DEFAULT_PAIRING_TIMEOUT,
#[cfg(feature = "pairing-code")]
static_pairing_code: None,
#[cfg(feature = "pairing-code")]
pairing_window: crate::DEFAULT_PAIRING_WINDOW,
#[cfg(feature = "pairing-code")]
pairing_pending_text: None,
#[cfg(feature = "pairing-code")]
code_formats: Vec::new(),
#[cfg(feature = "pairing-code")]
code_out_channels: Vec::new(),
},
psks: Vec::new(),
pairing: None,
events,
reported_volume: Arc::new(AtomicU8::new(42)),
#[cfg(feature = "pairing-code")]
failed_rounds: Arc::new(AtomicU32::new(0)),
}
}
fn empty_carried(control: Option<mpsc::UnboundedReceiver<ControlRequest>>) -> Carried {
Carried {
sink: Box::new(NullSink),
control,
volume: 42,
muted: false,
active_roles: Vec::new(),
#[cfg(feature = "pairing-code")]
failed_rounds: Arc::new(AtomicU32::new(0)),
}
}
#[tokio::test]
async fn a_retry_wait_without_a_control_handle_still_honours_the_delay() {
let (events, _receiver) = mpsc::unbounded_channel();
let connection = connection_at("127.0.0.1:1", events);
let (commands, control) = mpsc::unbounded_channel();
drop(commands);
let mut carried = empty_carried(Some(control));
let started = std::time::Instant::now();
let retry = wait_before_retry(&connection, &mut carried, Duration::from_millis(50)).await;
assert!(retry, "the delay elapsed, so the next attempt must follow");
assert!(
started.elapsed() >= Duration::from_millis(50),
"the delay must be waited out, not skipped"
);
assert!(
carried.control.is_none(),
"a control channel whose senders are gone is dropped"
);
}
#[tokio::test]
async fn dropping_the_event_stream_during_a_retry_ends_the_connection() {
let (events, receiver) = mpsc::unbounded_channel();
let connection = connection_at("127.0.0.1:1", events);
let mut carried = empty_carried(None);
let retry = wait_before_retry(&connection, &mut carried, Duration::from_secs(60));
tokio::pin!(retry);
let mut finished = false;
tokio::select! {
_ = &mut retry => finished = true,
() = tokio::time::sleep(Duration::from_millis(50)) => {}
}
assert!(!finished, "the wait must not end while the stream is open");
drop(receiver);
assert!(
!retry.await,
"a dropped event stream must stop the retry loop"
);
}
#[tokio::test]
async fn a_failed_attempt_with_no_event_stream_ends_the_connection() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a loopback port");
let address = listener.local_addr().expect("the bound address");
drop(listener);
let (events, receiver) = mpsc::unbounded_channel();
drop(receiver);
let connection = connection_at(&address.to_string(), events);
let outcome = serve_until_dropped(connection, empty_carried(None)).await;
assert!(
outcome.is_ok(),
"a host that dropped the stream ends the connection cleanly"
);
}
#[tokio::test]
async fn the_namespace_entry_points_wrap_the_free_functions() {
let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
config.player_name.clear();
let error = Client::connect(config, Box::new(NullSink))
.await
.expect_err("an invalid configuration must be rejected");
assert!(format!("{error:#}").contains("player_name"));
let mut config = connection_at("127.0.0.1:1", mpsc::unbounded_channel().0).config;
config.server = "wss://example.test".to_owned();
let error = Client::connect_with_psks(config, Box::new(NullSink), Vec::new())
.await
.expect_err("a TLS address must be rejected before connecting");
assert!(format!("{error:#}").contains("TLS"));
}
}