1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_dispatch/middleware/server_timing.rb
Sebastian Sogamoso 0547b1646d
Add Server Timing middleware (#36289)
* Add Server Timing middleware

What is server timing?
It's a specification that defines how the server can communicate the
user-agent performance metrics about the request it is responding to.

Here's the official specification:
https://www.w3.org/TR/server-timing/#dfn-server-timing-header-field

How does it work?
This introduces a new `ServerTiming` middleware only on `development` by
default, this is done using the `config.server_timing` setting.

It works by subscribing to all `ActiveSupport::Notifications` and adding
their duration to the `Server-Timing` header.

Why is this useful?
It makes looking at performance metrics in development much easier,
especially when using Chrome dev tools which includes the metrics in the
Network Inspector. Here's an example:

![](https://d3vv6lp55qjaqc.cloudfront.net/items/371h2y3B3a0U470j040u/Image%202019-05-15%20at%205.40.37%20PM.png?)

Paired on this with @guilleiguaran
2021-09-19 21:27:07 -07:00

33 lines
809 B
Ruby

# frozen_string_literal: true
require "active_support/notifications"
module ActionDispatch
class ServerTiming
SERVER_TIMING_HEADER = "Server-Timing"
def initialize(app)
@app = app
end
def call(env)
events = []
subscriber = ActiveSupport::Notifications.subscribe(/.*/) do |*args|
events << ActiveSupport::Notifications::Event.new(*args)
end
status, headers, body = begin
@app.call(env)
ensure
ActiveSupport::Notifications.unsubscribe(subscriber)
end
header_info = events.group_by(&:name).map do |event_name, events_collection|
"#{event_name};dur=#{events_collection.sum(&:duration)}"
end
headers[SERVER_TIMING_HEADER] = header_info.join(", ")
[ status, headers, body ]
end
end
end