module LibP2P.NAT.AutoNAT.Service (
AutoNATClientConfig (..),
defaultAutoNATClientConfig,
AutoNATClientService,
startAutoNATClient,
autoNATClientStatus,
stopAutoNATClient,
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.STM (
TVar,
atomically,
newTVarIO,
readTVar,
writeTVar,
)
import Control.Exception (
SomeAsyncException,
SomeException,
bracket,
fromException,
tryJust,
)
import Control.Monad (filterM, forever)
import Data.List (sortOn)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Multiaddr (Multiaddr, isRelayedAddr)
import LibP2P.MultistreamSelect.Negotiation (
NegotiationResult (..),
closeQuietly,
negotiateInitiator,
)
import LibP2P.NAT.AutoNAT (
NATStatus (..),
probeNATStatusPure,
requestAutoNAT,
)
import LibP2P.NAT.AutoNAT.Message (
AutoNATDialResponse,
autoNATProtocolId,
)
import LibP2P.Switch (registerSwitchShutdownAction)
import LibP2P.Switch.ConnPool (allConns)
import LibP2P.Switch.Connection (newStream)
import LibP2P.Switch.Listen (switchListenAddrs)
import LibP2P.Switch.Types (
ConnState (..),
Connection (..),
Switch (..),
)
import System.Timeout (timeout)
data AutoNATClientConfig = AutoNATClientConfig
{ AutoNATClientConfig -> Int
ancThreshold :: !Int
, AutoNATClientConfig -> Int
ancBootDelayMicros :: !Int
, AutoNATClientConfig -> Int
ancRetryIntervalMicros :: !Int
, AutoNATClientConfig -> Int
ancRefreshIntervalMicros :: !Int
, AutoNATClientConfig -> Int
ancRequestTimeoutMicros :: !Int
, AutoNATClientConfig -> Int
ancPeerThrottleMicros :: !Int
, AutoNATClientConfig -> Int
ancMaxPeers :: !Int
}
deriving (Int -> AutoNATClientConfig -> ShowS
[AutoNATClientConfig] -> ShowS
AutoNATClientConfig -> String
(Int -> AutoNATClientConfig -> ShowS)
-> (AutoNATClientConfig -> String)
-> ([AutoNATClientConfig] -> ShowS)
-> Show AutoNATClientConfig
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AutoNATClientConfig -> ShowS
showsPrec :: Int -> AutoNATClientConfig -> ShowS
$cshow :: AutoNATClientConfig -> String
show :: AutoNATClientConfig -> String
$cshowList :: [AutoNATClientConfig] -> ShowS
showList :: [AutoNATClientConfig] -> ShowS
Show, AutoNATClientConfig -> AutoNATClientConfig -> Bool
(AutoNATClientConfig -> AutoNATClientConfig -> Bool)
-> (AutoNATClientConfig -> AutoNATClientConfig -> Bool)
-> Eq AutoNATClientConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
== :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
$c/= :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
/= :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
Eq)
defaultAutoNATClientConfig :: AutoNATClientConfig
defaultAutoNATClientConfig :: AutoNATClientConfig
defaultAutoNATClientConfig =
AutoNATClientConfig
{ ancThreshold :: Int
ancThreshold = Int
3
, ancBootDelayMicros :: Int
ancBootDelayMicros = Int
15 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
, ancRetryIntervalMicros :: Int
ancRetryIntervalMicros = Int
90 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
, ancRefreshIntervalMicros :: Int
ancRefreshIntervalMicros = Int
15 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
minute
, ancRequestTimeoutMicros :: Int
ancRequestTimeoutMicros = Int
30 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
, ancPeerThrottleMicros :: Int
ancPeerThrottleMicros = Int
90 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
, ancMaxPeers :: Int
ancMaxPeers = Int
4
}
where
second :: Int
second = Int
1000000
minute :: Int
minute = Int
60 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
data AutoNATClientService = AutoNATClientService
{ AutoNATClientService -> TVar NATStatus
acsStatus :: !(TVar NATStatus)
, AutoNATClientService -> Async ()
acsWorker :: !(Async ())
}
startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService
startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService
startAutoNATClient Switch
sw AutoNATClientConfig
config = do
AutoNATClientConfig -> IO ()
validateConfig AutoNATClientConfig
config
status <- NATStatus -> IO (TVar NATStatus)
forall a. a -> IO (TVar a)
newTVarIO NATStatus
NATUnknown
recent <- newTVarIO Map.empty
worker <- async (clientLoop sw config status recent)
let service = TVar NATStatus -> Async () -> AutoNATClientService
AutoNATClientService TVar NATStatus
status Async ()
worker
registerSwitchShutdownAction sw (stopAutoNATClient service)
pure service
autoNATClientStatus :: AutoNATClientService -> IO NATStatus
autoNATClientStatus :: AutoNATClientService -> IO NATStatus
autoNATClientStatus AutoNATClientService
service = STM NATStatus -> IO NATStatus
forall a. STM a -> IO a
atomically (STM NATStatus -> IO NATStatus) -> STM NATStatus -> IO NATStatus
forall a b. (a -> b) -> a -> b
$ TVar NATStatus -> STM NATStatus
forall a. TVar a -> STM a
readTVar (AutoNATClientService -> TVar NATStatus
acsStatus AutoNATClientService
service)
stopAutoNATClient :: AutoNATClientService -> IO ()
stopAutoNATClient :: AutoNATClientService -> IO ()
stopAutoNATClient = Async () -> IO ()
forall a. Async a -> IO ()
cancel (Async () -> IO ())
-> (AutoNATClientService -> Async ())
-> AutoNATClientService
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AutoNATClientService -> Async ()
acsWorker
validateConfig :: AutoNATClientConfig -> IO ()
validateConfig :: AutoNATClientConfig -> IO ()
validateConfig AutoNATClientConfig
config
| AutoNATClientConfig -> Int
ancThreshold AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"threshold must be non-negative"
| AutoNATClientConfig -> Int
ancBootDelayMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"boot delay must be non-negative"
| AutoNATClientConfig -> Int
ancRetryIntervalMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"retry interval must be non-negative"
| AutoNATClientConfig -> Int
ancRefreshIntervalMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"refresh interval must be non-negative"
| AutoNATClientConfig -> Int
ancRequestTimeoutMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"request timeout must be positive"
| AutoNATClientConfig -> Int
ancPeerThrottleMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"peer throttle must be non-negative"
| AutoNATClientConfig -> Int
ancMaxPeers AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= AutoNATClientConfig -> Int
ancThreshold AutoNATClientConfig
config =
String -> IO ()
forall {a}. String -> IO a
invalid String
"max peers must be greater than the decision threshold"
| Bool
otherwise = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
where
invalid :: String -> IO a
invalid = IOError -> IO a
forall a. IOError -> IO a
ioError (IOError -> IO a) -> (String -> IOError) -> String -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IOError
userError (String -> IOError) -> ShowS -> String -> IOError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"invalid AutoNAT client configuration: " String -> ShowS
forall a. [a] -> [a] -> [a]
++)
clientLoop ::
Switch ->
AutoNATClientConfig ->
TVar NATStatus ->
TVar (Map.Map PeerId UTCTime) ->
IO ()
clientLoop :: Switch
-> AutoNATClientConfig
-> TVar NATStatus
-> TVar (Map PeerId UTCTime)
-> IO ()
clientLoop Switch
sw AutoNATClientConfig
config TVar NATStatus
status TVar (Map PeerId UTCTime)
recent = do
Int -> IO ()
threadDelay (AutoNATClientConfig -> Int
ancBootDelayMicros AutoNATClientConfig
config)
IO () -> IO ()
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
result <- Switch
-> AutoNATClientConfig -> TVar (Map PeerId UTCTime) -> IO NATStatus
runProbeCycle Switch
sw AutoNATClientConfig
config TVar (Map PeerId UTCTime)
recent
atomically $ writeTVar status result
threadDelay $ case result of
NATStatus
NATUnknown -> AutoNATClientConfig -> Int
ancRetryIntervalMicros AutoNATClientConfig
config
NATStatus
_ -> AutoNATClientConfig -> Int
ancRefreshIntervalMicros AutoNATClientConfig
config
runProbeCycle ::
Switch ->
AutoNATClientConfig ->
TVar (Map.Map PeerId UTCTime) ->
IO NATStatus
runProbeCycle :: Switch
-> AutoNATClientConfig -> TVar (Map PeerId UTCTime) -> IO NATStatus
runProbeCycle Switch
sw AutoNATClientConfig
config TVar (Map PeerId UTCTime)
recentVar = do
now <- IO UTCTime
getCurrentTime
connections <- connectedProbeCandidates sw
recent <- atomically $ readTVar recentVar
let oldestFirst = (Connection -> Maybe UTCTime) -> [Connection] -> [Connection]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\Connection
conn -> PeerId -> Map PeerId UTCTime -> Maybe UTCTime
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Connection -> PeerId
connPeerId Connection
conn) Map PeerId UTCTime
recent) [Connection]
connections
eligible =
Int -> [Connection] -> [Connection]
forall a. Int -> [a] -> [a]
take
(AutoNATClientConfig -> Int
ancMaxPeers AutoNATClientConfig
config)
((Connection -> Bool) -> [Connection] -> [Connection]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Connection -> Bool) -> Connection -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AutoNATClientConfig
-> UTCTime -> Map PeerId UTCTime -> PeerId -> Bool
throttled AutoNATClientConfig
config UTCTime
now Map PeerId UTCTime
recent (PeerId -> Bool) -> (Connection -> PeerId) -> Connection -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Connection -> PeerId
connPeerId) [Connection]
oldestFirst)
updated = (Connection -> Map PeerId UTCTime -> Map PeerId UTCTime)
-> Map PeerId UTCTime -> [Connection] -> Map PeerId UTCTime
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\Connection
conn -> PeerId -> UTCTime -> Map PeerId UTCTime -> Map PeerId UTCTime
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (Connection -> PeerId
connPeerId Connection
conn) UTCTime
now) Map PeerId UTCTime
recent [Connection]
eligible
connectedPeers = [PeerId] -> Set PeerId
forall a. Ord a => [a] -> Set a
Set.fromList ((Connection -> PeerId) -> [Connection] -> [PeerId]
forall a b. (a -> b) -> [a] -> [b]
map Connection -> PeerId
connPeerId [Connection]
connections)
atomically $ writeTVar recentVar (Map.restrictKeys updated connectedPeers)
addrs <- switchListenAddrs sw
results <- mapM (probePeer sw config addrs) eligible
pure (probeNATStatusPure (ancThreshold config) results)
connectedProbeCandidates :: Switch -> IO [Connection]
connectedProbeCandidates :: Switch -> IO [Connection]
connectedProbeCandidates Switch
sw = 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
$ do
connections <- TVar (Map PeerId [Connection]) -> STM [Connection]
allConns (Switch -> TVar (Map PeerId [Connection])
swConnPool Switch
sw)
openDirect <- filterM isOpenDirect connections
pure (Map.elems (Map.fromList [(connPeerId conn, conn) | conn <- openDirect]))
where
isOpenDirect :: Connection -> STM Bool
isOpenDirect Connection
conn = do
state <- TVar ConnState -> STM ConnState
forall a. TVar a -> STM a
readTVar (Connection -> TVar ConnState
connState Connection
conn)
pure (state == ConnOpen && not (isRelayedAddr (connRemoteAddr conn)))
probePeer ::
Switch ->
AutoNATClientConfig ->
[Multiaddr] ->
Connection ->
IO (Either String AutoNATDialResponse)
probePeer :: Switch
-> AutoNATClientConfig
-> [Multiaddr]
-> Connection
-> IO (Either String AutoNATDialResponse)
probePeer Switch
sw AutoNATClientConfig
config [Multiaddr]
addrs Connection
conn = do
outcome <- (SomeException -> Maybe SomeException)
-> IO (Maybe (Either String AutoNATDialResponse))
-> IO
(Either SomeException (Maybe (Either String AutoNATDialResponse)))
forall e b a.
Exception e =>
(e -> Maybe b) -> IO a -> IO (Either b a)
tryJust SomeException -> Maybe SomeException
synchronousException (IO (Maybe (Either String AutoNATDialResponse))
-> IO
(Either SomeException (Maybe (Either String AutoNATDialResponse))))
-> IO (Maybe (Either String AutoNATDialResponse))
-> IO
(Either SomeException (Maybe (Either String AutoNATDialResponse)))
forall a b. (a -> b) -> a -> b
$ Int
-> IO (Either String AutoNATDialResponse)
-> IO (Maybe (Either String AutoNATDialResponse))
forall a. Int -> IO a -> IO (Maybe a)
timeout (AutoNATClientConfig -> Int
ancRequestTimeoutMicros AutoNATClientConfig
config) (IO (Either String AutoNATDialResponse)
-> IO (Maybe (Either String AutoNATDialResponse)))
-> IO (Either String AutoNATDialResponse)
-> IO (Maybe (Either String AutoNATDialResponse))
forall a b. (a -> b) -> a -> b
$ do
opened <- Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream Switch
sw Connection
conn
case opened of
Left StreamOpenError
err -> Either String AutoNATDialResponse
-> IO (Either String AutoNATDialResponse)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left (StreamOpenError -> String
forall a. Show a => a -> String
show StreamOpenError
err))
Right StreamIO
stream -> IO StreamIO
-> (StreamIO -> IO ())
-> (StreamIO -> IO (Either String AutoNATDialResponse))
-> IO (Either String AutoNATDialResponse)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (StreamIO -> IO StreamIO
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure StreamIO
stream) StreamIO -> IO ()
closeQuietly ((StreamIO -> IO (Either String AutoNATDialResponse))
-> IO (Either String AutoNATDialResponse))
-> (StreamIO -> IO (Either String AutoNATDialResponse))
-> IO (Either String AutoNATDialResponse)
forall a b. (a -> b) -> a -> b
$ \StreamIO
openedStream -> do
negotiated <- StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiateInitiator StreamIO
openedStream [ProtocolId
autoNATProtocolId]
case negotiated of
NegotiationResult
NoProtocol -> Either String AutoNATDialResponse
-> IO (Either String AutoNATDialResponse)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left String
"peer does not support AutoNAT v1")
Accepted ProtocolId
_ -> StreamIO
-> PeerId -> [Multiaddr] -> IO (Either String AutoNATDialResponse)
requestAutoNAT StreamIO
openedStream (Switch -> PeerId
swLocalPeerId Switch
sw) [Multiaddr]
addrs
pure $ case outcome of
Left (SomeException
err :: SomeException) -> String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left (SomeException -> String
forall a. Show a => a -> String
show SomeException
err)
Right Maybe (Either String AutoNATDialResponse)
Nothing -> String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left String
"AutoNAT request timed out"
Right (Just Either String AutoNATDialResponse
result) -> Either String AutoNATDialResponse
result
throttled ::
AutoNATClientConfig ->
UTCTime ->
Map.Map PeerId UTCTime ->
PeerId ->
Bool
throttled :: AutoNATClientConfig
-> UTCTime -> Map PeerId UTCTime -> PeerId -> Bool
throttled AutoNATClientConfig
config UTCTime
now Map PeerId UTCTime
recent PeerId
peerId =
case PeerId -> Map PeerId UTCTime -> Maybe UTCTime
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
peerId Map PeerId UTCTime
recent of
Maybe UTCTime
Nothing -> Bool
False
Just UTCTime
probedAt -> UTCTime -> UTCTime -> Int
elapsedMicros UTCTime
now UTCTime
probedAt Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< AutoNATClientConfig -> Int
ancPeerThrottleMicros AutoNATClientConfig
config
synchronousException :: SomeException -> Maybe SomeException
synchronousException :: SomeException -> Maybe SomeException
synchronousException SomeException
err = case SomeException -> Maybe SomeAsyncException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
err :: Maybe SomeAsyncException of
Just SomeAsyncException
_ -> Maybe SomeException
forall a. Maybe a
Nothing
Maybe SomeAsyncException
Nothing -> SomeException -> Maybe SomeException
forall a. a -> Maybe a
Just SomeException
err
elapsedMicros :: UTCTime -> UTCTime -> Int
elapsedMicros :: UTCTime -> UTCTime -> Int
elapsedMicros UTCTime
later UTCTime
earlier = Double -> Int
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor (NominalDiffTime -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac (UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
later UTCTime
earlier) Double -> Double -> Double
forall a. Num a => a -> a -> a
* (Double
1000000 :: Double))