{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Handler for the @WatchMempool@ SubmitService RPC method: stream
-- mempool transactions matching a predicate as they enter the mempool.
module Cardano.Rpc.Server.Internal.UtxoRpc.Mempool
  ( watchMempoolMethod
  , watchMempoolStream
  )
where

import Cardano.Rpc.Proto.Api.UtxoRpc.Submit qualified as U5c
import Cardano.Rpc.Server.Internal.FieldMask (FieldMaskTree, fillFrom, resolve, runFillPure)
import Cardano.Rpc.Server.Internal.Monad (MonadRpc)
import Cardano.Rpc.Server.Internal.UtxoRpc.Predicate (matchesTxPredicate)
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.Mempool
  ( TxInMempoolFields (..)
  , txInModeToTxInMempoolFields
  , watchMempoolFill
  )
import Cardano.Rpc.Server.NodeKernelAccess
  ( MempoolWatchSnapshot (..)
  , grabNodeKernelAccess
  , nextMempoolWatchSnapshot
  , watchMempoolSnapshot
  )

import Ouroboros.Consensus.Mempool.API qualified as Consensus (TicketNo, zeroTicketNo)

import RIO

import Network.GRPC.Spec (NextElem (NextElem), Proto (..), getProto)

import Proto.Google.Protobuf.FieldMask_Fields qualified as FieldMask (paths)

-- | Handle the @WatchMempool@ SubmitService RPC method.
--
-- Streams new mempool entries matching the request's predicate, each with
-- 'U5c.stage' always @STAGE_MEMPOOL@ (the first locally observable stage;
-- see 'Cardano.Rpc.Server.Internal.UtxoRpc.Predicate.matchesTxPredicate').
--
-- The field mask is resolved once, before the stream starts; paths start at
-- the response message, for example @tx.native_bytes@.
--
-- Runs until the client disconnects or the stream is otherwise closed.
watchMempoolMethod
  :: MonadRpc e m
  => Proto U5c.WatchMempoolRequest
  -- ^ Request containing a filter predicate and an optional field mask
  -> (NextElem (Proto U5c.WatchMempoolResponse) -> IO ())
  -- ^ Callback used to send each streamed response
  -> m ()
watchMempoolMethod :: forall e (m :: * -> *).
MonadRpc e m =>
Proto WatchMempoolRequest
-> (NextElem (Proto WatchMempoolResponse) -> IO ()) -> m ()
watchMempoolMethod Proto WatchMempoolRequest
request NextElem (Proto WatchMempoolResponse) -> IO ()
send = do
  nodeKernelAccess <- m NodeKernelAccess
forall e (m :: * -> *). MonadRpc e m => m NodeKernelAccess
grabNodeKernelAccess
  let fieldMask = [FieldPath] -> FieldMaskTree WatchMempoolResponse
forall msg. Message msg => [FieldPath] -> FieldMaskTree msg
resolve ([FieldPath] -> FieldMaskTree WatchMempoolResponse)
-> [FieldPath] -> FieldMaskTree WatchMempoolResponse
forall a b. (a -> b) -> a -> b
$ Proto WatchMempoolRequest -> WatchMempoolRequest
forall msg. Proto msg -> msg
getProto Proto WatchMempoolRequest
request WatchMempoolRequest
-> Getting [FieldPath] WatchMempoolRequest [FieldPath]
-> [FieldPath]
forall s a. s -> Getting a s a -> a
^. LensLike' (Const [FieldPath]) WatchMempoolRequest FieldMask
forall (f :: * -> *) s a.
(Functor f, HasField s "fieldMask" a) =>
LensLike' f s a
U5c.fieldMask LensLike' (Const [FieldPath]) WatchMempoolRequest FieldMask
-> (([FieldPath] -> Const [FieldPath] [FieldPath])
    -> FieldMask -> Const [FieldPath] FieldMask)
-> Getting [FieldPath] WatchMempoolRequest [FieldPath]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([FieldPath] -> Const [FieldPath] [FieldPath])
-> FieldMask -> Const [FieldPath] FieldMask
forall (f :: * -> *) s a.
(Functor f, HasField s "paths" a) =>
LensLike' f s a
FieldMask.paths
  watchMempoolStream
    (watchMempoolSnapshot nodeKernelAccess)
    (nextMempoolWatchSnapshot nodeKernelAccess)
    (request ^. U5c.predicate)
    fieldMask
    send

-- | The @WatchMempool@ streaming loop. Emits every mempool entry newer than
-- the last one seen, oldest first, filtered by the predicate and trimmed to
-- the field mask.
--
-- Removals produce no message: the proto has no representation for eviction.
watchMempoolStream
  :: forall m
   . MonadIO m
  => m MempoolWatchSnapshot
  -- ^ Read the current mempool watch snapshot, without blocking - used
  -- once, for the initial baseline
  -> (Consensus.TicketNo -> m MempoolWatchSnapshot)
  -- ^ Block until an entry newer than the given ticket exists, then return
  -- the snapshot
  -> Proto U5c.TxPredicate
  -- ^ Predicate filtering which new entries are sent
  -> FieldMaskTree U5c.WatchMempoolResponse
  -- ^ Field mask resolved once for the whole stream
  -> (NextElem (Proto U5c.WatchMempoolResponse) -> IO ())
  -- ^ Callback used to send each streamed response
  -> m ()
watchMempoolStream :: forall (m :: * -> *).
MonadIO m =>
m MempoolWatchSnapshot
-> (TicketNo -> m MempoolWatchSnapshot)
-> Proto TxPredicate
-> FieldMaskTree WatchMempoolResponse
-> (NextElem (Proto WatchMempoolResponse) -> IO ())
-> m ()
watchMempoolStream m MempoolWatchSnapshot
doReadSnapshot TicketNo -> m MempoolWatchSnapshot
nextSnapshot Proto TxPredicate
predicate FieldMaskTree WatchMempoolResponse
fieldMask NextElem (Proto WatchMempoolResponse) -> IO ()
send = do
  initial <- m MempoolWatchSnapshot
doReadSnapshot
  go Consensus.zeroTicketNo initial
 where
  go :: Consensus.TicketNo -> MempoolWatchSnapshot -> m ()
  go :: TicketNo -> MempoolWatchSnapshot -> m ()
go TicketNo
lastSeenTicket MempoolWatchSnapshot{mempoolWatchTxsAfter :: MempoolWatchSnapshot -> TicketNo -> [(TxInMode, TicketNo)]
mempoolWatchTxsAfter = TicketNo -> [(TxInMode, TicketNo)]
txsAfter} = do
    let newEntries :: [(TxInMode, TicketNo)]
newEntries = TicketNo -> [(TxInMode, TicketNo)]
txsAfter TicketNo
lastSeenTicket
    [(TxInMode, TicketNo)] -> ((TxInMode, TicketNo) -> m ()) -> m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(TxInMode, TicketNo)]
newEntries (((TxInMode, TicketNo) -> m ()) -> m ())
-> ((TxInMode, TicketNo) -> m ()) -> m ()
forall a b. (a -> b) -> a -> b
$ \(TxInMode
txInMode, TicketNo
_ticketNo) ->
      Maybe TxInMempoolFields -> (TxInMempoolFields -> m ()) -> m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (TxInMode -> Maybe TxInMempoolFields
txInModeToTxInMempoolFields TxInMode
txInMode) ((TxInMempoolFields -> m ()) -> m ())
-> (TxInMempoolFields -> m ()) -> m ()
forall a b. (a -> b) -> a -> b
$ \TxInMempoolFields
fields ->
        Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Proto TxPredicate -> Proto Tx -> Bool
matchesTxPredicate Proto TxPredicate
predicate (Proto Tx -> Bool) -> (Tx -> Proto Tx) -> Tx -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tx -> Proto Tx
forall msg. msg -> Proto msg
Proto (Tx -> Bool) -> Tx -> Bool
forall a b. (a -> b) -> a -> b
$ TxInMempoolFields -> Tx
txInMempoolFieldsCardano TxInMempoolFields
fields)
          (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ())
-> (FieldFill Identity WatchMempoolResponse -> IO ())
-> FieldFill Identity WatchMempoolResponse
-> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NextElem (Proto WatchMempoolResponse) -> IO ()
send (NextElem (Proto WatchMempoolResponse) -> IO ())
-> (FieldFill Identity WatchMempoolResponse
    -> NextElem (Proto WatchMempoolResponse))
-> FieldFill Identity WatchMempoolResponse
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Proto WatchMempoolResponse -> NextElem (Proto WatchMempoolResponse)
forall a. a -> NextElem a
NextElem (Proto WatchMempoolResponse
 -> NextElem (Proto WatchMempoolResponse))
-> (FieldFill Identity WatchMempoolResponse
    -> Proto WatchMempoolResponse)
-> FieldFill Identity WatchMempoolResponse
-> NextElem (Proto WatchMempoolResponse)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WatchMempoolResponse -> Proto WatchMempoolResponse
forall msg. msg -> Proto msg
Proto (WatchMempoolResponse -> Proto WatchMempoolResponse)
-> (FieldFill Identity WatchMempoolResponse
    -> WatchMempoolResponse)
-> FieldFill Identity WatchMempoolResponse
-> Proto WatchMempoolResponse
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldMaskTree WatchMempoolResponse
-> FieldFill Identity WatchMempoolResponse -> WatchMempoolResponse
forall msg.
Message msg =>
FieldMaskTree msg -> FieldFill Identity msg -> msg
runFillPure FieldMaskTree WatchMempoolResponse
fieldMask
          (FieldFill Identity WatchMempoolResponse -> m ())
-> FieldFill Identity WatchMempoolResponse -> m ()
forall a b. (a -> b) -> a -> b
$ TxInMempoolFields
-> FieldFill ((->) TxInMempoolFields) WatchMempoolResponse
-> FieldFill Identity WatchMempoolResponse
forall (m :: * -> *) shared msg.
Applicative m =>
shared -> FieldFill ((->) shared) msg -> FieldFill m msg
fillFrom TxInMempoolFields
fields FieldFill ((->) TxInMempoolFields) WatchMempoolResponse
watchMempoolFill
    let lastSeenTicket' :: TicketNo
lastSeenTicket' = case [(TxInMode, TicketNo)]
newEntries of
          [] -> TicketNo
lastSeenTicket
          [(TxInMode, TicketNo)]
_ -> (TxInMode, TicketNo) -> TicketNo
forall a b. (a, b) -> b
snd ([(TxInMode, TicketNo)] -> (TxInMode, TicketNo)
forall a. HasCallStack => [a] -> a
last [(TxInMode, TicketNo)]
newEntries)
    TicketNo -> m MempoolWatchSnapshot
nextSnapshot TicketNo
lastSeenTicket' m MempoolWatchSnapshot -> (MempoolWatchSnapshot -> m ()) -> m ()
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TicketNo -> MempoolWatchSnapshot -> m ()
go TicketNo
lastSeenTicket'