Class: Kirei::Routing::Base

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/kirei/routing/base.rb

Direct Known Subclasses

App, Controller

Constant Summary collapse

NOT_FOUND =

rubocop:disable Style/MutableConstant

T.let([404, {}, ["Not Found"]], RackResponseType)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params: {}) ⇒ Base

Returns a new instance of Base.



14
15
16
17
# File 'lib/kirei/routing/base.rb', line 14

def initialize(params: {})
  @router = T.let(Router.instance, Router)
  @params = T.let(params, T::Hash[String, T.untyped])
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



20
21
22
# File 'lib/kirei/routing/base.rb', line 20

def params
  @params
end

Instance Method Details

#add_cors_headers(headers, env) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/kirei/routing/base.rb', line 164

def add_cors_headers(headers, env)
  origin = T.cast(env.fetch("HTTP_ORIGIN", nil), T.nilable(String))
  return if origin.nil?

  allowed_origins = Kirei::App.config.allowed_origins
  return unless allowed_origins.include?(origin)

  headers["Access-Control-Allow-Origin"] = origin
  headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
  headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Referer"
  headers["Access-Control-Allow-Credentials"] = "true"
end

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/kirei/routing/base.rb', line 26

def call(env)
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
  status = 500 # we use it in the "ensure" block, so we need to define early (Sorbet doesn't like `status ||= 418`)

  http_verb = Verb.deserialize(env.fetch("REQUEST_METHOD"))
  req_path = T.cast(env.fetch("REQUEST_PATH"), String)
  #
  # TODO: reject requests from unexpected hosts -> allow configuring allowed hosts in a `cors.rb` file
  #   ( offer a scaffold for this file )
  # -> use https://github.com/cyu/rack-cors ?
  #

  route = router.get(http_verb, req_path)
  return NOT_FOUND if route.nil?

  params = case route.verb
           when Verb::GET
             query = T.cast(env.fetch("QUERY_STRING"), String)
             query.split("&").to_h do |p|
               k, v = p.split("=")
               k = T.cast(k, String)
               [k, v]
             end
           when Verb::POST, Verb::PUT, Verb::PATCH
             # TODO: based on content-type, parse the body differently
             #       build-in support for JSON & XML
             body = T.cast(env.fetch("rack.input"), T.any(IO, StringIO))
             res = Oj.load(body.read, Kirei::OJ_OPTIONS)
             body.rewind # TODO: maybe don't rewind if we don't need to?
             T.cast(res, T::Hash[String, T.untyped])
           else
             Logging::Logger.logger.warn("Unsupported HTTP verb: #{http_verb.serialize} send to #{req_path}")
             {}
  end

  req_id = T.cast(env["HTTP_X_REQUEST_ID"], T.nilable(String))
  req_id ||= "req_#{App.environment}_#{SecureRandom.uuid}"
  Thread.current[:request_id] = req_id

  controller = route.controller
  before_hooks = collect_hooks(controller, :before_hooks)
  run_hooks(before_hooks)

  Kirei::Logging::Logger.call(
    level: Kirei::Logging::Level::INFO,
    label: "Request Started",
    meta: {
      "http.method" => route.verb.serialize,
      "http.route" => route.path,
      "http.host" => env.fetch("HTTP_HOST"),
      "http.request_params" => params,
      "http.client_ip" => env.fetch("CF-Connecting-IP", env.fetch("REMOTE_ADDR")),
    },
  )

  statsd_timing_tags = {
    "controller" => controller.name,
    "route" => route.action,
  }
  Logging::Metric.inject_defaults(statsd_timing_tags)

  status, headers, response_body = T.cast(
    controller.new(params: params).public_send(route.action),
    RackResponseType,
  )

  after_hooks = collect_hooks(controller, :after_hooks)
  run_hooks(after_hooks)

  headers["X-Request-Id"] ||= req_id

  default_headers.each do |header_name, default_value|
    headers[header_name] ||= default_value
  end

  add_cors_headers(headers, env)

  [
    status,
    headers,
    response_body,
  ]
ensure
  stop = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
  if start # early return for 404
    latency_in_ms = stop - start
    ::StatsD.measure("request", latency_in_ms, tags: statsd_timing_tags)

    Kirei::Logging::Logger.call(
      level: status >= 500 ? Kirei::Logging::Level::ERROR : Kirei::Logging::Level::INFO,
      label: "Request Finished",
      meta: { "response.body" => response_body, "response.latency_in_ms" => latency_in_ms },
    )
  end

  # reset global variables after the request has been served
  # and after all "after" hooks have run to avoid leaking
  Thread.current[:enduser_id] = nil
  Thread.current[:request_id] = nil
end

#default_headersObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/kirei/routing/base.rb', line 147

def default_headers
  {
    # security relevant headers
    "X-Frame-Options" => "DENY",
    "X-Content-Type-Options" => "nosniff",
    "X-XSS-Protection" => "1; mode=block", # for legacy clients/browsers
    "Strict-Transport-Security" => "max-age=31536000; includeSubDomains", # for HTTPS
    "Cache-Control" => "no-store", # the user should set that if caching is needed
    "Referrer-Policy" => "strict-origin-when-cross-origin",
    "Content-Security-Policy" => "default-src 'none'; frame-ancestors 'none'",

    # other headers
    "Content-Type" => "application/json; charset=utf-8",
  }
end

#render(body, status: 200, headers: {}) ⇒ Object



138
139
140
141
142
143
144
# File 'lib/kirei/routing/base.rb', line 138

def render(body, status: 200, headers: {})
  [
    status,
    headers,
    [body],
  ]
end