In a Rails controller, how do you push a CI build's log lines to the browser as they arrive with ActionController::Live and Live::SSE?
answer
- include ActionController::Live
- headers before the first write
- response.stream.write commits
- SSE.new(stream, event:, id:, retry:)
- close in ensure
basics
~10 sInclude ActionController::Live, set Content-Type to text/event-stream, wrap response.stream in ActionController::Live::SSE and write each log line as an event; the first write commits the headers, and the stream must be closed in an ensure.
solid answer
~40 sI put the action in its own controller with `include ActionController::Live`, because that makes every action there run on a separate thread whose writes to `response.stream` reach the client immediately. Before writing anything I set `response.headers["Content-Type"] = "text/event-stream"`: the first write commits status and headers. Then `sse = ActionController::Live::SSE.new(response.stream, event: "log", retry: 3000)` and, in a loop, `sse.write({ text: line.body }, id: line.number)`: non-String objects are JSON-encoded and `id:` lets a reconnecting browser resume through `Last-Event-ID`. When the build finishes I write a final event and, in `ensure`, close the stream, otherwise the socket can stay open. For a file built row by row, `send_stream(filename:)` does the headers and the close for me.
code
ruby · 27 linesclass BuildLogStreamsController < ApplicationController
include ActionController::Live
before_action :set_build # a 404 here happens before anything commits
def show
last = request.headers["Last-Event-ID"].to_i
response.headers["Content-Type"] = "text/event-stream"
sse = ActionController::Live::SSE.new(response.stream, event: "log", retry: 3000)
loop do
@build.log_lines.where("number > ?", last).order(:number).each do |line|
sse.write({ text: line.body }, id: line.number)
last = line.number
end
break if @build.reload.finished?
sleep 1
end
sse.write({ status: @build.status }, event: "finished")
ensure
response.stream.close
end
private
def set_build
@build = Build.find(params[:build_id])
end
endgo deeper
Recall the pieces: include ActionController::Live, write to response.stream, set the event-stream content type first, and always close the stream.
Explain commit on first write, what Live::SSE formats (event, id, retry, JSON data lines), and when send_stream beats send_data.
Point out that Live changes every action in the controller, so streams get their own controller, and that ids plus Last-Event-ID make reconnects resume instead of replaying.
Decide when a held-open HTTP stream is the right transport for live logs compared with WebSocket broadcasts or polling, given server threads and proxies.
## Turning a controller into a streaming one A normal Rails action builds its whole response, then returns it. **`ActionController::Live`** changes that: `include ActionController::Live` in a controller and **every action in that controller** runs on a separate thread, while the request thread waits only until the response is **committed** (the first write or a close) and then hands status and headers to the web server. From then on, whatever the action writes to **`response.stream`** goes to the client as it is written. That is what a CI dashboard needs to show a build's log lines while the build runs. ## Writing to the stream - `response.stream.write(string)` queues bytes for the client; `response.stream.writeln(string)` adds a trailing newline. - The **first write commits the response**. Status and headers go to the server at that moment, so set `Content-Type` and any other header **before** it. A header set later never reaches the browser, and if no content type was set the response was committed as `text/html`. - On the first write Rails sets `Cache-Control: no-cache` unless you set one, and removes `Content-Length`, since the length is unknown. - **`response.stream.close`** ends the response. The Live documentation is blunt: if you never close, the socket may be left open forever. Put it in an `ensure`. ## Live::SSE: the event-stream formatter For a browser `EventSource`, the body must be `text/event-stream` with each event in `field: value` lines. **`ActionController::Live::SSE`** wraps the stream and does the formatting: | option | effect | |---|---| | `event:` | the event name the browser dispatches | | `id:` | the event id; a reconnecting browser sends it back as `Last-Event-ID` | | `retry:` | reconnection delay in milliseconds | Options passed to `SSE.new(response.stream, ...)` apply to every later write; options passed to `write` override them for that event. `sse.write(object)` JSON-encodes anything that is not a String, writes a String as it is, and turns each newline in the payload into a new `data:` line. `SSE` does **not** set `Content-Type`; the action must. `sse.close` closes the underlying stream. ## A build-log action, step by step 1. Include `ActionController::Live` in a controller dedicated to streams, so ordinary actions do not pay for an extra thread. 2. Load and authorize the build in a `before_action`, so a failure there still gets its proper status (the action's own `ensure` close would commit the response), and read `request.headers["Last-Event-ID"]` to resume after a reconnect. 3. Set `Content-Type: text/event-stream`. 4. Loop: fetch new log lines, write each with `id:` set to its line number, stop when the build has finished, otherwise sleep briefly. 5. Close the stream in `ensure`. ## send_stream for downloads produced as you go `ActionController::Live` also provides **`send_stream(filename:, disposition: "attachment", type: nil)`**. It sets `Content-Type` (from `type:` or the filename's extension) and `Content-Disposition`, yields `response.stream` to the block and closes it afterwards. It is the tool for a CSV of every build in the past year: rows reach the browser as `find_each` produces them instead of piling up in memory as `send_data` would. ## Testing and observing a stream - The stream is plain HTTP, so `curl -N` against the action prints events as they are written, which is the quickest check that nothing in between buffers them. - `send_stream` is instrumented as `send_stream.action_controller`, so a log subscriber can record each export's filename and duration. - Because the action runs on another thread, anything the code reads from thread-local state is a copy taken when the request started. ## Details that surprise people - A request that arrives as **HTTP/1.0** gets an ordinary buffered response; Live only swaps in its streaming response for other protocol versions. - Live changes *every* action in the controller, which is why a separate streaming controller is the usual layout. - The action thread is a different thread from the request thread, which matters for thread-local state and database connections.
- What does Live::SSE write for sse.write({ text: "step 3 ok" }, id: 42) when the SSE object was created with event: "log"?The constructor options merge with the per-write ones, so it writes an `event: log` line, an `id: 42` line and `data: {"text":"step 3 ok"}`, then a blank line ending the event. The Hash is JSON-encoded because it is not a String.
- How does send_stream differ from send_data for a large CSV export?`send_data` needs the whole CSV as one String before anything is sent. `send_stream(filename: "builds.csv")`, available in controllers that include `ActionController::Live`, sets the type and disposition, yields `response.stream` so rows go out as they are produced, and closes the stream when the block returns.
- Including ActionController::Live affects only the actions that write to response.stream.
- Headers can be set at any point, because Rails sends them when the stream closes.
- Live::SSE sets Content-Type text/event-stream for you.
- Live::SSE#write JSON-encodes Strings too, wrapping them in quotes.
- A rescue-free action needs no ensure, since Rails closes the stream after the action.