git.iko.soy/distributed-process
on fd/ci-update help sign in
1346 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 Just proc <- liftIO $ dequeue queue Blocking (map unMatch ms)
404 proc
406-- | Like 'receiveWait' but with a timeout.
407--
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)
416 case mProc of
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.
425--
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.
429--
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.
433--
434-- Note there are no ordering guarnatees with respect to these disparate input
435-- sources.
436--
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
448 False -> Nothing
449 True -> case msg of
450 (UnencodedMessage _ m) ->
451 let m' = unsafeCoerce m :: a in
452 case (c m') of
453 True -> Just (p m')
454 False -> Nothing
455 (EncodedMessage _ _) ->
456 if (c decoded) then Just (p decoded) else Nothing
457 where
458 decoded :: a
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 ->
471 case (c msg) of
472 True -> Just (p msg)
473 False -> Nothing
475-- | Forward a raw 'Message' to the given 'ProcessId'.
476forward :: Message -> ProcessId -> Process ()
477forward msg them = do
478 proc <- ask
479 let node = processNode proc
480 us = processId 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)
488 NoImplicitReconnect
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)
493 (MxSent them us msg)
495-- | Forward a raw 'Message' to the given 'ProcessId'.
496--
497-- Unlike 'forward', this function is insensitive to 'reconnect'. It will
498-- try to send the message regardless of the history of connection failures
499-- between the nodes.
500uforward :: Message -> ProcessId -> Process ()
501uforward msg them = do
502 proc <- ask
503 let node = processNode proc
504 us = processId 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)
510 msg
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)
514 (MxSent them us msg)
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.
520--
521-- @
522-- do
523-- self <- getSelfPid
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)
528-- @
529--
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
546-- do not match.
547--
548-- This expression, for example, will evaluate to @Nothing@
549-- > unwrapMessage (wrapMessage "foobar") :: Process (Maybe Int)
550--
551-- Whereas this expression, will yield @Just "foo"@
552-- > unwrapMessage (wrapMessage "foo") :: Process (Maybe String)
553--
554unwrapMessage :: forall m a. (Monad m, Serializable a) => Message -> m (Maybe a)
555unwrapMessage msg =
556 case messageFingerprint msg == fingerprint (undefined :: a) of
557 False -> return Nothing :: m (Maybe a)
558 True -> case msg of
559 (UnencodedMessage _ ms) ->
560 let ms' = unsafeCoerce ms :: a
561 in return (Just ms')
562 (EncodedMessage _ _) ->
563 return (Just (decoded))
564 where
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@.
574--
575-- Intended for use in `catchesExit` and `matchAny` primitives.
576--
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.
585--
586handleMessageIf :: forall m a b . (Monad m, Serializable a)
587 => Message
588 -> (a -> Bool)
589 -> (a -> m b)
590 -> m (Maybe b)
591handleMessageIf msg c proc = do
592 case messageFingerprint msg == fingerprint (undefined :: a) of
593 False -> return Nothing :: m (Maybe b)
594 True -> case msg of
595 (UnencodedMessage _ ms) ->
596 let ms' = unsafeCoerce ms :: a in
597 case (c ms') of
598 True -> do { r <- proc ms'; return (Just r) }
599 False -> return Nothing :: m (Maybe b)
600 (EncodedMessage _ _) ->
601 case (c decoded) of
602 True -> do { r <- proc (decoded :: a); return (Just r) }
603 False -> return Nothing :: m (Maybe b)
604 where
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.
610--
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_'.
616--
617handleMessageIf_ :: forall m a . (Monad m, Serializable a)
618 => Message
619 -> (a -> Bool)
620 -> (a -> m ())
621 -> m ()
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'.
627--
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.
639--
640matchAnyIf :: forall a b. (Serializable a)
641 => (a -> Bool)
642 -> (Message -> Process b)
643 -> Match b
644matchAnyIf c p = Match $ MatchMsg $ \msg ->
645 case messageFingerprint msg == fingerprint (undefined :: a) of
646 True | check -> Just (p msg)
647 where
648 check :: Bool
649 !check =
650 case msg of
651 (EncodedMessage _ _) -> c decoded
652 (UnencodedMessage _ m') -> c (unsafeCoerce m')
654 decoded :: a -- note [decoding]
655 !decoded = decode (messageEncoding msg)
656 _ -> Nothing
658{- note [decoding]
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.
663-}
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 ()
671delegate pid p = do
672 receiveWait [
673 matchAny (\m -> case (p m) of
674 True -> forward m pid
675 False -> return ())
676 ]
677 delegate pid p
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 ()
688proxy pid proc = do
689 receiveWait [
690 matchAny (\m -> do
691 next <- handleMessage m proc
692 case next of
693 Just True -> forward m pid
694 Just False -> return () -- explicitly ignored
695 Nothing -> return ()) -- un-routable
696 ]
697 proxy pid proc
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
713-- [Issue #110]
714-- | Die immediately - throws a 'ProcessExitException' with the given @reason@.
715die :: Serializable a => a -> Process b
716die reason = do
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.
720 pid <- getSelfPid
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.
747--
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)
751 => Process b
752 -> (ProcessId -> a -> Process b)
753 -> Process b
754catchExit act exitHandler = Catch.catch act handleExit
755 where
756 handleExit ex@(ProcessExitException from msg) =
757 if messageFingerprint msg == fingerprint (undefined :: a)
758 then exitHandler from decoded
759 else throwM ex
760 where
761 decoded :: a
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).
767--
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@).
773--
774-- See 'maybeHandleMessage' and 'Message' for more details.
775catchesExit :: Process b
776 -> [(ProcessId -> Message -> (Process (Maybe b)))]
777 -> Process b
778catchesExit act handlers = Catch.catch act ((flip handleExit) handlers)
779 where
780 handleExit :: ProcessExitException
781 -> [(ProcessId -> Message -> Process (Maybe b))]
782 -> Process b
783 handleExit ex [] = throwM ex
784 handleExit ex@(ProcessExitException from msg) (h:hs) = do
785 r <- h from msg
786 case r of
787 Nothing -> handleExit ex hs
788 Just p -> return p
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)
801getNodeStats nid = do
802 selfNode <- getSelfNode
803 if nid == selfNode
804 then Right `fmap` getLocalNodeStats -- optimisation
805 else getNodeStatsRemote selfNode
806 where
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)
814 ]
816-- | Get statistics about our local node
817getLocalNodeStats :: Process NodeStats
818getLocalNodeStats = do
819 self <- getSelfNode
820 sendCtrlMsg Nothing $ GetNodeStats self
821 receiveWait [ match (\(stats :: NodeStats) -> return stats) ]
823-- | Get information about the specified process
824getProcessInfo :: ProcessId -> Process (Maybe ProcessInfo)
825getProcessInfo pid =
826 let them = processNodeId pid in do
827 us <- getSelfNode
828 dest <- mkNode them us
829 sendCtrlMsg dest $ GetInfo pid
830 receiveWait [
831 match (\(p :: ProcessInfo) -> return $ Just p)
832 , match (\(_ :: ProcessInfoNone) -> return Nothing)
833 ]
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)
844--
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
851--
852-- > link pidB -- Link to process B
853-- > expect -- Wait for a message from process B
854-- > unlink pidB -- Unlink again
855--
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).
860--
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.
863--
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)
871--
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.).
878--
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.
886--
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.
891--
892withMonitor :: ProcessId -> (MonitorRef -> Process a) -> Process a
893withMonitor pid = bracket (monitor pid) unmonitor
895-- | Establishes temporary monitoring of another process.
896--
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.
901--
902-- Since 0.6.1
903withMonitor_ :: ProcessId -> Process a -> Process a
904withMonitor_ p = withMonitor p . const
906-- | Remove a link
907--
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
911-- node.
912unlink :: ProcessId -> Process ()
913unlink pid = do
914 unlinkAsync pid
915 receiveWait [ matchIf (\(DidUnlinkProcess pid') -> pid' == pid)
916 (\_ -> return ())
917 ]
919-- | Remove a node link
920--
921-- This has the same synchronous/asynchronous nature as 'unlink'.
922unlinkNode :: NodeId -> Process ()
923unlinkNode nid = do
924 unlinkNodeAsync nid
925 receiveWait [ matchIf (\(DidUnlinkNode nid') -> nid' == nid)
926 (\_ -> return ())
927 ]
929-- | Remove a channel (send port) link
930--
931-- This has the same synchronous/asynchronous nature as 'unlink'.
932unlinkPort :: SendPort a -> Process ()
933unlinkPort sport = do
934 unlinkPortAsync sport
935 receiveWait [ matchIf (\(DidUnlinkPort cid) -> cid == sendPortId sport)
936 (\_ -> return ())
937 ]
939-- | Remove a monitor
940--
941-- This has the same synchronous/asynchronous nature as 'unlink'.
942--
943-- ProcessMonitorNotification messages for the given MonitorRef are removed from
944-- the mailbox.
945unmonitor :: MonitorRef -> Process ()
946unmonitor ref = do
947 unmonitorAsync ref
948 receiveWait [ matchIf (\(DidUnmonitor ref') -> ref' == ref)
949 (\_ -> return ())
950 ]
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)
955 (const $ return ())
956 ]
958--------------------------------------------------------------------------------
959-- Exception handling --
960--------------------------------------------------------------------------------
962-- | Lift 'Control.Exception.catch'
963catch :: Exception e => Process a -> (e -> Process a) -> Process a
964catch = Catch.catch
965{-# DEPRECATED catch "Use Control.Monad.Catch.catch instead" #-}
967-- | Lift 'Control.Exception.try'
968try :: Exception e => Process a -> Process (Either e a)
969try = Catch.try
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
974mask = Catch.mask
975{-# DEPRECATED mask "Use Control.Monad.Catch.mask_ instead" #-}
977-- | Lift 'Control.Exception.mask_'
978mask_ :: Process a -> Process a
979mask_ = Catch.mask_
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'
1017 Nothing -> res
1019--------------------------------------------------------------------------------
1020-- Auxiliary API --
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
1033 node <- getSelfNode
1034 if nid == node
1035 then sendCtrlMsg Nothing $ Spawn proc spawnRef
1036 else sendCtrlMsg (Just nid) $ Spawn proc spawnRef
1037 return spawnRef
1039-- | Monitor a node (asynchronous)
1040monitorNode :: NodeId -> Process MonitorRef
1041monitorNode =
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 ()
1051unmonitorAsync =
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 ()
1065unlinkAsync =
1066 sendCtrlMsg Nothing . Unlink . ProcessIdentifier
1068-- | Remove a node link (asynchronous)
1069unlinkNodeAsync :: NodeId -> Process ()
1070unlinkNodeAsync =
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--------------------------------------------------------------------------------
1079-- Logging --
1080--------------------------------------------------------------------------------
1082data SayMessage = SayMessage { sayTime :: UTCTime
1083 , sayProcess :: ProcessId
1084 , sayMessage :: String }
1085 deriving (Typeable)
1087-- There is sadly no Show UTCTime instance
1088instance Show SayMessage where
1089 showsPrec p msg =
1090 showParen (p >= 11)
1091 $ showString "SayMessage "
1092 . showString (formatTime defaultTimeLocale "%c" (sayTime msg))
1093 . showChar ' '
1094 . showsPrec 11 (sayProcess msg) . showChar ' '
1095 . showsPrec 11 (sayMessage msg) . showChar ' '
1097instance Binary SayMessage where
1098 put s = do
1099 putUTCTime (sayTime s)
1100 put (sayProcess s)
1101 put (sayMessage s)
1102 get = SayMessage <$> getUTCTime <*> get <*> get
1104-- Sadly there is no Binary UTCTime instance
1105putUTCTime :: UTCTime -> Put
1106putUTCTime (UTCTime (ModifiedJulianDay day) tod) = do
1107 put day
1108 put (toRational tod)
1110getUTCTime :: Get UTCTime
1111getUTCTime = do
1112 day <- get
1113 tod <- get
1114 return $! UTCTime (ModifiedJulianDay day)
1115 (fromRational tod)
1117-- | Log a string
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 ()
1124say string = do
1125 now <- liftIO getCurrentTime
1126 us <- getSelfPid
1127 nsend "logger" (SayMessage now us string)
1129--------------------------------------------------------------------------------
1130-- Registry --
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)
1150 receiveWait
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
1163 here <- getSelfNode
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)
1178 receiveWait
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 =
1187 when (not ok) $
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)
1201whereis label = do
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
1218 here <- getSelfNode
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 ()
1223nsend label msg =
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
1236 here <- getSelfNode
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--------------------------------------------------------------------------------
1248-- Closures --
1249--------------------------------------------------------------------------------
1251-- | Resolve a static value
1252unStatic :: Typeable a => Static a -> Process a
1253unStatic static = do
1254 rtable <- remoteTable . processNode <$> ask
1255 case Static.unstatic rtable static of
1256 Left err -> fail $ "Could not resolve static value: " ++ err
1257 Right x -> return x
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
1265 Right x -> return x
1267--------------------------------------------------------------------------------
1268-- Reconnecting --
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 ()
1292reconnect them = do
1293 us <- getSelfPid
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
1300 us <- getSelfPid
1301 node <- processNode <$> ask
1302 liftIO $ disconnect node (ProcessIdentifier us) (SendPortIdentifier (sendPortId them))
1304--------------------------------------------------------------------------------
1305-- Auxiliary functions --
1306--------------------------------------------------------------------------------
1308sendLocal :: (Serializable a) => ProcessId -> a -> Process ()
1309sendLocal to msg =
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
1321 proc <- ask
1322 liftIO $ modifyMVar (processState proc) $ \st -> do
1323 let counter = st ^. monitorCounter
1324 return ( monitorCounter ^: (+ 1) $ st
1325 , MonitorRef ident counter
1328getSpawnRef :: Process SpawnRef
1329getSpawnRef = do
1330 proc <- ask
1331 liftIO $ modifyMVar (processState proc) $ \st -> do
1332 let counter = st ^. spawnCounter
1333 return ( spawnCounter ^: (+ 1) $ st
1334 , SpawnRef counter
1337-- | Monitor a process/node/channel
1338monitor' :: Identifier -> Process MonitorRef
1339monitor' ident = do
1340 monitorRef <- getMonitorRefFor ident
1341 sendCtrlMsg Nothing $ Monitor monitorRef
1342 return monitorRef
1344-- | Link to a process/node/channel
1345link' :: Identifier -> Process ()
1346link' = sendCtrlMsg Nothing . Link