Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions crates/kiri-image/src/cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use std::time::{Duration, Instant};
#[derive(Debug, Clone, Default)]
pub struct Cancel(Arc<Inner>);

pub(crate) const INTERRUPT: Duration = Duration::from_millis(50);

#[derive(Debug, Default)]
struct Inner {
cancelled: AtomicBool,
Expand Down Expand Up @@ -73,6 +75,7 @@ impl Cancel {
fn watch(&self, stream: &Arc<TcpStream>) -> io::Result<()> {
let mut streams = self.0.streams.lock().unwrap_or_else(|e| e.into_inner());
if self.is_cancelled() {
let _ = stream.shutdown(Shutdown::Both);
return Err(io::Error::other("pull cancelled"));
}
streams.retain(|s| s.strong_count() > 0);
Expand Down Expand Up @@ -102,6 +105,14 @@ pub(crate) fn watch(stream: &Arc<TcpStream>) -> io::Result<()> {
})
}

pub(crate) fn active() -> bool {
CURRENT.with(|c| c.borrow().is_some())
}

pub(crate) fn is_cancelled() -> bool {
CURRENT.with(|c| c.borrow().as_ref().is_some_and(Cancel::is_cancelled))
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -120,9 +131,32 @@ mod tests {
std::thread::spawn(move || {
let _on = cancel.enter();
watch(&client).unwrap();
client.set_read_timeout(Some(INTERRUPT)).unwrap();
let started = Instant::now();
let n = (&*client).read(&mut [0u8; 16]).unwrap_or(0);
(n, started.elapsed())
let mut buf = [0u8; 16];
loop {
match (&*client).read(&mut buf) {
Ok(n) => break (n, started.elapsed()),
Err(e)
if matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) && cancel.is_cancelled() =>
{
break (0, started.elapsed());
}
Err(e)
if matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) =>
{
continue;
}
Err(_) if cancel.is_cancelled() => break (0, started.elapsed()),
Err(e) => panic!("read failed: {e}"),
}
}
})
};
std::thread::sleep(Duration::from_millis(100));
Expand Down
54 changes: 44 additions & 10 deletions crates/kiri-image/src/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,28 +232,62 @@ impl Transport for TcpTransport {
fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, Error> {
let timeout = timeout.for_read();
let limit = capped(remaining(timeout)?, self.stall);
if limit != self.timeout_read {
self.stream.set_read_timeout(limit)?;
self.timeout_read = limit;
}
// A cancelled pull's reads end here, or at once if already waiting.
crate::cancel::watch(&self.stream)?;
let interruptible = crate::cancel::active();
let started = Instant::now();
let input = self.buffers.input_append_buf();
let amount = loop {
if crate::cancel::is_cancelled() {
return Err(Error::Io(io::Error::other("pull cancelled")));
}
let left = limit.map(|l| l.saturating_sub(started.elapsed()));
if left.is_some_and(|l| l.is_zero()) {
return Err(Error::Timeout(timeout.reason));
}
// Only cancel-scoped reads poll; other connections keep the full stall timeout.
let read_timeout = if interruptible {
Some(left.map_or(crate::cancel::INTERRUPT, |l| {
l.min(crate::cancel::INTERRUPT)
}))
} else {
left
};
if read_timeout != self.timeout_read {
self.stream.set_read_timeout(read_timeout)?;
self.timeout_read = read_timeout;
}
match (&*self.stream).read(input) {
// A signal: Linux does not restart a socket read that has a
// timeout, so go again with what is left of it.
Err(e) if e.kind() == io::ErrorKind::Interrupted => {
let Some(limit) = limit else {
if !interruptible && limit.is_none() {
return Err(Error::Io(e));
};
let left = limit.saturating_sub(started.elapsed());
if left.is_zero() {
}
if limit.is_some_and(|l| l <= started.elapsed()) {
return Err(Error::Timeout(timeout.reason));
}
}
Err(e)
if interruptible
&& matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
)
&& crate::cancel::is_cancelled() =>
{
return Err(Error::Io(io::Error::other("pull cancelled")));
}
Err(e)
if interruptible
&& matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) =>
{
if limit.is_some_and(|l| l <= started.elapsed()) {
return Err(Error::Timeout(timeout.reason));
}
self.stream.set_read_timeout(Some(left))?;
self.timeout_read = Some(left);
}
result => break result.map_err(|e| io_error(e, timeout.reason))?,
}
Expand Down