I'm working on the backend for a mobile app, which is currently running on Play 2.1.1. As part of processing some requests, we send push notifications. The downstream request to send the push notification should be entirely asynchronous and decoupled from the originating request-response for the mobile client.
I want to have access to the Http.Context.current()
while sending the downstream request in order to access some tracing information that we pass in request headers.
Originally, the code looked like this, following suggestions in the Play! documentation:
PushNotificationRunnable sendNotificationTask = new ...
Akka.system().scheduler().scheduleOnce(Duration.apply(0, TimeUnit.MICROSECONDS),
sendNotificationTask, Akka.system().dispatcher());
Exploring the play.libs.Akka
helper lead me to the future method, which takes a callable and returns a Promise. The promise allows me to chain further code. Here I've chained a Callback
which has access to Http.Context.current() thanks to set up code in Play's PromiseActor
class. This allows me to log a line, including the trace id, when the task is complete, but my log lines during the task still can not access the tracing information.
PushNotificationCallable sendNotificationTask = new ...
Akka.future(sendNotificationTask).onRedeem(new F.Callback<Void>() {
@Override
public void invoke(Void aVoid) throws Throwable {
Logger.info("Completed sendNotificationTask from the service");
}
});
Here are some much abbreviated application logs to show where I currently am and what is missing, trace id in the 5th column:
2013-07-26 11:31:06,885 DEBUG play-akka.actor.default-dispatcher-10 -2454018518484259555 [application] : Processing request for mobile app
2013-07-26 11:31:06,907 DEBUG play-akka.actor.default-dispatcher-10 -2454018518484259555 [application] : About to schedule push notification message send
2013-07-26 11:31:06,907 INFO application-akka.actor.default-dispatcher-8 n/a [services.PushMessageSenderTask] : Sending message in akka background task
2013-07-26 11:31:06,924 INFO application-akka.actor.default-dispatcher-8 n/a [services.PushMessageSenderTask] : Sent message in akka background task
2013-07-26 11:31:06,925 INFO play-akka.actor.default-dispatcher-16 -2454018518484259555 [application] : Completed sendNotificationTask
The fields are date, time, level, thread and trace id. With this logback configuration if it helps:
%d{ISO8601} %-5level %thread %traceId [%logger] : %msg%n
As you can see, lines 3 and 4 are from the Akka thread and do not have access to the TraceId, instead of printing n/a
. Lines 1 and 2 are on the initial request handling thread and do have access. Finally, line 5 is on a different request handling thread and also has access.
Is there some different way that I could schedule the task that would give it access to Http.Context.request(), but would still run it "outside" of the request-response loop to the browser?