{- | Rendezvous protocol (specs/rendezvous/README.md), protocol id
/rendezvous/1.0.0.

Peers connect to a rendezvous point and register their presence in
one or more namespaces with a signed peer record (RFC 0003, see
\"LibP2P.Crypto.PeerRecord\"); other peers discover registrations by
namespace with cookie-based pagination for progressive refresh.

This module implements both sides:

  * server — 'registerRendezvousPoint' registers a stream handler on
    the Switch, turning this node into a rendezvous point.
    Registrations carry signed peer record envelopes, expire by TTL,
    and are bounded by the rendezvous-point recommendations
    (namespace length, TTL range, per-peer and per-query limits).
    Only the peer initiating a registration may register itself.
  * client — 'registerSelf', 'unregisterSelf' and 'discover' operate
    over an existing connection to a rendezvous point.

On the wire every message is varint-length-delimited protobuf
(uvarint(len) ++ protobuf), the framing go-libp2p, rust-libp2p and
js-libp2p use for rendezvous streams, and the same framing this
codebase uses for Identify.
-}
module LibP2P.Discovery.Rendezvous (
  -- * Types
  RendezvousPoint,
  RendezvousConfig (..),
  defaultRendezvousConfig,
  RendezvousError (..),

  -- * Events
  DiscoveryEvent (..),
  newDiscoveryQueue,
  tryReadDiscoveryQueue,
  drainDiscoveryQueue,

  -- * Server (rendezvous point)
  newRendezvousPoint,
  registerRendezvousPoint,
  handleRendezvousStream,
  registeredCount,

  -- * Client
  rendezvousProtocolId,
  rendezvousTimeoutMicros,
  registerSelf,
  unregisterSelf,
  discover,
  inspectRegistration,
  pushDiscoverEvents,

  -- * Wire framing
  encodeFramedMessage,
  readFramedMessage,
) where

import Control.Concurrent.STM (
  TQueue,
  TVar,
  atomically,
  newTVarIO,
  readTVar,
  readTVarIO,
  writeTQueue,
  writeTVar,
 )
import Control.Exception (SomeException, bracket, finally, try)
import Control.Monad (forM_)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.List (sortBy)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe, maybeToList)
import Data.Ord (comparing)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time.Clock (UTCTime, addUTCTime, getCurrentTime)
import Data.Word (Word64, Word8)
import LibP2P.Core.Varint (decodeUvarint, encodeUvarint)
import LibP2P.Crypto.PeerId (PeerId (..), peerIdBytes)
import LibP2P.Crypto.PeerRecord (
  PeerRecord (..),
  openPeerRecordEnvelope,
  sealPeerRecord,
  timestampSeq,
 )
import LibP2P.Crypto.SignedEnvelope (encodeSignedEnvelope)
import LibP2P.Discovery.Rendezvous.Message (
  DiscoverLimit (..),
  RegistrationInfo (..),
  RendezvousMessage (..),
  ResponseStatus (..),
  decodeRendezvousMessage,
  encodeRendezvousMessage,
  maxRendezvousMessageSize,
 )
import LibP2P.Discovery.Types (
  DiscoveryEvent (..),
  drainDiscoveryQueue,
  newDiscoveryQueue,
  tryReadDiscoveryQueue,
 )
import LibP2P.Multiaddr (Multiaddr (..), fromBytes)
import LibP2P.Multiaddr.Codec (encodeProtocols)
import LibP2P.MultistreamSelect.Negotiation (
  NegotiationResult (..),
  ProtocolId,
  StreamIO (..),
  closeQuietly,
  negotiateInitiator,
  readExactBounded,
 )
import LibP2P.Switch (setStreamHandler)
import LibP2P.Switch.Connection (newStream)
import LibP2P.Switch.Types (
  ActiveListener (..),
  Connection (..),
  Switch (..),
 )
import System.Timeout (timeout)

-- | Protocol ID (specs/rendezvous/README.md §The Protocol).
rendezvousProtocolId :: ProtocolId
rendezvousProtocolId :: Text
rendezvousProtocolId = Text
"/rendezvous/1.0.0"

{- | Timeout for one rendezvous exchange: 5 seconds, the same bound as
this codebase's Identify interaction. Discovery calls are
interactive; a rendezvous point that negotiates and never answers
must not pin a stream and a thread forever.
-}
rendezvousTimeoutMicros :: Int
rendezvousTimeoutMicros :: Int
rendezvousTimeoutMicros = Int
5000000

{- | Rendezvous point configuration. Defaults follow the spec's
"Recommendations for Rendezvous Points configurations": minimum TTL
2h, maximum TTL 72h, namespace length 255, 1000 registrations per
peer, 1000 registrations returned per namespace query.
-}
data RendezvousConfig = RendezvousConfig
  { RendezvousConfig -> Word64
rcMinTTL :: !Word64
  -- ^ Minimum acceptable TTL (seconds)
  , RendezvousConfig -> Word64
rcMaxTTL :: !Word64
  -- ^ Maximum acceptable TTL (seconds); larger requests are clamped
  , RendezvousConfig -> Word64
rcDefaultTTL :: !Word64
  -- ^ TTL for registrations without one
  , RendezvousConfig -> Int
rcMaxNamespaceLength :: !Int
  -- ^ Maximum namespace length
  , RendezvousConfig -> Int
rcMaxPerPeer :: !Int
  -- ^ Maximum live registrations per peer
  , RendezvousConfig -> Int
rcMaxResults :: !Int
  -- ^ Maximum registrations per DISCOVER
  }
  deriving (Int -> RendezvousConfig -> ShowS
[RendezvousConfig] -> ShowS
RendezvousConfig -> [Char]
(Int -> RendezvousConfig -> ShowS)
-> (RendezvousConfig -> [Char])
-> ([RendezvousConfig] -> ShowS)
-> Show RendezvousConfig
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RendezvousConfig -> ShowS
showsPrec :: Int -> RendezvousConfig -> ShowS
$cshow :: RendezvousConfig -> [Char]
show :: RendezvousConfig -> [Char]
$cshowList :: [RendezvousConfig] -> ShowS
showList :: [RendezvousConfig] -> ShowS
Show, RendezvousConfig -> RendezvousConfig -> Bool
(RendezvousConfig -> RendezvousConfig -> Bool)
-> (RendezvousConfig -> RendezvousConfig -> Bool)
-> Eq RendezvousConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RendezvousConfig -> RendezvousConfig -> Bool
== :: RendezvousConfig -> RendezvousConfig -> Bool
$c/= :: RendezvousConfig -> RendezvousConfig -> Bool
/= :: RendezvousConfig -> RendezvousConfig -> Bool
Eq)

defaultRendezvousConfig :: RendezvousConfig
defaultRendezvousConfig :: RendezvousConfig
defaultRendezvousConfig =
  RendezvousConfig
    { rcMinTTL :: Word64
rcMinTTL = Word64
2 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
3600 -- 2h
    , rcMaxTTL :: Word64
rcMaxTTL = Word64
72 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
3600 -- 72h
    , rcDefaultTTL :: Word64
rcDefaultTTL = Word64
2 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
3600 -- 2h
    , rcMaxNamespaceLength :: Int
rcMaxNamespaceLength = Int
255
    , rcMaxPerPeer :: Int
rcMaxPerPeer = Int
1000
    , rcMaxResults :: Int
rcMaxResults = Int
1000
    }

{- | A live registration: the signed peer record envelope as received,
the TTL it was granted, when it expires, and the rendezvous point's
version at the time it was (last) written. The version is the
substance of the discovery cookie: a DISCOVER carrying a cookie from
a previous response only returns registrations written since
(specs/rendezvous §The Protocol).
-}
data Registration = Registration
  { Registration -> ByteString
regRecord :: !ByteString
  -- ^ Signed peer-record envelope
  , Registration -> Word64
regTTL :: !Word64
  -- ^ Granted TTL in seconds
  , Registration -> UTCTime
regExpires :: !UTCTime
  , Registration -> Word64
regVersion :: !Word64
  -- ^ Version counter value at write time
  }
  deriving (Registration -> Registration -> Bool
(Registration -> Registration -> Bool)
-> (Registration -> Registration -> Bool) -> Eq Registration
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Registration -> Registration -> Bool
== :: Registration -> Registration -> Bool
$c/= :: Registration -> Registration -> Bool
/= :: Registration -> Registration -> Bool
Eq)

instance Show Registration where
  show :: Registration -> [Char]
show Registration
r =
    [Char]
"Registration {regTTL = "
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> Word64 -> [Char]
forall a. Show a => a -> [Char]
show (Registration -> Word64
regTTL Registration
r)
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> [Char]
", regVersion = "
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> Word64 -> [Char]
forall a. Show a => a -> [Char]
show (Registration -> Word64
regVersion Registration
r)
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> [Char]
", regRecord = "
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> Int -> [Char]
forall a. Show a => a -> [Char]
show (ByteString -> Int
BS.length (Registration -> ByteString
regRecord Registration
r))
      [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> [Char]
" bytes}"

-- | The rendezvous point's mutable state.
data RendezvousPoint = RendezvousPoint
  { RendezvousPoint -> RendezvousConfig
rvConfig :: !RendezvousConfig
  , RendezvousPoint -> TVar (Map Text (Map PeerId Registration))
rvRegs :: !(TVar (Map Text (Map PeerId Registration)))
  {- ^ Registrations per namespace, the inner map keyed by the
  registered peer id
  -}
  , RendezvousPoint -> TVar Word64
rvVersion :: !(TVar Word64)
  -- ^ Monotonic registration counter
  }

{- | Client-side failure. Rejections carry the rendezvous point's
status ('LibP2P.Discovery.Rendezvous.Message.ResponseStatus') so the
application can distinguish, say, an invalid TTL from an
unauthorized registration.
-}
data RendezvousError
  = -- | No answer within the exchange timeout
    RendezvousTimeout
  | -- | Stream/negotiation failure
    RendezvousTransport !String
  | -- | Rendezvous point rejected the request, with its status text
    RendezvousRejected !ResponseStatus !(Maybe Text)
  | -- | Malformed response
    RendezvousDecode !String
  deriving (Int -> RendezvousError -> ShowS
[RendezvousError] -> ShowS
RendezvousError -> [Char]
(Int -> RendezvousError -> ShowS)
-> (RendezvousError -> [Char])
-> ([RendezvousError] -> ShowS)
-> Show RendezvousError
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RendezvousError -> ShowS
showsPrec :: Int -> RendezvousError -> ShowS
$cshow :: RendezvousError -> [Char]
show :: RendezvousError -> [Char]
$cshowList :: [RendezvousError] -> ShowS
showList :: [RendezvousError] -> ShowS
Show, RendezvousError -> RendezvousError -> Bool
(RendezvousError -> RendezvousError -> Bool)
-> (RendezvousError -> RendezvousError -> Bool)
-> Eq RendezvousError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RendezvousError -> RendezvousError -> Bool
== :: RendezvousError -> RendezvousError -> Bool
$c/= :: RendezvousError -> RendezvousError -> Bool
/= :: RendezvousError -> RendezvousError -> Bool
Eq)

--------------------------------------------------------------------------------
-- Server
--------------------------------------------------------------------------------

-- | Create an in-memory rendezvous point.
newRendezvousPoint :: RendezvousConfig -> IO RendezvousPoint
newRendezvousPoint :: RendezvousConfig -> IO RendezvousPoint
newRendezvousPoint RendezvousConfig
cfg =
  RendezvousConfig
-> TVar (Map Text (Map PeerId Registration))
-> TVar Word64
-> RendezvousPoint
RendezvousPoint RendezvousConfig
cfg (TVar (Map Text (Map PeerId Registration))
 -> TVar Word64 -> RendezvousPoint)
-> IO (TVar (Map Text (Map PeerId Registration)))
-> IO (TVar Word64 -> RendezvousPoint)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map Text (Map PeerId Registration)
-> IO (TVar (Map Text (Map PeerId Registration)))
forall a. a -> IO (TVar a)
newTVarIO Map Text (Map PeerId Registration)
forall k a. Map k a
Map.empty IO (TVar Word64 -> RendezvousPoint)
-> IO (TVar Word64) -> IO RendezvousPoint
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Word64 -> IO (TVar Word64)
forall a. a -> IO (TVar a)
newTVarIO Word64
0

{- | Serve /rendezvous/1.0.0 on the Switch, making this node act as a
rendezvous point. Returns the point so callers can query state
('registeredCount') for tests and observability.
-}
registerRendezvousPoint :: Switch -> RendezvousConfig -> IO RendezvousPoint
registerRendezvousPoint :: Switch -> RendezvousConfig -> IO RendezvousPoint
registerRendezvousPoint Switch
sw RendezvousConfig
cfg = do
  point <- RendezvousConfig -> IO RendezvousPoint
newRendezvousPoint RendezvousConfig
cfg
  setStreamHandler
    sw
    rendezvousProtocolId
    (\Connection
conn StreamIO
stream -> RendezvousPoint -> StreamIO -> PeerId -> IO ()
handleRendezvousStream RendezvousPoint
point StreamIO
stream (Connection -> PeerId
connPeerId Connection
conn))
  pure point

{- | Number of currently valid registrations across all namespaces,
excluding expired ones. Expired entries are pruned lazily (on
discovery; nothing scans in the background), so 'rcMaxPerPeer'
counts live registrations: a peer that keeps re-registering a fresh
record keeps one slot per namespace.
-}
registeredCount :: RendezvousPoint -> IO Int
registeredCount :: RendezvousPoint -> IO Int
registeredCount RendezvousPoint
point = do
  now <- IO UTCTime
getCurrentTime
  regs <- readTVarIO (rvRegs point)
  pure
    ( sum
        [ 1
        | nsRegs <- Map.elems regs
        , reg <- Map.elems nsRegs
        , regExpires reg > now
        ]
    )

{- | Handle an inbound rendezvous stream (server side).

Clients open one stream per operation in practice (go-libp2p), but
the stream is a message channel: pipelined messages are served until
the stream ends. Framing or decode errors stop serving the stream; a
disconnect (EOF, reset) ends it too. Either way the local side is
closed so a half-open Yamux stream cannot leak ('handleDHTRequest'
follows the same loop shape).
-}
handleRendezvousStream :: RendezvousPoint -> StreamIO -> PeerId -> IO ()
handleRendezvousStream :: RendezvousPoint -> StreamIO -> PeerId -> IO ()
handleRendezvousStream RendezvousPoint
point StreamIO
stream PeerId
remotePeer =
  IO ()
loop IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` StreamIO -> IO ()
closeQuietly StreamIO
stream
 where
  loop :: IO ()
loop = do
    cont <- IO Bool -> IO (Either SomeException Bool)
forall e a. Exception e => IO a -> IO (Either e a)
try IO Bool
goServe
    case cont :: Either SomeException Bool of
      Right Bool
True -> IO ()
loop
      -- EOF/reset, framing or decode error, or a dead write: end the
      -- interaction. The exception never escapes; the stream is
      -- closed below.
      Either SomeException Bool
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

  goServe :: IO Bool
goServe = do
    readResult <- IO (Either [Char] RendezvousMessage)
-> IO (Either SomeException (Either [Char] RendezvousMessage))
forall e a. Exception e => IO a -> IO (Either e a)
try (StreamIO -> Int -> IO (Either [Char] RendezvousMessage)
readFramedMessage StreamIO
stream Int
maxRendezvousMessageSize)
    case readResult :: Either SomeException (Either String RendezvousMessage) of
      Left SomeException
_ -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False -- client hung up mid-message
      Right (Left [Char]
_err) -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False -- framing/decode error
      Right (Right RendezvousMessage
msg) -> do
        responses <- RendezvousPoint
-> PeerId -> RendezvousMessage -> IO [RendezvousMessage]
processMessage RendezvousPoint
point PeerId
remotePeer RendezvousMessage
msg
        -- Frame every response: a rendezvous stream is a channel of
        -- varint-length-delimited messages, and the client's framing
        -- read (readFramedMessage) consumes uvarint(len) ++ protobuf.
        all (== True) <$> mapM (writeServe stream . encodeFramedMessage) responses

  writeServe :: StreamIO -> ByteString -> IO Bool
writeServe StreamIO
st ByteString
resp = do
    outcome <- IO () -> IO (Either SomeException ())
forall e a. Exception e => IO a -> IO (Either e a)
try (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
st ByteString
resp)
    case outcome :: Either SomeException () of
      Right () -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
      Left SomeException
_ -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False

{- | Process one client message (server side); the loop frames each
response on the way out.
-}
processMessage ::
  RendezvousPoint -> PeerId -> RendezvousMessage -> IO [RendezvousMessage]
processMessage :: RendezvousPoint
-> PeerId -> RendezvousMessage -> IO [RendezvousMessage]
processMessage RendezvousPoint
point PeerId
remotePeer RendezvousMessage
msg = case RendezvousMessage
msg of
  RMRegister Text
ns ByteString
record Maybe Word64
mTTL ->
    (RendezvousMessage -> [RendezvousMessage] -> [RendezvousMessage]
forall a. a -> [a] -> [a]
: []) (RendezvousMessage -> [RendezvousMessage])
-> IO RendezvousMessage -> IO [RendezvousMessage]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RendezvousPoint
-> PeerId
-> Text
-> ByteString
-> Maybe Word64
-> IO RendezvousMessage
acceptRegistration RendezvousPoint
point PeerId
remotePeer Text
ns ByteString
record Maybe Word64
mTTL
  RMUnregister Text
ns -> do
    RendezvousPoint -> PeerId -> Text -> IO ()
unregisterRegistration RendezvousPoint
point PeerId
remotePeer Text
ns
    [RendezvousMessage] -> IO [RendezvousMessage]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [] -- no response (specs/rendezvous §Registration Lifetime)
  RMDiscover Maybe Text
ns DiscoverLimit
limit ByteString
cookie ->
    (RendezvousMessage -> [RendezvousMessage] -> [RendezvousMessage]
forall a. a -> [a] -> [a]
: []) (RendezvousMessage -> [RendezvousMessage])
-> IO RendezvousMessage -> IO [RendezvousMessage]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RendezvousPoint
-> Maybe Text
-> DiscoverLimit
-> ByteString
-> IO RendezvousMessage
handleDiscover RendezvousPoint
point Maybe Text
ns DiscoverLimit
limit ByteString
cookie
  -- REGISTER_RESPONSE / DISCOVER_RESPONSE coming from the client side
  -- are protocol violations; ignore them and keep serving the stream
  -- rather than tearing down a connection over garbage.
  RendezvousMessage
_ -> [RendezvousMessage] -> IO [RendezvousMessage]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

{- | Remove the peer's registration from a namespace. An unknown
namespace or peer is a no-op (spec: "UNREGISTER messages for a
namespace that a client is not registered for should be treated as a
no-op").
-}
unregisterRegistration :: RendezvousPoint -> PeerId -> Text -> IO ()
unregisterRegistration :: RendezvousPoint -> PeerId -> Text -> IO ()
unregisterRegistration RendezvousPoint
point PeerId
peer Text
ns = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  regs <- TVar (Map Text (Map PeerId Registration))
-> STM (Map Text (Map PeerId Registration))
forall a. TVar a -> STM a
readTVar (RendezvousPoint -> TVar (Map Text (Map PeerId Registration))
rvRegs RendezvousPoint
point)
  case Map.lookup ns regs of
    Maybe (Map PeerId Registration)
Nothing -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Just Map PeerId Registration
nsRegs ->
      TVar (Map Text (Map PeerId Registration))
-> Map Text (Map PeerId Registration) -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (RendezvousPoint -> TVar (Map Text (Map PeerId Registration))
rvRegs RendezvousPoint
point) (Text
-> Map PeerId Registration
-> Map Text (Map PeerId Registration)
-> Map Text (Map PeerId Registration)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Text
ns (PeerId -> Map PeerId Registration -> Map PeerId Registration
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete PeerId
peer Map PeerId Registration
nsRegs) Map Text (Map PeerId Registration)
regs)

{- | Validate a REGISTER and record it. Validation order follows the
status codes: namespace, signed peer record, self-registration rule,
TTL. Re-registration overwrites the peer's slot in the namespace (a
new REGISTER supersedes previous registrations, per spec).
-}
acceptRegistration ::
  RendezvousPoint ->
  PeerId ->
  Text ->
  ByteString ->
  Maybe Word64 ->
  IO RendezvousMessage
acceptRegistration :: RendezvousPoint
-> PeerId
-> Text
-> ByteString
-> Maybe Word64
-> IO RendezvousMessage
acceptRegistration RendezvousPoint
point PeerId
peer Text
ns ByteString
record Maybe Word64
mTTL
  | Text -> Bool
T.null Text
ns Bool -> Bool -> Bool
|| Text -> Int
T.length Text
ns Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxNs =
      RendezvousMessage -> IO RendezvousMessage
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResponseStatus -> RendezvousMessage
reject ResponseStatus
StatusInvalidNamespace)
  | Bool
otherwise = case ByteString -> Either [Char] (SignedEnvelope, PeerRecord)
openPeerRecordEnvelope ByteString
record of
      Left [Char]
_ -> RendezvousMessage -> IO RendezvousMessage
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResponseStatus -> RendezvousMessage
reject ResponseStatus
StatusInvalidSignedPeerRecord)
      Right (SignedEnvelope
_, PeerRecord
rec)
        | PeerRecord -> ByteString
prPeerId PeerRecord
rec ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= PeerId -> ByteString
peerIdBytes PeerId
peer ->
            RendezvousMessage -> IO RendezvousMessage
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResponseStatus -> RendezvousMessage
reject ResponseStatus
StatusNotAuthorized) -- only self-registration
        | Bool
otherwise -> do
            granted <- IO (Maybe Word64)
checkTTL
            case granted of
              Maybe Word64
Nothing -> RendezvousMessage -> IO RendezvousMessage
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResponseStatus -> RendezvousMessage
reject ResponseStatus
StatusInvalidTTL)
              Just Word64
ttl -> do
                stored <- RendezvousPoint
-> PeerId -> Text -> ByteString -> Word64 -> IO (Maybe ())
storeRegistration RendezvousPoint
point PeerId
peer Text
ns ByteString
record Word64
ttl
                pure $ case stored of
                  Maybe ()
Nothing -> ResponseStatus -> RendezvousMessage
reject ResponseStatus
StatusNotAuthorized -- per-peer limit
                  Just () -> ResponseStatus -> Maybe Text -> Maybe Word64 -> RendezvousMessage
RMRegisterResponse ResponseStatus
StatusOK (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"OK") (Word64 -> Maybe Word64
forall a. a -> Maybe a
Just Word64
ttl)
 where
  cfg :: RendezvousConfig
cfg = RendezvousPoint -> RendezvousConfig
rvConfig RendezvousPoint
point
  maxNs :: Int
maxNs = RendezvousConfig -> Int
rcMaxNamespaceLength RendezvousConfig
cfg
  reject :: ResponseStatus -> RendezvousMessage
reject ResponseStatus
status = ResponseStatus -> Maybe Text -> Maybe Word64 -> RendezvousMessage
RMRegisterResponse ResponseStatus
status (Text -> Maybe Text
forall a. a -> Maybe a
Just (ResponseStatus -> Text
statusText ResponseStatus
status)) Maybe Word64
forall a. Maybe a
Nothing

  -- 'Nothing' means inadmissible (E_INVALID_TTL); a TTL above the
  -- configured maximum is clamped down, matching the spec's
  -- "rendezvous point-specific upper bound on TTL".
  checkTTL :: IO (Maybe Word64)
  checkTTL :: IO (Maybe Word64)
checkTTL = case Maybe Word64
mTTL of
    Maybe Word64
Nothing -> Maybe Word64 -> IO (Maybe Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Word64 -> Maybe Word64
forall a. a -> Maybe a
Just (RendezvousConfig -> Word64
rcDefaultTTL RendezvousConfig
cfg))
    Just Word64
ttl
      | Word64
ttl Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< RendezvousConfig -> Word64
rcMinTTL RendezvousConfig
cfg -> Maybe Word64 -> IO (Maybe Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Word64
forall a. Maybe a
Nothing
      | Word64
ttl Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> RendezvousConfig -> Word64
rcMaxTTL RendezvousConfig
cfg -> Maybe Word64 -> IO (Maybe Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Word64 -> Maybe Word64
forall a. a -> Maybe a
Just (RendezvousConfig -> Word64
rcMaxTTL RendezvousConfig
cfg))
      | Bool
otherwise -> Maybe Word64 -> IO (Maybe Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Word64 -> Maybe Word64
forall a. a -> Maybe a
Just Word64
ttl)

{- | Insert (or replace) a registration, enforcing the per-peer limit
across all namespaces. Returns 'Nothing' when the limit is reached.
The version counter is bumped in the same transaction so concurrent
registrations get strictly distinct versions; it is the rendezvous
point's registration heartbeat and the source of discovery cookies.
-}
storeRegistration ::
  RendezvousPoint ->
  PeerId ->
  Text ->
  ByteString ->
  Word64 ->
  IO (Maybe ())
storeRegistration :: RendezvousPoint
-> PeerId -> Text -> ByteString -> Word64 -> IO (Maybe ())
storeRegistration RendezvousPoint
point PeerId
peer Text
ns ByteString
record Word64
ttl = do
  now <- IO UTCTime
getCurrentTime
  accepted <- atomically $ do
    regs <- readTVar (rvRegs point)
    -- Re-registering into a namespace that already holds this peer's
    -- slot replaces it instead of consuming a new one (spec: a new
    -- REGISTER supersedes previous registrations).
    let replacesExisting =
          PeerId -> Map PeerId Registration -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member PeerId
peer (Map PeerId Registration
-> Text
-> Map Text (Map PeerId Registration)
-> Map PeerId Registration
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map PeerId Registration
forall k a. Map k a
Map.empty Text
ns Map Text (Map PeerId Registration)
regs)
        liveCount = PeerId -> UTCTime -> Map Text (Map PeerId Registration) -> Int
countLiveByPeer PeerId
peer UTCTime
now Map Text (Map PeerId Registration)
regs
        projected =
          if Bool
replacesExisting then Int
liveCount else Int
liveCount Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    if projected > rcMaxPerPeer cfg
      then pure False
      else do
        -- Bump first, assign after: version 0 is what the initial
        -- (never-registered) cookie encodes, so a registration's
        -- version must be strictly greater than any cookie older than
        -- itself.
        next <- readTVar (rvVersion point)
        writeTVar (rvVersion point) (next + 1)
        let reg =
              Registration
                { regRecord :: ByteString
regRecord = ByteString
record
                , regTTL :: Word64
regTTL = Word64
ttl
                , regExpires :: UTCTime
regExpires = NominalDiffTime -> UTCTime -> UTCTime
addUTCTime (Word64 -> NominalDiffTime
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
ttl) UTCTime
now
                , regVersion :: Word64
regVersion = Word64
next Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
1
                }
            nsRegs = Map PeerId Registration
-> Text
-> Map Text (Map PeerId Registration)
-> Map PeerId Registration
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map PeerId Registration
forall k a. Map k a
Map.empty Text
ns Map Text (Map PeerId Registration)
regs
        writeTVar
          (rvRegs point)
          (Map.insert ns (Map.insert peer reg nsRegs) regs)
        pure True
  pure (if accepted then Just () else Nothing)
 where
  cfg :: RendezvousConfig
cfg = RendezvousPoint -> RendezvousConfig
rvConfig RendezvousPoint
point

-- | Live registrations by one peer across all namespaces.
countLiveByPeer :: PeerId -> UTCTime -> Map Text (Map PeerId Registration) -> Int
countLiveByPeer :: PeerId -> UTCTime -> Map Text (Map PeerId Registration) -> Int
countLiveByPeer PeerId
peer UTCTime
now Map Text (Map PeerId Registration)
regs =
  [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum
    [ Int
1
    | Map PeerId Registration
nsRegs <- Map Text (Map PeerId Registration) -> [Map PeerId Registration]
forall k a. Map k a -> [a]
Map.elems Map Text (Map PeerId Registration)
regs
    , Registration
reg <- Maybe Registration -> [Registration]
forall a. Maybe a -> [a]
maybeToList (PeerId -> Map PeerId Registration -> Maybe Registration
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
peer Map PeerId Registration
nsRegs)
    , Registration -> UTCTime
regExpires Registration
reg UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
> UTCTime
now
    ]

{- | Answer a DISCOVER (server side).

The cookie is the rendezvous point's registration version counter:
reading the counter /before/ the registration snapshot guarantees the
returned cookie covers every registration that already existed, so a
client polling with it never misses a registration — anything
registered afterwards gets a strictly larger version and shows up in
the next poll. Registrations are returned in version order, so
cookie pagination is stable.
-}
handleDiscover ::
  RendezvousPoint ->
  Maybe Text ->
  DiscoverLimit ->
  ByteString ->
  IO RendezvousMessage
handleDiscover :: RendezvousPoint
-> Maybe Text
-> DiscoverLimit
-> ByteString
-> IO RendezvousMessage
handleDiscover RendezvousPoint
point Maybe Text
ns DiscoverLimit
limit ByteString
cookie = do
  now <- IO UTCTime
getCurrentTime
  case cookieVersion cookie of
    Maybe (Maybe Word64)
Nothing -> RendezvousMessage -> IO RendezvousMessage
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResponseStatus -> RendezvousMessage
discoverResponse ResponseStatus
StatusInvalidCookie)
    Just Maybe Word64
since -> do
      (counter, selected) <- STM (Word64, [(Text, Registration)])
-> IO (Word64, [(Text, Registration)])
forall a. STM a -> IO a
atomically (STM (Word64, [(Text, Registration)])
 -> IO (Word64, [(Text, Registration)]))
-> STM (Word64, [(Text, Registration)])
-> IO (Word64, [(Text, Registration)])
forall a b. (a -> b) -> a -> b
$ do
        counter <- TVar Word64 -> STM Word64
forall a. TVar a -> STM a
readTVar (RendezvousPoint -> TVar Word64
rvVersion RendezvousPoint
point)
        liveRegs <- readTVar (rvRegs point)
        let live =
              (Map PeerId Registration -> Map PeerId Registration)
-> Map Text (Map PeerId Registration)
-> Map Text (Map PeerId Registration)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map ((Registration -> Bool)
-> Map PeerId Registration -> Map PeerId Registration
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter (\Registration
r -> Registration -> UTCTime
regExpires Registration
r UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
> UTCTime
now)) Map Text (Map PeerId Registration)
liveRegs
            taggedAll =
              [ (Text
name, Registration
reg)
              | (Text
name, Map PeerId Registration
nsRegs) <- Map Text (Map PeerId Registration)
-> [(Text, Map PeerId Registration)]
forall k a. Map k a -> [(k, a)]
Map.toList Map Text (Map PeerId Registration)
live
              , Registration
reg <- Map PeerId Registration -> [Registration]
forall k a. Map k a -> [a]
Map.elems Map PeerId Registration
nsRegs
              ]
            tagged = case Maybe Text
ns of
              -- A named scope returns only that namespace; an absent or
              -- empty namespace asks for all registrations.
              Just Text
name ->
                (Text
name,)
                  (Registration -> (Text, Registration))
-> [Registration] -> [(Text, Registration)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map PeerId Registration -> [Registration]
forall k a. Map k a -> [a]
Map.elems (Map PeerId Registration
-> Text
-> Map Text (Map PeerId Registration)
-> Map PeerId Registration
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map PeerId Registration
forall k a. Map k a
Map.empty Text
name Map Text (Map PeerId Registration)
live)
              Maybe Text
Nothing -> [(Text, Registration)]
taggedAll
            fresh = case Maybe Word64
since of
              Just Word64
v -> Word64 -> [(Text, Registration)] -> [(Text, Registration)]
forall {a}. Word64 -> [(a, Registration)] -> [(a, Registration)]
keepSince Word64
v [(Text, Registration)]
tagged
              Maybe Word64
Nothing -> [(Text, Registration)]
tagged
            keepSince Word64
v [(a, Registration)]
rs = [(a
name, Registration
reg) | (a
name, Registration
reg) <- [(a, Registration)]
rs, Registration -> Word64
regVersion Registration
reg Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Word64
v]
            ordered = ((Text, Registration) -> (Text, Registration) -> Ordering)
-> [(Text, Registration)] -> [(Text, Registration)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (((Text, Registration) -> Word64)
-> (Text, Registration) -> (Text, Registration) -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (Registration -> Word64
regVersion (Registration -> Word64)
-> ((Text, Registration) -> Registration)
-> (Text, Registration)
-> Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, Registration) -> Registration
forall a b. (a, b) -> b
snd)) [(Text, Registration)]
fresh
        pure (counter, take maxResults ordered)
      pure $
        RMDiscoverResponse
          [ RegistrationInfo
              { riNamespace = name
              , riPeerRecord = regRecord reg
              , riTTL = regTTL reg
              }
          | (name, reg) <- selected
          ]
          (encodeCookieVersion counter)
          StatusOK
          (Just "OK")
 where
  cfg :: RendezvousConfig
cfg = RendezvousPoint -> RendezvousConfig
rvConfig RendezvousPoint
point
  maxResults :: Int
maxResults = case DiscoverLimit
limit of
    DiscoverLimit
LimitDefault -> RendezvousConfig -> Int
rcMaxResults RendezvousConfig
cfg
    -- An explicit limit above the rendezvous point's ceiling is
    -- capped, per the spec's 1000-per-query recommendation; compute
    -- the cap in Word64 so an absurd limit cannot overflow Int.
    LimitExact Word64
n ->
      Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
min Word64
n (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (RendezvousConfig -> Int
rcMaxResults RendezvousConfig
cfg) :: Word64))

-- | Shell for an error DISCOVER_RESPONSE.
discoverResponse :: ResponseStatus -> RendezvousMessage
discoverResponse :: ResponseStatus -> RendezvousMessage
discoverResponse ResponseStatus
status =
  [RegistrationInfo]
-> ByteString -> ResponseStatus -> Maybe Text -> RendezvousMessage
RMDiscoverResponse [] ByteString
BS.empty ResponseStatus
status (Text -> Maybe Text
forall a. a -> Maybe a
Just (ResponseStatus -> Text
statusText ResponseStatus
status))

-- | Short human-readable text for a status; goes into statusText.
statusText :: ResponseStatus -> Text
statusText :: ResponseStatus -> Text
statusText ResponseStatus
status = case ResponseStatus
status of
  ResponseStatus
StatusOK -> Text
"OK"
  ResponseStatus
StatusInvalidNamespace -> Text
"invalid namespace"
  ResponseStatus
StatusInvalidSignedPeerRecord -> Text
"invalid signed peer record"
  ResponseStatus
StatusInvalidTTL -> Text
"invalid ttl"
  ResponseStatus
StatusInvalidCookie -> Text
"invalid cookie"
  ResponseStatus
StatusNotAuthorized -> Text
"not authorized"
  ResponseStatus
StatusInternalError -> Text
"internal error"
  ResponseStatus
StatusUnavailable -> Text
"unavailable"
  StatusUnknown Word64
c -> [Char] -> Text
T.pack ([Char]
"unknown status " [Char] -> ShowS
forall a. Semigroup a => a -> a -> a
<> Word64 -> [Char]
forall a. Show a => a -> [Char]
show Word64
c)

{- | Decode a discovery cookie. Empty means "first query" ('Nothing'
inside); exactly 8 bytes decode to the registration version any
other length is invalid ('Nothing' outside).
-}
cookieVersion :: ByteString -> Maybe (Maybe Word64)
cookieVersion :: ByteString -> Maybe (Maybe Word64)
cookieVersion ByteString
bs
  | ByteString -> Bool
BS.null ByteString
bs = Maybe Word64 -> Maybe (Maybe Word64)
forall a. a -> Maybe a
Just Maybe Word64
forall a. Maybe a
Nothing
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
8 =
      Maybe Word64 -> Maybe (Maybe Word64)
forall a. a -> Maybe a
Just (Word64 -> Maybe Word64
forall a. a -> Maybe a
Just ((Word64 -> Word8 -> Word64) -> Word64 -> ByteString -> Word64
forall a. (a -> Word8 -> a) -> a -> ByteString -> a
BS.foldl' (\Word64
acc Word8
b -> Word64
acc Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
256 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
b) Word64
0 ByteString
bs))
  | Bool
otherwise = Maybe (Maybe Word64)
forall a. Maybe a
Nothing

{- | Encode a discovery cookie: the registration version counter as
8 big-endian bytes.
-}
encodeCookieVersion :: Word64 -> ByteString
encodeCookieVersion :: Word64 -> ByteString
encodeCookieVersion = [Word8] -> ByteString
BS.pack ([Word8] -> ByteString)
-> (Word64 -> [Word8]) -> Word64 -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Word64 -> [Word8]
go Int
8
 where
  go :: Int -> Word64 -> [Word8]
  go :: Int -> Word64 -> [Word8]
go Int
0 Word64
_ = []
  go Int
n Word64
v = Int -> Word64 -> [Word8]
go (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) (Word64
v Word64 -> Word64 -> Word64
forall a. Integral a => a -> a -> a
`div` Word64
256) [Word8] -> [Word8] -> [Word8]
forall a. [a] -> [a] -> [a]
++ [Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64
v Word64 -> Word64 -> Word64
forall a. Integral a => a -> a -> a
`mod` Word64
256)]

--------------------------------------------------------------------------------
-- Client
--------------------------------------------------------------------------------

{- | Run one client interaction over a fresh stream to the rendezvous
point: open, negotiate, run the body, close on every exit path, all
bounded by 'rendezvousTimeoutMicros'.
-}
withRendezvousStream ::
  Switch ->
  Connection ->
  (StreamIO -> IO (Either RendezvousError a)) ->
  IO (Either RendezvousError a)
withRendezvousStream :: forall a.
Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError a))
-> IO (Either RendezvousError a)
withRendezvousStream Switch
sw Connection
conn StreamIO -> IO (Either RendezvousError a)
body = do
  opened <- Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream Switch
sw Connection
conn
  case opened of
    Left StreamOpenError
err ->
      Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport ([Char]
"stream reservation failed: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ StreamOpenError -> [Char]
forall a. Show a => a -> [Char]
show StreamOpenError
err)))
    Right StreamIO
stream -> do
      outcome <-
        Int
-> IO (Either RendezvousError a)
-> IO (Maybe (Either RendezvousError a))
forall a. Int -> IO a -> IO (Maybe a)
timeout
          Int
rendezvousTimeoutMicros
          (IO StreamIO
-> (StreamIO -> IO ())
-> (StreamIO -> IO (Either RendezvousError a))
-> IO (Either RendezvousError a)
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 RendezvousError a)
negotiateThen)
      pure $ case outcome of
        Maybe (Either RendezvousError a)
Nothing -> RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left RendezvousError
RendezvousTimeout
        Just Either RendezvousError a
r -> Either RendezvousError a
r
 where
  negotiateThen :: StreamIO -> IO (Either RendezvousError a)
negotiateThen StreamIO
st = do
    negotiated <- StreamIO -> [Text] -> IO NegotiationResult
negotiateInitiator StreamIO
st [Text
rendezvousProtocolId]
    case negotiated of
      NegotiationResult
NoProtocol ->
        Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport [Char]
"remote does not support rendezvous"))
      Accepted Text
_ -> StreamIO -> IO (Either RendezvousError a)
body StreamIO
st

-- | Send one request and read exactly one framed reply.
exchange ::
  StreamIO ->
  RendezvousMessage ->
  (RendezvousMessage -> Either RendezvousError a) ->
  IO (Either RendezvousError a)
exchange :: forall a.
StreamIO
-> RendezvousMessage
-> (RendezvousMessage -> Either RendezvousError a)
-> IO (Either RendezvousError a)
exchange StreamIO
stream RendezvousMessage
request RendezvousMessage -> Either RendezvousError a
check = do
  writeOutcome <- IO () -> IO (Either SomeException ())
forall e a. Exception e => IO a -> IO (Either e a)
try (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream (RendezvousMessage -> ByteString
encodeFramedMessage RendezvousMessage
request))
  case writeOutcome :: Either SomeException () of
    Left SomeException
e -> Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport ([Char]
"write failed: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ SomeException -> [Char]
forall a. Show a => a -> [Char]
show SomeException
e)))
    Right () -> do
      reply <- IO (Either [Char] RendezvousMessage)
-> IO (Either SomeException (Either [Char] RendezvousMessage))
forall e a. Exception e => IO a -> IO (Either e a)
try (StreamIO -> Int -> IO (Either [Char] RendezvousMessage)
readFramedMessage StreamIO
stream Int
maxRendezvousMessageSize)
      case reply :: Either SomeException (Either String RendezvousMessage) of
        Left SomeException
e -> Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport ([Char]
"read failed: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ SomeException -> [Char]
forall a. Show a => a -> [Char]
show SomeException
e)))
        Right (Left [Char]
err) -> Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError a
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousDecode [Char]
err))
        Right (Right RendezvousMessage
msg) -> Either RendezvousError a -> IO (Either RendezvousError a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousMessage -> Either RendezvousError a
check RendezvousMessage
msg)

{- | Build the local signed peer record (RFC 0003 envelope) over our
current listen addresses, the payload a registration carries. The
record always builds; sealing cannot fail with our own identity key,
so the Either only reports the impossible.
-}
buildLocalPeerRecord :: Switch -> IO (Either String ByteString)
buildLocalPeerRecord :: Switch -> IO (Either [Char] ByteString)
buildLocalPeerRecord Switch
sw = do
  listeners <- TVar [ActiveListener] -> IO [ActiveListener]
forall a. TVar a -> IO a
readTVarIO (Switch -> TVar [ActiveListener]
swListeners Switch
sw)
  seqNo <- timestampSeq
  let record =
        PeerRecord
          { prPeerId :: ByteString
prPeerId = PeerId -> ByteString
peerIdBytes (Switch -> PeerId
swLocalPeerId Switch
sw)
          , prSeq :: Word64
prSeq = Word64
seqNo
          , prAddresses :: [ByteString]
prAddresses =
              (Multiaddr -> ByteString) -> [Multiaddr] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (\(Multiaddr [Protocol]
ps) -> [Protocol] -> ByteString
encodeProtocols [Protocol]
ps) ((ActiveListener -> Multiaddr) -> [ActiveListener] -> [Multiaddr]
forall a b. (a -> b) -> [a] -> [b]
map ActiveListener -> Multiaddr
alAddress [ActiveListener]
listeners)
          }
  pure
    ( either
        (Left . ("seal local peer record failed: " ++))
        (Right . encodeSignedEnvelope)
        (sealPeerRecord (swIdentityKey sw) record)
    )

{- | Register ourselves in a namespace (client side of REGISTER). A
signed peer record over our current listen addresses is built here;
the granted TTL is returned so the application knows when to
refresh.
-}
registerSelf ::
  Switch ->
  Connection ->
  Text ->
  Maybe Word64 ->
  IO (Either RendezvousError Word64)
registerSelf :: Switch
-> Connection
-> Text
-> Maybe Word64
-> IO (Either RendezvousError Word64)
registerSelf Switch
sw Connection
conn Text
ns Maybe Word64
mTTL = do
  recordE <- Switch -> IO (Either [Char] ByteString)
buildLocalPeerRecord Switch
sw
  case recordE of
    Left [Char]
err -> Either RendezvousError Word64 -> IO (Either RendezvousError Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousError -> Either RendezvousError Word64
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport [Char]
err))
    Right ByteString
record ->
      Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError Word64))
-> IO (Either RendezvousError Word64)
forall a.
Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError a))
-> IO (Either RendezvousError a)
withRendezvousStream Switch
sw Connection
conn ((StreamIO -> IO (Either RendezvousError Word64))
 -> IO (Either RendezvousError Word64))
-> (StreamIO -> IO (Either RendezvousError Word64))
-> IO (Either RendezvousError Word64)
forall a b. (a -> b) -> a -> b
$ \StreamIO
stream ->
        StreamIO
-> RendezvousMessage
-> (RendezvousMessage -> Either RendezvousError Word64)
-> IO (Either RendezvousError Word64)
forall a.
StreamIO
-> RendezvousMessage
-> (RendezvousMessage -> Either RendezvousError a)
-> IO (Either RendezvousError a)
exchange StreamIO
stream (Text -> ByteString -> Maybe Word64 -> RendezvousMessage
RMRegister Text
ns ByteString
record Maybe Word64
mTTL) ((RendezvousMessage -> Either RendezvousError Word64)
 -> IO (Either RendezvousError Word64))
-> (RendezvousMessage -> Either RendezvousError Word64)
-> IO (Either RendezvousError Word64)
forall a b. (a -> b) -> a -> b
$ \RendezvousMessage
reply -> case RendezvousMessage
reply of
          RMRegisterResponse ResponseStatus
StatusOK Maybe Text
_ (Just Word64
ttl) -> Word64 -> Either RendezvousError Word64
forall a b. b -> Either a b
Right Word64
ttl
          RMRegisterResponse ResponseStatus
StatusOK Maybe Text
_ Maybe Word64
Nothing ->
            RendezvousError -> Either RendezvousError Word64
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousDecode [Char]
"ok registration response without ttl")
          RMRegisterResponse ResponseStatus
status Maybe Text
text Maybe Word64
_ -> RendezvousError -> Either RendezvousError Word64
forall a b. a -> Either a b
Left (ResponseStatus -> Maybe Text -> RendezvousError
RendezvousRejected ResponseStatus
status Maybe Text
text)
          RendezvousMessage
_ -> RendezvousError -> Either RendezvousError Word64
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousDecode [Char]
"unexpected response to REGISTER")

{- | Cancel our registration in a namespace (client side of
UNREGISTER). No reply is sent by the rendezvous point; the write
succeeding is the outcome.
-}
unregisterSelf :: Switch -> Connection -> Text -> IO (Either RendezvousError ())
unregisterSelf :: Switch -> Connection -> Text -> IO (Either RendezvousError ())
unregisterSelf Switch
sw Connection
conn Text
ns =
  Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError ()))
-> IO (Either RendezvousError ())
forall a.
Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError a))
-> IO (Either RendezvousError a)
withRendezvousStream Switch
sw Connection
conn ((StreamIO -> IO (Either RendezvousError ()))
 -> IO (Either RendezvousError ()))
-> (StreamIO -> IO (Either RendezvousError ()))
-> IO (Either RendezvousError ())
forall a b. (a -> b) -> a -> b
$ \StreamIO
stream -> do
    outcome <- IO () -> IO (Either SomeException ())
forall e a. Exception e => IO a -> IO (Either e a)
try (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream (RendezvousMessage -> ByteString
encodeFramedMessage (Text -> RendezvousMessage
RMUnregister Text
ns)))
    pure $ case outcome :: Either SomeException () of
      Right () -> () -> Either RendezvousError ()
forall a b. b -> Either a b
Right ()
      Left SomeException
e -> RendezvousError -> Either RendezvousError ()
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousTransport ([Char]
"write failed: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ SomeException -> [Char]
forall a. Show a => a -> [Char]
show SomeException
e))

{- | Discover registrations (client side of DISCOVER). Pass 'Nothing'
for the namespace to query every namespace; pass the cookie from a
previous response to list only registrations made since (progressive
refresh, specs/rendezvous §The Protocol). Returns the registrations
and the cookie for the next poll.
-}
discover ::
  Switch ->
  Connection ->
  Maybe Text ->
  DiscoverLimit ->
  ByteString ->
  IO (Either RendezvousError ([RegistrationInfo], ByteString))
discover :: Switch
-> Connection
-> Maybe Text
-> DiscoverLimit
-> ByteString
-> IO (Either RendezvousError ([RegistrationInfo], ByteString))
discover Switch
sw Connection
conn Maybe Text
ns DiscoverLimit
limit ByteString
cookie =
  Switch
-> Connection
-> (StreamIO
    -> IO (Either RendezvousError ([RegistrationInfo], ByteString)))
-> IO (Either RendezvousError ([RegistrationInfo], ByteString))
forall a.
Switch
-> Connection
-> (StreamIO -> IO (Either RendezvousError a))
-> IO (Either RendezvousError a)
withRendezvousStream Switch
sw Connection
conn ((StreamIO
  -> IO (Either RendezvousError ([RegistrationInfo], ByteString)))
 -> IO (Either RendezvousError ([RegistrationInfo], ByteString)))
-> (StreamIO
    -> IO (Either RendezvousError ([RegistrationInfo], ByteString)))
-> IO (Either RendezvousError ([RegistrationInfo], ByteString))
forall a b. (a -> b) -> a -> b
$ \StreamIO
stream ->
    StreamIO
-> RendezvousMessage
-> (RendezvousMessage
    -> Either RendezvousError ([RegistrationInfo], ByteString))
-> IO (Either RendezvousError ([RegistrationInfo], ByteString))
forall a.
StreamIO
-> RendezvousMessage
-> (RendezvousMessage -> Either RendezvousError a)
-> IO (Either RendezvousError a)
exchange StreamIO
stream (Maybe Text -> DiscoverLimit -> ByteString -> RendezvousMessage
RMDiscover Maybe Text
ns DiscoverLimit
limit ByteString
cookie) ((RendezvousMessage
  -> Either RendezvousError ([RegistrationInfo], ByteString))
 -> IO (Either RendezvousError ([RegistrationInfo], ByteString)))
-> (RendezvousMessage
    -> Either RendezvousError ([RegistrationInfo], ByteString))
-> IO (Either RendezvousError ([RegistrationInfo], ByteString))
forall a b. (a -> b) -> a -> b
$ \RendezvousMessage
reply -> case RendezvousMessage
reply of
      RMDiscoverResponse [RegistrationInfo]
regs ByteString
nextCookie ResponseStatus
StatusOK Maybe Text
_ -> ([RegistrationInfo], ByteString)
-> Either RendezvousError ([RegistrationInfo], ByteString)
forall a b. b -> Either a b
Right ([RegistrationInfo]
regs, ByteString
nextCookie)
      RMDiscoverResponse [RegistrationInfo]
_ ByteString
_ ResponseStatus
status Maybe Text
text -> RendezvousError
-> Either RendezvousError ([RegistrationInfo], ByteString)
forall a b. a -> Either a b
Left (ResponseStatus -> Maybe Text -> RendezvousError
RendezvousRejected ResponseStatus
status Maybe Text
text)
      RendezvousMessage
_ -> RendezvousError
-> Either RendezvousError ([RegistrationInfo], ByteString)
forall a b. a -> Either a b
Left ([Char] -> RendezvousError
RendezvousDecode [Char]
"unexpected response to DISCOVER")

{- | Validate a received registration's signed peer record envelope and
extract the peer identity and dialable addresses it advertises.
-}
inspectRegistration ::
  RegistrationInfo -> Either String DiscoveryEvent
inspectRegistration :: RegistrationInfo -> Either [Char] DiscoveryEvent
inspectRegistration RegistrationInfo
ri = do
  (_, rec) <- ByteString -> Either [Char] (SignedEnvelope, PeerRecord)
openPeerRecordEnvelope (RegistrationInfo -> ByteString
riPeerRecord RegistrationInfo
ri)
  let addrs = (ByteString -> Maybe Multiaddr) -> [ByteString] -> [Multiaddr]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (([Char] -> Maybe Multiaddr)
-> (Multiaddr -> Maybe Multiaddr)
-> Either [Char] Multiaddr
-> Maybe Multiaddr
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Multiaddr -> [Char] -> Maybe Multiaddr
forall a b. a -> b -> a
const Maybe Multiaddr
forall a. Maybe a
Nothing) Multiaddr -> Maybe Multiaddr
forall a. a -> Maybe a
Just (Either [Char] Multiaddr -> Maybe Multiaddr)
-> (ByteString -> Either [Char] Multiaddr)
-> ByteString
-> Maybe Multiaddr
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either [Char] Multiaddr
fromBytes) (PeerRecord -> [ByteString]
prAddresses PeerRecord
rec)
  pure (DiscoveryEvent (PeerId (prPeerId rec)) addrs)

{- | Push decoded discovery events for registrations onto a queue;
registrations whose record does not verify are dropped rather than
poisoning the feed.
-}
pushDiscoverEvents :: TQueue DiscoveryEvent -> [RegistrationInfo] -> IO ()
pushDiscoverEvents :: TQueue DiscoveryEvent -> [RegistrationInfo] -> IO ()
pushDiscoverEvents TQueue DiscoveryEvent
queue [RegistrationInfo]
regs =
  [RegistrationInfo] -> (RegistrationInfo -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [RegistrationInfo]
regs ((RegistrationInfo -> IO ()) -> IO ())
-> (RegistrationInfo -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \RegistrationInfo
ri -> case RegistrationInfo -> Either [Char] DiscoveryEvent
inspectRegistration RegistrationInfo
ri of
    Right DiscoveryEvent
ev -> STM () -> IO ()
forall a. STM a -> IO a
atomically (TQueue DiscoveryEvent -> DiscoveryEvent -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue DiscoveryEvent
queue DiscoveryEvent
ev)
    Left [Char]
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

--------------------------------------------------------------------------------
-- Wire framing
--------------------------------------------------------------------------------

{- | Encode a message with its uvarint length prefix, as written on the
wire: uvarint(len) ++ protobuf.
-}
encodeFramedMessage :: RendezvousMessage -> ByteString
encodeFramedMessage :: RendezvousMessage -> ByteString
encodeFramedMessage RendezvousMessage
msg =
  let payload :: ByteString
payload = RendezvousMessage -> ByteString
encodeRendezvousMessage RendezvousMessage
msg
   in Word64 -> ByteString
encodeUvarint (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
payload)) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
payload

{- | Read one varint-length-prefixed message from a stream.

Reads the uvarint length prefix, then exactly that many payload
bytes, and decodes the protobuf. Rejects messages larger than
maxSize before reading the payload.
-}
readFramedMessage :: StreamIO -> Int -> IO (Either String RendezvousMessage)
readFramedMessage :: StreamIO -> Int -> IO (Either [Char] RendezvousMessage)
readFramedMessage StreamIO
stream Int
maxSize = do
  varintBytes <- StreamIO -> IO ByteString
readVarintBytes StreamIO
stream
  case decodeUvarint varintBytes of
    Left [Char]
err -> Either [Char] RendezvousMessage
-> IO (Either [Char] RendezvousMessage)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Char] -> Either [Char] RendezvousMessage
forall a b. a -> Either a b
Left ([Char]
"rendezvous length prefix decode error: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
err))
    Right (Word64
len, ByteString
_) -> do
      let msgLen :: Int
msgLen = Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
len :: Int
      if Int
msgLen Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxSize
        then
          Either [Char] RendezvousMessage
-> IO (Either [Char] RendezvousMessage)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
            ( [Char] -> Either [Char] RendezvousMessage
forall a b. a -> Either a b
Left
                ( [Char]
"rendezvous message too large: "
                    [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ Int -> [Char]
forall a. Show a => a -> [Char]
show Int
msgLen
                    [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
" > "
                    [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ Int -> [Char]
forall a. Show a => a -> [Char]
show Int
maxSize
                )
            )
        else do
          payloadOrErr <- StreamIO -> Int -> Int -> IO (Either [Char] ByteString)
readExactBounded StreamIO
stream Int
maxSize Int
msgLen
          case payloadOrErr of
            Left [Char]
err -> Either [Char] RendezvousMessage
-> IO (Either [Char] RendezvousMessage)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Char] -> Either [Char] RendezvousMessage
forall a b. a -> Either a b
Left ([Char]
"rendezvous read error: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
err))
            Right ByteString
payload -> case ByteString -> Either ParseError RendezvousMessage
decodeRendezvousMessage ByteString
payload of
              Left ParseError
parseErr ->
                Either [Char] RendezvousMessage
-> IO (Either [Char] RendezvousMessage)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Char] -> Either [Char] RendezvousMessage
forall a b. a -> Either a b
Left ([Char]
"rendezvous protobuf decode error: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ ParseError -> [Char]
forall a. Show a => a -> [Char]
show ParseError
parseErr))
              Right RendezvousMessage
msg -> Either [Char] RendezvousMessage
-> IO (Either [Char] RendezvousMessage)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RendezvousMessage -> Either [Char] RendezvousMessage
forall a b. b -> Either a b
Right RendezvousMessage
msg)

{- | Read the bytes of one unsigned varint from a stream (up to 10
bytes).
-}
readVarintBytes :: StreamIO -> IO ByteString
readVarintBytes :: StreamIO -> IO ByteString
readVarintBytes StreamIO
stream = [Word8] -> Int -> IO ByteString
forall {t}. (Ord t, Num t) => [Word8] -> t -> IO ByteString
go [] (Int
0 :: Int)
 where
  go :: [Word8] -> t -> IO ByteString
go [Word8]
acc t
n
    | t
n t -> t -> Bool
forall a. Ord a => a -> a -> Bool
>= t
10 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Word8] -> ByteString
BS.pack ([Word8] -> [Word8]
forall a. [a] -> [a]
reverse [Word8]
acc))
    | Bool
otherwise = do
        b <- StreamIO -> IO Word8
streamReadByte StreamIO
stream
        if b < 0x80
          then pure (BS.pack (reverse (b : acc)))
          else go (b : acc) (n + 1)