-- | Shared types for Yamux session management.
--
-- Types follow the HashiCorp yamux spec.md.
-- SessionRole determines stream ID parity, StreamState tracks the
-- stream lifecycle state machine, and YamuxSession/YamuxStream hold
-- per-session/per-stream mutable state via STM.
module LibP2P.Yamux.Types
  ( SessionRole (..)
  , StreamState (..)
  , YamuxError (..)
  , YamuxStream (..)
  , YamuxSession (..)
  , PingWaiter
  , Micros
  , mkMicros
  , microsToInt
  , YamuxConfig (..)
  , defaultYamuxConfig
  , enqueueFrame
  , enqueueDataFrame
  , enqueueFrameNumbered
  , awaitFrameWritten
  ) where

import Control.Concurrent.STM (STM, TBQueue, TMVar, TQueue, TVar, check, readTVar, writeTQueue, writeTVar)
import Control.Monad (void)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import Data.Word (Word32, Word64)
import LibP2P.Switch.ResourceManager
  ( MemoryAccount (..)
  , ResourceError
  )
import LibP2P.Yamux.Frame (GoAwayCode, YamuxHeader)

-- | Result delivered to a pending ping waiter: Right on a matching ACK,
-- Left when the session dies before the ACK arrives.
type PingWaiter = TMVar (Either YamuxError ())

-- | A strictly positive duration in microseconds.
newtype Micros = Micros Int
  deriving (Int -> Micros -> ShowS
[Micros] -> ShowS
Micros -> String
(Int -> Micros -> ShowS)
-> (Micros -> String) -> ([Micros] -> ShowS) -> Show Micros
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Micros -> ShowS
showsPrec :: Int -> Micros -> ShowS
$cshow :: Micros -> String
show :: Micros -> String
$cshowList :: [Micros] -> ShowS
showList :: [Micros] -> ShowS
Show, Micros -> Micros -> Bool
(Micros -> Micros -> Bool)
-> (Micros -> Micros -> Bool) -> Eq Micros
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Micros -> Micros -> Bool
== :: Micros -> Micros -> Bool
$c/= :: Micros -> Micros -> Bool
/= :: Micros -> Micros -> Bool
Eq, Eq Micros
Eq Micros =>
(Micros -> Micros -> Ordering)
-> (Micros -> Micros -> Bool)
-> (Micros -> Micros -> Bool)
-> (Micros -> Micros -> Bool)
-> (Micros -> Micros -> Bool)
-> (Micros -> Micros -> Micros)
-> (Micros -> Micros -> Micros)
-> Ord Micros
Micros -> Micros -> Bool
Micros -> Micros -> Ordering
Micros -> Micros -> Micros
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 :: Micros -> Micros -> Ordering
compare :: Micros -> Micros -> Ordering
$c< :: Micros -> Micros -> Bool
< :: Micros -> Micros -> Bool
$c<= :: Micros -> Micros -> Bool
<= :: Micros -> Micros -> Bool
$c> :: Micros -> Micros -> Bool
> :: Micros -> Micros -> Bool
$c>= :: Micros -> Micros -> Bool
>= :: Micros -> Micros -> Bool
$cmax :: Micros -> Micros -> Micros
max :: Micros -> Micros -> Micros
$cmin :: Micros -> Micros -> Micros
min :: Micros -> Micros -> Micros
Ord)

-- | Accept a positive number of microseconds, reject anything else.
mkMicros :: Int -> Maybe Micros
mkMicros :: Int -> Maybe Micros
mkMicros Int
n
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 = Micros -> Maybe Micros
forall a. a -> Maybe a
Just (Int -> Micros
Micros Int
n)
  | Bool
otherwise = Maybe Micros
forall a. Maybe a
Nothing

-- | The duration in microseconds, as System.Timeout.timeout takes it.
microsToInt :: Micros -> Int
microsToInt :: Micros -> Int
microsToInt (Micros Int
n) = Int
n

-- | Session tunables that spec.md leaves to the implementation.
data YamuxConfig = YamuxConfig
  { YamuxConfig -> Maybe Micros
ycKeepAlive :: !(Maybe Micros) -- ^ Time without a received frame before a keepalive Ping; Nothing disables keepalive
  , YamuxConfig -> Micros
ycPingTimeout :: !Micros -- ^ Limit for writing a Ping SYN, and again for its ACK
  }
  deriving (Int -> YamuxConfig -> ShowS
[YamuxConfig] -> ShowS
YamuxConfig -> String
(Int -> YamuxConfig -> ShowS)
-> (YamuxConfig -> String)
-> ([YamuxConfig] -> ShowS)
-> Show YamuxConfig
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> YamuxConfig -> ShowS
showsPrec :: Int -> YamuxConfig -> ShowS
$cshow :: YamuxConfig -> String
show :: YamuxConfig -> String
$cshowList :: [YamuxConfig] -> ShowS
showList :: [YamuxConfig] -> ShowS
Show, YamuxConfig -> YamuxConfig -> Bool
(YamuxConfig -> YamuxConfig -> Bool)
-> (YamuxConfig -> YamuxConfig -> Bool) -> Eq YamuxConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: YamuxConfig -> YamuxConfig -> Bool
== :: YamuxConfig -> YamuxConfig -> Bool
$c/= :: YamuxConfig -> YamuxConfig -> Bool
/= :: YamuxConfig -> YamuxConfig -> Bool
Eq)

defaultYamuxConfig :: YamuxConfig
defaultYamuxConfig :: YamuxConfig
defaultYamuxConfig =
  YamuxConfig
    { ycKeepAlive :: Maybe Micros
ycKeepAlive = Micros -> Maybe Micros
forall a. a -> Maybe a
Just (Int -> Micros
Micros Int
30000000) -- 30s
    , ycPingTimeout :: Micros
ycPingTimeout = Int -> Micros
Micros Int
10000000 -- 10s
    }

-- | SessionRole determines stream ID parity (spec.md §Stream Identification).
-- Client uses odd IDs (1, 3, 5, ...), Server uses even IDs (2, 4, 6, ...).
data SessionRole = RoleClient | RoleServer
  deriving (Int -> SessionRole -> ShowS
[SessionRole] -> ShowS
SessionRole -> String
(Int -> SessionRole -> ShowS)
-> (SessionRole -> String)
-> ([SessionRole] -> ShowS)
-> Show SessionRole
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SessionRole -> ShowS
showsPrec :: Int -> SessionRole -> ShowS
$cshow :: SessionRole -> String
show :: SessionRole -> String
$cshowList :: [SessionRole] -> ShowS
showList :: [SessionRole] -> ShowS
Show, SessionRole -> SessionRole -> Bool
(SessionRole -> SessionRole -> Bool)
-> (SessionRole -> SessionRole -> Bool) -> Eq SessionRole
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SessionRole -> SessionRole -> Bool
== :: SessionRole -> SessionRole -> Bool
$c/= :: SessionRole -> SessionRole -> Bool
/= :: SessionRole -> SessionRole -> Bool
Eq)

-- | Stream state machine (spec.md §Stream Open/Close/Reset).
-- States map to the spec's lifecycle:
--   SYN sent/received -> Established -> FIN sent/received -> Closed
data StreamState
  = StreamSYNSent -- ^ SYN sent, awaiting ACK (initiator)
  | StreamSYNReceived -- ^ SYN received, awaiting local ACK (responder)
  | StreamEstablished -- ^ Both SYN/ACK exchanged, data flows
  | StreamLocalClose -- ^ Local FIN sent (half-closed)
  | StreamRemoteClose -- ^ Remote FIN received (half-closed)
  | StreamClosed -- ^ Both FIN'd
  | StreamReset -- ^ RST sent or received
  deriving (Int -> StreamState -> ShowS
[StreamState] -> ShowS
StreamState -> String
(Int -> StreamState -> ShowS)
-> (StreamState -> String)
-> ([StreamState] -> ShowS)
-> Show StreamState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> StreamState -> ShowS
showsPrec :: Int -> StreamState -> ShowS
$cshow :: StreamState -> String
show :: StreamState -> String
$cshowList :: [StreamState] -> ShowS
showList :: [StreamState] -> ShowS
Show, StreamState -> StreamState -> Bool
(StreamState -> StreamState -> Bool)
-> (StreamState -> StreamState -> Bool) -> Eq StreamState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: StreamState -> StreamState -> Bool
== :: StreamState -> StreamState -> Bool
$c/= :: StreamState -> StreamState -> Bool
/= :: StreamState -> StreamState -> Bool
Eq)

-- | Errors map to spec-defined conditions.
data YamuxError
  = YamuxProtocolError !String -- ^ Spec violation (e.g., invalid version, unknown frame type)
  | YamuxStreamClosed -- ^ Write/read on closed stream
  | YamuxStreamReset -- ^ RST received
  | YamuxSessionShutdown -- ^ GoAway received or session closed
  | YamuxGoAway !GoAwayCode -- ^ Remote sent GoAway with specific code
  | YamuxPingTimeout -- ^ Ping SYN not written, or its ACK not received, in time
  | YamuxResourceLimit !ResourceError -- ^ Stream buffer reservation failed
  deriving (Int -> YamuxError -> ShowS
[YamuxError] -> ShowS
YamuxError -> String
(Int -> YamuxError -> ShowS)
-> (YamuxError -> String)
-> ([YamuxError] -> ShowS)
-> Show YamuxError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> YamuxError -> ShowS
showsPrec :: Int -> YamuxError -> ShowS
$cshow :: YamuxError -> String
show :: YamuxError -> String
$cshowList :: [YamuxError] -> ShowS
showList :: [YamuxError] -> ShowS
Show, YamuxError -> YamuxError -> Bool
(YamuxError -> YamuxError -> Bool)
-> (YamuxError -> YamuxError -> Bool) -> Eq YamuxError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: YamuxError -> YamuxError -> Bool
== :: YamuxError -> YamuxError -> Bool
$c/= :: YamuxError -> YamuxError -> Bool
/= :: YamuxError -> YamuxError -> Bool
Eq)

-- | Per-stream state (spec.md §Flow Control: per-stream windows only).
data YamuxStream = YamuxStream
  { YamuxStream -> Word32
ysStreamId :: !Word32
  , YamuxStream -> TVar StreamState
ysState :: !(TVar StreamState)
  , YamuxStream -> TVar Word32
ysSendWindow :: !(TVar Word32) -- ^ Starts at 262144 (256 KiB)
  , YamuxStream -> TVar Word32
ysRecvWindow :: !(TVar Word32) -- ^ Starts at 262144 (256 KiB)
  , YamuxStream -> TQueue ByteString
ysRecvBuf :: !(TQueue ByteString) -- ^ Incoming data frames
  , YamuxStream -> TMVar ()
ysSendNotify :: !(TMVar ()) -- ^ Wakeup blocked writers on WindowUpdate
  , YamuxStream -> MemoryAccount
ysMemoryAccount :: !MemoryAccount -- ^ Buffer ownership for this stream
  , YamuxStream -> YamuxSession
ysSession :: !YamuxSession -- ^ Back-reference for frame sending
  }

-- | Session state.
data YamuxSession = YamuxSession
  { YamuxSession -> YamuxConfig
ysessConfig :: !YamuxConfig
  , YamuxSession -> SessionRole
ysessRole :: !SessionRole
  , YamuxSession -> TVar Word32
ysessNextStreamId :: !(TVar Word32) -- ^ Next ID to allocate
  , YamuxSession -> TVar (Map Word32 YamuxStream)
ysessStreams :: !(TVar (Map.Map Word32 YamuxStream)) -- ^ Active streams
  , YamuxSession -> TBQueue YamuxStream
ysessAcceptCh :: !(TBQueue YamuxStream) -- ^ Inbound streams, bounded to acceptBacklog (256); excess SYNs are reset
  , YamuxSession
-> TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)
ysessSendCh :: !(TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)) -- ^ Outbound frame queue
  , YamuxSession -> MemoryAccount
ysessConnectionMemory :: !MemoryAccount -- ^ Memory used outside a known stream
  , YamuxSession -> STM (Either ResourceError MemoryAccount)
ysessInboundMemory :: !(STM (Either ResourceError MemoryAccount)) -- ^ Account factory for inbound streams
  , YamuxSession -> STM (Either ResourceError MemoryAccount)
ysessOutboundMemory :: !(STM (Either ResourceError MemoryAccount)) -- ^ Account factory for outbound streams
  , YamuxSession -> TVar Bool
ysessShutdown :: !(TVar Bool) -- ^ Local GoAway sent
  , YamuxSession -> TVar (Maybe GoAwayCode)
ysessRemoteGoAway :: !(TVar (Maybe GoAwayCode)) -- ^ Code of the remote GoAway, if one was received
  , YamuxSession -> TVar (Map Word32 PingWaiter)
ysessPings :: !(TVar (Map.Map Word32 PingWaiter)) -- ^ Pending ping responses
  , YamuxSession -> TVar Word32
ysessNextPingId :: !(TVar Word32)
  , YamuxSession -> TVar Word64
ysessQueuedCount :: !(TVar Word64) -- ^ Frames queued so far; the number of the latest queued frame
  , YamuxSession -> TVar Word64
ysessSentCount :: !(TVar Word64) -- ^ Frames sendLoop has finished writing
  , YamuxSession -> TVar Word64
ysessRecvCount :: !(TVar Word64) -- ^ Frame headers recvLoop has read
  , YamuxSession -> ByteString -> IO ()
ysessWrite :: !(ByteString -> IO ()) -- ^ Underlying transport write
  , YamuxSession -> Int -> IO ByteString
ysessRead :: !(Int -> IO ByteString) -- ^ Underlying transport read exact N bytes
  }

-- | Queue a frame for sendLoop to write. Every outbound frame goes
-- through here, so this is the one place that sees each frame as it
-- enters the send queue.
enqueueFrame :: YamuxSession -> YamuxHeader -> ByteString -> STM ()
enqueueFrame :: YamuxSession -> YamuxHeader -> ByteString -> STM ()
enqueueFrame YamuxSession
sess YamuxHeader
hdr ByteString
payload = STM Word64 -> STM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (YamuxSession -> YamuxHeader -> ByteString -> STM Word64
enqueueFrameNumbered YamuxSession
sess YamuxHeader
hdr ByteString
payload)

-- | Like 'enqueueFrame', returning the frame's number. Frames are
-- numbered from 1 in queue order, in the same transaction that queues
-- them, so the number also tells how many frames sendLoop must write
-- before this one is out (see 'awaitFrameWritten').
--
-- The counters are Word64, which cannot wrap in practice (about 58,000
-- years at 10M frames/s), so frame numbers are compared directly.
enqueueFrameNumbered :: YamuxSession -> YamuxHeader -> ByteString -> STM Word64
enqueueFrameNumbered :: YamuxSession -> YamuxHeader -> ByteString -> STM Word64
enqueueFrameNumbered YamuxSession
sess YamuxHeader
hdr ByteString
payload = do
  TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)
-> (YamuxHeader, ByteString, Maybe MemoryAccount) -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue (YamuxSession
-> TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)
ysessSendCh YamuxSession
sess) (YamuxHeader
hdr, ByteString
payload, Maybe MemoryAccount
forall a. Maybe a
Nothing)
  YamuxSession -> STM Word64
numberQueuedFrame YamuxSession
sess

-- | Reserve a payload while it waits in the outbound queue.
enqueueDataFrame
  :: YamuxSession -> MemoryAccount -> YamuxHeader -> ByteString
  -> STM (Either ResourceError Word64)
enqueueDataFrame :: YamuxSession
-> MemoryAccount
-> YamuxHeader
-> ByteString
-> STM (Either ResourceError Word64)
enqueueDataFrame YamuxSession
sess MemoryAccount
account YamuxHeader
hdr ByteString
payload = do
  reserved <- MemoryAccount -> Int -> STM (Either ResourceError ())
maReserve MemoryAccount
account (ByteString -> Int
BS.length ByteString
payload)
  case reserved of
    Left ResourceError
err -> Either ResourceError Word64 -> STM (Either ResourceError Word64)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError Word64
forall a b. a -> Either a b
Left ResourceError
err)
    Right () -> do
      TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)
-> (YamuxHeader, ByteString, Maybe MemoryAccount) -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue (YamuxSession
-> TQueue (YamuxHeader, ByteString, Maybe MemoryAccount)
ysessSendCh YamuxSession
sess) (YamuxHeader
hdr, ByteString
payload, MemoryAccount -> Maybe MemoryAccount
forall a. a -> Maybe a
Just MemoryAccount
account)
      Word64 -> Either ResourceError Word64
forall a b. b -> Either a b
Right (Word64 -> Either ResourceError Word64)
-> STM Word64 -> STM (Either ResourceError Word64)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> YamuxSession -> STM Word64
numberQueuedFrame YamuxSession
sess

numberQueuedFrame :: YamuxSession -> STM Word64
numberQueuedFrame :: YamuxSession -> STM Word64
numberQueuedFrame YamuxSession
sess = do
  n <- (Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
1) (Word64 -> Word64) -> STM Word64 -> STM Word64
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar Word64 -> STM Word64
forall a. TVar a -> STM a
readTVar (YamuxSession -> TVar Word64
ysessQueuedCount YamuxSession
sess)
  writeTVar (ysessQueuedCount sess) n
  pure n

-- | Block until sendLoop has finished writing the frame with the given
-- number to the transport.
awaitFrameWritten :: YamuxSession -> Word64 -> STM ()
awaitFrameWritten :: YamuxSession -> Word64 -> STM ()
awaitFrameWritten YamuxSession
sess Word64
n = TVar Word64 -> STM Word64
forall a. TVar a -> STM a
readTVar (YamuxSession -> TVar Word64
ysessSentCount YamuxSession
sess) STM Word64 -> (Word64 -> STM ()) -> STM ()
forall a b. STM a -> (a -> STM b) -> STM b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Bool -> STM ()
check (Bool -> STM ()) -> (Word64 -> Bool) -> Word64 -> STM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
n)