Expand description
Server-Sent Event Streams Codec
Implements a Codec for encoding and decoding Server-Sent Events streams.
Advantages:
- Minimizes allocations by using the buffer provided by
FramedWriteandFramedReadwhile parsing lines - Easy to use with the rest of the tokio ecosystem
- Can be used with any type that implements
AsyncReadorAsyncWrite - Errors implement
miette::Diagnosticfor better error and diagnostic messages
§Quick Links
SseDecoder- turns a bytes into FramesSseEncoder- turns Frames into bytesFrame- A parsed frame from an SSE stream containing either an event, comment or retry valueEvent- SSE Event containing the name, data and optional id
§Examples
use futures::StreamExt;
use tokio_util::codec::{FramedRead, Decoder};
use tokio_sse_codec::{SseDecoder, Frame, Event, SseDecodeError};
// you can use any stream or type that implements `AsyncRead`
let data = "id: 1\nevent: example\ndata: hello, world\n\n";
let mut reader = FramedRead::new(data.as_bytes(), SseDecoder::<String>::new());
while let Some(Ok(frame)) = reader.next().await {
match frame {
Frame::Event(event) => println!("event: id={:?}, name={}, data={}", event.id, event.name, event.data),
Frame::Comment(comment) => println!("comment: {}", comment),
Frame::Retry(duration) => println!("retry: {:#?}", duration),
}
}§Setting a buffer size limit
By default, the decoder will not limit the size of the buffer used to store the data of an event. It’s recommended to set one when dealing with untrusted input, otherwise a malicious server could send a very large event and consume all available memory.
The buffer should be able to hold a single event and it’s data.
use tokio_sse_codec::SseDecoder;
let decoder = SseDecoder::<String>::with_max_size(1024);Structs§
- Bytes
Str - Represents a str reference backed by
bytes::Bytes - Decode
Utf8 Error - Error indicating that the codec failed to decode bytes to valid utf-8.
- Event
- Represents an SSE event.
- Exceeded
Size Limit Error - Error indicating that the incoming data exceeded the set buffer size limit.
- SseDecoder
- Decodes bytes from an SSE Stream into
Frame<T> - SseEncoder
- Encodes SSE
Frames into bytes
Enums§
- Frame
- Represents a parsed frame from an SSE stream. See Interpreting an Event Stream
- SseDecode
Error - Returned by
SSEDecoder::decodeandSSEDecoder::decode_eoffor unrecoverable errors - SseEncode
Error - Error returned by
SseEncoder::encode
Traits§
- TryFrom
Bytes Frame - Convert
Frame<Bytes>intoFrame<T> - TryInto
Frame - Automatically implemented for
TryFromBytesFrame<T>You should not implement this trait yourself!
Type Aliases§
- Decoder
Parts - Tuple representing the internal buffers of the decoder Most users should not use this directly unless you’re re-using the buffers after consuming the decoder.