-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Polled SSR Stream #2824
Merged
+506
−279
Merged
Polled SSR Stream #2824
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
5bf1ae8
Switch to pinned channels.
futursolo fb2603e
Fix ServerRenderer so it's not blocked until the result is resolved.
futursolo 892b759
Fix tests.
futursolo 29a46bd
Remove unused SendError.
futursolo 20fc4a3
Merge branch 'master' into pinned-channels
futursolo 8a41c3e
Implement a stream to be polled alongside rendering.
futursolo 8688045
Update Buffer Size.
futursolo 3bd9e0a
Make Send renderer work.
futursolo ed36760
Remove pinned channels.
futursolo 2799a22
Unified Naming.
futursolo 02a838d
Optimise code.
futursolo 3de0770
Restore capacity.
futursolo 689980e
merge 'master' into polled-stream
futursolo cbbd765
Remove unused profile.
futursolo 2045c49
Merge branch 'master' into polled-stream
futursolo a470862
Default to separate resolver.
futursolo 3ac02fd
Reduce allocations on string.
futursolo 345b745
Adjust API.
futursolo d1a6ab3
Remove duplicate trait bound.
futursolo f0863a4
Update docs.
futursolo 7dcaf6e
Remove capacity setting.
futursolo ced12ac
Merge branch 'master' into polled-stream
futursolo 475f52e
Merge branch 'master' into polled-stream
futursolo e757d35
Unsafe?
futursolo 0a399ba
Separate files.
futursolo 6ae5a65
Adjust inlining.
futursolo f310575
Merge branch 'master' into polled-stream
futursolo e18e0fd
Fix test.
futursolo 67348d3
Update notice.
futursolo f491d6c
Update documentation.
futursolo 2a300fe
Merge branch 'master' into polled-stream
futursolo a78f0b3
Fix tests.
futursolo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Implement a stream to be polled alongside rendering.
commit 8a41c3e4ec0453aaa9b465e5728cf56e012db6de
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,143 +1,203 @@ | ||
//! This module contains types for I/O functionality. | ||
|
||
// This module should remain private until impl trait type alias becomes available so | ||
// `BufReader` can be produced with an existential type. | ||
use std::cell::RefCell; | ||
use std::fmt::{self, Write}; | ||
use std::future::Future; | ||
use std::rc::Rc; | ||
use std::task::{Poll, Waker}; | ||
|
||
use std::borrow::Cow; | ||
use futures::future::{self, FusedFuture, MaybeDone}; | ||
use futures::stream::{FusedStream, Stream}; | ||
use pin_project::pin_project; | ||
|
||
use crate::platform::pinned; | ||
|
||
// Same as std::io::BufWriter and futures::io::BufWriter. | ||
pub(crate) const DEFAULT_BUF_SIZE: usize = 8 * 1024; | ||
struct BufStreamInner { | ||
buf: String, | ||
waker: Option<Waker>, | ||
done: bool, | ||
} | ||
|
||
pub(crate) trait BufSend { | ||
fn buf_send(&self, item: String); | ||
pub(crate) struct Writer { | ||
inner: Rc<RefCell<BufStreamInner>>, | ||
} | ||
|
||
impl BufSend for pinned::mpsc::UnboundedSender<String> { | ||
fn buf_send(&self, item: String) { | ||
let _ = self.send_now(item); | ||
impl Write for Writer { | ||
fn write_str(&mut self, s: &str) -> fmt::Result { | ||
let mut inner = self.inner.borrow_mut(); | ||
|
||
if inner.buf.is_empty() { | ||
inner.buf.reserve(1024); | ||
} | ||
|
||
let result = inner.buf.write_str(s); | ||
|
||
if let Some(waker) = inner.waker.take() { | ||
waker.wake(); | ||
} | ||
|
||
result | ||
} | ||
} | ||
|
||
impl BufSend for futures::channel::mpsc::UnboundedSender<String> { | ||
fn buf_send(&self, item: String) { | ||
let _ = self.unbounded_send(item); | ||
fn write_char(&mut self, c: char) -> fmt::Result { | ||
let mut inner = self.inner.borrow_mut(); | ||
|
||
if inner.buf.is_empty() { | ||
inner.buf.reserve(1024); | ||
} | ||
|
||
let result = inner.buf.write_char(c); | ||
|
||
if let Some(waker) = inner.waker.take() { | ||
waker.wake(); | ||
} | ||
|
||
result | ||
} | ||
} | ||
|
||
pub trait BufWrite { | ||
fn capacity(&self) -> usize; | ||
fn write(&mut self, s: Cow<'_, str>); | ||
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { | ||
let mut inner = self.inner.borrow_mut(); | ||
|
||
if inner.buf.is_empty() { | ||
inner.buf.reserve(1024); | ||
} | ||
|
||
let result = inner.buf.write_fmt(args); | ||
|
||
if let Some(waker) = inner.waker.take() { | ||
waker.wake(); | ||
} | ||
|
||
result | ||
} | ||
} | ||
|
||
/// A [`futures::io::BufWriter`], but operates over string and yields into a Stream. | ||
pub(crate) struct BufWriter<S> | ||
#[pin_project] | ||
pub(crate) struct BufStream<F> | ||
where | ||
S: BufSend, | ||
F: Future<Output = ()>, | ||
{ | ||
buf: String, | ||
tx: S, | ||
capacity: usize, | ||
#[pin] | ||
resolver: Option<MaybeDone<F>>, | ||
inner: Rc<RefCell<BufStreamInner>>, | ||
} | ||
|
||
// Implementation Notes: | ||
// | ||
// When jemalloc is used and a reasonable buffer length is chosen, | ||
// performance of this buffer is related to the number of allocations | ||
// instead of the amount of memory that is allocated. | ||
// | ||
// A Bytes-based implementation is also tested, and yielded a similar performance to String-based | ||
// buffer. | ||
// | ||
// Having a String-based buffer avoids unsafe / cost of conversion between String and Bytes | ||
// when text based content is needed (e.g.: post-processing). | ||
// | ||
// `Bytes::from` can be used to convert a `String` to `Bytes` if web server asks for an | ||
// `impl Stream<Item = Bytes>`. This conversion incurs no memory allocation. | ||
// | ||
// Yielding the output with a Stream provides a couple advantages: | ||
// | ||
// 1. All child components of a VList can have their own buffer and be rendered concurrently. | ||
// 2. If a fixed buffer is used, the rendering process can become blocked if the buffer is filled. | ||
// Using a stream avoids this side effect and allows the renderer to finish rendering | ||
// without being actively polled. | ||
impl<S> BufWriter<S> | ||
impl<F> BufStream<F> | ||
where | ||
S: BufSend, | ||
F: Future<Output = ()>, | ||
{ | ||
pub fn new(tx: S, capacity: usize) -> Self { | ||
Self { | ||
buf: String::new(), | ||
tx, | ||
capacity, | ||
} | ||
} | ||
|
||
#[inline] | ||
fn drain(&mut self) { | ||
if !self.buf.is_empty() { | ||
self.tx.buf_send(self.buf.split_off(0)); | ||
} | ||
} | ||
pub fn new<C>(f: C) -> Self | ||
where | ||
C: FnOnce(Writer) -> F, | ||
{ | ||
let inner = { | ||
Rc::new(RefCell::new(BufStreamInner { | ||
buf: String::new(), | ||
waker: None, | ||
done: false, | ||
})) | ||
}; | ||
|
||
let resolver = { | ||
let inner = inner.clone(); | ||
let w = Writer { inner }; | ||
|
||
future::maybe_done(f(w)) | ||
}; | ||
|
||
#[inline] | ||
fn reserve(&mut self) { | ||
if self.buf.is_empty() { | ||
self.buf.reserve(self.capacity); | ||
Self { | ||
resolver: Some(resolver), | ||
inner, | ||
} | ||
} | ||
|
||
/// Returns `True` if the internal buffer has capacity to fit a string of certain length. | ||
#[inline] | ||
fn has_capacity_of(&self, next_part_len: usize) -> bool { | ||
self.buf.capacity() >= self.buf.len() + next_part_len | ||
pub fn new_with_resolver<C>(f: C) -> (BufStream<F>, impl Future<Output = ()>) | ||
where | ||
C: FnOnce(Writer) -> F, | ||
{ | ||
let inner = { | ||
Rc::new(RefCell::new(BufStreamInner { | ||
buf: String::new(), | ||
waker: None, | ||
done: false, | ||
})) | ||
}; | ||
|
||
let resolver = { | ||
let inner = inner.clone(); | ||
let w = { | ||
let inner = inner.clone(); | ||
|
||
Writer { inner } | ||
}; | ||
|
||
async move { | ||
f(w).await; | ||
inner.borrow_mut().done = true; | ||
} | ||
}; | ||
|
||
( | ||
Self { | ||
resolver: None, | ||
inner, | ||
}, | ||
resolver, | ||
) | ||
} | ||
} | ||
|
||
impl<S> BufWrite for BufWriter<S> | ||
impl<F> Stream for BufStream<F> | ||
where | ||
S: BufSend, | ||
F: Future<Output = ()>, | ||
{ | ||
#[inline] | ||
fn capacity(&self) -> usize { | ||
self.capacity | ||
} | ||
type Item = String; | ||
|
||
/// Writes a string into the buffer, optionally drains the buffer. | ||
fn write(&mut self, s: Cow<'_, str>) { | ||
// Try to reserve the capacity first. | ||
self.reserve(); | ||
fn poll_next( | ||
self: std::pin::Pin<&mut Self>, | ||
cx: &mut std::task::Context<'_>, | ||
) -> std::task::Poll<Option<Self::Item>> { | ||
let this = self.project(); | ||
|
||
if !self.has_capacity_of(s.len()) { | ||
// There isn't enough capacity, we drain the buffer. | ||
self.drain(); | ||
} | ||
match this.resolver.as_pin_mut() { | ||
Some(mut resolver) => { | ||
let _ = resolver.as_mut().poll(cx); | ||
|
||
let mut inner = this.inner.borrow_mut(); | ||
|
||
if self.has_capacity_of(s.len()) { | ||
// The next part is going to fit into the buffer, we push it onto the buffer. | ||
self.buf.push_str(&s); | ||
} else { | ||
// if the next part is more than buffer size, we send the next part. | ||
|
||
// We don't need to drain the buffer here as the result of self.has_capacity_of() only | ||
// changes if the buffer was drained. If the buffer capacity didn't change, | ||
// then it means self.has_capacity_of() has returned true the first time which will be | ||
// guaranteed to be matched by the left hand side of this implementation. | ||
self.tx.buf_send(s.into_owned()); | ||
match (inner.buf.is_empty(), resolver.is_terminated()) { | ||
(true, true) => Poll::Ready(None), | ||
(true, false) => Poll::Pending, | ||
(false, _) => Poll::Ready(Some(inner.buf.split_off(0))), | ||
} | ||
} | ||
None => { | ||
let mut inner = this.inner.borrow_mut(); | ||
|
||
if !inner.buf.is_empty() { | ||
return Poll::Ready(Some(inner.buf.split_off(0))); | ||
} | ||
|
||
if inner.done { | ||
return Poll::Ready(None); | ||
} | ||
|
||
inner.waker = Some(cx.waker().clone()); | ||
|
||
Poll::Pending | ||
} | ||
} | ||
} | ||
} | ||
|
||
impl<S> Drop for BufWriter<S> | ||
impl<F> FusedStream for BufStream<F> | ||
where | ||
S: BufSend, | ||
F: Future<Output = ()>, | ||
{ | ||
fn drop(&mut self) { | ||
if !self.buf.is_empty() { | ||
let mut buf = String::new(); | ||
std::mem::swap(&mut buf, &mut self.buf); | ||
self.tx.buf_send(buf); | ||
fn is_terminated(&self) -> bool { | ||
let inner = self.inner.borrow(); | ||
|
||
match self.resolver.as_ref() { | ||
Some(resolver) => inner.buf.is_empty() && resolver.is_terminated(), | ||
None => inner.buf.is_empty() && inner.done, | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pin-project-lite
maybe?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
See: https://docs.rs/pin-project-lite/0.2.8/pin_project_lite/#different-no-proc-macro-related-dependencies
The primary benefit of
#[pin_project]
is that rustfmt will continue to work for the struct.