Module: Datadog::Tracing::Contrib::Grape::Endpoint

Defined in:
lib/datadog/tracing/contrib/grape/endpoint.rb

Overview

Endpoint module includes a list of subscribers to create traces when a Grape endpoint is hit

Constant Summary collapse

KEY_RUN =
'datadog_grape_endpoint_run'
KEY_RENDER =
'datadog_grape_endpoint_render'
CLOUDWISE_JS_ENABLED =

✅ 优化:缓存 ENV 配置为常量,避免每次请求读取操作系统环境变量 rubocop:disable CustomCops/EnvUsageCop

ENV.fetch('CLOUDWISE_JS_CONFIG', 'false') == 'true'

Class Method Summary collapse

Class Method Details

.endpoint_render(name, start, finish, id, payload) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 220

def endpoint_render(name, start, finish, id, payload)
  return unless Thread.current[KEY_RENDER]

  Thread.current[KEY_RENDER] = false

  return unless enabled?

  span = Tracing.active_span
  return unless span

  # catch thrown exceptions
  begin
    # Measure service stats
    Contrib::Analytics.set_measured(span)

    handle_error(span, payload[:exception_object]) if payload[:exception_object]
  ensure
    span.start(start)
    span.finish(finish)
  end
rescue => e
  Datadog.logger.error(e.message)
  Datadog::Core::Telemetry::Logger.report(e)
end

.endpoint_run(name, start, finish, id, payload) ⇒ Object



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
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 128

def endpoint_run(name, start, finish, id, payload)
  return unless Thread.current[KEY_RUN]

  Thread.current[KEY_RUN] = false

  return unless enabled?

  trace = Tracing.active_trace
  span = Tracing.active_span
  return unless trace && span

  begin
    # collect endpoint details
    endpoint = payload.fetch(:endpoint)
    env = payload.fetch(:env)
    api_view = api_view(endpoint.options[:for])
    request_method = endpoint.options.fetch(:method).first
    path = endpoint_expand_path(endpoint)

    trace.resource = span.resource

    # Set analytics sample rate
    Contrib::Analytics.set_sample_rate(span, analytics_sample_rate) if analytics_enabled?

    # Measure service stats
    Contrib::Analytics.set_measured(span)

    handle_error_and_status_code(span, endpoint, payload)

    # override the current span with this notification values
    span.set_tag(Ext::TAG_ROUTE_ENDPOINT, api_view) unless api_view.nil?
    span.set_tag(Ext::TAG_ROUTE_PATH, path)
    span.set_tag(Ext::TAG_ROUTE_METHOD, request_method)

    span.set_tag(Tracing::::Ext::HTTP::TAG_METHOD, request_method)
    span.set_tag(Tracing::::Ext::HTTP::TAG_URL, path)

    # 处理响应头注入
    inject_response_headers(endpoint, env, span, trace)
  ensure
    span.start(start)
    span.finish(finish)
  end
rescue => e
  Datadog.logger.error(e.message)
  Datadog::Core::Telemetry::Logger.report(e)
end

.endpoint_run_filters(name, start, finish, id, payload) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 245

def endpoint_run_filters(name, start, finish, id, payload)
  return unless enabled?

  # safe-guard to prevent submitting empty filters
  zero_length = (finish - start).zero?
  filters = payload[:filters]
  type = payload[:type]
  return if (!filters || filters.empty?) || !type || zero_length

  span = Tracing.trace(
    Ext::SPAN_ENDPOINT_RUN_FILTERS,
    service: service_name,
    type: Tracing::::Ext::HTTP::TYPE_INBOUND,
    start_time: start
  )

  begin
    span.set_tag(Tracing::::Ext::TAG_COMPONENT, Ext::TAG_COMPONENT)
    span.set_tag(Tracing::::Ext::TAG_OPERATION, Ext::TAG_OPERATION_ENDPOINT_RUN_FILTERS)

    # Set analytics sample rate
    Contrib::Analytics.set_sample_rate(span, analytics_sample_rate) if analytics_enabled?

    # Measure service stats
    Contrib::Analytics.set_measured(span)

    # catch thrown exceptions
    handle_error(span, payload[:exception_object]) if payload[:exception_object]

    span.set_tag(Ext::TAG_FILTER_TYPE, type.to_s)
  ensure
    span.start(start)
    span.finish(finish)
  end
rescue => e
  Datadog.logger.error(e.message)
  Datadog::Core::Telemetry::Logger.report(e)
end

.endpoint_start_process(_name, _start, _finish, _id, payload) ⇒ Object



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
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 44

def endpoint_start_process(_name, _start, _finish, _id, payload)
  return if Thread.current[KEY_RUN]
  return unless enabled?

  # collect endpoint details
  endpoint = payload.fetch(:endpoint)
  env = payload.fetch(:env)
  api_view = api_view(endpoint.options[:for])
  request_method = endpoint.options.fetch(:method).first
  path = endpoint_expand_path(endpoint)
  resource = "#{api_view} #{request_method} #{path}"

  # Store the beginning of a trace
  span = Tracing.trace(
    Ext::SPAN_ENDPOINT_RUN,
    service: service_name,
    type: Tracing::::Ext::HTTP::TYPE_INBOUND,
    resource: resource
  )
  trace = Tracing.active_trace

  # Set the trace resource
  trace.resource = span.resource

  span.set_tag(Tracing::::Ext::TAG_COMPONENT, Ext::TAG_COMPONENT)
  span.set_tag(Tracing::::Ext::TAG_OPERATION, Ext::TAG_OPERATION_ENDPOINT_RUN)
  span.set_tag(Tracing::::Ext::TAG_KIND, Tracing::::Ext::SpanKind::TAG_SERVER)

  # Set User-Agent
  user_agent = env['HTTP_USER_AGENT']
  span.set_tag(Tracing::::Ext::HTTP::TAG_USER_AGENT, user_agent) if user_agent

  # Set base URL (scheme://host:port)
  base_url = build_base_url_from_env(env)
  span.set_tag(Tracing::::Ext::HTTP::TAG_BASE_URL, base_url) unless base_url.empty?

  # 处理 CLOUDWISEREQUESTINFO(前端调用)
  cloudwise_info = env['HTTP_CLOUDWISEREQUESTINFO']
  request_id = nil

  if cloudwise_info
    # 提取 request_id
    request_id = extract_request_id(cloudwise_info)
  end

  # 如果存在 request_id,设置到 span
  if request_id
    span.set_tag('cwsa_trace', request_id)
    Datadog.logger.debug do
      "Set cwsa_trace tag on span: #{request_id}"
    end
  end

  # 处理 CLOUDWISE(外部服务调用,如 Java/PHP/Ruby)
  cloudwise_header = env['HTTP_CLOUDWISE']

  # 如果存在 CLOUDWISE 头(外部服务调用),提取并设置字段到 span
  if cloudwise_header
    require_relative '../cloudwise/propagation'
    Cloudwise::Propagation.extract_and_tag_from_header!(span, cloudwise_header)
  end

  # 提取 CLOUDWISE-OTHER 头并添加到根 span
  require_relative '../cloudwise/propagation'
  Cloudwise::Propagation.extract_other_from_request!(span, env)

  if (grape_route = env['grape.routing_args']) && grape_route[:route_info]
    trace.set_tag(
      Tracing::::Ext::HTTP::TAG_ROUTE,
      # here we are removing the format from the path:
      # e.g. /path/to/resource(.json) => /path/to/resource
      # e.g. /path/to/resource(.:format) => /path/to/resource
      grape_route[:route_info].path&.gsub(/\(\.:?\w+\)\z/, '')
    )

    trace.set_tag(Tracing::::Ext::HTTP::TAG_ROUTE_PATH, env['SCRIPT_NAME'])
  end

  Thread.current[KEY_RUN] = true
rescue => e
  Datadog.logger.error(e.message)
  Datadog::Core::Telemetry::Logger.report(e)
end

.endpoint_start_renderObject



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 200

def endpoint_start_render(*)
  return if Thread.current[KEY_RENDER]
  return unless enabled?

  # Store the beginning of a trace
  span = Tracing.trace(
    Ext::SPAN_ENDPOINT_RENDER,
    service: service_name,
    type: Tracing::::Ext::HTTP::TYPE_TEMPLATE
  )

  span.set_tag(Tracing::::Ext::TAG_COMPONENT, Ext::TAG_COMPONENT)
  span.set_tag(Tracing::::Ext::TAG_OPERATION, Ext::TAG_OPERATION_ENDPOINT_RENDER)

  Thread.current[KEY_RENDER] = true
rescue => e
  Datadog.logger.error(e.message)
  Datadog::Core::Telemetry::Logger.report(e)
end

.handle_error_and_status_code(span, endpoint, payload) ⇒ Object

Status code resolution is tied to the exception handling



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 177

def handle_error_and_status_code(span, endpoint, payload)
  status = nil

  # Handle exceptions and status code
  if (exception_object = payload[:exception_object])
    # If the exception is not an internal Grape error, we won't have a status code at this point.
    status = exception_object.status if exception_object.respond_to?(:status)

    handle_error(span, exception_object, status)
  else
    # Status code is unreliable in `endpoint_run.grape` if there was an exception.
    # Only after `Grape::Middleware::Error#run_rescue_handler` that the error status code of a request with a
    # Ruby exception error is resolved. But that handler is called further down the Grape middleware stack.
    # Rack span will then be the most reliable source for status codes.
    # DEV: As a corollary, instrumenting Grape without Rack will provide incomplete
    # DEV: status quote information.
    status = endpoint.status
    span.set_error(endpoint) if error_status_codes.include?(status)
  end

  span.set_tag(Tracing::::Ext::HTTP::TAG_STATUS_CODE, status) if status
end

.subscribeObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/datadog/tracing/contrib/grape/endpoint.rb', line 25

def subscribe
  # subscribe when a Grape endpoint is hit
  ::ActiveSupport::Notifications.subscribe('endpoint_run.grape.start_process') do |*args|
    endpoint_start_process(*args)
  end
  ::ActiveSupport::Notifications.subscribe('endpoint_run.grape') do |*args|
    endpoint_run(*args)
  end
  ::ActiveSupport::Notifications.subscribe('endpoint_render.grape.start_render') do |*args|
    endpoint_start_render(*args)
  end
  ::ActiveSupport::Notifications.subscribe('endpoint_render.grape') do |*args|
    endpoint_render(*args)
  end
  ::ActiveSupport::Notifications.subscribe('endpoint_run_filters.grape') do |*args|
    endpoint_run_filters(*args)
  end
end