Repository navigation
refactor(framer): replace Framer trait with tokio-util codecs #43193
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
4 commits
Select commit
Hold shift + click to select a range
b793c64
refactor(framer): replace Framer trait with tokio-util codecs
yujonglee-berri 6d3d09b
refactor(framer): port SSE and AWS event stream framing to codecs
yujonglee-berri 57b0015
fix(rust): drop clone on Copy capabilities in messages request test
yujonglee-berri ed1437d
fix(rust): use field init shorthand in messages request test
yujonglee-berri 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 |
|---|---|---|
| @@ -1,66 +1,47 @@ | ||
| use bytes::{Buf, Bytes, BytesMut}; | ||
| use futures_util::{Stream, StreamExt}; | ||
| use aws_smithy_eventstream::frame::{read_message_from, write_message_to}; | ||
| pub use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; | ||
| use bytes::BytesMut; | ||
| use tokio_util::codec::{Decoder, Encoder}; | ||
|
|
||
| use aws_smithy_eventstream::frame::read_message_from; | ||
| use aws_smithy_types::event_stream::Header; | ||
|
|
||
| use crate::{Error, Framer}; | ||
| use crate::EventStreamError; | ||
|
|
||
| const MIN_FRAME_BYTES: usize = 16; | ||
| const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024; | ||
|
|
||
| #[derive(Clone, Debug, PartialEq)] | ||
| pub struct AwsEventStreamFrame { | ||
| pub headers: Vec<Header>, | ||
| pub payload: Bytes, | ||
| } | ||
|
|
||
| #[derive(Clone, Copy, Debug, Default)] | ||
| pub struct AwsEventStreamFramer; | ||
| pub struct AwsEventStreamCodec; | ||
|
|
||
| impl Decoder for AwsEventStreamCodec { | ||
| type Item = Message; | ||
| type Error = EventStreamError; | ||
|
|
||
| fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Message>, EventStreamError> { | ||
| let Some(prefix) = src.first_chunk::<4>() else { | ||
| return Ok(None); | ||
| }; | ||
| let length = u32::from_be_bytes(*prefix) as usize; | ||
| if !(MIN_FRAME_BYTES..=MAX_FRAME_BYTES).contains(&length) { | ||
| return Err(EventStreamError::InvalidLength(length)); | ||
| } | ||
| if src.len() < length { | ||
| return Ok(None); | ||
| } | ||
| Ok(Some(read_message_from(src.split_to(length).freeze())?)) | ||
| } | ||
|
|
||
| fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Message>, EventStreamError> { | ||
| match self.decode(src)? { | ||
| Some(message) => Ok(Some(message)), | ||
| None if src.is_empty() => Ok(None), | ||
| None => Err(EventStreamError::Truncated), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Framer for AwsEventStreamFramer { | ||
| type Frame = AwsEventStreamFrame; | ||
| impl Encoder<Message> for AwsEventStreamCodec { | ||
| type Error = EventStreamError; | ||
|
|
||
| fn frame<S, B, E>(self, input: S) -> impl Stream<Item = Result<Self::Frame, Error>> + Send | ||
| where | ||
| S: Stream<Item = Result<B, E>> + Send, | ||
| B: Buf + Send, | ||
| E: std::error::Error + Send + Sync + 'static, | ||
| { | ||
| futures_util::stream::try_unfold( | ||
| (Box::pin(input), BytesMut::new()), | ||
| |(mut input, mut buffer)| async move { | ||
| loop { | ||
| if buffer.len() >= 4 { | ||
| let length = (&buffer[..4]).get_u32() as usize; | ||
| if !(16..=MAX_FRAME_BYTES).contains(&length) { | ||
| return Err(Error::InvalidLength(length)); | ||
| } | ||
| if buffer.len() >= length { | ||
| let raw = buffer.split_to(length).freeze(); | ||
| let message = read_message_from(raw)?; | ||
| let frame = AwsEventStreamFrame { | ||
| headers: message.headers().to_vec(), | ||
| payload: message.payload().clone(), | ||
| }; | ||
| return Ok(Some((frame, (input, buffer)))); | ||
| } | ||
| } | ||
| match input.next().await { | ||
| Some(Ok(mut chunk)) => { | ||
| while chunk.has_remaining() { | ||
| let bytes = chunk.chunk(); | ||
| buffer.extend_from_slice(bytes); | ||
| let length = bytes.len(); | ||
| chunk.advance(length); | ||
| } | ||
| } | ||
| Some(Err(error)) => return Err(Error::Body(Box::new(error))), | ||
| None if buffer.is_empty() => return Ok(None), | ||
| None => return Err(Error::Truncated), | ||
| } | ||
| } | ||
| }, | ||
| ) | ||
| .fuse() | ||
| fn encode(&mut self, message: Message, dst: &mut BytesMut) -> Result<(), EventStreamError> { | ||
| Ok(write_message_to(&message, dst)?) | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -1,17 +1,21 @@ | ||
| #[cfg(feature = "sse")] | ||
| #[derive(Debug, thiserror::Error)] | ||
| pub enum Error { | ||
| #[cfg(feature = "sse")] | ||
| #[error("SSE framing failed: {0}")] | ||
| Sse(#[from] sse_stream::Error), | ||
| #[cfg(feature = "aws")] | ||
| #[error("AWS EventStream framing failed: {0}")] | ||
| Aws(#[from] aws_smithy_eventstream::error::Error), | ||
| pub enum SseError { | ||
| #[error("body stream failed: {0}")] | ||
| Body(#[source] Box<dyn std::error::Error + Send + Sync>), | ||
| #[cfg(feature = "aws")] | ||
| Body(#[from] std::io::Error), | ||
| #[error("SSE field is not UTF-8: {0}")] | ||
| InvalidUtf8(#[from] std::str::Utf8Error), | ||
| } | ||
|
|
||
| #[cfg(feature = "aws")] | ||
| #[derive(Debug, thiserror::Error)] | ||
| pub enum EventStreamError { | ||
| #[error("body stream failed: {0}")] | ||
| Body(#[from] std::io::Error), | ||
| #[error("invalid AWS EventStream frame length: {0}")] | ||
| InvalidLength(usize), | ||
| #[cfg(feature = "aws")] | ||
| #[error("truncated AWS EventStream frame")] | ||
| Truncated, | ||
| #[error("malformed AWS EventStream frame: {0}")] | ||
| Malformed(#[from] aws_smithy_eventstream::error::Error), | ||
| } |
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,21 @@ | ||
| use std::io; | ||
|
|
||
| use bytes::Buf; | ||
| use futures_util::{Stream, StreamExt, TryStreamExt}; | ||
| use tokio_util::{ | ||
| codec::{Decoder, FramedRead}, | ||
| io::StreamReader, | ||
| }; | ||
|
|
||
| pub fn frames<S, B, E, D>( | ||
| input: S, | ||
| codec: D, | ||
| ) -> impl Stream<Item = Result<D::Item, D::Error>> + Send | ||
| where | ||
| S: Stream<Item = Result<B, E>> + Send, | ||
| B: Buf + Send, | ||
| E: std::error::Error + Send + Sync + 'static, | ||
| D: Decoder + Send, | ||
| { | ||
| FramedRead::new(StreamReader::new(input.map_err(io::Error::other)), codec).fuse() | ||
| } | ||
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
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.