# frozen_string_literal: true module Gitlab module Middleware class Speedscope def initialize(app) @app = app end def call(env) request = ActionDispatch::Request.new(env) return @app.call(env) unless rendering_flamegraph?(request) body = nil ::Gitlab::SafeRequestStore[:capturing_flamegraph] = true require 'stackprof' begin flamegraph = ::StackProf.run( mode: :wall, raw: true, aggregate: false, interval: ::Gitlab::StackProf::DEFAULT_INTERVAL_US ) do _, _, body = @app.call(env) end ensure body.close if body.respond_to?(:close) end render_flamegraph(flamegraph, request) end private def rendering_flamegraph?(request) request.params['performance_bar'] == 'flamegraph' && ::Gitlab::PerformanceBar.allowed_for_user?(request.env['warden']&.user) end def render_flamegraph(graph, request) headers = { 'Content-Type' => 'text/html' } path = request.env['PATH_INFO'].sub('//', '/') speedscope_path = ::Gitlab::Utils.append_path(::Gitlab.config.gitlab.relative_url_root, '/-/speedscope/index.html') html = <<~HTML
HTML [200, headers, [html]] end end end end