Class: Hooks::App::API

Inherits:
Object
  • Object
show all
Includes:
Auth, Helpers
Defined in:
lib/hooks/app/api.rb

Overview

Factory for creating configured Grape API classes

Class Attribute Summary collapse

Class Method Summary collapse

Methods included from Auth

#validate_auth!

Methods included from Helpers

#enforce_request_limits, #ip_filtering!, #load_handler, #parse_payload, #uuid

Class Attribute Details

.server_start_timeObject (readonly)

Returns the value of attribute server_start_time.



28
29
30
# File 'lib/hooks/app/api.rb', line 28

def server_start_time
  @server_start_time
end

Class Method Details

.create(config:, endpoints:, log:) ⇒ Object

Create a new configured API class



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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/hooks/app/api.rb', line 32

def self.create(config:, endpoints:, log:)
  # :nocov:
  @production = config[:environment].downcase.strip == "production"
  @server_start_time = Time.now.utc

  api_class = Class.new(Grape::API) do
    content_type :json, "application/json"
    content_type :txt, "text/plain"
    content_type :xml, "application/xml"
    content_type :any, "*/*"

    default_format config[:default_format] || :json
  end

  api_class.class_eval do
    helpers Helpers, Auth

    mount Hooks::App::HealthEndpoint => config[:health_path]
    mount Hooks::App::VersionEndpoint => config[:version_path]

    endpoints.each do |endpoint_config|
      full_path = "#{config[:root_path]}#{endpoint_config[:path]}"
      handler_class_name = endpoint_config[:handler]
      http_method = (endpoint_config[:method] || "post").downcase.to_sym

      send(http_method, full_path) do
        request_id = uuid
        start_time = Time.now.utc

        request_context = {
          request_id:,
          path: full_path,
          handler: handler_class_name
        }

        # everything wrapped in the log context has access to the request context and includes it in log messages
        # ex: Hooks::Log.info("message") will include request_id, path, handler, etc
        Core::LogContext.with(request_context) do
          begin
            # Build Rack environment for lifecycle hooks
            rack_env_builder = RackEnvBuilder.new(
              request,
              headers,
              request_context,
              endpoint_config,
              start_time,
              full_path
            )
            rack_env = rack_env_builder.build

            # Call lifecycle hooks: on_request
            Core::PluginLoader.lifecycle_plugins.each do |plugin|
              plugin.on_request(rack_env)
            end

            # IP filtering before processing the request if defined
            # If IP filtering is enabled at either global or endpoint level, run the filtering rules
            # before processing the request
            if config[:ip_filtering] || endpoint_config[:ip_filtering]
              ip_filtering!(headers, endpoint_config, config, request_context, rack_env)
            end

            enforce_request_limits(config, request_context)
            request.body.rewind
            raw_body = request.body.read

            if endpoint_config[:auth]
              validate_auth!(raw_body, headers, endpoint_config, config, request_context)
            end

            payload = parse_payload(raw_body, headers, symbolize: false)
            handler = load_handler(handler_class_name)
            processed_headers = config[:normalize_headers] ? Hooks::Utils::Normalize.headers(headers) : headers

            response = handler.call(
              payload:,
              headers: processed_headers,
              env: rack_env,
              config: endpoint_config
            )

            # Call lifecycle hooks: on_response
            Core::PluginLoader.lifecycle_plugins.each do |plugin|
              plugin.on_response(rack_env, response)
            end

            log.info("successfully processed webhook event with handler: #{handler_class_name}")
            log.debug("processing duration: #{Time.now.utc - start_time}s")
            status 200
            response
          rescue Hooks::Plugins::Handlers::Error => e
            # Handler called error! method - immediately return error response and exit the request
            log.debug("handler #{handler_class_name} called `error!` method")

            status e.status
            case e.body
            when String
              # if error! was called with a string, we assume it's a simple text error
              # example: error!("simple text error", 400) -> should return a plain text response
              content_type "text/plain"
              error_response = e.body
            else
              # Let Grape handle JSON conversion with the default format
              error_response = e.body
            end

            return error_response
          rescue StandardError => e
            err_msg = "Error processing webhook event with handler: #{handler_class_name} - #{e.message} " \
              "- request_id: #{request_id} - path: #{full_path} - method: #{http_method} - " \
              "backtrace: #{e.backtrace.join("\n")}"
            log.error(err_msg)

            # call lifecycle hooks: on_error if the rack_env is available
            # if the rack_env is not available, it means the error occurred before we could build it
            if defined?(rack_env)
              Core::PluginLoader.lifecycle_plugins.each do |plugin|
                plugin.on_error(e, rack_env)
              end
            end

            # construct a standardized error response
            error_response = {
              error: "server_error",
              message: "an unexpected error occurred while processing the request",
              request_id:
            }

            # enrich the error response with details if not in production
            error_response[:backtrace] = e.backtrace.join("\n") unless @production
            error_response[:message] = e.message unless @production
            error_response[:handler] = handler_class_name unless @production

            status determine_error_code(e)
            error_response
          end
        end
      end
    end

    if config[:use_catchall_route]
      route_path = Hooks::App::CatchallEndpoint.mount_path(config)
      route_block = Hooks::App::CatchallEndpoint.route_block(config, log)
      post(route_path, &route_block)
    end
  end

  api_class
  # :nocov:
end