Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support interrupted streams in response #46

Closed
connorslade opened this issue Aug 20, 2023 · 0 comments
Closed

Support interrupted streams in response #46

connorslade opened this issue Aug 20, 2023 · 0 comments
Assignees
Labels
bug Something isn't working

Comments

@connorslade
Copy link
Owner

The following code does not work because in the ResponseData write method, if the Reader returns any error, including interrupted kind errors it just passes it up. What it should do, is copy the impl of read_to_end in Read where it just continues. Perhaps spin-locking like this isn't the best solution long term, but it's easy enough, and it's not like anybody is going to stop me.

pub fn attach(server: &mut Server<App>) {
    server.route(afire::Method::GET, "/test", |_| {
        Response::new().stream(TestStream::new())
    });
}

struct TestStream {
    count: usize,
    last: Instant,
}

impl TestStream {
    fn new() -> Self {
        Self {
            count: 0,
            last: Instant::now(),
        }
    }
}

impl Read for TestStream {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.count > 10 {
            return Ok(0);
        }

        let elapsed = self.last.elapsed().as_secs_f64();
        if elapsed < 0.5 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Interrupted,
                "Not enough time has elapsed.",
            ));
        }

        self.count += 1;
        let data = format!("{{\"count\": {}}}", self.count);
        let bytes = data.as_bytes();
        let len = bytes.len().min(buf.len());
        buf[..len].copy_from_slice(&bytes[..len]);
        Ok(len)
    }
}
@connorslade connorslade added the bug Something isn't working label Aug 20, 2023
@connorslade connorslade self-assigned this Aug 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: 🎉 Done
Development

No branches or pull requests

1 participant