-- | Hierarchical resource management for the Switch.
--
-- Resources are owned by a System -> Peer -> Connection -> Stream scope tree.
-- Reservations walk from the owning scope to the system scope in one STM
-- transaction, so a failed ancestor check never leaves partial usage behind.
module LibP2P.Switch.ResourceManager
  ( Direction (..)
  , ResourceUsage (..)
  , emptyUsage
  , ResourceLimits (..)
  , noLimits
  , DefaultLimits (..)
  , defaultSystemLimits
  , defaultPeerLimits
  , defaultConnectionLimits
  , defaultStreamLimits
  , ResourceScope (..)
  , ScopeName (..)
  , ResourceError (..)
  , MemoryAccount (..)
  , ResourceManager (..)
  , newResourceManager
  , getOrCreatePeerScope
  , reserveConnection
  , releaseConnection
  , reserveStream
  , releaseStream
  , reserveMemory
  , releaseMemory
  , scopeMemoryAccount
  , unlimitedMemoryAccount
  , withConnection
  , withStream
  ) where

import Control.Concurrent.STM
  ( STM
  , TVar
  , atomically
  , modifyTVar'
  , newTVar
  , readTVar
  , writeTVar
  )
import Control.Exception (Exception, bracket)
import Control.Monad (unless)
import qualified Data.Map.Strict as Map
import LibP2P.Crypto.PeerId (PeerId)

-- | Direction of a resource relative to this node.
data Direction = Inbound | Outbound
  deriving (Int -> Direction -> ShowS
[Direction] -> ShowS
Direction -> String
(Int -> Direction -> ShowS)
-> (Direction -> String)
-> ([Direction] -> ShowS)
-> Show Direction
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Direction -> ShowS
showsPrec :: Int -> Direction -> ShowS
$cshow :: Direction -> String
show :: Direction -> String
$cshowList :: [Direction] -> ShowS
showList :: [Direction] -> ShowS
Show, Direction -> Direction -> Bool
(Direction -> Direction -> Bool)
-> (Direction -> Direction -> Bool) -> Eq Direction
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Direction -> Direction -> Bool
== :: Direction -> Direction -> Bool
$c/= :: Direction -> Direction -> Bool
/= :: Direction -> Direction -> Bool
Eq)

-- | Tracked usage aggregated at a scope.
data ResourceUsage = ResourceUsage
  { ResourceUsage -> Int
ruConnsInbound :: !Int
  , ResourceUsage -> Int
ruConnsOutbound :: !Int
  , ResourceUsage -> Int
ruStreamsInbound :: !Int
  , ResourceUsage -> Int
ruStreamsOutbound :: !Int
  , ResourceUsage -> Int
ruMemory :: !Int
  } deriving (Int -> ResourceUsage -> ShowS
[ResourceUsage] -> ShowS
ResourceUsage -> String
(Int -> ResourceUsage -> ShowS)
-> (ResourceUsage -> String)
-> ([ResourceUsage] -> ShowS)
-> Show ResourceUsage
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ResourceUsage -> ShowS
showsPrec :: Int -> ResourceUsage -> ShowS
$cshow :: ResourceUsage -> String
show :: ResourceUsage -> String
$cshowList :: [ResourceUsage] -> ShowS
showList :: [ResourceUsage] -> ShowS
Show, ResourceUsage -> ResourceUsage -> Bool
(ResourceUsage -> ResourceUsage -> Bool)
-> (ResourceUsage -> ResourceUsage -> Bool) -> Eq ResourceUsage
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResourceUsage -> ResourceUsage -> Bool
== :: ResourceUsage -> ResourceUsage -> Bool
$c/= :: ResourceUsage -> ResourceUsage -> Bool
/= :: ResourceUsage -> ResourceUsage -> Bool
Eq)

emptyUsage :: ResourceUsage
emptyUsage :: ResourceUsage
emptyUsage = Int -> Int -> Int -> Int -> Int -> ResourceUsage
ResourceUsage Int
0 Int
0 Int
0 Int
0 Int
0

-- | Configurable limits per scope. 'Nothing' means unlimited.
data ResourceLimits = ResourceLimits
  { ResourceLimits -> Maybe Int
rlMaxConnsInbound :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxConnsOutbound :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxConnsTotal :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxStreamsInbound :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxStreamsOutbound :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxStreamsTotal :: !(Maybe Int)
  , ResourceLimits -> Maybe Int
rlMaxMemory :: !(Maybe Int)
  } deriving (Int -> ResourceLimits -> ShowS
[ResourceLimits] -> ShowS
ResourceLimits -> String
(Int -> ResourceLimits -> ShowS)
-> (ResourceLimits -> String)
-> ([ResourceLimits] -> ShowS)
-> Show ResourceLimits
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ResourceLimits -> ShowS
showsPrec :: Int -> ResourceLimits -> ShowS
$cshow :: ResourceLimits -> String
show :: ResourceLimits -> String
$cshowList :: [ResourceLimits] -> ShowS
showList :: [ResourceLimits] -> ShowS
Show, ResourceLimits -> ResourceLimits -> Bool
(ResourceLimits -> ResourceLimits -> Bool)
-> (ResourceLimits -> ResourceLimits -> Bool) -> Eq ResourceLimits
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResourceLimits -> ResourceLimits -> Bool
== :: ResourceLimits -> ResourceLimits -> Bool
$c/= :: ResourceLimits -> ResourceLimits -> Bool
/= :: ResourceLimits -> ResourceLimits -> Bool
Eq)

noLimits :: ResourceLimits
noLimits :: ResourceLimits
noLimits = Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> ResourceLimits
ResourceLimits Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing

-- | Stable names make sibling connection and stream scopes distinguishable.
data ScopeName
  = SystemScope
  | PeerScope !PeerId
  | ConnectionScope !Int
  | StreamScope !Int
  deriving (Int -> ScopeName -> ShowS
[ScopeName] -> ShowS
ScopeName -> String
(Int -> ScopeName -> ShowS)
-> (ScopeName -> String)
-> ([ScopeName] -> ShowS)
-> Show ScopeName
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ScopeName -> ShowS
showsPrec :: Int -> ScopeName -> ShowS
$cshow :: ScopeName -> String
show :: ScopeName -> String
$cshowList :: [ScopeName] -> ShowS
showList :: [ScopeName] -> ShowS
Show, ScopeName -> ScopeName -> Bool
(ScopeName -> ScopeName -> Bool)
-> (ScopeName -> ScopeName -> Bool) -> Eq ScopeName
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ScopeName -> ScopeName -> Bool
== :: ScopeName -> ScopeName -> Bool
$c/= :: ScopeName -> ScopeName -> Bool
/= :: ScopeName -> ScopeName -> Bool
Eq, Eq ScopeName
Eq ScopeName =>
(ScopeName -> ScopeName -> Ordering)
-> (ScopeName -> ScopeName -> Bool)
-> (ScopeName -> ScopeName -> Bool)
-> (ScopeName -> ScopeName -> Bool)
-> (ScopeName -> ScopeName -> Bool)
-> (ScopeName -> ScopeName -> ScopeName)
-> (ScopeName -> ScopeName -> ScopeName)
-> Ord ScopeName
ScopeName -> ScopeName -> Bool
ScopeName -> ScopeName -> Ordering
ScopeName -> ScopeName -> ScopeName
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: ScopeName -> ScopeName -> Ordering
compare :: ScopeName -> ScopeName -> Ordering
$c< :: ScopeName -> ScopeName -> Bool
< :: ScopeName -> ScopeName -> Bool
$c<= :: ScopeName -> ScopeName -> Bool
<= :: ScopeName -> ScopeName -> Bool
$c> :: ScopeName -> ScopeName -> Bool
> :: ScopeName -> ScopeName -> Bool
$c>= :: ScopeName -> ScopeName -> Bool
>= :: ScopeName -> ScopeName -> Bool
$cmax :: ScopeName -> ScopeName -> ScopeName
max :: ScopeName -> ScopeName -> ScopeName
$cmin :: ScopeName -> ScopeName -> ScopeName
min :: ScopeName -> ScopeName -> ScopeName
Ord)

-- | A node in the resource ownership tree.
data ResourceScope = ResourceScope
  { ResourceScope -> ScopeName
rsName :: !ScopeName
  , ResourceScope -> TVar ResourceUsage
rsUsage :: !(TVar ResourceUsage)
  , ResourceScope -> ResourceLimits
rsLimits :: !ResourceLimits
  , ResourceScope -> Maybe ResourceScope
rsParent :: !(Maybe ResourceScope)
  , ResourceScope -> TVar (Map Int ResourceScope)
rsChildren :: !(TVar (Map.Map Int ResourceScope))
  , ResourceScope -> TVar Bool
rsClosed :: !(TVar Bool)
  }

-- | Resource reservation failures.
data ResourceError
  = ResourceLimitExceeded !ScopeName !String
  | ResourceScopeClosed !ScopeName
  | InvalidMemoryReservation !Int
  | InvalidParentScope !ScopeName
  deriving (Int -> ResourceError -> ShowS
[ResourceError] -> ShowS
ResourceError -> String
(Int -> ResourceError -> ShowS)
-> (ResourceError -> String)
-> ([ResourceError] -> ShowS)
-> Show ResourceError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ResourceError -> ShowS
showsPrec :: Int -> ResourceError -> ShowS
$cshow :: ResourceError -> String
show :: ResourceError -> String
$cshowList :: [ResourceError] -> ShowS
showList :: [ResourceError] -> ShowS
Show, ResourceError -> ResourceError -> Bool
(ResourceError -> ResourceError -> Bool)
-> (ResourceError -> ResourceError -> Bool) -> Eq ResourceError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResourceError -> ResourceError -> Bool
== :: ResourceError -> ResourceError -> Bool
$c/= :: ResourceError -> ResourceError -> Bool
/= :: ResourceError -> ResourceError -> Bool
Eq)

instance Exception ResourceError

-- | Generic memory hooks used by buffering layers without exposing the tree.
data MemoryAccount = MemoryAccount
  { MemoryAccount -> Int -> STM (Either ResourceError ())
maReserve :: !(Int -> STM (Either ResourceError ()))
  , MemoryAccount -> Int -> STM ()
maRelease :: !(Int -> STM ())
  , MemoryAccount -> STM ()
maClose :: !(STM ())
  }

-- | Limits used for automatically-created scopes.
data DefaultLimits = DefaultLimits
  { DefaultLimits -> ResourceLimits
dlSystemLimits :: !ResourceLimits
  , DefaultLimits -> ResourceLimits
dlPeerLimits :: !ResourceLimits
  , DefaultLimits -> ResourceLimits
dlConnectionLimits :: !ResourceLimits
  , DefaultLimits -> ResourceLimits
dlStreamLimits :: !ResourceLimits
  } deriving (Int -> DefaultLimits -> ShowS
[DefaultLimits] -> ShowS
DefaultLimits -> String
(Int -> DefaultLimits -> ShowS)
-> (DefaultLimits -> String)
-> ([DefaultLimits] -> ShowS)
-> Show DefaultLimits
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DefaultLimits -> ShowS
showsPrec :: Int -> DefaultLimits -> ShowS
$cshow :: DefaultLimits -> String
show :: DefaultLimits -> String
$cshowList :: [DefaultLimits] -> ShowS
showList :: [DefaultLimits] -> ShowS
Show, DefaultLimits -> DefaultLimits -> Bool
(DefaultLimits -> DefaultLimits -> Bool)
-> (DefaultLimits -> DefaultLimits -> Bool) -> Eq DefaultLimits
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DefaultLimits -> DefaultLimits -> Bool
== :: DefaultLimits -> DefaultLimits -> Bool
$c/= :: DefaultLimits -> DefaultLimits -> Bool
/= :: DefaultLimits -> DefaultLimits -> Bool
Eq)

defaultSystemLimits :: ResourceLimits
defaultSystemLimits :: ResourceLimits
defaultSystemLimits = ResourceLimits
noLimits
  { rlMaxConnsInbound = Just 256
  , rlMaxConnsOutbound = Just 256
  , rlMaxConnsTotal = Just 512
  , rlMaxStreamsInbound = Just 4096
  , rlMaxStreamsOutbound = Just 4096
  , rlMaxStreamsTotal = Just 8192
  , rlMaxMemory = Just (256 * 1024 * 1024)
  }

defaultPeerLimits :: ResourceLimits
defaultPeerLimits :: ResourceLimits
defaultPeerLimits = ResourceLimits
noLimits
  { rlMaxConnsInbound = Just 4
  , rlMaxConnsOutbound = Just 4
  , rlMaxConnsTotal = Just 8
  , rlMaxStreamsInbound = Just 256
  , rlMaxStreamsOutbound = Just 256
  , rlMaxStreamsTotal = Just 512
  , rlMaxMemory = Just (16 * 1024 * 1024)
  }

defaultConnectionLimits :: ResourceLimits
defaultConnectionLimits :: ResourceLimits
defaultConnectionLimits = ResourceLimits
noLimits

defaultStreamLimits :: ResourceLimits
defaultStreamLimits :: ResourceLimits
defaultStreamLimits = ResourceLimits
noLimits

data ResourceManager = ResourceManager
  { ResourceManager -> ResourceScope
rmSystemScope :: !ResourceScope
  , ResourceManager -> DefaultLimits
rmDefaults :: !DefaultLimits
  , ResourceManager -> TVar (Map PeerId ResourceScope)
rmPeerScopes :: !(TVar (Map.Map PeerId ResourceScope))
  , ResourceManager -> TVar Int
rmNextScopeId :: !(TVar Int)
  }

newResourceManager :: DefaultLimits -> IO ResourceManager
newResourceManager :: DefaultLimits -> IO ResourceManager
newResourceManager DefaultLimits
defaults = STM ResourceManager -> IO ResourceManager
forall a. STM a -> IO a
atomically (STM ResourceManager -> IO ResourceManager)
-> STM ResourceManager -> IO ResourceManager
forall a b. (a -> b) -> a -> b
$ do
  systemScope <- ScopeName
-> ResourceLimits -> Maybe ResourceScope -> STM ResourceScope
newScope ScopeName
SystemScope (DefaultLimits -> ResourceLimits
dlSystemLimits DefaultLimits
defaults) Maybe ResourceScope
forall a. Maybe a
Nothing
  peers <- newTVar Map.empty
  nextId <- newTVar 1
  pure ResourceManager
    { rmSystemScope = systemScope
    , rmDefaults = defaults
    , rmPeerScopes = peers
    , rmNextScopeId = nextId
    }

newScope :: ScopeName -> ResourceLimits -> Maybe ResourceScope -> STM ResourceScope
newScope :: ScopeName
-> ResourceLimits -> Maybe ResourceScope -> STM ResourceScope
newScope ScopeName
name ResourceLimits
limits Maybe ResourceScope
parent = do
  usage <- ResourceUsage -> STM (TVar ResourceUsage)
forall a. a -> STM (TVar a)
newTVar ResourceUsage
emptyUsage
  children <- newTVar Map.empty
  closed <- newTVar False
  pure ResourceScope
    { rsName = name
    , rsUsage = usage
    , rsLimits = limits
    , rsParent = parent
    , rsChildren = children
    , rsClosed = closed
    }

nextScopeId :: ResourceManager -> STM Int
nextScopeId :: ResourceManager -> STM Int
nextScopeId ResourceManager
rm = do
  scopeId <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar (ResourceManager -> TVar Int
rmNextScopeId ResourceManager
rm)
  writeTVar (rmNextScopeId rm) (scopeId + 1)
  pure scopeId

getOrCreatePeerScope :: ResourceManager -> PeerId -> STM ResourceScope
getOrCreatePeerScope :: ResourceManager -> PeerId -> STM ResourceScope
getOrCreatePeerScope ResourceManager
rm PeerId
pid = do
  peers <- TVar (Map PeerId ResourceScope) -> STM (Map PeerId ResourceScope)
forall a. TVar a -> STM a
readTVar (ResourceManager -> TVar (Map PeerId ResourceScope)
rmPeerScopes ResourceManager
rm)
  case Map.lookup pid peers of
    Just ResourceScope
scope -> ResourceScope -> STM ResourceScope
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ResourceScope
scope
    Maybe ResourceScope
Nothing -> do
      scope <- ScopeName
-> ResourceLimits -> Maybe ResourceScope -> STM ResourceScope
newScope (PeerId -> ScopeName
PeerScope PeerId
pid) (DefaultLimits -> ResourceLimits
dlPeerLimits (ResourceManager -> DefaultLimits
rmDefaults ResourceManager
rm))
        (ResourceScope -> Maybe ResourceScope
forall a. a -> Maybe a
Just (ResourceManager -> ResourceScope
rmSystemScope ResourceManager
rm))
      writeTVar (rmPeerScopes rm) (Map.insert pid scope peers)
      pure scope

-- | Create and reserve one connection scope.
reserveConnection
  :: ResourceManager -> PeerId -> Direction
  -> STM (Either ResourceError ResourceScope)
reserveConnection :: ResourceManager
-> PeerId -> Direction -> STM (Either ResourceError ResourceScope)
reserveConnection ResourceManager
rm PeerId
pid Direction
direction = do
  peer <- ResourceManager -> PeerId -> STM ResourceScope
getOrCreatePeerScope ResourceManager
rm PeerId
pid
  scopeId <- nextScopeId rm
  scope <- newScope (ConnectionScope scopeId)
    (dlConnectionLimits (rmDefaults rm)) (Just peer)
  result <- reserveUsage scope (incrementConnection direction)
  case result of
    Left ResourceError
err -> ResourceManager -> ResourceScope -> STM ()
dropPeerIfUnused ResourceManager
rm ResourceScope
peer STM ()
-> STM (Either ResourceError ResourceScope)
-> STM (Either ResourceError ResourceScope)
forall a b. STM a -> STM b -> STM b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either ResourceError ResourceScope
-> STM (Either ResourceError ResourceScope)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ResourceScope
forall a b. a -> Either a b
Left ResourceError
err)
    Right () -> ResourceScope -> Int -> ResourceScope -> STM ()
attachChild ResourceScope
peer Int
scopeId ResourceScope
scope STM ()
-> STM (Either ResourceError ResourceScope)
-> STM (Either ResourceError ResourceScope)
forall a b. STM a -> STM b -> STM b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either ResourceError ResourceScope
-> STM (Either ResourceError ResourceScope)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceScope -> Either ResourceError ResourceScope
forall a b. b -> Either a b
Right ResourceScope
scope)

-- | Close a connection and every stream it owns. Idempotent.
releaseConnection :: ResourceManager -> ResourceScope -> STM ()
releaseConnection :: ResourceManager -> ResourceScope -> STM ()
releaseConnection ResourceManager
rm ResourceScope
scope = case ResourceScope -> ScopeName
rsName ResourceScope
scope of
  ConnectionScope Int
_ -> ResourceManager -> ResourceScope -> STM ()
closeOwnedScope ResourceManager
rm ResourceScope
scope
  ScopeName
_ -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

-- | Create and reserve one stream below a connection scope.
reserveStream
  :: ResourceManager -> ResourceScope -> Direction
  -> STM (Either ResourceError ResourceScope)
reserveStream :: ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream ResourceManager
rm ResourceScope
connection Direction
direction = case ResourceScope -> ScopeName
rsName ResourceScope
connection of
  ConnectionScope Int
_ -> do
    scopeId <- ResourceManager -> STM Int
nextScopeId ResourceManager
rm
    scope <- newScope (StreamScope scopeId)
      (dlStreamLimits (rmDefaults rm)) (Just connection)
    result <- reserveUsage scope (incrementStream direction)
    case result of
      Left ResourceError
err -> Either ResourceError ResourceScope
-> STM (Either ResourceError ResourceScope)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ResourceScope
forall a b. a -> Either a b
Left ResourceError
err)
      Right () -> ResourceScope -> Int -> ResourceScope -> STM ()
attachChild ResourceScope
connection Int
scopeId ResourceScope
scope STM ()
-> STM (Either ResourceError ResourceScope)
-> STM (Either ResourceError ResourceScope)
forall a b. STM a -> STM b -> STM b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either ResourceError ResourceScope
-> STM (Either ResourceError ResourceScope)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceScope -> Either ResourceError ResourceScope
forall a b. b -> Either a b
Right ResourceScope
scope)
  ScopeName
name -> Either ResourceError ResourceScope
-> STM (Either ResourceError ResourceScope)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ResourceScope
forall a b. a -> Either a b
Left (ScopeName -> ResourceError
InvalidParentScope ScopeName
name))

-- | Close a stream and release all usage it still owns. Idempotent.
releaseStream :: ResourceManager -> ResourceScope -> STM ()
releaseStream :: ResourceManager -> ResourceScope -> STM ()
releaseStream ResourceManager
rm ResourceScope
scope = case ResourceScope -> ScopeName
rsName ResourceScope
scope of
  StreamScope Int
_ -> ResourceManager -> ResourceScope -> STM ()
closeOwnedScope ResourceManager
rm ResourceScope
scope
  ScopeName
_ -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

reserveMemory :: ResourceScope -> Int -> STM (Either ResourceError ())
reserveMemory :: ResourceScope -> Int -> STM (Either ResourceError ())
reserveMemory ResourceScope
_ Int
bytes | Int
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = Either ResourceError () -> STM (Either ResourceError ())
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ()
forall a b. a -> Either a b
Left (Int -> ResourceError
InvalidMemoryReservation Int
bytes))
reserveMemory ResourceScope
scope Int
bytes = ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError ())
reserveUsage ResourceScope
scope ((ResourceUsage -> ResourceUsage) -> STM (Either ResourceError ()))
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError ())
forall a b. (a -> b) -> a -> b
$ \ResourceUsage
usage ->
  ResourceUsage
usage {ruMemory = ruMemory usage + bytes}

releaseMemory :: ResourceScope -> Int -> STM ()
releaseMemory :: ResourceScope -> Int -> STM ()
releaseMemory ResourceScope
_ Int
bytes | Int
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
releaseMemory ResourceScope
scope Int
bytes = do
  usage <- TVar ResourceUsage -> STM ResourceUsage
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
scope)
  let released = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min Int
bytes (ResourceUsage -> Int
ruMemory ResourceUsage
usage)
  subtractMemoryFromChain scope released

scopeMemoryAccount :: ResourceManager -> ResourceScope -> MemoryAccount
scopeMemoryAccount :: ResourceManager -> ResourceScope -> MemoryAccount
scopeMemoryAccount ResourceManager
rm ResourceScope
scope = MemoryAccount
  { maReserve :: Int -> STM (Either ResourceError ())
maReserve = ResourceScope -> Int -> STM (Either ResourceError ())
reserveMemory ResourceScope
scope
  , maRelease :: Int -> STM ()
maRelease = ResourceManager -> ResourceScope -> Int -> STM ()
releaseAccountMemory ResourceManager
rm ResourceScope
scope
  , maClose :: STM ()
maClose = ResourceManager -> ResourceScope -> STM ()
closeOwnedScope ResourceManager
rm ResourceScope
scope
  }

releaseAccountMemory :: ResourceManager -> ResourceScope -> Int -> STM ()
releaseAccountMemory :: ResourceManager -> ResourceScope -> Int -> STM ()
releaseAccountMemory ResourceManager
rm ResourceScope
scope Int
bytes = do
  ResourceScope -> Int -> STM ()
releaseMemory ResourceScope
scope Int
bytes
  ResourceManager -> ResourceScope -> STM ()
finalizeDrainedStream ResourceManager
rm ResourceScope
scope

-- | An account for standalone protocol use where no manager is installed.
unlimitedMemoryAccount :: MemoryAccount
unlimitedMemoryAccount :: MemoryAccount
unlimitedMemoryAccount = MemoryAccount
  { maReserve :: Int -> STM (Either ResourceError ())
maReserve = \Int
bytes -> if Int
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0
      then Either ResourceError () -> STM (Either ResourceError ())
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either ResourceError ()
forall a b. b -> Either a b
Right ())
      else Either ResourceError () -> STM (Either ResourceError ())
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ()
forall a b. a -> Either a b
Left (Int -> ResourceError
InvalidMemoryReservation Int
bytes))
  , maRelease :: Int -> STM ()
maRelease = STM () -> Int -> STM ()
forall a b. a -> b -> a
const (() -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
  , maClose :: STM ()
maClose = () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  }

withConnection
  :: ResourceManager -> PeerId -> Direction
  -> (ResourceScope -> IO a) -> IO a
withConnection :: forall a.
ResourceManager
-> PeerId -> Direction -> (ResourceScope -> IO a) -> IO a
withConnection ResourceManager
rm PeerId
pid Direction
direction = IO ResourceScope
-> (ResourceScope -> IO ()) -> (ResourceScope -> IO a) -> IO a
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket IO ResourceScope
acquire ResourceScope -> IO ()
release
  where
    acquire :: IO ResourceScope
acquire = STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (ResourceManager
-> PeerId -> Direction -> STM (Either ResourceError ResourceScope)
reserveConnection ResourceManager
rm PeerId
pid Direction
direction)
      IO (Either ResourceError ResourceScope)
-> (Either ResourceError ResourceScope -> IO ResourceScope)
-> IO ResourceScope
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ResourceError -> IO ResourceScope)
-> (ResourceScope -> IO ResourceScope)
-> Either ResourceError ResourceScope
-> IO ResourceScope
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO ResourceScope
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ResourceScope)
-> (ResourceError -> String) -> ResourceError -> IO ResourceScope
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ResourceError -> String
forall a. Show a => a -> String
show) ResourceScope -> IO ResourceScope
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    release :: ResourceScope -> IO ()
release = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ())
-> (ResourceScope -> STM ()) -> ResourceScope -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ResourceManager -> ResourceScope -> STM ()
releaseConnection ResourceManager
rm

withStream
  :: ResourceManager -> ResourceScope -> Direction
  -> (ResourceScope -> IO a) -> IO a
withStream :: forall a.
ResourceManager
-> ResourceScope -> Direction -> (ResourceScope -> IO a) -> IO a
withStream ResourceManager
rm ResourceScope
connection Direction
direction = IO ResourceScope
-> (ResourceScope -> IO ()) -> (ResourceScope -> IO a) -> IO a
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket IO ResourceScope
acquire ResourceScope -> IO ()
release
  where
    acquire :: IO ResourceScope
acquire = STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream ResourceManager
rm ResourceScope
connection Direction
direction)
      IO (Either ResourceError ResourceScope)
-> (Either ResourceError ResourceScope -> IO ResourceScope)
-> IO ResourceScope
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ResourceError -> IO ResourceScope)
-> (ResourceScope -> IO ResourceScope)
-> Either ResourceError ResourceScope
-> IO ResourceScope
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO ResourceScope
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ResourceScope)
-> (ResourceError -> String) -> ResourceError -> IO ResourceScope
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ResourceError -> String
forall a. Show a => a -> String
show) ResourceScope -> IO ResourceScope
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    release :: ResourceScope -> IO ()
release = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ())
-> (ResourceScope -> STM ()) -> ResourceScope -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ResourceManager -> ResourceScope -> STM ()
releaseStream ResourceManager
rm

attachChild :: ResourceScope -> Int -> ResourceScope -> STM ()
attachChild :: ResourceScope -> Int -> ResourceScope -> STM ()
attachChild ResourceScope
parent Int
scopeId ResourceScope
child =
  TVar (Map Int ResourceScope)
-> (Map Int ResourceScope -> Map Int ResourceScope) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (ResourceScope -> TVar (Map Int ResourceScope)
rsChildren ResourceScope
parent) (Int
-> ResourceScope -> Map Int ResourceScope -> Map Int ResourceScope
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Int
scopeId ResourceScope
child)

reserveUsage
  :: ResourceScope -> (ResourceUsage -> ResourceUsage)
  -> STM (Either ResourceError ())
reserveUsage :: ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError ())
reserveUsage ResourceScope
scope ResourceUsage -> ResourceUsage
update = do
  proposed <- ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectUpdates ResourceScope
scope ResourceUsage -> ResourceUsage
update
  case proposed of
    Left ResourceError
err -> Either ResourceError () -> STM (Either ResourceError ())
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError -> Either ResourceError ()
forall a b. a -> Either a b
Left ResourceError
err)
    Right [(ResourceScope, ResourceUsage)]
updates -> do
      ((ResourceScope, ResourceUsage) -> STM ())
-> [(ResourceScope, ResourceUsage)] -> STM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ((ResourceScope -> ResourceUsage -> STM ())
-> (ResourceScope, ResourceUsage) -> STM ()
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry ResourceScope -> ResourceUsage -> STM ()
writeScopeUsage) [(ResourceScope, ResourceUsage)]
updates
      Either ResourceError () -> STM (Either ResourceError ())
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either ResourceError ()
forall a b. b -> Either a b
Right ())

writeScopeUsage :: ResourceScope -> ResourceUsage -> STM ()
writeScopeUsage :: ResourceScope -> ResourceUsage -> STM ()
writeScopeUsage = TVar ResourceUsage -> ResourceUsage -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (TVar ResourceUsage -> ResourceUsage -> STM ())
-> (ResourceScope -> TVar ResourceUsage)
-> ResourceScope
-> ResourceUsage
-> STM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ResourceScope -> TVar ResourceUsage
rsUsage

collectUpdates
  :: ResourceScope -> (ResourceUsage -> ResourceUsage)
  -> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectUpdates :: ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectUpdates ResourceScope
scope ResourceUsage -> ResourceUsage
update = do
  closed <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar Bool
rsClosed ResourceScope
scope)
  if closed
    then pure (Left (ResourceScopeClosed (rsName scope)))
    else do
      proposed <- update <$> readTVar (rsUsage scope)
      case checkLimits scope proposed of
        Left ResourceError
err -> Either ResourceError [(ResourceScope, ResourceUsage)]
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ResourceError
-> Either ResourceError [(ResourceScope, ResourceUsage)]
forall a b. a -> Either a b
Left ResourceError
err)
        Right () -> ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> ResourceUsage
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectParentUpdates ResourceScope
scope ResourceUsage -> ResourceUsage
update ResourceUsage
proposed

collectParentUpdates
  :: ResourceScope -> (ResourceUsage -> ResourceUsage) -> ResourceUsage
  -> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectParentUpdates :: ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> ResourceUsage
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectParentUpdates ResourceScope
scope ResourceUsage -> ResourceUsage
update ResourceUsage
proposed = case ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope of
  Maybe ResourceScope
Nothing -> Either ResourceError [(ResourceScope, ResourceUsage)]
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([(ResourceScope, ResourceUsage)]
-> Either ResourceError [(ResourceScope, ResourceUsage)]
forall a b. b -> Either a b
Right [(ResourceScope
scope, ResourceUsage
proposed)])
  Just ResourceScope
parent -> do
    parentResult <- ResourceScope
-> (ResourceUsage -> ResourceUsage)
-> STM (Either ResourceError [(ResourceScope, ResourceUsage)])
collectUpdates ResourceScope
parent ResourceUsage -> ResourceUsage
update
    pure $ ((scope, proposed) :) <$> parentResult

checkLimits :: ResourceScope -> ResourceUsage -> Either ResourceError ()
checkLimits :: ResourceScope -> ResourceUsage -> Either ResourceError ()
checkLimits ResourceScope
scope ResourceUsage
usage = [(Maybe Int, Int, String)] -> Either ResourceError ()
forall {a}.
Ord a =>
[(Maybe a, a, String)] -> Either ResourceError ()
firstExceeded [(Maybe Int, Int, String)]
checks
  where
    limits :: ResourceLimits
limits = ResourceScope -> ResourceLimits
rsLimits ResourceScope
scope
    checks :: [(Maybe Int, Int, String)]
checks =
      [ (ResourceLimits -> Maybe Int
rlMaxConnsInbound ResourceLimits
limits, ResourceUsage -> Int
ruConnsInbound ResourceUsage
usage, String
"inbound connections")
      , (ResourceLimits -> Maybe Int
rlMaxConnsOutbound ResourceLimits
limits, ResourceUsage -> Int
ruConnsOutbound ResourceUsage
usage, String
"outbound connections")
      , (ResourceLimits -> Maybe Int
rlMaxConnsTotal ResourceLimits
limits, ResourceUsage -> Int
totalConnections ResourceUsage
usage, String
"total connections")
      , (ResourceLimits -> Maybe Int
rlMaxStreamsInbound ResourceLimits
limits, ResourceUsage -> Int
ruStreamsInbound ResourceUsage
usage, String
"inbound streams")
      , (ResourceLimits -> Maybe Int
rlMaxStreamsOutbound ResourceLimits
limits, ResourceUsage -> Int
ruStreamsOutbound ResourceUsage
usage, String
"outbound streams")
      , (ResourceLimits -> Maybe Int
rlMaxStreamsTotal ResourceLimits
limits, ResourceUsage -> Int
totalStreams ResourceUsage
usage, String
"total streams")
      , (ResourceLimits -> Maybe Int
rlMaxMemory ResourceLimits
limits, ResourceUsage -> Int
ruMemory ResourceUsage
usage, String
"memory")
      ]
    firstExceeded :: [(Maybe a, a, String)] -> Either ResourceError ()
firstExceeded [] = () -> Either ResourceError ()
forall a b. b -> Either a b
Right ()
    firstExceeded ((Just a
limit, a
actual, String
label) : [(Maybe a, a, String)]
rest)
      | a
actual a -> a -> Bool
forall a. Ord a => a -> a -> Bool
> a
limit = ResourceError -> Either ResourceError ()
forall a b. a -> Either a b
Left (ScopeName -> String -> ResourceError
ResourceLimitExceeded (ResourceScope -> ScopeName
rsName ResourceScope
scope) String
label)
      | Bool
otherwise = [(Maybe a, a, String)] -> Either ResourceError ()
firstExceeded [(Maybe a, a, String)]
rest
    firstExceeded ((Maybe a
Nothing, a
_, String
_) : [(Maybe a, a, String)]
rest) = [(Maybe a, a, String)] -> Either ResourceError ()
firstExceeded [(Maybe a, a, String)]
rest

incrementConnection :: Direction -> ResourceUsage -> ResourceUsage
incrementConnection :: Direction -> ResourceUsage -> ResourceUsage
incrementConnection Direction
Inbound ResourceUsage
usage =
  ResourceUsage
usage {ruConnsInbound = ruConnsInbound usage + 1}
incrementConnection Direction
Outbound ResourceUsage
usage =
  ResourceUsage
usage {ruConnsOutbound = ruConnsOutbound usage + 1}

incrementStream :: Direction -> ResourceUsage -> ResourceUsage
incrementStream :: Direction -> ResourceUsage -> ResourceUsage
incrementStream Direction
Inbound ResourceUsage
usage =
  ResourceUsage
usage {ruStreamsInbound = ruStreamsInbound usage + 1}
incrementStream Direction
Outbound ResourceUsage
usage =
  ResourceUsage
usage {ruStreamsOutbound = ruStreamsOutbound usage + 1}

totalConnections :: ResourceUsage -> Int
totalConnections :: ResourceUsage -> Int
totalConnections ResourceUsage
usage = ResourceUsage -> Int
ruConnsInbound ResourceUsage
usage Int -> Int -> Int
forall a. Num a => a -> a -> a
+ ResourceUsage -> Int
ruConnsOutbound ResourceUsage
usage

totalStreams :: ResourceUsage -> Int
totalStreams :: ResourceUsage -> Int
totalStreams ResourceUsage
usage = ResourceUsage -> Int
ruStreamsInbound ResourceUsage
usage Int -> Int -> Int
forall a. Num a => a -> a -> a
+ ResourceUsage -> Int
ruStreamsOutbound ResourceUsage
usage

closeOwnedScope :: ResourceManager -> ResourceScope -> STM ()
closeOwnedScope :: ResourceManager -> ResourceScope -> STM ()
closeOwnedScope ResourceManager
rm ResourceScope
scope = case ResourceScope -> ScopeName
rsName ResourceScope
scope of
  StreamScope Int
_ -> ResourceManager -> ResourceScope -> STM ()
closeStreamScope ResourceManager
rm ResourceScope
scope
  ScopeName
_ -> ResourceManager -> ResourceScope -> STM ()
closeScopeImmediately ResourceManager
rm ResourceScope
scope

-- Keep a closing stream charged while queued payloads still own memory.
-- Their final release completes the close without permitting new reserves.
closeStreamScope :: ResourceManager -> ResourceScope -> STM ()
closeStreamScope :: ResourceManager -> ResourceScope -> STM ()
closeStreamScope ResourceManager
rm ResourceScope
scope = do
  TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (ResourceScope -> TVar Bool
rsClosed ResourceScope
scope) Bool
True
  ResourceManager -> ResourceScope -> STM ()
finalizeDrainedStream ResourceManager
rm ResourceScope
scope

finalizeDrainedStream :: ResourceManager -> ResourceScope -> STM ()
finalizeDrainedStream :: ResourceManager -> ResourceScope -> STM ()
finalizeDrainedStream ResourceManager
rm ResourceScope
scope = case ResourceScope -> ScopeName
rsName ResourceScope
scope of
  StreamScope Int
_ -> do
    closed <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar Bool
rsClosed ResourceScope
scope)
    usage <- readTVar (rsUsage scope)
    if closed && ruMemory usage == 0 && usage /= emptyUsage
      then finalizeScope rm scope usage
      else pure ()
  ScopeName
_ -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

closeScopeImmediately :: ResourceManager -> ResourceScope -> STM ()
closeScopeImmediately :: ResourceManager -> ResourceScope -> STM ()
closeScopeImmediately ResourceManager
rm ResourceScope
scope = do
  closed <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar Bool
rsClosed ResourceScope
scope)
  unless closed $ do
    usage <- readTVar (rsUsage scope)
    markSubtreeClosed scope
    finalizeScope rm scope usage

finalizeScope :: ResourceManager -> ResourceScope -> ResourceUsage -> STM ()
finalizeScope :: ResourceManager -> ResourceScope -> ResourceUsage -> STM ()
finalizeScope ResourceManager
rm ResourceScope
scope ResourceUsage
usage = do
  TVar ResourceUsage -> ResourceUsage -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
scope) ResourceUsage
emptyUsage
  Maybe ResourceScope -> ResourceUsage -> STM ()
subtractUsageFromParents (ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope) ResourceUsage
usage
  ResourceScope -> STM ()
detachFromParent ResourceScope
scope
  ResourceManager -> ResourceScope -> STM ()
maybeDropOwningPeer ResourceManager
rm ResourceScope
scope

markSubtreeClosed :: ResourceScope -> STM ()
markSubtreeClosed :: ResourceScope -> STM ()
markSubtreeClosed ResourceScope
scope = do
  TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (ResourceScope -> TVar Bool
rsClosed ResourceScope
scope) Bool
True
  TVar ResourceUsage -> ResourceUsage -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
scope) ResourceUsage
emptyUsage
  children <- TVar (Map Int ResourceScope) -> STM (Map Int ResourceScope)
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar (Map Int ResourceScope)
rsChildren ResourceScope
scope)
  mapM_ markSubtreeClosed (Map.elems children)
  writeTVar (rsChildren scope) Map.empty

subtractUsageFromParents :: Maybe ResourceScope -> ResourceUsage -> STM ()
subtractUsageFromParents :: Maybe ResourceScope -> ResourceUsage -> STM ()
subtractUsageFromParents Maybe ResourceScope
Nothing ResourceUsage
_ = () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
subtractUsageFromParents (Just ResourceScope
scope) ResourceUsage
usage = do
  TVar ResourceUsage -> (ResourceUsage -> ResourceUsage) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
scope) (ResourceUsage -> ResourceUsage -> ResourceUsage
`minusUsage` ResourceUsage
usage)
  Maybe ResourceScope -> ResourceUsage -> STM ()
subtractUsageFromParents (ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope) ResourceUsage
usage

subtractMemoryFromChain :: ResourceScope -> Int -> STM ()
subtractMemoryFromChain :: ResourceScope -> Int -> STM ()
subtractMemoryFromChain ResourceScope
_ Int
0 = () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
subtractMemoryFromChain ResourceScope
scope Int
bytes = do
  TVar ResourceUsage -> (ResourceUsage -> ResourceUsage) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
scope) ((ResourceUsage -> ResourceUsage) -> STM ())
-> (ResourceUsage -> ResourceUsage) -> STM ()
forall a b. (a -> b) -> a -> b
$ \ResourceUsage
usage ->
    ResourceUsage
usage {ruMemory = max 0 (ruMemory usage - bytes)}
  case ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope of
    Maybe ResourceScope
Nothing -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Just ResourceScope
parent -> ResourceScope -> Int -> STM ()
subtractMemoryFromChain ResourceScope
parent Int
bytes

minusUsage :: ResourceUsage -> ResourceUsage -> ResourceUsage
minusUsage :: ResourceUsage -> ResourceUsage -> ResourceUsage
minusUsage ResourceUsage
current ResourceUsage
released = ResourceUsage
  { ruConnsInbound :: Int
ruConnsInbound = Int -> Int -> Int
forall {a}. (Ord a, Num a) => a -> a -> a
difference (ResourceUsage -> Int
ruConnsInbound ResourceUsage
current) (ResourceUsage -> Int
ruConnsInbound ResourceUsage
released)
  , ruConnsOutbound :: Int
ruConnsOutbound = Int -> Int -> Int
forall {a}. (Ord a, Num a) => a -> a -> a
difference (ResourceUsage -> Int
ruConnsOutbound ResourceUsage
current) (ResourceUsage -> Int
ruConnsOutbound ResourceUsage
released)
  , ruStreamsInbound :: Int
ruStreamsInbound = Int -> Int -> Int
forall {a}. (Ord a, Num a) => a -> a -> a
difference (ResourceUsage -> Int
ruStreamsInbound ResourceUsage
current) (ResourceUsage -> Int
ruStreamsInbound ResourceUsage
released)
  , ruStreamsOutbound :: Int
ruStreamsOutbound = Int -> Int -> Int
forall {a}. (Ord a, Num a) => a -> a -> a
difference (ResourceUsage -> Int
ruStreamsOutbound ResourceUsage
current) (ResourceUsage -> Int
ruStreamsOutbound ResourceUsage
released)
  , ruMemory :: Int
ruMemory = Int -> Int -> Int
forall {a}. (Ord a, Num a) => a -> a -> a
difference (ResourceUsage -> Int
ruMemory ResourceUsage
current) (ResourceUsage -> Int
ruMemory ResourceUsage
released)
  }
  where
    difference :: a -> a -> a
difference a
a a
b = a -> a -> a
forall a. Ord a => a -> a -> a
max a
0 (a
a a -> a -> a
forall a. Num a => a -> a -> a
- a
b)

detachFromParent :: ResourceScope -> STM ()
detachFromParent :: ResourceScope -> STM ()
detachFromParent ResourceScope
scope = case (ScopeName -> Maybe Int
scopeIdOf (ResourceScope -> ScopeName
rsName ResourceScope
scope), ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope) of
  (Just Int
scopeId, Just ResourceScope
parent) ->
    TVar (Map Int ResourceScope)
-> (Map Int ResourceScope -> Map Int ResourceScope) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (ResourceScope -> TVar (Map Int ResourceScope)
rsChildren ResourceScope
parent) (Int -> Map Int ResourceScope -> Map Int ResourceScope
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete Int
scopeId)
  (Maybe Int, Maybe ResourceScope)
_ -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

scopeIdOf :: ScopeName -> Maybe Int
scopeIdOf :: ScopeName -> Maybe Int
scopeIdOf (ConnectionScope Int
scopeId) = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
scopeId
scopeIdOf (StreamScope Int
scopeId) = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
scopeId
scopeIdOf ScopeName
_ = Maybe Int
forall a. Maybe a
Nothing

maybeDropOwningPeer :: ResourceManager -> ResourceScope -> STM ()
maybeDropOwningPeer :: ResourceManager -> ResourceScope -> STM ()
maybeDropOwningPeer ResourceManager
rm ResourceScope
scope = case ResourceScope -> Maybe ResourceScope
owningPeer ResourceScope
scope of
  Maybe ResourceScope
Nothing -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  Just ResourceScope
peer -> ResourceManager -> ResourceScope -> STM ()
dropPeerIfUnused ResourceManager
rm ResourceScope
peer

owningPeer :: ResourceScope -> Maybe ResourceScope
owningPeer :: ResourceScope -> Maybe ResourceScope
owningPeer ResourceScope
scope = case ResourceScope -> ScopeName
rsName ResourceScope
scope of
  PeerScope PeerId
_ -> ResourceScope -> Maybe ResourceScope
forall a. a -> Maybe a
Just ResourceScope
scope
  ScopeName
_ -> ResourceScope -> Maybe ResourceScope
rsParent ResourceScope
scope Maybe ResourceScope
-> (ResourceScope -> Maybe ResourceScope) -> Maybe ResourceScope
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ResourceScope -> Maybe ResourceScope
owningPeer

dropPeerIfUnused :: ResourceManager -> ResourceScope -> STM ()
dropPeerIfUnused :: ResourceManager -> ResourceScope -> STM ()
dropPeerIfUnused ResourceManager
rm ResourceScope
peer = case ResourceScope -> ScopeName
rsName ResourceScope
peer of
  PeerScope PeerId
pid -> do
    usage <- TVar ResourceUsage -> STM ResourceUsage
forall a. TVar a -> STM a
readTVar (ResourceScope -> TVar ResourceUsage
rsUsage ResourceScope
peer)
    children <- readTVar (rsChildren peer)
    if usage == emptyUsage && Map.null children
      then do
        modifyTVar' (rmPeerScopes rm) (Map.delete pid)
        writeTVar (rsClosed peer) True
      else pure ()
  ScopeName
_ -> () -> STM ()
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()