Context
The ConnectionActor currently maintains two separate optional fields for handling streaming output:
response: Option<FrameStream<F, E>>
multi_packet: MultiPacketContext<F>
These fields are mutually exclusive by design, but this invariant is enforced only through runtime assertions at multiple points in the code:
src/connection/mod.rs:245: set_response() asserts multi_packet is not active
src/connection/mod.rs:257: set_multi_packet() asserts response is None
src/connection/mod.rs:295: set_multi_packet_with_stamp() asserts response is None
src/connection/mod.rs:366: run() asserts at most one is active
Proposed Solution
Replace the two separate fields with a single enum that encodes the mutual exclusion at the type level:
enum ActiveOutput<F, E> {
None,
Response(FrameStream<F, E>),
MultiPacket(MultiPacketContext<F>),
}
This approach would:
- Eliminate the runtime invariant checks entirely (making violation a compile-time error)
- Simplify the
tokio::select! logic by removing conditional branches
- Make the mutual exclusion explicit in the type system
- Reduce cognitive overhead when reading and maintaining the actor code
Benefits
- Type safety: Impossible states become unrepresentable
- Simplified logic: No need for runtime checks or conditional branches
- Clearer intent: The mutual exclusion is self-documenting in the type
- Easier maintenance: Future modifications won't accidentally violate the invariant
Related
Follow-up to PR #424 which refactored the connection module into submodules.
Requested by: @leynos
Source: #424 (comment)
Context
The
ConnectionActorcurrently maintains two separate optional fields for handling streaming output:response: Option<FrameStream<F, E>>multi_packet: MultiPacketContext<F>These fields are mutually exclusive by design, but this invariant is enforced only through runtime assertions at multiple points in the code:
src/connection/mod.rs:245:set_response()asserts multi_packet is not activesrc/connection/mod.rs:257:set_multi_packet()asserts response is Nonesrc/connection/mod.rs:295:set_multi_packet_with_stamp()asserts response is Nonesrc/connection/mod.rs:366:run()asserts at most one is activeProposed Solution
Replace the two separate fields with a single enum that encodes the mutual exclusion at the type level:
This approach would:
tokio::select!logic by removing conditional branchesBenefits
Related
Follow-up to PR #424 which refactored the connection module into submodules.
Requested by: @leynos
Source: #424 (comment)