-
Notifications
You must be signed in to change notification settings - Fork 0
Unify outbound codec path with FramePipeline & CodecDriver #461
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
13 commits
Select commit
Hold shift + click to select a range
cf895e6
docs(execplans): add detailed exec plan for unifying codec handling b…
leynos 9928292
Unify outbound frame processing through FramePipeline
leynos 3f972f7
Add integration tests for the unified codec pipeline
leynos dbffdb3
Add BDD behavioural tests for the unified codec pipeline
leynos 16f55b1
Update documentation for the unified codec pipeline
leynos 722bfb0
Mark exec plan 9.3.1 as done with outcomes and retrospective
leynos c70637a
refactor(tests/fixtures/unified_codec): deduplicate payload verificat…
leynos e9e068e
Integrate inbound MessageAssembler; add assembly helper and routing (…
leynos 8735a08
Fix duplicated message assembly bindings
leynos fc713f7
refactor(unified-codec): unify test setup with shared runtime and hel…
leynos d575230
refactor(tests): consolidate payload verification in unified_codec steps
leynos d2ef2ca
fix(test_helpers): make first and continuation frame payload builders…
leynos 55651bc
refactor(tests): propagate errors from shared Tokio runtime initializ…
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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
Large diffs are not rendered by default.
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
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,224 @@ | ||
| //! Codec-aware connection driver that bridges the connection actor's frame | ||
| //! processing pipeline to a framed transport stream. | ||
| //! | ||
| //! The [`FramePipeline`] applies optional fragmentation and outbound metrics | ||
| //! to every [`Envelope`] before it reaches the wire. The [`send_envelope`] | ||
| //! and [`flush_pipeline_output`] helpers then serialize, wrap via | ||
| //! [`FrameCodec::wrap_payload`], and write the resulting frame to the | ||
| //! underlying [`Framed`] stream. | ||
| //! | ||
| //! This module ensures all outbound frames — handler responses, push | ||
| //! messages, streaming responses, and multi-packet channels — pass through | ||
| //! the same fragmentation and metrics pipeline before reaching the wire. | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| use bytes::Bytes; | ||
| use futures::SinkExt; | ||
| use log::warn; | ||
| use tokio::io::{self, AsyncRead, AsyncWrite}; | ||
| use tokio_util::codec::Framed; | ||
|
|
||
| use super::{ | ||
| combined_codec::ConnectionCodec, | ||
| envelope::Envelope, | ||
| fragmentation_state::FragmentationState, | ||
| }; | ||
| use crate::{ | ||
| codec::FrameCodec, | ||
| fragment::{FragmentationConfig, FragmentationError}, | ||
| serializer::Serializer, | ||
| }; | ||
|
|
||
| /// Outbound frame processing pipeline mirroring the connection actor's | ||
| /// `process_frame_with_hooks_and_metrics` logic. | ||
| /// | ||
| /// Applies optional fragmentation and outbound metrics to each envelope. | ||
| /// Produces a buffer of processed envelopes ready for serialization and | ||
| /// transmission. | ||
| pub(crate) struct FramePipeline { | ||
| fragmentation: Option<FragmentationState>, | ||
| out: Vec<Envelope>, | ||
| } | ||
|
|
||
| impl FramePipeline { | ||
| /// Create a pipeline with the given optional fragmentation config. | ||
| pub(crate) fn new(fragmentation: Option<FragmentationConfig>) -> Self { | ||
| Self { | ||
| fragmentation: fragmentation.map(FragmentationState::new), | ||
| out: Vec::new(), | ||
| } | ||
| } | ||
|
|
||
| /// Process an envelope through the pipeline: fragment → metrics. | ||
| /// | ||
| /// Processed envelopes are buffered internally. Call | ||
| /// [`drain_output`](Self::drain_output) to retrieve them. | ||
| pub(crate) fn process(&mut self, envelope: Envelope) -> io::Result<()> { | ||
| let id = envelope.id; | ||
| let correlation_id = envelope.correlation_id; | ||
| let frames = self.fragment_envelope(envelope).map_err(|err| { | ||
| warn!( | ||
| "failed to fragment outbound envelope: id={id}, \ | ||
| correlation_id={correlation_id:?}, error={err:?}" | ||
| ); | ||
| crate::metrics::inc_handler_errors(); | ||
| io::Error::other(err) | ||
| })?; | ||
| for frame in frames { | ||
| self.push_frame(frame); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Fragment an envelope if fragmentation is enabled, otherwise return it | ||
| /// as a single-element vector. | ||
| fn fragment_envelope( | ||
| &mut self, | ||
| envelope: Envelope, | ||
| ) -> Result<Vec<Envelope>, FragmentationError> { | ||
| match self.fragmentation.as_mut() { | ||
| Some(state) => state.fragment(envelope), | ||
| None => Ok(vec![envelope]), | ||
| } | ||
| } | ||
|
|
||
| /// Purge expired fragment reassembly state, if fragmentation is enabled. | ||
| pub(crate) fn purge_expired(&mut self) { | ||
| if let Some(state) = self.fragmentation.as_mut() { | ||
| state.purge_expired(); | ||
| } | ||
| } | ||
|
|
||
| /// Drain all buffered output envelopes, returning them for transmission. | ||
| pub(crate) fn drain_output(&mut self) -> Vec<Envelope> { std::mem::take(&mut self.out) } | ||
|
|
||
| /// Returns a mutable reference to the inner fragmentation state, if | ||
| /// fragmentation is enabled. | ||
| /// | ||
| /// Used by the inbound reassembly path which needs direct access to | ||
| /// [`FragmentationState::reassemble`]. | ||
| pub(crate) fn fragmentation_mut(&mut self) -> Option<&mut FragmentationState> { | ||
| self.fragmentation.as_mut() | ||
| } | ||
|
|
||
| /// Returns `true` when fragmentation is enabled. | ||
| #[cfg(test)] | ||
| pub(crate) fn has_fragmentation(&self) -> bool { self.fragmentation.is_some() } | ||
|
|
||
| fn push_frame(&mut self, envelope: Envelope) { | ||
| self.out.push(envelope); | ||
| crate::metrics::inc_frames(crate::metrics::Direction::Outbound); | ||
| } | ||
| } | ||
|
|
||
| /// Serialize an [`Envelope`] and write it through the codec to the framed | ||
| /// stream. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an [`io::Error`] if serialization or sending fails. | ||
| pub(super) async fn send_envelope<S, W, F>( | ||
| serializer: &S, | ||
| codec: &F, | ||
| framed: &mut Framed<W, ConnectionCodec<F>>, | ||
| envelope: &Envelope, | ||
| ) -> io::Result<()> | ||
| where | ||
| S: Serializer + Send + Sync, | ||
| W: AsyncRead + AsyncWrite + Unpin, | ||
| F: FrameCodec, | ||
| { | ||
| let bytes = serializer.serialize(envelope).map_err(|e| { | ||
| let id = envelope.id; | ||
| let correlation_id = envelope.correlation_id; | ||
| warn!( | ||
| "failed to serialize outbound envelope: id={id}, correlation_id={correlation_id:?}, \ | ||
| error={e:?}" | ||
| ); | ||
| crate::metrics::inc_handler_errors(); | ||
| io::Error::other(e) | ||
| })?; | ||
| let frame = codec.wrap_payload(Bytes::from(bytes)); | ||
| framed.send(frame).await.map_err(|e| { | ||
| let id = envelope.id; | ||
| let correlation_id = envelope.correlation_id; | ||
| warn!( | ||
| "failed to send outbound frame: id={id}, correlation_id={correlation_id:?}, \ | ||
| error={e:?}" | ||
| ); | ||
| crate::metrics::inc_handler_errors(); | ||
| io::Error::other(e) | ||
| }) | ||
| } | ||
|
|
||
| /// Flush a batch of pipeline-produced [`Envelope`] values through the codec | ||
| /// to the framed stream. | ||
| /// | ||
| /// Each envelope is serialized, wrapped, and written individually. On the | ||
| /// first I/O failure the remaining envelopes are discarded and the error is | ||
| /// returned. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an [`io::Error`] if any envelope fails to serialize or send. | ||
| pub(super) async fn flush_pipeline_output<S, W, F>( | ||
| serializer: &S, | ||
| codec: &F, | ||
| framed: &mut Framed<W, ConnectionCodec<F>>, | ||
| envelopes: &mut Vec<Envelope>, | ||
| ) -> io::Result<()> | ||
| where | ||
| S: Serializer + Send + Sync, | ||
| W: AsyncRead + AsyncWrite + Unpin, | ||
| F: FrameCodec, | ||
| { | ||
| for envelope in envelopes.drain(..) { | ||
| send_envelope(serializer, codec, framed, &envelope).await?; | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use rstest::{fixture, rstest}; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[fixture] | ||
| fn pipeline() -> FramePipeline { | ||
| let config = None; | ||
| FramePipeline::new(config) | ||
| } | ||
|
|
||
| #[rstest] | ||
| fn process_single_envelope_emits_one_frame(mut pipeline: FramePipeline) { | ||
| let env = Envelope::new(1, Some(42), vec![1, 2, 3]); | ||
| pipeline | ||
| .process(env) | ||
| .expect("processing should succeed without fragmentation"); | ||
| let mut output = pipeline.drain_output(); | ||
| assert_eq!(output.len(), 1); | ||
| let first = output | ||
| .pop() | ||
| .expect("pipeline should emit exactly one envelope"); | ||
| assert_eq!(first.id, 1); | ||
| assert_eq!(first.correlation_id, Some(42)); | ||
| assert_eq!(first.payload, vec![1, 2, 3]); | ||
| } | ||
|
|
||
| #[rstest] | ||
| fn drain_clears_buffer(mut pipeline: FramePipeline) { | ||
| pipeline | ||
| .process(Envelope::new(1, None, vec![])) | ||
| .expect("processing should succeed without fragmentation"); | ||
| let first = pipeline.drain_output(); | ||
| assert_eq!(first.len(), 1); | ||
|
|
||
| let second = pipeline.drain_output(); | ||
| assert!(second.is_empty()); | ||
| } | ||
|
|
||
| #[rstest] | ||
| fn pipeline_without_fragmentation(pipeline: FramePipeline) { | ||
| assert!(!pipeline.has_fragmentation()); | ||
| } | ||
| } | ||
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.