Skip to content

Add a built-in :sse (server-sent events) format - #3113

Open
ericproulx wants to merge 1 commit into
masterfrom
feature/sse-formatter
Open

ericproulx wants to merge 1 commit into
masterfrom
feature/sse-formatter

Conversation

@ericproulx

Copy link
Copy Markdown
Contributor

Adds :sse, a built-in format for server-sent events: the text/event-stream a browser reads with EventSource, and the format most APIs use to stream output as it is produced, such as LLM tokens. It builds on the Enumerator streaming that :jsonl added in #3029.

class Chat < Grape::API
  content_type :sse, 'text/event-stream'
  format :sse

  get :completions do
    header 'cache-control', 'no-cache'
    Enumerator.new do |events|
      llm.stream(params[:prompt]) { |token| events << { text: token } } # data: {"text":"Hel"}
      events << Grape::ServerSentEvent.new(event: 'done', data: '')       # event: done
    end
  end
end

Today an endpoint can stream with stream, but it has to write the wire format itself. That includes details that are easy to get wrong:

  • one data: line per line of data;
  • a line break in an id or event, which forges a field or a whole event;
  • Last-Event-ID on reconnect.

What it does

Grape::Formatter::Sse follows :jsonl:

  • An Array renders one event per element; any other object renders one event.
  • An element's data is a String as it is, or anything else as :json renders it. A Grape::PrecompiledJson is served as its JSON.
  • Data that spans lines (\n, \r\n or \r) is sent as one data: line per line.
  • A String body is served as it is, taken to be an event stream already.
  • An Enumerator is streamed: each event is rendered and sent as the enumerator yields it.

Grape::ServerSentEvent is a Data for an event that needs more than its data: event, id, retry and comment.

  • It raises ArgumentError on an event or id holding a line break (or, for id, NUL), and on a retry that is not a non-negative Integer.
  • An event without data dispatches nothing on the client, which is what a keepalive comment or a retry-only event wants. data: '' gives an empty event.

Grape::ErrorFormatter::Sse renders an error, such as a validation failure, error! or an auth refusal, as one event: error whose data is the JSON error. The error body is then an event stream like the response it replaces.

:sse is not a default content type, like :jsonl and :md, so only an API that declares it is affected. UPGRADING covers an API that had already declared content_type :sse itself.

Checked on real servers

A route yielding an event every 0.5 s, read with curl -N. The events arrive 0.5 s apart on both servers, not all at the end:

  • Puma 8.0.2: chunked;
  • Falcon 0.57.0.

Open questions

  1. Cache-Control. stream sets cache-control: no-cache; a stream a formatter hands back doesn't. The README tells SSE routes to set it. The alternative is to have Middleware::Formatter set it on every stream a formatter hands back, unless the endpoint set one. That would change :jsonl responses too, so I've left it out of this PR.
  2. Heartbeats. A plain Enumerator blocks until the app yields its next event, so Grape can't send keepalives on its own. The README says to yield a comment: event every 15 seconds or so. A timer would need a fiber- or thread-aware body, a bigger design.
  3. No last_event_id helper. headers['last-event-id'] already reads it, and the README shows that.
  4. Names. The format is :sse and the value class is Grape::ServerSentEvent. :event_stream would match the media type, but sse is what people search for.

Tests

  • spec/grape/formatter/sse_spec.rb:
    • objects, Arrays and String elements;
    • PrecompiledJson;
    • multi-line data with each kind of line break;
    • every field, a comment alone, and empty data;
    • lazy streaming;
    • negotiation by Accept: text/event-stream.
  • spec/grape/error_formatter/sse_spec.rb: a message, and a Hash with a newline.
  • spec/grape/server_sent_event_spec.rb: the validations.

bundle exec rake: 400 files, no offenses; 3410 examples, 0 failures.

🤖 Generated with Claude Code

`format :sse` serves server-sent events, the text/event-stream a browser
reads with EventSource. An Array renders one event per element and any
other object one event. An element's data is a String as it is, or
anything else as the JSON formatter renders it, and data that spans lines
is sent as one `data:` line per line. A String body is served as it is.
An Enumerator body is streamed, each event sent as the enumerator yields
it, the way :jsonl streams its lines.

Grape::ServerSentEvent gives an event a type, an id, a reconnection delay
or a comment. It rejects an event or id holding a line break, which would
start a field or an event of its own.

An error renders as one `error` event whose data is the JSON error.

Like :jsonl, :sse is not a default content type: an API declares it with
`content_type :sse, 'text/event-stream'`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ericproulx
ericproulx force-pushed the feature/sse-formatter branch from 6a06bb4 to b3eef14 Compare November 27, 2026 17:55
@ericproulx
ericproulx marked this pull request as ready for review November 27, 2026 17:59
@dblock

dblock commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

This is more than a media type. Specifically, is it correct that to actually get proper SSE support we will need to figure out how to do heartbeats? In that case maybe the implementation belongs in a new grape-sse gem to avoid bringing in some async processing kitchen sink?

@ericproulx

Copy link
Copy Markdown
Contributor Author

Not for SSE itself. The protocol is the text/event-stream format plus reconnection (retry, and an event's id coming back as Last-Event-ID), and that's what this adds. The spec suggests a comment line every 15 seconds or so only to get past proxies that close idle connections. A token stream from an LLM never sits idle that long.

When a stream does sit idle, as with notifications, the app knows it's waiting, so it can send the heartbeat itself. Nothing new is needed in Grape:

Enumerator.new do |events|
  loop do
    event = feed.pop(timeout: 15)
    next events << Grape::ServerSentEvent.new(comment: 'keepalive') if event.nil?

    events << event
  end
ensure
  unsubscribe(feed)
end

The heartbeat is also how the server finds out the client has gone: the write fails, and the ensure runs.

The async kitchen sink would only come in if Grape sent heartbeats on its own while the app's enumerator blocks. That takes a thread per stream or a fiber scheduler, and those differ between Puma and Falcon. Agreed, that doesn't belong in Grape. If someone needs it, it fits in a grape-sse gem on top of this format.

So I'd keep this PR to the format, like :jsonl, with no new dependency. The README would show the pattern above in place of the line telling people to yield a comment every 15 seconds. WDYT?

@dblock

dblock commented Dec 1, 2026

Copy link
Copy Markdown
Member

I don't mind the formatter, but do we have precedent for ServerSentEvent?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants