Skip to content

Add context with metadata and correlation

Bob Van Landuyt requested to merge bvl-add-context into master

The context can be passed from the client applications as a hash.

Every time a new context is added, it will inherit the values of the previous context. Those previous values will be overridden by any new ones passed.

A context always has a correlation id that is not empty. If an empty correlation id is passed, a new one will be generated.

There is a Labkit::Middleware::Rack that will set the correlation id to the current request id. Because of this, every newly started context within a rack request will get the same correlation id.

Using the Labkit::Middleware::Sidekiq::Client middleware the context active at the moment of scheduling a job will be serialized into the job.

The Labkit::Middleware::Sidekiq::Server middleware will load the context that was stored on the job, so newly scheduled jobs would start with the same context. This context could be modified by the job.

In this iteration the following extra values can be specified on the context:

  • user
  • project
  • root_namespace

Usage of the Labkit::Context

The preferred way of specifying a context is using a block:

  Labkit::Context.with_context(
    user: 'jane.doe',
    project: 'jane.doe/cool'
  ) do |context|
    # application code
  end

If there's no way to wrap the application code into a block (for example for the grape api), then context can be pushed and popped:

  def context
    @context ||= Labkit::Context.push(user: 'jane.doe')
  end

  before { context }
  after { Labkit::Context.pop(context) }

It is possible to provide procs when assigning values to the context:

  Labkit::Context.with_context(user: -> { current_user }) { # ... }

This proc will only be executed when needed: When serialising the context into a log or a job. This happens when calling Labkit::Context.to_h.

Edited by Bob Van Landuyt

Merge request reports