Asynchronous Tracking

By default, Castle extracts all the necessary information, such as Client, IP address and HTTP headers, from the request context in order to build and send the requests to the Castle API.

In some cases you want to track data to Castle from a context where these globals are not available, for example when tracking happens asynchronously in a background worker. In this case you need build the request context manually and send it along to your background process.

Request context

Extract the information needed to send to the worker:

context = ::Castle::Client.to_context(request)
track_options = ::Castle::Client.to_options({
  event: '$login.succeeded',
  user_id: 'e325bcdd10ac',
  properties: {
    key: 'value'
  },
  user_traits: {
    key: 'value'
  }
})
from castle.client import Client

context = Client.to_context(request)
track_options = Client.to_options({
  'event': '$login.succeeded',
  'user_id': user.id,
  'properties': {
    'key': 'value'
  },
  'user_traits': {
    'key': 'value'
  }
})
$context = Castle_RequestContext::extractJson();
$track_options = array(
  'user_id' => 'e325bcdd10ac',
  'event' => '$login.succeeded'
);

Now, push this data to your async worker, for example:

CastleTrackingWorker.perform_async(context, track_options)
CastleTrackingWorker.perform_async(context, track_options)
$castleWorker->perform($track_options, $context);

Asynchronous context

Pass the context to track:

class CastleTrackingWorker
  include Sidekiq::Worker

  def perform(context, track_options = {})
    client = ::Castle::Client.new(context)
    client.track(track_options)
  end
end
Client(context).track(track_options)
Castle::track(array(
  'event' => $track_options['event'],
  'user_id' => $track_options['user_id'],
  'context' => json_decode($context)
));