Repository navigation
Add a built-in :sse (server-sent events) format - #3113
ericproulx wants to merge 1 commit into
Conversation
`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>
6a06bb4 to
b3eef14
Compare
|
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 |
|
Not for SSE itself. The protocol is the 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)
endThe heartbeat is also how the server finds out the client has gone: the write fails, and the 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 So I'd keep this PR to the format, like |
|
I don't mind the formatter, but do we have precedent for |
Adds
:sse, a built-in format for server-sent events: thetext/event-streama browser reads withEventSource, and the format most APIs use to stream output as it is produced, such as LLM tokens. It builds on the Enumerator streaming that:jsonladded in #3029.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:data:line per line of data;idorevent, which forges a field or a whole event;Last-Event-IDon reconnect.What it does
Grape::Formatter::Ssefollows:jsonl::jsonrenders it. AGrape::PrecompiledJsonis served as its JSON.\n,\r\nor\r) is sent as onedata:line per line.Grape::ServerSentEventis aDatafor an event that needs more than its data:event,id,retryandcomment.ArgumentErroron aneventoridholding a line break (or, forid, NUL), and on aretrythat is not a non-negative Integer.datadispatches nothing on the client, which is what a keepalive comment or aretry-only event wants.data: ''gives an empty event.Grape::ErrorFormatter::Sserenders an error, such as a validation failure,error!or an auth refusal, as oneevent: errorwhose data is the JSON error. The error body is then an event stream like the response it replaces.:sseis not a default content type, like:jsonland:md, so only an API that declares it is affected. UPGRADING covers an API that had already declaredcontent_type :sseitself.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:Open questions
Cache-Control.streamsetscache-control: no-cache; a stream a formatter hands back doesn't. The README tells SSE routes to set it. The alternative is to haveMiddleware::Formatterset it on every stream a formatter hands back, unless the endpoint set one. That would change:jsonlresponses too, so I've left it out of this PR.comment:event every 15 seconds or so. A timer would need a fiber- or thread-aware body, a bigger design.last_event_idhelper.headers['last-event-id']already reads it, and the README shows that.:sseand the value class isGrape::ServerSentEvent.:event_streamwould match the media type, butsseis what people search for.Tests
spec/grape/formatter/sse_spec.rb:PrecompiledJson;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