The central flatMap() operation, which as in any Monad is key to composing these things together.
The central flatMap() operation, which as in any Monad is key to composing these things together.
flatMap() is a bit tricky. The problem we have is that we need to return a RequestM *synchronously* from flatMap, so that higher-level code can compose on it. But the *real* RequestM being returned from handler won't come into existence until some indefinite time in the future. So we need to create a new one right now, and when the real one comes into existence, link its success to that of the one we're returning here.
The initial version of this was beautiful, elegant, and caused stack overflows if you nested flatMaps more than a couple thousand levels deep. (Which, yes, we occasionally do at Querki.) The issue comes during "unwinding" time, when the innermost RequestM finally gets set to a value. The original version had it then call resolve() on the one that contained it, which called resolve() on its parent, and so on, until we finally blew the stack.
So instead, flatMap builds an ugly but practical linked list of RequestM's, with each one essentially pointing to the one above it. We still call resolve() at each level, but those are *not* recursive; instead, we walk up the flatMap chain *tail*-recursively, resolving each node along the way. It's a bit less elegant, but doesn't cause the JVM to have conniptions.
Build up a chain of RequestM's, from lower levels to higher, so that we can unwind results iteratively instead of through the callbacks.
Build up a chain of RequestM's, from lower levels to higher, so that we can unwind results iteratively instead of through the callbacks.
This is rather ugly, but necessary. The original design did the unwinding completely cleanly, with each inner RequestM propagating its result by calling resolve() on the level above it. But that turned out to cause stack overflow crashes when you got to ~2000 levels of flatMap(). So we need a mechanism that can be handled iteratively (well, tail-recursively) instead.
Set the value for this RequestM, and run through its dependency chain.
Set the value for this RequestM, and run through its dependency chain.
You should *not* normally call this yourself -- it is mainly for internal use. Call this only when you have obtained a RequestM through prep(), and need to finish it up, usually because you have to work around some other concurrency construct. (Such as PersistentActor's persist() call.)
You should ignore the startUnwind flag, which is for internal use only.
The request "monad". It's actually a bit nasty, in that it's mutable, but by and large this behaves the way you expect a monad to work. In particular, it works with for comprehensions, allowing you to compose requests much the way you normally do Futures. But since it is mutable, it should never be used outside the context of an Actor.