2{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE DeriveDataTypeable #-}
4{-# LANGUAGE DeriveFunctor #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE ExistentialQuantification #-}
7{-# LANGUAGE BangPatterns #-}
9-- | Cloud Haskell primitives
11-- We define these in a separate module so that we don't have to rely on
12-- the closure combinators
13module Control.Distributed.Process.Internal.Primitives
14 ( -- * Basic messaging
24 -- * Unsafe messaging variants
30 -- * Advanced messaging
56 -- * Process management
58 , ProcessTerminationException(..)
64 -- keep the exception constructor hidden, so that handling exit
65 -- reasons /must/ take place via the 'catchExit' family of primitives
66 , ProcessExitException()
74 -- * Monitoring and linking
91 , reregisterRemoteAsync
92 , unregisterRemoteAsync
98 -- * Exception handling
122 -- * Internal Exports
126#if ! MIN_VERSION_base(4,6,0)
127import Prelude hiding (catch)
130import Data.Binary (Binary(..), Put, Get, decode)
131import Data.Time.Clock (getCurrentTime, UTCTime(..))
132import Data.Time.Calendar (Day(..))
133import Data.Time.Format (formatTime)
134#if MIN_VERSION_time(1,5,0)
135import Data.Time.Format (defaultTimeLocale)
137import System.Locale (defaultTimeLocale)
139import System.Timeout (timeout)
140import Control.Monad (when, void)
141import Control.Monad.Reader (ask)
142import Control.Monad.IO.Class (liftIO)
143import Control.Monad.Catch
149import qualified Control.Monad.Catch as Catch
150import Control.Applicative
151import Control.Distributed.Process.Internal.StrictMVar
156import Control.Concurrent.STM
165import Control.Distributed.Process.Internal.CQueue
170import Control.Distributed.Process.Serializable (Serializable, fingerprint)
171import Data.Accessor ((^.), (^:), (^=))
172import Control.Distributed.Static
176import Data.Rank1Typeable (Typeable)
177import qualified Control.Distributed.Static as Static (unstatic, unclosure)
178import qualified Control.Distributed.Process.UnsafePrimitives as Unsafe
179import Control.Distributed.Process.Internal.Types
189 , NodeMonitorNotification(..)
190 , ProcessMonitorNotification(..)
200 , ProcessExitException(..)
203 , DidUnlinkProcess(..)
208 , ProcessRegistrationException(..)
210 , ProcessInfoNone(..)
214 , createUnencodedMessage
215 , ImplicitReconnect( NoImplicitReconnect)
220import Control.Distributed.Process.Internal.Messaging
227import Control.Distributed.Process.Management.Internal.Types
230import Control.Distributed.Process.Management.Internal.Trace.Types
233import Control.Distributed.Process.Internal.WeakTQueue
242--------------------------------------------------------------------------------
244--------------------------------------------------------------------------------
247send :: Serializable a => ProcessId -> a -> Process ()
248-- This requires a lookup on every send. If we want to avoid that we need to
249-- modify serializable to allow for stateful (IO) deserialization.
252 let us = processId proc
253 node = processNode proc
254 nodeId = localNodeId node
255 destNode = (processNodeId them) in do
256 case destNode == nodeId of
257 True -> sendLocal them msg
258 False -> liftIO $ sendMessage (processNode proc)
259 (ProcessIdentifier (processId proc))
260 (ProcessIdentifier them)
263 -- We do not fire the trace event until after the sending is complete;
264 -- In the remote case, 'sendMessage' can block in the networking stack.
265 liftIO $ traceEvent (localEventBus node)
266 (MxSent them us (createUnencodedMessage msg))
268-- | /Unsafe/ variant of 'send'. This function makes /no/ attempt to serialize
269-- and (in the case when the destination process resides on the same local
270-- node) therefore ensure that the payload is fully evaluated before it is
272unsafeSend :: Serializable a => ProcessId -> a -> Process ()
273unsafeSend = Unsafe.send
275-- | Send a message unreliably.
277-- Unlike 'send', this function is insensitive to 'reconnect'. It will
278-- try to send the message regardless of the history of connection failures
281-- Message passing with 'usend' is ordered for a given sender and receiver
282-- if the messages arrive at all.
284usend :: Serializable a => ProcessId -> a -> Process ()
287 let there = processNodeId them
289 then sendLocal them msg
290 else sendCtrlMsg (Just there) $ UnreliableSend (processLocalId them)
293-- | /Unsafe/ variant of 'usend'. This function makes /no/ attempt to serialize
294-- the message when the destination process resides on the same local
295-- node. Therefore, a local receiver would need to be prepared to cope with any
296-- errors resulting from evaluation of the message.
297unsafeUSend :: Serializable a => ProcessId -> a -> Process ()
298unsafeUSend = Unsafe.usend
300-- | Wait for a message of a specific type
301expect :: forall a. Serializable a => Process a
302expect = receiveWait [match return]
304--------------------------------------------------------------------------------
306--------------------------------------------------------------------------------
308-- | Create a new typed channel
309newChan :: Serializable a => Process (SendPort a, ReceivePort a)
312 liftIO . modifyMVar (processState proc) $ \st -> do
313 let lcid = st ^. channelCounter
314 let cid = SendPortId { sendPortProcessId = processId proc
315 , sendPortLocalId = lcid
317 let sport = SendPort cid
318 chan <- liftIO newTQueueIO
319 chan' <- mkWeakTQueue chan $ finalizer (processState proc) lcid
320 let rport = ReceivePort $ readTQueue chan
321 let tch = TypedChannel chan'
322 return ( (channelCounter ^: (+ 1))
323 . (typedChannelWithId lcid ^= Just tch)
328 finalizer :: StrictMVar LocalProcessState -> LocalSendPortId -> IO ()
329 finalizer st lcid = modifyMVar_ st $
330 return . (typedChannelWithId lcid ^= Nothing)
332-- | Send a message on a typed channel
333sendChan :: Serializable a => SendPort a -> a -> Process ()
334sendChan (SendPort cid) msg = do
336 let node = localNodeId (processNode proc)
337 destNode = processNodeId (sendPortProcessId cid) in do
338 case destNode == node of
339 True -> sendChanLocal cid msg
341 liftIO $ sendBinary (processNode proc)
342 (ProcessIdentifier (processId proc))
343 (SendPortIdentifier cid)
347-- | Send a message on a typed channel. This function makes /no/ attempt to
348-- serialize and (in the case when the @ReceivePort@ resides on the same local
349-- node) therefore ensure that the payload is fully evaluated before it is
351unsafeSendChan :: Serializable a => SendPort a -> a -> Process ()
352unsafeSendChan = Unsafe.sendChan
354-- | Wait for a message on a typed channel
355receiveChan :: Serializable a => ReceivePort a -> Process a
356receiveChan = liftIO . atomically . receiveSTM
358-- | Like 'receiveChan' but with a timeout. If the timeout is 0, do a
359-- non-blocking check for a message.
360receiveChanTimeout :: Serializable a => Int -> ReceivePort a -> Process (Maybe a)
361receiveChanTimeout 0 ch = liftIO . atomically $
362 (Just <$> receiveSTM ch) `orElse` return Nothing
363receiveChanTimeout n ch = liftIO . timeout n . atomically $
366-- | Merge a list of typed channels.
368-- The result port is left-biased: if there are messages available on more
369-- than one port, the first available message is returned.
370mergePortsBiased :: Serializable a => [ReceivePort a] -> Process (ReceivePort a)
371mergePortsBiased = return . ReceivePort. foldr1 orElse . map receiveSTM
373-- | Like 'mergePortsBiased', but with a round-robin scheduler (rather than
375mergePortsRR :: Serializable a => [ReceivePort a] -> Process (ReceivePort a)
376mergePortsRR = \ps -> do
377 psVar <- liftIO . atomically $ newTVar (map receiveSTM ps)
378 return $ ReceivePort (rr psVar)
382 rotate (x:xs) = xs ++ [x]
384 rr :: TVar [STM a] -> STM a
387 a <- foldr1 orElse ps
388 writeTVar psVar (rotate ps)
391--------------------------------------------------------------------------------
392-- Advanced messaging --
393--------------------------------------------------------------------------------
395-- | Opaque type used in 'receiveWait' and 'receiveTimeout'
396newtype Match b = Match { unMatch :: MatchOn Message (Process b) }
399-- | Test the matches in order against each message in the queue
400receiveWait :: [Match b] -> Process b
402 queue <- processQueue <$> ask
403 Just proc <- liftIO $ dequeue queue Blocking (map unMatch ms)
406-- | Like 'receiveWait' but with a timeout.
408-- If the timeout is zero do a non-blocking check for matching messages. A
409-- non-zero timeout is applied only when waiting for incoming messages (that is,
410-- /after/ we have checked the messages that are already in the mailbox).
411receiveTimeout :: Int -> [Match b] -> Process (Maybe b)
412receiveTimeout t ms = do
413 queue <- processQueue <$> ask
414 let blockSpec = if t == 0 then NonBlocking else Timeout t
415 mProc <- liftIO $ dequeue queue blockSpec (map unMatch ms)
417 Nothing -> return Nothing
418 Just proc -> Just <$> proc
420-- | Match on a typed channel
421matchChan :: ReceivePort a -> (a -> Process b) -> Match b
422matchChan p fn = Match $ MatchChan (fmap fn (receiveSTM p))
424-- | Match on an arbitrary STM action.
426-- This rather unusaul /match primitive/ allows us to compose arbitrary STM
427-- actions with checks against our process' mailbox and/or any typed channel
428-- @ReceivePort@s we may hold.
430-- This allows us to process multiple input streams /along with our mailbox/,
431-- in just the same way that 'matchChan' supports checking both the mailbox
432-- /and/ an arbitrary set of typed channels in one atomic transaction.
434-- Note there are no ordering guarnatees with respect to these disparate input
437matchSTM :: STM a -> (a -> Process b) -> Match b
438matchSTM stm fn = Match $ MatchChan (fmap fn stm)
440-- | Match against any message of the right type
441match :: forall a b. Serializable a => (a -> Process b) -> Match b
442match = matchIf (const True)
444-- | Match against any message of the right type that satisfies a predicate
445matchIf :: forall a b. Serializable a => (a -> Bool) -> (a -> Process b) -> Match b
446matchIf c p = Match $ MatchMsg $ \msg ->
447 case messageFingerprint msg == fingerprint (undefined :: a) of
450 (UnencodedMessage _ m) ->
451 let m' = unsafeCoerce m :: a in
455 (EncodedMessage _ _) ->
456 if (c decoded) then Just (p decoded) else Nothing
459 -- Make sure the value is fully decoded so that we don't hang to
460 -- bytestrings when the process calling 'matchIf' doesn't process
461 -- the values immediately
462 !decoded = decode (messageEncoding msg)
464-- | Match against any message, regardless of the underlying (contained) type
465matchMessage :: (Message -> Process Message) -> Match Message
466matchMessage p = Match $ MatchMsg $ \msg -> Just (p msg)
468-- | Match against any message (regardless of underlying type) that satisfies a predicate
469matchMessageIf :: (Message -> Bool) -> (Message -> Process Message) -> Match Message
470matchMessageIf c p = Match $ MatchMsg $ \msg ->
475-- | Forward a raw 'Message' to the given 'ProcessId'.
476forward :: Message -> ProcessId -> Process ()
479 let node = processNode proc
481 nid = localNodeId node
482 destNode = (processNodeId them) in do
483 case destNode == nid of
484 True -> sendCtrlMsg Nothing (LocalSend them msg)
485 False -> liftIO $ sendPayload (processNode proc)
486 (ProcessIdentifier (processId proc))
487 (ProcessIdentifier them)
489 (messageToPayload msg)
490 -- We do not fire the trace event until after the sending is complete;
491 -- In the remote case, 'sendMessage' can block in the networking stack.
492 liftIO $ traceEvent (localEventBus node)
495-- | Forward a raw 'Message' to the given 'ProcessId'.
497-- Unlike 'forward', this function is insensitive to 'reconnect'. It will
498-- try to send the message regardless of the history of connection failures
500uforward :: Message -> ProcessId -> Process ()
501uforward msg them = do
503 let node = processNode proc
505 nid = localNodeId node
506 destNode = (processNodeId them) in do
507 case destNode == nid of
508 True -> sendCtrlMsg Nothing (LocalSend them msg)
509 False -> sendCtrlMsg (Just destNode) $ UnreliableSend (processLocalId them)
511 -- We do not fire the trace event until after the sending is complete;
512 -- In the remote case, 'sendCtrlMsg' can block in the networking stack.
513 liftIO $ traceEvent (localEventBus node)
516-- | Wrap a 'Serializable' value in a 'Message'. Note that 'Message's are
517-- 'Serializable' - like the datum they contain - but also note, deserialising
518-- such a 'Message' will yield a 'Message', not the type within it! To obtain the
519-- wrapped datum, use 'unwrapMessage' or 'handleMessage' with a specific type.
524-- send self (wrapMessage "blah")
525-- Nothing <- expectTimeout 1000000 :: Process (Maybe String)
526-- (Just m) <- expectTimeout 1000000 :: Process (Maybe Message)
527-- (Just "blah") <- unwrapMessage m :: Process (Maybe String)
530wrapMessage :: Serializable a => a -> Message
531wrapMessage = createUnencodedMessage -- see [note Serializable UnencodedMessage]
533-- | This is the /unsafe/ variant of 'wrapMessage'. See
534-- "Control.Distributed.Process.UnsafePrimitives" for details.
535unsafeWrapMessage :: Serializable a => a -> Message
536unsafeWrapMessage = Unsafe.wrapMessage
538-- [note Serializable UnencodedMessage]
539-- if we attempt to serialise an UnencodedMessage, it will be converted to an
540-- EncodedMessage first, so we're ok here. See 'messageToPayload' in
541-- Primitives.hs for the gory details
543-- | Attempt to unwrap a raw 'Message'.
544-- If the type of the decoded message payload matches the expected type, the
545-- value will be returned with @Just@, otherwise @Nothing@ indicates the types
548-- This expression, for example, will evaluate to @Nothing@
549-- > unwrapMessage (wrapMessage "foobar") :: Process (Maybe Int)
551-- Whereas this expression, will yield @Just "foo"@
552-- > unwrapMessage (wrapMessage "foo") :: Process (Maybe String)
554unwrapMessage :: forall m a. (Monad m, Serializable a) => Message -> m (Maybe a)
556 case messageFingerprint msg == fingerprint (undefined :: a) of
557 False -> return Nothing :: m (Maybe a)
559 (UnencodedMessage _ ms) ->
560 let ms' = unsafeCoerce ms :: a
562 (EncodedMessage _ _) ->
563 return (Just (decoded))
565 decoded :: a -- note [decoding]
566 !decoded = decode (messageEncoding msg)
568-- | Attempt to handle a raw 'Message'.
569-- If the type of the message matches the type of the first argument to
570-- the supplied expression, then the message will be decoded and the expression
571-- evaluated against its value. If this runtime type checking fails however,
572-- @Nothing@ will be returned to indicate the fact. If the check succeeds and
573-- evaluation proceeds, the resulting value with be wrapped with @Just@.
575-- Intended for use in `catchesExit` and `matchAny` primitives.
577handleMessage :: forall m a b. (Monad m, Serializable a)
578 => Message -> (a -> m b) -> m (Maybe b)
579handleMessage msg proc = handleMessageIf msg (const True) proc
581-- | Conditionally handle a raw 'Message'.
582-- If the predicate @(a -> Bool)@ evaluates to @True@, invokes the supplied
583-- handler, other returns @Nothing@ to indicate failure. See 'handleMessage'
584-- for further information about runtime type checking.
586handleMessageIf :: forall m a b . (Monad m, Serializable a)
591handleMessageIf msg c proc = do
592 case messageFingerprint msg == fingerprint (undefined :: a) of
593 False -> return Nothing :: m (Maybe b)
595 (UnencodedMessage _ ms) ->
596 let ms' = unsafeCoerce ms :: a in
598 True -> do { r <- proc ms'; return (Just r) }
599 False -> return Nothing :: m (Maybe b)
600 (EncodedMessage _ _) ->
602 True -> do { r <- proc (decoded :: a); return (Just r) }
603 False -> return Nothing :: m (Maybe b)
605 decoded :: a -- note [decoding]
606 !decoded = decode (messageEncoding msg)
608-- | As 'handleMessage' but ignores result, which is useful if you don't
609-- care whether or not the handler succeeded.
611handleMessage_ :: forall m a . (Monad m, Serializable a)
612 => Message -> (a -> m ()) -> m ()
613handleMessage_ msg proc = handleMessageIf_ msg (const True) proc
615-- | Conditional version of 'handleMessage_'.
617handleMessageIf_ :: forall m a . (Monad m, Serializable a)
622handleMessageIf_ msg c proc = handleMessageIf msg c proc >> return ()
624-- | Match against an arbitrary message. 'matchAny' removes the first available
625-- message from the process mailbox. To handle arbitrary /raw/ messages once
626-- removed from the mailbox, see 'handleMessage' and 'unwrapMessage'.
628matchAny :: forall b. (Message -> Process b) -> Match b
629matchAny p = Match $ MatchMsg $ \msg -> Just (p msg)
631-- | Match against an arbitrary message. Intended for use with 'handleMessage'
632-- and 'unwrapMessage', this function /only/ removes a message from the process
633-- mailbox, /if/ the supplied condition matches. The success (or failure) of
634-- runtime type checks deferred to @handleMessage@ and friends is irrelevant
635-- here, i.e., if the condition evaluates to @True@ then the message will
636-- be removed from the process mailbox and decoded, but that does /not/
637-- guarantee that an expression passed to @handleMessage@ will pass the
638-- runtime type checks and therefore be evaluated.
640matchAnyIf :: forall a b. (Serializable a)
642 -> (Message -> Process b)
644matchAnyIf c p = Match $ MatchMsg $ \msg ->
645 case messageFingerprint msg == fingerprint (undefined :: a) of
646 True | check -> Just (p msg)
651 (EncodedMessage _ _) -> c decoded
652 (UnencodedMessage _ m') -> c (unsafeCoerce m')
654 decoded :: a -- note [decoding]
655 !decoded = decode (messageEncoding msg)
659For an EncodedMessage, we need to ensure the value is fully decoded so that
660we don't hang to bytestrings if the calling process doesn't evaluate
661immediately. For UnencodedMessage we know (because the fingerprint comparison
662succeeds) that unsafeCoerce will not fail.
665-- | Remove any message from the queue
666matchUnknown :: Process b -> Match b
667matchUnknown p = Match $ MatchMsg (const (Just p))
669-- | Receives messages and forwards them to @pid@ if @p msg == True@.
670delegate :: ProcessId -> (Message -> Bool) -> Process ()
673 matchAny (\m -> case (p m) of
674 True -> forward m pid
679-- | A straight relay that forwards all messages to the supplied pid.
680relay :: ProcessId -> Process ()
681relay !pid = receiveWait [ matchAny (\m -> forward m pid) ] >> relay pid
683-- | Proxies @pid@ and forwards messages whenever @proc@ evaluates to @True@.
684-- Unlike 'delegate' the predicate @proc@ runs in the 'Process' monad, allowing
685-- for richer proxy behaviour. If @proc@ returns @False@ or the /runtime type check/
686-- fails, no action is taken and the proxy process will continue running.
687proxy :: Serializable a => ProcessId -> (a -> Process Bool) -> Process ()
691 next <- handleMessage m proc
693 Just True -> forward m pid
694 Just False -> return () -- explicitly ignored
695 Nothing -> return ()) -- un-routable
699--------------------------------------------------------------------------------
700-- Process management --
701--------------------------------------------------------------------------------
703-- | Thrown by 'terminate'
704data ProcessTerminationException = ProcessTerminationException
705 deriving (Show, Typeable)
707instance Exception ProcessTerminationException
709-- | Terminate immediately (throws a ProcessTerminationException)
710terminate :: Process a
711terminate = throwM ProcessTerminationException
714-- | Die immediately - throws a 'ProcessExitException' with the given @reason@.
715die :: Serializable a => a -> Process b
717-- NOTE: We do /not/ want to use UnencodedMessage here, as the exception
718-- could be decoded by a handler passed to 'catchExit', re-thrown or even
719-- passed to another process via the tracing mechanism.
721 throwM (ProcessExitException pid (createMessage reason))
723-- | Forceful request to kill a process. Where 'exit' provides an exception
724-- that can be caught and handled, 'kill' throws an unexposed exception type
725-- which cannot be handled explicitly (by type).
726kill :: ProcessId -> String -> Process ()
727-- NOTE: We send the message to our local node controller, which will then
728-- forward it to a remote node controller (if applicable). Sending it directly
729-- to a remote node controller means that that the message may overtake a
730-- 'monitor' or 'link' request.
731kill them reason = sendCtrlMsg Nothing (Kill them reason)
733-- | Graceful request to exit a process. Throws 'ProcessExitException' with the
734-- supplied @reason@ encoded as a message. Any /exit signal/ raised in this
735-- manner can be handled using the 'catchExit' family of functions.
736exit :: Serializable a => ProcessId -> a -> Process ()
737-- NOTE: We send the message to our local node controller, which will then
738-- forward it to a remote node controller (if applicable). Sending it directly
739-- to a remote node controller means that that the message may overtake a
740-- 'monitor' or 'link' request.
741exit them reason = sendCtrlMsg Nothing (Exit them (createMessage reason))
743-- | Catches 'ProcessExitException'. The handler will not be applied unless its
744-- type matches the encoded data stored in the exception (see the /reason/
745-- argument given to the 'exit' primitive). If the handler cannot be applied,
746-- the exception will be re-thrown.
748-- To handle 'ProcessExitException' without regard for /reason/, see 'catch'.
749-- To handle multiple /reasons/ of differing types, see 'catchesExit'.
750catchExit :: forall a b . (Show a, Serializable a)
752 -> (ProcessId -> a -> Process b)
754catchExit act exitHandler = Catch.catch act handleExit
756 handleExit ex@(ProcessExitException from msg) =
757 if messageFingerprint msg == fingerprint (undefined :: a)
758 then exitHandler from decoded
762 -- Make sure the value is fully decoded so that we don't hang to
763 -- bytestrings if the caller doesn't use the value immediately
764 !decoded = decode (messageEncoding msg)
766-- | Lift 'Control.Exception.catches' (almost).
768-- As 'ProcessExitException' stores the exit @reason@ as a typed, encoded
769-- message, a handler must accept inputs of the expected type. In order to
770-- handle a list of potentially different handlers (and therefore input types),
771-- a handler passed to 'catchesExit' must accept 'Message' and return
772-- @Maybe@ (i.e., @Just p@ if it handled the exit reason, otherwise @Nothing@).
774-- See 'maybeHandleMessage' and 'Message' for more details.
775catchesExit :: Process b
776 -> [(ProcessId -> Message -> (Process (Maybe b)))]
778catchesExit act handlers = Catch.catch act ((flip handleExit) handlers)
780 handleExit :: ProcessExitException
781 -> [(ProcessId -> Message -> Process (Maybe b))]
783 handleExit ex [] = throwM ex
784 handleExit ex@(ProcessExitException from msg) (h:hs) = do
787 Nothing -> handleExit ex hs
790-- | Our own process ID
791getSelfPid :: Process ProcessId
792getSelfPid = processId <$> ask
794-- | Get the node ID of our local node
795getSelfNode :: Process NodeId
796getSelfNode = localNodeId . processNode <$> ask
799-- | Get statistics about the specified node
800getNodeStats :: NodeId -> Process (Either DiedReason NodeStats)
802 selfNode <- getSelfNode
804 then Right `fmap` getLocalNodeStats -- optimisation
805 else getNodeStatsRemote selfNode
807 getNodeStatsRemote :: NodeId -> Process (Either DiedReason NodeStats)
808 getNodeStatsRemote selfNode = do
809 sendCtrlMsg (Just nid) $ GetNodeStats selfNode
810 bracket (monitorNode nid) unmonitor $ \mRef ->
811 receiveWait [ match (\(stats :: NodeStats) -> return $ Right stats)
812 , matchIf (\(NodeMonitorNotification ref _ _) -> ref == mRef)
813 (\(NodeMonitorNotification _ _ dr) -> return $ Left dr)
816-- | Get statistics about our local node
817getLocalNodeStats :: Process NodeStats
818getLocalNodeStats = do
820 sendCtrlMsg Nothing $ GetNodeStats self
821 receiveWait [ match (\(stats :: NodeStats) -> return stats) ]
823-- | Get information about the specified process
824getProcessInfo :: ProcessId -> Process (Maybe ProcessInfo)
826 let them = processNodeId pid in do
828 dest <- mkNode them us
829 sendCtrlMsg dest $ GetInfo pid
831 match (\(p :: ProcessInfo) -> return $ Just p)
832 , match (\(_ :: ProcessInfoNone) -> return Nothing)
834 where mkNode :: NodeId -> NodeId -> Process (Maybe NodeId)
835 mkNode them us = case them == us of
836 True -> return Nothing
837 _ -> return $ Just them
839--------------------------------------------------------------------------------
840-- Monitoring and linking --
841--------------------------------------------------------------------------------
843-- | Link to a remote process (asynchronous)
845-- When process A links to process B (that is, process A calls
846-- @link pidB@) then an asynchronous exception will be thrown to process A
847-- when process B terminates (normally or abnormally), or when process A gets
848-- disconnected from process B. Although it is /technically/ possible to catch
849-- these exceptions, chances are if you find yourself trying to do so you should
850-- probably be using 'monitor' rather than 'link'. In particular, code such as
852-- > link pidB -- Link to process B
853-- > expect -- Wait for a message from process B
854-- > unlink pidB -- Unlink again
856-- doesn't quite do what one might expect: if process B sends a message to
857-- process A, and /subsequently terminates/, then process A might or might not
858-- be terminated too, depending on whether the exception is thrown before or
859-- after the 'unlink' (i.e., this code has a race condition).
861-- Linking is all-or-nothing: A is either linked to B, or it's not. A second
862-- call to 'link' has no effect.
864-- Note that 'link' provides unidirectional linking (see 'spawnSupervised').
865-- Linking makes no distinction between normal and abnormal termination of
866-- the remote process.
867link :: ProcessId -> Process ()
868link = sendCtrlMsg Nothing . Link . ProcessIdentifier
870-- | Monitor another process (asynchronous)
872-- When process A monitors process B (that is, process A calls
873-- @monitor pidB@) then process A will receive a 'ProcessMonitorNotification'
874-- when process B terminates (normally or abnormally), or when process A gets
875-- disconnected from process B. You receive this message like any other (using
876-- 'expect'); the notification includes a reason ('DiedNormal', 'DiedException',
877-- 'DiedDisconnect', etc.).
879-- Every call to 'monitor' returns a new monitor reference 'MonitorRef'; if
880-- multiple monitors are set up, multiple notifications will be delivered
881-- and monitors can be disabled individually using 'unmonitor'.
882monitor :: ProcessId -> Process MonitorRef
883monitor = monitor' . ProcessIdentifier
885-- | Establishes temporary monitoring of another process.
887-- @withMonitor pid code@ sets up monitoring of @pid@ for the duration
888-- of @code@. Note: although monitoring is no longer active when
889-- @withMonitor@ returns, there might still be unreceived monitor
890-- messages in the queue.
892withMonitor :: ProcessId -> (MonitorRef -> Process a) -> Process a
893withMonitor pid = bracket (monitor pid) unmonitor
895-- | Establishes temporary monitoring of another process.
897-- @withMonitor_ pid code@ sets up monitoring of @pid@ for the duration
898-- of @code@. Note: although monitoring is no longer active when
899-- @withMonitor_@ returns, there might still be unreceived monitor
900-- messages in the queue.
903withMonitor_ :: ProcessId -> Process a -> Process a
904withMonitor_ p = withMonitor p . const
908-- This is synchronous in the sense that once it returns you are guaranteed
909-- that no exception will be raised if the remote process dies. However, it is
910-- asynchronous in the sense that we do not wait for a response from the remote
912unlink :: ProcessId -> Process ()
915 receiveWait [ matchIf (\(DidUnlinkProcess pid') -> pid' == pid)
919-- | Remove a node link
921-- This has the same synchronous/asynchronous nature as 'unlink'.
922unlinkNode :: NodeId -> Process ()
925 receiveWait [ matchIf (\(DidUnlinkNode nid') -> nid' == nid)
929-- | Remove a channel (send port) link
931-- This has the same synchronous/asynchronous nature as 'unlink'.
932unlinkPort :: SendPort a -> Process ()
934 unlinkPortAsync sport
935 receiveWait [ matchIf (\(DidUnlinkPort cid) -> cid == sendPortId sport)
941-- This has the same synchronous/asynchronous nature as 'unlink'.
943-- ProcessMonitorNotification messages for the given MonitorRef are removed from
945unmonitor :: MonitorRef -> Process ()
948 receiveWait [ matchIf (\(DidUnmonitor ref') -> ref' == ref)
951 -- Discard the notification if any. With the current NC implementation at most
952 -- one notification is in the mailbox for any given ref.
953 void $ receiveTimeout 0
954 [ matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == ref)
958--------------------------------------------------------------------------------
959-- Exception handling --
960--------------------------------------------------------------------------------
962-- | Lift 'Control.Exception.catch'
963catch :: Exception e => Process a -> (e -> Process a) -> Process a
965{-# DEPRECATED catch "Use Control.Monad.Catch.catch instead" #-}
967-- | Lift 'Control.Exception.try'
968try :: Exception e => Process a -> Process (Either e a)
970{-# DEPRECATED try "Use Control.Monad.Catch.try instead" #-}
972-- | Lift 'Control.Exception.mask'
973mask :: ((forall a. Process a -> Process a) -> Process b) -> Process b
975{-# DEPRECATED mask "Use Control.Monad.Catch.mask_ instead" #-}
977-- | Lift 'Control.Exception.mask_'
978mask_ :: Process a -> Process a
980{-# DEPRECATED mask_ "Use Control.Monad.Catch.mask_ instead" #-}
982-- | Lift 'Control.Exception.onException'
983onException :: Process a -> Process b -> Process a
984onException = Catch.onException
985{-# DEPRECATED onException "Use Control.Monad.Catch.onException instead" #-}
987-- | Lift 'Control.Exception.bracket'
988bracket :: Process a -> (a -> Process b) -> (a -> Process c) -> Process c
989bracket = Catch.bracket
990{-# DEPRECATED bracket "Use Control.Monad.Catch.bracket instead" #-}
992-- | Lift 'Control.Exception.bracket_'
993bracket_ :: Process a -> Process b -> Process c -> Process c
994bracket_ = Catch.bracket_
995{-# DEPRECATED bracket_ "Use Control.Monad.Catch.bracket_ instead" #-}
997-- | Lift 'Control.Exception.finally'
998finally :: Process a -> Process b -> Process a
999finally = Catch.finally
1000{-# DEPRECATED finally "Use Control.Monad.Catch.finally instead" #-}
1002-- | You need this when using 'catches'
1003data Handler a = forall e . Exception e => Handler (e -> Process a)
1005instance Functor Handler where
1006 fmap f (Handler h) = Handler (fmap f . h)
1008-- | Lift 'Control.Exception.catches'
1009catches :: Process a -> [Handler a] -> Process a
1010catches proc handlers = proc `Catch.catch` catchesHandler handlers
1012catchesHandler :: [Handler a] -> SomeException -> Process a
1013catchesHandler handlers e = foldr tryHandler (throwM e) handlers
1014 where tryHandler (Handler handler) res
1015 = case fromException e of
1016 Just e' -> handler e'
1019--------------------------------------------------------------------------------
1021--------------------------------------------------------------------------------
1023-- | Like 'expect' but with a timeout
1024expectTimeout :: forall a. Serializable a => Int -> Process (Maybe a)
1025expectTimeout n = receiveTimeout n [match return]
1027-- | Asynchronous version of 'spawn'
1029-- ('spawn' is defined in terms of 'spawnAsync' and 'expect')
1030spawnAsync :: NodeId -> Closure (Process ()) -> Process SpawnRef
1031spawnAsync nid proc = do
1032 spawnRef <- getSpawnRef
1035 then sendCtrlMsg Nothing $ Spawn proc spawnRef
1036 else sendCtrlMsg (Just nid) $ Spawn proc spawnRef
1039-- | Monitor a node (asynchronous)
1040monitorNode :: NodeId -> Process MonitorRef
1042 monitor' . NodeIdentifier
1044-- | Monitor a typed channel (asynchronous)
1045monitorPort :: forall a. Serializable a => SendPort a -> Process MonitorRef
1046monitorPort (SendPort cid) =
1047 monitor' (SendPortIdentifier cid)
1049-- | Remove a monitor (asynchronous)
1050unmonitorAsync :: MonitorRef -> Process ()
1052 sendCtrlMsg Nothing . Unmonitor
1054-- | Link to a node (asynchronous)
1055linkNode :: NodeId -> Process ()
1056linkNode = link' . NodeIdentifier
1058-- | Link to a channel (asynchronous)
1059linkPort :: SendPort a -> Process ()
1060linkPort (SendPort cid) =
1061 link' (SendPortIdentifier cid)
1063-- | Remove a process link (asynchronous)
1064unlinkAsync :: ProcessId -> Process ()
1066 sendCtrlMsg Nothing . Unlink . ProcessIdentifier
1068-- | Remove a node link (asynchronous)
1069unlinkNodeAsync :: NodeId -> Process ()
1071 sendCtrlMsg Nothing . Unlink . NodeIdentifier
1073-- | Remove a channel (send port) link (asynchronous)
1074unlinkPortAsync :: SendPort a -> Process ()
1075unlinkPortAsync (SendPort cid) =
1076 sendCtrlMsg Nothing . Unlink $ SendPortIdentifier cid
1078--------------------------------------------------------------------------------
1080--------------------------------------------------------------------------------
1082data SayMessage = SayMessage { sayTime :: UTCTime
1083 , sayProcess :: ProcessId
1084 , sayMessage :: String }
1087-- There is sadly no Show UTCTime instance
1088instance Show SayMessage where
1091 $ showString "SayMessage "
1092 . showString (formatTime defaultTimeLocale "%c" (sayTime msg))
1094 . showsPrec 11 (sayProcess msg) . showChar ' '
1095 . showsPrec 11 (sayMessage msg) . showChar ' '
1097instance Binary SayMessage where
1099 putUTCTime (sayTime s)
1102 get = SayMessage <$> getUTCTime <*> get <*> get
1104-- Sadly there is no Binary UTCTime instance
1105putUTCTime :: UTCTime -> Put
1106putUTCTime (UTCTime (ModifiedJulianDay day) tod) = do
1108 put (toRational tod)
1110getUTCTime :: Get UTCTime
1114 return $! UTCTime (ModifiedJulianDay day)
1119-- @say message@ sends a message of type 'SayMessage' with the current time and
1120-- 'ProcessId' of the current process to the process registered as @logger@. By
1121-- default, this process simply sends the string to @stderr@. Individual Cloud
1122-- Haskell backends might replace this with a different logger process, however.
1123say :: String -> Process ()
1125 now <- liftIO getCurrentTime
1127 nsend "logger" (SayMessage now us string)
1129--------------------------------------------------------------------------------
1131--------------------------------------------------------------------------------
1133-- | Register a process with the local registry (synchronous). The name must not
1134-- already be registered. The process need not be on this node. A bad
1135-- registration will result in a 'ProcessRegistrationException'
1137-- The process to be registered does not have to be local itself.
1138register :: String -> ProcessId -> Process ()
1139register = registerImpl False
1141-- | Like 'register', but will replace an existing registration.
1142-- The name must already be registered.
1143reregister :: String -> ProcessId -> Process ()
1144reregister = registerImpl True
1146registerImpl :: Bool -> String -> ProcessId -> Process ()
1147registerImpl force label pid = do
1148 mynid <- getSelfNode
1149 sendCtrlMsg Nothing (Register label mynid (Just pid) force)
1151 [ matchIf (\(RegisterReply label' _ _) -> label == label')
1152 (\(RegisterReply _ ok owner) -> handleRegistrationReply label ok owner)
1155-- | Register a process with a remote registry (asynchronous).
1157-- The process to be registered does not have to live on the same remote node.
1158-- Reply wil come in the form of a 'RegisterReply' message
1160-- See comments in 'whereisRemoteAsync'
1161registerRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
1162registerRemoteAsync nid label pid = do
1164 sendCtrlMsg (if nid == here then Nothing else Just nid)
1165 (Register label nid (Just pid) False)
1167reregisterRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
1168reregisterRemoteAsync nid label pid =
1169 sendCtrlMsg (Just nid) (Register label nid (Just pid) True)
1171-- | Remove a process from the local registry (asynchronous).
1172-- This version will wait until a response is gotten from the
1173-- management process. The name must already be registered.
1174unregister :: String -> Process ()
1175unregister label = do
1176 mynid <- getSelfNode
1177 sendCtrlMsg Nothing (Register label mynid Nothing False)
1179 [ matchIf (\(RegisterReply label' _ _) -> label == label')
1180 (\(RegisterReply _ ok owner) -> handleRegistrationReply label ok owner)
1183-- | Deal with the result from an attempted registration or unregistration
1184-- by throwing an exception if necessary
1185handleRegistrationReply :: String -> Bool -> Maybe ProcessId -> Process ()
1186handleRegistrationReply label ok owner =
1188 throwM $ ProcessRegistrationException label owner
1190-- | Remove a process from a remote registry (asynchronous).
1192-- Reply wil come in the form of a 'RegisterReply' message
1194-- See comments in 'whereisRemoteAsync'
1195unregisterRemoteAsync :: NodeId -> String -> Process ()
1196unregisterRemoteAsync nid label =
1197 sendCtrlMsg (Just nid) (Register label nid Nothing False)
1199-- | Query the local process registry
1200whereis :: String -> Process (Maybe ProcessId)
1202 sendCtrlMsg Nothing (WhereIs label)
1203 receiveWait [ matchIf (\(WhereIsReply label' _) -> label == label')
1204 (\(WhereIsReply _ mPid) -> return mPid)
1207-- | Query a remote process registry (asynchronous)
1209-- Reply will come in the form of a 'WhereIsReply' message.
1211-- There is currently no synchronous version of 'whereisRemoteAsync': if
1212-- you implement one yourself, be sure to take into account that the remote
1213-- node might die or get disconnect before it can respond (i.e. you should
1214-- use 'monitorNode' and take appropriate action when you receive a
1215-- 'NodeMonitorNotification').
1216whereisRemoteAsync :: NodeId -> String -> Process ()
1217whereisRemoteAsync nid label = do
1219 sendCtrlMsg (if nid == here then Nothing else Just nid) (WhereIs label)
1221-- | Named send to a process in the local registry (asynchronous)
1222nsend :: Serializable a => String -> a -> Process ()
1224 sendCtrlMsg Nothing (NamedSend label (createUnencodedMessage msg))
1226-- | Named send to a process in the local registry (asynchronous).
1227-- This function makes /no/ attempt to serialize and (in the case when the
1228-- destination process resides on the same local node) therefore ensure that
1229-- the payload is fully evaluated before it is delivered.
1230unsafeNSend :: Serializable a => String -> a -> Process ()
1231unsafeNSend = Unsafe.nsend
1233-- | Named send to a process in a remote registry (asynchronous)
1234nsendRemote :: Serializable a => NodeId -> String -> a -> Process ()
1235nsendRemote nid label msg = do
1237 if here == nid then nsend label msg
1238 else sendCtrlMsg (Just nid) (NamedSend label (createMessage msg))
1240-- | Named send to a process in a remote registry (asynchronous)
1241-- This function makes /no/ attempt to serialize and (in the case when the
1242-- destination process resides on the same local node) therefore ensure that
1243-- the payload is fully evaluated before it is delivered.
1244unsafeNSendRemote :: Serializable a => NodeId -> String -> a -> Process ()
1245unsafeNSendRemote = Unsafe.nsendRemote
1247--------------------------------------------------------------------------------
1249--------------------------------------------------------------------------------
1251-- | Resolve a static value
1252unStatic :: Typeable a => Static a -> Process a
1254 rtable <- remoteTable . processNode <$> ask
1255 case Static.unstatic rtable static of
1256 Left err -> fail $ "Could not resolve static value: " ++ err
1259-- | Resolve a closure
1260unClosure :: Typeable a => Closure a -> Process a
1261unClosure closure = do
1262 rtable <- remoteTable . processNode <$> ask
1263 case Static.unclosure rtable closure of
1264 Left err -> fail $ "Could not resolve closure: " ++ err
1267--------------------------------------------------------------------------------
1269--------------------------------------------------------------------------------
1271-- | Cloud Haskell provides the illusion of connection-less, reliable, ordered
1272-- message passing. However, when network connections get disrupted this
1273-- illusion cannot always be maintained. Once a network connection breaks (even
1274-- temporarily) no further communication on that connection will be possible.
1275-- For example, if process A sends a message to process B, and A is then
1276-- notified (by monitor notification) that it got disconnected from B, A will
1277-- not be able to send any further messages to B, /unless/ A explicitly
1278-- indicates that it is acceptable to attempt to reconnect to B using the
1279-- Cloud Haskell 'reconnect' primitive.
1281-- Importantly, when A calls 'reconnect' it acknowledges that some messages to
1282-- B might have been lost. For instance, if A sends messages m1 and m2 to B,
1283-- then receives a monitor notification that its connection to B has been lost,
1284-- calls 'reconnect' and then sends m3, it is possible that B will receive m1
1285-- and m3 but not m2.
1287-- Note that 'reconnect' does not mean /reconnect now/ but rather /it is okay
1288-- to attempt to reconnect on the next send/. In particular, if no further
1289-- communication attempts are made to B then A can use reconnect to clean up
1290-- its connection to B.
1291reconnect :: ProcessId -> Process ()
1294 node <- processNode <$> ask
1295 liftIO $ disconnect node (ProcessIdentifier us) (ProcessIdentifier them)
1297-- | Reconnect to a sendport. See 'reconnect' for more information.
1298reconnectPort :: SendPort a -> Process ()
1299reconnectPort them = do
1301 node <- processNode <$> ask
1302 liftIO $ disconnect node (ProcessIdentifier us) (SendPortIdentifier (sendPortId them))
1304--------------------------------------------------------------------------------
1305-- Auxiliary functions --
1306--------------------------------------------------------------------------------
1308sendLocal :: (Serializable a) => ProcessId -> a -> Process ()
1310 sendCtrlMsg Nothing $ LocalSend to (createUnencodedMessage msg)
1312sendChanLocal :: (Serializable a) => SendPortId -> a -> Process ()
1313sendChanLocal spId msg =
1314 -- we *must* fully serialize/encode the message here, because
1315 -- attempting to use `unsafeCoerce' in the node controller
1316 -- won't work since we know nothing about the required type
1317 sendCtrlMsg Nothing $ LocalPortSend spId (createUnencodedMessage msg)
1319getMonitorRefFor :: Identifier -> Process MonitorRef
1320getMonitorRefFor ident = do
1322 liftIO $ modifyMVar (processState proc) $ \st -> do
1323 let counter = st ^. monitorCounter
1324 return ( monitorCounter ^: (+ 1) $ st
1325 , MonitorRef ident counter
1328getSpawnRef :: Process SpawnRef
1331 liftIO $ modifyMVar (processState proc) $ \st -> do
1332 let counter = st ^. spawnCounter
1333 return ( spawnCounter ^: (+ 1) $ st
1337-- | Monitor a process/node/channel
1338monitor' :: Identifier -> Process MonitorRef
1340 monitorRef <- getMonitorRefFor ident
1341 sendCtrlMsg Nothing $ Monitor monitorRef
1344-- | Link to a process/node/channel
1345link' :: Identifier -> Process ()
1346link' = sendCtrlMsg Nothing . Link
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list