{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}

-- | The LeiosTxCache interface: the handle type and the small set of types
-- shared by every implementation. See "Ouroboros.Consensus.Leios.TxCache" for
-- the overview.
module Ouroboros.Consensus.Leios.TxCache.API
  ( -- * Handle
    LeiosTxCache (..)
  , evictOlderThan
  , insertBody

    -- * Body payloads
  , ReferencesTxsByHash (..)
  , PackedEndorserBlock
  , packEndorserBlock

    -- * Tx states
  , TxState (..)
  , LandedTx (..)

    -- * Bounds
  , maxLeiosPointCount

    -- * Insert-body observability summary
  , LeiosTxCacheInsertBodySummary (..)
  , defaultLeiosTxCacheShift
  , worstCaseCacheTxCount

    -- * Arrival classification
  , TxArrivalPrior (..)
  , bucketTxArrival
  ) where

import Cardano.Crypto.Hash (Hash (UnsafeHash), hashToBytesShort)
import Cardano.Slotting.Slot (SlotNo)
import qualified Data.ByteString.Short as SBS
import Data.Maybe.Strict (StrictMaybe)
import Data.Set (Set)
import qualified Data.Vector.Unboxed as VU
import Ouroboros.Consensus.Leios.Types
  ( BytesSize
  , EndorserBlock
  , LeiosPoint
  , TxHash
  , TxLocation
  , TxOffset
  , endorserBlockReferences
  , maxTxsPerEndorserBlock
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Trace
  ( FetchArrivalBytes
  , LeiosTxCacheInsertBodySummary (..)
  , fetchArrivalEvicted
  , fetchArrivalExtra
  , fetchArrivalGood
  )

-- | The maximum number of points the cache retains, each one at which a body was
-- taken in. Retaining one more evicts the oldest.
--
-- It is chosen to be:
--
-- * small enough that the cache's RAM cost stays tolerable even in the worst
--   case, where every retained point's EB references 'maxTxsPerEndorserBlock'
--   (about 17 thousand) distinct txs: that 'worstCaseCacheTxCount' (about 2.2
--   million) fills the capacity the node's cache is sized for
--   ('defaultLeiosTxCacheShift') to a load factor of only about half; and
--
-- * large enough that a "significant" portion of stake is likely to be elected
--   again before its previous EB has been evicted from a recipient node's
--   LeiosTxCache.
maxLeiosPointCount :: Int
maxLeiosPointCount :: Int
maxLeiosPointCount = Int
128

-- | The worst-case number of txs the cache can be asked to hold: a full
-- 'maxLeiosPointCount' window of points, each of its own EB referencing the maximum
-- 'maxTxsPerEndorserBlock' distinct txs.
worstCaseCacheTxCount :: Int
worstCaseCacheTxCount :: Int
worstCaseCacheTxCount = Int
maxLeiosPointCount Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
maxTxsPerEndorserBlock

-- | The capacity the node's Leios tx cache is sized for: @2 ^@ this many
-- txs, which it reports as 'ibsCacheCapacity'. It covers
-- 'worstCaseCacheTxCount' about twice over.
defaultLeiosTxCacheShift :: Int
defaultLeiosTxCacheShift :: Int
defaultLeiosTxCacheShift = Int
22

-- | A handle on the LeiosTxCache. Its operations are atomic with respect to
-- each other: each holds the handle's lock while it runs, including any
-- continuation it is given.
--
-- The cache holds a tx for as long as it retains a point that the tx landed at
-- ('insertLandedTxs'), or whose body it took in while holding the tx
-- ('insertBodyAndFoldl''). It evicts points oldest first, so it tracks only
-- each tx's youngest such point, its youngest reference, and forgets the tx
-- when it evicts that point. Evicting a point also forgets the locations at it.
data LeiosTxCache m a v b = LeiosTxCache
  { forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall w.
   SlotNo -> w -> (w -> TxHash -> w) -> m (Set LeiosPoint, w)
evictOlderThanFoldl' ::
      forall w.
      SlotNo ->
      w ->
      (w -> TxHash -> w) ->
      m (Set LeiosPoint, w)
  -- ^ Evict every retained point whose slot is strictly older than the given
  -- boundary; returns the points it evicted. The tip-driven eviction entrypoint
  -- (see "Ouroboros.Consensus.Leios.TxCache"), complementing the count-driven
  -- eviction that 'insertBodyAndFoldl'' performs. Also records the boundary,
  -- after which 'insertBodyAndFoldl'' retains no point that old.
  --
  -- Pruning this cache before the LeiosDb is pruned to the same slot keeps its
  -- tx locations from naming rows the LeiosDb has deleted, though such a
  -- location would only cost a fetch; see "Ouroboros.Consensus.Leios.TxCache".
  --
  -- Also fold a caller-supplied accumulator over the txs it forgets. It walks
  -- the evicted points oldest first (least slot, then least EB hash), each body
  -- from its first tx to its last, and visits each forgotten tx once: at its
  -- first offset in the body of its youngest reference. It is a strict left
  -- fold: it evaluates each accumulator, the final one included, to WHNF before
  -- it returns.
  , forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall w.
   LeiosPoint
   -> b
   -> w
   -> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
   -> m (Maybe LeiosTxCacheInsertBodySummary, w)
insertBodyAndFoldl' ::
      forall w.
      LeiosPoint ->
      b ->
      w ->
      (w -> TxOffset -> TxHash -> BytesSize -> Maybe TxLocation -> w) ->
      m (Maybe LeiosTxCacheInsertBodySummary, w)
  -- ^ Take in the body of the EB at this point: retain the point with its body,
  -- make it the youngest reference of each tx the body references that the
  -- cache holds, if it is younger, and summarise that. A point of an EB the
  -- cache already holds at another point is taken in like any other. Nothing
  -- changes, and there is no summary, when the point is already retained, when
  -- it is strictly older than the latest 'evictOlderThanFoldl'' boundary, or
  -- when 'maxLeiosPointCount' points are retained and it is older than all of
  -- them. Otherwise, when 'maxLeiosPointCount' points are retained, it first
  -- evicts the oldest (least slot, then least EB hash).
  --
  -- Either way, fold a caller-supplied accumulator over /every/ referenced tx:
  -- starting from the nil @w@ and extending it with the snoc @w -> offset ->
  -- 'TxHash' -> 'BytesSize' -> 'Maybe' 'TxLocation' -> w@, where @offset@ is the
  -- tx's position in the body and the location is 'Just' iff the tx landed at
  -- some retained point ('insertLandedTxs'), i.e. it can serve a cross-EB
  -- fill. The fold lets the caller build what it needs without a list of every
  -- referenced tx in between. It is a strict left fold: it evaluates each
  -- accumulator, the final one included, to WHNF before it returns.
  , forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> LeiosPoint -> [LandedTx a v] -> m FetchArrivalBytes
insertLandedTxs :: LeiosPoint -> [LandedTx a v] -> m FetchArrivalBytes
  -- ^ Record that the given point now holds these txs, each the one its body
  -- lists at the tx's offset, with its state. Call this once the write lands.
  -- A no-op if the cache does not (still) retain the point.
  --
  -- A tx the cache does not hold is recorded with this point as its youngest
  -- reference and its location. For one it holds, this point becomes its
  -- youngest reference if it is younger than the tx's existing youngest
  -- reference, and its location if it is younger than the tx's existing
  -- location or the tx has none (younger: greater slot, then greater EB hash;
  -- the cache evicts it last). Either way, the tx is recorded as validated if
  -- it already has been, or if this says so.
  --
  -- Has exclusive write-access. Each tx's 'ltSize' is only used to accumulate
  -- the 'FetchArrivalBytes', which is only used for observability.
  --
  -- MAY be called repeatedly for one point: its closure arrives over many
  -- 'MsgLeiosBlockTxs'.
  , forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall r.
   (forall (n :: * -> *).
    Monad n =>
    (TxHash -> n (StrictMaybe (TxState a v))) -> n r)
   -> m r
withLookupTx ::
      forall r.
      (forall n. Monad n => (TxHash -> n (StrictMaybe (TxState a v))) -> n r) ->
      m r
  -- ^ Run the continuation with a lookup of the state of each tx the cache
  -- holds.
  --
  -- NOTE: The continuation's type is polymorphic in its monad so that it cannot
  -- call any operation of this handle, this one included: this runs it while
  -- holding the lock, so any such call would deadlock.
  }

-- | 'evictOlderThanFoldl'', for a caller that needs nothing back.
evictOlderThan :: Functor m => LeiosTxCache m a v b -> SlotNo -> m ()
evictOlderThan :: forall (m :: * -> *) a v b.
Functor m =>
LeiosTxCache m a v b -> SlotNo -> m ()
evictOlderThan LeiosTxCache m a v b
cache SlotNo
boundary =
  () () -> m (Set LeiosPoint, ()) -> m ()
forall a b. a -> m b -> m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ LeiosTxCache m a v b
-> forall w.
   SlotNo -> w -> (w -> TxHash -> w) -> m (Set LeiosPoint, w)
forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall w.
   SlotNo -> w -> (w -> TxHash -> w) -> m (Set LeiosPoint, w)
evictOlderThanFoldl' LeiosTxCache m a v b
cache SlotNo
boundary () (\() TxHash
_txh -> ())

-- | 'insertBodyAndFoldl'', for a caller that needs only the summary.
insertBody ::
  Functor m =>
  LeiosTxCache m a v b ->
  LeiosPoint ->
  b ->
  m (Maybe LeiosTxCacheInsertBodySummary)
insertBody :: forall (m :: * -> *) a v b.
Functor m =>
LeiosTxCache m a v b
-> LeiosPoint -> b -> m (Maybe LeiosTxCacheInsertBodySummary)
insertBody LeiosTxCache m a v b
cache LeiosPoint
point b
b =
  (Maybe LeiosTxCacheInsertBodySummary, ())
-> Maybe LeiosTxCacheInsertBodySummary
forall a b. (a, b) -> a
fst ((Maybe LeiosTxCacheInsertBodySummary, ())
 -> Maybe LeiosTxCacheInsertBodySummary)
-> m (Maybe LeiosTxCacheInsertBodySummary, ())
-> m (Maybe LeiosTxCacheInsertBodySummary)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> LeiosTxCache m a v b
-> forall w.
   LeiosPoint
   -> b
   -> w
   -> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
   -> m (Maybe LeiosTxCacheInsertBodySummary, w)
forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall w.
   LeiosPoint
   -> b
   -> w
   -> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
   -> m (Maybe LeiosTxCacheInsertBodySummary, w)
insertBodyAndFoldl' LeiosTxCache m a v b
cache LeiosPoint
point b
b () (\() Int
_off TxHash
_txh BytesSize
_sz Maybe TxLocation
_loc -> ())

-- | A body @b@ from which the referenced txs can be enumerated, each paired with
-- its on-the-wire size, in body order.
--
-- Visiting in body order lets a consumer recover each tx's offset from its
-- position in the fold.
class ReferencesTxsByHash b where
  foldTxReferences :: (r -> TxHash -> BytesSize -> r) -> r -> b -> r

-- | The node's body payload: each referenced tx's hash and size, in body order,
-- the hashes in one byte string and the sizes in an unboxed vector, at 36 bytes
-- per tx, about as much as the body's own encoding takes. The cache retains up
-- to 'maxLeiosPointCount' (128) of them, of up to
-- 'Ouroboros.Consensus.Leios.Types.maxEndorserBlockBytesSize' (600 kB) each, so
-- about 77 MB at worst; a decoded 'EndorserBlock' would cost several times
-- more.
data PackedEndorserBlock
  = MkPackedEndorserBlock !SBS.ShortByteString !(VU.Vector BytesSize)

packEndorserBlock :: EndorserBlock -> PackedEndorserBlock
packEndorserBlock :: EndorserBlock -> PackedEndorserBlock
packEndorserBlock EndorserBlock
eb =
  ShortByteString -> Vector BytesSize -> PackedEndorserBlock
MkPackedEndorserBlock
    ([ShortByteString] -> ShortByteString
forall a. Monoid a => [a] -> a
mconcat (((TxHash, BytesSize) -> ShortByteString)
-> [(TxHash, BytesSize)] -> [ShortByteString]
forall a b. (a -> b) -> [a] -> [b]
map (TxHash -> ShortByteString
forall h a. Hash h a -> ShortByteString
hashToBytesShort (TxHash -> ShortByteString)
-> ((TxHash, BytesSize) -> TxHash)
-> (TxHash, BytesSize)
-> ShortByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TxHash, BytesSize) -> TxHash
forall a b. (a, b) -> a
fst) [(TxHash, BytesSize)]
refs))
    ([BytesSize] -> Vector BytesSize
forall a. Unbox a => [a] -> Vector a
VU.fromList (((TxHash, BytesSize) -> BytesSize)
-> [(TxHash, BytesSize)] -> [BytesSize]
forall a b. (a -> b) -> [a] -> [b]
map (TxHash, BytesSize) -> BytesSize
forall a b. (a, b) -> b
snd [(TxHash, BytesSize)]
refs))
 where
  refs :: [(TxHash, BytesSize)]
refs = EndorserBlock -> [(TxHash, BytesSize)]
endorserBlockReferences EndorserBlock
eb

instance ReferencesTxsByHash PackedEndorserBlock where
  foldTxReferences :: forall r.
(r -> TxHash -> BytesSize -> r) -> r -> PackedEndorserBlock -> r
foldTxReferences r -> TxHash -> BytesSize -> r
f r
z (MkPackedEndorserBlock ShortByteString
hashes Vector BytesSize
sizes) =
    (r -> Int -> BytesSize -> r) -> r -> Vector BytesSize -> r
forall b a. Unbox b => (a -> Int -> b -> a) -> a -> Vector b -> a
VU.ifoldl' (\r
acc Int
i BytesSize
sz -> r -> TxHash -> BytesSize -> r
f r
acc (Int -> TxHash
forall {h} {a}. HashAlgorithm h => Int -> Hash h a
hashAt Int
i) BytesSize
sz) r
z Vector BytesSize
sizes
   where
    hashAt :: Int -> Hash h a
hashAt Int
i = ShortByteString -> Hash h a
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash (Int -> ShortByteString -> ShortByteString
SBS.take Int
32 (Int -> ShortByteString -> ShortByteString
SBS.drop (Int
32 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
i) ShortByteString
hashes))

-- | Whether a tx the cache holds was applied, and what it records of the tx.
data TxState a v
  = -- | The tx is inserted (fetched) but not yet applied, neither by the
    -- Mempool nor the LeiosVoting thread.
    TxInserted !a
  | -- | The tx has been applied.
    TxValidated !v
  deriving (TxState a v -> TxState a v -> Bool
(TxState a v -> TxState a v -> Bool)
-> (TxState a v -> TxState a v -> Bool) -> Eq (TxState a v)
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
forall a v. (Eq a, Eq v) => TxState a v -> TxState a v -> Bool
$c== :: forall a v. (Eq a, Eq v) => TxState a v -> TxState a v -> Bool
== :: TxState a v -> TxState a v -> Bool
$c/= :: forall a v. (Eq a, Eq v) => TxState a v -> TxState a v -> Bool
/= :: TxState a v -> TxState a v -> Bool
Eq, Int -> TxState a v -> ShowS
[TxState a v] -> ShowS
TxState a v -> String
(Int -> TxState a v -> ShowS)
-> (TxState a v -> String)
-> ([TxState a v] -> ShowS)
-> Show (TxState a v)
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
forall a v. (Show a, Show v) => Int -> TxState a v -> ShowS
forall a v. (Show a, Show v) => [TxState a v] -> ShowS
forall a v. (Show a, Show v) => TxState a v -> String
$cshowsPrec :: forall a v. (Show a, Show v) => Int -> TxState a v -> ShowS
showsPrec :: Int -> TxState a v -> ShowS
$cshow :: forall a v. (Show a, Show v) => TxState a v -> String
show :: TxState a v -> String
$cshowList :: forall a v. (Show a, Show v) => [TxState a v] -> ShowS
showList :: [TxState a v] -> ShowS
Show)

-- | A tx a write landed at a point.
data LandedTx a v = MkLandedTx
  { forall a v. LandedTx a v -> Int
ltOffset :: !TxOffset
  -- ^ the offset at which the point's body lists it
  , forall a v. LandedTx a v -> TxHash
ltHash :: !TxHash
  -- ^ its hash
  , forall a v. LandedTx a v -> BytesSize
ltSize :: !BytesSize
  -- ^ its size
  , forall a v. LandedTx a v -> TxState a v
ltState :: !(TxState a v)
  -- ^ its state
  }

-- | What the cache held of a tx before it landed, by which 'insertLandedTxs'
-- classifies the tx's bytes ('bucketTxArrival').
data TxArrivalPrior
  = -- | The cache does not retain the point the tx landed at: it has evicted
    -- that point, or ignored its body as older than what it retains.
    TxEvicted
  | -- | The cache did not hold the tx (the expected case).
    TxWasAbsent
  | -- | The cache already held the tx, so this arrival is redundant.
    TxWasHeld
  deriving (TxArrivalPrior -> TxArrivalPrior -> Bool
(TxArrivalPrior -> TxArrivalPrior -> Bool)
-> (TxArrivalPrior -> TxArrivalPrior -> Bool) -> Eq TxArrivalPrior
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TxArrivalPrior -> TxArrivalPrior -> Bool
== :: TxArrivalPrior -> TxArrivalPrior -> Bool
$c/= :: TxArrivalPrior -> TxArrivalPrior -> Bool
/= :: TxArrivalPrior -> TxArrivalPrior -> Bool
Eq, Int -> TxArrivalPrior -> ShowS
[TxArrivalPrior] -> ShowS
TxArrivalPrior -> String
(Int -> TxArrivalPrior -> ShowS)
-> (TxArrivalPrior -> String)
-> ([TxArrivalPrior] -> ShowS)
-> Show TxArrivalPrior
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TxArrivalPrior -> ShowS
showsPrec :: Int -> TxArrivalPrior -> ShowS
$cshow :: TxArrivalPrior -> String
show :: TxArrivalPrior -> String
$cshowList :: [TxArrivalPrior] -> ShowS
showList :: [TxArrivalPrior] -> ShowS
Show)

-- | Bucket an arriving tx's bytes by its prior state (for 'FetchArrivalBytes').
bucketTxArrival :: TxArrivalPrior -> BytesSize -> FetchArrivalBytes
bucketTxArrival :: TxArrivalPrior -> BytesSize -> FetchArrivalBytes
bucketTxArrival = \case
  TxArrivalPrior
TxEvicted -> BytesSize -> FetchArrivalBytes
fetchArrivalEvicted
  TxArrivalPrior
TxWasAbsent -> BytesSize -> FetchArrivalBytes
fetchArrivalGood
  TxArrivalPrior
TxWasHeld -> BytesSize -> FetchArrivalBytes
fetchArrivalExtra