@@ -1,12 +1,23 @@
1−{-# LANGUAGE DeriveGeneric #-}
1+{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE ParallelListComp #-}
3+
24module Control.Distributed.Process.Tests.Mx (tests) where
35
46import Control.Distributed.Process.Tests.Internal.Utils
57import Network.Transport.Test (TestTransport(..))
6−
7−import Control.Concurrent (threadDelay)
8−import Control.Distributed.Process
8+import Control.Distributed.Process hiding (bracket, finally, try)
9+import Control.Distributed.Process.Internal.Types
10+ ( ProcessExitException(..)
11+ , unsafeCreateUnencodedMessage
12+ )
913import Control.Distributed.Process.Node
14+import qualified Control.Distributed.Process.UnsafePrimitives as Unsafe
15+ ( send
16+ , nsend
17+ , nsendRemote
18+ , usend
19+ , sendChan
20+ )
1021import Control.Distributed.Process.Management
1122 ( MxEvent(..)
1223 , MxAgentId(..)
@@ -21,15 +32,15 @@ import Control.Distributed.Process.Management
2132 , mxUpdateLocal
2233 , mxNotify
2334 , mxBroadcast
24− , mxGetId
2535 )
2636import Control.Monad (void, unless)
37+import Control.Monad.Catch(finally, bracket, try)
2738import Control.Rematch (equalTo)
2839import Data.Binary
29−import Data.List (find, sort)
30−import Data.Maybe (isJust, isNothing)
40+import Data.List (find, sort, intercalate)
41+import Data.Maybe (isJust, fromJust, isNothing, fromMaybe, catMaybes)
3142import Data.Typeable
32−import GHC.Generics
43+import GHC.Generics hiding (from)
3344#if ! MIN_VERSION_base(4,6,0)
3445import Prelude hiding (catch, log)
3546#endif
@@ -53,9 +64,9 @@ awaitExit pid =
5364 (\_ -> return ())
5465 ]
5566 where
56− withMonitorRef pid = bracket (monitor pid) unmonitor
67+ withMonitorRef p = bracket (monitor p) unmonitor
5768
58−testAgentBroadcast :: TestResult () -> Process ()
69+testAgentBroadcast :: TestResult (Maybe ()) -> Process ()
5970testAgentBroadcast result = do
6071 (resultSP, resultRP) <- newChan :: Process (SendPort (), ReceivePort ())
6172
@@ -70,10 +81,10 @@ testAgentBroadcast result = do
7081 mxNotify ()
7182 -- Once the publisher has seen our message, it will broadcast the Publish
7283 -- and the consumer will see that and send the result to our typed channel.
73− stash result =<< receiveChan resultRP
84+ stash result =<< receiveChanTimeout 10000000 resultRP
7485
75− kill publisher "finished" >> awaitExit publisher
76− kill consumer "finished" >> awaitExit consumer
86+ kill publisher "finished"
87+ kill consumer "finished"
7788
7889testAgentDualInput :: TestResult (Maybe Int) -> Process ()
7990testAgentDualInput result = do
@@ -88,6 +99,8 @@ testAgentDualInput result = do
8899 else mxReady)
89100 ]
90101
102+ mRef <- monitor s
103+
91104 mxNotify (1 :: Int)
92105 nsend "sum-agent" (3 :: Int)
93106 mxNotify (2 :: Int)
@@ -95,7 +108,10 @@ testAgentDualInput result = do
95108 mxNotify (5 :: Int)
96109
97110 stash result =<< receiveChanTimeout 10000000 rp
98− awaitExit s
111+ died <- receiveTimeout 10000000 [
112+ matchIf (\(ProcessMonitorNotification r _ _) -> r == mRef) (const $ return True)
113+ ]
114+ died `shouldBe` equalTo (Just True)
99115
100116testAgentPrioritisation :: TestResult [String] -> Process ()
101117testAgentPrioritisation result = do
@@ -109,10 +125,10 @@ testAgentPrioritisation result = do
109125 (sp, rp) <- newChan
110126 s <- mxAgent (MxAgentId name) ["first"] [
111127 mxSink (\(s :: String) -> do
112− mxUpdateLocal ((s:))
128+ mxUpdateLocal (s:)
113129 st <- mxGetLocal
114130 case length st of
115− n | n == 5 -> do liftMX $ sendChan sp st
131+ n | n == 5 -> do liftMX $ sendChan sp (sort st)
116132 mxDeactivate "finished"
117133 _ -> mxReceive -- go to the mailbox
118134 )
@@ -123,7 +139,7 @@ testAgentPrioritisation result = do
123139 mxNotify "fourth"
124140 nsend name "fifth"
125141
126− stash result . sort =<< receiveChan rp
142+ stash result . fromMaybe [] =<< receiveChanTimeout 10000000 rp
127143 awaitExit s
128144
129145testAgentMailboxHandling :: TestResult (Maybe ()) -> Process ()
@@ -136,12 +152,19 @@ testAgentMailboxHandling result = do
136152 nsend "mailbox-agent" ()
137153
138154 stash result =<< receiveChanTimeout 1000000 rp
139− kill agent "finished" >> awaitExit agent
155+ kill agent "finished"
140156
141157testAgentEventHandling :: TestResult Bool -> Process ()
142158testAgentEventHandling result = do
143− let initState = [] :: [MxEvent]
159+ us <- getSelfPid
160+ -- because this test is a bit racy, let's ensure it can't run indefinitely
161+ timer <- spawnLocal $ do
162+ pause (1000000 * 60 * 5)
163+ -- okay we've waited 5 mins, let's kill the test off if it's stuck...
164+ stash result False
165+ kill us "Test Timed Out"
144166
167+ let initState = [] :: [MxEvent]
145168 (rc, rs) <- newChan
146169 agentPid <- mxAgent (MxAgentId "lifecycle-listener-agent") initState [
147170 (mxSink $ \ev -> do
@@ -174,8 +197,7 @@ testAgentEventHandling result = do
174197 -- TODO: yes, this is racy, but we're at the mercy of the scheduler here...
175198 faff 2000000 rs
176199
177− _ <- monitor agentPid
178− (sp, rp) <- newChan
200+ (sp, rp) <- newChan :: Process (SendPort (), ReceivePort ())
179201
180202 pid <- spawnLocal $ expect >>= sendChan sp
181203
@@ -184,9 +206,11 @@ testAgentEventHandling result = do
184206 monitor pid
185207
186208 send pid ()
187− () <- receiveChan rp
209+ rct <- receiveChanTimeout 10000000 rp
210+ unless (isJust rct) $ die "No response on channel"
188211
189− receiveWait [ match (\(ProcessMonitorNotification _ _ _) -> return ()) ]
212+ pmn <- receiveTimeout 2000000 [ match (\ProcessMonitorNotification{} -> return ()) ]
213+ unless (isJust pmn) $ die "No monitor notification arrived"
190214
191215 -- TODO: yes, this is racy, but we're at the mercy of the scheduler here...
192216 faff 2000000 rs
@@ -195,17 +219,16 @@ testAgentEventHandling result = do
195219 mxNotify (MxSpawned pid, replyTo)
196220 mxNotify (MxProcessDied pid DiedNormal, replyTo)
197221
198− seenAlive <- receiveChan reply
199− seenDead <- receiveChan reply
222+ seenAlive <- receiveChanTimeout 10000000 reply
223+ seenDead <- receiveChanTimeout 10000000 reply
200224
201− stash result $ seenAlive && seenDead
202− kill agentPid "test-complete" >> awaitExit agentPid
225+ stash result $ foldr (&&) True $ catMaybes [seenAlive, seenDead]
226+ kill timer "test-complete"
227+ kill agentPid "test-complete"
203228 where
204229 faff delay port = do
205230 res <- receiveChanTimeout delay port
206− unless (isNothing res) $ do
207− pause delay
208− faff delay port
231+ unless (isNothing res) $ pause delay
209232
210233testMxRegEvents :: TestResult () -> Process ()
211234testMxRegEvents result = do
@@ -252,7 +275,6 @@ testMxRegEvents result = do
252275 reg3 `shouldBe` equalTo (Just (label, p1))
253276
254277 mapM_ (flip kill $ "test-complete") [agent, p1, p2]
255− awaitExit agent
256278
257279testMxRegMon :: LocalNode -> TestResult () -> Process ()
258280testMxRegMon remoteNode result = do
@@ -310,48 +332,211 @@ testMxRegMon remoteNode result = do
310332 evts `shouldContain` (Just (label1, p1))
311333 evts `shouldContain` (Just (label2, p1))
312334
313− kill agent "test-complete" >> awaitExit agent
335+ kill agent "test-complete"
314336
315337ensure :: Process () -> Process () -> Process ()
316338ensure = flip finally
317339
340+testNSend :: (String -> () -> Process ())
341+ -> Maybe LocalNode
342+ -> Process ()
343+testNSend op n = do
344+ us <- getSelfPid
345+ let delay = 5000000
346+ let label = "testMxSend" ++ (show us)
347+ let isValid = isValidLabel n label
348+
349+ testMxSend n label $ \p1 sink -> do
350+ register label p1
351+ reg1 <- receiveChanTimeout delay sink
352+ case reg1 of
353+ Just (MxRegistered pd lb)
354+ | pd == p1 && isValid lb -> return ()
355+ _ -> die $ "Reg-Failed: " ++ show reg1
356+
357+ op label ()
358+
359+ sent <- receiveChanTimeout delay sink
360+ case sent of
361+ Just (MxSentToName lb by _)
362+ | by == us && isValid lb -> return True
363+ _ -> die $ "Send-Failed: " ++ show sent
364+
365+ where
366+ isValidLabel nd l1 l2
367+ | l2 == l2 = True
368+ | isJust nd = l2 == l1 ++ "@" ++ show (localNodeId $ fromJust nd)
369+ | otherwise = False
370+
371+testSend :: (ProcessId -> () -> Process ())
372+ -> Maybe LocalNode
373+ -> Process ()
374+testSend op n = do
375+ us <- getSelfPid
376+ let label = "testMxSend" ++ (show us)
377+ testMxSend n label $ \p1 sink -> do
378+ -- initiate a send
379+ op p1 ()
380+
381+ -- verify the management event
382+ sent <- receiveChanTimeout 5000000 sink
383+ case sent of
384+ Just (MxSent pidTo pidFrom _)
385+ | pidTo == p1 && pidFrom == us -> return True
386+ _ -> return False
387+
388+testChan :: (SendPort () -> () -> Process ())
389+ -> Maybe LocalNode
390+ -> Process ()
391+testChan op n = testMxSend n "" $ \p1 sink -> do
392+
393+ us <- getSelfPid
394+ send p1 us
395+
396+ cleared <- receiveChanTimeout 2000000 sink
397+ case cleared of
398+ Just (MxSent pidTo pidFrom _)
399+ | pidTo == p1 && pidFrom == us -> return ()
400+ _ -> die "Received uncleared Mx Event"
401+
402+ chan <- receiveTimeout 5000000 [ match return ]
403+ let ch' = fromMaybe (error "No reply chan received") chan
404+
405+ -- initiate a send
406+ op ch' ()
407+
408+ -- verify the management event
409+ sent <- receiveChanTimeout 5000000 sink
410+ case sent of
411+ Just (MxSentToPort sId spId _)
412+ | sId == us && spId == sendPortId ch' -> return True
413+ _ -> return False
414+
415+type SendTest = ProcessId -> ReceivePort MxEvent -> Process Bool
416+
417+testMxSend :: Maybe LocalNode -> String -> SendTest -> Process ()
418+testMxSend mNode label test = do
419+ us <- getSelfPid
420+ (sp, rp) <- newChan
421+ (chan, sink) <- newChan
422+ agent <- mxAgent (MxAgentId $ agentLabel us) () [
423+ mxSink $ \ev -> do
424+ case ev of
425+ m@(MxSentToPort _ cid _)
426+ | cid /= sendPortId chan
427+ && cid /= sendPortId sp -> liftMX $ sendChan chan m
428+ m@(MxSent _ fromPid _)
429+ | fromPid == us -> liftMX $ sendChan chan m
430+ m@(MxSentToName _ fromPid _)
431+ | fromPid == us -> liftMX $ sendChan chan m
432+ m@(MxRegistered _ name)
433+ | name == label -> liftMX $ sendChan chan m
434+ _ -> return ()
435+ mxReady
436+ ]
437+
438+ case mNode of
439+ Nothing -> void $ spawnLocal (proc sp)
440+ Just remoteNode -> void $ liftIO $ forkProcess remoteNode $ proc sp
441+
442+ p1 <- receiveChanTimeout 2000000 rp
443+ unless (isJust p1) $ die "Timed out waiting for ProcessId"
444+ res <- try $ test (fromJust p1) sink
445+
446+ kill agent "bye"
447+ kill (fromJust p1) "bye"
448+
449+ case res of
450+ Left (ProcessExitException _ m) -> (liftIO $ putStrLn $ "SomeException-" ++ show m) >> die m
451+ Right tr -> tr `shouldBe` equalTo True
452+
453+
454+ where
455+ agentLabel s = "mx-unsafe-check-agent-" ++ show s
456+ proc sp' = getSelfPid >>= sendChan sp' >> go Nothing
457+
458+ go :: Maybe (ReceivePort ()) -> Process ()
459+ go Nothing = receiveTimeout 5000000 [ match replyChannel ] >>= go
460+ go c@(Just c') = receiveWait [ matchChan c' return ] >> go c
461+
462+ replyChannel p' = do
463+ (s, r) <- newChan
464+ send p' s
465+ return r
466+
318467tests :: TestTransport -> IO [Test]
319468tests TestTransport{..} = do
320469 node1 <- newLocalNode testTransport initRemoteTable
321470 node2 <- newLocalNode testTransport initRemoteTable
322471 return [
323− testGroup "Mx Agents" [
324− testCase "Event Handling"
472+ testGroup "MxAgents" [
473+ testCase "EventHandling"
325474 (delayedAssertion
326475 "expected True, but events where not as expected"
327476 node1 True testAgentEventHandling)
328− , testCase "Inter-Agent Broadcast"
477+ , testCase "InterAgentBroadcast"
329478 (delayedAssertion
330479 "expected (), but no broadcast was received"
331− node1 () testAgentBroadcast)
332− , testCase "Agent Mailbox Handling"
480+ node1 (Just ()) testAgentBroadcast)
481+ , testCase "AgentMailboxHandling"
333482 (delayedAssertion
334483 "expected (Just ()), but no regular (mailbox) input was handled"
335484 node1 (Just ()) testAgentMailboxHandling)
336− , testCase "Agent Dual Input Handling"
485+ , testCase "AgentDualInputHandling"
337486 (delayedAssertion
338487 "expected sum = 15, but the result was Nothing"
339488 node1 (Just 15 :: Maybe Int) testAgentDualInput)
340− , testCase "Agent Input Prioritisation"
489+ , testCase "AgentInputPrioritisation"
341490 (delayedAssertion
342491 "expected [first, second, third, fourth, fifth], but result diverged"
343492 node1 (sort ["first", "second",
344493 "third", "fourth",
345494 "fifth"]) testAgentPrioritisation)
346495 ]
347− , testGroup "Mx Events" [
348− testCase "Name Registration Events"
496+ , testGroup "MxEvents" [
497+ testCase "NameRegistrationEvents"
349498 (delayedAssertion
350499 "expected registration events to map to the correct ProcessId"
351500 node1 () testMxRegEvents)
352− , testCase "Post Death Name UnRegistration Events"
501+ , testCase "PostDeathNameUnRegistrationEvents"
353502 (delayedAssertion
354503 "expected process deaths to result in unregistration events"
355504 node1 () (testMxRegMon node2))
505+ , testGroup "SendEvents" $ buildTestCases node1 node2
356506 ]
357507 ]
508+ where
509+ buildTestCases n1 n2 = let nid = localNodeId n2 in build n1 n2 [
510+ ("NSend", [
511+ ("nsend", testNSend nsend)
512+ , ("Unsafe.nsend", testNSend Unsafe.nsend)
513+ , ("nsendRemote", testNSend (nsendRemote nid))
514+ , ("Unsafe.nsendRemote", testNSend (Unsafe.nsendRemote nid))
515+ ])
516+ , ("Send", [
517+ ("send", testSend send)
518+ , ("Unsafe.send", testSend Unsafe.send)
519+ , ("usend", testSend usend)
520+ , ("Unsafe.usend", testSend Unsafe.usend)
521+ , ("sendChan", testChan sendChan)
522+ , ("Unsafe.sendChan", testChan Unsafe.sendChan)
523+ ])
524+ , ("Forward", [
525+ ("forward", testSend (\p m -> forward (unsafeCreateUnencodedMessage m) p))
526+ , ("uforward", testSend (\p m -> uforward (unsafeCreateUnencodedMessage m) p))
527+ ])
528+ ]
529+
530+ build :: LocalNode
531+ -> LocalNode
532+ -> [(String, [(String, (Maybe LocalNode -> Process ()))])]
533+ -> [Test]
534+ build n ln specs =
535+ [ testGroup (intercalate "-" [groupName, caseSuffix]) [
536+ testCase (intercalate "-" [caseName, caseSuffix])
537+ (runProcess n (caseImpl caseNode))
538+ | (caseName, caseImpl) <- groupCases
539+ ]
540+ | (groupName, groupCases) <- specs
541+ , (caseSuffix, caseNode) <- [("RemotePid", Just ln), ("LocalPid", Nothing)]
542+ ]