Expand description
PDK WebSockets Library
Library for decoding and encoding WebSocket frames in Flex Gateway custom policies.
It wraps [websocket-sans-io] to provide ergonomic frame-level access for policies
that operate on WebSocket upgrade connections.
§Primary types
Frame: a single WebSocket frame with its payload and metadataFrameType: the kind of frame (Text, Binary, Ping, Pong, etc.)Decoder: incrementally decodes raw bytes intoFramesEncoder: re-encodes a collection ofFrames into bytesSinkResult: outcome of feeding bytes to theDecoderUpgradeTracker: tracks HTTP to WebSocket protocol upgrade
§Examples
§Incremental decoding with sink()
ⓘ
use pdk_websockets_lib::{Decoder, Encoder, Frame, FrameType, SinkResult};
let mut decoder = Decoder::default();
match decoder.sink(raw_bytes) {
SinkResult::MidFrame => { /* pause and wait for more bytes */ }
SinkResult::Complete(mut frames) => {
// inspect frames
if let Some(frame) = frames.first() {
if let FrameType::Text = frame.frame_type() {
let text = String::from_utf8_lossy(frame.data());
}
}
// modify frames, then re-encode
frames.push(Frame::ping());
let bytes = Encoder::default().encode_server(frames);
}
}§Stateless parsing with parse()
ⓘ
use pdk_websockets_lib::{Decoder, Encoder};
// In your event loop, when new bytes arrive:
fn on_websocket_data(bytes: Vec<u8>, remainder: &mut Vec<u8>) -> Vec<Vec<u8>> {
// Concatenate previous remainder + new bytes
let full_buffer = [&remainder[..], &bytes[..]].concat();
// Parse into frames
let (frames, new_remainder) = Decoder::parse(full_buffer);
// Store remainder for next iteration
*remainder = new_remainder;
// Re-encode frames (e.g., to forward to upstream)
let encoder = Encoder::default();
frames.into_iter()
.map(|f| encoder.encode_server(vec![f]))
.collect()
}Structs§
- Decoder
- Incrementally decodes raw bytes into
Frames. - Encoder
- Encodes a collection of
Frames back into raw bytes suitable for writing to a WebSocket connection. - Frame
- A single WebSocket frame.
- Upgrade
Tracker - Tracks HTTP to WebSocket protocol upgrade.
Enums§
- Frame
Type - The kind of a WebSocket frame, derived from its opcode.
- Sink
Result - The result of feeding bytes to
Decoder::sink.