File: rack.rb

package info (click to toggle)
ruby-gitlab-labkit 0.36.1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 444 kB
  • sloc: ruby: 1,705; makefile: 6
file content (49 lines) | stat: -rw-r--r-- 1,173 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# frozen_string_literal: true

require "action_dispatch"
require "json"

module Labkit
  module Middleware
    HEADER = "X-Gitlab-Meta"

    # This is a rack middleware to be inserted in GitLab-rails
    # It makes sure that there's always a root context containing the correlation
    # id.
    # Since this context always get's cleaned up by this middleware, we can be
    # sure that any nested contexts will also be cleaned up.
    class Rack
      def initialize(app)
        @app = app
      end

      def call(env)
        Labkit::Context.with_context(Labkit::Context::CORRELATION_ID_KEY => correlation_id(env)) do |context|
          status, headers, response = @app.call(env)

          headers[HEADER] = context_to_json(context)

          [status, headers, response]
        end
      end

      private

      def correlation_id(env)
        request(env).request_id
      end

      def request(env)
        ActionDispatch::Request.new(env)
      end

      def context_to_json(context)
        context
          .to_h
          .transform_keys { |k| k.delete_prefix("meta.") }
          .merge("version" => "1")
          .to_json
      end
    end
  end
end