{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeApplications #-}

-- | The unit of Leios tx-fetch work: 'LeiosJob's and the per-EB 'LeiosJobPool'
-- that schedules them.
--
-- The pool's structural operations -- greedy partition, least-requested
-- selection, multiplicity bookkeeping -- stay together here, along with the
-- 'JobCommitment' a job carries.
--
-- The key benefit of jobs is to minimize the bookkeeping footprint and churn.
--
-- TO BE IMPORTED QUALIFIED
module Ouroboros.Consensus.MiniProtocol.LeiosFetch.Jobs
  ( -- * Jobs
    LeiosJob (..)
  , LeiosJobId (..)
  , JobCommitment (..)
  , jobCommitmentOfTxs

    -- * Pools
  , LeiosJobPool
  , mkJobPool
  , emptyJobPool
  , nullJobPool
  , lookupJob
  , restrictToPending
  , pickLeastRequestedJobExcept
  , unpickJob
  , completeJob

    -- * Inspecting pools
  , jobMultiplicities
  , hasExactReverseIndex
  ) where

import qualified Cardano.Crypto.Hash as Hash
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BSB
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.IntSet.NonEmpty (NEIntSet)
import qualified Data.IntSet.NonEmpty as NEIntSet
import Data.Word (Word32)
import Ouroboros.Consensus.Leios.Types (TxHash)
import System.Random (StdGen, uniformR)

-- | A job's commitment to which txs it covers, at which sizes: the Blake2b-256
-- hash of each tx's hash followed by its size in four big-endian bytes (in
-- ascending offset order), via 'jobCommitmentOfTxs'. It lets an arriving
-- @MsgLeiosBlockTxs@ be validated against the job /without/ retaining the EB
-- body -- crucial, since up to ~10k EBs (each up to ~600 kB) could have txs in
-- flight at once, far too much to hold in memory.
--
-- A tx that is not the size the body declares for it fails the validation,
-- even if it is the tx the body names. So the validation cannot tell a peer
-- that sends the wrong tx from an endorser block that declares the wrong size
-- for the right one: the node never notices such an endorser block, and only
-- disconnects each peer that serves it. Separate commitments to the hashes and
-- to the sizes would tell the two apart, but they would double the
-- commitments' footprint in the heap, which is already non-trivial, and they
-- would only guard against a suboptimal adversary, which could send a tx with
-- the wrong txhash instead of with the wrong size and have wasted the same
-- resources.
newtype JobCommitment = MkJobCommitment ByteString
  deriving (JobCommitment -> JobCommitment -> Bool
(JobCommitment -> JobCommitment -> Bool)
-> (JobCommitment -> JobCommitment -> Bool) -> Eq JobCommitment
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: JobCommitment -> JobCommitment -> Bool
== :: JobCommitment -> JobCommitment -> Bool
$c/= :: JobCommitment -> JobCommitment -> Bool
/= :: JobCommitment -> JobCommitment -> Bool
Eq, Int -> JobCommitment -> ShowS
[JobCommitment] -> ShowS
JobCommitment -> String
(Int -> JobCommitment -> ShowS)
-> (JobCommitment -> String)
-> ([JobCommitment] -> ShowS)
-> Show JobCommitment
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> JobCommitment -> ShowS
showsPrec :: Int -> JobCommitment -> ShowS
$cshow :: JobCommitment -> String
show :: JobCommitment -> String
$cshowList :: [JobCommitment] -> ShowS
showList :: [JobCommitment] -> ShowS
Show)

jobCommitmentOfTxs :: [(TxHash, Word32)] -> JobCommitment
jobCommitmentOfTxs :: [(TxHash, Word32)] -> JobCommitment
jobCommitmentOfTxs =
  ByteString -> JobCommitment
MkJobCommitment
    (ByteString -> JobCommitment)
-> ([(TxHash, Word32)] -> ByteString)
-> [(TxHash, Word32)]
-> JobCommitment
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Hash Blake2b_256 ByteString -> ByteString
forall h a. Hash h a -> ByteString
Hash.hashToBytes
    (Hash Blake2b_256 ByteString -> ByteString)
-> ([(TxHash, Word32)] -> Hash Blake2b_256 ByteString)
-> [(TxHash, Word32)]
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall h a. HashAlgorithm h => (a -> ByteString) -> a -> Hash h a
Hash.hashWith @Hash.Blake2b_256 ByteString -> ByteString
forall a. a -> a
id
    (ByteString -> Hash Blake2b_256 ByteString)
-> ([(TxHash, Word32)] -> ByteString)
-> [(TxHash, Word32)]
-> Hash Blake2b_256 ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LazyByteString -> ByteString
BS.toStrict
    (LazyByteString -> ByteString)
-> ([(TxHash, Word32)] -> LazyByteString)
-> [(TxHash, Word32)]
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Builder -> LazyByteString
BSB.toLazyByteString
    (Builder -> LazyByteString)
-> ([(TxHash, Word32)] -> Builder)
-> [(TxHash, Word32)]
-> LazyByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((TxHash, Word32) -> Builder) -> [(TxHash, Word32)] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(TxHash
txHash, Word32
size) -> ByteString -> Builder
BSB.byteString (TxHash -> ByteString
forall h a. Hash h a -> ByteString
Hash.hashToBytes TxHash
txHash) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word32 -> Builder
BSB.word32BE Word32
size)

-- | A unit of tx-fetch work: some of an EB's txs, fetched by one
-- @MsgLeiosBlockTxsRequest@.
data LeiosJob
  = MkLeiosJob
      -- | The txs' offsets in the EB body's tx vector
      --
      -- TODO the offset set is immutable and only ever fully traversed, so a
      -- packed bitfield (a strict ByteString or unboxed Word64 vector) would be
      -- more compact than the 'IntSet' Patricia tree.
      !IntSet
      -- | The txs' total on-the-wire byte size, for the fetch byte budget
      !Word32
      -- | What the response is validated against
      !JobCommitment
  deriving (LeiosJob -> LeiosJob -> Bool
(LeiosJob -> LeiosJob -> Bool)
-> (LeiosJob -> LeiosJob -> Bool) -> Eq LeiosJob
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LeiosJob -> LeiosJob -> Bool
== :: LeiosJob -> LeiosJob -> Bool
$c/= :: LeiosJob -> LeiosJob -> Bool
/= :: LeiosJob -> LeiosJob -> Bool
Eq, Int -> LeiosJob -> ShowS
[LeiosJob] -> ShowS
LeiosJob -> String
(Int -> LeiosJob -> ShowS)
-> (LeiosJob -> String) -> ([LeiosJob] -> ShowS) -> Show LeiosJob
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LeiosJob -> ShowS
showsPrec :: Int -> LeiosJob -> ShowS
$cshow :: LeiosJob -> String
show :: LeiosJob -> String
$cshowList :: [LeiosJob] -> ShowS
showList :: [LeiosJob] -> ShowS
Show)

-- | Identifies a 'LeiosJob' within its 'LeiosJobPool' (0-based, stable for the
-- pool's lifetime). A point's pool is built once, so a reply for a point names
-- only that pool's jobs.
newtype LeiosJobId = MkLeiosJobId Int
  deriving (LeiosJobId -> LeiosJobId -> Bool
(LeiosJobId -> LeiosJobId -> Bool)
-> (LeiosJobId -> LeiosJobId -> Bool) -> Eq LeiosJobId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LeiosJobId -> LeiosJobId -> Bool
== :: LeiosJobId -> LeiosJobId -> Bool
$c/= :: LeiosJobId -> LeiosJobId -> Bool
/= :: LeiosJobId -> LeiosJobId -> Bool
Eq, Eq LeiosJobId
Eq LeiosJobId =>
(LeiosJobId -> LeiosJobId -> Ordering)
-> (LeiosJobId -> LeiosJobId -> Bool)
-> (LeiosJobId -> LeiosJobId -> Bool)
-> (LeiosJobId -> LeiosJobId -> Bool)
-> (LeiosJobId -> LeiosJobId -> Bool)
-> (LeiosJobId -> LeiosJobId -> LeiosJobId)
-> (LeiosJobId -> LeiosJobId -> LeiosJobId)
-> Ord LeiosJobId
LeiosJobId -> LeiosJobId -> Bool
LeiosJobId -> LeiosJobId -> Ordering
LeiosJobId -> LeiosJobId -> LeiosJobId
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: LeiosJobId -> LeiosJobId -> Ordering
compare :: LeiosJobId -> LeiosJobId -> Ordering
$c< :: LeiosJobId -> LeiosJobId -> Bool
< :: LeiosJobId -> LeiosJobId -> Bool
$c<= :: LeiosJobId -> LeiosJobId -> Bool
<= :: LeiosJobId -> LeiosJobId -> Bool
$c> :: LeiosJobId -> LeiosJobId -> Bool
> :: LeiosJobId -> LeiosJobId -> Bool
$c>= :: LeiosJobId -> LeiosJobId -> Bool
>= :: LeiosJobId -> LeiosJobId -> Bool
$cmax :: LeiosJobId -> LeiosJobId -> LeiosJobId
max :: LeiosJobId -> LeiosJobId -> LeiosJobId
$cmin :: LeiosJobId -> LeiosJobId -> LeiosJobId
min :: LeiosJobId -> LeiosJobId -> LeiosJobId
Ord, Int -> LeiosJobId -> ShowS
[LeiosJobId] -> ShowS
LeiosJobId -> String
(Int -> LeiosJobId -> ShowS)
-> (LeiosJobId -> String)
-> ([LeiosJobId] -> ShowS)
-> Show LeiosJobId
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LeiosJobId -> ShowS
showsPrec :: Int -> LeiosJobId -> ShowS
$cshow :: LeiosJobId -> String
show :: LeiosJobId -> String
$cshowList :: [LeiosJobId] -> ShowS
showList :: [LeiosJobId] -> ShowS
Show)

-- | How many peers currently have an in-flight request for a job.
newtype LeiosJobMultiplicity = MkLeiosJobMultiplicity Int
  deriving (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
(LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> Eq LeiosJobMultiplicity
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
== :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
$c/= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
/= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
Eq, Eq LeiosJobMultiplicity
Eq LeiosJobMultiplicity =>
(LeiosJobMultiplicity -> LeiosJobMultiplicity -> Ordering)
-> (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> (LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool)
-> (LeiosJobMultiplicity
    -> LeiosJobMultiplicity -> LeiosJobMultiplicity)
-> (LeiosJobMultiplicity
    -> LeiosJobMultiplicity -> LeiosJobMultiplicity)
-> Ord LeiosJobMultiplicity
LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
LeiosJobMultiplicity -> LeiosJobMultiplicity -> Ordering
LeiosJobMultiplicity
-> LeiosJobMultiplicity -> LeiosJobMultiplicity
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Ordering
compare :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Ordering
$c< :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
< :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
$c<= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
<= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
$c> :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
> :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
$c>= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
>= :: LeiosJobMultiplicity -> LeiosJobMultiplicity -> Bool
$cmax :: LeiosJobMultiplicity
-> LeiosJobMultiplicity -> LeiosJobMultiplicity
max :: LeiosJobMultiplicity
-> LeiosJobMultiplicity -> LeiosJobMultiplicity
$cmin :: LeiosJobMultiplicity
-> LeiosJobMultiplicity -> LeiosJobMultiplicity
min :: LeiosJobMultiplicity
-> LeiosJobMultiplicity -> LeiosJobMultiplicity
Ord, Int -> LeiosJobMultiplicity -> ShowS
[LeiosJobMultiplicity] -> ShowS
LeiosJobMultiplicity -> String
(Int -> LeiosJobMultiplicity -> ShowS)
-> (LeiosJobMultiplicity -> String)
-> ([LeiosJobMultiplicity] -> ShowS)
-> Show LeiosJobMultiplicity
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LeiosJobMultiplicity -> ShowS
showsPrec :: Int -> LeiosJobMultiplicity -> ShowS
$cshow :: LeiosJobMultiplicity -> String
show :: LeiosJobMultiplicity -> String
$cshowList :: [LeiosJobMultiplicity] -> ShowS
showList :: [LeiosJobMultiplicity] -> ShowS
Show)

-- | A job together with its current in-flight multiplicity.
data LeiosJobState = MkLeiosJobState !LeiosJob !LeiosJobMultiplicity
  deriving (LeiosJobState -> LeiosJobState -> Bool
(LeiosJobState -> LeiosJobState -> Bool)
-> (LeiosJobState -> LeiosJobState -> Bool) -> Eq LeiosJobState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LeiosJobState -> LeiosJobState -> Bool
== :: LeiosJobState -> LeiosJobState -> Bool
$c/= :: LeiosJobState -> LeiosJobState -> Bool
/= :: LeiosJobState -> LeiosJobState -> Bool
Eq, Int -> LeiosJobState -> ShowS
[LeiosJobState] -> ShowS
LeiosJobState -> String
(Int -> LeiosJobState -> ShowS)
-> (LeiosJobState -> String)
-> ([LeiosJobState] -> ShowS)
-> Show LeiosJobState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LeiosJobState -> ShowS
showsPrec :: Int -> LeiosJobState -> ShowS
$cshow :: LeiosJobState -> String
show :: LeiosJobState -> String
$cshowList :: [LeiosJobState] -> ShowS
showList :: [LeiosJobState] -> ShowS
Show)

-- | The unfinished jobs for one acquired EB, requested or not, plus a reverse
-- index by multiplicity so a least-requested job is one 'IntMap.minView' away.
--
-- INVARIANT: 'jobsByMultiplicity' is the exact inverse of the multiplicities in
-- 'jobs' -- every job id in 'jobs' sits in exactly the bucket named by its
-- 'LeiosJobState' multiplicity.
data LeiosJobPool = UnsafeLeiosJobPool
  { LeiosJobPool -> IntMap LeiosJobState
jobs :: !(IntMap LeiosJobState)
  -- ^ keyed by 'LeiosJobId'
  , LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity :: !(IntMap NEIntSet)
  -- ^ keyed by 'LeiosJobMultiplicity'
  }
  deriving (LeiosJobPool -> LeiosJobPool -> Bool
(LeiosJobPool -> LeiosJobPool -> Bool)
-> (LeiosJobPool -> LeiosJobPool -> Bool) -> Eq LeiosJobPool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LeiosJobPool -> LeiosJobPool -> Bool
== :: LeiosJobPool -> LeiosJobPool -> Bool
$c/= :: LeiosJobPool -> LeiosJobPool -> Bool
/= :: LeiosJobPool -> LeiosJobPool -> Bool
Eq, Int -> LeiosJobPool -> ShowS
[LeiosJobPool] -> ShowS
LeiosJobPool -> String
(Int -> LeiosJobPool -> ShowS)
-> (LeiosJobPool -> String)
-> ([LeiosJobPool] -> ShowS)
-> Show LeiosJobPool
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LeiosJobPool -> ShowS
showsPrec :: Int -> LeiosJobPool -> ShowS
$cshow :: LeiosJobPool -> String
show :: LeiosJobPool -> String
$cshowList :: [LeiosJobPool] -> ShowS
showList :: [LeiosJobPool] -> ShowS
Show)

-- | Partition the missing txs into jobs, greedily in offset order: a job grows
-- until adding the next tx would exceed @maxJobBytes@ or @maxJobTxCount@, but
-- always holds at least one tx (so an oversized tx would form a solo job, in
-- the unintended case of max tx size exceeding max job size).
--
-- Each miss is its offset within the EB body mapped to its tx hash and its
-- on-the-wire byte size. Each job's 'JobCommitment' is computed here via
-- 'jobCommitmentOfTxs' over its covered txs' hashes and sizes.
--
-- The jobs are numbered from 0.
mkJobPool :: Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
mkJobPool :: Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
mkJobPool Word32
maxJobBytes Int
maxJobTxCount IntMap (TxHash, Word32)
misses =
  UnsafeLeiosJobPool
    { jobs :: IntMap LeiosJobState
jobs =
        [(Int, LeiosJobState)] -> IntMap LeiosJobState
forall a. [(Int, a)] -> IntMap a
IntMap.fromList
          [ (Int
jid, LeiosJob -> LeiosJobMultiplicity -> LeiosJobState
MkLeiosJobState LeiosJob
job (Int -> LeiosJobMultiplicity
MkLeiosJobMultiplicity Int
0))
          | (Int
jid, LeiosJob
job) <- [(Int, LeiosJob)]
ijbs
          ]
    , jobsByMultiplicity :: IntMap NEIntSet
jobsByMultiplicity =
        IntMap NEIntSet
-> (NEIntSet -> IntMap NEIntSet)
-> Maybe NEIntSet
-> IntMap NEIntSet
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IntMap NEIntSet
forall a. IntMap a
IntMap.empty (Int -> NEIntSet -> IntMap NEIntSet
forall a. Int -> a -> IntMap a
IntMap.singleton Int
0) (Maybe NEIntSet -> IntMap NEIntSet)
-> Maybe NEIntSet -> IntMap NEIntSet
forall a b. (a -> b) -> a -> b
$
          IntSet -> Maybe NEIntSet
NEIntSet.nonEmptySet ([Int] -> IntSet
IntSet.fromList (((Int, LeiosJob) -> Int) -> [(Int, LeiosJob)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, LeiosJob) -> Int
forall a b. (a, b) -> a
fst [(Int, LeiosJob)]
ijbs))
    }
 where
  ijbs :: [(Int, LeiosJob)]
ijbs = [Int] -> [LeiosJob] -> [(Int, LeiosJob)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] ([LeiosJob] -> [(Int, LeiosJob)])
-> [LeiosJob] -> [(Int, LeiosJob)]
forall a b. (a -> b) -> a -> b
$ case IntMap (TxHash, Word32) -> [(Int, (TxHash, Word32))]
forall a. IntMap a -> [(Int, a)]
IntMap.toAscList IntMap (TxHash, Word32)
misses of
    [] -> []
    ((Int
off0, ref0 :: (TxHash, Word32)
ref0@(TxHash
_h0, Word32
sz0)) : [(Int, (TxHash, Word32))]
rest) -> IntSet
-> Word32
-> Int
-> [(TxHash, Word32)]
-> [(Int, (TxHash, Word32))]
-> [LeiosJob]
grow (Int -> IntSet
IntSet.singleton Int
off0) Word32
sz0 Int
1 [(TxHash, Word32)
ref0] [(Int, (TxHash, Word32))]
rest

  flush :: IntSet -> Word32 -> [(TxHash, Word32)] -> LeiosJob
flush !IntSet
cur !Word32
bytes [(TxHash, Word32)]
refsRev = IntSet -> Word32 -> JobCommitment -> LeiosJob
MkLeiosJob IntSet
cur Word32
bytes ([(TxHash, Word32)] -> JobCommitment
jobCommitmentOfTxs ([(TxHash, Word32)] -> [(TxHash, Word32)]
forall a. [a] -> [a]
reverse [(TxHash, Word32)]
refsRev))

  grow :: IntSet
-> Word32
-> Int
-> [(TxHash, Word32)]
-> [(Int, (TxHash, Word32))]
-> [LeiosJob]
grow !IntSet
cur !Word32
bytes !Int
_count [(TxHash, Word32)]
refsRev [] = [IntSet -> Word32 -> [(TxHash, Word32)] -> LeiosJob
flush IntSet
cur Word32
bytes [(TxHash, Word32)]
refsRev]
  grow !IntSet
cur !Word32
bytes !Int
count [(TxHash, Word32)]
refsRev ((Int
off, ref :: (TxHash, Word32)
ref@(TxHash
_h, Word32
sz)) : [(Int, (TxHash, Word32))]
rest)
    | Int
count Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
maxJobTxCount Bool -> Bool -> Bool
&& Word32
bytes Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
sz Word32 -> Word32 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word32
maxJobBytes =
        IntSet
-> Word32
-> Int
-> [(TxHash, Word32)]
-> [(Int, (TxHash, Word32))]
-> [LeiosJob]
grow (Int -> IntSet -> IntSet
IntSet.insert Int
off IntSet
cur) (Word32
bytes Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
sz) (Int
count Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) ((TxHash, Word32)
ref (TxHash, Word32) -> [(TxHash, Word32)] -> [(TxHash, Word32)]
forall a. a -> [a] -> [a]
: [(TxHash, Word32)]
refsRev) [(Int, (TxHash, Word32))]
rest
    | Bool
otherwise = IntSet -> Word32 -> [(TxHash, Word32)] -> LeiosJob
flush IntSet
cur Word32
bytes [(TxHash, Word32)]
refsRev LeiosJob -> [LeiosJob] -> [LeiosJob]
forall a. a -> [a] -> [a]
: IntSet
-> Word32
-> Int
-> [(TxHash, Word32)]
-> [(Int, (TxHash, Word32))]
-> [LeiosJob]
grow (Int -> IntSet
IntSet.singleton Int
off) Word32
sz Int
1 [(TxHash, Word32)
ref] [(Int, (TxHash, Word32))]
rest

-- | No unfinished jobs remain -- the EB's whole tx-closure has been fetched.
nullJobPool :: LeiosJobPool -> Bool
nullJobPool :: LeiosJobPool -> Bool
nullJobPool = IntMap LeiosJobState -> Bool
forall a. IntMap a -> Bool
IntMap.null (IntMap LeiosJobState -> Bool)
-> (LeiosJobPool -> IntMap LeiosJobState) -> LeiosJobPool -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosJobPool -> IntMap LeiosJobState
jobs

-- | The bitfield of an unfinished job, if it is still in the pool.
lookupJob :: LeiosJobId -> LeiosJobPool -> Maybe LeiosJob
lookupJob :: LeiosJobId -> LeiosJobPool -> Maybe LeiosJob
lookupJob (MkLeiosJobId Int
jid) LeiosJobPool
pool =
  (\(MkLeiosJobState LeiosJob
job LeiosJobMultiplicity
_multiplicity) -> LeiosJob
job) (LeiosJobState -> LeiosJob)
-> Maybe LeiosJobState -> Maybe LeiosJob
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> IntMap LeiosJobState -> Maybe LeiosJobState
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
jid (LeiosJobPool -> IntMap LeiosJobState
jobs LeiosJobPool
pool)

-- | Restrict a map keyed by 'LeiosJobId' to the jobs still unfinished in the
-- pool, dropping entries for jobs already 'completeJob'd. Lets the tx-arrival
-- handler pick out, from a request's covered jobs, the ones we still need to
-- ingest (a redundant delivery of a completed job is dropped).
restrictToPending :: IntMap a -> LeiosJobPool -> IntMap a
restrictToPending :: forall a. IntMap a -> LeiosJobPool -> IntMap a
restrictToPending IntMap a
m LeiosJobPool
pool = IntMap a
m IntMap a -> IntMap LeiosJobState -> IntMap a
forall a b. IntMap a -> IntMap b -> IntMap a
`IntMap.intersection` LeiosJobPool -> IntMap LeiosJobState
jobs LeiosJobPool
pool

-- | The pool with no jobs -- nothing left to fetch.
emptyJobPool :: LeiosJobPool
emptyJobPool :: LeiosJobPool
emptyJobPool = IntMap LeiosJobState -> IntMap NEIntSet -> LeiosJobPool
UnsafeLeiosJobPool IntMap LeiosJobState
forall a. IntMap a
IntMap.empty IntMap NEIntSet
forall a. IntMap a
IntMap.empty

-- | Select a least-requested unfinished job (fewest in-flight requests; ties
-- broken uniformly at random via the supplied PRNG) whose id is /not/ in
-- @excluded@, record one more in-flight request for it, and return its id, its
-- bitfield, the updated pool, and the advanced PRNG. 'Nothing' if every
-- unfinished job is excluded (or the pool is empty), in which case the caller
-- keeps its own PRNG (nothing was drawn).
--
-- The caller passes the job ids this peer already has in flight for the EB, so a
-- peer is never asked for the same job twice.
pickLeastRequestedJobExcept ::
  StdGen -> IntSet -> LeiosJobPool -> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
pickLeastRequestedJobExcept :: StdGen
-> IntSet
-> LeiosJobPool
-> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
pickLeastRequestedJobExcept StdGen
prng IntSet
excluded LeiosJobPool
pool =
  case Maybe (Int, IntSet)
eligibleBucket of
    Maybe (Int, IntSet)
Nothing -> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
forall a. Maybe a
Nothing
    Just (Int
m, IntSet
diff) ->
      -- Draw a uniform index into the eligible bucket's non-excluded jobs.
      -- 'Data.IntSet' has no indexed access, but a bucket holds at most the ~184
      -- jobs of one EB, so indexing the ascending list is cheap.
      let (Int
i, StdGen
prng') = (Int, Int) -> StdGen -> (Int, StdGen)
forall a g. (UniformRange a, RandomGen g) => (a, a) -> g -> (a, g)
uniformR (Int
0, IntSet -> Int
IntSet.size IntSet
diff Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) StdGen
prng
          jid :: Int
jid = IntSet -> [Int]
IntSet.toAscList IntSet
diff [Int] -> Int -> Int
forall a. HasCallStack => [a] -> Int -> a
!! Int
i
       in case (Maybe LeiosJobState -> (Maybe LeiosJob, Maybe LeiosJobState))
-> Int
-> IntMap LeiosJobState
-> (Maybe LeiosJob, IntMap LeiosJobState)
forall (f :: * -> *) a.
Functor f =>
(Maybe a -> f (Maybe a)) -> Int -> IntMap a -> f (IntMap a)
IntMap.alterF (Int -> Maybe LeiosJobState -> (Maybe LeiosJob, Maybe LeiosJobState)
bump1 Int
m) Int
jid (LeiosJobPool -> IntMap LeiosJobState
jobs LeiosJobPool
pool) of
            (Maybe LeiosJob
Nothing, IntMap LeiosJobState
_) -> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
forall a. Maybe a
Nothing
            (Just LeiosJob
job, IntMap LeiosJobState
jobs') ->
              (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
-> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
forall a. a -> Maybe a
Just
                ( Int -> LeiosJobId
MkLeiosJobId Int
jid
                , LeiosJob
job
                , UnsafeLeiosJobPool
                    { jobs :: IntMap LeiosJobState
jobs = IntMap LeiosJobState
jobs'
                    , jobsByMultiplicity :: IntMap NEIntSet
jobsByMultiplicity =
                        Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketInsert (Int
m Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
jid (Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketDelete Int
m Int
jid (LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity LeiosJobPool
pool))
                    }
                , StdGen
prng'
                )
 where
  -- Walk multiplicity buckets low-to-high, stopping at the first whose
  -- non-excluded jobs are non-empty; the caller draws a random one from that
  -- 'IntSet' difference. 'foldrWithKey' visits ascending keys and is lazy in the
  -- accumulator, so this stops at the first eligible bucket without materialising
  -- the bucket list.
  --
  -- TODO if we wanted to enforce a limit on the multiplicity of /each job/,
  -- it'd be easy to do so here: only visit the lower-multiplicity buckets
  eligibleBucket :: Maybe (Int, IntSet)
eligibleBucket =
    (Int -> NEIntSet -> Maybe (Int, IntSet) -> Maybe (Int, IntSet))
-> Maybe (Int, IntSet) -> IntMap NEIntSet -> Maybe (Int, IntSet)
forall a b. (Int -> a -> b -> b) -> b -> IntMap a -> b
IntMap.foldrWithKey
      ( \Int
m NEIntSet
bucket Maybe (Int, IntSet)
rest ->
          let diff :: IntSet
diff = IntSet -> IntSet -> IntSet
IntSet.difference (NEIntSet -> IntSet
NEIntSet.toSet NEIntSet
bucket) IntSet
excluded
           in if IntSet -> Bool
IntSet.null IntSet
diff then Maybe (Int, IntSet)
rest else (Int, IntSet) -> Maybe (Int, IntSet)
forall a. a -> Maybe a
Just (Int
m, IntSet
diff)
      )
      Maybe (Int, IntSet)
forall a. Maybe a
Nothing
      (LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity LeiosJobPool
pool)

  -- Bump jid from bucket m to m+1, carrying its bitfield out in the same traversal.
  bump1 :: Int -> Maybe LeiosJobState -> (Maybe LeiosJob, Maybe LeiosJobState)
bump1 Int
_m Maybe LeiosJobState
Nothing = (Maybe LeiosJob
forall a. Maybe a
Nothing, Maybe LeiosJobState
forall a. Maybe a
Nothing)
  bump1 Int
m (Just (MkLeiosJobState LeiosJob
job LeiosJobMultiplicity
_oldMultiplicity)) =
    (LeiosJob -> Maybe LeiosJob
forall a. a -> Maybe a
Just LeiosJob
job, LeiosJobState -> Maybe LeiosJobState
forall a. a -> Maybe a
Just (LeiosJob -> LeiosJobMultiplicity -> LeiosJobState
MkLeiosJobState LeiosJob
job (Int -> LeiosJobMultiplicity
MkLeiosJobMultiplicity (Int
m Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1))))

-- | Record one fewer in-flight request for a job (on disconnect). A no-op if the
-- job is no longer in the pool: a peer disconnecting after its response already
-- arrived and 'completeJob' removed the job hits the @Nothing@ branch below.
unpickJob :: LeiosJobId -> LeiosJobPool -> LeiosJobPool
unpickJob :: LeiosJobId -> LeiosJobPool -> LeiosJobPool
unpickJob (MkLeiosJobId Int
jid) LeiosJobPool
pool =
  case (Maybe LeiosJobState -> (Maybe (Int, Int), Maybe LeiosJobState))
-> Int
-> IntMap LeiosJobState
-> (Maybe (Int, Int), IntMap LeiosJobState)
forall (f :: * -> *) a.
Functor f =>
(Maybe a -> f (Maybe a)) -> Int -> IntMap a -> f (IntMap a)
IntMap.alterF Maybe LeiosJobState -> (Maybe (Int, Int), Maybe LeiosJobState)
decrement1 Int
jid (LeiosJobPool -> IntMap LeiosJobState
jobs LeiosJobPool
pool) of
    (Maybe (Int, Int)
Nothing, IntMap LeiosJobState
_) -> LeiosJobPool
pool
    (Just (Int
m, Int
m'), IntMap LeiosJobState
jobs') ->
      UnsafeLeiosJobPool
        { jobs :: IntMap LeiosJobState
jobs = IntMap LeiosJobState
jobs'
        , -- Move the job from its old bucket to the decremented one. When the
          -- count was already floored at 0, @m' == m@ and this deletes then
          -- re-inserts into the same bucket -- a net no-op, not special-cased
          -- because the floor is reached only on a surplus disconnect.
          jobsByMultiplicity :: IntMap NEIntSet
jobsByMultiplicity =
            Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketInsert Int
m' Int
jid (Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketDelete Int
m Int
jid (LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity LeiosJobPool
pool))
        }
 where
  -- One traversal of 'jobs': the pair functor carries the prior and new
  -- multiplicities (for the reverse-index move) alongside the new value.
  decrement1 :: Maybe LeiosJobState -> (Maybe (Int, Int), Maybe LeiosJobState)
decrement1 Maybe LeiosJobState
Nothing = (Maybe (Int, Int)
forall a. Maybe a
Nothing, Maybe LeiosJobState
forall a. Maybe a
Nothing)
  -- Floored: the multiplicity is an in-flight count, so it has no meaning below
  -- zero, and a negative one would sort the job into a bucket ahead of every
  -- genuinely unrequested one.
  decrement1 (Just (MkLeiosJobState LeiosJob
job (MkLeiosJobMultiplicity Int
m))) =
    let m' :: Int
m' = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
m Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)
     in ((Int, Int) -> Maybe (Int, Int)
forall a. a -> Maybe a
Just (Int
m, Int
m'), LeiosJobState -> Maybe LeiosJobState
forall a. a -> Maybe a
Just (LeiosJob -> LeiosJobMultiplicity -> LeiosJobState
MkLeiosJobState LeiosJob
job (Int -> LeiosJobMultiplicity
MkLeiosJobMultiplicity Int
m')))

-- | Remove a job from the pool entirely (on its response arriving).
completeJob :: LeiosJobId -> LeiosJobPool -> LeiosJobPool
completeJob :: LeiosJobId -> LeiosJobPool -> LeiosJobPool
completeJob (MkLeiosJobId Int
jid) LeiosJobPool
pool =
  case (Maybe LeiosJobState -> (Maybe Int, Maybe LeiosJobState))
-> Int -> IntMap LeiosJobState -> (Maybe Int, IntMap LeiosJobState)
forall (f :: * -> *) a.
Functor f =>
(Maybe a -> f (Maybe a)) -> Int -> IntMap a -> f (IntMap a)
IntMap.alterF Maybe LeiosJobState -> (Maybe Int, Maybe LeiosJobState)
forall {a}. Maybe LeiosJobState -> (Maybe Int, Maybe a)
delete1 Int
jid (LeiosJobPool -> IntMap LeiosJobState
jobs LeiosJobPool
pool) of
    (Maybe Int
Nothing, IntMap LeiosJobState
_) -> LeiosJobPool
pool
    (Just Int
m, IntMap LeiosJobState
jobs') ->
      UnsafeLeiosJobPool
        { jobs :: IntMap LeiosJobState
jobs = IntMap LeiosJobState
jobs'
        , jobsByMultiplicity :: IntMap NEIntSet
jobsByMultiplicity = Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketDelete Int
m Int
jid (LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity LeiosJobPool
pool)
        }
 where
  -- One traversal of 'jobs': carry out the removed job's multiplicity (for the
  -- reverse-index delete) while deleting the entry.
  delete1 :: Maybe LeiosJobState -> (Maybe Int, Maybe a)
delete1 Maybe LeiosJobState
Nothing = (Maybe Int
forall a. Maybe a
Nothing, Maybe a
forall a. Maybe a
Nothing)
  delete1 (Just (MkLeiosJobState LeiosJob
_job (MkLeiosJobMultiplicity Int
m))) = (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
m, Maybe a
forall a. Maybe a
Nothing)

-- | How many peers have each unfinished job in flight.
jobMultiplicities :: LeiosJobPool -> IntMap Int
jobMultiplicities :: LeiosJobPool -> IntMap Int
jobMultiplicities =
  (LeiosJobState -> Int) -> IntMap LeiosJobState -> IntMap Int
forall a b. (a -> b) -> IntMap a -> IntMap b
IntMap.map (\(MkLeiosJobState LeiosJob
_job (MkLeiosJobMultiplicity Int
m)) -> Int
m) (IntMap LeiosJobState -> IntMap Int)
-> (LeiosJobPool -> IntMap LeiosJobState)
-> LeiosJobPool
-> IntMap Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosJobPool -> IntMap LeiosJobState
jobs

-- | Whether 'jobsByMultiplicity' is the exact inverse of the multiplicities in
-- 'jobs', as 'LeiosJobPool' requires.
hasExactReverseIndex :: LeiosJobPool -> Bool
hasExactReverseIndex :: LeiosJobPool -> Bool
hasExactReverseIndex LeiosJobPool
pool =
  (NEIntSet -> IntSet) -> IntMap NEIntSet -> IntMap IntSet
forall a b. (a -> b) -> IntMap a -> IntMap b
IntMap.map NEIntSet -> IntSet
NEIntSet.toSet (LeiosJobPool -> IntMap NEIntSet
jobsByMultiplicity LeiosJobPool
pool)
    IntMap IntSet -> IntMap IntSet -> Bool
forall a. Eq a => a -> a -> Bool
== (IntSet -> IntSet -> IntSet) -> [(Int, IntSet)] -> IntMap IntSet
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IntMap.fromListWith
      IntSet -> IntSet -> IntSet
IntSet.union
      [(Int
m, Int -> IntSet
IntSet.singleton Int
jid) | (Int
jid, Int
m) <- IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IntMap.toList (LeiosJobPool -> IntMap Int
jobMultiplicities LeiosJobPool
pool)]

bucketDelete :: Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketDelete :: Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketDelete Int
m Int
jid = (NEIntSet -> Maybe NEIntSet)
-> Int -> IntMap NEIntSet -> IntMap NEIntSet
forall a. (a -> Maybe a) -> Int -> IntMap a -> IntMap a
IntMap.update (IntSet -> Maybe NEIntSet
NEIntSet.nonEmptySet (IntSet -> Maybe NEIntSet)
-> (NEIntSet -> IntSet) -> NEIntSet -> Maybe NEIntSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> NEIntSet -> IntSet
NEIntSet.delete Int
jid) Int
m

bucketInsert :: Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketInsert :: Int -> Int -> IntMap NEIntSet -> IntMap NEIntSet
bucketInsert Int
m Int
jid = (NEIntSet -> NEIntSet -> NEIntSet)
-> Int -> NEIntSet -> IntMap NEIntSet -> IntMap NEIntSet
forall a. (a -> a -> a) -> Int -> a -> IntMap a -> IntMap a
IntMap.insertWith NEIntSet -> NEIntSet -> NEIntSet
NEIntSet.union Int
m (Int -> NEIntSet
NEIntSet.singleton Int
jid)