Teya.SSE (teya v0.4.0)

Copy Markdown View Source

SSE (Server-Sent Events) frame parser for consuming Teya POSLink streaming endpoints.

Parses raw bytes from a streaming HTTP response into event maps. Designed for use with Req's into: :self streaming mode, where chunks arrive as {ref, {:data, binary}} messages.

Usage

defp receive_loop(ref, buffer) do
  receive do
    {^ref, {:data, chunk}} ->
      {events, rest} = Teya.SSE.parse(buffer <> chunk)
      Enum.each(events, &handle_event/1)
      receive_loop(ref, rest)

    {^ref, :done} ->
      :ok
  end
end

Event format

Each parsed event is a map with string keys. Only fields present in the SSE frame are included.

%{
  "event" => "full",             # event type (if present)
  "data"  => "{"status":"NEW"}",  # raw data string (multi-line joined with \n)
  "id"    => "event-id",         # last event ID (if present)
  "retry" => 5000                # reconnect delay in ms (if present)
}

Events without a data: line (e.g. keepalive comment-only frames) are discarded and never appear in the output list.

Summary

Functions

Parses complete SSE events from a binary buffer.

Types

event()

@type event() :: %{required(String.t()) => String.t() | non_neg_integer()}

Functions

parse(buffer)

@spec parse(binary()) :: {[event()], binary()}

Parses complete SSE events from a binary buffer.

Returns {events, remaining} where events is the list of parsed event maps and remaining is any trailing bytes that do not yet form a complete event, to be prepended to the next incoming chunk.

Examples

iex> Teya.SSE.parse("event: full\ndata: {}")
{[], "event: full\ndata: {}"}

iex> Teya.SSE.parse("event: full\ndata: {}\n\n")
{[%{"event" => "full", "data" => "{}"}], ""}