Method: Stackdriver::Core::TraceContext.parse_rack_env

Defined in:
lib/stackdriver/core/trace_context.rb

.parse_rack_env(env) ⇒ TraceContext

Obtains a TraceContext from the given Rack environment. This should be used by any service that wants to obtain the TraceContext for a Rack request. If a new trace context is generated in the process, it is memoized into the Rack environment so subsequent services will get the same context.

Specifically, the following steps are attempted in order:

  1. Attempts to use any memoized context previously obtained.
  2. Attempts to parse the trace context header.
  3. Creates a new trace context with a random trace ID.

Furthermore, if a block is given, it is provided with an opportunity to modify the trace context. The current trace context and the Rack environment is passed to the block, and its result is used as the final trace context. The final context is memoized back into the Rack environment.

Examples:

require "stackdriver/core"

class MyMiddleware
  def initialize app
    @app = app
  end

  def call env
    ctx = Stackdriver::Core::TraceContext.parse_rack_env env
    do_something_with ctx
    @app.call env
  end
end

Parameters:

  • env (Hash)

    The Rack environment hash

Returns:



281
282
283
284
285
286
287
# File 'lib/stackdriver/core/trace_context.rb', line 281

def self.parse_rack_env env
  trace_context = env[MEMO_RACK_KEY] ||
                  parse_string(env[HEADER_RACK_KEY].to_s) ||
                  new
  trace_context = yield trace_context, env if block_given?
  env[MEMO_RACK_KEY] = trace_context
end