{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RankNTypes #-}

-- | The LeiosTxCache tracks txs that were acquired because a /recent/ EB
-- referenced them.
--
-- The LeiosTxCacheIndex records two facts about each tx it holds: whether it has
-- already been validated (by the Mempool or by the LeiosVoting thread), and
-- where a LeiosDB write of it landed.
--
-- The index is in-memory so that latency-critical consumers (LeiosFetch,
-- LeiosVoting) can query it with constantly low latency; it /supplants/ the
-- by-hash membership check that the fetch logic would otherwise do against the
-- LeiosDb. The size of the LeiosTxCache is bounded first and foremost by the
-- requirement that its index fits comfortably in-memory, even in a worst case.
--
-- This module is the umbrella: it re-exports the
-- "Ouroboros.Consensus.Leios.TxCache.API" interface and the handle factory
-- 'newPureLeiosTxCache', which wraps
-- "Ouroboros.Consensus.Leios.TxCache.Reference".
--
-- == What it promises about the LeiosDb
--
-- Nothing: its records are hints. A location it records for a tx need not hold
-- that tx in the LeiosDb. Once a point is older than the LeiosDb's promoted
-- slot, the LeiosDb's garbage collection deletes the point's txs, and a later
-- write of txs to that point stores none of them, though it settles as usual.
-- The cache evicts that point when LeiosFetch prunes to the immutable tip
-- ('evictOlderThanFoldl''), which can come after either.
--
-- Offering a recorded location to the LeiosDb as a fill is safe anyway: the
-- LeiosDb copies a fill only if its bytes hash to the tx the body lists at that
-- offset (see 'Ouroboros.Consensus.Storage.LeiosDB.API.writeEbBody'), so a
-- stale or wrong location costs a fetch, never a wrong tx.
module Ouroboros.Consensus.Leios.TxCache
  ( module Ouroboros.Consensus.Leios.TxCache.API
  , newPureLeiosTxCache
  , nullLeiosTxCache
  ) where

import qualified Data.Foldable as Foldable
import Data.Maybe.Strict (StrictMaybe (SNothing))
import qualified Data.Set as Set
import Ouroboros.Consensus.Leios.TxCache.API
import qualified Ouroboros.Consensus.Leios.TxCache.Reference as Pure
import Ouroboros.Consensus.Util.IOLike (IOLike, evaluate)
import qualified Ouroboros.Consensus.Util.NormalForm.StrictMVar as MVar

-- | A handle backed by the pure reference index behind an MVar.
--
-- The table shift only sizes 'ibsCacheCapacity' reporting -- the pure index has
-- no allocation of its own: pass 'defaultLeiosTxCacheShift'.
newPureLeiosTxCache ::
  (IOLike m, ReferencesTxsByHash b) =>
  Int ->
  m (LeiosTxCache m a v b)
newPureLeiosTxCache :: forall (m :: * -> *) b a v.
(IOLike m, ReferencesTxsByHash b) =>
Int -> m (LeiosTxCache m a v b)
newPureLeiosTxCache Int
nshift = do
  var <- LeiosTxCacheIndex a v b
-> m (StrictMVar m (LeiosTxCacheIndex a v b))
forall (m :: * -> *) a. MonadMVar m => a -> m (StrictMVar m a)
MVar.uncheckedNewMVar LeiosTxCacheIndex a v b
forall a v b. LeiosTxCacheIndex a v b
Pure.emptyLeiosTxCacheIndex
  pure
    LeiosTxCache
      { evictOlderThanFoldl' = \SlotNo
boundary w
nil w -> TxHash -> w
snoc ->
          StrictMVar m (LeiosTxCacheIndex a v b)
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b, (Set LeiosPoint, w)))
-> m (Set LeiosPoint, w)
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
MVar.modifyMVar StrictMVar m (LeiosTxCacheIndex a v b)
var ((LeiosTxCacheIndex a v b
  -> m (LeiosTxCacheIndex a v b, (Set LeiosPoint, w)))
 -> m (Set LeiosPoint, w))
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b, (Set LeiosPoint, w)))
-> m (Set LeiosPoint, w)
forall a b. (a -> b) -> a -> b
$ \LeiosTxCacheIndex a v b
idx -> do
            let (LeiosTxCacheIndex a v b
idx', Set LeiosPoint
evPoints, w
w) = SlotNo
-> w
-> (w -> TxHash -> w)
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b, Set LeiosPoint, w)
forall b w a v.
ReferencesTxsByHash b =>
SlotNo
-> w
-> (w -> TxHash -> w)
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b, Set LeiosPoint, w)
Pure.evictOlderThanFoldl' SlotNo
boundary w
nil w -> TxHash -> w
snoc LeiosTxCacheIndex a v b
idx
            -- Computed now, under the lock, as for 'insertBodyAndFoldl''.
            _ <- Set LeiosPoint -> m (Set LeiosPoint)
forall a. a -> m a
forall (m :: * -> *) a. MonadEvaluate m => a -> m a
evaluate Set LeiosPoint
evPoints
            _ <- evaluate w
            pure (idx', (evPoints, w))
      , insertBodyAndFoldl' = \LeiosPoint
point b
b w
nil w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w
snoc ->
          StrictMVar m (LeiosTxCacheIndex a v b)
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b,
          (Maybe LeiosTxCacheInsertBodySummary, w)))
-> m (Maybe LeiosTxCacheInsertBodySummary, w)
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
MVar.modifyMVar StrictMVar m (LeiosTxCacheIndex a v b)
var ((LeiosTxCacheIndex a v b
  -> m (LeiosTxCacheIndex a v b,
        (Maybe LeiosTxCacheInsertBodySummary, w)))
 -> m (Maybe LeiosTxCacheInsertBodySummary, w))
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b,
          (Maybe LeiosTxCacheInsertBodySummary, w)))
-> m (Maybe LeiosTxCacheInsertBodySummary, w)
forall a b. (a -> b) -> a -> b
$ \LeiosTxCacheIndex a v b
idx -> do
            let (LeiosTxCacheIndex a v b
idx', (Maybe LeiosTxCacheInsertBodySummary
summary, w
w)) = Int
-> LeiosPoint
-> b
-> w
-> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b,
    (Maybe LeiosTxCacheInsertBodySummary, w))
forall b w a v.
ReferencesTxsByHash b =>
Int
-> LeiosPoint
-> b
-> w
-> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b,
    (Maybe LeiosTxCacheInsertBodySummary, w))
Pure.insertBodyAndFoldl' (Int
2 Int -> Int -> Int
forall a b. (Num a, Integral b) => a -> b -> a
^ Int
nshift) LeiosPoint
point b
b w
nil w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w
snoc LeiosTxCacheIndex a v b
idx
            -- Computed now, under the lock, rather than when the caller first
            -- reads them, which would retain this snapshot of the index until
            -- then.
            (LeiosTxCacheInsertBodySummary -> m LeiosTxCacheInsertBodySummary)
-> Maybe LeiosTxCacheInsertBodySummary -> m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ LeiosTxCacheInsertBodySummary -> m LeiosTxCacheInsertBodySummary
forall a. a -> m a
forall (m :: * -> *) a. MonadEvaluate m => a -> m a
evaluate Maybe LeiosTxCacheInsertBodySummary
summary
            _ <- w -> m w
forall a. a -> m a
forall (m :: * -> *) a. MonadEvaluate m => a -> m a
evaluate w
w
            pure (idx', (summary, w))
      , insertLandedTxs = \LeiosPoint
point [LandedTx a v]
landed ->
          StrictMVar m (LeiosTxCacheIndex a v b)
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b, FetchArrivalBytes))
-> m FetchArrivalBytes
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
MVar.modifyMVar StrictMVar m (LeiosTxCacheIndex a v b)
var ((LeiosTxCacheIndex a v b
  -> m (LeiosTxCacheIndex a v b, FetchArrivalBytes))
 -> m FetchArrivalBytes)
-> (LeiosTxCacheIndex a v b
    -> m (LeiosTxCacheIndex a v b, FetchArrivalBytes))
-> m FetchArrivalBytes
forall a b. (a -> b) -> a -> b
$ \LeiosTxCacheIndex a v b
idx -> do
            let step :: (LeiosTxCacheIndex a v b, FetchArrivalBytes)
-> LandedTx a v -> (LeiosTxCacheIndex a v b, FetchArrivalBytes)
step (!LeiosTxCacheIndex a v b
idx', !FetchArrivalBytes
fab) (MkLandedTx Int
off TxHash
txh BytesSize
sz TxState a v
st) =
                  let (LeiosTxCacheIndex a v b
idx'', TxArrivalPrior
prior) = LeiosPoint
-> Int
-> TxHash
-> TxState a v
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b, TxArrivalPrior)
forall a v b.
LeiosPoint
-> Int
-> TxHash
-> TxState a v
-> LeiosTxCacheIndex a v b
-> (LeiosTxCacheIndex a v b, TxArrivalPrior)
Pure.insertLandedTx LeiosPoint
point Int
off TxHash
txh TxState a v
st LeiosTxCacheIndex a v b
idx'
                   in (LeiosTxCacheIndex a v b
idx'', FetchArrivalBytes
fab FetchArrivalBytes -> FetchArrivalBytes -> FetchArrivalBytes
forall a. Semigroup a => a -> a -> a
<> TxArrivalPrior -> BytesSize -> FetchArrivalBytes
bucketTxArrival TxArrivalPrior
prior BytesSize
sz)
                (LeiosTxCacheIndex a v b
landedIdx, FetchArrivalBytes
arrival) = ((LeiosTxCacheIndex a v b, FetchArrivalBytes)
 -> LandedTx a v -> (LeiosTxCacheIndex a v b, FetchArrivalBytes))
-> (LeiosTxCacheIndex a v b, FetchArrivalBytes)
-> [LandedTx a v]
-> (LeiosTxCacheIndex a v b, FetchArrivalBytes)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
Foldable.foldl' (LeiosTxCacheIndex a v b, FetchArrivalBytes)
-> LandedTx a v -> (LeiosTxCacheIndex a v b, FetchArrivalBytes)
forall {a} {v} {b}.
(LeiosTxCacheIndex a v b, FetchArrivalBytes)
-> LandedTx a v -> (LeiosTxCacheIndex a v b, FetchArrivalBytes)
step (LeiosTxCacheIndex a v b
idx, FetchArrivalBytes
forall a. Monoid a => a
mempty) [LandedTx a v]
landed
            _ <- FetchArrivalBytes -> m FetchArrivalBytes
forall a. a -> m a
forall (m :: * -> *) a. MonadEvaluate m => a -> m a
evaluate FetchArrivalBytes
arrival
            pure (landedIdx, arrival)
      , withLookupTx = \forall (n :: * -> *).
Monad n =>
(TxHash -> n (StrictMaybe (TxState a v))) -> n r
k ->
          -- Holds the lock, as 'withLookupTx' promises, though reading a
          -- snapshot of the index would do.
          StrictMVar m (LeiosTxCacheIndex a v b)
-> (LeiosTxCacheIndex a v b -> m r) -> m r
forall (m :: * -> *) a b.
MonadMVar m =>
StrictMVar m a -> (a -> m b) -> m b
MVar.withMVar StrictMVar m (LeiosTxCacheIndex a v b)
var ((LeiosTxCacheIndex a v b -> m r) -> m r)
-> (LeiosTxCacheIndex a v b -> m r) -> m r
forall a b. (a -> b) -> a -> b
$ \LeiosTxCacheIndex a v b
idx -> (TxHash -> m (StrictMaybe (TxState a v))) -> m r
forall (n :: * -> *).
Monad n =>
(TxHash -> n (StrictMaybe (TxState a v))) -> n r
k ((TxHash -> m (StrictMaybe (TxState a v))) -> m r)
-> (TxHash -> m (StrictMaybe (TxState a v))) -> m r
forall a b. (a -> b) -> a -> b
$ \TxHash
txh -> StrictMaybe (TxState a v) -> m (StrictMaybe (TxState a v))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (StrictMaybe (TxState a v) -> m (StrictMaybe (TxState a v)))
-> StrictMaybe (TxState a v) -> m (StrictMaybe (TxState a v))
forall a b. (a -> b) -> a -> b
$! TxHash -> LeiosTxCacheIndex a v b -> StrictMaybe (TxState a v)
forall a v b.
TxHash -> LeiosTxCacheIndex a v b -> StrictMaybe (TxState a v)
Pure.lookupTx TxHash
txh LeiosTxCacheIndex a v b
idx
      }

-- | A handle whose every operation is inert: bodies are never retained,
-- summarised nor their txs folded over, landed txs are counted evicted, and
-- lookups always miss. For
-- contexts that don't maintain the cache, such as tools that replay or forge
-- blocks.
nullLeiosTxCache :: Monad m => LeiosTxCache m a v b
nullLeiosTxCache :: forall (m :: * -> *) a v b. Monad m => LeiosTxCache m a v b
nullLeiosTxCache =
  LeiosTxCache
    { evictOlderThanFoldl' :: forall w.
SlotNo -> w -> (w -> TxHash -> w) -> m (Set LeiosPoint, w)
evictOlderThanFoldl' = \SlotNo
_boundary w
nil w -> TxHash -> w
_snoc -> (Set LeiosPoint, w) -> m (Set LeiosPoint, w)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Set LeiosPoint
forall a. Set a
Set.empty, w
nil)
    , insertBodyAndFoldl' :: forall w.
LeiosPoint
-> b
-> w
-> (w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w)
-> m (Maybe LeiosTxCacheInsertBodySummary, w)
insertBodyAndFoldl' = \LeiosPoint
_point b
_b w
nil w -> Int -> TxHash -> BytesSize -> Maybe TxLocation -> w
_snoc -> (Maybe LeiosTxCacheInsertBodySummary, w)
-> m (Maybe LeiosTxCacheInsertBodySummary, w)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe LeiosTxCacheInsertBodySummary
forall a. Maybe a
Nothing, w
nil)
    , insertLandedTxs :: LeiosPoint -> [LandedTx a v] -> m FetchArrivalBytes
insertLandedTxs = \LeiosPoint
_point [LandedTx a v]
landed ->
        FetchArrivalBytes -> m FetchArrivalBytes
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((LandedTx a v -> FetchArrivalBytes)
-> [LandedTx a v] -> FetchArrivalBytes
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (TxArrivalPrior -> BytesSize -> FetchArrivalBytes
bucketTxArrival TxArrivalPrior
TxEvicted (BytesSize -> FetchArrivalBytes)
-> (LandedTx a v -> BytesSize) -> LandedTx a v -> FetchArrivalBytes
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LandedTx a v -> BytesSize
forall a v. LandedTx a v -> BytesSize
ltSize) [LandedTx a v]
landed)
    , withLookupTx :: forall r.
(forall (n :: * -> *).
 Monad n =>
 (TxHash -> n (StrictMaybe (TxState a v))) -> n r)
-> m r
withLookupTx = \forall (n :: * -> *).
Monad n =>
(TxHash -> n (StrictMaybe (TxState a v))) -> n r
k -> (TxHash -> m (StrictMaybe (TxState a v))) -> m r
forall (n :: * -> *).
Monad n =>
(TxHash -> n (StrictMaybe (TxState a v))) -> n r
k (\TxHash
_txh -> StrictMaybe (TxState a v) -> m (StrictMaybe (TxState a v))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure StrictMaybe (TxState a v)
forall a. StrictMaybe a
SNothing)
    }