-
Notifications
You must be signed in to change notification settings - Fork 0
Implement preamble callback tests #28
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b837fc7
Add tests for preamble callbacks
leynos 5e5c3ec
Document preamble callbacks
leynos 1ef9d82
Refine preamble handling and tests
leynos dd75bce
Refactor preamble reader
leynos 4c57460
Spawn per-connection tasks
leynos 429aad4
Document decode context
leynos 0be9b53
Log worker failures and avoid unused app
leynos ac74c8f
Handle leftover bytes in preamble
leynos 7b0c371
Add stream wrapper for leftover preamble bytes
leynos 8c824fc
Forward connections to application
leynos 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
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # Connection Preamble Validation | ||
|
|
||
| `wireframe` supports an optional connection preamble that is read as soon as a | ||
| client connects. The server decodes the preamble with | ||
| [`read_preamble`](../src/preamble.rs) and can invoke user-supplied callbacks on | ||
| success or failure. The helper uses `bincode` to decode any type implementing | ||
| `bincode::Decode` and reads exactly the number of bytes required. | ||
|
|
||
| The flow is summarized below: | ||
|
|
||
| ```mermaid | ||
| sequenceDiagram | ||
| participant Client | ||
| participant Server | ||
| participant PreambleDecoder | ||
| participant SuccessCallback | ||
| participant FailureCallback | ||
|
|
||
| Client->>Server: Connects and sends preamble bytes | ||
| Server->>PreambleDecoder: Reads and decodes preamble | ||
| alt Decode success | ||
| PreambleDecoder-->>Server: Decoded preamble (T) | ||
| Server->>SuccessCallback: Invoke with preamble data | ||
| else Decode failure | ||
| PreambleDecoder-->>Server: DecodeError | ||
| Server->>FailureCallback: Invoke with error | ||
| end | ||
| Server-->>Client: (Continues or closes connection) | ||
| ``` | ||
|
|
||
| In the tests, a `HotlinePreamble` struct illustrates the pattern, but any | ||
| preamble type may be used. Register callbacks via `on_preamble_decode_success` | ||
| and `on_preamble_decode_failure` on `WireframeServer`. |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| use bincode::error::DecodeError; | ||
| use bincode::{Decode, config, decode_from_slice}; | ||
| use tokio::io::{self, AsyncRead, AsyncReadExt}; | ||
|
|
||
| const MAX_PREAMBLE_LEN: usize = 1024; | ||
|
|
||
| async fn read_more<R>( | ||
| reader: &mut R, | ||
| buf: &mut Vec<u8>, | ||
| additional: usize, | ||
| ) -> Result<(), DecodeError> | ||
| where | ||
| R: AsyncRead + Unpin, | ||
| { | ||
| let start = buf.len(); | ||
| if start + additional > MAX_PREAMBLE_LEN { | ||
| return Err(DecodeError::Other("preamble too long")); | ||
| } | ||
| buf.resize(start + additional, 0); | ||
| let mut read = 0; | ||
| while read < additional { | ||
| match reader | ||
| .read(&mut buf[start + read..start + additional]) | ||
| .await | ||
| { | ||
| Ok(0) => { | ||
| return Err(DecodeError::Io { | ||
| inner: io::Error::from(io::ErrorKind::UnexpectedEof), | ||
| additional: additional - read, | ||
| }); | ||
| } | ||
| Ok(n) => read += n, | ||
| Err(inner) => { | ||
| return Err(DecodeError::Io { | ||
| inner, | ||
| additional: additional - read, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Read and decode a connection preamble using bincode. | ||
| /// | ||
| /// This helper reads the exact number of bytes required by `T`, as | ||
| /// indicated by [`DecodeError::UnexpectedEnd`]. Additional bytes are | ||
| /// requested from the reader until decoding succeeds or fails for some | ||
| /// other reason. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns a [`DecodeError`] if decoding the preamble fails or an | ||
| /// underlying I/O error occurs while reading from `reader`. | ||
| pub async fn read_preamble<R, T>(reader: &mut R) -> Result<(T, Vec<u8>), DecodeError> | ||
| where | ||
| R: AsyncRead + Unpin, | ||
| // `Decode` expects a decoding context type, not a lifetime. Most callers | ||
| // use the unit type as the context, which requires no external state. | ||
| T: Decode<()>, | ||
| { | ||
| let mut buf = Vec::new(); | ||
| // Build the decoder configuration once to avoid repeated allocations. | ||
| let config = config::standard() | ||
| .with_big_endian() | ||
| .with_fixed_int_encoding(); | ||
| loop { | ||
| match decode_from_slice::<T, _>(&buf, config) { | ||
| Ok((value, consumed)) => { | ||
| let leftover = buf.split_off(consumed); | ||
| return Ok((value, leftover)); | ||
| } | ||
| Err(DecodeError::UnexpectedEnd { additional }) => { | ||
| read_more(reader, &mut buf, additional).await?; | ||
| } | ||
| Err(e) => return Err(e), | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| use std::io; | ||
| use std::pin::Pin; | ||
| use std::task::{Context, Poll}; | ||
|
|
||
| use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; | ||
|
|
||
| /// A stream adapter that replays buffered bytes before reading | ||
| /// from the underlying stream. | ||
| pub struct RewindStream<S> { | ||
| leftover: Vec<u8>, | ||
| pos: usize, | ||
| inner: S, | ||
| } | ||
|
|
||
| impl<S> RewindStream<S> { | ||
| /// Create a new `RewindStream` that will yield `leftover` before | ||
| /// delegating to `inner`. | ||
| pub fn new(leftover: Vec<u8>, inner: S) -> Self { | ||
| Self { | ||
| leftover, | ||
| pos: 0, | ||
| inner, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<S: AsyncRead + Unpin> AsyncRead for RewindStream<S> { | ||
| fn poll_read( | ||
| mut self: Pin<&mut Self>, | ||
| cx: &mut Context<'_>, | ||
| buf: &mut ReadBuf<'_>, | ||
| ) -> Poll<io::Result<()>> { | ||
| if self.pos < self.leftover.len() { | ||
| let remaining = self.leftover.len() - self.pos; | ||
| let to_copy = remaining.min(buf.remaining()); | ||
| let start = self.pos; | ||
| let end = start + to_copy; | ||
| buf.put_slice(&self.leftover[start..end]); | ||
| self.pos += to_copy; | ||
| if self.pos < self.leftover.len() || to_copy > 0 { | ||
| return Poll::Ready(Ok(())); | ||
| } | ||
| } | ||
|
|
||
| if self.pos >= self.leftover.len() && !self.leftover.is_empty() { | ||
| self.leftover.clear(); | ||
| self.pos = 0; | ||
| } | ||
|
|
||
| Pin::new(&mut self.inner).poll_read(cx, buf) | ||
| } | ||
| } | ||
|
|
||
| impl<S: AsyncWrite + Unpin> AsyncWrite for RewindStream<S> { | ||
| fn poll_write( | ||
| mut self: Pin<&mut Self>, | ||
| cx: &mut Context<'_>, | ||
| buf: &[u8], | ||
| ) -> Poll<io::Result<usize>> { | ||
| Pin::new(&mut self.inner).poll_write(cx, buf) | ||
| } | ||
|
|
||
| fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { | ||
| Pin::new(&mut self.inner).poll_flush(cx) | ||
| } | ||
|
|
||
| fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { | ||
| Pin::new(&mut self.inner).poll_shutdown(cx) | ||
| } | ||
| } | ||
|
|
||
| impl<S: Unpin> Unpin for RewindStream<S> {} |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.