git.iko.soy/distributed-process
on bbb3a2e help sign in
1349 lines 51 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE DeriveDataTypeable #-}
4{-# LANGUAGE DeriveFunctor #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE ExistentialQuantification #-}
7{-# LANGUAGE BangPatterns #-}
9-- | Cloud Haskell primitives
10--
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
15 send
16 , usend
17 , expect
18 -- * Channels
19 , newChan
20 , sendChan
21 , receiveChan
22 , mergePortsBiased
23 , mergePortsRR
24 -- * Unsafe messaging variants
25 , unsafeSend
26 , unsafeUSend
27 , unsafeSendChan
28 , unsafeNSend
29 , unsafeNSendRemote
30 -- * Advanced messaging
31 , Match
32 , receiveWait
33 , receiveTimeout
34 , match
35 , matchIf
36 , matchUnknown
37 , matchAny
38 , matchAnyIf
39 , matchChan
40 , matchSTM
41 , matchMessage
42 , matchMessageIf
43 , isEncoded
44 , wrapMessage
45 , unsafeWrapMessage
46 , unwrapMessage
47 , handleMessage
48 , handleMessageIf
49 , handleMessage_
50 , handleMessageIf_
51 , forward
52 , uforward
53 , delegate
54 , relay
55 , proxy
56 -- * Process management
57 , terminate
58 , ProcessTerminationException(..)
59 , die
60 , kill
61 , exit
62 , catchExit
63 , catchesExit
64 -- keep the exception constructor hidden, so that handling exit
65 -- reasons /must/ take place via the 'catchExit' family of primitives
66 , ProcessExitException()
67 , getSelfPid
68 , getSelfNode
69 , ProcessInfo(..)
70 , getProcessInfo
71 , NodeStats(..)
72 , getNodeStats
73 , getLocalNodeStats
74 -- * Monitoring and linking
75 , link
76 , unlink
77 , monitor
78 , unmonitor
79 , withMonitor
80 , withMonitor_
81 -- * Logging
82 , SayMessage(..)
83 , say
84 -- * Registry
85 , register
86 , reregister
87 , unregister
88 , whereis
89 , nsend
90 , registerRemoteAsync
91 , reregisterRemoteAsync
92 , unregisterRemoteAsync
93 , whereisRemoteAsync
94 , nsendRemote
95 -- * Closures
96 , unClosure
97 , unStatic
98 -- * Exception handling
99 , catch
100 , Handler(..)
101 , catches
102 , try
103 , mask
104 , mask_
105 , onException
106 , bracket
107 , bracket_
108 , finally
109 -- * Auxiliary API
110 , expectTimeout
111 , receiveChanTimeout
112 , spawnAsync
113 , linkNode
114 , linkPort
115 , unlinkNode
116 , unlinkPort
117 , monitorNode
118 , monitorPort
119 -- * Reconnecting
120 , reconnect
121 , reconnectPort
122 -- * Internal Exports
123 , sendCtrlMsg
124 ) where
126#if ! MIN_VERSION_base(4,6,0)
127import Prelude hiding (catch)
128#endif
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)
136#else
137import System.Locale (defaultTimeLocale)
138#endif
139import System.Timeout (timeout)
140import Control.Monad (when, void)
141import Control.Monad.Reader (ask)
142import Control.Monad.IO.Class (liftIO)
143import Control.Monad.Catch
144 ( Exception
145 , SomeException
146 , throwM
147 , fromException
148 )
149import qualified Control.Monad.Catch as Catch
150import Control.Applicative
151import Control.Distributed.Process.Internal.StrictMVar
152 ( StrictMVar
153 , modifyMVar
154 , modifyMVar_
155 )
156import Control.Concurrent.STM
157 ( STM
158 , TVar
159 , atomically
160 , orElse
161 , newTVar
162 , readTVar
163 , writeTVar
164 )
165import Control.Distributed.Process.Internal.CQueue
166 ( dequeue
167 , BlockSpec(..)
168 , MatchOn(..)
169 )
170import Control.Distributed.Process.Serializable (Serializable, fingerprint)
171import Data.Accessor ((^.), (^:), (^=))
172import Control.Distributed.Static
173 ( Static
174 , Closure
175 )
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
180 ( NodeId(..)
181 , ProcessId(..)
182 , LocalNode(..)
183 , LocalProcess(..)
184 , Process(..)
185 , Message(..)
186 , MonitorRef(..)
187 , SpawnRef(..)
188 , ProcessSignal(..)
189 , NodeMonitorNotification(..)
190 , ProcessMonitorNotification(..)
191 , monitorCounter
192 , spawnCounter
193 , SendPort(..)
194 , ReceivePort(..)
195 , channelCounter
196 , typedChannelWithId
197 , TypedChannel(..)
198 , SendPortId(..)
199 , Identifier(..)
200 , ProcessExitException(..)
201 , DiedReason(..)
202 , DidUnmonitor(..)
203 , DidUnlinkProcess(..)
204 , DidUnlinkNode(..)
205 , DidUnlinkPort(..)
206 , WhereIsReply(..)
207 , RegisterReply(..)
208 , ProcessRegistrationException(..)
209 , ProcessInfo(..)
210 , ProcessInfoNone(..)
211 , NodeStats(..)
212 , isEncoded
213 , createMessage
214 , createUnencodedMessage
215 , ImplicitReconnect( NoImplicitReconnect)
216 , LocalProcessState
217 , LocalSendPortId
218 , messageToPayload
219 )
220import Control.Distributed.Process.Internal.Messaging
221 ( sendMessage
222 , sendBinary
223 , sendPayload
224 , disconnect
225 , sendCtrlMsg
226 )
227import Control.Distributed.Process.Management.Internal.Types
228 ( MxEvent(..)
229 )
230import Control.Distributed.Process.Management.Internal.Trace.Types
231 ( traceEvent
232 )
233import Control.Distributed.Process.Internal.WeakTQueue
234 ( newTQueueIO
235 , readTQueue
236 , mkWeakTQueue
237 )
238import Prelude
240import Unsafe.Coerce
242--------------------------------------------------------------------------------
243-- Basic messaging --
244--------------------------------------------------------------------------------
246-- | Send a message
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.
250send them msg = do
251 proc <- ask
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)
261 NoImplicitReconnect
262 msg
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
271-- delivered.
272unsafeSend :: Serializable a => ProcessId -> a -> Process ()
273unsafeSend = Unsafe.send
275-- | Send a message unreliably.
276--
277-- Unlike 'send', this function is insensitive to 'reconnect'. It will
278-- try to send the message regardless of the history of connection failures
279-- between the nodes.
280--
281-- Message passing with 'usend' is ordered for a given sender and receiver
282-- if the messages arrive at all.
283--
284usend :: Serializable a => ProcessId -> a -> Process ()
285usend them msg = do
286 here <- getSelfNode
287 let there = processNodeId them
288 if here == there
289 then sendLocal them msg
290 else sendCtrlMsg (Just there) $ UnreliableSend (processLocalId them)
291 (createMessage msg)
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--------------------------------------------------------------------------------
305-- Channels --
306--------------------------------------------------------------------------------
308-- | Create a new typed channel
309newChan :: Serializable a => Process (SendPort a, ReceivePort a)
310newChan = do
311 proc <- ask
312 liftIO . modifyMVar (processState proc) $ \st -> do
313 let lcid = st ^. channelCounter
314 let cid = SendPortId { sendPortProcessId = processId proc
315 , sendPortLocalId = lcid
316 }
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)
324 $ st
325 , (sport, rport)
326 )
327 where
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
335 proc <- ask
336 let node = localNodeId (processNode proc)
337 destNode = processNodeId (sendPortProcessId cid) in do
338 case destNode == node of
339 True -> sendChanLocal cid msg
340 False -> do
341 liftIO $ sendBinary (processNode proc)
342 (ProcessIdentifier (processId proc))
343 (SendPortIdentifier cid)
344 NoImplicitReconnect
345 msg
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
350-- delivered.
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 $
364 receiveSTM ch
366-- | Merge a list of typed channels.
367--
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
374-- left-biased)
375mergePortsRR :: Serializable a => [ReceivePort a] -> Process (ReceivePort a)
376mergePortsRR = \ps -> do
377 psVar <- liftIO . atomically $ newTVar (map receiveSTM ps)
378 return $ ReceivePort (rr psVar)
379 where
380 rotate :: [a] -> [a]
381 rotate [] = []
382 rotate (x:xs) = xs ++ [x]
384 rr :: TVar [STM a] -> STM a
385 rr psVar = do
386 ps <- readTVar psVar
387 a <- foldr1 orElse ps
388 writeTVar psVar (rotate ps)
389 return a
391--------------------------------------------------------------------------------
392-- Advanced messaging --
393--------------------------------------------------------------------------------
395-- | Opaque type used in 'receiveWait' and 'receiveTimeout'
396newtype Match b = Match { unMatch :: MatchOn Message (Process b) }
397 deriving (Functor)
399-- | Test the matches in order against each message in the queue
400receiveWait :: [Match b] -> Process b
401receiveWait ms = do
402 queue <- processQueue <$> ask
403 mProc <- liftIO $ dequeue queue Blocking (map unMatch ms)
404 case mProc of
405 Just proc' -> proc'
406 Nothing -> die $ "System Invariant Violation: CQueue.hs returned `Nothing` "
407 ++ "in the absence of a timeout value."
409-- | Like 'receiveWait' but with a timeout.
410--
411-- If the timeout is zero do a non-blocking check for matching messages. A
412-- non-zero timeout is applied only when waiting for incoming messages (that is,
413-- /after/ we have checked the messages that are already in the mailbox).
414receiveTimeout :: Int -> [Match b] -> Process (Maybe b)
415receiveTimeout t ms = do
416 queue <- processQueue <$> ask
417 let blockSpec = if t == 0 then NonBlocking else Timeout t
418 mProc <- liftIO $ dequeue queue blockSpec (map unMatch ms)
419 case mProc of
420 Nothing -> return Nothing
421 Just proc -> Just <$> proc
423-- | Match on a typed channel
424matchChan :: ReceivePort a -> (a -> Process b) -> Match b
425matchChan p fn = Match $ MatchChan (fmap fn (receiveSTM p))
427-- | Match on an arbitrary STM action.
428--
429-- This rather unusaul /match primitive/ allows us to compose arbitrary STM
430-- actions with checks against our process' mailbox and/or any typed channel
431-- @ReceivePort@s we may hold.
432--
433-- This allows us to process multiple input streams /along with our mailbox/,
434-- in just the same way that 'matchChan' supports checking both the mailbox
435-- /and/ an arbitrary set of typed channels in one atomic transaction.
436--
437-- Note there are no ordering guarnatees with respect to these disparate input
438-- sources.
439--
440matchSTM :: STM a -> (a -> Process b) -> Match b
441matchSTM stm fn = Match $ MatchChan (fmap fn stm)
443-- | Match against any message of the right type
444match :: forall a b. Serializable a => (a -> Process b) -> Match b
445match = matchIf (const True)
447-- | Match against any message of the right type that satisfies a predicate
448matchIf :: forall a b. Serializable a => (a -> Bool) -> (a -> Process b) -> Match b
449matchIf c p = Match $ MatchMsg $ \msg ->
450 case messageFingerprint msg == fingerprint (undefined :: a) of
451 False -> Nothing
452 True -> case msg of
453 (UnencodedMessage _ m) ->
454 let m' = unsafeCoerce m :: a in
455 case (c m') of
456 True -> Just (p m')
457 False -> Nothing
458 (EncodedMessage _ _) ->
459 if (c decoded) then Just (p decoded) else Nothing
460 where
461 decoded :: a
462 -- Make sure the value is fully decoded so that we don't hang to
463 -- bytestrings when the process calling 'matchIf' doesn't process
464 -- the values immediately
465 !decoded = decode (messageEncoding msg)
467-- | Match against any message, regardless of the underlying (contained) type
468matchMessage :: (Message -> Process Message) -> Match Message
469matchMessage p = Match $ MatchMsg $ \msg -> Just (p msg)
471-- | Match against any message (regardless of underlying type) that satisfies a predicate
472matchMessageIf :: (Message -> Bool) -> (Message -> Process Message) -> Match Message
473matchMessageIf c p = Match $ MatchMsg $ \msg ->
474 case (c msg) of
475 True -> Just (p msg)
476 False -> Nothing
478-- | Forward a raw 'Message' to the given 'ProcessId'.
479forward :: Message -> ProcessId -> Process ()
480forward msg them = do
481 proc <- ask
482 let node = processNode proc
483 us = processId proc
484 nid = localNodeId node
485 destNode = (processNodeId them) in do
486 case destNode == nid of
487 True -> sendCtrlMsg Nothing (LocalSend them msg)
488 False -> liftIO $ sendPayload (processNode proc)
489 (ProcessIdentifier (processId proc))
490 (ProcessIdentifier them)
491 NoImplicitReconnect
492 (messageToPayload msg)
493 -- We do not fire the trace event until after the sending is complete;
494 -- In the remote case, 'sendMessage' can block in the networking stack.
495 liftIO $ traceEvent (localEventBus node)
496 (MxSent them us msg)
498-- | Forward a raw 'Message' to the given 'ProcessId'.
499--
500-- Unlike 'forward', this function is insensitive to 'reconnect'. It will
501-- try to send the message regardless of the history of connection failures
502-- between the nodes.
503uforward :: Message -> ProcessId -> Process ()
504uforward msg them = do
505 proc <- ask
506 let node = processNode proc
507 us = processId proc
508 nid = localNodeId node
509 destNode = (processNodeId them) in do
510 case destNode == nid of
511 True -> sendCtrlMsg Nothing (LocalSend them msg)
512 False -> sendCtrlMsg (Just destNode) $ UnreliableSend (processLocalId them)
513 msg
514 -- We do not fire the trace event until after the sending is complete;
515 -- In the remote case, 'sendCtrlMsg' can block in the networking stack.
516 liftIO $ traceEvent (localEventBus node)
517 (MxSent them us msg)
519-- | Wrap a 'Serializable' value in a 'Message'. Note that 'Message's are
520-- 'Serializable' - like the datum they contain - but also note, deserialising
521-- such a 'Message' will yield a 'Message', not the type within it! To obtain the
522-- wrapped datum, use 'unwrapMessage' or 'handleMessage' with a specific type.
523--
524-- @
525-- do
526-- self <- getSelfPid
527-- send self (wrapMessage "blah")
528-- Nothing <- expectTimeout 1000000 :: Process (Maybe String)
529-- (Just m) <- expectTimeout 1000000 :: Process (Maybe Message)
530-- (Just "blah") <- unwrapMessage m :: Process (Maybe String)
531-- @
532--
533wrapMessage :: Serializable a => a -> Message
534wrapMessage = createUnencodedMessage -- see [note Serializable UnencodedMessage]
536-- | This is the /unsafe/ variant of 'wrapMessage'. See
537-- "Control.Distributed.Process.UnsafePrimitives" for details.
538unsafeWrapMessage :: Serializable a => a -> Message
539unsafeWrapMessage = Unsafe.wrapMessage
541-- [note Serializable UnencodedMessage]
542-- if we attempt to serialise an UnencodedMessage, it will be converted to an
543-- EncodedMessage first, so we're ok here. See 'messageToPayload' in
544-- Primitives.hs for the gory details
546-- | Attempt to unwrap a raw 'Message'.
547-- If the type of the decoded message payload matches the expected type, the
548-- value will be returned with @Just@, otherwise @Nothing@ indicates the types
549-- do not match.
550--
551-- This expression, for example, will evaluate to @Nothing@
552-- > unwrapMessage (wrapMessage "foobar") :: Process (Maybe Int)
553--
554-- Whereas this expression, will yield @Just "foo"@
555-- > unwrapMessage (wrapMessage "foo") :: Process (Maybe String)
556--
557unwrapMessage :: forall m a. (Monad m, Serializable a) => Message -> m (Maybe a)
558unwrapMessage msg =
559 case messageFingerprint msg == fingerprint (undefined :: a) of
560 False -> return Nothing :: m (Maybe a)
561 True -> case msg of
562 (UnencodedMessage _ ms) ->
563 let ms' = unsafeCoerce ms :: a
564 in return (Just ms')
565 (EncodedMessage _ _) ->
566 return (Just (decoded))
567 where
568 decoded :: a -- note [decoding]
569 !decoded = decode (messageEncoding msg)
571-- | Attempt to handle a raw 'Message'.
572-- If the type of the message matches the type of the first argument to
573-- the supplied expression, then the message will be decoded and the expression
574-- evaluated against its value. If this runtime type checking fails however,
575-- @Nothing@ will be returned to indicate the fact. If the check succeeds and
576-- evaluation proceeds, the resulting value with be wrapped with @Just@.
577--
578-- Intended for use in `catchesExit` and `matchAny` primitives.
579--
580handleMessage :: forall m a b. (Monad m, Serializable a)
581 => Message -> (a -> m b) -> m (Maybe b)
582handleMessage msg proc = handleMessageIf msg (const True) proc
584-- | Conditionally handle a raw 'Message'.
585-- If the predicate @(a -> Bool)@ evaluates to @True@, invokes the supplied
586-- handler, other returns @Nothing@ to indicate failure. See 'handleMessage'
587-- for further information about runtime type checking.
588--
589handleMessageIf :: forall m a b . (Monad m, Serializable a)
590 => Message
591 -> (a -> Bool)
592 -> (a -> m b)
593 -> m (Maybe b)
594handleMessageIf msg c proc = do
595 case messageFingerprint msg == fingerprint (undefined :: a) of
596 False -> return Nothing :: m (Maybe b)
597 True -> case msg of
598 (UnencodedMessage _ ms) ->
599 let ms' = unsafeCoerce ms :: a in
600 case (c ms') of
601 True -> do { r <- proc ms'; return (Just r) }
602 False -> return Nothing :: m (Maybe b)
603 (EncodedMessage _ _) ->
604 case (c decoded) of
605 True -> do { r <- proc (decoded :: a); return (Just r) }
606 False -> return Nothing :: m (Maybe b)
607 where
608 decoded :: a -- note [decoding]
609 !decoded = decode (messageEncoding msg)
611-- | As 'handleMessage' but ignores result, which is useful if you don't
612-- care whether or not the handler succeeded.
613--
614handleMessage_ :: forall m a . (Monad m, Serializable a)
615 => Message -> (a -> m ()) -> m ()
616handleMessage_ msg proc = handleMessageIf_ msg (const True) proc
618-- | Conditional version of 'handleMessage_'.
619--
620handleMessageIf_ :: forall m a . (Monad m, Serializable a)
621 => Message
622 -> (a -> Bool)
623 -> (a -> m ())
624 -> m ()
625handleMessageIf_ msg c proc = handleMessageIf msg c proc >> return ()
627-- | Match against an arbitrary message. 'matchAny' removes the first available
628-- message from the process mailbox. To handle arbitrary /raw/ messages once
629-- removed from the mailbox, see 'handleMessage' and 'unwrapMessage'.
630--
631matchAny :: forall b. (Message -> Process b) -> Match b
632matchAny p = Match $ MatchMsg $ \msg -> Just (p msg)
634-- | Match against an arbitrary message. Intended for use with 'handleMessage'
635-- and 'unwrapMessage', this function /only/ removes a message from the process
636-- mailbox, /if/ the supplied condition matches. The success (or failure) of
637-- runtime type checks deferred to @handleMessage@ and friends is irrelevant
638-- here, i.e., if the condition evaluates to @True@ then the message will
639-- be removed from the process mailbox and decoded, but that does /not/
640-- guarantee that an expression passed to @handleMessage@ will pass the
641-- runtime type checks and therefore be evaluated.
642--
643matchAnyIf :: forall a b. (Serializable a)
644 => (a -> Bool)
645 -> (Message -> Process b)
646 -> Match b
647matchAnyIf c p = Match $ MatchMsg $ \msg ->
648 case messageFingerprint msg == fingerprint (undefined :: a) of
649 True | check -> Just (p msg)
650 where
651 check :: Bool
652 !check =
653 case msg of
654 (EncodedMessage _ _) -> c decoded
655 (UnencodedMessage _ m') -> c (unsafeCoerce m')
657 decoded :: a -- note [decoding]
658 !decoded = decode (messageEncoding msg)
659 _ -> Nothing
661{- note [decoding]
662For an EncodedMessage, we need to ensure the value is fully decoded so that
663we don't hang to bytestrings if the calling process doesn't evaluate
664immediately. For UnencodedMessage we know (because the fingerprint comparison
665succeeds) that unsafeCoerce will not fail.
666-}
668-- | Remove any message from the queue
669matchUnknown :: Process b -> Match b
670matchUnknown p = Match $ MatchMsg (const (Just p))
672-- | Receives messages and forwards them to @pid@ if @p msg == True@.
673delegate :: ProcessId -> (Message -> Bool) -> Process ()
674delegate pid p = do
675 receiveWait [
676 matchAny (\m -> case (p m) of
677 True -> forward m pid
678 False -> return ())
679 ]
680 delegate pid p
682-- | A straight relay that forwards all messages to the supplied pid.
683relay :: ProcessId -> Process ()
684relay !pid = receiveWait [ matchAny (\m -> forward m pid) ] >> relay pid
686-- | Proxies @pid@ and forwards messages whenever @proc@ evaluates to @True@.
687-- Unlike 'delegate' the predicate @proc@ runs in the 'Process' monad, allowing
688-- for richer proxy behaviour. If @proc@ returns @False@ or the /runtime type check/
689-- fails, no action is taken and the proxy process will continue running.
690proxy :: Serializable a => ProcessId -> (a -> Process Bool) -> Process ()
691proxy pid proc = do
692 receiveWait [
693 matchAny (\m -> do
694 next <- handleMessage m proc
695 case next of
696 Just True -> forward m pid
697 Just False -> return () -- explicitly ignored
698 Nothing -> return ()) -- un-routable
699 ]
700 proxy pid proc
702--------------------------------------------------------------------------------
703-- Process management --
704--------------------------------------------------------------------------------
706-- | Thrown by 'terminate'
707data ProcessTerminationException = ProcessTerminationException
708 deriving (Show, Typeable)
710instance Exception ProcessTerminationException
712-- | Terminate immediately (throws a ProcessTerminationException)
713terminate :: Process a
714terminate = throwM ProcessTerminationException
716-- [Issue #110]
717-- | Die immediately - throws a 'ProcessExitException' with the given @reason@.
718die :: Serializable a => a -> Process b
719die reason = do
720-- NOTE: We do /not/ want to use UnencodedMessage here, as the exception
721-- could be decoded by a handler passed to 'catchExit', re-thrown or even
722-- passed to another process via the tracing mechanism.
723 pid <- getSelfPid
724 throwM (ProcessExitException pid (createMessage reason))
726-- | Forceful request to kill a process. Where 'exit' provides an exception
727-- that can be caught and handled, 'kill' throws an unexposed exception type
728-- which cannot be handled explicitly (by type).
729kill :: ProcessId -> String -> Process ()
730-- NOTE: We send the message to our local node controller, which will then
731-- forward it to a remote node controller (if applicable). Sending it directly
732-- to a remote node controller means that that the message may overtake a
733-- 'monitor' or 'link' request.
734kill them reason = sendCtrlMsg Nothing (Kill them reason)
736-- | Graceful request to exit a process. Throws 'ProcessExitException' with the
737-- supplied @reason@ encoded as a message. Any /exit signal/ raised in this
738-- manner can be handled using the 'catchExit' family of functions.
739exit :: Serializable a => ProcessId -> a -> Process ()
740-- NOTE: We send the message to our local node controller, which will then
741-- forward it to a remote node controller (if applicable). Sending it directly
742-- to a remote node controller means that that the message may overtake a
743-- 'monitor' or 'link' request.
744exit them reason = sendCtrlMsg Nothing (Exit them (createMessage reason))
746-- | Catches 'ProcessExitException'. The handler will not be applied unless its
747-- type matches the encoded data stored in the exception (see the /reason/
748-- argument given to the 'exit' primitive). If the handler cannot be applied,
749-- the exception will be re-thrown.
750--
751-- To handle 'ProcessExitException' without regard for /reason/, see 'catch'.
752-- To handle multiple /reasons/ of differing types, see 'catchesExit'.
753catchExit :: forall a b . (Show a, Serializable a)
754 => Process b
755 -> (ProcessId -> a -> Process b)
756 -> Process b
757catchExit act exitHandler = Catch.catch act handleExit
758 where
759 handleExit ex@(ProcessExitException from msg) =
760 if messageFingerprint msg == fingerprint (undefined :: a)
761 then exitHandler from decoded
762 else throwM ex
763 where
764 decoded :: a
765 -- Make sure the value is fully decoded so that we don't hang to
766 -- bytestrings if the caller doesn't use the value immediately
767 !decoded = decode (messageEncoding msg)
769-- | Lift 'Control.Exception.catches' (almost).
770--
771-- As 'ProcessExitException' stores the exit @reason@ as a typed, encoded
772-- message, a handler must accept inputs of the expected type. In order to
773-- handle a list of potentially different handlers (and therefore input types),
774-- a handler passed to 'catchesExit' must accept 'Message' and return
775-- @Maybe@ (i.e., @Just p@ if it handled the exit reason, otherwise @Nothing@).
776--
777-- See 'maybeHandleMessage' and 'Message' for more details.
778catchesExit :: Process b
779 -> [(ProcessId -> Message -> (Process (Maybe b)))]
780 -> Process b
781catchesExit act handlers = Catch.catch act ((flip handleExit) handlers)
782 where
783 handleExit :: ProcessExitException
784 -> [(ProcessId -> Message -> Process (Maybe b))]
785 -> Process b
786 handleExit ex [] = throwM ex
787 handleExit ex@(ProcessExitException from msg) (h:hs) = do
788 r <- h from msg
789 case r of
790 Nothing -> handleExit ex hs
791 Just p -> return p
793-- | Our own process ID
794getSelfPid :: Process ProcessId
795getSelfPid = processId <$> ask
797-- | Get the node ID of our local node
798getSelfNode :: Process NodeId
799getSelfNode = localNodeId . processNode <$> ask
802-- | Get statistics about the specified node
803getNodeStats :: NodeId -> Process (Either DiedReason NodeStats)
804getNodeStats nid = do
805 selfNode <- getSelfNode
806 if nid == selfNode
807 then Right `fmap` getLocalNodeStats -- optimisation
808 else getNodeStatsRemote selfNode
809 where
810 getNodeStatsRemote :: NodeId -> Process (Either DiedReason NodeStats)
811 getNodeStatsRemote selfNode = do
812 sendCtrlMsg (Just nid) $ GetNodeStats selfNode
813 bracket (monitorNode nid) unmonitor $ \mRef ->
814 receiveWait [ match (\(stats :: NodeStats) -> return $ Right stats)
815 , matchIf (\(NodeMonitorNotification ref _ _) -> ref == mRef)
816 (\(NodeMonitorNotification _ _ dr) -> return $ Left dr)
817 ]
819-- | Get statistics about our local node
820getLocalNodeStats :: Process NodeStats
821getLocalNodeStats = do
822 self <- getSelfNode
823 sendCtrlMsg Nothing $ GetNodeStats self
824 receiveWait [ match (\(stats :: NodeStats) -> return stats) ]
826-- | Get information about the specified process
827getProcessInfo :: ProcessId -> Process (Maybe ProcessInfo)
828getProcessInfo pid =
829 let them = processNodeId pid in do
830 us <- getSelfNode
831 dest <- mkNode them us
832 sendCtrlMsg dest $ GetInfo pid
833 receiveWait [
834 match (\(p :: ProcessInfo) -> return $ Just p)
835 , match (\(_ :: ProcessInfoNone) -> return Nothing)
836 ]
837 where mkNode :: NodeId -> NodeId -> Process (Maybe NodeId)
838 mkNode them us = case them == us of
839 True -> return Nothing
840 _ -> return $ Just them
842--------------------------------------------------------------------------------
843-- Monitoring and linking --
844--------------------------------------------------------------------------------
846-- | Link to a remote process (asynchronous)
847--
848-- When process A links to process B (that is, process A calls
849-- @link pidB@) then an asynchronous exception will be thrown to process A
850-- when process B terminates (normally or abnormally), or when process A gets
851-- disconnected from process B. Although it is /technically/ possible to catch
852-- these exceptions, chances are if you find yourself trying to do so you should
853-- probably be using 'monitor' rather than 'link'. In particular, code such as
854--
855-- > link pidB -- Link to process B
856-- > expect -- Wait for a message from process B
857-- > unlink pidB -- Unlink again
858--
859-- doesn't quite do what one might expect: if process B sends a message to
860-- process A, and /subsequently terminates/, then process A might or might not
861-- be terminated too, depending on whether the exception is thrown before or
862-- after the 'unlink' (i.e., this code has a race condition).
863--
864-- Linking is all-or-nothing: A is either linked to B, or it's not. A second
865-- call to 'link' has no effect.
866--
867-- Note that 'link' provides unidirectional linking (see 'spawnSupervised').
868-- Linking makes no distinction between normal and abnormal termination of
869-- the remote process.
870link :: ProcessId -> Process ()
871link = sendCtrlMsg Nothing . Link . ProcessIdentifier
873-- | Monitor another process (asynchronous)
874--
875-- When process A monitors process B (that is, process A calls
876-- @monitor pidB@) then process A will receive a 'ProcessMonitorNotification'
877-- when process B terminates (normally or abnormally), or when process A gets
878-- disconnected from process B. You receive this message like any other (using
879-- 'expect'); the notification includes a reason ('DiedNormal', 'DiedException',
880-- 'DiedDisconnect', etc.).
881--
882-- Every call to 'monitor' returns a new monitor reference 'MonitorRef'; if
883-- multiple monitors are set up, multiple notifications will be delivered
884-- and monitors can be disabled individually using 'unmonitor'.
885monitor :: ProcessId -> Process MonitorRef
886monitor = monitor' . ProcessIdentifier
888-- | Establishes temporary monitoring of another process.
889--
890-- @withMonitor pid code@ sets up monitoring of @pid@ for the duration
891-- of @code@. Note: although monitoring is no longer active when
892-- @withMonitor@ returns, there might still be unreceived monitor
893-- messages in the queue.
894--
895withMonitor :: ProcessId -> (MonitorRef -> Process a) -> Process a
896withMonitor pid = bracket (monitor pid) unmonitor
898-- | Establishes temporary monitoring of another process.
899--
900-- @withMonitor_ pid code@ sets up monitoring of @pid@ for the duration
901-- of @code@. Note: although monitoring is no longer active when
902-- @withMonitor_@ returns, there might still be unreceived monitor
903-- messages in the queue.
904--
905-- Since 0.6.1
906withMonitor_ :: ProcessId -> Process a -> Process a
907withMonitor_ p = withMonitor p . const
909-- | Remove a link
910--
911-- This is synchronous in the sense that once it returns you are guaranteed
912-- that no exception will be raised if the remote process dies. However, it is
913-- asynchronous in the sense that we do not wait for a response from the remote
914-- node.
915unlink :: ProcessId -> Process ()
916unlink pid = do
917 unlinkAsync pid
918 receiveWait [ matchIf (\(DidUnlinkProcess pid') -> pid' == pid)
919 (\_ -> return ())
920 ]
922-- | Remove a node link
923--
924-- This has the same synchronous/asynchronous nature as 'unlink'.
925unlinkNode :: NodeId -> Process ()
926unlinkNode nid = do
927 unlinkNodeAsync nid
928 receiveWait [ matchIf (\(DidUnlinkNode nid') -> nid' == nid)
929 (\_ -> return ())
930 ]
932-- | Remove a channel (send port) link
933--
934-- This has the same synchronous/asynchronous nature as 'unlink'.
935unlinkPort :: SendPort a -> Process ()
936unlinkPort sport = do
937 unlinkPortAsync sport
938 receiveWait [ matchIf (\(DidUnlinkPort cid) -> cid == sendPortId sport)
939 (\_ -> return ())
940 ]
942-- | Remove a monitor
943--
944-- This has the same synchronous/asynchronous nature as 'unlink'.
945--
946-- ProcessMonitorNotification messages for the given MonitorRef are removed from
947-- the mailbox.
948unmonitor :: MonitorRef -> Process ()
949unmonitor ref = do
950 unmonitorAsync ref
951 receiveWait [ matchIf (\(DidUnmonitor ref') -> ref' == ref)
952 (\_ -> return ())
953 ]
954 -- Discard the notification if any. With the current NC implementation at most
955 -- one notification is in the mailbox for any given ref.
956 void $ receiveTimeout 0
957 [ matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == ref)
958 (const $ return ())
959 ]
961--------------------------------------------------------------------------------
962-- Exception handling --
963--------------------------------------------------------------------------------
965-- | Lift 'Control.Exception.catch'
966catch :: Exception e => Process a -> (e -> Process a) -> Process a
967catch = Catch.catch
968{-# DEPRECATED catch "Use Control.Monad.Catch.catch instead" #-}
970-- | Lift 'Control.Exception.try'
971try :: Exception e => Process a -> Process (Either e a)
972try = Catch.try
973{-# DEPRECATED try "Use Control.Monad.Catch.try instead" #-}
975-- | Lift 'Control.Exception.mask'
976mask :: ((forall a. Process a -> Process a) -> Process b) -> Process b
977mask = Catch.mask
978{-# DEPRECATED mask "Use Control.Monad.Catch.mask_ instead" #-}
980-- | Lift 'Control.Exception.mask_'
981mask_ :: Process a -> Process a
982mask_ = Catch.mask_
983{-# DEPRECATED mask_ "Use Control.Monad.Catch.mask_ instead" #-}
985-- | Lift 'Control.Exception.onException'
986onException :: Process a -> Process b -> Process a
987onException = Catch.onException
988{-# DEPRECATED onException "Use Control.Monad.Catch.onException instead" #-}
990-- | Lift 'Control.Exception.bracket'
991bracket :: Process a -> (a -> Process b) -> (a -> Process c) -> Process c
992bracket = Catch.bracket
993{-# DEPRECATED bracket "Use Control.Monad.Catch.bracket instead" #-}
995-- | Lift 'Control.Exception.bracket_'
996bracket_ :: Process a -> Process b -> Process c -> Process c
997bracket_ = Catch.bracket_
998{-# DEPRECATED bracket_ "Use Control.Monad.Catch.bracket_ instead" #-}
1000-- | Lift 'Control.Exception.finally'
1001finally :: Process a -> Process b -> Process a
1002finally = Catch.finally
1003{-# DEPRECATED finally "Use Control.Monad.Catch.finally instead" #-}
1005-- | You need this when using 'catches'
1006data Handler a = forall e . Exception e => Handler (e -> Process a)
1008instance Functor Handler where
1009 fmap f (Handler h) = Handler (fmap f . h)
1011-- | Lift 'Control.Exception.catches'
1012catches :: Process a -> [Handler a] -> Process a
1013catches proc handlers = proc `Catch.catch` catchesHandler handlers
1015catchesHandler :: [Handler a] -> SomeException -> Process a
1016catchesHandler handlers e = foldr tryHandler (throwM e) handlers
1017 where tryHandler (Handler handler) res
1018 = case fromException e of
1019 Just e' -> handler e'
1020 Nothing -> res
1022--------------------------------------------------------------------------------
1023-- Auxiliary API --
1024--------------------------------------------------------------------------------
1026-- | Like 'expect' but with a timeout
1027expectTimeout :: forall a. Serializable a => Int -> Process (Maybe a)
1028expectTimeout n = receiveTimeout n [match return]
1030-- | Asynchronous version of 'spawn'
1032-- ('spawn' is defined in terms of 'spawnAsync' and 'expect')
1033spawnAsync :: NodeId -> Closure (Process ()) -> Process SpawnRef
1034spawnAsync nid proc = do
1035 spawnRef <- getSpawnRef
1036 node <- getSelfNode
1037 if nid == node
1038 then sendCtrlMsg Nothing $ Spawn proc spawnRef
1039 else sendCtrlMsg (Just nid) $ Spawn proc spawnRef
1040 return spawnRef
1042-- | Monitor a node (asynchronous)
1043monitorNode :: NodeId -> Process MonitorRef
1044monitorNode =
1045 monitor' . NodeIdentifier
1047-- | Monitor a typed channel (asynchronous)
1048monitorPort :: forall a. Serializable a => SendPort a -> Process MonitorRef
1049monitorPort (SendPort cid) =
1050 monitor' (SendPortIdentifier cid)
1052-- | Remove a monitor (asynchronous)
1053unmonitorAsync :: MonitorRef -> Process ()
1054unmonitorAsync =
1055 sendCtrlMsg Nothing . Unmonitor
1057-- | Link to a node (asynchronous)
1058linkNode :: NodeId -> Process ()
1059linkNode = link' . NodeIdentifier
1061-- | Link to a channel (asynchronous)
1062linkPort :: SendPort a -> Process ()
1063linkPort (SendPort cid) =
1064 link' (SendPortIdentifier cid)
1066-- | Remove a process link (asynchronous)
1067unlinkAsync :: ProcessId -> Process ()
1068unlinkAsync =
1069 sendCtrlMsg Nothing . Unlink . ProcessIdentifier
1071-- | Remove a node link (asynchronous)
1072unlinkNodeAsync :: NodeId -> Process ()
1073unlinkNodeAsync =
1074 sendCtrlMsg Nothing . Unlink . NodeIdentifier
1076-- | Remove a channel (send port) link (asynchronous)
1077unlinkPortAsync :: SendPort a -> Process ()
1078unlinkPortAsync (SendPort cid) =
1079 sendCtrlMsg Nothing . Unlink $ SendPortIdentifier cid
1081--------------------------------------------------------------------------------
1082-- Logging --
1083--------------------------------------------------------------------------------
1085data SayMessage = SayMessage { sayTime :: UTCTime
1086 , sayProcess :: ProcessId
1087 , sayMessage :: String }
1088 deriving (Typeable)
1090-- There is sadly no Show UTCTime instance
1091instance Show SayMessage where
1092 showsPrec p msg =
1093 showParen (p >= 11)
1094 $ showString "SayMessage "
1095 . showString (formatTime defaultTimeLocale "%c" (sayTime msg))
1096 . showChar ' '
1097 . showsPrec 11 (sayProcess msg) . showChar ' '
1098 . showsPrec 11 (sayMessage msg) . showChar ' '
1100instance Binary SayMessage where
1101 put s = do
1102 putUTCTime (sayTime s)
1103 put (sayProcess s)
1104 put (sayMessage s)
1105 get = SayMessage <$> getUTCTime <*> get <*> get
1107-- Sadly there is no Binary UTCTime instance
1108putUTCTime :: UTCTime -> Put
1109putUTCTime (UTCTime (ModifiedJulianDay day) tod) = do
1110 put day
1111 put (toRational tod)
1113getUTCTime :: Get UTCTime
1114getUTCTime = do
1115 day <- get
1116 tod <- get
1117 return $! UTCTime (ModifiedJulianDay day)
1118 (fromRational tod)
1120-- | Log a string
1122-- @say message@ sends a message of type 'SayMessage' with the current time and
1123-- 'ProcessId' of the current process to the process registered as @logger@. By
1124-- default, this process simply sends the string to @stderr@. Individual Cloud
1125-- Haskell backends might replace this with a different logger process, however.
1126say :: String -> Process ()
1127say string = do
1128 now <- liftIO getCurrentTime
1129 us <- getSelfPid
1130 nsend "logger" (SayMessage now us string)
1132--------------------------------------------------------------------------------
1133-- Registry --
1134--------------------------------------------------------------------------------
1136-- | Register a process with the local registry (synchronous). The name must not
1137-- already be registered. The process need not be on this node. A bad
1138-- registration will result in a 'ProcessRegistrationException'
1140-- The process to be registered does not have to be local itself.
1141register :: String -> ProcessId -> Process ()
1142register = registerImpl False
1144-- | Like 'register', but will replace an existing registration.
1145-- The name must already be registered.
1146reregister :: String -> ProcessId -> Process ()
1147reregister = registerImpl True
1149registerImpl :: Bool -> String -> ProcessId -> Process ()
1150registerImpl force label pid = do
1151 mynid <- getSelfNode
1152 sendCtrlMsg Nothing (Register label mynid (Just pid) force)
1153 receiveWait
1154 [ matchIf (\(RegisterReply label' _ _) -> label == label')
1155 (\(RegisterReply _ ok owner) -> handleRegistrationReply label ok owner)
1158-- | Register a process with a remote registry (asynchronous).
1160-- The process to be registered does not have to live on the same remote node.
1161-- Reply wil come in the form of a 'RegisterReply' message
1163-- See comments in 'whereisRemoteAsync'
1164registerRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
1165registerRemoteAsync nid label pid = do
1166 here <- getSelfNode
1167 sendCtrlMsg (if nid == here then Nothing else Just nid)
1168 (Register label nid (Just pid) False)
1170reregisterRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
1171reregisterRemoteAsync nid label pid =
1172 sendCtrlMsg (Just nid) (Register label nid (Just pid) True)
1174-- | Remove a process from the local registry (asynchronous).
1175-- This version will wait until a response is gotten from the
1176-- management process. The name must already be registered.
1177unregister :: String -> Process ()
1178unregister label = do
1179 mynid <- getSelfNode
1180 sendCtrlMsg Nothing (Register label mynid Nothing False)
1181 receiveWait
1182 [ matchIf (\(RegisterReply label' _ _) -> label == label')
1183 (\(RegisterReply _ ok owner) -> handleRegistrationReply label ok owner)
1186-- | Deal with the result from an attempted registration or unregistration
1187-- by throwing an exception if necessary
1188handleRegistrationReply :: String -> Bool -> Maybe ProcessId -> Process ()
1189handleRegistrationReply label ok owner =
1190 when (not ok) $
1191 throwM $ ProcessRegistrationException label owner
1193-- | Remove a process from a remote registry (asynchronous).
1195-- Reply wil come in the form of a 'RegisterReply' message
1197-- See comments in 'whereisRemoteAsync'
1198unregisterRemoteAsync :: NodeId -> String -> Process ()
1199unregisterRemoteAsync nid label =
1200 sendCtrlMsg (Just nid) (Register label nid Nothing False)
1202-- | Query the local process registry
1203whereis :: String -> Process (Maybe ProcessId)
1204whereis label = do
1205 sendCtrlMsg Nothing (WhereIs label)
1206 receiveWait [ matchIf (\(WhereIsReply label' _) -> label == label')
1207 (\(WhereIsReply _ mPid) -> return mPid)
1210-- | Query a remote process registry (asynchronous)
1212-- Reply will come in the form of a 'WhereIsReply' message.
1214-- There is currently no synchronous version of 'whereisRemoteAsync': if
1215-- you implement one yourself, be sure to take into account that the remote
1216-- node might die or get disconnect before it can respond (i.e. you should
1217-- use 'monitorNode' and take appropriate action when you receive a
1218-- 'NodeMonitorNotification').
1219whereisRemoteAsync :: NodeId -> String -> Process ()
1220whereisRemoteAsync nid label = do
1221 here <- getSelfNode
1222 sendCtrlMsg (if nid == here then Nothing else Just nid) (WhereIs label)
1224-- | Named send to a process in the local registry (asynchronous)
1225nsend :: Serializable a => String -> a -> Process ()
1226nsend label msg =
1227 sendCtrlMsg Nothing (NamedSend label (createUnencodedMessage msg))
1229-- | Named send to a process in the local registry (asynchronous).
1230-- This function makes /no/ attempt to serialize and (in the case when the
1231-- destination process resides on the same local node) therefore ensure that
1232-- the payload is fully evaluated before it is delivered.
1233unsafeNSend :: Serializable a => String -> a -> Process ()
1234unsafeNSend = Unsafe.nsend
1236-- | Named send to a process in a remote registry (asynchronous)
1237nsendRemote :: Serializable a => NodeId -> String -> a -> Process ()
1238nsendRemote nid label msg = do
1239 here <- getSelfNode
1240 if here == nid then nsend label msg
1241 else sendCtrlMsg (Just nid) (NamedSend label (createMessage msg))
1243-- | Named send to a process in a remote registry (asynchronous)
1244-- This function makes /no/ attempt to serialize and (in the case when the
1245-- destination process resides on the same local node) therefore ensure that
1246-- the payload is fully evaluated before it is delivered.
1247unsafeNSendRemote :: Serializable a => NodeId -> String -> a -> Process ()
1248unsafeNSendRemote = Unsafe.nsendRemote
1250--------------------------------------------------------------------------------
1251-- Closures --
1252--------------------------------------------------------------------------------
1254-- | Resolve a static value
1255unStatic :: Typeable a => Static a -> Process a
1256unStatic static = do
1257 rtable <- remoteTable . processNode <$> ask
1258 case Static.unstatic rtable static of
1259 Left err -> fail $ "Could not resolve static value: " ++ err
1260 Right x -> return x
1262-- | Resolve a closure
1263unClosure :: Typeable a => Closure a -> Process a
1264unClosure closure = do
1265 rtable <- remoteTable . processNode <$> ask
1266 case Static.unclosure rtable closure of
1267 Left err -> fail $ "Could not resolve closure: " ++ err
1268 Right x -> return x
1270--------------------------------------------------------------------------------
1271-- Reconnecting --
1272--------------------------------------------------------------------------------
1274-- | Cloud Haskell provides the illusion of connection-less, reliable, ordered
1275-- message passing. However, when network connections get disrupted this
1276-- illusion cannot always be maintained. Once a network connection breaks (even
1277-- temporarily) no further communication on that connection will be possible.
1278-- For example, if process A sends a message to process B, and A is then
1279-- notified (by monitor notification) that it got disconnected from B, A will
1280-- not be able to send any further messages to B, /unless/ A explicitly
1281-- indicates that it is acceptable to attempt to reconnect to B using the
1282-- Cloud Haskell 'reconnect' primitive.
1284-- Importantly, when A calls 'reconnect' it acknowledges that some messages to
1285-- B might have been lost. For instance, if A sends messages m1 and m2 to B,
1286-- then receives a monitor notification that its connection to B has been lost,
1287-- calls 'reconnect' and then sends m3, it is possible that B will receive m1
1288-- and m3 but not m2.
1290-- Note that 'reconnect' does not mean /reconnect now/ but rather /it is okay
1291-- to attempt to reconnect on the next send/. In particular, if no further
1292-- communication attempts are made to B then A can use reconnect to clean up
1293-- its connection to B.
1294reconnect :: ProcessId -> Process ()
1295reconnect them = do
1296 us <- getSelfPid
1297 node <- processNode <$> ask
1298 liftIO $ disconnect node (ProcessIdentifier us) (ProcessIdentifier them)
1300-- | Reconnect to a sendport. See 'reconnect' for more information.
1301reconnectPort :: SendPort a -> Process ()
1302reconnectPort them = do
1303 us <- getSelfPid
1304 node <- processNode <$> ask
1305 liftIO $ disconnect node (ProcessIdentifier us) (SendPortIdentifier (sendPortId them))
1307--------------------------------------------------------------------------------
1308-- Auxiliary functions --
1309--------------------------------------------------------------------------------
1311sendLocal :: (Serializable a) => ProcessId -> a -> Process ()
1312sendLocal to msg =
1313 sendCtrlMsg Nothing $ LocalSend to (createUnencodedMessage msg)
1315sendChanLocal :: (Serializable a) => SendPortId -> a -> Process ()
1316sendChanLocal spId msg =
1317 -- we *must* fully serialize/encode the message here, because
1318 -- attempting to use `unsafeCoerce' in the node controller
1319 -- won't work since we know nothing about the required type
1320 sendCtrlMsg Nothing $ LocalPortSend spId (createUnencodedMessage msg)
1322getMonitorRefFor :: Identifier -> Process MonitorRef
1323getMonitorRefFor ident = do
1324 proc <- ask
1325 liftIO $ modifyMVar (processState proc) $ \st -> do
1326 let counter = st ^. monitorCounter
1327 return ( monitorCounter ^: (+ 1) $ st
1328 , MonitorRef ident counter
1331getSpawnRef :: Process SpawnRef
1332getSpawnRef = do
1333 proc <- ask
1334 liftIO $ modifyMVar (processState proc) $ \st -> do
1335 let counter = st ^. spawnCounter
1336 return ( spawnCounter ^: (+ 1) $ st
1337 , SpawnRef counter
1340-- | Monitor a process/node/channel
1341monitor' :: Identifier -> Process MonitorRef
1342monitor' ident = do
1343 monitorRef <- getMonitorRefFor ident
1344 sendCtrlMsg Nothing $ Monitor monitorRef
1345 return monitorRef
1347-- | Link to a process/node/channel
1348link' :: Identifier -> Process ()
1349link' = sendCtrlMsg Nothing . Link