J Pullar
J Pullar

Reputation: 1935

Scala Akka actor, validation of messages

This is an Architecture/design form question as I have a nominally workable solution. I want to see if there is a better way...

I have an actor which handles a number of messages. Each message may have its own content structure validation. I wish to know if there is a suitable pattern for (near seemless) message validation. For example, if I did

val f:Future[Any] = actorRef ask MyMessage(invalidContent)

I could expect back:

f = Future.failure(ValidationException(someMessage))

Currently I have achieved this by creating a wrapper which inherits

trait ValidatingActorRef[-T] {

  def actorRef:ActorRef

  def validate:PartialFunction[T, Option[ValidationException]]

  def ask(message:T)(implicit timeout:Timeout):Future[Any] =
    validate
      .lift(message)
      .flatten
      .map(t => Future.failed(t))
      .getOrElse(akka.pattern.ask(actorRef, message))
}

Giving me

val myActorRefWrapper = new ValidatingActorRef[MyMessages] {  

  val actorRef = system.system.actorOf(Props[MyActor])

  val log = {

    case MyMessage(content) if content == badContent =>
      BadContentValidationException("you have bad content")
  }

}

What I have got here is a validation response without having to waste time on the actor mailbox, or dealing with a future. However the wrapper approach isnt very seemless, I have explicitly wire in a ValidatingActorRef, not just an ActorRef

Is there a better pattern?

Upvotes: 0

Views: 826

Answers (1)

1esha
1esha

Reputation: 1722

In my opinion it is better to validate message not on the sender side, but on actors side.

Just wrap your receive method with general validation logic and mixin some validation implementation.

Also check presentation from ooyala guys - http://slideshare.net/EvanChan2/akka-inproductionpnw-scala2013. Look from 14th slide and find how they build stackable traits on actors

Upvotes: 1

Related Questions