-- | Connection lifecycle for the Switch.
--
-- Provides the single teardown path for upgraded connections and a
-- resource-accounted outbound stream opener. Teardown fires from the
-- stream accept loop exit (remote disconnect or session death), from
-- explicit 'closeConnection' calls, and from 'switchClose' via
-- 'closeAllConnections'.
module LibP2P.Switch.Connection
  ( closeConnection
  , closeAllConnections
  , newStream
  , newStreamAllowingLimited
  , StreamOpenError (..)
  ) where

import Control.Concurrent.STM (atomically, readTVar, writeTChan, writeTVar)
import Control.Exception (Exception, SomeException, catch, mask, onException)
import Control.Monad (when)
import LibP2P.MultistreamSelect.Negotiation (StreamIO (..))
import LibP2P.Switch.ConnPool (allConns, removeConn)
import LibP2P.Switch.ResourceManager
  ( Direction (..)
  , ResourceError (..)
  , releaseConnection
  , releaseStream
  , reserveStream
  , scopeMemoryAccount
  )
import LibP2P.Transport (relayCircuitIsLimited)
import LibP2P.Switch.Types
  ( ConnState (..)
  , Connection (..)
  , MuxerSession (..)
  , Switch (..)
  , SwitchEvent (..)
  )

-- | Tear down a connection: remove it from the pool, release its
-- resource reservation, publish a Disconnected event, run the
-- disconnect notifiers, and close the muxer session together with the
-- underlying transport.
--
-- Idempotent: the state transition to ConnClosed is atomic, so
-- concurrent calls (accept loop exit, explicit close, switchClose)
-- perform the teardown exactly once, and the notifiers run once.
--
-- Notifiers run synchronously, after the pool removal has committed and
-- before the muxer is closed, so a notifier that asks whether the peer
-- still has a live connection (Circuit Relay v2 reservation cleanup)
-- never sees the connection being torn down. Each is isolated so a
-- failing notifier cannot abort the teardown.
closeConnection :: Switch -> Connection -> IO ()
closeConnection :: Switch -> Connection -> IO ()
closeConnection Switch
sw Connection
conn = do
  shouldClose <- STM Bool -> IO Bool
forall a. STM a -> IO a
atomically (STM Bool -> IO Bool) -> STM Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ do
    st <- TVar ConnState -> STM ConnState
forall a. TVar a -> STM a
readTVar (Connection -> TVar ConnState
connState Connection
conn)
    if st == ConnClosed
      then pure False
      else do
        writeTVar (connState conn) ConnClosed
        removeConn (swConnPool sw) conn
        releaseConnection (swResourceMgr sw) (connResourceScope conn)
        writeTChan (swEvents sw)
          (Disconnected (connPeerId conn) (connDirection conn) (connRemoteAddr conn))
        pure True
  when shouldClose $ do
    notifiers <- atomically $ readTVar (swDisconnectNotifiers sw)
    mapM_ (\Connection -> IO ()
f -> Connection -> IO ()
f Connection
conn IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) notifiers
    muxClose (connSession conn) `catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

-- | Tear down every pooled connection (used by switchClose).
closeAllConnections :: Switch -> IO ()
closeAllConnections :: Switch -> IO ()
closeAllConnections Switch
sw = do
  conns <- STM [Connection] -> IO [Connection]
forall a. STM a -> IO a
atomically (STM [Connection] -> IO [Connection])
-> STM [Connection] -> IO [Connection]
forall a b. (a -> b) -> a -> b
$ TVar (Map PeerId [Connection]) -> STM [Connection]
allConns (Switch -> TVar (Map PeerId [Connection])
swConnPool Switch
sw)
  mapM_ (closeConnection sw) conns

-- | Failure to open an outbound stream.
data StreamOpenError
  = StreamResourceLimit !ResourceError
    -- ^ Peer or connection stream budget is exhausted
  | StreamLimitedConnection
    -- ^ The connection is a relay circuit with an active budget, and
    -- the caller did not opt in. No stream slot is reserved.
  deriving (Int -> StreamOpenError -> ShowS
[StreamOpenError] -> ShowS
StreamOpenError -> String
(Int -> StreamOpenError -> ShowS)
-> (StreamOpenError -> String)
-> ([StreamOpenError] -> ShowS)
-> Show StreamOpenError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> StreamOpenError -> ShowS
showsPrec :: Int -> StreamOpenError -> ShowS
$cshow :: StreamOpenError -> String
show :: StreamOpenError -> String
$cshowList :: [StreamOpenError] -> ShowS
showList :: [StreamOpenError] -> ShowS
Show, StreamOpenError -> StreamOpenError -> Bool
(StreamOpenError -> StreamOpenError -> Bool)
-> (StreamOpenError -> StreamOpenError -> Bool)
-> Eq StreamOpenError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: StreamOpenError -> StreamOpenError -> Bool
== :: StreamOpenError -> StreamOpenError -> Bool
$c/= :: StreamOpenError -> StreamOpenError -> Bool
/= :: StreamOpenError -> StreamOpenError -> Bool
Eq)

instance Exception StreamOpenError

-- | Open an outbound stream on a connection, reserving a stream slot
-- against the peer's resource scope. The slot is released when the
-- returned stream is closed (exactly once, even on double close).
--
-- Refuses a relay-limited connection. Protocols that must run over a
-- relay circuit (Identify, Ping, DCUtR) use 'newStreamAllowingLimited'.
newStream :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream = Bool
-> Switch -> Connection -> IO (Either StreamOpenError StreamIO)
openOutboundStream Bool
False

-- | Like 'newStream', but allows a relay-limited connection.
--
-- The circuit still dies when its budget is exhausted
-- ('LibP2P.NAT.Relay.Limit.RelayCircuitExhausted'). Opt in only for a
-- short exchange that can tolerate that.
newStreamAllowingLimited
  :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStreamAllowingLimited :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStreamAllowingLimited = Bool
-> Switch -> Connection -> IO (Either StreamOpenError StreamIO)
openOutboundStream Bool
True

openOutboundStream
  :: Bool -> Switch -> Connection -> IO (Either StreamOpenError StreamIO)
openOutboundStream :: Bool
-> Switch -> Connection -> IO (Either StreamOpenError StreamIO)
openOutboundStream Bool
allowLimited Switch
sw Connection
conn
  | Bool -> Bool
not Bool
allowLimited Bool -> Bool -> Bool
&& Maybe RelayCircuitLimit -> Bool
relayCircuitIsLimited (Connection -> Maybe RelayCircuitLimit
connRelayLimit Connection
conn) =
      Either StreamOpenError StreamIO
-> IO (Either StreamOpenError StreamIO)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (StreamOpenError -> Either StreamOpenError StreamIO
forall a b. a -> Either a b
Left StreamOpenError
StreamLimitedConnection)
  | Bool
otherwise = ((forall a. IO a -> IO a) -> IO (Either StreamOpenError StreamIO))
-> IO (Either StreamOpenError StreamIO)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO (Either StreamOpenError StreamIO))
 -> IO (Either StreamOpenError StreamIO))
-> ((forall a. IO a -> IO a)
    -> IO (Either StreamOpenError StreamIO))
-> IO (Either StreamOpenError StreamIO)
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
      reserved <- STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (STM (Either ResourceError ResourceScope)
 -> IO (Either ResourceError ResourceScope))
-> STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a b. (a -> b) -> a -> b
$
        ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream (Switch -> ResourceManager
swResourceMgr Switch
sw) (Connection -> ResourceScope
connResourceScope Connection
conn) Direction
Outbound
      case reserved of
        Left ResourceError
err -> Either StreamOpenError StreamIO
-> IO (Either StreamOpenError StreamIO)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (StreamOpenError -> Either StreamOpenError StreamIO
forall a b. a -> Either a b
Left (ResourceError -> StreamOpenError
StreamResourceLimit ResourceError
err))
        Right ResourceScope
streamScope -> do
          let release :: IO ()
release = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ ResourceManager -> ResourceScope -> STM ()
releaseStream (Switch -> ResourceManager
swResourceMgr Switch
sw) ResourceScope
streamScope
              account :: MemoryAccount
account = ResourceManager -> ResourceScope -> MemoryAccount
scopeMemoryAccount (Switch -> ResourceManager
swResourceMgr Switch
sw) ResourceScope
streamScope
          stream <- IO StreamIO -> IO StreamIO
forall a. IO a -> IO a
restore (MuxerSession -> MemoryAccount -> IO StreamIO
muxOpenStream (Connection -> MuxerSession
connSession Connection
conn) MemoryAccount
account)
            IO StreamIO -> IO () -> IO StreamIO
forall a b. IO a -> IO b -> IO a
`onException` IO ()
release
          pure (Right stream)