mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
0547b1646d
* 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
70 lines
1.8 KiB
Ruby
70 lines
1.8 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require "abstract_unit"
|
|
|
|
class ServerTimingTest < ActionDispatch::IntegrationTest
|
|
class TestController < ActionController::Base
|
|
def index
|
|
head :ok
|
|
end
|
|
|
|
def show
|
|
ActiveSupport::Notifications.instrument("custom.event") do
|
|
true
|
|
end
|
|
head :ok
|
|
end
|
|
|
|
def create
|
|
ActiveSupport::Notifications.instrument("custom.event") do
|
|
raise
|
|
end
|
|
end
|
|
end
|
|
|
|
test "server timing header is included in the response" do
|
|
with_test_route_set do
|
|
get "/"
|
|
assert_match(/\w+/, @response.headers["Server-Timing"])
|
|
end
|
|
end
|
|
|
|
test "includes default action controller events duration" do
|
|
with_test_route_set do
|
|
get "/"
|
|
assert_match(/start_processing.action_controller;dur=\w+/, @response.headers["Server-Timing"])
|
|
assert_match(/process_action.action_controller;dur=\w+/, @response.headers["Server-Timing"])
|
|
end
|
|
end
|
|
|
|
test "includes custom active support events duration" do
|
|
with_test_route_set do
|
|
get "/id"
|
|
assert_match(/custom.event;dur=\w+/, @response.headers["Server-Timing"])
|
|
end
|
|
end
|
|
|
|
test "ensures it doesn't leak subscriptions when the app crashes" do
|
|
with_test_route_set do
|
|
post "/"
|
|
assert_not ActiveSupport::Notifications.notifier.listening?("custom.event")
|
|
end
|
|
end
|
|
|
|
private
|
|
def with_test_route_set
|
|
with_routing do |set|
|
|
set.draw do
|
|
get "/", to: ::ServerTimingTest::TestController.action(:index)
|
|
get "/id", to: ::ServerTimingTest::TestController.action(:show)
|
|
post "/", to: ::ServerTimingTest::TestController.action(:create)
|
|
end
|
|
|
|
@app = self.class.build_app(set) do |middleware|
|
|
middleware.use ActionDispatch::ServerTiming
|
|
end
|
|
|
|
yield
|
|
end
|
|
end
|
|
end
|