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.



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

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.



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

def params
  @params
end

Instance Method Details

#add_cors_headers(headers, env) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/kirei/routing/base.rb', line 277

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



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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/kirei/routing/base.rb', line 25

def call(env)
  statsd_timing_tags = T.let({}, T::Hash[String, T.untyped])
  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 ?
  #

  lookup_verb = http_verb == Verb::HEAD ? Verb::GET : http_verb
  result = router.resolve(lookup_verb, req_path)
  return NOT_FOUND if result.nil?

  route, path_params = result

  router.current_env = env # expose the env to the controller

  params = case http_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
             #       built-in support for JSON & XML
             body = env.fetch("rack.input")
             if body.nil? || !body.respond_to?(:read) || (body.respond_to?(:empty?) && body.empty?)
               {}
             else
               body = T.cast(body, 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])
             end
           when Verb::HEAD, Verb::DELETE, Verb::OPTIONS
             {}
           else
             T.absurd(http_verb)
  end

  params.merge!(path_params)

  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
  statsd_timing_tags["route"] = route.action

  status, headers, response_body = case http_verb
                                   when Verb::HEAD, Verb::OPTIONS
                                     [200, {}, []]
                                   when Verb::GET, Verb::POST, Verb::PUT, Verb::PATCH, Verb::DELETE
                                     T.cast(
                                       controller.new(params: params).public_send(route.action),
                                       RackResponseType,
                                     )
                                   else
                                     T.absurd(http_verb)
  end

  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,
  ]
rescue StandardError => e
  status = 500

  Kirei::Logging::Logger.call(
    level: Kirei::Logging::Level::ERROR,
    label: "Unhandled Exception",
    meta: {
      "error.class" => e.class.name,
      "error.message" => e.message,
      "error.backtrace" => e.backtrace&.first(10)&.join("\n"),
    },
  )

  detail = if Kirei::App.environment == "development"
    "#{e.class}: #{e.message}\n#{e.backtrace&.first(10)&.join("\n")}"
  else
    "An unexpected error occurred"
  end

  error = Errors::JsonApiError.new(code: "internal_server_error", detail: detail)
  body = Oj.dump({ "errors" => [error.serialize] }, Kirei::OJ_OPTIONS)
  response_body = [body]

  [status, { "Content-Type" => "application/json; charset=utf-8" }, response_body]
ensure
  stop = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
  if start && statsd_timing_tags # early return for 404
    latency_in_ms = stop - start
    Logging::Metric.inject_defaults(statsd_timing_tags)
    App.config.metrics_backend.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



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/kirei/routing/base.rb', line 260

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



180
181
182
183
184
185
186
# File 'lib/kirei/routing/base.rb', line 180

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

#render_error(errors, status: 422, headers: {}) ⇒ Object



234
235
236
# File 'lib/kirei/routing/base.rb', line 234

def render_error(errors, status: 422, headers: {})
  render_json({ "errors" => errors.map(&:serialize) }, status: status, headers: headers)
end

#render_json(data, status: 200, headers: {}) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/kirei/routing/base.rb', line 203

def render_json(data, status: 200, headers: {})
  body = case data
         when String
           data
         when Hash, Array
           Oj.dump(data, Kirei::OJ_OPTIONS)
         else
           unless data.respond_to?(:serialize)
             raise ArgumentError,
                   "render_json expects a String, Hash, Array, or an object responding to #serialize, " \
                   "got #{data.class}"
           end

           result = data.serialize
           result.is_a?(String) ? result : Oj.dump(result, Kirei::OJ_OPTIONS)
  end

  render(body, status: status, headers: headers)
end

#render_result(result, status_success: 200, status_failure: 400, headers: {}) ⇒ Object



251
252
253
254
255
256
257
# File 'lib/kirei/routing/base.rb', line 251

def render_result(result, status_success: 200, status_failure: 400, headers: {})
  if result.success?
    render_json(result.result, status: status_success, headers: headers)
  else
    render_error(result.errors, status: status_failure, headers: headers)
  end
end