-
Notifications
You must be signed in to change notification settings - Fork 20
/
Jumping.hs
325 lines (305 loc) · 12 KB
/
Jumping.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
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE UndecidableInstances #-}
module Ouroboros.Consensus.MiniProtocol.ChainSync.Client.Jumping (
Context
, ContextWith (..)
, Instruction (..)
, JumpResult (..)
, makeContext
, nextInstruction
, onAwaitReply
, onRollForward
, processJumpResult
, registerClient
, unregisterClient
) where
import Cardano.Slotting.Slot (SlotNo (..), WithOrigin (..))
import Control.Monad (forM, forM_, when)
import qualified Data.List as List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import GHC.Generics (Generic)
import Ouroboros.Consensus.Block (GenesisWindow (unGenesisWindow),
HasHeader, Header, Point(..), castPoint, pointSlot,
succWithOrigin)
import Ouroboros.Consensus.MiniProtocol.ChainSync.Client.State
(ChainSyncClientHandle (..), ChainSyncJumpingState (..),
ChainSyncState (..))
import Ouroboros.Consensus.Util.IOLike hiding (handle)
import Ouroboros.Network.AnchoredFragment (AnchoredFragment,
AnchoredSeq(Empty), Anchor(AnchorGenesis), headPoint,
headSlot)
-- | A context for ChainSync jumping, pointing for some data.
--
-- Invariants:
--
-- - If 'handlesVar' is not empty, then there is exactly one dynamo in it.
-- - There is at most one objector in 'handlesVar'.
data ContextWith peerField handleField m peer blk = Context
{ peer :: !peerField,
handle :: !handleField,
handlesVar :: !(StrictTVar m (Map peer (ChainSyncClientHandle m blk))),
jumpSize :: !SlotNo,
genesisWindow :: !GenesisWindow
}
-- | A non-specific, generic context for ChainSync jumping.
type Context = ContextWith () ()
-- | A peer-specific context for ChainSync jumping. This is a 'PointedContext'
-- pointing on the handler of the peer in question.
--
-- Invariant: The binding from 'peer' to 'handle' is present in 'handlesVar'.
type PeerContext m peer blk = ContextWith peer (ChainSyncClientHandle m blk) m peer blk
makeContext ::
StrictTVar m (Map peer (ChainSyncClientHandle m blk)) ->
SlotNo ->
-- ^ The size of jumps, in number of slots.
GenesisWindow ->
Context m peer blk
makeContext = Context () ()
-- | Get a generic context from a peer context by stripping away the
-- peer-specific fields.
stripContext :: PeerContext m peer blk -> Context m peer blk
stripContext context = context {peer = (), handle = ()}
-- | Instruction from the jumping governor, either to run normal ChainSync, or
-- to jump to follow a dynamo with the given fragment.
data Instruction blk
= RunNormally
| -- | Jump to the tip of the given fragment.
JumpTo !(AnchoredFragment (Header blk))
deriving (Generic)
deriving instance (HasHeader blk, Eq (Header blk)) => Eq (Instruction blk)
deriving instance (HasHeader blk, Show (Header blk)) => Show (Instruction blk)
deriving anyclass instance (HasHeader blk, NoThunks (Header blk)) => NoThunks (Instruction blk)
-- | The result of a jump request, either accepted or rejected.
data JumpResult blk
= AcceptedJump !(AnchoredFragment (Header blk))
| RejectedJump !(AnchoredFragment (Header blk))
deriving (Generic)
deriving instance (HasHeader blk, Eq (Header blk)) => Eq (JumpResult blk)
deriving instance (HasHeader blk, Show (Header blk)) => Show (JumpResult blk)
deriving anyclass instance (HasHeader blk, NoThunks (Header blk)) => NoThunks (JumpResult blk)
-- | Compute the next instruction for the given peer. In the majority of cases,
-- this consists in reading the peer's handle, having the dynamo and objector
-- run normally and the jumpers wait for the next jump. As such, this function
-- mostly only reads the handle of the peer. For the dynamo, every once in a
-- while, we need to indicate to the jumpers that they need to jump, and this
-- requires writing to all TVars.
nextInstruction ::
( MonadSTM m,
HasHeader blk,
HasHeader (Header blk)
) =>
PeerContext m peer blk ->
STM m (Instruction blk)
nextInstruction context =
readTVar (cschJumping (handle context)) >>= \case
Dynamo lastJumpSlot -> maybeSetNextJump lastJumpSlot >> pure RunNormally
Objector _ -> pure RunNormally
Jumper nextJumpVar -> do
fragment <- readTVar nextJumpVar
if headPoint fragment == GenesisPoint then
retry
else do
writeTVar nextJumpVar (Empty AnchorGenesis)
pure $ JumpTo fragment
where
-- | We are the dynamo. When the tip of our candidate fragment is 'jumpSize'
-- slots younger than the last jump, set jumpers to jump to it.
maybeSetNextJump lastJumpSlot = do
dynamoFragment <- csCandidate <$> readTVar (cschState (handle context))
when (succWithOrigin (headSlot dynamoFragment) >= succWithOrigin lastJumpSlot + jumpSize context) $ do
handles <- readTVar (handlesVar context)
forM_ (Map.elems handles) $ \ChainSyncClientHandle{cschJumping = cschJumping'} ->
readTVar cschJumping' >>= \case
Jumper nextJumpVar -> writeTVar nextJumpVar dynamoFragment
_ -> pure ()
writeTVar (cschJumping (handle context)) $ Dynamo (headSlot dynamoFragment)
-- | This function is called when we receive a 'MsgRollForward' message.
--
-- When a dynamo rolls forward, we might need to jump to the candidate
-- fragment's tip to advance the jumpers if the dynamo sent all the headers
-- in the genesis window since the last jump. e.g.
--
-- > -- last jump -- h0 -- h1 -- ... -- tip -- genesis window limit -- next header
--
-- This is necessary when the tip is before the next jump according to the jump
-- size.
--
onRollForward ::
( MonadSTM m,
HasHeader blk,
HasHeader (Header blk)
) =>
PeerContext m peer blk ->
SlotNo ->
STM m ()
onRollForward context slot =
readTVar (cschJumping (handle context)) >>= \case
Objector _ -> pure ()
Jumper{} -> pure ()
Dynamo lastJumpSlot
| slot >= succWithOrigin lastJumpSlot + genesisWindowSlot -> do
fragment <- csCandidate <$> readTVar (cschState (handle context))
let csTipPoint = headPoint fragment
when (pointSlot csTipPoint > lastJumpSlot) $
setJumps fragment
| otherwise -> pure ()
where
genesisWindowSlot = SlotNo (unGenesisWindow (genesisWindow context))
setJumps fragment = do
handles <- readTVar (handlesVar context)
forM_ (Map.elems handles) $ \h ->
readTVar (cschJumping h) >>= \case
Jumper nextJumpVar -> writeTVar nextJumpVar fragment
_ -> pure ()
-- | This function is called when we receive a 'MsgAwaitReply' message.
--
-- If this is the dynamo, we need to elect a new dynamo as no more headers
-- are available.
onAwaitReply ::
( MonadSTM m,
HasHeader blk,
Eq peer,
NoThunks (Header blk)
) =>
PeerContext m peer blk ->
STM m ()
onAwaitReply context =
readTVar (cschJumping (handle context)) >>= \case
Objector{} -> pure ()
Jumper{} -> pure ()
Dynamo{} -> electNewDynamo (stripContext context)
-- | Process the result of a jump. In the happy case, this only consists in
-- updating the peer's handle to take the new candidate fragment and the new
-- last jump point into account. When disagreeing with the dynamo, though, we
-- enter a phase of several jumps to pinpoint exactly where the disagreement
-- occurs. Once this phase is finished, we trigger the election of a new
-- objector, which might update many TVars.
processJumpResult ::
( MonadSTM m,
HasHeader (Header blk)
) =>
PeerContext m peer blk ->
JumpResult blk ->
STM m ()
processJumpResult context jumpResult = do
readTVar (cschJumping (handle context)) >>= \case
Dynamo _ -> pure ()
Objector _ -> pure ()
Jumper nextJumpVar ->
case jumpResult of
AcceptedJump fragment -> do
-- The jump was accepted; we set the jumper's candidate fragment to
-- the dynamo's candidate fragment up to the accepted point.
--
-- The candidate fragments of jumpers don't grow otherwise, as only the
-- objector and the dynamo request further headers.
modifyTVar (cschState (handle context)) $ \csState -> csState {csCandidate = fragment}
writeTVar (cschJumping (handle context)) $ Jumper nextJumpVar
RejectedJump fragment ->
writeTVar (cschJumping (handle context)) $
Objector $ castPoint (headPoint fragment)
-- | Find the dynamo in a TVar containing a map of handles. Returns then handle
-- of the dynamo, or 'Nothing' if there is none.
getDynamo ::
(MonadSTM m) =>
StrictTVar m (Map peer (ChainSyncClientHandle m blk)) ->
STM m (Maybe (ChainSyncClientHandle m blk))
getDynamo handlesVar = do
handles <- Map.toList <$> readTVar handlesVar
handlesWithState <- forM handles (\(_, handle) -> (handle,) <$> readTVar (cschJumping handle))
pure $ (fst <$>) $ List.find (isDynamo . snd) $ handlesWithState
where
isDynamo (Dynamo _) = True
isDynamo _ = False
-- | Convenience function that, given an intersection point and a jumper state,
-- make a fresh 'Jumper' constructor.
newJumper ::
( MonadSTM m,
HasHeader blk,
NoThunks (Header blk)
) =>
AnchoredFragment (Header blk) ->
STM m (ChainSyncJumpingState m blk)
newJumper nextJump = do
nextJumpVar <- newTVar nextJump
pure $ Jumper nextJumpVar
-- | Register a new ChainSync client to a context, returning a 'PeerContext' for
-- that peer. If there is no dynamo, the peer starts as dynamo; otherwise, it
-- starts as a jumper.
registerClient ::
( Ord peer,
HasHeader blk,
IOLike m,
NoThunks (Header blk)
) =>
Context m peer blk ->
peer ->
-- | A function to make a client handle from a jumping state.
(StrictTVar m (ChainSyncJumpingState m blk) -> ChainSyncClientHandle m blk) ->
STM m (PeerContext m peer blk)
registerClient context peer mkHandle = do
csjState <- getDynamo (handlesVar context) >>= \case
Nothing -> pure $ Dynamo Origin
Just handle -> do
fragment <- csCandidate <$> readTVar (cschState handle)
newJumper fragment
cschJumping <- newTVar csjState
let handle = mkHandle cschJumping
modifyTVar (handlesVar context) $ Map.insert peer handle
pure $ context {peer, handle}
-- | Unregister a client from a 'PeerContext'; this might trigger the election
-- of a new dynamo or objector if the peer was one of these two.
unregisterClient ::
( MonadSTM m,
Ord peer,
HasHeader blk,
NoThunks (Header blk)
) =>
PeerContext m peer blk ->
STM m ()
unregisterClient context = do
modifyTVar (handlesVar context) $ Map.delete (peer context)
let context' = stripContext context
readTVar (cschJumping (handle context)) >>= \case
Jumper{} -> pure ()
Objector{} -> pure ()
Dynamo _ -> electNewDynamo context'
-- | Choose an unspecified new non-idling dynamo and demote all other peers to
-- jumpers.
electNewDynamo ::
( MonadSTM m,
HasHeader blk,
Eq peer,
NoThunks (Header blk)
) =>
Context m peer blk ->
STM m ()
electNewDynamo context = do
peerStates <- Map.toList <$> readTVar (handlesVar context)
mDynamo <- findNonIdling peerStates
case mDynamo of
Nothing -> pure () -- TODO: turn off CSJ
Just (dynId, dynamo) -> do
writeTVar (cschJumping dynamo) $ Dynamo Origin
forM_ peerStates $ \(peer, st) ->
when (peer /= dynId) $ do
fragment <- csCandidate <$> readTVar (cschState dynamo)
writeTVar (cschJumping st) =<< newJumper fragment
where
findNonIdling [] = pure Nothing
findNonIdling ((peer, st) : rest) = do
idling <- csIdling <$> readTVar (cschState st)
if idling
then findNonIdling rest
else pure $ Just (peer, st)