-- | Client-side enforcement of a relay-advertised circuit budget.
--
-- specs/relay/circuit-v2: the relay counts bytes on the relayed
-- connection itself (the byte stream after the hop or stop handshake),
-- separately in each direction, and resets both sides when either
-- direction exceeds @data@ or the circuit has been open for @duration@.
-- A component of 0, or an absent component, is unlimited. An omitted
-- limit means the relay applies none.
--
-- This wrapper charges that same stream. A write that does not fit is
-- not sent. A read never consumes a byte past the cap. Once either
-- budget is exhausted the underlying stream is closed and every later
-- read or write throws 'RelayCircuitExhausted', rather than waiting for
-- the relay's reset to surface as an opaque transport failure.
module LibP2P.NAT.Relay.Limit
  ( RelayCircuitExhausted (..)
  , toRelayCircuitLimit
  , enforceRelayCircuitLimit
  ) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Control.Exception (Exception (..), onException, throwIO)
import Control.Monad (unless, when)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)
import Data.Maybe (fromMaybe)
import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime)
import Data.Word (Word64, Word8)
import LibP2P.MultistreamSelect.Negotiation (StreamIO (..), closeQuietly)
import LibP2P.NAT.Relay.Message (RelayLimit (..))
import LibP2P.Transport (RelayCircuitLimit (..), relayCircuitIsLimited)

-- | Why a relayed circuit was closed locally.
data RelayCircuitExhausted
  = RelayCircuitDurationExhausted
  | RelayCircuitDataExhausted
  deriving (RelayCircuitExhausted -> RelayCircuitExhausted -> Bool
(RelayCircuitExhausted -> RelayCircuitExhausted -> Bool)
-> (RelayCircuitExhausted -> RelayCircuitExhausted -> Bool)
-> Eq RelayCircuitExhausted
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool
== :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool
$c/= :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool
/= :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool
Eq, Int -> RelayCircuitExhausted -> ShowS
[RelayCircuitExhausted] -> ShowS
RelayCircuitExhausted -> String
(Int -> RelayCircuitExhausted -> ShowS)
-> (RelayCircuitExhausted -> String)
-> ([RelayCircuitExhausted] -> ShowS)
-> Show RelayCircuitExhausted
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RelayCircuitExhausted -> ShowS
showsPrec :: Int -> RelayCircuitExhausted -> ShowS
$cshow :: RelayCircuitExhausted -> String
show :: RelayCircuitExhausted -> String
$cshowList :: [RelayCircuitExhausted] -> ShowS
showList :: [RelayCircuitExhausted] -> ShowS
Show)

instance Exception RelayCircuitExhausted

data Charge = Charge
  { Charge -> Word64
chRead   :: !Word64
  , Charge -> Word64
chWrite  :: !Word64
  , Charge -> Maybe RelayCircuitExhausted
chReason :: !(Maybe RelayCircuitExhausted)
  }

data ActiveLimit = ActiveLimit
  { ActiveLimit -> Maybe Word64
alData     :: !(Maybe Word64)
  , ActiveLimit -> Maybe POSIXTime
alDeadline :: !(Maybe POSIXTime)
  }

-- | Copy a relay protobuf limit into the transport-level budget.
toRelayCircuitLimit :: RelayLimit -> RelayCircuitLimit
toRelayCircuitLimit :: RelayLimit -> RelayCircuitLimit
toRelayCircuitLimit RelayLimit
lim = RelayCircuitLimit
  { rclDurationSeconds :: Maybe Word32
rclDurationSeconds = RelayLimit -> Maybe Word32
rlDuration RelayLimit
lim
  , rclDataBytes :: Maybe Word64
rclDataBytes = RelayLimit -> Maybe Word64
rlData RelayLimit
lim
  }

-- | Charge @stream@ against @mLimit@. A missing or inactive budget
-- (every component 0 or absent) is returned unchanged. The duration
-- clock starts when this returns, which is when the hop or stop
-- handshake has completed and the stream has become the circuit.
enforceRelayCircuitLimit :: Maybe RelayCircuitLimit -> StreamIO -> IO StreamIO
enforceRelayCircuitLimit :: Maybe RelayCircuitLimit -> StreamIO -> IO StreamIO
enforceRelayCircuitLimit Maybe RelayCircuitLimit
mLimit StreamIO
stream = case Maybe RelayCircuitLimit
mLimit of
  Just RelayCircuitLimit
lim | Maybe RelayCircuitLimit -> Bool
relayCircuitIsLimited Maybe RelayCircuitLimit
mLimit -> RelayCircuitLimit -> StreamIO -> IO StreamIO
arm RelayCircuitLimit
lim StreamIO
stream
  Maybe RelayCircuitLimit
_ -> StreamIO -> IO StreamIO
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure StreamIO
stream

arm :: RelayCircuitLimit -> StreamIO -> IO StreamIO
arm :: RelayCircuitLimit -> StreamIO -> IO StreamIO
arm RelayCircuitLimit
lim StreamIO
stream = do
  now <- IO POSIXTime
getPOSIXTime
  ref <- newIORef Charge { chRead = 0, chWrite = 0, chReason = Nothing }
  pure (wrap ref (activeLimit lim now) stream)

activeLimit :: RelayCircuitLimit -> POSIXTime -> ActiveLimit
activeLimit :: RelayCircuitLimit -> POSIXTime -> ActiveLimit
activeLimit RelayCircuitLimit
lim POSIXTime
now = ActiveLimit
  { alData :: Maybe Word64
alData = Maybe Word64 -> Maybe Word64
forall {a}. (Ord a, Num a) => Maybe a -> Maybe a
positive (RelayCircuitLimit -> Maybe Word64
rclDataBytes RelayCircuitLimit
lim)
  , alDeadline :: Maybe POSIXTime
alDeadline = (POSIXTime
now POSIXTime -> POSIXTime -> POSIXTime
forall a. Num a => a -> a -> a
+) (POSIXTime -> POSIXTime)
-> (Word32 -> POSIXTime) -> Word32 -> POSIXTime
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word32 -> POSIXTime
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word32 -> POSIXTime) -> Maybe Word32 -> Maybe POSIXTime
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Word32 -> Maybe Word32
forall {a}. (Ord a, Num a) => Maybe a -> Maybe a
positive (RelayCircuitLimit -> Maybe Word32
rclDurationSeconds RelayCircuitLimit
lim)
  }
  where
    positive :: Maybe a -> Maybe a
positive (Just a
n) | a
n a -> a -> Bool
forall a. Ord a => a -> a -> Bool
> a
0 = a -> Maybe a
forall a. a -> Maybe a
Just a
n
    positive Maybe a
_ = Maybe a
forall a. Maybe a
Nothing

wrap :: IORef Charge -> ActiveLimit -> StreamIO -> StreamIO
wrap :: IORef Charge -> ActiveLimit -> StreamIO -> StreamIO
wrap IORef Charge
ref ActiveLimit
lim StreamIO
inner = StreamIO
  { streamWrite :: ByteString -> IO ()
streamWrite = IORef Charge -> ActiveLimit -> StreamIO -> ByteString -> IO ()
writeLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner
  , streamReadByte :: IO Word8
streamReadByte = IORef Charge -> ActiveLimit -> StreamIO -> IO Word8
readByteLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner
  , streamReadChunk :: Int -> IO ByteString
streamReadChunk = IORef Charge -> ActiveLimit -> StreamIO -> Int -> IO ByteString
readChunkLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner
  , streamClose :: IO ()
streamClose = StreamIO -> IO ()
closeQuietly StreamIO
inner
  }

writeLimited :: IORef Charge -> ActiveLimit -> StreamIO -> ByteString -> IO ()
writeLimited :: IORef Charge -> ActiveLimit -> StreamIO -> ByteString -> IO ()
writeLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner ByteString
bs = do
  IORef Charge -> ActiveLimit -> StreamIO -> IO ()
ensureFresh IORef Charge
ref ActiveLimit
lim StreamIO
inner
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
BS.null ByteString
bs) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    ok <- IORef Charge -> Maybe Word64 -> Int -> IO Bool
reserveWrite IORef Charge
ref (ActiveLimit -> Maybe Word64
alData ActiveLimit
lim) (ByteString -> Int
BS.length ByteString
bs)
    unless ok (trip ref inner RelayCircuitDataExhausted)
    runBounded ref lim inner (streamWrite inner bs)
      `onException` refundWrite ref (fromIntegral (BS.length bs))

readByteLimited :: IORef Charge -> ActiveLimit -> StreamIO -> IO Word8
readByteLimited :: IORef Charge -> ActiveLimit -> StreamIO -> IO Word8
readByteLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner = do
  IORef Charge -> ActiveLimit -> StreamIO -> IO ()
ensureFresh IORef Charge
ref ActiveLimit
lim StreamIO
inner
  claimed <- IORef Charge -> Maybe Word64 -> Int -> IO Int
claimRead IORef Charge
ref (ActiveLimit -> Maybe Word64
alData ActiveLimit
lim) Int
1
  when (claimed <= 0) (trip ref inner RelayCircuitDataExhausted)
  runBounded ref lim inner (streamReadByte inner)
    `onException` refundRead ref 1

readChunkLimited :: IORef Charge -> ActiveLimit -> StreamIO -> Int -> IO ByteString
readChunkLimited :: IORef Charge -> ActiveLimit -> StreamIO -> Int -> IO ByteString
readChunkLimited IORef Charge
ref ActiveLimit
lim StreamIO
inner Int
n
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
1 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
  | Bool
otherwise = do
      IORef Charge -> ActiveLimit -> StreamIO -> IO ()
ensureFresh IORef Charge
ref ActiveLimit
lim StreamIO
inner
      claimed <- IORef Charge -> Maybe Word64 -> Int -> IO Int
claimRead IORef Charge
ref (ActiveLimit -> Maybe Word64
alData ActiveLimit
lim) Int
n
      when (claimed <= 0) (trip ref inner RelayCircuitDataExhausted)
      chunk <- runBounded ref lim inner (streamReadChunk inner claimed)
        `onException` refundRead ref (fromIntegral claimed)
      refundUnused claimed chunk
      pure (BS.take claimed chunk)
  where
    refundUnused :: Int -> ByteString -> IO ()
refundUnused Int
claimed ByteString
chunk =
      let extra :: Int
extra = Int
claimed Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
chunk
      in Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
extra Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0) (IORef Charge -> Word64 -> IO ()
refundRead IORef Charge
ref (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
extra))

-- | Run an I/O action, failing with the duration error if the deadline
-- passes while it is blocked. @race@ cancels the loser, so a blocked
-- read does not surface later as a transport reset.
runBounded :: IORef Charge -> ActiveLimit -> StreamIO -> IO a -> IO a
runBounded :: forall a. IORef Charge -> ActiveLimit -> StreamIO -> IO a -> IO a
runBounded IORef Charge
ref ActiveLimit
lim StreamIO
inner IO a
action = case ActiveLimit -> Maybe POSIXTime
alDeadline ActiveLimit
lim of
  Maybe POSIXTime
Nothing -> IO a
action
  Just POSIXTime
deadline -> do
    result <- IO () -> IO a -> IO (Either () a)
forall a b. IO a -> IO b -> IO (Either a b)
race (POSIXTime -> IO ()
waitDeadline POSIXTime
deadline) IO a
action
    case result of
      Left () -> IORef Charge -> StreamIO -> RelayCircuitExhausted -> IO a
forall a. IORef Charge -> StreamIO -> RelayCircuitExhausted -> IO a
trip IORef Charge
ref StreamIO
inner RelayCircuitExhausted
RelayCircuitDurationExhausted
      Right a
a -> a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
a

ensureFresh :: IORef Charge -> ActiveLimit -> StreamIO -> IO ()
ensureFresh :: IORef Charge -> ActiveLimit -> StreamIO -> IO ()
ensureFresh IORef Charge
ref ActiveLimit
lim StreamIO
inner = do
  reason <- Charge -> Maybe RelayCircuitExhausted
chReason (Charge -> Maybe RelayCircuitExhausted)
-> IO Charge -> IO (Maybe RelayCircuitExhausted)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IORef Charge -> IO Charge
forall a. IORef a -> IO a
readIORef IORef Charge
ref
  case reason of
    Just RelayCircuitExhausted
stored -> RelayCircuitExhausted -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO RelayCircuitExhausted
stored
    Maybe RelayCircuitExhausted
Nothing -> case ActiveLimit -> Maybe POSIXTime
alDeadline ActiveLimit
lim of
      Just POSIXTime
deadline -> do
        now <- IO POSIXTime
getPOSIXTime
        when (now >= deadline) (trip ref inner RelayCircuitDurationExhausted)
      Maybe POSIXTime
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

trip :: IORef Charge -> StreamIO -> RelayCircuitExhausted -> IO a
trip :: forall a. IORef Charge -> StreamIO -> RelayCircuitExhausted -> IO a
trip IORef Charge
ref StreamIO
inner RelayCircuitExhausted
reason = do
  stored <- IORef Charge
-> (Charge -> (Charge, RelayCircuitExhausted))
-> IO RelayCircuitExhausted
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Charge
ref ((Charge -> (Charge, RelayCircuitExhausted))
 -> IO RelayCircuitExhausted)
-> (Charge -> (Charge, RelayCircuitExhausted))
-> IO RelayCircuitExhausted
forall a b. (a -> b) -> a -> b
$ \Charge
ch ->
    let reason' :: RelayCircuitExhausted
reason' = RelayCircuitExhausted
-> Maybe RelayCircuitExhausted -> RelayCircuitExhausted
forall a. a -> Maybe a -> a
fromMaybe RelayCircuitExhausted
reason (Charge -> Maybe RelayCircuitExhausted
chReason Charge
ch)
    in (Charge
ch { chReason = Just reason' }, RelayCircuitExhausted
reason')
  closeQuietly inner
  throwIO stored

reserveWrite :: IORef Charge -> Maybe Word64 -> Int -> IO Bool
reserveWrite :: IORef Charge -> Maybe Word64 -> Int -> IO Bool
reserveWrite IORef Charge
_ Maybe Word64
Nothing Int
_ = Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
reserveWrite IORef Charge
ref (Just Word64
cap) Int
n = IORef Charge -> (Charge -> (Charge, Bool)) -> IO Bool
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Charge
ref ((Charge -> (Charge, Bool)) -> IO Bool)
-> (Charge -> (Charge, Bool)) -> IO Bool
forall a b. (a -> b) -> a -> b
$ \Charge
ch ->
  let need :: Word64
need = Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n :: Word64
      used :: Word64
used = Charge -> Word64
chWrite Charge
ch
      fits :: Bool
fits = Word64
used Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
cap Bool -> Bool -> Bool
&& Word64
need Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
cap Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
used
      ch' :: Charge
ch' = if Bool
fits then Charge
ch { chWrite = used + need } else Charge
ch
  in (Charge
ch', Bool
fits)

claimRead :: IORef Charge -> Maybe Word64 -> Int -> IO Int
claimRead :: IORef Charge -> Maybe Word64 -> Int -> IO Int
claimRead IORef Charge
_ Maybe Word64
Nothing Int
n = Int -> IO Int
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int
n
claimRead IORef Charge
ref (Just Word64
cap) Int
n = IORef Charge -> (Charge -> (Charge, Int)) -> IO Int
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Charge
ref ((Charge -> (Charge, Int)) -> IO Int)
-> (Charge -> (Charge, Int)) -> IO Int
forall a b. (a -> b) -> a -> b
$ \Charge
ch ->
  let room :: Word64
room = if Charge -> Word64
chRead Charge
ch Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
cap then Word64
0 else Word64
cap Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Charge -> Word64
chRead Charge
ch
      takeN :: Word64
takeN = Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
min (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n) Word64
room
  in (Charge
ch { chRead = chRead ch + takeN }, Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
takeN)

refundWrite :: IORef Charge -> Word64 -> IO ()
refundWrite :: IORef Charge -> Word64 -> IO ()
refundWrite IORef Charge
ref Word64
n = IORef Charge -> (Charge -> (Charge, ())) -> IO ()
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Charge
ref ((Charge -> (Charge, ())) -> IO ())
-> (Charge -> (Charge, ())) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Charge
ch ->
  (Charge
ch { chWrite = chWrite ch - min n (chWrite ch) }, ())

refundRead :: IORef Charge -> Word64 -> IO ()
refundRead :: IORef Charge -> Word64 -> IO ()
refundRead IORef Charge
ref Word64
n = IORef Charge -> (Charge -> (Charge, ())) -> IO ()
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Charge
ref ((Charge -> (Charge, ())) -> IO ())
-> (Charge -> (Charge, ())) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Charge
ch ->
  (Charge
ch { chRead = chRead ch - min n (chRead ch) }, ())

-- | Block until @deadline@. A duration longer than one 'threadDelay'
-- step (possible on 32-bit 'Int') is waited out in pieces. Cancelled
-- when the I/O it races against finishes first.
waitDeadline :: POSIXTime -> IO ()
waitDeadline :: POSIXTime -> IO ()
waitDeadline POSIXTime
deadline = do
  now <- IO POSIXTime
getPOSIXTime
  let remainUs = POSIXTime -> Integer
forall b. Integral b => POSIXTime -> b
forall a b. (RealFrac a, Integral b) => a -> b
ceiling ((POSIXTime
deadline POSIXTime -> POSIXTime -> POSIXTime
forall a. Num a => a -> a -> a
- POSIXTime
now) POSIXTime -> POSIXTime -> POSIXTime
forall a. Num a => a -> a -> a
* POSIXTime
1000000) :: Integer
  when (remainUs > 0) $ do
    let step = Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min Integer
remainUs (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int))
    threadDelay (fromInteger step)
    when (step < remainUs) (waitDeadline deadline)