Skip to content

Refactor ConnectionActor to use single enum for mutually-exclusive response/multi-packet state #430

@coderabbitai

Description

@coderabbitai

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:

  1. Eliminate the runtime invariant checks entirely (making violation a compile-time error)
  2. Simplify the tokio::select! logic by removing conditional branches
  3. Make the mutual exclusion explicit in the type system
  4. 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)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions