Soumya Simanta
Soumya Simanta

Reputation: 11741

Sending a response back when a chain of actors are involved in Spray

I'm implementing a REST endpoint in Spray.

Here is the flow along with the name of the actors that are responsible for each of the step below.

  1. Invoke the REST API and pass the required parameters (ActorSupervisor)
  2. Validate the parameters (ValidateActor)
  3. Call an external datastore to get data based on the parameter values (DataStoreActor) 3a. The external datastore API returns a Future
  4. Pass the Future in step 3a. to an actor that can process the data (ProcessingActor)
  5. Returned the processing results back to the client (as Future[ HTTP Response])

The most expensive step is #4 (which may take anywhere from a 400ms to 5 minutes depending on the size of the input dataset.

My question is how can I return a HTTP response back from #5?

Upvotes: 2

Views: 399

Answers (1)

mohit
mohit

Reputation: 4999

There are multiple ways to handle that which you can use which gels well with your architecture. Using any method, you will have to use ctx's (spray's RequestContext) complete method to complete the HTTP request. You can use:-

  1. Pass "ctx" (spray's RequestContext) encapsulated in the Actor's message and utilize ctx in the Step #5 to complete the request. For example:- If currently, you pass message from ActorStep1 to ActorStep2 then you will need to pass message(ctx) in this method. The benefit in this method is that you can complete the request from any step but an extra attribute will be added to each message.
  2. Instead of telling you can use ask pattern. In the step 5, you will respond back to Actor in step 4 with Future[ HTTP Response]. Similarly, Actor in step 4 will respond to Actor in step 3 and so on. This works for me because I have only one chain, may not work for you.
  3. You can use forward pattern. For example - Actor in step 1 will pass a message to Actor in Step 2. The Actor in Step 2 will forward the message to Actor in Step 3 after processing and so on till Actor in Step 5. The actor in Step 5 will respond back using sender ! Future[HTTPResponse] which will actually send the message to Actor in Step 1 where you can complete the request.

Spray is just a thin layer on top of Akka, treat this as a case of passing a message back to parent Actor from child actor.

Upvotes: 1

Related Questions