ssevents

Encode and decode Server-Sent Events, the text/event-stream format.

A server builds each Event with new or named, adds id and retry when it needs them, and writes the stream with encode or encode_items. A client reads a whole body with decode, or one chunk at a time with new_decoder, push and finish.

Types

The text of a comment line. Build one with comment.

pub opaque type Comment

The state of a decoder that reads a stream one chunk at a time.

pub opaque type DecodeState

An event with its event, data, id and retry fields.

Build one with new or named, and read it with name_of, data_of, id_of and retry_of.

pub opaque type Event

What a stream holds, in the order it appears.

pub type Item {
  EventItem(Event)
  CommentItem(Comment)
  ReconnectItem(
    id: option.Option(String),
    retry: option.Option(Int),
  )
}

Constructors

  • EventItem(Event)
  • CommentItem(Comment)
  • ReconnectItem(
      id: option.Option(String),
      retry: option.Option(Int),
    )

    The id and retry of a block that has no data line. A browser does not dispatch such a block as an event, but it keeps the id to send in Last-Event-ID and waits retry milliseconds before it reconnects. id: Some("") clears the last event id.

Bounds on what the decoder accepts, so a peer cannot make it buffer without limit. The values are not checked, and a value below 1 rejects what it bounds: a max_line_bytes of 0 allows only blank lines and a negative one not even those, a max_event_bytes or max_data_lines of 0 rejects every field or data line, and a negative max_retry_value ignores every retry. Start from default_limits and change the fields you need:

ssevents.Limits(..ssevents.default_limits, max_event_bytes: 200_000)
pub type Limits {
  Limits(
    max_line_bytes: Int,
    max_event_bytes: Int,
    max_data_lines: Int,
    max_retry_value: Int,
  )
}

Constructors

  • Limits(
      max_line_bytes: Int,
      max_event_bytes: Int,
      max_data_lines: Int,
      max_retry_value: Int,
    )

    Arguments

    max_line_bytes

    The longest line in bytes, not counting its line ending.

    max_event_bytes

    The most bytes the field lines of one event can add up to. Comment lines do not count.

    max_data_lines

    The most data lines one event can have.

    max_retry_value

    The largest retry value in milliseconds. A larger value is ignored and the event is still returned.

What a client remembers between connections: the last id it saw, which it sends in the Last-Event-ID header, and the last retry.

Start from ReconnectState(last_event_id: None, retry: None) and give each item to update_reconnect.

pub type ReconnectState {
  ReconnectState(
    last_event_id: option.Option(String),
    retry: option.Option(Int),
  )
}

Constructors

Why a stream could not be decoded.

pub type SseError {
  LineTooLong(limit: Int)
  EventTooLarge(limit: Int)
  TooManyDataLines(limit: Int)
}

Constructors

  • LineTooLong(limit: Int)

    A line is longer than max_line_bytes.

  • EventTooLarge(limit: Int)

    An event is larger than max_event_bytes.

  • TooManyDataLines(limit: Int)

    An event has more data lines than max_data_lines.

Values

pub fn comment(text: String) -> Result(Item, Nil)

Creates a comment line. Clients ignore comments, so a server can send one to keep an idle connection open.

Returns an error when text holds a CR or LF, because a comment is a single line.

Examples

let assert Ok(ping) = ssevents.comment("ping")
ssevents.encode_items([ping])
// -> ": ping\n"
pub fn comment_text(comment: Comment) -> String

Returns the text of a comment.

pub fn content_type() -> String

Returns "text/event-stream", the media type of an event stream response.

pub fn data_of(event: Event) -> String

Returns the data field. Lines are separated by LF.

pub fn decode(
  input: BitArray,
  limits: Limits,
) -> Result(List(Item), SseError)

Decodes a whole stream into its items, as the WHATWG HTML standard reads an event stream.

Lines can end with LF, CRLF or CR, a byte order mark at the start is skipped, and bytes that are not UTF-8 become U+FFFD. Unknown fields are ignored, as are an id that contains NUL and a retry that is not all digits or is above max_retry_value. A block with data gives an EventItem, and a block without it gives a ReconnectItem if it has an id or a retry. An event at the end of the input without its closing blank line is dropped, as a browser drops it, but its retry is kept. The first error ends decoding.

Examples

ssevents.decode(<<"data: 1\n\nretry: 50\n\n":utf8>>, ssevents.default_limits)
// -> Ok([
//   ssevents.EventItem(ssevents.new("1")),
//   ssevents.ReconnectItem(id: None, retry: Some(50)),
// ])
let limits = ssevents.Limits(..ssevents.default_limits, max_line_bytes: 4)
ssevents.decode(<<"data: hello\n\n":utf8>>, limits)
// -> Error(ssevents.LineTooLong(limit: 4))
pub const default_limits: Limits

8192 bytes per line, 65_536 bytes per event, 1024 data lines per event, and a retry of at most 86_400_000 milliseconds (24 hours).

pub fn encode(event: Event) -> String

Encodes one event, ending with the blank line that makes a client dispatch it. Lines end with LF.

A data line longer than 8000 bytes is written as several data lines of at most 2000 code points each, so that decode with default_limits can read it. A client joins those lines with LF, so the data it receives has an LF at each split. Data that has to arrive unchanged needs lines of at most 8000 bytes. The event and id lines are never split, so a name or id longer than about 8000 bytes gives a stream that decode with default_limits rejects.

Examples

ssevents.new("a\nb") |> ssevents.retry(500) |> ssevents.encode
// -> "retry: 500\ndata: a\ndata: b\n\n"
pub fn encode_items(items: List(Item)) -> String

Encodes the items in order into one string.

A ReconnectItem is written as a block without data. Its id is left out, without an error, if id would refuse it, and its retry if retry would remove it, so a hand-built item cannot add lines to the stream. An item with neither is written as nothing. Check a value from a user with id first if losing it matters.

Examples

ssevents.encode_items([
  ssevents.EventItem(ssevents.new("x")),
  ssevents.ReconnectItem(id: None, retry: Some(5000)),
])
// -> "data: x\n\nretry: 5000\n\n"
pub fn error_to_string(error: SseError) -> String

Describes an error in English, for logs.

pub fn finish(state: DecodeState) -> List(Item)

Ends the stream. The event that has not seen its closing blank line is dropped, as is a last line without a line ending, and a retry already read for that event is returned as a ReconnectItem.

pub fn id(event: Event, id: String) -> Result(Event, Nil)

Sets the id field. A client sends the last id it saw back in the Last-Event-ID header when it reconnects.

Returns an error when id holds a CR or LF, which would end the line on the wire, or a NUL, which makes a browser ignore the field. An empty id tells the client to forget the last one.

Examples

ssevents.new("x") |> ssevents.id("7") |> result.map(ssevents.id_of)
// -> Ok(Some("7"))
pub fn id_of(event: Event) -> option.Option(String)

Returns the id field.

pub fn name_of(event: Event) -> option.Option(String)

Returns the event field, or None for an event made with new.

pub fn named(name: String, data: String) -> Result(Event, Nil)

Creates an event whose event field is name, which a browser EventSource hands to the listeners for that name.

Returns an error when name holds a CR or LF, which would end the line on the wire. data is cleaned as in new, and an empty name gives the same event as new.

Examples

ssevents.named("job.done", "42") |> result.map(ssevents.name_of)
// -> Ok(Some("job.done"))
ssevents.named("job\ndata: forged", "42")
// -> Error(Nil)
pub fn new(data: String) -> Event

Creates an event without a name, which a browser EventSource hands to its message listeners.

CR and CRLF in data become LF, so data_of returns what a client will see.

Examples

ssevents.new("a\r\nb") |> ssevents.data_of
// -> "a\nb"
pub fn new_decoder(limits: Limits) -> DecodeState

Creates a decoder for a stream that arrives in chunks, such as the body of an HTTP response. Give each chunk to push and call finish when the stream ends.

pub fn push(
  state: DecodeState,
  chunk: BitArray,
) -> Result(#(DecodeState, List(Item)), SseError)

Reads the next chunk and returns the items it completes.

A chunk can end anywhere, even inside a character. The bytes of an unfinished line wait for the next chunk. Returns the same items and errors as decode would for the whole stream, however it is split.

Examples

let decoder = ssevents.new_decoder(ssevents.default_limits)
let assert Ok(#(decoder, [])) = ssevents.push(decoder, <<"data: he":utf8>>)
ssevents.push(decoder, <<"llo\n\n":utf8>>)
// -> Ok(#(_, [ssevents.EventItem(ssevents.new("hello"))]))
pub fn retry(event: Event, milliseconds: Int) -> Event

Sets the retry field, the number of milliseconds a client waits before it reconnects.

A value below 0 or above 86_400_000 (24 hours) removes the field instead: the format has no negative numbers, and decode with default_limits ignores larger values.

Examples

ssevents.new("x") |> ssevents.retry(5000) |> ssevents.retry_of
// -> Some(5000)
ssevents.new("x") |> ssevents.retry(-1) |> ssevents.retry_of
// -> None
pub fn retry_of(event: Event) -> option.Option(Int)

Returns the retry field in milliseconds.

pub fn update_reconnect(
  state: ReconnectState,
  item: Item,
) -> ReconnectState

Keeps the id and retry of an EventItem or a ReconnectItem, if it has them. An empty id sets last_event_id back to None, as a browser then sends no Last-Event-ID. Comments leave the state as it is. A ReconnectItem field that id or retry would refuse is ignored, so the state never holds an id that cannot be sent as a header.

✨ Search Document