-- | Keep configured GossipSub direct peers connected.
--
-- gossipsub-v1.1.md explicit peering: the router establishes a connection
-- to every configured direct peer and re-establishes it when it drops.
-- Addresses come from the Switch (certified record, else Identify listen
-- addresses). A peer with no stored addresses is skipped. Dialling goes
-- through 'LibP2P.Switch.Dial.dial', so backoff, deduplication, gating,
-- and the resource manager apply. This is not peer exchange: PX peers
-- are untrusted advertisements, direct peers are configured agreements.
module LibP2P.Protocol.GossipSub.DirectConnect
  ( DirectDialSlots
  , newDirectDialSlots
  , connectMissingDirectPeers
  , reconnectDirectPeer
  , runDirectConnectLoop
  , cancelDirectDials
  ) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.STM
  ( TVar
  , atomically
  , modifyTVar'
  , newTVarIO
  , readTVar
  , readTVarIO
  , writeTVar
  )
import Control.Exception (SomeException, catch, finally)
import Control.Monad (unless, void, when)
import Data.ByteString (ByteString)
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust, mapMaybe)
import qualified Data.Set as Set
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Multiaddr (Multiaddr, fromBytes)
import LibP2P.Protocol.GossipSub.Types
  ( GossipSubParams (..)
  , GossipSubRouter (..)
  )
import LibP2P.Protocol.Identify.Message (IdentifyInfo (..))
import LibP2P.Switch.CertifiedRecords (CertifiedRecord (..), lookupCertifiedRecord)
import LibP2P.Switch.ConnPool (lookupConn)
import LibP2P.Switch.Dial (checkBackoff, dial)
import LibP2P.Switch.Types (Switch (..))

-- | In-flight direct dials. 'Nothing' is a claim that a worker is about
-- to start, so a second wake cannot spawn another one.
newtype DirectDialSlots = DirectDialSlots (TVar (Map.Map PeerId (Maybe (Async ()))))

newDirectDialSlots :: IO DirectDialSlots
newDirectDialSlots :: IO DirectDialSlots
newDirectDialSlots = TVar (Map PeerId (Maybe (Async ()))) -> DirectDialSlots
DirectDialSlots (TVar (Map PeerId (Maybe (Async ()))) -> DirectDialSlots)
-> IO (TVar (Map PeerId (Maybe (Async ())))) -> IO DirectDialSlots
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map PeerId (Maybe (Async ()))
-> IO (TVar (Map PeerId (Maybe (Async ()))))
forall a. a -> IO (TVar a)
newTVarIO Map PeerId (Maybe (Async ()))
forall k a. Map k a
Map.empty

-- | Dial every configured direct peer that is down and has stored addresses.
connectMissingDirectPeers :: Switch -> GossipSubRouter -> DirectDialSlots -> IO ()
connectMissingDirectPeers :: Switch -> GossipSubRouter -> DirectDialSlots -> IO ()
connectMissingDirectPeers Switch
sw GossipSubRouter
router DirectDialSlots
slots =
  (PeerId -> IO ()) -> [PeerId] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Switch -> GossipSubRouter -> DirectDialSlots -> PeerId -> IO ()
reconnectDirectPeer Switch
sw GossipSubRouter
router DirectDialSlots
slots) (Set PeerId -> [PeerId]
forall a. Set a -> [a]
Set.toList (GossipSubParams -> Set PeerId
paramDirectPeers (GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router)))

-- | Dial one direct peer if it is configured, down, and addressable.
-- A non-direct peer is ignored, so a PX disconnect cannot enter this path.
reconnectDirectPeer :: Switch -> GossipSubRouter -> DirectDialSlots -> PeerId -> IO ()
reconnectDirectPeer :: Switch -> GossipSubRouter -> DirectDialSlots -> PeerId -> IO ()
reconnectDirectPeer Switch
sw GossipSubRouter
router DirectDialSlots
slots PeerId
pid
  | Bool -> Bool
not (PeerId -> Set PeerId -> Bool
forall a. Ord a => a -> Set a -> Bool
Set.member PeerId
pid (GossipSubParams -> Set PeerId
paramDirectPeers (GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router))) = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  | Bool
otherwise = do
      closed <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO (Switch -> TVar Bool
swClosed Switch
sw)
      unless closed $ do
        skip <- shouldSkip sw pid
        unless skip $ do
          addrs <- storedAddrs sw pid
          case nonEmpty addrs of
            Maybe [Multiaddr]
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
            Just [Multiaddr]
dialable -> Switch -> DirectDialSlots -> PeerId -> [Multiaddr] -> IO ()
spawnDial Switch
sw DirectDialSlots
slots PeerId
pid [Multiaddr]
dialable

-- | Initial pass, then one pass per 'paramDirectConnectInterval', until
-- 'started' is false. An interval of 0 runs the initial pass only.
runDirectConnectLoop
  :: Switch -> GossipSubRouter -> TVar Bool -> DirectDialSlots -> IO ()
runDirectConnectLoop :: Switch -> GossipSubRouter -> TVar Bool -> DirectDialSlots -> IO ()
runDirectConnectLoop Switch
sw GossipSubRouter
router TVar Bool
started DirectDialSlots
slots = IO ()
loop
  where
    loop :: IO ()
loop = do
      alive <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO TVar Bool
started
      when alive $ do
        connectMissingDirectPeers sw router slots
        let interval = GossipSubParams -> NominalDiffTime
paramDirectConnectInterval (GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router)
        when (interval > 0) $ do
          threadDelay (nominalToMicros interval)
          loop

-- | Cancel workers claimed by a slot map. Idempotent.
cancelDirectDials :: DirectDialSlots -> IO ()
cancelDirectDials :: DirectDialSlots -> IO ()
cancelDirectDials (DirectDialSlots TVar (Map PeerId (Maybe (Async ())))
var) = do
  workers <- STM (Map PeerId (Maybe (Async ())))
-> IO (Map PeerId (Maybe (Async ())))
forall a. STM a -> IO a
atomically (STM (Map PeerId (Maybe (Async ())))
 -> IO (Map PeerId (Maybe (Async ()))))
-> STM (Map PeerId (Maybe (Async ())))
-> IO (Map PeerId (Maybe (Async ())))
forall a b. (a -> b) -> a -> b
$ do
    current <- TVar (Map PeerId (Maybe (Async ())))
-> STM (Map PeerId (Maybe (Async ())))
forall a. TVar a -> STM a
readTVar TVar (Map PeerId (Maybe (Async ())))
var
    writeTVar var Map.empty
    pure current
  mapM_ cancelQuiet (Map.elems workers)

shouldSkip :: Switch -> PeerId -> IO Bool
shouldSkip :: Switch -> PeerId -> IO Bool
shouldSkip Switch
sw PeerId
pid = do
  connected <- Maybe Connection -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Connection -> Bool) -> IO (Maybe Connection) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> STM (Maybe Connection) -> IO (Maybe Connection)
forall a. STM a -> IO a
atomically (TVar (Map PeerId [Connection]) -> PeerId -> STM (Maybe Connection)
lookupConn (Switch -> TVar (Map PeerId [Connection])
swConnPool Switch
sw) PeerId
pid)
  blocked <- checkBackoff (swDialBackoffs sw) pid
  pure $ connected || isLeft blocked

spawnDial :: Switch -> DirectDialSlots -> PeerId -> [Multiaddr] -> IO ()
spawnDial :: Switch -> DirectDialSlots -> PeerId -> [Multiaddr] -> IO ()
spawnDial Switch
sw DirectDialSlots
slots PeerId
pid [Multiaddr]
addrs = do
  claimed <- DirectDialSlots -> PeerId -> IO Bool
claim DirectDialSlots
slots PeerId
pid
  when claimed $ do
    worker <- async $
      void (dial sw pid addrs) `finally` release slots pid
    record slots pid worker

claim :: DirectDialSlots -> PeerId -> IO Bool
claim :: DirectDialSlots -> PeerId -> IO Bool
claim (DirectDialSlots TVar (Map PeerId (Maybe (Async ())))
var) PeerId
pid = 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
  current <- TVar (Map PeerId (Maybe (Async ())))
-> STM (Map PeerId (Maybe (Async ())))
forall a. TVar a -> STM a
readTVar TVar (Map PeerId (Maybe (Async ())))
var
  if Map.member pid current
    then pure False
    else writeTVar var (Map.insert pid Nothing current) >> pure True

record :: DirectDialSlots -> PeerId -> Async () -> IO ()
record :: DirectDialSlots -> PeerId -> Async () -> IO ()
record (DirectDialSlots TVar (Map PeerId (Maybe (Async ())))
var) PeerId
pid Async ()
worker = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
  TVar (Map PeerId (Maybe (Async ())))
-> (Map PeerId (Maybe (Async ())) -> Map PeerId (Maybe (Async ())))
-> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' TVar (Map PeerId (Maybe (Async ())))
var ((Map PeerId (Maybe (Async ())) -> Map PeerId (Maybe (Async ())))
 -> STM ())
-> (Map PeerId (Maybe (Async ())) -> Map PeerId (Maybe (Async ())))
-> STM ()
forall a b. (a -> b) -> a -> b
$ \Map PeerId (Maybe (Async ()))
current ->
    if PeerId -> Map PeerId (Maybe (Async ())) -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member PeerId
pid Map PeerId (Maybe (Async ()))
current
      then PeerId
-> Maybe (Async ())
-> Map PeerId (Maybe (Async ()))
-> Map PeerId (Maybe (Async ()))
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert PeerId
pid (Async () -> Maybe (Async ())
forall a. a -> Maybe a
Just Async ()
worker) Map PeerId (Maybe (Async ()))
current
      else Map PeerId (Maybe (Async ()))
current

release :: DirectDialSlots -> PeerId -> IO ()
release :: DirectDialSlots -> PeerId -> IO ()
release (DirectDialSlots TVar (Map PeerId (Maybe (Async ())))
var) PeerId
pid = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
  TVar (Map PeerId (Maybe (Async ())))
-> (Map PeerId (Maybe (Async ())) -> Map PeerId (Maybe (Async ())))
-> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' TVar (Map PeerId (Maybe (Async ())))
var (PeerId
-> Map PeerId (Maybe (Async ())) -> Map PeerId (Maybe (Async ()))
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete PeerId
pid)

storedAddrs :: Switch -> PeerId -> IO [Multiaddr]
storedAddrs :: Switch -> PeerId -> IO [Multiaddr]
storedAddrs Switch
sw PeerId
pid = do
  raw <- STM [ByteString] -> IO [ByteString]
forall a. STM a -> IO a
atomically (STM [ByteString] -> IO [ByteString])
-> STM [ByteString] -> IO [ByteString]
forall a b. (a -> b) -> a -> b
$ do
    certified <- TVar (Map PeerId CertifiedRecord)
-> PeerId -> STM (Maybe CertifiedRecord)
lookupCertifiedRecord (Switch -> TVar (Map PeerId CertifiedRecord)
swCertifiedRecords Switch
sw) PeerId
pid
    case certified of
      Just CertifiedRecord
record -> [ByteString] -> STM [ByteString]
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CertifiedRecord -> [ByteString]
crAddresses CertifiedRecord
record)
      Maybe CertifiedRecord
Nothing -> do
        store <- TVar (Map PeerId IdentifyInfo) -> STM (Map PeerId IdentifyInfo)
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map PeerId IdentifyInfo)
swPeerStore Switch
sw)
        pure $ maybe [] idListenAddrs (Map.lookup pid store)
  pure $ mapMaybe (either (const Nothing) Just . fromBytes) raw

cancelQuiet :: Maybe (Async ()) -> IO ()
cancelQuiet :: Maybe (Async ()) -> IO ()
cancelQuiet Maybe (Async ())
Nothing = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
cancelQuiet (Just Async ()
worker) =
  Async () -> IO ()
forall a. Async a -> IO ()
cancel Async ()
worker 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 ()

nominalToMicros :: RealFrac a => a -> Int
nominalToMicros :: forall a. RealFrac a => a -> Int
nominalToMicros a
interval = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (a -> Int
forall b. Integral b => a -> b
forall a b. (RealFrac a, Integral b) => a -> b
round (a
interval a -> a -> a
forall a. Num a => a -> a -> a
* a
1000000))

nonEmpty :: [a] -> Maybe [a]
nonEmpty :: forall a. [a] -> Maybe [a]
nonEmpty [] = Maybe [a]
forall a. Maybe a
Nothing
nonEmpty [a]
xs = [a] -> Maybe [a]
forall a. a -> Maybe a
Just [a]
xs

isLeft :: Either e a -> Bool
isLeft :: forall e a. Either e a -> Bool
isLeft (Left e
_) = Bool
True
isLeft (Right a
_) = Bool
False