Repository navigation
Expand file tree
/
Copy pathMx.hs
More file actions
581 lines (479 loc) · 18.2 KB
/
Copy pathMx.hs
File metadata and controls
581 lines (479 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
module Control.Distributed.Process.Tests.Mx (tests) where
import Control.Concurrent.MVar (newEmptyMVar, putMVar, tryTakeMVar)
import Control.Concurrent (threadDelay)
import Control.Distributed.Process.Tests.Internal.Utils
import Network.Transport.Test (TestTransport(..))
import Control.Distributed.Process hiding (bracket, finally, try)
import Control.Distributed.Process.Internal.Types
( ProcessExitException(..)
, unsafeCreateUnencodedMessage
)
import Control.Distributed.Process.Node
import qualified Control.Distributed.Process.UnsafePrimitives as Unsafe
( send
, nsend
, nsendRemote
, usend
, sendChan
)
import Control.Distributed.Process.Management
( MxEvent(..)
, MxAgentId(..)
, mxAgent
, mxSink
, mxReady
, mxReceive
, mxDeactivate
, liftMX
, mxGetLocal
, mxSetLocal
, mxUpdateLocal
, mxNotify
, mxBroadcast
)
import Control.Monad (void, unless)
import Control.Monad.Catch(finally, bracket, try)
import Data.Binary
import Data.List (sort, intercalate)
import Data.Maybe (isJust, fromJust, fromMaybe)
import GHC.Generics hiding (from)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertEqual, testCase)
data Publish = Publish
deriving (Generic, Eq)
instance Binary Publish where
awaitExit :: ProcessId -> Process ()
awaitExit pid =
withMonitorRef pid $ \ref -> do
receiveWait
[ matchIf (\(ProcessMonitorNotification r _ _) -> r == ref)
(\_ -> return ())
]
where
withMonitorRef p = bracket (monitor p) unmonitor
testAgentBroadcast :: TestResult (Maybe ()) -> Process ()
testAgentBroadcast result = do
(resultSP, resultRP) <- newChan :: Process (SendPort (), ReceivePort ())
publisher <- mxAgent (MxAgentId "publisher-agent") () [
mxSink $ \() -> mxBroadcast Publish >> mxReady
]
consumer <- mxAgent (MxAgentId "consumer-agent") () [
mxSink $ \Publish -> (liftMX $ sendChan resultSP ()) >> mxReady
]
mxNotify ()
-- Once the publisher has seen our message, it will broadcast the Publish
-- and the consumer will see that and send the result to our typed channel.
stash result =<< receiveChanTimeout 10000000 resultRP
kill publisher "finished"
kill consumer "finished"
testAgentDualInput :: TestResult (Maybe Int) -> Process ()
testAgentDualInput result = do
(sp, rp) <- newChan
s <- mxAgent (MxAgentId "sum-agent") (0 :: Int) [
mxSink $ (\(i :: Int) -> do
mxSetLocal . (+i) =<< mxGetLocal
i' <- mxGetLocal
if i' == 15
then do mxGetLocal >>= liftMX . sendChan sp
mxDeactivate "finished"
else mxReady)
]
mRef <- monitor s
mxNotify (1 :: Int)
nsend "sum-agent" (3 :: Int)
mxNotify (2 :: Int)
nsend "sum-agent" (4 :: Int)
mxNotify (5 :: Int)
stash result =<< receiveChanTimeout 10000000 rp
died <- receiveTimeout 10000000 [
matchIf (\(ProcessMonitorNotification r _ _) -> r == mRef) (const $ return True)
]
liftIO $ assertEqual mempty (Just True) died
testAgentPrioritisation :: TestResult [String] -> Process ()
testAgentPrioritisation result = do
-- TODO: this isn't really testing how we /prioritise/ one source
-- over another at all, but I've not yet figured out the right way
-- to do so, since we're at the whim of the scheduler with regards
-- the timeliness of nsend versus mxNotify anyway.
let name = "prioritising-agent"
(sp, rp) <- newChan
s <- mxAgent (MxAgentId name) ["first"] [
mxSink (\(s :: String) -> do
mxUpdateLocal (s:)
st <- mxGetLocal
case length st of
n | n == 5 -> do liftMX $ sendChan sp (sort st)
mxDeactivate "finished"
_ -> mxReceive -- go to the mailbox
)
]
nsend name "second"
mxNotify "third"
mxNotify "fourth"
nsend name "fifth"
stash result . fromMaybe [] =<< receiveChanTimeout 10000000 rp
awaitExit s
testAgentMailboxHandling :: TestResult (Maybe ()) -> Process ()
testAgentMailboxHandling result = do
(sp, rp) <- newChan
agent <- mxAgent (MxAgentId "mailbox-agent") () [
mxSink $ \() -> (liftMX $ sendChan sp ()) >> mxReady
]
nsend "mailbox-agent" ()
stash result =<< receiveChanTimeout 1000000 rp
kill agent "finished"
testAgentEventHandling :: TestResult Bool -> Process ()
testAgentEventHandling result = do
let timeout = 1_000_000
(ackSP, ackRP) <- newChan :: Process (SendPort MxEvent, ReceivePort MxEvent)
let initState = [] :: [MxEvent]
agentPid <- mxAgent (MxAgentId "lifecycle-listener-agent") initState [
mxSink $ \ev -> do
case ev of
MxSpawned _ -> do
st <- mxGetLocal
mxSetLocal (ev : st)
liftMX $ sendChan ackSP ev
MxProcessDied _ _ -> do
st <- mxGetLocal
mxSetLocal (ev : st)
liftMX $ sendChan ackSP ev
_ -> pure ()
mxReady
, mxSink $ \(ev, sp :: SendPort Bool) -> do
st <- mxGetLocal
let found =
case ev of
MxSpawned p ->
any (\case
MxSpawned p' -> p' == p
_ -> False) st
MxProcessDied p r ->
any (\case
MxProcessDied p' r' ->
p' == p && r' == r
_ -> False) st
_ -> False
liftMX $ sendChan sp found
mxReady
]
(sp, rp) <- newChan :: Process (SendPort (), ReceivePort ())
pid <- spawnLocal $ (expect :: Process ()) >> sendChan sp ()
ref <- monitor pid
send pid ()
completed <- receiveChanTimeout timeout rp
terminated <- receiveTimeout timeout
[ matchIf
(\(ProcessMonitorNotification r _ _) -> r == ref)
(\_ -> pure ())
]
takingTooLong <- liftIO newEmptyMVar
spawnLocal . liftIO $ do
threadDelay timeout
putMVar takingTooLong ()
-- race conditions are eliminated by awaiting exactly the events
let awaitEvents seenSpawn seenDeath
| seenSpawn && seenDeath = pure True
| otherwise =
liftIO (tryTakeMVar takingTooLong) >>= \case
-- Awaiting is taking too long
Just () -> pure False
Nothing -> do
next <- receiveChanTimeout timeout ackRP
case next of
Nothing -> pure False
Just ev ->
case ev of
MxSpawned p
| p == pid -> awaitEvents True seenDeath
MxProcessDied p DiedNormal
| p == pid -> awaitEvents seenSpawn True
_ -> awaitEvents seenSpawn seenDeath
observed <- awaitEvents False False
(seenAlive, seenDead) <-
if observed
then do
(replyTo, reply) <- newChan :: Process (SendPort Bool, ReceivePort Bool)
mxNotify (MxSpawned pid, replyTo)
mxNotify (MxProcessDied pid DiedNormal, replyTo)
alive <- receiveChanTimeout timeout reply
dead <- receiveChanTimeout timeout reply
return (alive, dead)
else return (Nothing, Nothing)
stash result $
and [ completed == Just ()
, isJust terminated
, observed
, seenAlive == Just True
, seenDead == Just True
]
kill agentPid "test-complete"
testMxRegEvents :: TestResult () -> Process ()
testMxRegEvents result = do
{- This test only deals with the local case, to ensure that we are being
notified in the expected order - the remote cases related to the
behaviour of the node controller are contained in the CH test suite. -}
ensure (stash result ()) $ do
let label = "testMxRegEvents"
let agentLabel = "mxRegEvents-agent"
let delay = 1000000
(regChan, regSink) <- newChan
(unRegChan, unRegSink) <- newChan
agent <- mxAgent (MxAgentId agentLabel) () [
mxSink $ \ev -> do
case ev of
MxRegistered pid label'
| label' == label -> liftMX $ sendChan regChan (label', pid)
MxUnRegistered pid label'
| label' == label -> liftMX $ sendChan unRegChan (label', pid)
_ -> return ()
mxReady
]
p1 <- spawnLocal expect
p2 <- spawnLocal expect
register label p1
reg1 <- receiveChanTimeout delay regSink
liftIO $ assertEqual mempty (Just (label, p1)) reg1
unregister label
unreg1 <- receiveChanTimeout delay unRegSink
liftIO $ assertEqual mempty (Just (label, p1)) unreg1
register label p2
reg2 <- receiveChanTimeout delay regSink
liftIO $ assertEqual mempty (Just (label, p2)) reg2
reregister label p1
unreg2 <- receiveChanTimeout delay unRegSink
liftIO $ assertEqual mempty (Just (label, p2)) unreg2
reg3 <- receiveChanTimeout delay regSink
liftIO $ assertEqual mempty (Just (label, p1)) reg3
mapM_ (flip kill $ "test-complete") [agent, p1, p2]
testMxRegMon :: LocalNode -> TestResult () -> Process ()
testMxRegMon remoteNode result = do
ensure (stash result ()) $ do
-- ensure that when a registered process dies, we get a notification that
-- it has been unregistered as well as seeing the name get removed
let label1 = "aaaaa"
let label2 = "bbbbb"
let isValid l = l == label1 || l == label2
let agentLabel = "mxRegMon-agent"
let delay = 1000000
(regChan, regSink) <- newChan
(unRegChan, unRegSink) <- newChan
agent <- mxAgent (MxAgentId agentLabel) () [
mxSink $ \ev -> do
case ev of
MxRegistered pid label
| isValid label -> liftMX $ sendChan regChan (label, pid)
MxUnRegistered pid label
| isValid label -> liftMX $ sendChan unRegChan (label, pid)
_ -> return ()
mxReady
]
(sp, rp) <- newChan
liftIO $ forkProcess remoteNode $ do
getSelfPid >>= sendChan sp
expect :: Process ()
p1 <- receiveChan rp
register label1 p1
reg1 <- receiveChanTimeout delay regSink
liftIO $ assertEqual mempty (Just (label1, p1)) reg1
register label2 p1
reg2 <- receiveChanTimeout delay regSink
liftIO $ assertEqual mempty (Just (label2, p1)) reg2
n1 <- whereis label1
liftIO $ assertEqual mempty (Just p1) n1
n2 <- whereis label2
liftIO $ assertEqual mempty (Just p1) n2
kill p1 "goodbye"
unreg1 <- receiveChanTimeout delay unRegSink
unreg2 <- receiveChanTimeout delay unRegSink
let evts = [unreg1, unreg2]
-- we can't rely on the order of the values in the node controller's
-- map (it's either racy to do so, or no such guarantee exists for Data.Map),
-- so we simply verify that we received the un-registration events we expect
evts `shouldContain` (Just (label1, p1))
evts `shouldContain` (Just (label2, p1))
kill agent "test-complete"
ensure :: Process () -> Process () -> Process ()
ensure = flip finally
testNSend :: (String -> () -> Process ())
-> Maybe LocalNode
-> Process ()
testNSend op n = do
us <- getSelfPid
let delay = 5000000
let label = "testMxSend" ++ (show us)
let isValid = isValidLabel n label
testMxSend n label $ \p1 sink -> do
register label p1
reg1 <- receiveChanTimeout delay sink
case reg1 of
Just (MxRegistered pd lb)
| pd == p1 && isValid lb -> return ()
_ -> die $ "Reg-Failed: " ++ show reg1
op label ()
sent <- receiveChanTimeout delay sink
case sent of
Just (MxSentToName lb by _)
| by == us && isValid lb -> return True
_ -> die $ "Send-Failed: " ++ show sent
where
isValidLabel nd l1 l2
| l2 == l2 = True
| isJust nd = l2 == l1 ++ "@" ++ show (localNodeId $ fromJust nd)
| otherwise = False
testSend :: (ProcessId -> () -> Process ())
-> Maybe LocalNode
-> Process ()
testSend op n = do
us <- getSelfPid
let label = "testMxSend" ++ (show us)
testMxSend n label $ \p1 sink -> do
-- initiate a send
op p1 ()
-- verify the management event
sent <- receiveChanTimeout 5000000 sink
case sent of
Just (MxSent pidTo pidFrom _)
| pidTo == p1 && pidFrom == us -> return True
_ -> return False
testChan :: (SendPort () -> () -> Process ())
-> Maybe LocalNode
-> Process ()
testChan op n = testMxSend n "" $ \p1 sink -> do
us <- getSelfPid
send p1 us
cleared <- receiveChanTimeout 2000000 sink
case cleared of
Just (MxSent pidTo pidFrom _)
| pidTo == p1 && pidFrom == us -> return ()
_ -> die "Received uncleared Mx Event"
chan <- receiveTimeout 5000000 [ match return ]
let ch' = fromMaybe (error "No reply chan received") chan
-- initiate a send
op ch' ()
-- verify the management event
sent <- receiveChanTimeout 5000000 sink
case sent of
Just (MxSentToPort sId spId _)
| sId == us && spId == sendPortId ch' -> return True
_ -> return False
type SendTest = ProcessId -> ReceivePort MxEvent -> Process Bool
testMxSend :: Maybe LocalNode -> String -> SendTest -> Process ()
testMxSend mNode label test = do
us <- getSelfPid
(sp, rp) <- newChan
(chan, sink) <- newChan
agent <- mxAgent (MxAgentId $ agentLabel us) () [
mxSink $ \ev -> do
case ev of
m@(MxSentToPort _ cid _)
| cid /= sendPortId chan
&& cid /= sendPortId sp -> liftMX $ sendChan chan m
m@(MxSent _ fromPid _)
| fromPid == us -> liftMX $ sendChan chan m
m@(MxSentToName _ fromPid _)
| fromPid == us -> liftMX $ sendChan chan m
m@(MxRegistered _ name)
| name == label -> liftMX $ sendChan chan m
_ -> return ()
mxReady
]
case mNode of
Nothing -> void $ spawnLocal (proc sp)
Just remoteNode -> void $ liftIO $ forkProcess remoteNode $ proc sp
p1 <- receiveChanTimeout 2000000 rp
unless (isJust p1) $ die "Timed out waiting for ProcessId"
res <- try $ test (fromJust p1) sink
kill agent "bye"
kill (fromJust p1) "bye"
case res of
Left (ProcessExitException _ m) -> (liftIO $ putStrLn $ "SomeException-" ++ show m) >> die m
Right tr -> liftIO $ assertBool mempty tr
where
agentLabel s = "mx-unsafe-check-agent-" ++ show s
proc sp' = getSelfPid >>= sendChan sp' >> go Nothing
go :: Maybe (ReceivePort ()) -> Process ()
go Nothing = receiveTimeout 5000000 [ match replyChannel ] >>= go
go c@(Just c') = receiveWait [ matchChan c' return ] >> go c
replyChannel p' = do
(s, r) <- newChan
send p' s
return r
tests :: TestTransport -> IO TestTree
tests TestTransport{..} = do
node1 <- newLocalNode testTransport initRemoteTable
node2 <- newLocalNode testTransport initRemoteTable
return $ testGroup "Mx" [
testGroup "MxAgents" [
testCase "EventHandling"
(delayedAssertion
"expected True, but events where not as expected"
node1 True testAgentEventHandling)
, testCase "InterAgentBroadcast"
(delayedAssertion
"expected (), but no broadcast was received"
node1 (Just ()) testAgentBroadcast)
, testCase "AgentMailboxHandling"
(delayedAssertion
"expected (Just ()), but no regular (mailbox) input was handled"
node1 (Just ()) testAgentMailboxHandling)
, testCase "AgentDualInputHandling"
(delayedAssertion
"expected sum = 15, but the result was Nothing"
node1 (Just 15 :: Maybe Int) testAgentDualInput)
, testCase "AgentInputPrioritisation"
(delayedAssertion
"expected [first, second, third, fourth, fifth], but result diverged"
node1 (sort ["first", "second",
"third", "fourth",
"fifth"]) testAgentPrioritisation)
]
, testGroup "MxEvents" [
testCase "NameRegistrationEvents"
(delayedAssertion
"expected registration events to map to the correct ProcessId"
node1 () testMxRegEvents)
, testCase "PostDeathNameUnRegistrationEvents"
(delayedAssertion
"expected process deaths to result in unregistration events"
node1 () (testMxRegMon node2))
, testGroup "SendEvents" $ buildTestCases node1 node2
]
]
where
buildTestCases n1 n2 = let nid = localNodeId n2 in build n1 n2 [
("NSend", [
("nsend", testNSend nsend)
, ("Unsafe.nsend", testNSend Unsafe.nsend)
, ("nsendRemote", testNSend (nsendRemote nid))
, ("Unsafe.nsendRemote", testNSend (Unsafe.nsendRemote nid))
])
, ("Send", [
("send", testSend send)
, ("Unsafe.send", testSend Unsafe.send)
, ("usend", testSend usend)
, ("Unsafe.usend", testSend Unsafe.usend)
, ("sendChan", testChan sendChan)
, ("Unsafe.sendChan", testChan Unsafe.sendChan)
])
, ("Forward", [
("forward", testSend (\p m -> forward (unsafeCreateUnencodedMessage m) p))
, ("uforward", testSend (\p m -> uforward (unsafeCreateUnencodedMessage m) p))
])
]
build :: LocalNode
-> LocalNode
-> [(String, [(String, (Maybe LocalNode -> Process ()))])]
-> [TestTree]
build n ln specs =
[ testGroup (intercalate "-" [groupName, caseSuffix]) [
testCase (intercalate "-" [caseName, caseSuffix])
(runProcess n (caseImpl caseNode))
| (caseName, caseImpl) <- groupCases
]
| (groupName, groupCases) <- specs
, (caseSuffix, caseNode) <- [("RemotePid", Just ln), ("LocalPid", Nothing)]
]