简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM