-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathCH.hs
More file actions
1874 lines (1570 loc) · 65.3 KB
/
CH.hs
File metadata and controls
1874 lines (1570 loc) · 65.3 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE NumericUnderscores #-}
module Control.Distributed.Process.Tests.CH (tests) where
import Network.Transport.Test (TestTransport(..))
import Data.Binary (Binary(..))
import Data.Typeable (Typeable)
import Data.Foldable (forM_)
import Data.Function (fix)
import Data.IORef
( readIORef
, writeIORef
, newIORef
)
import Control.Concurrent (forkIO, threadDelay, myThreadId, throwTo, ThreadId, yield)
import Control.Concurrent.MVar
( MVar
, newEmptyMVar
, putMVar
, takeMVar
, readMVar
)
import Control.Monad (replicateM_, replicateM, forever, void, unless, join)
import Control.Exception (SomeException, throwIO, ErrorCall(..))
import Control.Monad.Catch (try, catch, finally, mask, onException)
import Control.Applicative ((<|>))
import qualified Network.Transport as NT (closeEndPoint, EndPointAddress)
import Control.Distributed.Process hiding
( try
, catch
, finally
, mask
, onException
)
import Control.Distributed.Process.Internal.Types
( LocalNode(localEndPoint)
, ProcessExitException(..)
, nullProcessId
, createUnencodedMessage
)
import Control.Distributed.Process.Node
import Control.Distributed.Process.Tests.Internal.Utils (pause)
import Control.Distributed.Process.Serializable (Serializable)
import Data.Maybe (isNothing, isJust)
import System.Timeout (timeout)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, assertEqual, testCase, assertFailure)
newtype Ping = Ping ProcessId
deriving (Typeable, Binary, Show)
newtype Pong = Pong ProcessId
deriving (Typeable, Binary, Show)
--------------------------------------------------------------------------------
-- Supporting definitions --
--------------------------------------------------------------------------------
-- | Like fork, but throw exceptions in the child thread to the parent
forkTry :: IO () -> IO ThreadId
forkTry p = do
tid <- myThreadId
forkIO $ catch p (\e -> throwTo tid (e :: SomeException))
-- | The ping server from the paper
ping :: Process ()
ping = do
Pong partner <- expect
self <- getSelfPid
send partner (Ping self)
ping
verifyClient :: String -> MVar Bool -> IO ()
verifyClient s b =
-- The timeout below must be generous enough to support
-- running tests in the Github Actions CI environment, which is quite slow.
timeout 60_000_000
(takeMVar b >>= assertBool s)
>>= maybe (assertFailure $ "verifyClient timeout: " <> s) (\_ -> pure ())
expectPing :: MVar Bool -> Process ()
expectPing mv = expect >>= liftIO . putMVar mv . checkPing
where
checkPing (Ping _) = True
-- | Quick and dirty synchronous version of whereisRemoteAsync
whereisRemote :: NodeId -> String -> Process (Maybe ProcessId)
whereisRemote nid string = do
whereisRemoteAsync nid string
receiveWait [
match (\(WhereIsReply _ mPid) -> return mPid)
]
verifyWhereIsRemote :: NodeId -> String -> Process ProcessId
verifyWhereIsRemote n s = whereisRemote n s >>= maybe (die "remote name not found") return
syncBreakConnection :: (NT.EndPointAddress -> NT.EndPointAddress -> IO ()) -> LocalNode -> LocalNode -> IO ()
syncBreakConnection breakConnection nid0 nid1 = do
m <- newEmptyMVar
_ <- forkProcess nid1 $ getSelfPid >>= liftIO . putMVar m
runProcess nid0 $ do
them <- liftIO $ takeMVar m
pinger <- spawnLocal $ forever $ send them ()
_ <- monitorNode (localNodeId nid1)
liftIO $ breakConnection (nodeAddress $ localNodeId nid0)
(nodeAddress $ localNodeId nid1)
NodeMonitorNotification _ _ _ <- expect
kill pinger "finished"
return ()
data Add = Add ProcessId Double Double deriving (Typeable)
data Divide = Divide ProcessId Double Double deriving (Typeable)
data DivByZero = DivByZero deriving (Typeable)
instance Binary Add where
put (Add pid x y) = put pid >> put x >> put y
get = Add <$> get <*> get <*> get
instance Binary Divide where
put (Divide pid x y) = put pid >> put x >> put y
get = Divide <$> get <*> get <*> get
instance Binary DivByZero where
put DivByZero = return ()
get = return DivByZero
-- The math server from the paper
math :: Process ()
math = do
receiveWait
[ match (\(Add pid x y) -> send pid (x + y))
, matchIf (\(Divide _ _ y) -> y /= 0)
(\(Divide pid x y) -> send pid (x / y))
, match (\(Divide pid _ _) -> send pid DivByZero)
]
math
-- | Monitor or link to a remote node
monitorOrLink :: Bool -- ^ 'True' for monitor, 'False' for link
-> ProcessId -- ^ Process to monitor/link to
-> Maybe (MVar ()) -- ^ MVar to signal on once the monitor has been set up
-> Process (Maybe MonitorRef)
monitorOrLink mOrL pid mSignal = do
result <- if mOrL then Just <$> monitor pid
else link pid >> return Nothing
-- Monitor is asynchronous, which usually does not matter but if we want a
-- *specific* signal then it does. Therefore we wait until the MonitorRef is
-- listed in the ProcessInfo and hope that this means the monitor has been set
-- up.
forM_ mSignal $ \signal -> do
self <- getSelfPid
spawnLocal $ do
let waitForMOrL = do
liftIO $ threadDelay 100000
mpinfo <- getProcessInfo pid
case mpinfo of
Nothing -> waitForMOrL
Just pinfo ->
if mOrL then
unless (result == lookup self (infoMonitors pinfo)) waitForMOrL
else
unless (elem self $ infoLinks pinfo) waitForMOrL
waitForMOrL
liftIO $ putMVar signal ()
return result
monitorTestProcess :: ProcessId -- Process to monitor/link to
-> Bool -- 'True' for monitor, 'False' for link
-> Bool -- Should we unmonitor?
-> DiedReason -- Expected cause of death
-> Maybe (MVar ()) -- Signal for 'monitor set up'
-> MVar () -- Signal for successful termination
-> Process ()
monitorTestProcess theirAddr mOrL un reason monitorSetup done =
catch (do mRef <- monitorOrLink mOrL theirAddr monitorSetup
case (un, mRef) of
(True, Nothing) -> do
unlink theirAddr
liftIO $ putMVar done ()
(True, Just ref) -> do
unmonitor ref
liftIO $ putMVar done ()
(False, ref) -> do
receiveTimeout 1_000_000 [
match (\(ProcessMonitorNotification ref' pid reason') -> do
liftIO $ do
assertBool "Bad Monitor Signal"
(Just ref' == ref && pid == theirAddr &&
mOrL && reason == reason')
putMVar done ())
] >>= maybe (liftIO $ assertFailure "No ProcessMonitorNotification received within timeout window") pure
)
(\(ProcessLinkException pid reason') -> do
(liftIO $ assertBool "link exception unmatched" $
pid == theirAddr && not mOrL && not un && reason == reason')
liftIO $ putMVar done ()
)
--------------------------------------------------------------------------------
-- The tests proper --
--------------------------------------------------------------------------------
-- | Basic ping test
testPing :: TestTransport -> Assertion
testPing TestTransport{..} = do
serverAddr <- newEmptyMVar
clientDone <- newEmptyMVar
-- Server
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode ping
putMVar serverAddr addr
-- Client
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
pingServer <- readMVar serverAddr
let numPings = 10000
runProcess localNode $ do
pid <- getSelfPid
replicateM_ numPings $ do
send pingServer (Pong pid)
p <- expectTimeout 3000000
case p of
Just (Ping _) -> return ()
Nothing -> let msg = "Failed to receive Ping" in liftIO (putMVar clientDone (Left msg)) >> die msg
putMVar clientDone (Right ())
takeMVar clientDone >>= either assertFailure pure
-- | Monitor a process on an unreachable node
testMonitorUnreachable :: TestTransport -> Bool -> Bool -> Assertion
testMonitorUnreachable TestTransport{..} mOrL un = do
deadProcess <- newEmptyMVar
done <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode expect
closeLocalNode localNode
putMVar deadProcess addr
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
theirAddr <- readMVar deadProcess
runProcess localNode $
monitorTestProcess theirAddr mOrL un DiedDisconnect Nothing done
takeMVar done
-- | Monitor a process which terminates normally
testMonitorNormalTermination :: TestTransport -> Bool -> Bool -> Assertion
testMonitorNormalTermination TestTransport{..} mOrL un = do
monitorSetup <- newEmptyMVar
monitoredProcess <- newEmptyMVar
done <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode $
liftIO $ readMVar monitorSetup
putMVar monitoredProcess addr
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
theirAddr <- readMVar monitoredProcess
runProcess localNode $
monitorTestProcess theirAddr mOrL un DiedNormal (Just monitorSetup) done
takeMVar done
-- | Monitor a process which terminates abnormally
testMonitorAbnormalTermination :: TestTransport -> Bool -> Bool -> Assertion
testMonitorAbnormalTermination TestTransport{..} mOrL un = do
monitorSetup <- newEmptyMVar
monitoredProcess <- newEmptyMVar
done <- newEmptyMVar
let err = userError "Abnormal termination"
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode . liftIO $ do
readMVar monitorSetup
throwIO err
putMVar monitoredProcess addr
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
theirAddr <- readMVar monitoredProcess
runProcess localNode $
monitorTestProcess theirAddr mOrL un (DiedException (show err)) (Just monitorSetup) done
takeMVar done
-- | Monitor a local process that is already dead
testMonitorLocalDeadProcess :: TestTransport -> Bool -> Bool -> Assertion
testMonitorLocalDeadProcess TestTransport{..} mOrL un = do
processAddr <- newEmptyMVar
localNode <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
forkIO $ do
addr <- forkProcess localNode $ return ()
putMVar processAddr addr
forkIO $ do
theirAddr <- readMVar processAddr
runProcess localNode $ do
monitor theirAddr
-- wait for the process to die
expect :: Process ProcessMonitorNotification
monitorTestProcess theirAddr mOrL un DiedUnknownId Nothing done
takeMVar done
-- | Monitor a remote process that is already dead
testMonitorRemoteDeadProcess :: TestTransport -> Bool -> Bool -> Assertion
testMonitorRemoteDeadProcess TestTransport{..} mOrL un = do
processDead <- newEmptyMVar
processAddr <- newEmptyMVar
done <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode . liftIO $ putMVar processDead ()
putMVar processAddr addr
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
theirAddr <- readMVar processAddr
readMVar processDead
runProcess localNode $ do
monitorTestProcess theirAddr mOrL un DiedUnknownId Nothing done
takeMVar done
-- | Monitor a process that becomes disconnected
testMonitorDisconnect :: TestTransport -> Bool -> Bool -> Assertion
testMonitorDisconnect TestTransport{..} mOrL un = do
processAddr <- newEmptyMVar
processAddr2 <- newEmptyMVar
monitorSetup <- newEmptyMVar
done <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode $ expect
addr2 <- forkProcess localNode $ return ()
putMVar processAddr addr
readMVar monitorSetup
NT.closeEndPoint (localEndPoint localNode)
threadDelay 100_000
putMVar processAddr2 addr2
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
theirAddr <- readMVar processAddr
forkProcess localNode $ do
lc <- liftIO $ readMVar processAddr2
send lc ()
runProcess localNode $ do
monitorTestProcess theirAddr mOrL un DiedDisconnect (Just monitorSetup) done
takeMVar done
-- | Test the math server (i.e., receiveWait)
testMath :: TestTransport -> Assertion
testMath TestTransport{..} = do
serverAddr <- newEmptyMVar
clientDone <- newEmptyMVar
-- Server
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode math
putMVar serverAddr addr
-- Client
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
mathServer <- readMVar serverAddr
runProcess localNode $ do
pid <- getSelfPid
send mathServer (Add pid 1 2)
three <- expect :: Process Double
send mathServer (Divide pid 8 2)
four <- expect :: Process Double
send mathServer (Divide pid 8 0)
divByZ <- expect
liftIO $ putMVar clientDone (three, four, divByZ)
res <- takeMVar clientDone
case res of
(3, 4, DivByZero) -> return ()
_ -> error $ "Something went horribly wrong"
-- | Send first message (i.e. connect) to an already terminated process
-- (without monitoring); then send another message to a second process on
-- the same remote node (we're checking that the remote node did not die)
testSendToTerminated :: TestTransport -> Assertion
testSendToTerminated TestTransport{..} = do
serverAddr1 <- newEmptyMVar
serverAddr2 <- newEmptyMVar
clientDone <- newEmptyMVar
forkIO $ do
terminated <- newEmptyMVar
localNode <- newLocalNode testTransport initRemoteTable
addr1 <- forkProcess localNode $ liftIO $ putMVar terminated ()
addr2 <- forkProcess localNode $ ping
readMVar terminated
putMVar serverAddr1 addr1
putMVar serverAddr2 addr2
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
server1 <- readMVar serverAddr1
server2 <- readMVar serverAddr2
runProcess localNode $ do
pid <- getSelfPid
send server1 "Hi"
send server2 (Pong pid)
expectPing clientDone
verifyClient "Expected Ping from server" clientDone
-- | Test (non-zero) timeout
testTimeout :: TestTransport -> Assertion
testTimeout TestTransport{..} = do
localNode <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
runProcess localNode $ do
res <- receiveTimeout 1_000_000 [match (\Add{} -> return ())]
liftIO $ putMVar done $ res == Nothing
verifyClient "Expected receiveTimeout to timeout..." done
-- | Test zero timeout
testTimeout0 :: TestTransport -> Assertion
testTimeout0 TestTransport{..} = do
serverAddr <- newEmptyMVar
clientDone <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
addr <- forkProcess localNode $ do
-- Variation on the venerable ping server which uses a zero timeout
partner <- fix $ \loop ->
receiveTimeout 0 [match (\(Pong partner) -> return partner)]
>>= maybe (liftIO (threadDelay 100_000) >> loop) return
self <- getSelfPid
send partner (Ping self)
putMVar serverAddr addr
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
server <- readMVar serverAddr
runProcess localNode $ do
pid <- getSelfPid
-- Send a bunch of messages. A large number of messages that the server
-- is not interested in, and then a single message that it wants
replicateM_ 10_000 $ send server "Irrelevant message"
send server (Pong pid)
expectPing clientDone
verifyClient "Expected Ping from server" clientDone
-- | Test typed channels
testTypedChannels :: TestTransport -> Assertion
testTypedChannels TestTransport{..} = do
serverChannel <- newEmptyMVar :: IO (MVar (SendPort (SendPort Bool, Int)))
clientDone <- newEmptyMVar
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
forkProcess localNode $ do
(serverSendPort, rport) <- newChan
liftIO $ putMVar serverChannel serverSendPort
(clientSendPort, i) <- receiveChan rport
sendChan clientSendPort (even i)
return ()
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
serverSendPort <- readMVar serverChannel
runProcess localNode $ do
(clientSendPort, rport) <- newChan
sendChan serverSendPort (clientSendPort, 5)
ch <- receiveChan rport
liftIO $ putMVar clientDone $ ch == False
verifyClient "Expected channel to send 'False'" clientDone
-- | Test merging receive ports
testMergeChannels :: TestTransport -> Assertion
testMergeChannels TestTransport{..} = do
localNode <- newLocalNode testTransport initRemoteTable
testFlat localNode True "aaabbbccc"
testFlat localNode False "abcabcabc"
testNested localNode True True "aaabbbcccdddeeefffggghhhiii"
testNested localNode True False "adgadgadgbehbehbehcficficfi"
testNested localNode False True "abcabcabcdefdefdefghighighi"
testNested localNode False False "adgbehcfiadgbehcfiadgbehcfi"
testBlocked localNode True
testBlocked localNode False
where
-- Single layer of merging
testFlat :: LocalNode -> Bool -> String -> IO ()
testFlat localNode biased expected = do
done <- newEmptyMVar
forkProcess localNode $ do
rs <- mapM charChannel "abc"
m <- mergePorts biased rs
xs <- replicateM 9 $ receiveChan m
liftIO $ putMVar done $ xs == expected
verifyClient "Expected single layer merge to match expected ordering" done
-- Two layers of merging
testNested :: LocalNode -> Bool -> Bool -> String -> IO ()
testNested localNode biasedInner biasedOuter expected = do
done <- newEmptyMVar
forkProcess localNode $ do
rss <- mapM (mapM charChannel) ["abc", "def", "ghi"]
ms <- mapM (mergePorts biasedInner) rss
m <- mergePorts biasedOuter ms
xs <- replicateM (9 * 3) $ receiveChan m
liftIO $ putMVar done $ xs == expected
verifyClient "Expected nested channels to match expeted ordering" done
-- Test that if no messages are (immediately) available, the scheduler makes no difference
testBlocked :: LocalNode -> Bool -> IO ()
testBlocked localNode biased = do
vs <- replicateM 3 newEmptyMVar
done <- newEmptyMVar
forkProcess localNode $ do
ss <- liftIO $ mapM readMVar vs
case ss of
[sa, sb, sc] ->
mapM_ ((>> pause 10000) . uncurry sendChan)
[ -- a, b, c
(sa, 'a')
, (sb, 'b')
, (sc, 'c')
-- a, c, b
, (sa, 'a')
, (sc, 'c')
, (sb, 'b')
-- b, a, c
, (sb, 'b')
, (sa, 'a')
, (sc, 'c')
-- b, c, a
, (sb, 'b')
, (sc, 'c')
, (sa, 'a')
-- c, a, b
, (sc, 'c')
, (sa, 'a')
, (sb, 'b')
-- c, b, a
, (sc, 'c')
, (sb, 'b')
, (sa, 'a')
]
_ -> die "Something went horribly wrong"
forkProcess localNode $ do
(ss, rs) <- unzip <$> replicateM 3 newChan
liftIO $ mapM_ (uncurry putMVar) $ zip vs ss
m <- mergePorts biased rs
xs <- replicateM (6 * 3) $ receiveChan m
liftIO $ putMVar done $ xs == "abcacbbacbcacabcba"
verifyClient "Expected merged ports to match expected ordering" done
mergePorts :: Serializable a => Bool -> [ReceivePort a] -> Process (ReceivePort a)
mergePorts True = mergePortsBiased
mergePorts False = mergePortsRR
charChannel :: Char -> Process (ReceivePort Char)
charChannel c = do
(sport, rport) <- newChan
replicateM_ 3 $ sendChan sport c
liftIO $ threadDelay 10_000 -- Make sure messages have been sent
return rport
testTerminate :: TestTransport -> Assertion
testTerminate TestTransport{..} = do
localNode <- newLocalNode testTransport initRemoteTable
runProcess localNode $ do
e <- try terminate :: Process (Either ProcessTerminationException ())
if either show show e == show ProcessTerminationException
then return ()
else die "Unexpected result from terminate"
testMonitorNode :: TestTransport -> Assertion
testMonitorNode TestTransport{..} = do
[node1, node2] <- replicateM 2 $ newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
closeLocalNode node1
runProcess node2 $ do
ref <- monitorNode (localNodeId node1)
receiveWait [
match (\(NodeMonitorNotification ref' nid DiedDisconnect) ->
return $ ref == ref' && nid == localNodeId node1)
] >>= liftIO . putMVar done
verifyClient "Expected NodeMonitorNotification with matching ref & nodeId" done
testMonitorLiveNode :: TestTransport -> Assertion
testMonitorLiveNode TestTransport{..} = do
[node1, node2] <- replicateM 2 $ newLocalNode testTransport initRemoteTable
ready <- newEmptyMVar
readyr <- newEmptyMVar
done <- newEmptyMVar
p <- forkProcess node1 $ return ()
forkProcess node2 $ do
ref <- monitorNode (localNodeId node1)
liftIO $ putMVar ready ()
-- node1 gets closed
liftIO $ takeMVar readyr
send p ()
receiveTimeout 10_000_000 [
match (\(NodeMonitorNotification ref' nid _) ->
(return $ ref == ref' && nid == localNodeId node1))
] >>= maybe
(liftIO $ assertFailure "Did not receive NodeMonitorNotification message within timeout window")
(liftIO . putMVar done)
takeMVar ready
closeLocalNode node1
threadDelay 1_000_000
putMVar readyr ()
verifyClient "Expected NodeMonitorNotification for LIVE node" done
testMonitorChannel :: TestTransport -> Assertion
testMonitorChannel TestTransport{..} = do
[node1, node2] <- replicateM 2 $ newLocalNode testTransport initRemoteTable
gotNotification <- newEmptyMVar
ready <- newEmptyMVar
pid <- forkProcess node1 $ do
liftIO $ putMVar ready ()
sport <- expect :: Process (SendPort ())
ref <- monitorPort sport
receiveTimeout 10_000_000 [
-- reason might be DiedUnknownId if the receive port is GCed before the
-- monitor is established (TODO: not sure that this is reasonable)
match (\(PortMonitorNotification ref' port' reason) ->
return $ ref' == ref && port' == sendPortId sport &&
(reason == DiedNormal || reason == DiedUnknownId))
] >>= maybe
(liftIO $ assertFailure "Did not receive PortMonitorNotification message within timeout window")
(liftIO . putMVar gotNotification)
runProcess node2 $ do
(sport, _) <- newChan :: Process (SendPort (), ReceivePort ())
liftIO $ takeMVar ready
send pid sport
liftIO $ threadDelay 100_000
verifyClient "Expected PortMonitorNotification" gotNotification
testRegistry :: TestTransport -> Assertion
testRegistry TestTransport{..} = do
node <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
pingServer <- forkProcess node ping
deadProcess <- forkProcess node (return ())
runProcess node $ do
register "ping" pingServer
whereis "ping" >>= liftIO . assertBool "Unexpected ping" . (== Just pingServer)
us <- getSelfPid
nsend "ping" (Pong us)
receiveWait [
matchIf (\(Ping pid') -> pingServer == pid') (const $ return ())
]
checkRegException "dead" Nothing deadProcess
checkRegException "ping" (Just pingServer) deadProcess
try (unregister "dead") >>= checkReg "dead" Nothing
liftIO $ putMVar done ()
takeMVar done
where
checkRegException name pid dead =
try (register name dead) >>= checkReg name pid
checkReg _ _ res =
case res of
Left (ProcessRegistrationException _ _) -> return ()
_ -> die $ "Unexpected Registration" ++ show res
testRegistryRemoteProcess :: TestTransport -> Assertion
testRegistryRemoteProcess TestTransport{..} = do
node1 <- newLocalNode testTransport initRemoteTable
node2 <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
pingServer <- forkProcess node1 ping
runProcess node2 $ do
register "ping" pingServer
whereis "ping" >>= liftIO . assertBool "Unexpected ping" . (== Just pingServer)
us <- getSelfPid
nsend "ping" (Pong us)
receiveWait [
matchIf (\(Ping pid') -> pingServer == pid')
(const $ liftIO $ putMVar done ())
]
takeMVar done
testRemoteRegistry :: TestTransport -> Assertion
testRemoteRegistry TestTransport{..} = do
node1 <- newLocalNode testTransport initRemoteTable
node2 <- newLocalNode testTransport initRemoteTable
pingServer <- forkProcess node1 ping
deadProcess <- forkProcess node1 (return ())
runProcess node2 $ do
let nid1 = localNodeId node1
registerRemoteAsync nid1 "ping" pingServer
receiveWait [
matchIf (\(RegisterReply label' _ (Just pid)) ->
"ping" == label' && pid == pingServer)
(\(RegisterReply _ _ _) -> return ()) ]
pid <- verifyWhereIsRemote nid1 "ping"
liftIO $ assertBool "Expected pindServer to match pid" $ pingServer == pid
us <- getSelfPid
nsendRemote nid1 "ping" (Pong us)
receiveWait [
match (\(Ping pid') -> return $ pingServer == pid')
] >>= liftIO . assertBool "Expected Ping with ping server's ProcessId"
-- test that if process was not registered Nothing is returned
-- in owner field.
registerRemoteAsync nid1 "dead" deadProcess
receiveWait [ matchIf (\(RegisterReply label' _ _) -> "dead" == label')
(\(RegisterReply _ f mPid) -> return (not f && isNothing mPid))
] >>= liftIO . assertBool "Expected False Nothing in RegisterReply"
registerRemoteAsync nid1 "ping" deadProcess
receiveWait [
matchIf (\(RegisterReply label' False mPid) ->
"ping" == label' && isJust mPid)
(\(RegisterReply _ f (Just pid'')) -> return (not f && pid'' == pingServer))
] >>= liftIO . assertBool "Expected False and (Just alreadyRegisteredPid) in RegisterReply"
unregisterRemoteAsync nid1 "dead"
receiveWait [
matchIf (\(RegisterReply label' _ _) -> "dead" == label')
(\(RegisterReply _ f mPid) -> return (not f && isNothing mPid))
] >>= liftIO . assertBool "Expected False and Nothing in RegisterReply"
testRemoteRegistryRemoteProcess :: TestTransport -> Assertion
testRemoteRegistryRemoteProcess TestTransport{..} = do
node1 <- newLocalNode testTransport initRemoteTable
node2 <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
pingServer <- forkProcess node2 ping
runProcess node2 $ do
let nid1 = localNodeId node1
registerRemoteAsync nid1 "ping" pingServer
receiveWait [
matchIf (\(RegisterReply label' _ _) -> "ping" == label')
(\(RegisterReply _ _ _) -> return ()) ]
pid <- verifyWhereIsRemote nid1 "ping"
liftIO $ assertBool "Expected pingServer to match remote name" $ pingServer == pid
us <- getSelfPid
nsendRemote nid1 "ping" (Pong us)
receiveWait [
match (\(Ping pid') -> return $ pingServer == pid')
] >>= liftIO . putMVar done
verifyClient "Expected Ping with ping server's ProcessId" done
testSpawnLocal :: TestTransport -> Assertion
testSpawnLocal TestTransport{..} = do
node <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
runProcess node $ do
us <- getSelfPid
pid <- spawnLocal $ do
sport <- expect
sendChan sport (1234 :: Int)
sport <- spawnChannelLocal $
\rport -> (receiveChan rport :: Process Int) >>= send us
send pid sport
expect >>= liftIO . putMVar done
res <- takeMVar done
assertBool "Expected 1234 :: Int" $ res == (1234 :: Int)
testSpawnAsyncStrictness :: TestTransport -> Assertion
testSpawnAsyncStrictness TestTransport{..} = do
node <- newLocalNode testTransport initRemoteTable
done <- newEmptyMVar
runProcess node $ do
here <-getSelfNode
ev <- try $ spawnAsync here (error "boom")
liftIO $ case ev of
Right _ -> putMVar done (error "Exception didn't fire")
Left (_::SomeException) -> putMVar done (return ())
join $ takeMVar done
testReconnect :: TestTransport -> Assertion
testReconnect TestTransport{..} = do
[node1, node2] <- replicateM 2 $ newLocalNode testTransport initRemoteTable
let nid1 = localNodeId node1
processA <- newEmptyMVar
[sendTestOk, registerTestOk] <- replicateM 2 newEmptyMVar
forkProcess node1 $ do
us <- getSelfPid
liftIO $ putMVar processA us
msg1 <- expect
msg2 <- expect
liftIO $ do
assertBool "messages did not match" $ msg1 == "message 1" && msg2 == "message 3"
putMVar sendTestOk ()
forkProcess node2 $ do
{-
- Make sure there is no implicit reconnect on normal message sending
-}
them <- liftIO $ readMVar processA
send them "message 1" >> liftIO (threadDelay 100000)
-- Simulate network failure
liftIO $ syncBreakConnection testBreakConnection node1 node2
-- Should not arrive
send them "message 2"
-- Should arrive
reconnect them
send them "message 3"
liftIO $ takeMVar sendTestOk
{-
- Test that there *is* implicit reconnect on node controller messages
-}
us <- getSelfPid
registerRemoteAsync nid1 "a" us -- registerRemote is asynchronous
receiveWait [
matchIf (\(RegisterReply label' _ _) -> "a" == label')
(\(RegisterReply _ _ _) -> return ()) ]
_ <- whereisRemote nid1 "a"
-- Simulate network failure
liftIO $ syncBreakConnection testBreakConnection node1 node2
-- This will happen due to implicit reconnect
registerRemoteAsync nid1 "b" us
receiveWait [
matchIf (\(RegisterReply label' _ _) -> "b" == label')
(\(RegisterReply _ _ _) -> return ()) ]
-- Should happen
registerRemoteAsync nid1 "c" us
receiveWait [
matchIf (\(RegisterReply label' _ _) -> "c" == label')
(\(RegisterReply _ _ _) -> return ()) ]
-- Check
mPid <- whereisRemote nid1 "a" -- this will fail because the name is removed when the node is disconnected
liftIO $ assertBool "Expected remote name to be lost" $ mPid == Nothing
verifyWhereIsRemote nid1 "b" -- this will suceed because the value is set after thereconnect
verifyWhereIsRemote nid1 "c"
liftIO $ putMVar registerTestOk ()
takeMVar registerTestOk
-- | Tests that unreliable messages arrive sorted even when there are connection
-- failures.
testUSend :: (ProcessId -> Int -> Process ())
-> TestTransport -> Int -> Assertion
testUSend usendPrim TestTransport{..} numMessages = do
[node1, node2] <- replicateM 2 $ newLocalNode testTransport initRemoteTable
let nid1 = localNodeId node1
nid2 = localNodeId node2
processA <- newEmptyMVar
usendTestOk <- newEmptyMVar
forkProcess node1 $ flip catch (\e -> liftIO $ print (e :: SomeException) ) $ do
us <- getSelfPid
liftIO $ putMVar processA us
them <- expect
send them ()
_ <- monitor them
let -- Collects messages from 'them' until the sender dies.
-- Disconnection notifications are ignored.
receiveMessages :: Process [Int]
receiveMessages = receiveWait
[ match $ \mn -> case mn of
ProcessMonitorNotification _ _ DiedDisconnect -> do
monitor them
receiveMessages
_ -> return []
, match $ \i -> fmap (i :) receiveMessages
]
msgs <- receiveMessages
let -- Checks that the input list is sorted.
isSorted :: [Int] -> Bool
isSorted (x : xs@(y : _)) = x <= y && isSorted xs
isSorted _ = True
-- The list can't be null since there are no failures after sending
-- the last message.
liftIO $ putMVar usendTestOk $ isSorted msgs && not (null msgs)
forkProcess node2 $ do
them <- liftIO $ readMVar processA
getSelfPid >>= send them
expect :: Process ()
forM_ [1..numMessages] $ \i -> do
liftIO $ testBreakConnection (nodeAddress nid1) (nodeAddress nid2)
usendPrim them i
liftIO (threadDelay 30000)
res <- takeMVar usendTestOk
assertBool "Unexpected failure after sending last msg" res
-- | Test 'matchAny'. This repeats the 'testMath' but with a proxy server
-- in between
testMatchAny :: TestTransport -> Assertion
testMatchAny TestTransport{..} = do
proxyAddr <- newEmptyMVar
clientDone <- newEmptyMVar
-- Math server
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
mathServer <- forkProcess localNode math
proxyServer <- forkProcess localNode $ forever $ do
msg <- receiveWait [ matchAny return ]
forward msg mathServer
putMVar proxyAddr proxyServer
-- Client
forkIO $ do
localNode <- newLocalNode testTransport initRemoteTable
mathServer <- readMVar proxyAddr
runProcess localNode $ do
pid <- getSelfPid
send mathServer (Add pid 1 2)
three <- expect :: Process Double
send mathServer (Divide pid 8 2)
four <- expect :: Process Double
send mathServer (Divide pid 8 0)
divByZ <- expect
liftIO $ putMVar clientDone (three, four, divByZ)
res <- takeMVar clientDone
case res of
(3, 4, DivByZero) -> return ()
_ -> error "Unexpected result"
-- | Test 'matchAny'. This repeats the 'testMath' but with a proxy server
-- in between, however we block 'Divide' requests ....
testMatchAnyHandle :: TestTransport -> Assertion
testMatchAnyHandle TestTransport{..} = do
proxyAddr <- newEmptyMVar
clientDone <- newEmptyMVar