use super::TimeoutCache;
use crate::stream_emit::TimeoutRead;
use glam::Vec3;
use indicatrix_dispatch::SampleRange;
use indicatrix_net::messages::{
ContributionError, ContributionHeader, ExpectedContribution, NetError,
};
use std::{
io::Read,
sync::{Condvar, Mutex, PoisonError},
time::{Duration, Instant},
};
pub const DEFAULT_CONTRIBUTION_WAIT: Duration = Duration::from_secs(30);
pub const CONTRIBUTION_PAYLOAD_READ_TIMEOUT: Duration = Duration::from_secs(30);
pub enum Awaited {
Arrived(Vec<Vec3>),
Reclaim {
reason: String,
},
Cancelled,
}
enum SlotState {
Waiting,
Receiving,
Arrived(Vec<Vec3>),
Invalid(String),
Reclaimed,
Taken,
}
pub struct ContributionSlot {
reserved: SampleRange,
width: u32,
height: u32,
state: Mutex<SlotState>,
changed: Condvar,
}
impl std::fmt::Debug for ContributionSlot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContributionSlot")
.field("reserved", &self.reserved)
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}
impl ContributionSlot {
#[must_use]
pub const fn new(reserved: SampleRange, width: u32, height: u32) -> Self {
Self {
reserved,
width,
height,
state: Mutex::new(SlotState::Waiting),
changed: Condvar::new(),
}
}
#[must_use]
pub const fn reserved(&self) -> SampleRange {
self.reserved
}
pub(crate) fn receive<S: Read + TimeoutRead>(
&self,
stream: &mut S,
header: &ContributionHeader,
request_id: u32,
timeouts: &mut TimeoutCache,
) -> Result<(), NetError> {
if !self.already_spent() {
self.set_state(SlotState::Receiving);
}
timeouts
.apply(stream, Some(CONTRIBUTION_PAYLOAD_READ_TIMEOUT))
.map_err(|e| NetError::Framing(indicatrix_net::framing::FramingError::Io(e)))?;
let expect = ExpectedContribution {
request_id,
first_sample: self.reserved.first_sample,
samples: self.reserved.samples,
width: self.width,
height: self.height,
};
let mut decoder = indicatrix_net::radiance::PayloadDecoder::new();
let outcome = indicatrix_net::messages::read_contribution_payload(
stream,
header,
expect,
&mut decoder,
);
self.finish_receive(request_id, outcome)
}
fn set_state(&self, state: SlotState) {
*self.state.lock().unwrap_or_else(PoisonError::into_inner) = state;
self.changed.notify_all();
}
fn finish_receive(
&self,
request_id: u32,
outcome: Result<Vec<Vec3>, ContributionError>,
) -> Result<(), NetError> {
match outcome {
Ok(sum) => {
if self.already_spent() {
tracing::info!(
request_id,
"a CONTRIBUTION arrived after its range was already reclaimed or taken; dropping it"
);
} else {
self.set_state(SlotState::Arrived(sum));
}
Ok(())
}
Err(ContributionError::TooLarge {
payload_len,
raw_len,
}) => Err(NetError::Framing(
indicatrix_net::framing::FramingError::FrameTooLarge {
len: payload_len,
max: raw_len,
},
)),
Err(ContributionError::Framing(e)) => Err(NetError::Framing(e)),
Err(e @ (ContributionError::Mismatch(_) | ContributionError::Radiance(_))) => {
let reason = e.to_string();
if self.already_spent() {
tracing::info!(
request_id,
"an invalid CONTRIBUTION arrived after its range was already reclaimed or \
taken; dropping it: {reason}"
);
} else {
self.set_state(SlotState::Invalid(reason));
}
Ok(())
}
}
}
fn already_spent(&self) -> bool {
matches!(
*self.state.lock().unwrap_or_else(PoisonError::into_inner),
SlotState::Reclaimed | SlotState::Taken
)
}
pub fn await_until(&self, wait: Duration, cancelled: impl Fn() -> bool) -> Awaited {
let mut deadline = Instant::now() + wait;
let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
loop {
match &*guard {
SlotState::Arrived(_) => {
let SlotState::Arrived(sum) = std::mem::replace(&mut *guard, SlotState::Taken)
else {
unreachable!("just matched SlotState::Arrived");
};
return Awaited::Arrived(sum);
}
SlotState::Invalid(reason) => {
let reason = reason.clone();
*guard = SlotState::Reclaimed;
return Awaited::Reclaim { reason };
}
SlotState::Receiving => deadline = Instant::now() + wait,
SlotState::Waiting | SlotState::Reclaimed | SlotState::Taken => {}
}
if cancelled() {
return Awaited::Cancelled;
}
if Instant::now() >= deadline {
*guard = SlotState::Reclaimed;
return Awaited::Reclaim {
reason: format!("no contribution within {wait:?}"),
};
}
guard = self
.changed
.wait_timeout(guard, Duration::from_millis(50))
.unwrap_or_else(PoisonError::into_inner)
.0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use indicatrix_net::{messages::PayloadEncoding, radiance::PayloadEncoder};
use std::{
io::Cursor,
sync::{Arc, mpsc},
thread,
};
struct MockStream(Cursor<Vec<u8>>);
impl Read for MockStream {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl TimeoutRead for MockStream {
fn set_read_timeout(&mut self, _duration: Option<Duration>) -> std::io::Result<()> {
Ok(())
}
}
fn contribution_wire(
request_id: u32,
range: SampleRange,
width: u32,
height: u32,
value: f32,
) -> Vec<u8> {
let sum = vec![Vec3::splat(value); (width * height) as usize];
let mut encoder = PayloadEncoder::new(PayloadEncoding::Raw);
let mut buf = Vec::new();
indicatrix_net::messages::write_contribution_message(
&mut buf,
request_id,
(range.first_sample, range.samples),
width,
height,
&sum,
&mut encoder,
)
.unwrap();
buf
}
fn header_and_stream(wire: Vec<u8>) -> (ContributionHeader, MockStream) {
let mut cursor = Cursor::new(wire);
let msg: indicatrix_net::messages::ClientMessage =
indicatrix_net::messages::read_message(&mut cursor).unwrap();
let indicatrix_net::messages::ClientMessage::Contribution(header) = msg else {
panic!("expected ClientMessage::Contribution");
};
(header, MockStream(cursor))
}
#[test]
fn an_arrival_before_the_wait_is_returned_immediately() {
let range = SampleRange::new(10, 4);
let slot = ContributionSlot::new(range, 2, 2);
let wire = contribution_wire(7, range, 2, 2, 3.0);
let (header, mut stream) = header_and_stream(wire);
slot.receive(&mut stream, &header, 7, &mut TimeoutCache::new())
.unwrap();
let start = Instant::now();
let Awaited::Arrived(sum) = slot.await_until(Duration::from_secs(30), || false) else {
panic!("expected Arrived");
};
assert_eq!(sum, vec![Vec3::splat(3.0); 4]);
assert!(start.elapsed() < Duration::from_secs(1));
}
#[test]
fn a_timeout_reclaims_and_a_late_arrival_is_dropped() {
let range = SampleRange::new(0, 2);
let slot = ContributionSlot::new(range, 1, 1);
let outcome = slot.await_until(Duration::from_millis(80), || false);
assert!(matches!(outcome, Awaited::Reclaim { .. }));
let wire = contribution_wire(1, range, 1, 1, 9.0);
let (header, mut stream) = header_and_stream(wire);
slot.receive(&mut stream, &header, 1, &mut TimeoutCache::new())
.unwrap();
assert!(matches!(*slot.state.lock().unwrap(), SlotState::Reclaimed));
}
#[test]
fn an_invalid_contribution_reclaims_without_waiting() {
let range = SampleRange::new(0, 2);
let slot = ContributionSlot::new(range, 1, 1);
let wire = contribution_wire(1, SampleRange::new(5, 2), 1, 1, 1.0);
let (header, mut stream) = header_and_stream(wire);
slot.receive(&mut stream, &header, 1, &mut TimeoutCache::new())
.unwrap();
let start = Instant::now();
let outcome = slot.await_until(Duration::from_secs(30), || false);
assert!(matches!(outcome, Awaited::Reclaim { .. }));
assert!(start.elapsed() < Duration::from_secs(1));
}
#[test]
fn a_receiving_upload_extends_the_deadline() {
const PASSES: usize = 6;
let range = SampleRange::new(0, 2);
let slot = Arc::new(ContributionSlot::new(range, 1, 1));
slot.set_state(SlotState::Receiving);
let (pass_tx, pass_rx) = mpsc::channel();
let waiter = {
let slot = Arc::clone(&slot);
thread::spawn(move || {
slot.await_until(Duration::from_millis(60), || {
let _ = pass_tx.send(());
false
})
})
};
for pass in 1..=PASSES {
pass_rx
.recv_timeout(Duration::from_secs(5))
.unwrap_or_else(|_| {
panic!(
"the waiter stopped after {} of {PASSES} wait passes: its 60 ms wait \
expired while an upload was still being received",
pass - 1
)
});
}
slot.set_state(SlotState::Arrived(vec![Vec3::ONE]));
let outcome = waiter.join().unwrap();
assert!(matches!(outcome, Awaited::Arrived(_)));
}
#[test]
fn cancel_ends_the_wait() {
let range = SampleRange::new(0, 2);
let slot = ContributionSlot::new(range, 1, 1);
let start = Instant::now();
let outcome = slot.await_until(Duration::from_secs(30), || true);
assert!(matches!(outcome, Awaited::Cancelled));
assert!(start.elapsed() < Duration::from_secs(1));
}
}