Skip to content

Commit

Permalink
test
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuay03 committed Sep 14, 2024
1 parent ac07a56 commit 7270be0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
47 changes: 38 additions & 9 deletions lib/puma_cfs_rails/middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
module PumaCFSRails
class Middleware
EMPTY_KEY = ""
PATH_INFO = "PATH_INFO"
REQUEST_METHOD = "REQUEST_METHOD"
MIN_VRUNTIME = "MIN_VRUNTIME"
SERVER_TIMING = ActionDispatch::Constants::SERVER_TIMING
PUMA_CFS_RAILS = "PUMA-CFS-RAILS"

def initialize(app)
@app = app
Expand All @@ -13,16 +18,31 @@ def initialize(app)

def call(env)
path_params = begin
Rails.application.routes.recognize_path(env["PATH_INFO"], method: env["REQUEST_METHOD"])
Rails.application.routes.recognize_path(env[PATH_INFO], method: env[REQUEST_METHOD])
rescue ActionController::RoutingError
{}
end
key = key_from(path_params)

env["MIN_VRUNTIME"] = @min_vruntimes[key] ||= 0
duration, response = with_time_diff { @app.call(env) }
unless key == EMPTY_KEY || (@min_vruntimes[key] > 0 && @min_vruntimes[key] < duration)
@min_vruntimes[key] = duration
env[MIN_VRUNTIME] = @min_vruntimes[key] ||= 0

response = @app.call(env)
headers = response[1]

if key == EMPTY_KEY
headers[PUMA_CFS_RAILS] = "Could not determine controller and action from path"
else
vruntime = cpu_time_sum(parsed_server_timing(headers))
pp vruntime
if vruntime > 0
headers[PUMA_CFS_RAILS] = "Success"
else
headers[PUMA_CFS_RAILS] = "No server timing data, check if `config.server_timings = true`"
end

if vruntime < @min_vruntimes[key]
@min_vruntimes[key] = vruntime
end
end

response
Expand All @@ -38,10 +58,19 @@ def key_from(path_params)
end
end

def with_time_diff
before = Time.now
result = yield
[Time.now - before, result]
def parsed_server_timing(headers)
(headers[SERVER_TIMING] || "").split(', ').to_h do |entry|
key, value = entry.split(';dur=')
[key, value.to_f]
end
end

def cpu_time_sum(timings)
(
(timings["start_processing.action_controller"] || 0) +
(timings["render_template.action_view"] || 0) +
(timings["process_action.action_controller"] || 0)
) - (timings["sql.active_record"] || 0)
end
end
end
4 changes: 2 additions & 2 deletions lib/puma_cfs_rails/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
require_relative 'middleware'

module PumaCFSRails
class Railtie < Rails::Railtie
class Railtie < ::Rails::Railtie
initializer "puma_cfs_rails.use_middleware" do |app|
app.middleware.use PumaCFSRails::Middleware
app.middleware.insert_before ::ActionDispatch::ServerTiming, ::PumaCFSRails::Middleware
end
end
end

0 comments on commit 7270be0

Please sign in to comment.