{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}

-- | What the node's LeiosFetch clients request, decided for all of them at
-- once: the node-wide state of what is outstanding, and the pure decision
-- that assigns the peers' offers to requests.
module Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision
  ( -- * Requests
    LeiosFetchRequest (..)
  , LeiosBlockRequest (..)
  , LeiosBlockTxsRequest (..)

    -- * Offers
  , OfferedHalves (..)
  , PeerOffer (..)
  , OfferPrune (..)
  , pruneOffers

    -- * Outstanding state
  , LeiosOutstanding (..)
  , EbState (..)
  , EbFetchState (..)
  , ebStateOnset
  , emptyLeiosOutstanding
  , initializeLeiosOutstanding
  , newLeiosJobPool
  , acquireEbBody
  , holdForgedEb
  , recordReferencedPoint
  , focusElectionIfUnfocused
  , focusCertifiedEb
  , trackCertifiedEb
  , focusElection
  , isFocusedPoint
  , pruneOutstandingToImmTip

    -- * Settled requests
  , removePeerFromOutstanding
  , refundEbRequest
  , refundTxRequest
  , completeTxRequest

    -- * Deciding
  , LeiosFetchStaticEnv (..)
  , defaultLeiosFetchStaticEnv
  , leiosFetchLogicIteration
  , fetchPriorityTiers
  , peerBudget
  ) where

import Cardano.Slotting.Slot (SlotNo (..))
import qualified Data.Foldable as F
import Data.IntMap.NonEmpty (NEIntMap)
import qualified Data.IntMap.NonEmpty as NEIntMap
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import Data.IntSet.NonEmpty (NEIntSet)
import qualified Data.IntSet.NonEmpty as NEIntSet
import Data.List (partition, sortOn)
import Data.List.NonEmpty (NonEmpty ((:|)), nonEmpty)
import Data.Map.NonEmpty (NEMap)
import qualified Data.Map.NonEmpty as NEMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (..))
import Data.Ord (Down (..))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Sequence.NonEmpty (NESeq)
import qualified Data.Sequence.NonEmpty as NESeq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Set.NonEmpty (NESet)
import qualified Data.Set.NonEmpty as NESet
import Data.Word (Word64)
import Ouroboros.Consensus.BlockchainTime.WallClock.Types (RelativeTime)
import Ouroboros.Consensus.Forecast (OutsideForecastRange)
import Ouroboros.Consensus.Leios.Acquisitions (LeiosAcquisition (..))
import Ouroboros.Consensus.Leios.Types
  ( BytesSize
  , ElectionId (..)
  , EndorserBlockHash
  , LeiosEbByteSizes
  , LeiosPoint (..)
  , SizeRole (..)
  , TxHash
  )
import qualified Ouroboros.Consensus.MiniProtocol.LeiosFetch.Jobs as Jobs
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Type (maxLeiosTxsRequestBytesSize)
import Ouroboros.Network.PeerSelection.LedgerPeers.Type (IsBigLedgerPeer (..))
import System.Random (StdGen)

{-------------------------------------------------------------------------------
  Requests
-------------------------------------------------------------------------------}

data LeiosFetchRequest
  = LeiosBlockRequest LeiosBlockRequest
  | LeiosBlockTxsRequest LeiosBlockTxsRequest

-- | A request for an endorser block's body.
data LeiosBlockRequest = MkLeiosBlockRequest
  { LeiosBlockRequest -> LeiosPoint
lbrPoint :: !LeiosPoint
  , LeiosBlockRequest -> Word32
lbrOfferedSize :: !BytesSize
  -- ^ The size the peer offered this endorser block at; not sent, but used by
  -- the reply handler.
  , LeiosBlockRequest -> LeiosEbByteSizes 'SizeLimit
lbrEbBounds :: !(LeiosEbByteSizes SizeLimit)
  -- ^ The ledger's bounds on this block; not sent, but used by the reply
  -- handler.
  }

-- | A request for some of an EB's txs: its point and the 'Jobs.LeiosJob's it
-- covers, keyed by job id (so a request can't list a job twice), each with its
-- full commitment. Everything needed to validate the response is carried here,
-- so the reply handler needs no lookup into the (body-less) job pool -- and a
-- redundant response for a job that has since completed still validates. On
-- the wire only the offset bitmap goes to the peer; it is derived from the
-- union of the jobs' offsets (see
-- 'Ouroboros.Consensus.MiniProtocol.LeiosFetch.Type.offsetsToBitmap'), not
-- stored.
data LeiosBlockTxsRequest
  = MkLeiosBlockTxsRequest
      !LeiosPoint
      !(NEIntMap Jobs.LeiosJob)

{-------------------------------------------------------------------------------
  Offers
-------------------------------------------------------------------------------}

-- | Which halves of an endorser block one peer has offered at one point. A peer
-- that offered neither has no offer there.
--
-- The two LeiosNotify offers are independent messages: either can arrive
-- first, or alone. A CertRB roll-forward makes both at once.
--
-- The body offer carries a size and the closure offer does not, and that
-- asymmetry is not an oversight. We hold nothing to size a body request by, so
-- the peer's claim is both what the request asks for and what it spends
-- against that peer's byte budget. Closure jobs carry their own byte counts,
-- taken from the body we already hold by the time 'assignClosure' runs, so
-- there is nothing there for a peer to claim.
--
-- The size the peer offered the body at is its own claim, and the only size
-- that decides anything: no announcement gets a say (see 'assignBody'), and
-- what the endorser block really weighs is settled by hashing the bytes that
-- arrive.
--
-- Offering one point twice costs the peer its connection, but one hash at two
-- /points/ does not: those are separate entries, each needing its own
-- announcement, and nothing here arbitrates between the sizes they name.
--
-- TODO disconnect a peer that ever offers one 'EndorserBlockHash' at two
-- sizes, whichever messages the two arrived on. That is proof it is lying, and
-- today we keep both and carry on.
data OfferedHalves
  = -- | The body, at this size
    OfferedBody !BytesSize
  | -- | The closure
    OfferedClosure
  | -- | Both, the body at this size
    OfferedBodyAndClosure !BytesSize
  deriving (OfferedHalves -> OfferedHalves -> Bool
(OfferedHalves -> OfferedHalves -> Bool)
-> (OfferedHalves -> OfferedHalves -> Bool) -> Eq OfferedHalves
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: OfferedHalves -> OfferedHalves -> Bool
== :: OfferedHalves -> OfferedHalves -> Bool
$c/= :: OfferedHalves -> OfferedHalves -> Bool
/= :: OfferedHalves -> OfferedHalves -> Bool
Eq, Int -> OfferedHalves -> ShowS
[OfferedHalves] -> ShowS
OfferedHalves -> String
(Int -> OfferedHalves -> ShowS)
-> (OfferedHalves -> String)
-> ([OfferedHalves] -> ShowS)
-> Show OfferedHalves
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OfferedHalves -> ShowS
showsPrec :: Int -> OfferedHalves -> ShowS
$cshow :: OfferedHalves -> String
show :: OfferedHalves -> String
$cshowList :: [OfferedHalves] -> ShowS
showList :: [OfferedHalves] -> ShowS
Show)

-- | What either offered. Of two body sizes, the leftmost wins, which for
-- 'Map.insertWith' is the newer offer's, and a peer that makes that choice
-- matter has already lost our trust.
instance Semigroup OfferedHalves where
  OfferedBody Word32
size <> :: OfferedHalves -> OfferedHalves -> OfferedHalves
<> OfferedBody Word32
_ = Word32 -> OfferedHalves
OfferedBody Word32
size
  OfferedBody Word32
size <> OfferedHalves
OfferedClosure = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedBody Word32
size <> OfferedBodyAndClosure Word32
_ = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedHalves
OfferedClosure <> OfferedBody Word32
size = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedHalves
OfferedClosure <> OfferedHalves
OfferedClosure = OfferedHalves
OfferedClosure
  OfferedHalves
OfferedClosure <> OfferedBodyAndClosure Word32
size = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedBodyAndClosure Word32
size <> OfferedBody Word32
_ = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedBodyAndClosure Word32
size <> OfferedHalves
OfferedClosure = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size
  OfferedBodyAndClosure Word32
size <> OfferedBodyAndClosure Word32
_ = Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
size

-- | What one peer has offered for one endorser block point.
data PeerOffer = MkPeerOffer
  { PeerOffer -> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
poEbBounds :: !(StrictMaybe (LeiosEbByteSizes SizeLimit))
  -- ^ The ledger's bounds on this offered EB. It's 'SNothing' if
  -- the offer arrived via LeiosNotify, and 'SJust' if it arrived via ChainSync.
  --
  -- The decision logic uses forecasting in the 'SNothing' case. We avoid
  -- forecasting in the ChainSync case so that the Leios Recovery Path can
  -- handle sparse chains.
  , PeerOffer -> OfferedHalves
poOffered :: !OfferedHalves
  }
  deriving (PeerOffer -> PeerOffer -> Bool
(PeerOffer -> PeerOffer -> Bool)
-> (PeerOffer -> PeerOffer -> Bool) -> Eq PeerOffer
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PeerOffer -> PeerOffer -> Bool
== :: PeerOffer -> PeerOffer -> Bool
$c/= :: PeerOffer -> PeerOffer -> Bool
/= :: PeerOffer -> PeerOffer -> Bool
Eq, Int -> PeerOffer -> ShowS
[PeerOffer] -> ShowS
PeerOffer -> String
(Int -> PeerOffer -> ShowS)
-> (PeerOffer -> String)
-> ([PeerOffer] -> ShowS)
-> Show PeerOffer
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PeerOffer -> ShowS
showsPrec :: Int -> PeerOffer -> ShowS
$cshow :: PeerOffer -> String
show :: PeerOffer -> String
$cshowList :: [PeerOffer] -> ShowS
showList :: [PeerOffer] -> ShowS
Show)

-- | What of a peer's offer of a point the decision logic found can no longer
-- help.
--
-- The decision logic reads the peers' offers in one transaction and prunes them
-- in a later one, so meanwhile a peer's closure offer may merge into its body
-- offer. Pruning the whole offer would lose that closure offer, so
-- 'PruneOffer' is decided only where no closure offer could help either.
data OfferPrune
  = -- | The whole offer.
    PruneOffer
  | -- | Its body half, and the whole offer unless it offers the closure: the
    -- body is held, or was requested of this peer, which is asked for it at
    -- most once.
    PruneOfferedBody
  deriving (OfferPrune -> OfferPrune -> Bool
(OfferPrune -> OfferPrune -> Bool)
-> (OfferPrune -> OfferPrune -> Bool) -> Eq OfferPrune
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: OfferPrune -> OfferPrune -> Bool
== :: OfferPrune -> OfferPrune -> Bool
$c/= :: OfferPrune -> OfferPrune -> Bool
/= :: OfferPrune -> OfferPrune -> Bool
Eq, Int -> OfferPrune -> ShowS
[OfferPrune] -> ShowS
OfferPrune -> String
(Int -> OfferPrune -> ShowS)
-> (OfferPrune -> String)
-> ([OfferPrune] -> ShowS)
-> Show OfferPrune
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OfferPrune -> ShowS
showsPrec :: Int -> OfferPrune -> ShowS
$cshow :: OfferPrune -> String
show :: OfferPrune -> String
$cshowList :: [OfferPrune] -> ShowS
showList :: [OfferPrune] -> ShowS
Show)

-- | Prune a peer's offers as 'leiosFetchLogicIteration' decided.
pruneOffers :: Map LeiosPoint OfferPrune -> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers :: Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers Map LeiosPoint OfferPrune
prunes Map LeiosPoint PeerOffer
offers = (Map LeiosPoint PeerOffer
 -> LeiosPoint -> OfferPrune -> Map LeiosPoint PeerOffer)
-> Map LeiosPoint PeerOffer
-> Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer
forall a k b. (a -> k -> b -> a) -> a -> Map k b -> a
Map.foldlWithKey' Map LeiosPoint PeerOffer
-> LeiosPoint -> OfferPrune -> Map LeiosPoint PeerOffer
forall {k}.
Ord k =>
Map k PeerOffer -> k -> OfferPrune -> Map k PeerOffer
prune Map LeiosPoint PeerOffer
offers Map LeiosPoint OfferPrune
prunes
 where
  prune :: Map k PeerOffer -> k -> OfferPrune -> Map k PeerOffer
prune Map k PeerOffer
acc k
point = \case
    OfferPrune
PruneOffer -> k -> Map k PeerOffer -> Map k PeerOffer
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete k
point Map k PeerOffer
acc
    OfferPrune
PruneOfferedBody -> (PeerOffer -> Maybe PeerOffer)
-> k -> Map k PeerOffer -> Map k PeerOffer
forall k a. Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
Map.update PeerOffer -> Maybe PeerOffer
withoutBody k
point Map k PeerOffer
acc
  withoutBody :: PeerOffer -> Maybe PeerOffer
withoutBody PeerOffer
offer = case PeerOffer -> OfferedHalves
poOffered PeerOffer
offer of
    OfferedBody Word32
_size -> Maybe PeerOffer
forall a. Maybe a
Nothing
    OfferedHalves
OfferedClosure -> PeerOffer -> Maybe PeerOffer
forall a. a -> Maybe a
Just PeerOffer
offer
    OfferedBodyAndClosure Word32
_size -> PeerOffer -> Maybe PeerOffer
forall a. a -> Maybe a
Just PeerOffer
offer{poOffered = OfferedClosure}

-- | Each field on its own terms (see 'OfferedHalves'). The bound is not a claim
-- of the peer's but a value we computed, so the two sides agree whenever both
-- have one and either will do.
instance Semigroup PeerOffer where
  MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
b1 OfferedHalves
o1 <> :: PeerOffer -> PeerOffer -> PeerOffer
<> MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
b2 OfferedHalves
o2 =
    StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall {a}. StrictMaybe a -> StrictMaybe a -> StrictMaybe a
pickBounds StrictMaybe (LeiosEbByteSizes 'SizeLimit)
b1 StrictMaybe (LeiosEbByteSizes 'SizeLimit)
b2) (OfferedHalves
o1 OfferedHalves -> OfferedHalves -> OfferedHalves
forall a. Semigroup a => a -> a -> a
<> OfferedHalves
o2)
   where
    pickBounds :: StrictMaybe a -> StrictMaybe a -> StrictMaybe a
pickBounds StrictMaybe a
SNothing StrictMaybe a
y = StrictMaybe a
y
    pickBounds x :: StrictMaybe a
x@SJust{} StrictMaybe a
_ = StrictMaybe a
x

{-------------------------------------------------------------------------------
  Outstanding state
-------------------------------------------------------------------------------}

-- | Main data structure used in the Leios fetching logic.
--
-- Tracks both EB-level state (what EBs we have/need) and TX-level state
-- (what TXs we need for each EB), along with request tracking for bandwidth
-- management.
data LeiosOutstanding peer = MkLeiosOutstanding
  { forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState :: !(Map LeiosPoint EbState)
  -- ^ Per-point state for every endorser block point this node is tracking.
  -- Four things add an entry: the announcement that takes an election's
  -- focus, the node's own forge ('holdForgedEb'), a verified certificate
  -- ('trackCertifiedEb'), and the start-up seeding
  -- ('initializeLeiosOutstanding') of the endorser blocks whose closures the
  -- LeiosDb already holds (merely to avoid refetching them). An offer never
  -- does, and is only ever acted on for a point already here.
  --
  -- Each point is fetched on its own, even when another point names the same
  -- endorser block, so the ledger's bounds an entry is held to never change:
  -- they are those of its slot.
  , forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus :: !(Map ElectionId EndorserBlockHash)
  -- ^ The endorser block each election is fetching.
  --
  -- Two activities decide it. Processing an announcement focuses an election
  -- that has no focus yet, and nothing more ('focusElectionIfUnfocused').
  -- Processing a certificate overrides whatever is there ('focusCertifiedEb')
  -- --- the CertRB itself, when its certificate is verified, not its header,
  -- which only records an offer.
  -- Pruning is the only other writer, and it just drops the elections below
  -- the immutable tip.
  --
  -- A point is focused when an election in its slot is fetching its endorser
  -- block ('isFocusedPoint'). Unless a point is focused, the decision logic
  -- asks no peer for anything about it: neither its body nor any of its
  -- closure's jobs, since this is what filters a peer's offers before either is
  -- considered. A body we already hold stays held and its job pool stays as it
  -- is, so an election that focuses it later resumes rather than restarts.
  , forall peer. LeiosOutstanding peer -> SlotNo
outstandingPrunedSlot :: !SlotNo
  -- ^ The slot this whole 'LeiosOutstanding' has most recently been pruned up
  -- to: 'pruneOutstandingToImmTip' moves it in the same record it prunes
  -- 'ebState' and 'elFocus' in, so it says how far both of them have got.
  --
  -- Used to robustly prevent re-inserting what has already been pruned out.
  , forall peer. LeiosOutstanding peer -> Map LeiosPoint (Set peer)
requestedEbPeers :: !(Map LeiosPoint (Set peer))
  -- ^ Which peers we've requested each point's body from
  , forall peer. LeiosOutstanding peer -> Map peer (NESet LeiosPoint)
requestedEbsPerPeer :: !(Map peer (NESet LeiosPoint))
  -- ^ The inverse of 'requestedEbPeers': the points whose body each peer has
  -- been requested, so that cancelling a peer's requests touches only those
  , forall peer. LeiosOutstanding peer -> Map peer Word32
requestedBytesSizePerPeer :: !(Map peer BytesSize)
  -- ^ Running total of bytes requested from each peer. This is the only
  -- outstanding-byte limit: there is no global cap (the global bound falls out
  -- as this per-peer cap times the peer count).
  , forall peer.
LeiosOutstanding peer -> Map peer (Map LeiosPoint NEIntSet)
requestedJobsPerPeer :: !(Map peer (Map LeiosPoint NEIntSet))
  -- ^ Per peer, per point, the job ids it currently has in flight -- for
  -- decrementing those multiplicities on disconnect
  , forall peer. LeiosOutstanding peer -> StdGen
leiosFetchPrng :: !StdGen
  -- ^ The LeiosFetch decision loop's own PRNG, threaded through each iteration.
  -- Used to shuffle which job is drawn when assigning tx-closure work to a peer
  -- (a uniform pick within the least-requested multiplicity bucket), so job ids
  -- aren't consumed in a fixed order. Seeded once at start-up.
  }

-- | The empty outstanding state, given the slot it has already been pruned up
-- to. The caller supplies the immutable-tip slot at startup so that a body at
-- or below it reads as too old from the outset (see
-- 'outstandingPrunedSlot' / 'pruneOutstandingToImmTip'), and the seed for
-- the decision loop's PRNG (see 'leiosFetchPrng').
emptyLeiosOutstanding :: StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding :: forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding StdGen
prng SlotNo
prunedSlot =
  MkLeiosOutstanding
    { ebState :: Map LeiosPoint EbState
ebState = Map LeiosPoint EbState
forall k a. Map k a
Map.empty
    , elFocus :: Map ElectionId EndorserBlockHash
elFocus = Map ElectionId EndorserBlockHash
forall k a. Map k a
Map.empty
    , outstandingPrunedSlot :: SlotNo
outstandingPrunedSlot = SlotNo
prunedSlot
    , requestedEbPeers :: Map LeiosPoint (Set peer)
requestedEbPeers = Map LeiosPoint (Set peer)
forall k a. Map k a
Map.empty
    , requestedEbsPerPeer :: Map peer (NESet LeiosPoint)
requestedEbsPerPeer = Map peer (NESet LeiosPoint)
forall k a. Map k a
Map.empty
    , requestedBytesSizePerPeer :: Map peer Word32
requestedBytesSizePerPeer = Map peer Word32
forall k a. Map k a
Map.empty
    , requestedJobsPerPeer :: Map peer (Map LeiosPoint NEIntSet)
requestedJobsPerPeer = Map peer (Map LeiosPoint NEIntSet)
forall k a. Map k a
Map.empty
    , leiosFetchPrng :: StdGen
leiosFetchPrng = StdGen
prng
    }

-- | Per-point state tracked in 'ebState'
data EbState
  = MkEbState
      -- | The wall-clock onset of the point's slot, if known. The acquisition
      -- traces subtract it from the arrival time, so they say how long after
      -- this point was announced we got it. It is 'SNothing' when nothing
      -- supplied an onset, as for a verified certificate or the start-up
      -- seeding.
      !(StrictMaybe RelativeTime)
      -- | The current progress of fetching it
      !EbFetchState
  deriving (EbState -> EbState -> Bool
(EbState -> EbState -> Bool)
-> (EbState -> EbState -> Bool) -> Eq EbState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EbState -> EbState -> Bool
== :: EbState -> EbState -> Bool
$c/= :: EbState -> EbState -> Bool
/= :: EbState -> EbState -> Bool
Eq, Int -> EbState -> ShowS
[EbState] -> ShowS
EbState -> String
(Int -> EbState -> ShowS)
-> (EbState -> String) -> ([EbState] -> ShowS) -> Show EbState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EbState -> ShowS
showsPrec :: Int -> EbState -> ShowS
$cshow :: EbState -> String
show :: EbState -> String
$cshowList :: [EbState] -> ShowS
showList :: [EbState] -> ShowS
Show)

-- | Whether we hold an EB's body.
data EbFetchState
  = -- | We've only ever received an announcement.
    NoBody
  | -- | The job pool: the jobs whose txs are not yet durably written.
    --
    -- A body too big for the point's bounds is held with an empty pool too. It
    -- is never written, and nothing more is fetched or emitted for it at this
    -- point.
    --
    -- The body itself is /not/ retained -- it lives in the LeiosDb, and each job
    -- carries a 'Jobs.JobCommitment' sufficient to validate its response.
    -- Retaining up to ~10k bodies (each up to ~600 kB) would cost gigabytes.
    --
    -- TODO the 'Jobs.LeiosJobPool' could be an 'MVar m LeiosJobPool' for per-EB
    -- locking, at the cost of an 'm' parameter on
    -- EbFetchState\/EbState\/LeiosOutstanding and a monadic body-acquire;
    -- deferred.
    BodyAcquired !Jobs.LeiosJobPool
  deriving (EbFetchState -> EbFetchState -> Bool
(EbFetchState -> EbFetchState -> Bool)
-> (EbFetchState -> EbFetchState -> Bool) -> Eq EbFetchState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EbFetchState -> EbFetchState -> Bool
== :: EbFetchState -> EbFetchState -> Bool
$c/= :: EbFetchState -> EbFetchState -> Bool
/= :: EbFetchState -> EbFetchState -> Bool
Eq, Int -> EbFetchState -> ShowS
[EbFetchState] -> ShowS
EbFetchState -> String
(Int -> EbFetchState -> ShowS)
-> (EbFetchState -> String)
-> ([EbFetchState] -> ShowS)
-> Show EbFetchState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EbFetchState -> ShowS
showsPrec :: Int -> EbFetchState -> ShowS
$cshow :: EbFetchState -> String
show :: EbFetchState -> String
$cshowList :: [EbFetchState] -> ShowS
showList :: [EbFetchState] -> ShowS
Show)

-- | The recorded onset of the point's slot, if any (see 'MkEbState'); the
-- arrival handlers use it to report the EB's age on arrival.
ebStateOnset :: EbState -> StrictMaybe RelativeTime
ebStateOnset :: EbState -> StrictMaybe RelativeTime
ebStateOnset (MkEbState StrictMaybe RelativeTime
onset EbFetchState
_fetchState) = StrictMaybe RelativeTime
onset

-- | A pool of jobs to fetch these missing txs of an EB's closure, given as in
-- 'Jobs.mkJobPool'.
newLeiosJobPool ::
  LeiosFetchStaticEnv ->
  IntMap.IntMap (TxHash, BytesSize) ->
  Jobs.LeiosJobPool
newLeiosJobPool :: LeiosFetchStaticEnv -> IntMap (TxHash, Word32) -> LeiosJobPool
newLeiosJobPool LeiosFetchStaticEnv
env = Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
Jobs.mkJobPool (LeiosFetchStaticEnv -> Word32
maxJobBytesSize LeiosFetchStaticEnv
env) (LeiosFetchStaticEnv -> Int
maxJobTxCount LeiosFetchStaticEnv
env)

-- | The body's LeiosDb write is durable, so record 'BodyAcquired' with the pool
-- of jobs the settled write still leaves to fetch.
--
-- There is no intermediate "write in flight" state. During the (brief, async)
-- write window the entry is still 'NoBody', so a concurrent offer may
-- redundantly re-fetch the body -- cheaper than tracking an in-flight state and
-- reverting it on a lost write, which with the single writer cannot happen
-- without bringing the node down anyway.
acquireEbBody ::
  LeiosPoint ->
  Jobs.LeiosJobPool ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
acquireEbBody :: forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
point LeiosJobPool
jobPool =
  LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
alterEbState LeiosPoint
point ((Maybe EbState -> Maybe EbState)
 -> LeiosOutstanding peer -> LeiosOutstanding peer)
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$ \case
    -- Pruned before the write landed (we could not have requested it
    -- without an announcement, and that was since evicted): ignore.
    Maybe EbState
Nothing -> Maybe EbState
forall a. Maybe a
Nothing
    Just st :: EbState
st@(MkEbState StrictMaybe RelativeTime
onset EbFetchState
fetchState) -> case EbFetchState
fetchState of
      EbFetchState
NoBody -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just (EbState -> Maybe EbState) -> EbState -> Maybe EbState
forall a b. (a -> b) -> a -> b
$ StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset (LeiosJobPool -> EbFetchState
BodyAcquired LeiosJobPool
jobPool)
      -- Already acquired -- e.g. a concurrent redundant delivery landed
      -- first; keep the existing pool rather than clobbering it.
      BodyAcquired{} -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just EbState
st

-- | The node's own forge produced the endorser block of this hash in this
-- election, and its body and closure have been written, so hold it with no job
-- left, and focus the election on it unless another endorser block took the
-- focus first. Also returns the acquisitions not yet emitted at its point.
--
-- As for 'acquireEbBody', there is no intermediate state: until the writes
-- land, a peer offering the same point (another leader of the slot built the
-- same endorser block) may be fetched from redundantly.
holdForgedEb ::
  ElectionId ->
  EndorserBlockHash ->
  -- | the size of the body
  BytesSize ->
  LeiosOutstanding peer ->
  (LeiosOutstanding peer, [LeiosAcquisition])
holdForgedEb :: forall peer.
ElectionId
-> EndorserBlockHash
-> Word32
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, [LeiosAcquisition])
holdForgedEb ElectionId
elId EndorserBlockHash
ebHash Word32
size LeiosOutstanding peer
outstanding
  | ElectionId -> SlotNo
electionSlot ElectionId
elId SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< LeiosOutstanding peer -> SlotNo
forall peer. LeiosOutstanding peer -> SlotNo
outstandingPrunedSlot LeiosOutstanding peer
outstanding = (LeiosOutstanding peer
outstanding, [])
  | Bool
otherwise =
      ( ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused ElectionId
elId EndorserBlockHash
ebHash (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$
          LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
alterEbState LeiosPoint
point (\Maybe EbState
_ -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just (EbState -> Maybe EbState) -> EbState -> Maybe EbState
forall a b. (a -> b) -> a -> b
$ StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset (LeiosJobPool -> EbFetchState
BodyAcquired LeiosJobPool
Jobs.emptyJobPool)) LeiosOutstanding peer
outstanding
      , [LeiosAcquisition]
acquired
      )
 where
  point :: LeiosPoint
point = SlotNo -> EndorserBlockHash -> LeiosPoint
MkLeiosPoint (ElectionId -> SlotNo
electionSlot ElectionId
elId) EndorserBlockHash
ebHash
  -- A forged endorser block records no onset: its age on arrival says nothing
  -- about diffusion.
  (StrictMaybe RelativeTime
onset, [LeiosAcquisition]
acquired) = case LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding) of
    Just (MkEbState StrictMaybe RelativeTime
onset' (BodyAcquired LeiosJobPool
jobPool))
      -- An empty pool means the body and closure were emitted, except for a
      -- body too big for its bounds. Our forge produces no such endorser
      -- block: it fits each one to its slot's bounds. For the closure, that
      -- relies on a tx's measure bounding its bytes, as
      -- prop_dijkstraEbTxSizeBounded checks for Dijkstra.
      | LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
jobPool -> (StrictMaybe RelativeTime
onset', [])
      | Bool
otherwise -> (StrictMaybe RelativeTime
onset', [LeiosPoint -> LeiosAcquisition
AcquiredEbTxs LeiosPoint
point])
    Just (MkEbState StrictMaybe RelativeTime
onset' EbFetchState
NoBody) -> (StrictMaybe RelativeTime
onset', [LeiosPoint -> Word32 -> LeiosAcquisition
AcquiredEb LeiosPoint
point Word32
size, LeiosPoint -> LeiosAcquisition
AcquiredEbTxs LeiosPoint
point])
    Maybe EbState
Nothing -> (StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing, [LeiosPoint -> Word32 -> LeiosAcquisition
AcquiredEb LeiosPoint
point Word32
size, LeiosPoint -> LeiosAcquisition
AcquiredEbTxs LeiosPoint
point])

-- | Record that this point is referenced --- announced, or named by a verified
-- certificate --- along with its slot's wall-clock onset if known. A
-- reference that carries no onset ('SNothing') never overrides one already
-- recorded.
recordReferencedPoint ::
  LeiosPoint ->
  StrictMaybe RelativeTime ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
recordReferencedPoint :: forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
point StrictMaybe RelativeTime
onset =
  LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
alterEbState LeiosPoint
point ((Maybe EbState -> Maybe EbState)
 -> LeiosOutstanding peer -> LeiosOutstanding peer)
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$ \case
    Maybe EbState
Nothing -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just (EbState -> Maybe EbState) -> EbState -> Maybe EbState
forall a b. (a -> b) -> a -> b
$ StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset EbFetchState
NoBody
    Just (MkEbState StrictMaybe RelativeTime
SNothing EbFetchState
fetchState) | SJust{} <- StrictMaybe RelativeTime
onset -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just (EbState -> Maybe EbState) -> EbState -> Maybe EbState
forall a b. (a -> b) -> a -> b
$ StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset EbFetchState
fetchState
    Just st :: EbState
st@MkEbState{} -> EbState -> Maybe EbState
forall a. a -> Maybe a
Just EbState
st

-- | Initialize the outstanding state
--
-- Its contents are only @'BodyAcquired' 'Jobs.emptyJobPool'@ for the EBs
-- the LeiosDb already holds /in full/: a complete tx closure whose announcer is
-- no older than the immutable tip. Each is marked 'BodyAcquired' with an empty
-- job pool so we neither re-fetch nor re-process (eg emit 'AcquiredEb') an EB
-- whose closure we already have at start-up time.
--
-- Everything else in the LeiosDb is deliberately ignored here, and it's
-- safe to do so:
--
--   * A merely body-held EB with a /partial/ closure is not seeded: an
--     empty pool would strand its missing txs. Left absent, it is
--     re-derived from a fresh announcement/offer, and the redundant body
--     re-fetch + re-insert is idempotent.
--
--   * Complete closures at or below the immutable tip are already final;
--     they would read as too old anyway, so there is nothing to track.
--
-- The announcements on the initially selected chain are likewise not replayed
-- here, though those blocks never roll forward and so are never announced to
-- us this run. Only two things list an endorser block to fetch --- the
-- announcement that takes an election's focus, and 'focusCertifiedEb' on a
-- verified certificate --- and between them they reach every endorser block we
-- could come to need. A CertRB on the initial chain has its endorser block
-- already, since it could not have been selected otherwise; one that is not on
-- the initial chain is re-fetched if some chain we would select needs it, and
-- verifying its certificate then sets the focus and lists it.
--
-- The per-peer request-tracking fields must start empty regardless: there are
-- no connections yet and nothing is in flight.
initializeLeiosOutstanding ::
  StdGen -> [LeiosPoint] -> SlotNo -> LeiosOutstanding peer
initializeLeiosOutstanding :: forall peer.
StdGen -> [LeiosPoint] -> SlotNo -> LeiosOutstanding peer
initializeLeiosOutstanding StdGen
prng [LeiosPoint]
points SlotNo
immTipSlot =
  (LeiosOutstanding peer -> LeiosPoint -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> [LeiosPoint] -> LeiosOutstanding peer
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
F.foldl' ((LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> LeiosPoint -> LeiosOutstanding peer
forall a b c. (a -> b -> c) -> b -> a -> c
flip LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
forall {peer}.
LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
seed1) (StdGen -> SlotNo -> LeiosOutstanding peer
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding StdGen
prng SlotNo
immTipSlot) [LeiosPoint]
points
 where
  -- These points were read back out of the LeiosDb, so the body is durable
  -- already: settle it at once.
  seed1 :: LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
seed1 LeiosPoint
point =
    LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
point LeiosJobPool
Jobs.emptyJobPool
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
point StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing

-- | Make this endorser block the one this election is fetching, unless the
-- election is already fetching one.
--
-- The first announcement we see for an election wins, which is what an honest
-- electee's single announcement gives; only a certificate ('focusCertifiedEb')
-- overrules it.
focusElectionIfUnfocused ::
  ElectionId -> EndorserBlockHash -> LeiosOutstanding peer -> LeiosOutstanding peer
focusElectionIfUnfocused :: forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused ElectionId
elId EndorserBlockHash
ebHash LeiosOutstanding peer
outstanding
  | ElectionId -> Map ElectionId EndorserBlockHash -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member ElectionId
elId (LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding peer
outstanding) = LeiosOutstanding peer
outstanding
  | Bool
otherwise = ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElection ElectionId
elId EndorserBlockHash
ebHash LeiosOutstanding peer
outstanding

-- | A verified certificate moves its election's focus onto the endorser block
-- it names, and lists that body as one to fetch.
--
-- The endorser block this names may never have been listed. The announcement
-- that took the election's focus listed its own; this one's may have lost that
-- race, or may never have reached us --- and nothing lists it in the meantime,
-- because an unverified claim must not be able to make us track an endorser
-- block.
--
-- It does nothing for an election older than what has been pruned: its
-- certificate may have been read before the pruning, and focusing it now would
-- track what the pruning dropped.
focusCertifiedEb ::
  ElectionId -> EndorserBlockHash -> LeiosOutstanding peer -> LeiosOutstanding peer
focusCertifiedEb :: forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusCertifiedEb ElectionId
elId EndorserBlockHash
ebHash LeiosOutstanding peer
outstanding
  | ElectionId -> SlotNo
electionSlot ElectionId
elId SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< LeiosOutstanding peer -> SlotNo
forall peer. LeiosOutstanding peer -> SlotNo
outstandingPrunedSlot LeiosOutstanding peer
outstanding = LeiosOutstanding peer
outstanding
  | Bool
otherwise =
      ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElection ElectionId
elId EndorserBlockHash
ebHash (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$
        LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
forall {peer}.
LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
trackCertifiedEb (SlotNo -> EndorserBlockHash -> LeiosPoint
MkLeiosPoint (ElectionId -> SlotNo
electionSlot ElectionId
elId) EndorserBlockHash
ebHash) LeiosOutstanding peer
outstanding

-- | Start tracking a certified endorser block, unless it is too old.
--
-- An 'ebState' entry is what makes a body fetchable at all: the decision logic
-- skips any offer of an endorser block it has no entry for. The announcement
-- this certificate names may have no entry, in two ways. Its announcing block
-- may have been on our selection since start-up, so its header never rolled
-- forward and nothing announced it to us. Or it may have been a second
-- announcement for an election already focused elsewhere, which is
-- deliberately not tracked.
--
-- Already holding the body is not a special case: 'recordReferencedPoint'
-- leaves the fetch state alone, so nothing is re-fetched.
trackCertifiedEb :: LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
trackCertifiedEb :: forall {peer}.
LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
trackCertifiedEb LeiosPoint
point LeiosOutstanding peer
outstanding
  | LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
point SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< LeiosOutstanding peer -> SlotNo
forall peer. LeiosOutstanding peer -> SlotNo
outstandingPrunedSlot LeiosOutstanding peer
outstanding = LeiosOutstanding peer
outstanding
  | Bool
otherwise = LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
point StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing LeiosOutstanding peer
outstanding

-- | Make this endorser block the one this election is fetching, whatever it was
-- fetching before.
--
-- Whatever it was fetching stops being asked for, unless another election is
-- also fetching it. Nothing else about that endorser block is disturbed: we
-- keep the body if we acquired it, and we still take whatever was already
-- requested for it, since those bytes are paid for either way.
--
-- NOTE One election, one certified endorser block --- which holds only while
-- enough of the committee's weight is honest, since two valid certificates for
-- one election means the committee equivocated. Should that ever happen, this
-- is last-claim-wins: each certificate moves the focus, so it ends on whichever
-- LeiosFetch learns of last, and the node can be left fetching the endorser
-- block of one fork while the chain it would select needs the other, and it
-- stays stuck there. The recourse is to restart the
-- node and hope the certificates arrive in the other order, since this state is
-- in memory only and the order they come back in is the network's to decide. We
-- deliberately do not spend complexity on that case here, since it requires
-- catastrophically buggy nodes and/or an amount of adversarial stake the
-- protocol itself is not designed to resist.
focusElection ::
  ElectionId -> EndorserBlockHash -> LeiosOutstanding peer -> LeiosOutstanding peer
focusElection :: forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElection ElectionId
elId EndorserBlockHash
ebHash LeiosOutstanding peer
outstanding = case ElectionId
-> Map ElectionId EndorserBlockHash -> Maybe EndorserBlockHash
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ElectionId
elId (LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding peer
outstanding) of
  Just EndorserBlockHash
oldEbHash | EndorserBlockHash
oldEbHash EndorserBlockHash -> EndorserBlockHash -> Bool
forall a. Eq a => a -> a -> Bool
== EndorserBlockHash
ebHash -> LeiosOutstanding peer
outstanding
  Maybe EndorserBlockHash
_ -> LeiosOutstanding peer
outstanding{elFocus = Map.insert elId ebHash (elFocus outstanding)}

-- | Whether some election is currently fetching this point: one in the point's
-- slot that focuses its endorser block. 'ElectionId' orders slot-first, so the
-- elections of a slot are a range of 'elFocus'. A slot has at most one election
-- per leader of that slot, and rarely has more than one leader, so the range is
-- short.
isFocusedPoint :: LeiosPoint -> LeiosOutstanding peer -> Bool
isFocusedPoint :: forall peer. LeiosPoint -> LeiosOutstanding peer -> Bool
isFocusedPoint (MkLeiosPoint SlotNo
slot EndorserBlockHash
ebHash) =
  EndorserBlockHash -> Map ElectionId EndorserBlockHash -> Bool
forall a. Eq a => a -> Map ElectionId a -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem EndorserBlockHash
ebHash
    (Map ElectionId EndorserBlockHash -> Bool)
-> (LeiosOutstanding peer -> Map ElectionId EndorserBlockHash)
-> LeiosOutstanding peer
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ElectionId -> Bool)
-> Map ElectionId EndorserBlockHash
-> Map ElectionId EndorserBlockHash
forall k a. (k -> Bool) -> Map k a -> Map k a
Map.takeWhileAntitone ((SlotNo -> SlotNo -> Bool
forall a. Eq a => a -> a -> Bool
== SlotNo
slot) (SlotNo -> Bool) -> (ElectionId -> SlotNo) -> ElectionId -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId -> SlotNo
electionSlot)
    (Map ElectionId EndorserBlockHash
 -> Map ElectionId EndorserBlockHash)
-> (LeiosOutstanding peer -> Map ElectionId EndorserBlockHash)
-> LeiosOutstanding peer
-> Map ElectionId EndorserBlockHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ElectionId -> Bool)
-> Map ElectionId EndorserBlockHash
-> Map ElectionId EndorserBlockHash
forall k a. (k -> Bool) -> Map k a -> Map k a
Map.dropWhileAntitone ((SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< SlotNo
slot) (SlotNo -> Bool) -> (ElectionId -> SlotNo) -> ElectionId -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId -> SlotNo
electionSlot)
    (Map ElectionId EndorserBlockHash
 -> Map ElectionId EndorserBlockHash)
-> (LeiosOutstanding peer -> Map ElectionId EndorserBlockHash)
-> LeiosOutstanding peer
-> Map ElectionId EndorserBlockHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus

-- | 'Map.alter' a point's 'ebState' entry.
alterEbState ::
  LeiosPoint ->
  (Maybe EbState -> Maybe EbState) ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
alterEbState :: forall peer.
LeiosPoint
-> (Maybe EbState -> Maybe EbState)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
alterEbState LeiosPoint
point Maybe EbState -> Maybe EbState
f LeiosOutstanding peer
outstanding =
  LeiosOutstanding peer
outstanding{ebState = Map.alter f point (ebState outstanding)}

-- | Prune 'LeiosOutstanding' to the immutable tip.
--
-- 'LeiosPoint' and 'ElectionId' both order slot-first, so what is below the tip
-- is a prefix of each map, dropped with @dropWhileAntitone@.
--
-- TODO still more it could prune (e.g. abandoned in-flight EB requests).
pruneOutstandingToImmTip :: SlotNo -> LeiosOutstanding peer -> LeiosOutstanding peer
pruneOutstandingToImmTip :: forall peer.
SlotNo -> LeiosOutstanding peer -> LeiosOutstanding peer
pruneOutstandingToImmTip SlotNo
immTipSlot LeiosOutstanding peer
outstanding =
  LeiosOutstanding peer
outstanding
    { ebState = Map.dropWhileAntitone ((< immTipSlot) . pointSlotNo) (ebState outstanding)
    , elFocus = Map.dropWhileAntitone ((< immTipSlot) . electionSlot) (elFocus outstanding)
    , outstandingPrunedSlot = max (outstandingPrunedSlot outstanding) immTipSlot
    }

{-------------------------------------------------------------------------------
  Settled requests
-------------------------------------------------------------------------------}

-- | 'Nothing' if the predicate holds.
delIf :: (a -> Bool) -> a -> Maybe a
delIf :: forall a. (a -> Bool) -> a -> Maybe a
delIf a -> Bool
predicate a
x = if a -> Bool
predicate a
x then Maybe a
forall a. Maybe a
Nothing else a -> Maybe a
forall a. a -> Maybe a
Just a
x

-- | Cancel all of a peer's outstanding fetch requests in bulk, e.g. when it
-- disconnects: refund its share of the request budget, drop it from the per-EB
-- body request set ('requestedEbPeers'), and -- via the per-peer
-- 'requestedEbsPerPeer' and 'requestedJobsPerPeer' indices -- decrement the
-- multiplicity of every job it had in flight, so those bodies and jobs become
-- re-requestable from other peers.
removePeerFromOutstanding ::
  Ord peer =>
  peer ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
removePeerFromOutstanding :: forall peer.
Ord peer =>
peer -> LeiosOutstanding peer -> LeiosOutstanding peer
removePeerFromOutstanding peer
peer LeiosOutstanding peer
o =
  LeiosOutstanding peer
o
    { requestedBytesSizePerPeer = Map.delete peer (requestedBytesSizePerPeer o)
    , requestedEbPeers =
        F.foldl'
          (flip $ Map.update (delIf Set.null . Set.delete peer))
          (requestedEbPeers o)
          (maybe Set.empty NESet.toSet (Map.lookup peer (requestedEbsPerPeer o)))
    , requestedEbsPerPeer = Map.delete peer (requestedEbsPerPeer o)
    , requestedJobsPerPeer = Map.delete peer (requestedJobsPerPeer o)
    , ebState =
        Map.foldrWithKey
          (\LeiosPoint
point NEIntSet
jobIds -> (EbState -> EbState)
-> LeiosPoint -> Map LeiosPoint EbState -> Map LeiosPoint EbState
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
Map.adjust (NEIntSet -> EbState -> EbState
releaseJobs NEIntSet
jobIds) LeiosPoint
point)
          (ebState o)
          (Map.findWithDefault Map.empty peer (requestedJobsPerPeer o))
    }
 where
  -- Decrement, in that EB's jobPool, the multiplicity of each job this peer held.
  releaseJobs :: NEIntSet -> EbState -> EbState
releaseJobs NEIntSet
jobIds (MkEbState StrictMaybe RelativeTime
onset EbFetchState
fetchState) =
    StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset (EbFetchState -> EbState) -> EbFetchState -> EbState
forall a b. (a -> b) -> a -> b
$ case EbFetchState
fetchState of
      EbFetchState
NoBody -> EbFetchState
NoBody
      BodyAcquired LeiosJobPool
jobPool -> LeiosJobPool -> EbFetchState
BodyAcquired (LeiosJobPool -> EbFetchState) -> LeiosJobPool -> EbFetchState
forall a b. (a -> b) -> a -> b
$! LeiosJobPool -> LeiosJobPool
release LeiosJobPool
jobPool
   where
    release :: LeiosJobPool -> LeiosJobPool
release LeiosJobPool
jobPool =
      (LeiosJobPool -> Int -> LeiosJobPool)
-> LeiosJobPool -> NEIntSet -> LeiosJobPool
forall a. (a -> Int -> a) -> a -> NEIntSet -> a
NEIntSet.foldl' ((Int -> LeiosJobPool -> LeiosJobPool)
-> LeiosJobPool -> Int -> LeiosJobPool
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((Int -> LeiosJobPool -> LeiosJobPool)
 -> LeiosJobPool -> Int -> LeiosJobPool)
-> (Int -> LeiosJobPool -> LeiosJobPool)
-> LeiosJobPool
-> Int
-> LeiosJobPool
forall a b. (a -> b) -> a -> b
$ LeiosJobId -> LeiosJobPool -> LeiosJobPool
Jobs.unpickJob (LeiosJobId -> LeiosJobPool -> LeiosJobPool)
-> (Int -> LeiosJobId) -> Int -> LeiosJobPool -> LeiosJobPool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> LeiosJobId
Jobs.MkLeiosJobId) LeiosJobPool
jobPool NEIntSet
jobIds

-- | Reverse this peer's per-request accounting for a received EB body, but only
-- if the peer is still tracked.
--
-- If the peer has already been cancelled in bulk (e.g. it disconnected and its
-- requests were refunded en masse via its 'requestedBytesSizePerPeer' total),
-- that entry is gone; re-applying the per-request refund here would
-- double-subtract 'requestedBytesSizePerPeer' and underflow. So we gate on the peer
-- still being present. The membership check, the refund, and the bulk
-- cancellation all run within the same critical section, so whichever happens
-- first refunds and the other does nothing.
refundEbRequest ::
  Ord peer =>
  peer ->
  LeiosPoint ->
  BytesSize ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
refundEbRequest :: forall peer.
Ord peer =>
peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
refundEbRequest peer
peer LeiosPoint
point Word32
ebBytesSize LeiosOutstanding peer
o
  | peer -> Map peer Word32 -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member peer
peer (LeiosOutstanding peer -> Map peer Word32
forall peer. LeiosOutstanding peer -> Map peer Word32
requestedBytesSizePerPeer LeiosOutstanding peer
o) =
      LeiosOutstanding peer
o
        { requestedBytesSizePerPeer =
            Map.update (\Word32
x -> (Word32 -> Bool) -> Word32 -> Maybe Word32
forall a. (a -> Bool) -> a -> Maybe a
delIf (Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
== Word32
0) (Word32
x Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
ebBytesSize)) peer (requestedBytesSizePerPeer o)
        , requestedEbPeers =
            Map.update (delIf Set.null . Set.delete peer) point (requestedEbPeers o)
        , requestedEbsPerPeer =
            Map.update (NESet.nonEmptySet . NESet.delete point) peer (requestedEbsPerPeer o)
        }
  | Bool
otherwise = LeiosOutstanding peer
o

-- | Like 'refundEbRequest', but for a received batch of EB txs: refunds the
-- bytes, gated on the peer still being tracked (see 'refundEbRequest'). The job
-- bookkeeping (jobPool + this peer's in-flight set) is handled by
-- 'completeTxRequest'.
refundTxRequest ::
  Ord peer =>
  peer ->
  BytesSize ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
refundTxRequest :: forall peer.
Ord peer =>
peer -> Word32 -> LeiosOutstanding peer -> LeiosOutstanding peer
refundTxRequest peer
peer Word32
txsBytesSize LeiosOutstanding peer
o
  | peer -> Map peer Word32 -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member peer
peer (LeiosOutstanding peer -> Map peer Word32
forall peer. LeiosOutstanding peer -> Map peer Word32
requestedBytesSizePerPeer LeiosOutstanding peer
o) =
      LeiosOutstanding peer
o
        { requestedBytesSizePerPeer =
            Map.update (\Word32
x -> (Word32 -> Bool) -> Word32 -> Maybe Word32
forall a. (a -> Bool) -> a -> Maybe a
delIf (Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
== Word32
0) (Word32
x Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
txsBytesSize)) peer (requestedBytesSizePerPeer o)
        }
  | Bool
otherwise = LeiosOutstanding peer
o

-- | On a received tx batch, remove its now-fetched jobs: delete them from the
-- EB's jobPool (they are done for /every/ peer) and from this peer's in-flight set,
-- so neither this peer nor any other is asked for them again. Complements
-- 'refundTxRequest', which handles only the per-peer byte accounting.
completeTxRequest ::
  Ord peer =>
  peer ->
  LeiosBlockTxsRequest ->
  LeiosOutstanding peer ->
  LeiosOutstanding peer
completeTxRequest :: forall peer.
Ord peer =>
peer
-> LeiosBlockTxsRequest
-> LeiosOutstanding peer
-> LeiosOutstanding peer
completeTxRequest peer
peer (MkLeiosBlockTxsRequest LeiosPoint
point NEIntMap LeiosJob
jobs) LeiosOutstanding peer
o =
  LeiosOutstanding peer
o
    { ebState = Map.adjust completeInJobPool point (ebState o)
    , requestedJobsPerPeer =
        Map.update (nonEmptyMap . Map.update dropJobs point) peer (requestedJobsPerPeer o)
    }
 where
  jobIds :: NEIntSet
jobIds = NEIntMap LeiosJob -> NEIntSet
forall a. NEIntMap a -> NEIntSet
NEIntMap.keysSet NEIntMap LeiosJob
jobs
  completeInJobPool :: EbState -> EbState
completeInJobPool (MkEbState StrictMaybe RelativeTime
onset EbFetchState
fetchState) =
    StrictMaybe RelativeTime -> EbFetchState -> EbState
MkEbState StrictMaybe RelativeTime
onset (EbFetchState -> EbState) -> EbFetchState -> EbState
forall a b. (a -> b) -> a -> b
$ case EbFetchState
fetchState of
      EbFetchState
NoBody -> EbFetchState
NoBody
      BodyAcquired LeiosJobPool
jobPool -> LeiosJobPool -> EbFetchState
BodyAcquired (LeiosJobPool -> EbFetchState) -> LeiosJobPool -> EbFetchState
forall a b. (a -> b) -> a -> b
$! LeiosJobPool -> LeiosJobPool
complete LeiosJobPool
jobPool
   where
    complete :: LeiosJobPool -> LeiosJobPool
complete LeiosJobPool
jobPool =
      (LeiosJobPool -> Int -> LeiosJobPool)
-> LeiosJobPool -> NEIntSet -> LeiosJobPool
forall a. (a -> Int -> a) -> a -> NEIntSet -> a
NEIntSet.foldl' ((Int -> LeiosJobPool -> LeiosJobPool)
-> LeiosJobPool -> Int -> LeiosJobPool
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((Int -> LeiosJobPool -> LeiosJobPool)
 -> LeiosJobPool -> Int -> LeiosJobPool)
-> (Int -> LeiosJobPool -> LeiosJobPool)
-> LeiosJobPool
-> Int
-> LeiosJobPool
forall a b. (a -> b) -> a -> b
$ LeiosJobId -> LeiosJobPool -> LeiosJobPool
Jobs.completeJob (LeiosJobId -> LeiosJobPool -> LeiosJobPool)
-> (Int -> LeiosJobId) -> Int -> LeiosJobPool -> LeiosJobPool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> LeiosJobId
Jobs.MkLeiosJobId) LeiosJobPool
jobPool NEIntSet
jobIds
  dropJobs :: NEIntSet -> Maybe NEIntSet
dropJobs NEIntSet
held =
    IntSet -> Maybe NEIntSet
NEIntSet.nonEmptySet (IntSet -> IntSet -> IntSet
IntSet.difference (NEIntSet -> IntSet
NEIntSet.toSet NEIntSet
held) (NEIntSet -> IntSet
NEIntSet.toSet NEIntSet
jobIds))
  nonEmptyMap :: Map k a -> Maybe (Map k a)
nonEmptyMap Map k a
m = if Map k a -> Bool
forall k a. Map k a -> Bool
Map.null Map k a
m then Maybe (Map k a)
forall a. Maybe a
Nothing else Map k a -> Maybe (Map k a)
forall a. a -> Maybe a
Just Map k a
m

{-------------------------------------------------------------------------------
  Deciding
-------------------------------------------------------------------------------}

-- | The limits the decision logic holds its requests to.
--
-- The per-peer caps are hard: a request is made only if it fits in what
-- remains of its peer's cap ('peerBudget'). A request larger than a whole cap
-- is never made to that peer, so each cap must be at least the largest body the
-- node fetches ('Ouroboros.Consensus.Leios.Types.maxEndorserBlockBytesSize')
-- and the largest job (the larger of 'maxJobBytesSize' and the ledger's
-- @maxTxSize@).
--
-- 'maxJobBytesSize' and 'maxRequestBytesSize' are technically soft, but
-- effectively hard because of the current protocol parameters. A transaction
-- larger than 'maxJobBytesSize' forms a job by itself, and a job larger than
-- 'maxRequestBytesSize' forms a request by itself. Neither happens while the
-- ledger's @maxTxSize@ is at most 'maxJobBytesSize' and that is at most
-- 'maxRequestBytesSize': the current constitution's guardrails cap @maxTxSize@
-- at 32,768 bytes (MTS-01), in Dijkstra as in Conway, and the defaults here
-- are 64 KiB and 500 kB. 'maxJobTxCount' is hard.
data LeiosFetchStaticEnv = MkLeiosFetchStaticEnv
  { LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerPeer :: BytesSize
  -- ^ At most this many outstanding bytes requested from each non-big-ledger
  -- peer
  , LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerBigLedgerPeer :: BytesSize
  -- ^ At most this many outstanding bytes requested from each big-ledger peer.
  --
  -- At most the LeiosFetch ingress queue's size: the scheduler must never
  -- leave more requested-but-unconsumed response bytes outstanding than that
  -- queue can hold, else the mux tears the connection down (see
  -- @Network.Mux.Ingress@'s @IngressQueueOverRun@).
  --
  -- Larger than 'maxRequestedBytesSizePerPeer' so a high-stake peer can be asked
  -- for multiple whole EB closures at once, but still bounded so an adversarial
  -- peer can't drown us.
  , LeiosFetchStaticEnv -> Word32
maxRequestBytesSize :: BytesSize
  -- ^ At most this many outstanding bytes per request.
  --
  -- At most 'maxLeiosTxsRequestBytesSize', by which the codec bounds the reply
  -- ('Ouroboros.Consensus.MiniProtocol.LeiosFetch.Type.byteLimitsLeiosFetch'):
  -- an honest peer's reply to a larger request could cost it its connection.
  , LeiosFetchStaticEnv -> Word32
maxJobBytesSize :: BytesSize
  -- ^ At most this many bytes of txs per job
  , LeiosFetchStaticEnv -> Int
maxJobTxCount :: Int
  -- ^ At most this many txs per job
  }

-- | The settings the node runs with, given 'maxRequestedBytesSizePerBigLedgerPeer'.
defaultLeiosFetchStaticEnv :: BytesSize -> LeiosFetchStaticEnv
defaultLeiosFetchStaticEnv :: Word32 -> LeiosFetchStaticEnv
defaultLeiosFetchStaticEnv Word32
maxPerBigLedgerPeer =
  MkLeiosFetchStaticEnv
    { maxRequestedBytesSizePerPeer :: Word32
maxRequestedBytesSizePerPeer = Word32
5 Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
forall a. Num a => a
million
    , maxRequestedBytesSizePerBigLedgerPeer :: Word32
maxRequestedBytesSizePerBigLedgerPeer = Word32
maxPerBigLedgerPeer
    , maxRequestBytesSize :: Word32
maxRequestBytesSize = Word32
maxLeiosTxsRequestBytesSize
    , maxJobBytesSize :: Word32
maxJobBytesSize = Word32
64 Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
forall a. Num a => a
thousandBase2
    , maxJobTxCount :: Int
maxJobTxCount = Int
20000 -- TODO do we want this to be low enough to matter?
    }
 where
  million :: Num a => a
  million :: forall a. Num a => a
million = a
10 a -> Int -> a
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
6 :: Int)
  thousandBase2 :: Num a => a
  thousandBase2 :: forall a. Num a => a
thousandBase2 = a
2 a -> Int -> a
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
10 :: Int)

-- | Decide what to request from each peer right now
--
-- A big-ledger peer is fetched from aggressively: it has a larger per-peer
-- byte budget, enough that a closure it offers is requested in full (the whole
-- remaining job pool) at once.
--
-- NOTE that which txs a point still lacks was settled when its body's write
-- landed, so a job is requested even if the node has come to hold its txs
-- elsewhere since. (TODO the LeiosFetch client could check again just before
-- it sends the request? That would need the txs' hashes, retained in memory or
-- read from disk.)
leiosFetchLogicIteration ::
  Ord peer =>
  LeiosFetchStaticEnv ->
  -- | The ledger's bounds on an EB, forecast from the immutable tip to a slot.
  -- The slot can be older than the immutable tip, for a point not pruned yet.
  --
  -- Only an offer that brought no bound of its own needs this, and for those it
  -- cannot fail: the announcement backing such an offer was accepted by
  -- forecasting to that same slot from an immutable tip no newer than this
  -- one. See 'poEbBounds'.
  (SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)) ->
  -- | The current slot, and how many slots before it a point is still worth
  -- voting on, as of the ledger there (see 'fetchPriorityTiers'); or 'Nothing'
  -- when either is not yet known (i.e. we are syncing), in which case we fetch
  -- freshest-last instead of freshest-first.
  Maybe (SlotNo, Word64) ->
  Map peer (Map LeiosPoint PeerOffer) ->
  -- | Which peers are big-ledger peers (a peer absent from this map is treated as
  -- 'IsNotBigLedgerPeer').
  Map peer IsBigLedgerPeer ->
  LeiosOutstanding peer ->
  -- | The new outstanding state, the requests to send, and what of the offers
  -- to prune ('pruneOffers')
  ( LeiosOutstanding peer
  , Map peer (NESeq LeiosFetchRequest)
  , Map peer (NEMap LeiosPoint OfferPrune)
  )
leiosFetchLogicIteration :: forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration LeiosFetchStaticEnv
env SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds Maybe (SlotNo, Word64)
mbHorizon Map peer (Map LeiosPoint PeerOffer)
offerings Map peer IsBigLedgerPeer
bigLedgerPeers = \LeiosOutstanding peer
acc0 ->
  -- One pass per peer. Bodies and tx-closure jobs compete on equal footing,
  -- ranked by their points' slots (see 'fetchPriorityTiers'), whether it is
  -- the body or the closure they still
  -- need.
  -- Each peer's 'assignPeer' yields only its own requests and dead offers; fold
  -- those into the per-peer maps here.
  ((LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
  Map peer (NEMap LeiosPoint OfferPrune))
 -> peer
 -> Map LeiosPoint PeerOffer
 -> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
     Map peer (NEMap LeiosPoint OfferPrune)))
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
-> Map peer (Map LeiosPoint PeerOffer)
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
forall a k b. (a -> k -> b -> a) -> a -> Map k b -> a
Map.foldlWithKey'
    ( \(LeiosOutstanding peer
acc, Map peer (NESeq LeiosFetchRequest)
reqs, Map peer (NEMap LeiosPoint OfferPrune)
drops) peer
peer Map LeiosPoint PeerOffer
offers ->
        let isBig :: IsBigLedgerPeer
isBig = IsBigLedgerPeer
-> peer -> Map peer IsBigLedgerPeer -> IsBigLedgerPeer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault IsBigLedgerPeer
IsNotBigLedgerPeer peer
peer Map peer IsBigLedgerPeer
bigLedgerPeers
            (LeiosOutstanding peer
acc', Seq LeiosFetchRequest
peerReqs, Map LeiosPoint OfferPrune
peerDrops) =
              LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> IsBigLedgerPeer
-> peer
-> Map LeiosPoint PeerOffer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> IsBigLedgerPeer
-> peer
-> Map LeiosPoint PeerOffer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
assignPeer LeiosFetchStaticEnv
env SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds Maybe (SlotNo, Word64)
mbHorizon IsBigLedgerPeer
isBig peer
peer Map LeiosPoint PeerOffer
offers LeiosOutstanding peer
acc
         in ( LeiosOutstanding peer
acc'
            , case Seq LeiosFetchRequest -> Maybe (NESeq LeiosFetchRequest)
forall a. Seq a -> Maybe (NESeq a)
NESeq.nonEmptySeq Seq LeiosFetchRequest
peerReqs of
                Maybe (NESeq LeiosFetchRequest)
Nothing -> Map peer (NESeq LeiosFetchRequest)
reqs
                Just NESeq LeiosFetchRequest
neReqs -> peer
-> NESeq LeiosFetchRequest
-> Map peer (NESeq LeiosFetchRequest)
-> Map peer (NESeq LeiosFetchRequest)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert peer
peer NESeq LeiosFetchRequest
neReqs Map peer (NESeq LeiosFetchRequest)
reqs
            , case Map LeiosPoint OfferPrune -> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Map k a -> Maybe (NEMap k a)
NEMap.nonEmptyMap Map LeiosPoint OfferPrune
peerDrops of
                Maybe (NEMap LeiosPoint OfferPrune)
Nothing -> Map peer (NEMap LeiosPoint OfferPrune)
drops
                Just NEMap LeiosPoint OfferPrune
nes -> peer
-> NEMap LeiosPoint OfferPrune
-> Map peer (NEMap LeiosPoint OfferPrune)
-> Map peer (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert peer
peer NEMap LeiosPoint OfferPrune
nes Map peer (NEMap LeiosPoint OfferPrune)
drops
            )
    )
    (LeiosOutstanding peer
acc0, Map peer (NESeq LeiosFetchRequest)
forall k a. Map k a
Map.empty, Map peer (NEMap LeiosPoint OfferPrune)
forall k a. Map k a
Map.empty)
    Map peer (Map LeiosPoint PeerOffer)
offerings

-- | A peer's remaining outstanding-byte budget. The only "global limit" falls
-- out as this per-peer cap multiplied by the peer count. That's good so that
-- an adversarial peer can't occupy "too much" of some fixed global budget,
-- thereby starving honest peers.
--
-- Big-ledger peers get a larger cap (so they can be asked for a whole EB closure
-- at once), but still a bounded one -- even a stake-based peer might be adversarial.
peerBudget ::
  Ord peer => LeiosFetchStaticEnv -> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
peerBudget :: forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
peerBudget LeiosFetchStaticEnv
env IsBigLedgerPeer
isBig LeiosOutstanding peer
acc peer
peer =
  Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
cap
    Int -> Int -> Int
forall a. Num a => a -> a -> a
- Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word32 -> peer -> Map peer Word32 -> Word32
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Word32
0 peer
peer (LeiosOutstanding peer -> Map peer Word32
forall peer. LeiosOutstanding peer -> Map peer Word32
requestedBytesSizePerPeer LeiosOutstanding peer
acc))
 where
  cap :: Word32
cap = case IsBigLedgerPeer
isBig of
    IsBigLedgerPeer
IsBigLedgerPeer -> LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerBigLedgerPeer LeiosFetchStaticEnv
env
    IsBigLedgerPeer
IsNotBigLedgerPeer -> LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerPeer LeiosFetchStaticEnv
env

-- | Prioritize a peer's Leios offers, each given with its point's slot
--
-- The offers are categorized into two tiers. The high-priority tier is the
-- points still worth voting on: those no older than @L = 3*L_hdr + L_vote +
-- L_diff@, in slots, as of the ledger at the current slot (ie whose slot is
-- @>= currentSlot - L@). It prioritizes /staler/ points. The low-priority tier
-- is the rest, and it prioritizes /fresher/ points.
--
-- 'assignPeer' processes the high-priority tier first and then it carries over
-- the resulting accumulator in order to process the low-priority tier.
--
-- When the node's ledger state is too old to know the current slot or @L@ there,
-- all points are categorized as the high-priority tier, and the low-priority
-- tier is empty.
--
-- TODO rank first the points a verified certificate certifies (see
-- 'focusCertifiedEb'): ChainSel cannot select the block certifying one until
-- the node holds its closure.
fetchPriorityTiers :: Maybe (SlotNo, Word64) -> [(SlotNo, v)] -> ([v], [v])
fetchPriorityTiers :: forall v. Maybe (SlotNo, Word64) -> [(SlotNo, v)] -> ([v], [v])
fetchPriorityTiers Maybe (SlotNo, Word64)
mbHorizon [(SlotNo, v)]
offers =
  ( ((SlotNo, v) -> v) -> [(SlotNo, v)] -> [v]
forall a b. (a -> b) -> [a] -> [b]
map (SlotNo, v) -> v
forall a b. (a, b) -> b
snd ([(SlotNo, v)] -> [v]) -> [(SlotNo, v)] -> [v]
forall a b. (a -> b) -> a -> b
$ ((SlotNo, v) -> SlotNo) -> [(SlotNo, v)] -> [(SlotNo, v)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (SlotNo, v) -> SlotNo
forall a b. (a, b) -> a
fst [(SlotNo, v)]
high
  , ((SlotNo, v) -> v) -> [(SlotNo, v)] -> [v]
forall a b. (a -> b) -> [a] -> [b]
map (SlotNo, v) -> v
forall a b. (a, b) -> b
snd ([(SlotNo, v)] -> [v]) -> [(SlotNo, v)] -> [v]
forall a b. (a -> b) -> a -> b
$ ((SlotNo, v) -> Down SlotNo) -> [(SlotNo, v)] -> [(SlotNo, v)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (SlotNo -> Down SlotNo
forall a. a -> Down a
Down (SlotNo -> Down SlotNo)
-> ((SlotNo, v) -> SlotNo) -> (SlotNo, v) -> Down SlotNo
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SlotNo, v) -> SlotNo
forall a b. (a, b) -> a
fst) [(SlotNo, v)]
low
  )
 where
  ([(SlotNo, v)]
high, [(SlotNo, v)]
low) = ((SlotNo, v) -> Bool)
-> [(SlotNo, v)] -> ([(SlotNo, v)], [(SlotNo, v)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Bool -> Bool
not (Bool -> Bool) -> ((SlotNo, v) -> Bool) -> (SlotNo, v) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SlotNo -> Bool
stale (SlotNo -> Bool) -> ((SlotNo, v) -> SlotNo) -> (SlotNo, v) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SlotNo, v) -> SlotNo
forall a b. (a, b) -> a
fst) [(SlotNo, v)]
offers

  -- @a + l < s@ (i.e. @a < S - L@) is stale, guarding underflow when @S < L@.
  stale :: SlotNo -> Bool
stale (SlotNo Word64
a) = case Maybe (SlotNo, Word64)
mbHorizon of
    Maybe (SlotNo, Word64)
Nothing -> Bool
False
    Just (SlotNo Word64
s, Word64
l) -> Word64
a Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
l Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
s

-- | Walk this peer's offered points in priority order (see
-- 'fetchPriorityTiers'), assigning requests to the peer until one does not fit
-- in what remains of its cap ('peerBudget'): 'maxRequestedBytesSizePerPeer',
-- or for a big-ledger peer the larger 'maxRequestedBytesSizePerBigLedgerPeer',
-- enough that a couple closures it offers can be entirely inflight at the same
-- time (see 'assignClosure').
--
-- The walk stops at that request rather than skipping it for smaller ones
-- further on, so that those cannot keep it waiting indefinitely.
--
-- Offers beyond that point are never visited, so aren't pruned this pass;
-- that's fine because it's ephemeral and/or the other prune based on the
-- imm-tip advancing is a backstop.
assignPeer ::
  Ord peer =>
  LeiosFetchStaticEnv ->
  (SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)) ->
  Maybe (SlotNo, Word64) ->
  IsBigLedgerPeer ->
  peer ->
  Map LeiosPoint PeerOffer ->
  LeiosOutstanding peer ->
  (LeiosOutstanding peer, Seq LeiosFetchRequest, Map LeiosPoint OfferPrune)
assignPeer :: forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> IsBigLedgerPeer
-> peer
-> Map LeiosPoint PeerOffer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
assignPeer LeiosFetchStaticEnv
env SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds Maybe (SlotNo, Word64)
mbHorizon IsBigLedgerPeer
isBig peer
peer Map LeiosPoint PeerOffer
offers LeiosOutstanding peer
acc =
  (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> [(LeiosPoint, PeerOffer)]
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
go (LeiosOutstanding peer
acc, Seq LeiosFetchRequest
forall a. Seq a
Seq.empty, Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty) ([(LeiosPoint, PeerOffer)]
highTier [(LeiosPoint, PeerOffer)]
-> [(LeiosPoint, PeerOffer)] -> [(LeiosPoint, PeerOffer)]
forall a. Semigroup a => a -> a -> a
<> [(LeiosPoint, PeerOffer)]
lowTier)
 where
  ([(LeiosPoint, PeerOffer)]
highTier, [(LeiosPoint, PeerOffer)]
lowTier) =
    Maybe (SlotNo, Word64)
-> [(SlotNo, (LeiosPoint, PeerOffer))]
-> ([(LeiosPoint, PeerOffer)], [(LeiosPoint, PeerOffer)])
forall v. Maybe (SlotNo, Word64) -> [(SlotNo, v)] -> ([v], [v])
fetchPriorityTiers
      Maybe (SlotNo, Word64)
mbHorizon
      -- Only what some election is currently fetching. An offer of anything
      -- else is skipped rather than dropped, so it comes back into play if some
      -- election later fetches that point, because a certificate moved an
      -- election onto it.
      [ (LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
point, (LeiosPoint
point, PeerOffer
offer))
      | (LeiosPoint
point, PeerOffer
offer) <- Map LeiosPoint PeerOffer -> [(LeiosPoint, PeerOffer)]
forall k a. Map k a -> [(k, a)]
Map.toList Map LeiosPoint PeerOffer
offers
      , LeiosPoint -> LeiosOutstanding peer -> Bool
forall peer. LeiosPoint -> LeiosOutstanding peer -> Bool
isFocusedPoint LeiosPoint
point LeiosOutstanding peer
acc
      ]

  go :: (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> [(LeiosPoint, PeerOffer)]
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
go (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st = \case
    [] -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st
    (LeiosPoint
point, PeerOffer
offerKind) : [(LeiosPoint, PeerOffer)]
rest -> case LeiosPoint
-> PeerOffer
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
classify LeiosPoint
point PeerOffer
offerKind (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st of
      ((LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st', WhetherPeerSaturated
PeerSaturated) -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st'
      ((LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st', WhetherPeerSaturated
PeerNotSaturated) -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> [(LeiosPoint, PeerOffer)]
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
go (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
st' [(LeiosPoint, PeerOffer)]
rest

  classify :: LeiosPoint
-> PeerOffer
-> (LeiosOutstanding peer, Seq LeiosFetchRequest,
    Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
classify LeiosPoint
point PeerOffer
offerKind (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, Map LeiosPoint OfferPrune
drops) =
    case LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
acc1) of
      Maybe EbState
Nothing ->
        -- We are no longer tracking this point (pruned off below the
        -- imm-tip). This is an ephemeral state, mid prune, but go ahead and
        -- prune it now.
        ((LeiosOutstanding peer, Seq LeiosFetchRequest,
  Map LeiosPoint OfferPrune),
 WhetherPeerSaturated)
pruneThisOffer
      Just (MkEbState StrictMaybe RelativeTime
onset EbFetchState
fetchState) -> case (EbFetchState
fetchState, PeerOffer -> OfferedHalves
poOffered PeerOffer
offerKind) of
        (EbFetchState
NoBody, OfferedBody Word32
size) ->
          -- Body-only offer: request the body, and prune the offer.
          Word32
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestBodyAndPrune Word32
size
        (EbFetchState
NoBody, OfferedHalves
OfferedClosure) ->
          -- Nothing to request until we hold the body.
          (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, Map LeiosPoint OfferPrune
drops)
        (EbFetchState
NoBody, OfferedBodyAndClosure Word32
size) ->
          -- Request the body now, and prune only the body half of the offer:
          -- we will request the closure from this peer once we hold the body,
          -- but never ask it for the body again.
          Word32
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestBodyAndPrune Word32
size
        (BodyAcquired LeiosJobPool
_jobPool, OfferedBody Word32
_size) ->
          -- We hold the body, and the peer offered only the body.
          (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, LeiosPoint
-> OfferPrune
-> Map LeiosPoint OfferPrune
-> Map LeiosPoint OfferPrune
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert LeiosPoint
point OfferPrune
PruneOfferedBody Map LeiosPoint OfferPrune
drops)
        (BodyAcquired LeiosJobPool
jobPool, OfferedHalves
OfferedClosure) -> StrictMaybe RelativeTime
-> LeiosJobPool
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestClosure StrictMaybe RelativeTime
onset LeiosJobPool
jobPool
        (BodyAcquired LeiosJobPool
jobPool, OfferedBodyAndClosure Word32
_size) -> StrictMaybe RelativeTime
-> LeiosJobPool
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestClosure StrictMaybe RelativeTime
onset LeiosJobPool
jobPool
   where
    budget :: Int
budget = LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
peerBudget LeiosFetchStaticEnv
env IsBigLedgerPeer
isBig LeiosOutstanding peer
acc1 peer
peer

    continue :: a -> (a, WhetherPeerSaturated)
continue a
st = (a
st, WhetherPeerSaturated
PeerNotSaturated)

    pruneThisOffer :: ((LeiosOutstanding peer, Seq LeiosFetchRequest,
  Map LeiosPoint OfferPrune),
 WhetherPeerSaturated)
pruneThisOffer = (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, LeiosPoint
-> OfferPrune
-> Map LeiosPoint OfferPrune
-> Map LeiosPoint OfferPrune
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert LeiosPoint
point OfferPrune
PruneOffer Map LeiosPoint OfferPrune
drops)

    -- Prune the offer's body half only once the body is requested, so that an
    -- offer not acted on now is still there for a later iteration.
    requestBodyAndPrune :: Word32
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestBodyAndPrune Word32
size =
      case (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Int
-> peer
-> LeiosPoint
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> Word32
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> AssignedBody peer
forall peer.
Ord peer =>
(SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Int
-> peer
-> LeiosPoint
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> Word32
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> AssignedBody peer
assignBody SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds Int
budget peer
peer LeiosPoint
point (PeerOffer -> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
poEbBounds PeerOffer
offerKind) Word32
size (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1) of
        AssignedBody peer
BodyNotRequested -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, Map LeiosPoint OfferPrune
drops)
        AssignedBody peer
BodyOverBudget -> ((LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1, Map LeiosPoint OfferPrune
drops), WhetherPeerSaturated
PeerSaturated)
        BodyRequested LeiosOutstanding peer
acc2 Seq LeiosFetchRequest
dec2 -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc2, Seq LeiosFetchRequest
dec2, LeiosPoint
-> OfferPrune
-> Map LeiosPoint OfferPrune
-> Map LeiosPoint OfferPrune
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert LeiosPoint
point OfferPrune
PruneOfferedBody Map LeiosPoint OfferPrune
drops)

    requestClosure :: StrictMaybe RelativeTime
-> LeiosJobPool
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
requestClosure StrictMaybe RelativeTime
onset LeiosJobPool
jobPool
      | LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
jobPool =
          -- Nothing left to fetch --- the whole datum is in hand, or we
          -- rejected the endorser block on arrival --- so the closure offer
          -- is useless now too.
          ((LeiosOutstanding peer, Seq LeiosFetchRequest,
  Map LeiosPoint OfferPrune),
 WhetherPeerSaturated)
pruneThisOffer
      | Bool
otherwise =
          -- Still need the txs, and the peer offered the closure. If we just
          -- now assign all remaining jobs to the peer, prune its offer.
          let ((LeiosOutstanding peer
acc2, Seq LeiosFetchRequest
dec2), WhyPickingStopped
stopped) = LeiosFetchStaticEnv
-> IsBigLedgerPeer
-> peer
-> LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosJobPool
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
    WhyPickingStopped)
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer
-> peer
-> LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosJobPool
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
    WhyPickingStopped)
assignClosure LeiosFetchStaticEnv
env IsBigLedgerPeer
isBig peer
peer LeiosPoint
point StrictMaybe RelativeTime
onset LeiosJobPool
jobPool (LeiosOutstanding peer
acc1, Seq LeiosFetchRequest
dec1)
           in case WhyPickingStopped
stopped of
                WhyPickingStopped
PeerEbExhausted -> (LeiosOutstanding peer, Seq LeiosFetchRequest,
 Map LeiosPoint OfferPrune)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest,
     Map LeiosPoint OfferPrune),
    WhetherPeerSaturated)
forall {a}. a -> (a, WhetherPeerSaturated)
continue (LeiosOutstanding peer
acc2, Seq LeiosFetchRequest
dec2, LeiosPoint
-> OfferPrune
-> Map LeiosPoint OfferPrune
-> Map LeiosPoint OfferPrune
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert LeiosPoint
point OfferPrune
PruneOffer Map LeiosPoint OfferPrune
drops)
                WhyPickingStopped
NextJobOverBudget -> ((LeiosOutstanding peer
acc2, Seq LeiosFetchRequest
dec2, Map LeiosPoint OfferPrune
drops), WhetherPeerSaturated
PeerSaturated)

-- | Whether a request did not fit in what remains of its peer's cap, which ends
-- the peer's walk ('assignPeer')
data WhetherPeerSaturated = PeerSaturated | PeerNotSaturated

-- | Request the EB body from this peer, at the size the peer offered it at, if
-- that fits in the peer's remaining budget.
--
-- The offered size is the only size with any say here; an announcement's has
-- none, since at most one announcement naming a hash is honest and nothing
-- tells us which. So we ask whoever says they have it, for as many bytes as
-- they say. The offer was bounded by the ledger's maximum endorser block size
-- when it arrived, and what the bytes really are is settled on arrival by
-- hashing them: a peer that misrepresented either the block or its length
-- loses the connection then.
assignBody ::
  Ord peer =>
  -- | The ledger's bounds on an EB, forecast for a slot. See 'poEbBounds'.
  (SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)) ->
  -- | The peer's remaining budget ('peerBudget')
  Int ->
  peer ->
  LeiosPoint ->
  -- | The offer's own bounds, if any
  StrictMaybe (LeiosEbByteSizes SizeLimit) ->
  -- | The size the peer offered the body at
  BytesSize ->
  (LeiosOutstanding peer, Seq LeiosFetchRequest) ->
  AssignedBody peer
assignBody :: forall peer.
Ord peer =>
(SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Int
-> peer
-> LeiosPoint
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> Word32
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> AssignedBody peer
assignBody SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds Int
budget peer
peer LeiosPoint
point StrictMaybe (LeiosEbByteSizes 'SizeLimit)
offerBounds Word32
size (LeiosOutstanding peer
acc, Seq LeiosFetchRequest
dec)
  | peer
peer peer -> Set peer -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set peer -> LeiosPoint -> Map LeiosPoint (Set peer) -> Set peer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Set peer
forall a. Set a
Set.empty LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint (Set peer)
forall peer. LeiosOutstanding peer -> Map LeiosPoint (Set peer)
requestedEbPeers LeiosOutstanding peer
acc) =
      -- unless we've already requested it from them
      AssignedBody peer
forall peer. AssignedBody peer
BodyNotRequested
  | Bool
otherwise = case Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
eEbBounds of
      -- Beyond our horizon and the offer brought no bound of its own, so we
      -- have nothing to hold the body to. Ignoring it this iteration costs
      -- nothing: a later one forecasts again, from a tip that has moved.
      Left OutsideForecastRange
_outsideRange -> AssignedBody peer
forall peer. AssignedBody peer
BodyNotRequested
      Right LeiosEbByteSizes 'SizeLimit
bounds
        | Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
size Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
budget -> AssignedBody peer
forall peer. AssignedBody peer
BodyOverBudget
        | Bool
otherwise ->
            let acc' :: LeiosOutstanding peer
acc' =
                  LeiosOutstanding peer
acc
                    { requestedEbPeers =
                        Map.insertWith Set.union point (Set.singleton peer) (requestedEbPeers acc)
                    , requestedEbsPerPeer =
                        Map.insertWith NESet.union peer (NESet.singleton point) (requestedEbsPerPeer acc)
                    , requestedBytesSizePerPeer =
                        Map.insertWith (+) peer size (requestedBytesSizePerPeer acc)
                    }
             in LeiosOutstanding peer -> Seq LeiosFetchRequest -> AssignedBody peer
forall peer.
LeiosOutstanding peer -> Seq LeiosFetchRequest -> AssignedBody peer
BodyRequested
                  LeiosOutstanding peer
acc'
                  ( Seq LeiosFetchRequest
dec
                      Seq LeiosFetchRequest -> LeiosFetchRequest -> Seq LeiosFetchRequest
forall a. Seq a -> a -> Seq a
Seq.|> LeiosBlockRequest -> LeiosFetchRequest
LeiosBlockRequest
                        MkLeiosBlockRequest
                          { lbrPoint :: LeiosPoint
lbrPoint = LeiosPoint
point
                          , lbrOfferedSize :: Word32
lbrOfferedSize = Word32
size
                          , lbrEbBounds :: LeiosEbByteSizes 'SizeLimit
lbrEbBounds = LeiosEbByteSizes 'SizeLimit
bounds
                          }
                  )
 where
  -- The bounds a request made for this offer holds the endorser block to: the
  -- offer's own, else what we can forecast for the slot.
  eEbBounds :: Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
eEbBounds = case StrictMaybe (LeiosEbByteSizes 'SizeLimit)
offerBounds of
    SJust LeiosEbByteSizes 'SizeLimit
x -> LeiosEbByteSizes 'SizeLimit
-> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall a b. b -> Either a b
Right LeiosEbByteSizes 'SizeLimit
x
    StrictMaybe (LeiosEbByteSizes 'SizeLimit)
SNothing -> SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds (LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
point)

-- | What 'assignBody' did
data AssignedBody peer
  = -- | It requested the body: the new outstanding state, and the requests so
    -- far
    BodyRequested (LeiosOutstanding peer) (Seq LeiosFetchRequest)
  | -- | It did not request the body, and would not have with more budget
    BodyNotRequested
  | -- | It did not request the body, which does not fit in the peer's
    -- remaining budget
    BodyOverBudget

-- | Why 'pickJobs' stopped
data WhyPickingStopped
  = -- | Every job left is already in flight from this peer
    PeerEbExhausted
  | -- | The next job does not fit in the peer's remaining budget
    NextJobOverBudget

-- | Request tx-closure jobs from this peer, the least-requested ones we haven't
-- already requested from it, until the next does not fit in the peer's
-- remaining budget or there are none left. Also returns which.
assignClosure ::
  Ord peer =>
  LeiosFetchStaticEnv ->
  IsBigLedgerPeer ->
  peer ->
  LeiosPoint ->
  -- | The point's onset (see 'EbState')
  StrictMaybe RelativeTime ->
  -- | The point's job pool
  Jobs.LeiosJobPool ->
  (LeiosOutstanding peer, Seq LeiosFetchRequest) ->
  ((LeiosOutstanding peer, Seq LeiosFetchRequest), WhyPickingStopped)
assignClosure :: forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer
-> peer
-> LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosJobPool
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
    WhyPickingStopped)
assignClosure LeiosFetchStaticEnv
env IsBigLedgerPeer
isBig peer
peer LeiosPoint
point StrictMaybe RelativeTime
onset LeiosJobPool
jobPool st :: (LeiosOutstanding peer, Seq LeiosFetchRequest)
st@(LeiosOutstanding peer
acc, Seq LeiosFetchRequest
dec) =
  let inflightJobs :: IntSet
inflightJobs =
        IntSet -> (NEIntSet -> IntSet) -> Maybe NEIntSet -> IntSet
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IntSet
IntSet.empty NEIntSet -> IntSet
NEIntSet.toSet (Maybe NEIntSet -> IntSet) -> Maybe NEIntSet -> IntSet
forall a b. (a -> b) -> a -> b
$
          LeiosPoint -> Map LeiosPoint NEIntSet -> Maybe NEIntSet
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (Map LeiosPoint NEIntSet -> Maybe NEIntSet)
-> Maybe (Map LeiosPoint NEIntSet) -> Maybe NEIntSet
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< peer
-> Map peer (Map LeiosPoint NEIntSet)
-> Maybe (Map LeiosPoint NEIntSet)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup peer
peer (LeiosOutstanding peer -> Map peer (Map LeiosPoint NEIntSet)
forall peer.
LeiosOutstanding peer -> Map peer (Map LeiosPoint NEIntSet)
requestedJobsPerPeer LeiosOutstanding peer
acc)
      -- A big-ledger peer gets a larger budget ('peerBudget'), enough for
      -- multiple full EB closures at once, but still bounded.
      --
      -- There are no more than 184 jobs per EB, so picked can't be a /long/ list.
      --
      -- 'pickJobs' draws from the decision loop's own PRNG ('leiosFetchPrng');
      -- its advanced state is written back below (unchanged when nothing is
      -- picked, so the 'Nothing' branch's 'st' is correct as-is).
      ([(LeiosJobId, LeiosJob)]
picked, LeiosJobPool
jobPool', StdGen
prng', WhyPickingStopped
stopped) =
        StdGen
-> IntSet
-> LeiosJobPool
-> Int
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
pickJobs (LeiosOutstanding peer -> StdGen
forall peer. LeiosOutstanding peer -> StdGen
leiosFetchPrng LeiosOutstanding peer
acc) IntSet
inflightJobs LeiosJobPool
jobPool (LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
peerBudget LeiosFetchStaticEnv
env IsBigLedgerPeer
isBig LeiosOutstanding peer
acc peer
peer)
   in ((LeiosOutstanding peer, Seq LeiosFetchRequest)
 -> WhyPickingStopped
 -> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
     WhyPickingStopped))
-> WhyPickingStopped
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
    WhyPickingStopped)
forall a b c. (a -> b -> c) -> b -> a -> c
flip (,) WhyPickingStopped
stopped ((LeiosOutstanding peer, Seq LeiosFetchRequest)
 -> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
     WhyPickingStopped))
-> (LeiosOutstanding peer, Seq LeiosFetchRequest)
-> ((LeiosOutstanding peer, Seq LeiosFetchRequest),
    WhyPickingStopped)
forall a b. (a -> b) -> a -> b
$ case [(LeiosJobId, LeiosJob)] -> Maybe (NonEmpty (LeiosJobId, LeiosJob))
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty [(LeiosJobId, LeiosJob)]
picked of
        Maybe (NonEmpty (LeiosJobId, LeiosJob))
Nothing -> (LeiosOutstanding peer, Seq LeiosFetchRequest)
st
        Just NonEmpty (LeiosJobId, LeiosJob)
nePicked ->
          let acc' :: LeiosOutstanding peer
acc' =
                LeiosOutstanding peer
acc
                  { ebState =
                      Map.insert
                        point
                        (MkEbState onset (BodyAcquired jobPool'))
                        (ebState acc)
                  , requestedJobsPerPeer =
                      Map.insertWith
                        (Map.unionWith NEIntSet.union)
                        peer
                        ( Map.singleton point $
                            NEIntSet.fromList $
                              fmap (\(Jobs.MkLeiosJobId Int
i, LeiosJob
_) -> Int
i) nePicked
                        )
                        (requestedJobsPerPeer acc)
                  , requestedBytesSizePerPeer =
                      Map.insertWith
                        (+)
                        peer
                        (sum $ fmap (\(LeiosJobId
_, Jobs.MkLeiosJob IntSet
_ Word32
bytes JobCommitment
_) -> Word32
bytes) nePicked)
                        (requestedBytesSizePerPeer acc)
                  , leiosFetchPrng = prng'
                  }
              reqs :: [LeiosFetchRequest]
reqs = LeiosFetchStaticEnv
-> LeiosPoint
-> NonEmpty (LeiosJobId, LeiosJob)
-> [LeiosFetchRequest]
batchTxsRequests LeiosFetchStaticEnv
env LeiosPoint
point NonEmpty (LeiosJobId, LeiosJob)
nePicked
           in (LeiosOutstanding peer
acc', Seq LeiosFetchRequest
dec Seq LeiosFetchRequest
-> Seq LeiosFetchRequest -> Seq LeiosFetchRequest
forall a. Semigroup a => a -> a -> a
<> [LeiosFetchRequest] -> Seq LeiosFetchRequest
forall a. [a] -> Seq a
Seq.fromList [LeiosFetchRequest]
reqs)

-- | Take least-requested-available jobs until the next one drawn does not fit
-- in the budget, or there are no more jobs that aren't already assigned to
-- this peer. Also returns which. Each pick carries the whole 'Jobs.LeiosJob'
-- (id + commitment) so the request can validate its own response. The supplied
-- PRNG shuffles which job is drawn within the least-requested bucket; its
-- advanced state is returned so the caller can persist it.
pickJobs ::
  StdGen ->
  IntSet.IntSet ->
  Jobs.LeiosJobPool ->
  Int ->
  ([(Jobs.LeiosJobId, Jobs.LeiosJob)], Jobs.LeiosJobPool, StdGen, WhyPickingStopped)
pickJobs :: StdGen
-> IntSet
-> LeiosJobPool
-> Int
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
pickJobs StdGen
prng0 IntSet
inflightJobs0 LeiosJobPool
jobPool0 Int
budget0 =
  StdGen
-> IntSet
-> LeiosJobPool
-> Int
-> [(LeiosJobId, LeiosJob)]
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
forall {t}.
(Ord t, Num t) =>
StdGen
-> IntSet
-> LeiosJobPool
-> t
-> [(LeiosJobId, LeiosJob)]
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
go StdGen
prng0 IntSet
inflightJobs0 LeiosJobPool
jobPool0 Int
budget0 []
 where
  go :: StdGen
-> IntSet
-> LeiosJobPool
-> t
-> [(LeiosJobId, LeiosJob)]
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
go StdGen
prng IntSet
inflightJobs LeiosJobPool
jobPool t
budget [(LeiosJobId, LeiosJob)]
acc =
    case StdGen
-> IntSet
-> LeiosJobPool
-> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Jobs.pickLeastRequestedJobExcept StdGen
prng IntSet
inflightJobs LeiosJobPool
jobPool of
      Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Nothing -> ([(LeiosJobId, LeiosJob)] -> [(LeiosJobId, LeiosJob)]
forall a. [a] -> [a]
reverse [(LeiosJobId, LeiosJob)]
acc, LeiosJobPool
jobPool, StdGen
prng, WhyPickingStopped
PeerEbExhausted)
      Just (jid :: LeiosJobId
jid@(Jobs.MkLeiosJobId Int
i), job :: LeiosJob
job@(Jobs.MkLeiosJob IntSet
_offsets Word32
bytes JobCommitment
_commitment), LeiosJobPool
jobPool', StdGen
prng')
        | Word32 -> t
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
bytes t -> t -> Bool
forall a. Ord a => a -> a -> Bool
> t
budget ->
            -- Undo the draw, since the job is not requested.
            ([(LeiosJobId, LeiosJob)] -> [(LeiosJobId, LeiosJob)]
forall a. [a] -> [a]
reverse [(LeiosJobId, LeiosJob)]
acc, LeiosJobPool
jobPool, StdGen
prng, WhyPickingStopped
NextJobOverBudget)
        | Bool
otherwise ->
            StdGen
-> IntSet
-> LeiosJobPool
-> t
-> [(LeiosJobId, LeiosJob)]
-> ([(LeiosJobId, LeiosJob)], LeiosJobPool, StdGen,
    WhyPickingStopped)
go
              StdGen
prng'
              (Int -> IntSet -> IntSet
IntSet.insert Int
i IntSet
inflightJobs)
              LeiosJobPool
jobPool'
              (t
budget t -> t -> t
forall a. Num a => a -> a -> a
- Word32 -> t
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
bytes)
              ((LeiosJobId
jid, LeiosJob
job) (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> [(LeiosJobId, LeiosJob)]
forall a. a -> [a] -> [a]
: [(LeiosJobId, LeiosJob)]
acc)

-- | Partition the picked jobs into requests, each within 'maxRequestBytesSize'
-- (a lone job above the cap simply forms its own request). Each request carries
-- the jobs it covers with their commitments; the wire bitmap is derived from the
-- union of their offsets at send time. Order within a request is irrelevant
-- (union offsets, set of ids, independent per-job validation).
batchTxsRequests ::
  LeiosFetchStaticEnv ->
  LeiosPoint ->
  NonEmpty (Jobs.LeiosJobId, Jobs.LeiosJob) ->
  [LeiosFetchRequest]
batchTxsRequests :: LeiosFetchStaticEnv
-> LeiosPoint
-> NonEmpty (LeiosJobId, LeiosJob)
-> [LeiosFetchRequest]
batchTxsRequests LeiosFetchStaticEnv
env LeiosPoint
point ((LeiosJobId, LeiosJob)
j0 :| [(LeiosJobId, LeiosJob)]
rest0) =
  (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)]
-> Int
-> [(LeiosJobId, LeiosJob)]
-> [LeiosFetchRequest]
go (LeiosJobId, LeiosJob)
j0 [] ((LeiosJobId, LeiosJob) -> Int
forall {a}. (a, LeiosJob) -> Int
jobBytes (LeiosJobId, LeiosJob)
j0) [(LeiosJobId, LeiosJob)]
rest0
 where
  cap :: Int
cap = Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (LeiosFetchStaticEnv -> Word32
maxRequestBytesSize LeiosFetchStaticEnv
env) :: Int
  jobBytes :: (a, LeiosJob) -> Int
jobBytes (a
_jid, Jobs.MkLeiosJob IntSet
_offs Word32
bytes JobCommitment
_commitment) = Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
bytes :: Int
  -- 'accRev' are the batch's jobs after its seed; a batch is always non-empty.
  -- 'NEIntMap.fromList' keys by the raw job id; the picks are distinct ids, so no
  -- merge.
  flush :: (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> LeiosFetchRequest
flush (LeiosJobId, LeiosJob)
seed [(LeiosJobId, LeiosJob)]
accRev =
    LeiosBlockTxsRequest -> LeiosFetchRequest
LeiosBlockTxsRequest (LeiosBlockTxsRequest -> LeiosFetchRequest)
-> LeiosBlockTxsRequest -> LeiosFetchRequest
forall a b. (a -> b) -> a -> b
$
      LeiosPoint -> NEIntMap LeiosJob -> LeiosBlockTxsRequest
MkLeiosBlockTxsRequest
        LeiosPoint
point
        (NonEmpty (Int, LeiosJob) -> NEIntMap LeiosJob
forall a. NonEmpty (Int, a) -> NEIntMap a
NEIntMap.fromList (((LeiosJobId, LeiosJob) -> (Int, LeiosJob))
-> NonEmpty (LeiosJobId, LeiosJob) -> NonEmpty (Int, LeiosJob)
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(Jobs.MkLeiosJobId Int
i, LeiosJob
job) -> (Int
i, LeiosJob
job)) ((LeiosJobId, LeiosJob)
seed (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> NonEmpty (LeiosJobId, LeiosJob)
forall a. a -> [a] -> NonEmpty a
:| [(LeiosJobId, LeiosJob)] -> [(LeiosJobId, LeiosJob)]
forall a. [a] -> [a]
reverse [(LeiosJobId, LeiosJob)]
accRev)))
  go :: (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)]
-> Int
-> [(LeiosJobId, LeiosJob)]
-> [LeiosFetchRequest]
go (LeiosJobId, LeiosJob)
seed [(LeiosJobId, LeiosJob)]
accRev Int
_curBytes [] = [(LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> LeiosFetchRequest
flush (LeiosJobId, LeiosJob)
seed [(LeiosJobId, LeiosJob)]
accRev]
  go (LeiosJobId, LeiosJob)
seed [(LeiosJobId, LeiosJob)]
accRev Int
curBytes ((LeiosJobId, LeiosJob)
j : [(LeiosJobId, LeiosJob)]
rest)
    | Int
curBytes Int -> Int -> Int
forall a. Num a => a -> a -> a
+ (LeiosJobId, LeiosJob) -> Int
forall {a}. (a, LeiosJob) -> Int
jobBytes (LeiosJobId, LeiosJob)
j Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
cap = (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> LeiosFetchRequest
flush (LeiosJobId, LeiosJob)
seed [(LeiosJobId, LeiosJob)]
accRev LeiosFetchRequest -> [LeiosFetchRequest] -> [LeiosFetchRequest]
forall a. a -> [a] -> [a]
: (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)]
-> Int
-> [(LeiosJobId, LeiosJob)]
-> [LeiosFetchRequest]
go (LeiosJobId, LeiosJob)
j [] ((LeiosJobId, LeiosJob) -> Int
forall {a}. (a, LeiosJob) -> Int
jobBytes (LeiosJobId, LeiosJob)
j) [(LeiosJobId, LeiosJob)]
rest
    | Bool
otherwise = (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)]
-> Int
-> [(LeiosJobId, LeiosJob)]
-> [LeiosFetchRequest]
go (LeiosJobId, LeiosJob)
seed ((LeiosJobId, LeiosJob)
j (LeiosJobId, LeiosJob)
-> [(LeiosJobId, LeiosJob)] -> [(LeiosJobId, LeiosJob)]
forall a. a -> [a] -> [a]
: [(LeiosJobId, LeiosJob)]
accRev) (Int
curBytes Int -> Int -> Int
forall a. Num a => a -> a -> a
+ (LeiosJobId, LeiosJob) -> Int
forall {a}. (a, LeiosJob) -> Int
jobBytes (LeiosJobId, LeiosJob)
j) [(LeiosJobId, LeiosJob)]
rest