-- | Switch core operations.
--
-- The Switch is the central coordinator of the libp2p stack.
-- This module provides construction, transport management,
-- protocol handler registration, and shutdown.
module LibP2P.Switch
  ( newSwitch
  , newSwitchWithConfig
  , subscribeSwitchEvents
  , addTransport
  , selectTransport
  , setConnectionGater
  , setStreamHandler
  , removeStreamHandler
  , lookupStreamHandler
  , registerSwitchShutdownAction
  , switchClose
  ) where

import Control.Concurrent.Async (async, cancel)
import Control.Concurrent.STM (TChan, atomically, dupTChan, newBroadcastTChanIO, newTVarIO, readTVar, writeTVar)
import Control.Exception (SomeException, catch)
import Control.Monad (unless, void)
import Data.List (find)
import qualified Data.Map.Strict as Map
import LibP2P.Crypto.Key (KeyPair)
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Multiaddr (Multiaddr)
import LibP2P.MultistreamSelect.Negotiation (ProtocolId)
import LibP2P.Protocol.Identify (pushIdentify)
import LibP2P.Switch.Connection (closeAllConnections)
import LibP2P.Switch.ResourceManager
  ( DefaultLimits (..)
  , defaultConnectionLimits
  , defaultPeerLimits
  , defaultStreamLimits
  , defaultSystemLimits
  , newResourceManager
  )
import LibP2P.Switch.Types
  ( ActiveListener (..)
  , ConnectionGater
  , StreamHandler
  , Switch (..)
  , SwitchConfig
  , SwitchEvent
  , defaultConnectionGater
  , defaultSwitchConfig
  )
import LibP2P.Transport (Listener (..), Transport (..))

-- | Create a new Switch with the given local identity.
-- All internal state is initialized empty.
newSwitch :: PeerId -> KeyPair -> IO Switch
newSwitch :: PeerId -> KeyPair -> IO Switch
newSwitch = SwitchConfig -> PeerId -> KeyPair -> IO Switch
newSwitchWithConfig SwitchConfig
defaultSwitchConfig

-- | Like 'newSwitch', with an explicit configuration.
newSwitchWithConfig :: SwitchConfig -> PeerId -> KeyPair -> IO Switch
newSwitchWithConfig :: SwitchConfig -> PeerId -> KeyPair -> IO Switch
newSwitchWithConfig SwitchConfig
config PeerId
pid KeyPair
kp = do
  transportsVar   <- [Transport] -> IO (TVar [Transport])
forall a. a -> IO (TVar a)
newTVarIO []
  poolVar         <- newTVarIO Map.empty
  protosVar       <- newTVarIO Map.empty
  eventsChan      <- newBroadcastTChanIO
  closedVar       <- newTVarIO False
  backoffsVar     <- newTVarIO Map.empty
  pendingDialsVar <- newTVarIO Map.empty
  connectionGaterVar <- newTVarIO defaultConnectionGater
  resMgr <- newResourceManager DefaultLimits
    { dlSystemLimits = defaultSystemLimits
    , dlPeerLimits = defaultPeerLimits
    , dlConnectionLimits = defaultConnectionLimits
    , dlStreamLimits = defaultStreamLimits
    }
  peerStoreVar <- newTVarIO Map.empty
  certifiedRecordsVar <- newTVarIO Map.empty
  notifiersVar <- newTVarIO []
  disconnectNotifiersVar <- newTVarIO []
  listenersVar <- newTVarIO []
  shutdownActionsVar <- newTVarIO []
  pure Switch
    { swLocalPeerId  = pid
    , swIdentityKey  = kp
    , swTransports   = transportsVar
    , swConnPool     = poolVar
    , swProtocols    = protosVar
    , swEvents       = eventsChan
    , swClosed       = closedVar
    , swDialBackoffs = backoffsVar
    , swPendingDials = pendingDialsVar
    , swConnectionGater = connectionGaterVar
    , swResourceMgr  = resMgr
    , swPeerStore    = peerStoreVar
    , swCertifiedRecords = certifiedRecordsVar
    , swNotifiers    = notifiersVar
    , swDisconnectNotifiers = disconnectNotifiersVar
    , swListeners    = listenersVar
    , swShutdownActions = shutdownActionsVar
    , swConfig       = config
    }

-- | Subscribe independently to future per-connection events (no replay).
-- Drop the channel to unsubscribe; unread channels retain queued events.
-- Shutdown neither waits for subscribers nor signals end-of-stream.
subscribeSwitchEvents :: Switch -> IO (TChan SwitchEvent)
subscribeSwitchEvents :: Switch -> IO (TChan SwitchEvent)
subscribeSwitchEvents Switch
sw = STM (TChan SwitchEvent) -> IO (TChan SwitchEvent)
forall a. STM a -> IO a
atomically (STM (TChan SwitchEvent) -> IO (TChan SwitchEvent))
-> STM (TChan SwitchEvent) -> IO (TChan SwitchEvent)
forall a b. (a -> b) -> a -> b
$ TChan SwitchEvent -> STM (TChan SwitchEvent)
forall a. TChan a -> STM (TChan a)
dupTChan (Switch -> TChan SwitchEvent
swEvents Switch
sw)

-- | Register a transport with the switch.
-- Appends to the list of transports; order matters for selectTransport.
addTransport :: Switch -> Transport -> IO ()
addTransport :: Switch -> Transport -> IO ()
addTransport Switch
sw Transport
t = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  ts <- TVar [Transport] -> STM [Transport]
forall a. TVar a -> STM a
readTVar (Switch -> TVar [Transport]
swTransports Switch
sw)
  writeTVar (swTransports sw) (ts ++ [t])

-- | Find the first registered transport that can dial the given multiaddr.
selectTransport :: Switch -> Multiaddr -> IO (Maybe Transport)
selectTransport :: Switch -> Multiaddr -> IO (Maybe Transport)
selectTransport Switch
sw Multiaddr
addr = STM (Maybe Transport) -> IO (Maybe Transport)
forall a. STM a -> IO a
atomically (STM (Maybe Transport) -> IO (Maybe Transport))
-> STM (Maybe Transport) -> IO (Maybe Transport)
forall a b. (a -> b) -> a -> b
$ do
  ts <- TVar [Transport] -> STM [Transport]
forall a. TVar a -> STM a
readTVar (Switch -> TVar [Transport]
swTransports Switch
sw)
  pure $ find (\Transport
t -> Transport -> Multiaddr -> Bool
transportCanDial Transport
t Multiaddr
addr) ts

-- | Set the admission policy used by future inbound and outbound connections.
-- Configure this before starting listeners or dialing peers.
setConnectionGater :: Switch -> ConnectionGater -> IO ()
setConnectionGater :: Switch -> ConnectionGater -> IO ()
setConnectionGater Switch
sw ConnectionGater
gater = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
  TVar ConnectionGater -> ConnectionGater -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (Switch -> TVar ConnectionGater
swConnectionGater Switch
sw) ConnectionGater
gater

-- | Register a protocol stream handler.
-- Overwrites any existing handler for the same protocol ID.
-- The changed protocol set is pushed to connected peers via
-- identify push (specs/identify) in the background.
setStreamHandler :: Switch -> ProtocolId -> StreamHandler -> IO ()
setStreamHandler :: Switch -> ProtocolId -> StreamHandler -> IO ()
setStreamHandler Switch
sw ProtocolId
proto StreamHandler
handler = do
  STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    protos <- TVar (Map ProtocolId StreamHandler)
-> STM (Map ProtocolId StreamHandler)
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map ProtocolId StreamHandler)
swProtocols Switch
sw)
    writeTVar (swProtocols sw) (Map.insert proto handler protos)
  IO (Async ()) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO (Async ()) -> IO ()) -> IO (Async ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (Switch -> IO ()
pushIdentify Switch
sw)

-- | Remove a protocol stream handler.
-- The changed protocol set is pushed to connected peers via
-- identify push (specs/identify) in the background.
removeStreamHandler :: Switch -> ProtocolId -> IO ()
removeStreamHandler :: Switch -> ProtocolId -> IO ()
removeStreamHandler Switch
sw ProtocolId
proto = do
  STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    protos <- TVar (Map ProtocolId StreamHandler)
-> STM (Map ProtocolId StreamHandler)
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map ProtocolId StreamHandler)
swProtocols Switch
sw)
    writeTVar (swProtocols sw) (Map.delete proto protos)
  IO (Async ()) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO (Async ()) -> IO ()) -> IO (Async ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (Switch -> IO ()
pushIdentify Switch
sw)

-- | Look up a registered stream handler by protocol ID.
lookupStreamHandler :: Switch -> ProtocolId -> IO (Maybe StreamHandler)
lookupStreamHandler :: Switch -> ProtocolId -> IO (Maybe StreamHandler)
lookupStreamHandler Switch
sw ProtocolId
proto = STM (Maybe StreamHandler) -> IO (Maybe StreamHandler)
forall a. STM a -> IO a
atomically (STM (Maybe StreamHandler) -> IO (Maybe StreamHandler))
-> STM (Maybe StreamHandler) -> IO (Maybe StreamHandler)
forall a b. (a -> b) -> a -> b
$ do
  protos <- TVar (Map ProtocolId StreamHandler)
-> STM (Map ProtocolId StreamHandler)
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map ProtocolId StreamHandler)
swProtocols Switch
sw)
  pure $ Map.lookup proto protos

-- | Register cleanup for a background service owned by the Switch.
-- If shutdown has already begun, the action runs immediately instead.
registerSwitchShutdownAction :: Switch -> IO () -> IO ()
registerSwitchShutdownAction :: Switch -> IO () -> IO ()
registerSwitchShutdownAction Switch
sw IO ()
action = do
  alreadyClosed <- 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
    closed <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (Switch -> TVar Bool
swClosed Switch
sw)
    unless closed $ do
      actions <- readTVar (swShutdownActions sw)
      writeTVar (swShutdownActions sw) (action : actions)
    pure closed
  if alreadyClosed then action else pure ()

-- | Shut down the switch.
-- Stops background services, cancels accept loops, closes listeners, and
-- tears down all pooled connections.
switchClose :: Switch -> IO ()
switchClose :: Switch -> IO ()
switchClose Switch
sw = do
  (actions, listeners) <- STM ([IO ()], [ActiveListener]) -> IO ([IO ()], [ActiveListener])
forall a. STM a -> IO a
atomically (STM ([IO ()], [ActiveListener]) -> IO ([IO ()], [ActiveListener]))
-> STM ([IO ()], [ActiveListener])
-> IO ([IO ()], [ActiveListener])
forall a b. (a -> b) -> a -> b
$ do
    registeredActions <- TVar [IO ()] -> STM [IO ()]
forall a. TVar a -> STM a
readTVar (Switch -> TVar [IO ()]
swShutdownActions Switch
sw)
    writeTVar (swShutdownActions sw) []
    ls <- readTVar (swListeners sw)
    writeTVar (swListeners sw) []
    writeTVar (swClosed sw) True
    pure (registeredActions, ls)
  mapM_ runShutdownAction actions
  -- Cancel accept loops and close listeners outside STM
  mapM_ closeListener listeners
  -- Tear down every pooled connection (pool removal, resource release,
  -- muxer close, transport close)
  closeAllConnections sw
  where
    runShutdownAction :: IO () -> IO ()
runShutdownAction IO ()
action =
      IO ()
action 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 ())
    closeListener :: ActiveListener -> IO ()
closeListener ActiveListener
al = do
      Async () -> IO ()
forall a. Async a -> IO ()
cancel (ActiveListener -> Async ()
alAcceptLoop ActiveListener
al) 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 ())
      Listener -> IO ()
listenerClose (ActiveListener -> Listener
alListener ActiveListener
al) 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 ())