-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
- [✅] I have looked for existing issues (including closed) about this
Feature Request
Motivation
When working with WebSockets in Axum, developers often need to handle low-level details such as Ping/Pong frames, Close frames, and connection cleanup manually. This leads to repetitive boilerplate code across projects, especially for applications that primarily care about processing Text and Binary messages. Additionally, configuring WebSocket parameters like ping intervals requires deep knowledge of Axum's internals, which can be a barrier for new users and slows down development for experienced users. A higher-level abstraction would simplify common use cases and reduce the chance of bugs related to improper handling of control frames.
Proposal
I propose adding a higher-level WebSocket interface that abstracts away low-level frame handling while allowing configuration of key parameters. The core features would include:
- Automatic control frame handling: The interface would automatically respond to Ping frames with Pongs, send periodic Ping frames to keep connections alive, and handle Close frames gracefully (including cleanup).
- Simplified message processing: Users would only need to handle Text and Binary messages, as control frames are filtered out and processed internally.
- Configurable options: A builder-style API for WebSocketUpgrade to set ping intervals, max message size, buffer limits, etc.
- Backward compatibility: The existing low-level WebSocket type would remain available for advanced use cases.
Implementation details:
- Introduce a HighLevelWebSocket struct that wraps the existing WebSocket and manages control frames in a background task.
- Expose a stream of HighLevelMessage (containing only Text/Binary variants) for user processing.
- Add methods to WebSocketUpgrade (e.g., with_ping_interval, with_max_message_size) to configure the high-level behavior.
- Handle connection cleanup when close frames are received or the stream ends.
Potential drawbacks:
- Adds a small layer of indirection, though this should be negligible.
- May not cover all edge cases for advanced users, but the low-level API remains available.
Alternatives
- Third-party libraries: Users could use community crates to wrap Axum's WebSocket, but this fragments the ecosystem and may not maintain compatibility with Axum updates.
- Manual middleware: Users could implement their own middleware to handle control frames, but this duplicates effort and increases the chance of inconsistent implementations.
- Extending existing types: Modifying the existing WebSocket type to include these features could break backward compatibility. A new type avoids this risk.
The proposed solution is preferred because it keeps the core Axum API consistent, provides a built-in solution for common use cases, and maintains flexibility for advanced users.