>
This module exports a simple, idiomatic implementation of the Actor Model.
> module Control.Concurrent.Actors (
>
>
>
>
> Action()
> , Behavior(..)
>
> , (<.|>)
>
>
>
> , Mailbox()
> , send , send' , (<->)
> , received
> , guardReceived
>
>
>
> , spawn
> , spawn_
> , spawnReading
>
>
> , yield
> , receive
>
>
>
> , coproductMb
> , productMb
> , zipMb
> , faninMb
> , fanoutMb
>
>
>
> , runBehavior_
> , runBehavior
>
>
> , printB
> , putStrB
> , signalB
> , constB
>
> ) where
>
> import Control.Monad
> import Control.Monad.Reader(ask)
> import qualified Data.Foldable as F
> import Control.Monad.IO.Class
> import Control.Concurrent(forkIO)
> import Data.Monoid
> import Control.Arrow((***),(&&&),(|||))
>
>
> import Data.Functor.Contravariant
>
> import Control.Concurrent.Chan.Split
>
>
> import Control.Concurrent.Actors.Behavior
TODO
-----
0.4
- allow destructuring using UndecidableInstances (see mockup) on spawn, allowing for new, awesome synchronization semantics!
- make that also work with Behaviors of arbitrary input types using new GHC generics!
Later:
- performance tuning / benchmarking:
+ look at interface file: ghc -ddump-hi Control/Concurrent/Actors.hs -O -c
+ remove current PRAGMA
- close browser and everything, do a fake quick benchmark to get clock info
- be more controlled about the source lists (do once before defaultMain), use 'evaluate'
- run with +RTS -s and make sure everything is 0
- see if case-based nil is better
- get accurate baseline comparison between actors and set
- use INLINABLE
- test again with SPECIALIZE instead
- try adding INLINE to all with higher-order args (or higher-order newtype wrappers)
and make sure our LHS looks good for inlining
- specialize `Action i (Behavior i)` or allow lots of unfolding... ? Optimize those loops, somehow. Rewrite rules?
- take a look at threadscope for random tree test
- look at "let floating" and INLINEABLE to get functions with "fully-applied (syntactically) LHS"
- compare with previous version (cp to /tmp to use previous version)
- get complete code coverage into simple test module
- interesting solution to exit detection:
http://en.wikipedia.org/wiki/Huang%27s_algorithm
- dynamically-bounded chans, based on number of writers to control
producer/consumer issues? Possibly add more goodies to chan-split
see: http://hackage.haskell.org/package/stm-chans
- look at what Functor/Contravariant for read/write ends, and corresponding
natural transformations those allow suggest about limits of Actor model
and investigate inverse of Actors (Reducers?)
- create an experimental Collectors sub-module
- investigate ways of positively influencing thread scheduling based on
actor work agenda?
- export some more useful Actors and global thingies
- 'loop' which keeps consuming (is this provided by a class?)
- function returning an actor to "load balance" inputs over multiple
actors
- an actor that sends a random stream?
- a pre-declared Mailbox for IO?
Eventually:
- some sort of exception handling technique (using actors?)
- abilty to launch an actor that automatically "replicates" if its chan needs more
consumers. This should probably be restricted to an `Action i ()` that we
repeat.
- can we automatically throttle producers on an Actor system level,
optimizing message flow with some algorithm?
- provide an "adapter" for amazon SQS, allowing truly distributed message
passing
- investigate erlang-style selective receive (using Alternative?)
- consider: combining TChans, where values are popped off when available,
for chan-split?
- look at ways we can represent network IO as channels to interface with
this. E.g:
- https://github.com/ztellman/aleph
- http://akka.io/ (scala remote actors lib)
- http://www.zeromq.org/intro:read-the-manual
- interface to amazon SQS
- http://msgpack.org/
- "shared memory" approaches?
- cloudhaskell, haskell-mpi, etc. see:
http://stackoverflow.com/questions/8362998/distributed-haskell-state-of-the-art-in-2011
-Behavior -> enumeratee package translator (and vice versa)
(maybe letting us use useful enumerators)
...also now pipes, conduits, etc. etc.
- study ambient/join/fusion calculi for clues as to where it's really at
CHAN TYPES
==========
By defining our Mailbox as the bare "send" operation we get a very convenient
way of defining contravariant instance, without all the overhead we had before,
while ALSO now supporting some great natural transformations on Mailboxes &
Messages.
We use this newtype to get 'Contravariant' for free, possibly revealing other
insights:
> type Sender a = Op (IO ()) a
>
> mailbox :: (a -> IO ()) -> Mailbox a
> mailbox = Mailbox . Op
>
> runMailbox :: Mailbox a -> a -> IO ()
> runMailbox = getOp . sender
>
> mkMailbox :: InChan a -> Mailbox a
> mkMailbox = mailbox . writeChan
>
> mkMessages :: OutChan a -> Messages a
> mkMessages = Messages . readChan
>
>
>
> newtype Mailbox a = Mailbox { sender :: Sender a }
> deriving (Contravariant)
We don't need to expose this thanks to the miracle of MonadFix and recursive do,
but this can be generated via the NewSplitChan class below if the user imports
the library:
> newtype Messages a = Messages { readMsg :: IO a }
> deriving (Functor)
>
>
> instance SplitChan Mailbox Messages where
> readChan = readMsg
> writeChan = runMailbox
>
> instance NewSplitChan Mailbox Messages where
> newSplitChan = (mkMailbox *** mkMessages) `fmap` newSplitChan
For Mailboxes we can define all transformations associated with Cartesian and
CoCartesian (from 'categories') but where the category is Dual (->), i.e. the
order of the transformation is flipped.
I don't know if/how these precisely fit into an existing class, but for now here
are a handful of useful combinators:
> coproductMb :: Mailbox a -> Mailbox b -> Mailbox (Either a b)
> coproductMb m1 m2 = mailbox $ either (writeChan m1) (writeChan m2)
>
> zipMb :: Mailbox a -> Mailbox b -> Mailbox (a,b)
> zipMb m1 m2 = mailbox $ \(a,b) -> writeChan m1 a >> writeChan m2 b
>
>
> productMb :: Mailbox (Either a b) -> (Mailbox a, Mailbox b)
> productMb = contramap Left &&& contramap Right
>
>
> faninMb :: (a -> c) -> (b -> c)-> Mailbox c -> Mailbox (Either a b)
> faninMb f g = contramap (f ||| g)
>
>
> fanoutMb :: (a -> b) -> (a -> c) -> Mailbox (b,c) -> Mailbox a
> fanoutMb f g = contramap (f &&& g)
ACTIONS
=======
Functionality is based on our underlying type classes, but users shouldn't need
to import a bunch of libraries to get basic Behavior building functionality.
> infixl 3 <.|>
>
>
>
>
>
> (<.|>) :: Behavior i -> Behavior i -> Behavior i
> b <.|> b' = b `mappend` constB b'
The 'yield' function is so named because it is "relinquishing control", i.e. I
think the name reminds of the functionality of <|> and mappend (the last input
is passed along) and also has the meaning "quit".
Its similarity (or not) to the 'enumerator' function of the same same may be a
source of confusion (or the opposite)... I'm not sure.
>
>
>
>
> yield :: Action i a
> yield = mzero
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> receive :: Action i (Behavior i) -> Action i (Behavior i)
> receive = return . Receive
>
>
>
>
> received :: Action i i
> received = ask
>
>
>
> guardReceived :: (i -> Bool) -> Action i i
> guardReceived p = ask >>= \i-> guard (p i) >> return i
>
>
>
>
>
> send :: (MonadIO m, SplitChan c x)=> c a -> a -> m ()
> send b = liftIO . writeChan b
>
>
>
> send' :: (MonadIO m, SplitChan c x)=> c a -> a -> m ()
> send' b a = a `seq` send b a
> infixr 1 <->
>
>
>
>
>
>
> (<->) :: (MonadIO m, SplitChan c x)=> a -> m (c a) -> m (c a)
> a <-> mmb = mmb >>= \mb-> send mb a >> return mb
FORKING AND RUNNING ACTORS:
===========================
>
>
>
> spawnReading :: (MonadIO m, SplitChan x c)=> c i -> Behavior i -> m ()
> spawnReading str = liftIO . void . forkIO . actorRunner
> where actorRunner b =
> readChan str >>= runBehaviorStep b >>= F.mapM_ actorRunner
RUNNING ACTORS
--------------
These work in IO, returning () when the actor finishes with done/mzero:
>
>
> runBehavior_ :: Behavior () -> IO ()
> runBehavior_ b = runBehavior b [(),()..]
>
>
> runBehavior :: Behavior a -> [a] -> IO ()
> runBehavior b (a:as) = runBehaviorStep b a >>= F.mapM_ (`runBehavior` as)
> runBehavior _ _ = return ()
FORKING ACTORS
--------------
>
>
>
>
>
>
> spawn :: (MonadIO m)=> Behavior i -> m (Mailbox i)
> spawn b = do
> (m,s) <- liftIO newSplitChan
> spawnReading s b
> return m
>
>
>
>
> spawn_ :: (MonadIO m)=> Behavior () -> m ()
> spawn_ = liftIO . void . forkIO . runBehavior_
USEFUL GENERAL BEHAVIORS
========================
>
>
> printB :: (Show s, Eq n, Num n)=> n -> Behavior s
> printB = contramap (unlines . return . show) . putStrB
We want to yield right after printing the last input to print. This lets us
compose with signalB for instance:
write5ThenExit = putStrB 5 `mappend` signalB c
and the above will signal as soon as it has printed the last message. If we try
to define this in a more traditional recursive way the signal above would only
happen as soon as the sixth message was received.
For now we allow negative
>
> putStrB :: (Eq n, Num n)=> n -> Behavior String
> putStrB 0 = mempty
> putStrB n = Receive $ do
> s <- received
> liftIO $ putStr s
> guard (n /= 1)
> return $ putStrB (n1)
>
>
>
>
> signalB :: (SplitChan c x)=> c () -> Behavior i
> signalB c = Receive (send c () >> yield)
>
>
>
>
>
> constB :: Behavior i -> Behavior i
> constB = Receive . return