-
Notifications
You must be signed in to change notification settings - Fork 86
/
Server2.hs
3578 lines (3286 loc) · 147 KB
/
Server2.hs
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 BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
-- for 'debugTracer'
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
module Test.Ouroboros.Network.Server2 (tests) where
import Control.Exception (AssertionFailed, SomeAsyncException (..))
import Control.Monad (replicateM, when, (>=>))
import Control.Monad.Class.MonadAsync
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadST (MonadST)
import qualified Control.Monad.Class.MonadSTM as LazySTM
import Control.Monad.Class.MonadSTM.Strict
import Control.Monad.Class.MonadSay
import Control.Monad.Class.MonadThrow
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer
import Control.Monad.IOSim
import Control.Tracer (Tracer (..), contramap, nullTracer)
import Codec.Serialise.Class (Serialise)
import Data.Bifoldable
import Data.Bifunctor
import Data.Bitraversable
import Data.Bool (bool)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Foldable (foldMap')
import Data.Functor (void, ($>), (<&>))
import Data.List (delete, dropWhileEnd, find, foldl', intercalate,
mapAccumL, nub, (\\))
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.Trace as Trace
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust, fromMaybe, isJust)
import Data.Monoid (Sum (..))
import Data.Monoid.Synchronisation (FirstToFinish (..))
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import Data.Void (Void)
import Foreign.C.Error
import qualified GHC.IO.Exception as IO
import Text.Printf
import Test.QuickCheck
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck
import Control.Concurrent.JobPool
import Codec.CBOR.Term (Term)
import qualified Network.Mux as Mux
import Network.Mux.Types (MuxRuntimeError)
import qualified Network.Socket as Socket
import Network.TypedProtocol.Core
import Network.TypedProtocol.ReqResp.Client
import Network.TypedProtocol.ReqResp.Codec.CBOR
import Network.TypedProtocol.ReqResp.Examples
import Network.TypedProtocol.ReqResp.Server
import Network.TypedProtocol.ReqResp.Type
import Ouroboros.Network.Channel (fromChannel)
import Ouroboros.Network.ConnectionHandler
import Ouroboros.Network.ConnectionId
import Ouroboros.Network.ConnectionManager.Core
import Ouroboros.Network.ConnectionManager.Types
import qualified Ouroboros.Network.ConnectionManager.Types as CM
import Ouroboros.Network.Driver.Limits
import Ouroboros.Network.IOManager
import Ouroboros.Network.InboundGovernor (InboundGovernorTrace (..),
RemoteSt (..))
import qualified Ouroboros.Network.InboundGovernor as IG
import qualified Ouroboros.Network.InboundGovernor.ControlChannel as Server
import Ouroboros.Network.InboundGovernor.State
(InboundGovernorCounters (..))
import Ouroboros.Network.Mux
import Ouroboros.Network.MuxMode
import Ouroboros.Network.Protocol.Handshake
import Ouroboros.Network.Protocol.Handshake.Codec
(cborTermVersionDataCodec, noTimeLimitsHandshake,
timeLimitsHandshake)
import Ouroboros.Network.Protocol.Handshake.Type (Handshake)
import Ouroboros.Network.Protocol.Handshake.Unversioned
import Ouroboros.Network.Protocol.Handshake.Version (Acceptable (..))
import Ouroboros.Network.RethrowPolicy
import Ouroboros.Network.Server.RateLimiting
(AcceptedConnectionsLimit (..))
import Ouroboros.Network.Server2 (RemoteTransition,
RemoteTransitionTrace, ServerArguments (..))
import qualified Ouroboros.Network.Server2 as Server
import Ouroboros.Network.Snocket (Snocket, TestAddress (..),
socketSnocket)
import qualified Ouroboros.Network.Snocket as Snocket
import Simulation.Network.Snocket
import Ouroboros.Network.Testing.Data.AbsBearerInfo
(AbsAttenuation (..), AbsBearerInfo (..),
AbsBearerInfoScript (..), AbsDelay (..), AbsSDUSize (..),
AbsSpeed (..), NonFailingAbsBearerInfoScript (..),
absNoAttenuation, toNonFailingAbsBearerInfoScript)
import Ouroboros.Network.Testing.Utils (genDelayWithPrecision)
import Test.Ouroboros.Network.ConnectionManager
(allValidTransitionsNames, validTransitionMap,
verifyAbstractTransition)
import Test.Ouroboros.Network.Orphans ()
import Test.Simulation.Network.Snocket hiding (tests)
tests :: TestTree
tests =
testGroup "Ouroboros.Network.Server2"
[ testProperty "unidirectional_IO" prop_unidirectional_IO
, testProperty "unidirectional_Sim" prop_unidirectional_Sim
, testProperty "bidirectional_IO" prop_bidirectional_IO
, testProperty "bidirectional_Sim" prop_bidirectional_Sim
, testProperty "connection_manager_pruning"
prop_connection_manager_pruning
, testProperty "inbound_governor_pruning"
prop_inbound_governor_pruning
, testProperty "never_above_hardlimit"
prop_never_above_hardlimit
, testProperty "connection_manager_valid_transitions"
prop_connection_manager_valid_transitions
, testProperty "connection_manager_no_invalid_traces"
prop_connection_manager_no_invalid_traces
, testProperty "connection_manager_transitions_coverage"
prop_connection_manager_transitions_coverage
, testProperty "inbound_governor_no_invalid_traces"
prop_inbound_governor_no_invalid_traces
, testProperty "inbound_governor_transitions_coverage"
prop_inbound_governor_transitions_coverage
, testProperty "inbound_governor_valid_transitions"
prop_inbound_governor_valid_transitions
, testProperty "inbound_governor_no_unsupported_state"
prop_inbound_governor_no_unsupported_state
, testProperty "connection_manager_valid_transition_order"
prop_connection_manager_valid_transition_order
, testProperty "inbound_governor_valid_transition_order"
prop_inbound_governor_valid_transition_order
, testProperty "connection_manager_counters"
prop_connection_manager_counters
, testProperty "inbound_governor_counters"
prop_inbound_governor_counters
, testGroup "unit_server_accept_error"
[ testProperty "throw ConnectionAborted"
(unit_server_accept_error IOErrConnectionAborted IOErrThrow)
, testProperty "throw ResourceExhausted"
(unit_server_accept_error IOErrResourceExhausted IOErrThrow)
, testProperty "return ConnectionAborted"
(unit_server_accept_error IOErrConnectionAborted IOErrReturn)
, testProperty "return ResourceExhausted"
(unit_server_accept_error IOErrResourceExhausted IOErrReturn)
]
, testProperty "unit_connection_terminated_when_negotiating"
unit_connection_terminated_when_negotiating
, testGroup "generators"
[ testProperty "MultiNodeScript"
prop_generator_MultiNodeScript
]
]
--
-- Server tests
--
-- | The protocol will run three instances of `ReqResp` protocol; one for each
-- state: warm, hot and established.
--
data ClientAndServerData req = ClientAndServerData {
accumulatorInit :: req,
-- ^ Initial value. In for each request the server sends back a list received requests (in
-- reverse order) terminating with the accumulatorInit.
hotInitiatorRequests :: [[req]],
-- ^ list of requests run by the hot initiator in each round; Running
-- multiple rounds allows us to test restarting of responders.
warmInitiatorRequests :: [[req]],
-- ^ list of requests run by the warm initiator in each round
establishedInitiatorRequests :: [[req]]
-- ^ list of requests run by the established initiator in each round
}
deriving Show
-- Number of rounds to exhaust all the requests.
--
numberOfRounds :: ClientAndServerData req -> Int
numberOfRounds ClientAndServerData {
hotInitiatorRequests,
warmInitiatorRequests,
establishedInitiatorRequests
} =
length hotInitiatorRequests
`max`
length warmInitiatorRequests
`max`
length establishedInitiatorRequests
-- | We use it to generate a list of messages for a list of rounds. In each
-- round we connect to the same server, and run 'ReqResp' protocol.
--
arbitraryList :: Arbitrary a => Gen [[a]]
arbitraryList =
resize 3 (listOf (resize 3 (listOf (resize 100 arbitrary))))
instance Arbitrary req => Arbitrary (ClientAndServerData req) where
arbitrary =
ClientAndServerData <$> arbitrary
<*> arbitraryList
<*> arbitraryList
<*> arbitraryList
shrink (ClientAndServerData ini hot warm est) = concat
[ shrink ini <&> \ ini' -> ClientAndServerData ini' hot warm est
, shrink hot <&> \ hot' -> ClientAndServerData ini hot' warm est
, shrink warm <&> \ warm' -> ClientAndServerData ini hot warm' est
, shrink est <&> \ est' -> ClientAndServerData ini hot warm est'
]
expectedResult :: ClientAndServerData req
-> ClientAndServerData req
-> [Bundle [[req]]]
expectedResult client@ClientAndServerData
{ hotInitiatorRequests
, warmInitiatorRequests
, establishedInitiatorRequests
}
ClientAndServerData { accumulatorInit
} =
go
(take rounds $ hotInitiatorRequests ++ repeat [])
(take rounds $ warmInitiatorRequests ++ repeat [])
(take rounds $ establishedInitiatorRequests ++ repeat [])
where
rounds = numberOfRounds client
fn acc x = (x : acc, x : acc)
go (a : as) (b : bs) (c : cs) =
Bundle
(WithHot (snd $ mapAccumL fn [accumulatorInit] a))
(WithWarm (snd $ mapAccumL fn [accumulatorInit] b))
(WithEstablished (snd $ mapAccumL fn [accumulatorInit] c))
: go as bs cs
go [] [] [] = []
go _ _ _ = error "expectedResult: impossible happened"
noNextRequests :: forall stm req peerAddr. Applicative stm => Bundle (ConnectionId peerAddr -> stm [req])
noNextRequests = pure $ \_ -> pure []
-- | Next requests bundle for bidirectional and unidirectional experiments.
oneshotNextRequests
:: forall req peerAddr m. MonadSTM m
=> ClientAndServerData req
-> m (Bundle (ConnectionId peerAddr -> STM m [req]))
oneshotNextRequests ClientAndServerData {
hotInitiatorRequests,
warmInitiatorRequests,
establishedInitiatorRequests
} = do
-- we pass a `StricTVar` with all the requests to each initiator. This way
-- the each round (which runs a single instance of `ReqResp` protocol) will
-- use its own request list.
hotRequestsVar <- newTVarIO hotInitiatorRequests
warmRequestsVar <- newTVarIO warmInitiatorRequests
establishedRequestsVar <- newTVarIO establishedInitiatorRequests
return $ Bundle (WithHot hotRequestsVar)
(WithWarm warmRequestsVar)
(WithEstablished establishedRequestsVar)
<&> \ reqVar _ -> popRequests reqVar
where
popRequests requestsVar = do
requests <- readTVar requestsVar
case requests of
reqs : rest -> writeTVar requestsVar rest $> reqs
[] -> pure []
-- | Configurable timeouts. We use different timeouts for 'IO' and 'IOSim' property tests.
--
data Timeouts = Timeouts {
tProtocolIdleTimeout :: DiffTime,
tOutboundIdleTimeout :: DiffTime,
tTimeWaitTimeout :: DiffTime
}
-- | Timeouts for 'IO' tests.
--
ioTimeouts :: Timeouts
ioTimeouts = Timeouts {
tProtocolIdleTimeout = 0.1,
tOutboundIdleTimeout = 0.1,
tTimeWaitTimeout = 0.1
}
-- | Timeouts for 'IOSim' tests.
--
simTimeouts :: Timeouts
simTimeouts = Timeouts {
tProtocolIdleTimeout = 5,
tOutboundIdleTimeout = 5,
tTimeWaitTimeout = 30
}
--
-- Various ConnectionManagers
--
type ConnectionManagerMonad m =
( MonadAsync m, MonadCatch m, MonadEvaluate m, MonadFork m, MonadMask m
, MonadST m, MonadTime m, MonadTimer m, MonadThrow m, MonadThrow (STM m)
)
withInitiatorOnlyConnectionManager
:: forall name peerAddr socket req resp m a.
( ConnectionManagerMonad m
, resp ~ [req]
, Ord peerAddr, Show peerAddr, Typeable peerAddr
, Serialise req, Typeable req
, MonadAsync m
, MonadLabelledSTM m
, MonadSay m, Show req
, Show name
)
=> name
-- ^ identifier (for logging)
-> Timeouts
-> Tracer m (WithName name (AbstractTransitionTrace peerAddr))
-> Tracer m (WithName name
(ConnectionManagerTrace
peerAddr
(ConnectionHandlerTrace UnversionedProtocol DataFlowProtocolData)))
-> Snocket m socket peerAddr
-- ^ series of request possible to do with the bidirectional connection
-- manager towards some peer.
-> Maybe peerAddr
-> Bundle (ConnectionId peerAddr -> STM m [req])
-- ^ Functions to get the next requests for a given connection
-> ProtocolTimeLimits (Handshake UnversionedProtocol Term)
-- ^ Handshake time limits
-> AcceptedConnectionsLimit
-> (MuxConnectionManager
InitiatorMode socket peerAddr
UnversionedProtocol ByteString m [resp] Void
-> m a)
-> m a
withInitiatorOnlyConnectionManager name timeouts trTracer cmTracer snocket localAddr
nextRequests handshakeTimeLimits acceptedConnLimit k = do
mainThreadId <- myThreadId
let muxTracer = (name,) `contramap` nullTracer -- mux tracer
withConnectionManager
ConnectionManagerArguments {
-- ConnectionManagerTrace
cmTracer = WithName name
`contramap` cmTracer,
cmTrTracer = (WithName name . fmap abstractState)
`contramap` trTracer,
-- MuxTracer
cmMuxTracer = muxTracer,
cmIPv4Address = localAddr,
cmIPv6Address = Nothing,
cmAddressType = \_ -> Just IPv4Address,
cmSnocket = snocket,
connectionDataFlow = getProtocolDataFlow . snd,
cmPrunePolicy = simplePrunePolicy,
cmConnectionsLimits = acceptedConnLimit,
cmTimeWaitTimeout = tTimeWaitTimeout timeouts,
cmOutboundIdleTimeout = tOutboundIdleTimeout timeouts
}
(makeConnectionHandler
muxTracer
SingInitiatorMode
clientMiniProtocolBundle
HandshakeArguments {
-- TraceSendRecv
haHandshakeTracer = (name,) `contramap` nullTracer,
haHandshakeCodec = unversionedHandshakeCodec,
haVersionDataCodec = cborTermVersionDataCodec dataFlowProtocolDataCodec,
haAcceptVersion = acceptableVersion,
haTimeLimits = handshakeTimeLimits
}
(dataFlowProtocol Unidirectional clientApplication)
(mainThreadId, debugMuxErrorRethrowPolicy
<> debugMuxRuntimeErrorRethrowPolicy
<> debugIOErrorRethrowPolicy
<> assertRethrowPolicy))
(\_ -> HandshakeFailure)
NotInResponderMode
(\cm ->
k cm `catch` \(e :: SomeException) -> throwIO e)
where
clientMiniProtocolBundle :: Mux.MiniProtocolBundle InitiatorMode
clientMiniProtocolBundle = Mux.MiniProtocolBundle
[ Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 1,
Mux.miniProtocolDir = Mux.InitiatorDirectionOnly,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 2,
Mux.miniProtocolDir = Mux.InitiatorDirectionOnly,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 3,
Mux.miniProtocolDir = Mux.InitiatorDirectionOnly,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
]
clientApplication :: Bundle
(ConnectionId peerAddr
-> ControlMessageSTM m
-> [MiniProtocol InitiatorMode ByteString m [resp] Void])
clientApplication = mkProto <$> (Mux.MiniProtocolNum <$> nums)
<*> nextRequests
where nums = Bundle (WithHot 1) (WithWarm 2) (WithEstablished 3)
mkProto miniProtocolNum nextRequest connId _ =
[MiniProtocol {
miniProtocolNum,
miniProtocolLimits = Mux.MiniProtocolLimits maxBound,
miniProtocolRun = reqRespInitiator miniProtocolNum
(nextRequest connId)
}]
reqRespInitiator :: Mux.MiniProtocolNum
-> STM m [req]
-> RunMiniProtocol InitiatorMode ByteString m [resp] Void
reqRespInitiator protocolNum nextRequest =
InitiatorProtocolOnly
(MuxPeerRaw $ \channel ->
runPeerWithLimits
(WithName (name,"Initiator",protocolNum) `contramap` nullTracer)
-- TraceSendRecv
codecReqResp
reqRespSizeLimits
reqRespTimeLimits
channel
(Effect $ do
reqs <- atomically nextRequest
pure $ reqRespClientPeer (reqRespClientMap reqs)))
--
-- Rethrow policies
--
debugMuxErrorRethrowPolicy :: RethrowPolicy
debugMuxErrorRethrowPolicy =
mkRethrowPolicy $
\_ MuxError { errorType } ->
case errorType of
MuxIOException _ -> ShutdownPeer
MuxBearerClosed -> ShutdownPeer
MuxSDUReadTimeout -> ShutdownPeer
MuxSDUWriteTimeout -> ShutdownPeer
_ -> ShutdownNode
debugMuxRuntimeErrorRethrowPolicy :: RethrowPolicy
debugMuxRuntimeErrorRethrowPolicy =
mkRethrowPolicy $
\_ (_ :: MuxRuntimeError) -> ShutdownPeer
debugIOErrorRethrowPolicy :: RethrowPolicy
debugIOErrorRethrowPolicy =
mkRethrowPolicy $
\_ (_ :: IOError) -> ShutdownPeer
assertRethrowPolicy :: RethrowPolicy
assertRethrowPolicy =
mkRethrowPolicy $
\_ (_ :: AssertionFailed) -> ShutdownNode
-- | Runs an example server which runs a single 'ReqResp' protocol for any hot
-- \/ warm \/ established peers and also gives access to bidirectional
-- 'ConnectionManager'. This gives a way to connect to other peers.
-- Slightly unfortunate design decision does not give us a way to create
-- a client per connection. This means that this connection manager takes list
-- of 'req' type which it will make to the other side (they will be multiplexed
-- across warm \/ how \/ established) protocols.
--
withBidirectionalConnectionManager
:: forall name peerAddr socket acc req resp m a.
( ConnectionManagerMonad m
, acc ~ [req], resp ~ [req]
, Ord peerAddr, Show peerAddr, Typeable peerAddr
, Serialise req, Typeable req
-- debugging
, MonadAsync m
, MonadLabelledSTM m
, MonadSay m, Show req
, Show name
)
=> name
-> Timeouts
-- ^ identifier (for logging)
-> Tracer m (WithName name (RemoteTransitionTrace peerAddr))
-> Tracer m (WithName name (AbstractTransitionTrace peerAddr))
-> Tracer m (WithName name
(ConnectionManagerTrace
peerAddr
(ConnectionHandlerTrace UnversionedProtocol DataFlowProtocolData)))
-> Tracer m (WithName name (InboundGovernorTrace peerAddr))
-> Snocket m socket peerAddr
-> socket
-- ^ listening socket
-> Maybe peerAddr
-> acc
-- ^ Initial state for the server
-> Bundle (ConnectionId peerAddr -> STM m [req])
-- ^ Functions to get the next requests for a given connection
-- ^ series of request possible to do with the bidirectional connection
-- manager towards some peer.
-> ProtocolTimeLimits (Handshake UnversionedProtocol Term)
-- ^ Handshake time limits
-> AcceptedConnectionsLimit
-> (MuxConnectionManager
InitiatorResponderMode socket peerAddr
UnversionedProtocol ByteString m [resp] acc
-> peerAddr
-> Async m Void
-> m a)
-> m a
withBidirectionalConnectionManager name timeouts
inboundTrTracer trTracer
cmTracer inboundTracer
snocket socket localAddress
accumulatorInit nextRequests
handshakeTimeLimits
acceptedConnLimit k = do
mainThreadId <- myThreadId
inbgovControlChannel <- Server.newControlChannel
-- we are not using the randomness
observableStateVar <- Server.newObservableStateVarFromSeed 0
let muxTracer = WithName name `contramap` nullTracer -- mux tracer
withConnectionManager
ConnectionManagerArguments {
-- ConnectionManagerTrace
cmTracer = WithName name
`contramap` cmTracer,
cmTrTracer = (WithName name . fmap abstractState)
`contramap` trTracer,
-- MuxTracer
cmMuxTracer = muxTracer,
cmIPv4Address = localAddress,
cmIPv6Address = Nothing,
cmAddressType = \_ -> Just IPv4Address,
cmSnocket = snocket,
cmTimeWaitTimeout = tTimeWaitTimeout timeouts,
cmOutboundIdleTimeout = tOutboundIdleTimeout timeouts,
connectionDataFlow = getProtocolDataFlow . snd,
cmPrunePolicy = simplePrunePolicy,
cmConnectionsLimits = acceptedConnLimit
}
(makeConnectionHandler
muxTracer
SingInitiatorResponderMode
serverMiniProtocolBundle
HandshakeArguments {
-- TraceSendRecv
haHandshakeTracer = WithName name `contramap` nullTracer,
haHandshakeCodec = unversionedHandshakeCodec,
haVersionDataCodec = cborTermVersionDataCodec dataFlowProtocolDataCodec,
haAcceptVersion = acceptableVersion,
haTimeLimits = handshakeTimeLimits
}
(dataFlowProtocol Duplex serverApplication)
(mainThreadId, debugMuxErrorRethrowPolicy
<> debugMuxRuntimeErrorRethrowPolicy
<> debugIOErrorRethrowPolicy
<> assertRethrowPolicy))
(\_ -> HandshakeFailure)
(InResponderMode inbgovControlChannel)
$ \connectionManager ->
do
serverAddr <- Snocket.getLocalAddr snocket socket
withAsync
(Server.run
ServerArguments {
serverSockets = socket :| [],
serverSnocket = snocket,
serverTrTracer =
WithName name `contramap` inboundTrTracer,
serverTracer =
WithName name `contramap` nullTracer, -- ServerTrace
serverInboundGovernorTracer =
WithName name `contramap` inboundTracer, -- InboundGovernorTrace
serverConnectionLimits = acceptedConnLimit,
serverConnectionManager = connectionManager,
serverInboundIdleTimeout = tProtocolIdleTimeout timeouts,
serverControlChannel = inbgovControlChannel,
serverObservableStateVar = observableStateVar
}
)
(\serverAsync -> k connectionManager serverAddr serverAsync)
`catch` \(e :: SomeException) -> do
throwIO e
where
-- for a bidirectional mux we need to define 'Mux.MiniProtocolInfo' for each
-- protocol for each direction.
serverMiniProtocolBundle :: Mux.MiniProtocolBundle InitiatorResponderMode
serverMiniProtocolBundle = Mux.MiniProtocolBundle
[ Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 1,
Mux.miniProtocolDir = Mux.ResponderDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 1,
Mux.miniProtocolDir = Mux.InitiatorDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 2,
Mux.miniProtocolDir = Mux.ResponderDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 2,
Mux.miniProtocolDir = Mux.InitiatorDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 3,
Mux.miniProtocolDir = Mux.ResponderDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
, Mux.MiniProtocolInfo {
Mux.miniProtocolNum = Mux.MiniProtocolNum 3,
Mux.miniProtocolDir = Mux.InitiatorDirection,
Mux.miniProtocolLimits = Mux.MiniProtocolLimits maxBound
}
]
serverApplication :: Bundle
(ConnectionId peerAddr
-> ControlMessageSTM m
-> [MiniProtocol InitiatorResponderMode ByteString m [resp] acc])
serverApplication = mkProto <$> (Mux.MiniProtocolNum <$> nums) <*> nextRequests
where nums = Bundle (WithHot 1) (WithWarm 2) (WithEstablished 3)
mkProto miniProtocolNum nextRequest connId _ =
[MiniProtocol {
miniProtocolNum,
miniProtocolLimits = Mux.MiniProtocolLimits maxBound,
miniProtocolRun = reqRespInitiatorAndResponder
miniProtocolNum
accumulatorInit
(nextRequest connId)
}]
reqRespInitiatorAndResponder
:: Mux.MiniProtocolNum
-> acc
-> STM m [req]
-> RunMiniProtocol InitiatorResponderMode ByteString m [resp] acc
reqRespInitiatorAndResponder protocolNum accInit nextRequest =
InitiatorAndResponderProtocol
(MuxPeerRaw $ \channel ->
runPeerWithLimits
(WithName (name,"Initiator",protocolNum) `contramap` nullTracer)
-- TraceSendRecv
codecReqResp
reqRespSizeLimits
reqRespTimeLimits
channel
(Effect $ do
reqs <- atomically nextRequest
pure $ reqRespClientPeer (reqRespClientMap reqs)))
(MuxPeerRaw $ \channel ->
runPeerWithLimits
(WithName (name,"Responder",protocolNum) `contramap` nullTracer)
-- TraceSendRecv
codecReqResp
reqRespSizeLimits
reqRespTimeLimits
channel
(reqRespServerPeer $ reqRespServerMapAccumL' accInit))
reqRespServerMapAccumL' :: acc -> ReqRespServer req resp m acc
reqRespServerMapAccumL' = go
where
fn acc x = (x : acc, x : acc)
go acc =
ReqRespServer {
recvMsgReq = \req ->
let (acc', resp) = fn acc req
in return (resp, go acc'),
recvMsgDone = return acc
}
reqRespSizeLimits :: forall req resp. ProtocolSizeLimits (ReqResp req resp)
ByteString
reqRespSizeLimits = ProtocolSizeLimits
{ sizeLimitForState
, dataSize = fromIntegral . LBS.length
}
where
sizeLimitForState :: forall (pr :: PeerRole) (st :: ReqResp req resp).
PeerHasAgency pr st -> Word
sizeLimitForState _ = maxBound
reqRespTimeLimits :: forall req resp. ProtocolTimeLimits (ReqResp req resp)
reqRespTimeLimits = ProtocolTimeLimits { timeLimitForState }
where
timeLimitForState :: forall (pr :: PeerRole) (st :: ReqResp req resp).
PeerHasAgency pr st -> Maybe DiffTime
timeLimitForState (ClientAgency TokIdle) = Nothing
timeLimitForState (ServerAgency TokBusy) = Just 60
-- | Run all initiator mini-protocols and collect results. Throw exception if
-- any of the thread returned an exception.
--
-- This function assumes that there's one established, one warm and one hot
-- mini-protocol, which is compatible with both
--
-- * 'withInitiatorOnlyConnectionManager', and
-- * 'withBidirectionalConnectionManager'.
--
runInitiatorProtocols
:: forall muxMode m a b.
( MonadAsync m
, MonadCatch m
, MonadSTM m
, MonadThrow (STM m)
, HasInitiator muxMode ~ True
, MonadSay m
)
=> SingMuxMode muxMode
-> Mux.Mux muxMode m
-> MuxBundle muxMode ByteString m a b
-> m (Bundle a)
runInitiatorProtocols
singMuxMode mux
bundle
= do -- start all mini-protocols
bundle' <- traverse runInitiator (head <$> bundle)
-- await for their termination
traverse (atomically >=> either throwIO return)
bundle'
where
runInitiator :: MiniProtocol muxMode ByteString m a b
-> m (STM m (Either SomeException a))
runInitiator ptcl =
Mux.runMiniProtocol
mux
(miniProtocolNum ptcl)
(case singMuxMode of
SingInitiatorMode -> Mux.InitiatorDirectionOnly
SingInitiatorResponderMode -> Mux.InitiatorDirection)
Mux.StartEagerly
(runMuxPeer
(case miniProtocolRun ptcl of
InitiatorProtocolOnly initiator -> initiator
InitiatorAndResponderProtocol initiator _ -> initiator)
. fromChannel)
--
-- Experiments \/ Demos & Properties
--
-- | This test runs an initiator only connection manager (client side) and bidirectional
-- connection manager (which runs a server). The client connect to the
-- server and runs protocols to completion.
--
-- There is a good reason why we don't run two bidirectional connection managers;
-- If we would do that, when the either side terminates the connection the
-- client side server would through an exception as it is listening.
--
unidirectionalExperiment
:: forall peerAddr socket acc req resp m.
( ConnectionManagerMonad m
, MonadAsync m
, MonadLabelledSTM m
, MonadSay m
, acc ~ [req], resp ~ [req]
, Ord peerAddr, Show peerAddr, Typeable peerAddr, Eq peerAddr
, Serialise req, Show req
, Serialise resp, Show resp, Eq resp
, Typeable req, Typeable resp
)
=> Timeouts
-> Snocket m socket peerAddr
-> socket
-> ClientAndServerData req
-> m Property
unidirectionalExperiment timeouts snocket socket clientAndServerData = do
nextReqs <- oneshotNextRequests clientAndServerData
withInitiatorOnlyConnectionManager
"client" timeouts nullTracer nullTracer snocket Nothing nextReqs
timeLimitsHandshake maxAcceptedConnectionsLimit
$ \connectionManager ->
withBidirectionalConnectionManager "server" timeouts
nullTracer nullTracer nullTracer
nullTracer snocket socket Nothing
[accumulatorInit clientAndServerData]
noNextRequests
timeLimitsHandshake
maxAcceptedConnectionsLimit
$ \_ serverAddr serverAsync -> do
link serverAsync
-- client → server: connect
(rs :: [Either SomeException (Bundle [resp])]) <-
replicateM
(numberOfRounds clientAndServerData)
(bracket
(requestOutboundConnection connectionManager serverAddr)
(\_ -> unregisterOutboundConnection connectionManager serverAddr)
(\connHandle -> do
case connHandle of
Connected _ _ (Handle mux muxBundle _
:: Handle InitiatorMode peerAddr ByteString m [resp] Void) ->
try @_ @SomeException $
(runInitiatorProtocols
SingInitiatorMode mux muxBundle
:: m (Bundle [resp])
)
Disconnected _ err ->
throwIO (userError $ "unidirectionalExperiment: " ++ show err))
)
pure $
foldr
(\ (r, expected) acc ->
case r of
Left err -> counterexample (show err) False
Right a -> a === expected .&&. acc)
(property True)
$ zip rs (expectedResult clientAndServerData clientAndServerData)
prop_unidirectional_Sim :: ClientAndServerData Int
-> Property
prop_unidirectional_Sim clientAndServerData =
simulatedPropertyWithTimeout 7200 $
withSnocket nullTracer
noAttenuation
Map.empty
$ \snock _ ->
bracket (Snocket.open snock Snocket.TestFamily)
(Snocket.close snock) $ \fd -> do
Snocket.bind snock fd serverAddr
Snocket.listen snock fd
unidirectionalExperiment simTimeouts snock fd clientAndServerData
where
serverAddr = Snocket.TestAddress (0 :: Int)
prop_unidirectional_IO
:: ClientAndServerData Int
-> Property
prop_unidirectional_IO clientAndServerData =
ioProperty $ do
withIOManager $ \iomgr ->
bracket
(Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol)
Socket.close
$ \socket -> do
associateWithIOManager iomgr (Right socket)
addr <- head <$> Socket.getAddrInfo Nothing (Just "127.0.0.1") (Just "0")
Socket.bind socket (Socket.addrAddress addr)
Socket.listen socket maxBound
unidirectionalExperiment
ioTimeouts
(socketSnocket iomgr)
socket
clientAndServerData
-- | Bidirectional send and receive.
--
bidirectionalExperiment
:: forall peerAddr socket acc req resp m.
( ConnectionManagerMonad m
, MonadAsync m
, MonadLabelledSTM m
, MonadSay m
, acc ~ [req], resp ~ [req]
, Ord peerAddr, Show peerAddr, Typeable peerAddr, Eq peerAddr
, Serialise req, Show req
, Serialise resp, Show resp, Eq resp
, Typeable req, Typeable resp
, Show acc
)
=> Bool
-> Timeouts
-> Snocket m socket peerAddr
-> socket
-> socket
-> peerAddr
-> peerAddr
-> ClientAndServerData req
-> ClientAndServerData req
-> m Property
bidirectionalExperiment
useLock timeouts snocket socket0 socket1 localAddr0 localAddr1
clientAndServerData0 clientAndServerData1 = do
lock <- newTMVarIO ()
nextRequests0 <- oneshotNextRequests clientAndServerData0
nextRequests1 <- oneshotNextRequests clientAndServerData1
withBidirectionalConnectionManager "node-0" timeouts
nullTracer nullTracer nullTracer
nullTracer snocket socket0
(Just localAddr0)
[accumulatorInit clientAndServerData0]
nextRequests0
noTimeLimitsHandshake
maxAcceptedConnectionsLimit
(\connectionManager0 _serverAddr0 serverAsync0 -> do
link serverAsync0
withBidirectionalConnectionManager "node-1" timeouts
nullTracer nullTracer nullTracer
nullTracer snocket socket1
(Just localAddr1)
[accumulatorInit clientAndServerData1]
nextRequests1
noTimeLimitsHandshake
maxAcceptedConnectionsLimit
(\connectionManager1 _serverAddr1 serverAsync1 -> do
link serverAsync1
-- runInitiatorProtocols returns a list of results per each
-- protocol in each bucket (warm \/ hot \/ established); but
-- we run only one mini-protocol. We can use `concat` to
-- flatten the results.
( rs0 :: [Either SomeException (Bundle [resp])]
, rs1 :: [Either SomeException (Bundle [resp])]
) <-
-- Run initiator twice; this tests if the responders on
-- the other end are restarted.
replicateM
(numberOfRounds clientAndServerData0)
(bracket
(withLock useLock lock
(requestOutboundConnection
connectionManager0
localAddr1))
(\_ ->
unregisterOutboundConnection
connectionManager0
localAddr1)
(\connHandle ->
case connHandle of
Connected _ _ (Handle mux muxBundle _) -> do
try @_ @SomeException $
runInitiatorProtocols
SingInitiatorResponderMode
mux muxBundle
Disconnected _ err ->
throwIO (userError $ "bidirectionalExperiment: " ++ show err)
))
`concurrently`
replicateM
(numberOfRounds clientAndServerData1)
(bracket
(withLock useLock lock
(requestOutboundConnection
connectionManager1
localAddr0))
(\_ ->
unregisterOutboundConnection
connectionManager1
localAddr0)
(\connHandle ->
case connHandle of
Connected _ _ (Handle mux muxBundle _) -> do
try @_ @SomeException $
runInitiatorProtocols