The previous blog entry was a broad brush description of the implementation concepts. This entry will cover the details of actually implementing the Lookup trait.
Lookup uses a curried
apply to simplify the DSL, minimizing the visual clutter.
call is the actual implementation of the sub-service, launching the request-response interaction with
arg and returning a
CI instance that will appear in the corresponding response.
Pending provides a (Recursive)PartialFunction that matches the
CI instance. It's
apply ignores the
CI instance since its actual value has no impact on the processing. It returns a function that casts the request value to the expected type and evaluates the function originally provided in the call to
Lookup.apply.
trait Lookup[A,R] {
def apply(arg:A)(fn:R =>RPF):RPF = new Pending(call(arg),fn)
protected def call(arg:A):CI
}
private class Pending[T](correlationId:CI,fn:T=>RPF) extends RPF{
def isDefinedAt(ci:CI) = ci == correlationId
def apply(ci:CI) = {a:Any=>fn(a.asInstanceOf[T])}
}
case class CI(id:Int)
A trivial example Lookup that doubles the integer request
object DoubleLookup extends Lookup[Int,Int]{
var responseQueue:List[(CI,Int)] = _
protected def call(arg:Int) = {
val ci = CorrelationAllocator()
responseQueue = ci->arg*2 :: responseQueue
ci
}
}
Note
responseQueue which provides a trivial implementation of the mechanism required to asynchronously deliver the response. It captures the CI (to match the
Pending instance that triggered the request and the actual value that will be processed via that
Pending.
CorrelationAllocator is an object that creates sufficiently unique
CI values.