Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing an API for the client to a 3rd-party service

Tags:

scala

api

I am fairly new to Scala and I'm working on an application (library) which is a client to a 3rd-party service (I'm not able to modify the server side and it uses custom binary protocol). I use Netty for networking.

I want to design an API which should allow users to:

  • Send requests to the server
  • Send requests to the server and get the response asynchronously
  • Subscribe to events triggered by the server (having multiple asynchronous event handlers which should be able to send requests as well)

I am not sure how should I design it. Exploring Scala, I stumble upon a bunch of information about Actor model, but I am not sure if it can be applied there and if it can, how.

I'd like to get some recommendations on the way I should take.

like image 235
izstas Avatar asked Feb 15 '23 07:02

izstas


1 Answers

In general, the Scala-ish way to expose asynchronous functionality to user code is to return a scala.concurrent.Future[T].

If you're going the actor route, you might consider encapsulating the binary communication within the context of a single actor class. You can scale the instances of this proxy actor using Akka's router support, and you could produce response futures easily using the ask pattern. There are a few nice libraries (Spray, Play Framework) that make wrapping e.g. a RESTful or even WebSocket layer over Akka almost trivial.

A nice model for the pub-sub functionality might be to define a Publisher trait that you can mix in to some actor subclasses. This could define some state to keep track of subscribers, handle Subscribe and Unsubscribe messages, and provide some sort of convenient method for broadcasting messages:

  /**
    * Sends a copy of the supplied event object to every subscriber of
    * the event object class and superclasses.
    */
  protected[this] def publish[T](event: T) {
    for (subscriber <- subscribersFor(event)) subscriber ! event
  }

These are just some ideas based on doing something similar in some recent projects. Feel free to elaborate on your use case if you need more specific direction. Also, the Akka user list is a great resource for general questions like this, if indeed you're interested in exploring actors in Scala.

like image 122
Connor Doyle Avatar answered Feb 25 '23 10:02

Connor Doyle