-- | DHT provider republishing and value-record expiry maintenance.
module LibP2P.DHT.Maintenance
  ( DHTMaintenanceConfig (..)
  , defaultDHTMaintenanceConfig
  , DHTMaintenanceState
  , newDHTMaintenanceState
  , startValueGCWorker
  , runValueGCTick
  , ensureProviderWorker
  , stopDHTMaintenance
  , storeReceivedRecord
  , lookupLiveRecord
  , recordIsExpired
  , rememberLocalProvider
  , nextLocalProviderBatch
  ) where

import Control.Concurrent (threadDelay, yield)
import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Concurrent.STM
import Control.Monad (unless, when)
import Data.ByteString (ByteString)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (isNothing)
import qualified Data.Text as T
import Data.Time (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Format.ISO8601 (iso8601ParseM, iso8601Show)
import LibP2P.DHT.Message (DHTRecord (..))
import LibP2P.Multiaddr (Multiaddr)

-- | Scheduling, expiry, and per-tick work limits for DHT maintenance.
data DHTMaintenanceConfig = DHTMaintenanceConfig
  { DHTMaintenanceConfig -> Int
dmcProviderRepublishIntervalMicros :: !Int
    -- ^ Delay between complete provider republish cycles, in microseconds.
  , DHTMaintenanceConfig -> Int
dmcValueGCIntervalMicros :: !Int
    -- ^ Delay between bounded value GC ticks. Non-positive disables GC.
  , DHTMaintenanceConfig -> NominalDiffTime
dmcRecordMaxAge :: !NominalDiffTime
    -- ^ Receiver-side value-record TTL. Non-positive disables age expiry.
  , DHTMaintenanceConfig -> Int
dmcProviderBatchSize :: !Int
    -- ^ Maximum provider announcements started before yielding.
  , DHTMaintenanceConfig -> Int
dmcValueGCBatchSize :: !Int
    -- ^ Maximum value records inspected by one GC tick.
  , DHTMaintenanceConfig -> IO UTCTime
dmcNow :: !(IO UTCTime)
    -- ^ Wall clock used for receive timestamps and expiry checks.
  }

-- | go-libp2p Amino DHT defaults: providers republish every 22 hours,
-- value records expire after 48 hours, and value GC runs every 24 hours.
defaultDHTMaintenanceConfig :: DHTMaintenanceConfig
defaultDHTMaintenanceConfig :: DHTMaintenanceConfig
defaultDHTMaintenanceConfig = DHTMaintenanceConfig
  { dmcProviderRepublishIntervalMicros :: Int
dmcProviderRepublishIntervalMicros = Int
22 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
hour
  , dmcValueGCIntervalMicros :: Int
dmcValueGCIntervalMicros = Int
24 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
hour
  , dmcRecordMaxAge :: NominalDiffTime
dmcRecordMaxAge = NominalDiffTime
48 NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a -> a
* NominalDiffTime
3600
  , dmcProviderBatchSize :: Int
dmcProviderBatchSize = Int
64
  , dmcValueGCBatchSize :: Int
dmcValueGCBatchSize = Int
256
  , dmcNow :: IO UTCTime
dmcNow = IO UTCTime
getCurrentTime
  }
  where
    hour :: Int
hour = Int
60 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
60 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1000000

-- | Mutable worker state owned by one DHT node.
data DHTMaintenanceState = DHTMaintenanceState
  { DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig :: !DHTMaintenanceConfig
  , DHTMaintenanceState -> TVar (Map ByteString [Multiaddr])
dmsLocalProviders :: !(TVar (Map ByteString [Multiaddr]))
  , DHTMaintenanceState -> TVar (Maybe (Async ()))
dmsProviderWorker :: !(TVar (Maybe (Async ())))
  , DHTMaintenanceState -> TVar (Maybe ByteString)
dmsProviderCursor :: !(TVar (Maybe ByteString))
  , DHTMaintenanceState -> TVar (Maybe (Async ()))
dmsValueGCWorker :: !(TVar (Maybe (Async ())))
  , DHTMaintenanceState -> TVar (Maybe ByteString)
dmsValueGCCursor :: !(TVar (Maybe ByteString))
  , DHTMaintenanceState -> MVar ()
dmsWorkerLock :: !(MVar ())
  }

newDHTMaintenanceState :: DHTMaintenanceConfig -> IO DHTMaintenanceState
newDHTMaintenanceState :: DHTMaintenanceConfig -> IO DHTMaintenanceState
newDHTMaintenanceState DHTMaintenanceConfig
config = do
  DHTMaintenanceConfig -> IO ()
validateConfig DHTMaintenanceConfig
config
  DHTMaintenanceConfig
-> TVar (Map ByteString [Multiaddr])
-> TVar (Maybe (Async ()))
-> TVar (Maybe ByteString)
-> TVar (Maybe (Async ()))
-> TVar (Maybe ByteString)
-> MVar ()
-> DHTMaintenanceState
DHTMaintenanceState DHTMaintenanceConfig
config
    (TVar (Map ByteString [Multiaddr])
 -> TVar (Maybe (Async ()))
 -> TVar (Maybe ByteString)
 -> TVar (Maybe (Async ()))
 -> TVar (Maybe ByteString)
 -> MVar ()
 -> DHTMaintenanceState)
-> IO (TVar (Map ByteString [Multiaddr]))
-> IO
     (TVar (Maybe (Async ()))
      -> TVar (Maybe ByteString)
      -> TVar (Maybe (Async ()))
      -> TVar (Maybe ByteString)
      -> MVar ()
      -> DHTMaintenanceState)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map ByteString [Multiaddr]
-> IO (TVar (Map ByteString [Multiaddr]))
forall a. a -> IO (TVar a)
newTVarIO Map ByteString [Multiaddr]
forall k a. Map k a
Map.empty
    IO
  (TVar (Maybe (Async ()))
   -> TVar (Maybe ByteString)
   -> TVar (Maybe (Async ()))
   -> TVar (Maybe ByteString)
   -> MVar ()
   -> DHTMaintenanceState)
-> IO (TVar (Maybe (Async ())))
-> IO
     (TVar (Maybe ByteString)
      -> TVar (Maybe (Async ()))
      -> TVar (Maybe ByteString)
      -> MVar ()
      -> DHTMaintenanceState)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe (Async ()) -> IO (TVar (Maybe (Async ())))
forall a. a -> IO (TVar a)
newTVarIO Maybe (Async ())
forall a. Maybe a
Nothing
    IO
  (TVar (Maybe ByteString)
   -> TVar (Maybe (Async ()))
   -> TVar (Maybe ByteString)
   -> MVar ()
   -> DHTMaintenanceState)
-> IO (TVar (Maybe ByteString))
-> IO
     (TVar (Maybe (Async ()))
      -> TVar (Maybe ByteString) -> MVar () -> DHTMaintenanceState)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe ByteString -> IO (TVar (Maybe ByteString))
forall a. a -> IO (TVar a)
newTVarIO Maybe ByteString
forall a. Maybe a
Nothing
    IO
  (TVar (Maybe (Async ()))
   -> TVar (Maybe ByteString) -> MVar () -> DHTMaintenanceState)
-> IO (TVar (Maybe (Async ())))
-> IO (TVar (Maybe ByteString) -> MVar () -> DHTMaintenanceState)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe (Async ()) -> IO (TVar (Maybe (Async ())))
forall a. a -> IO (TVar a)
newTVarIO Maybe (Async ())
forall a. Maybe a
Nothing
    IO (TVar (Maybe ByteString) -> MVar () -> DHTMaintenanceState)
-> IO (TVar (Maybe ByteString))
-> IO (MVar () -> DHTMaintenanceState)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe ByteString -> IO (TVar (Maybe ByteString))
forall a. a -> IO (TVar a)
newTVarIO Maybe ByteString
forall a. Maybe a
Nothing
    IO (MVar () -> DHTMaintenanceState)
-> IO (MVar ()) -> IO DHTMaintenanceState
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> () -> IO (MVar ())
forall a. a -> IO (MVar a)
newMVar ()

validateConfig :: DHTMaintenanceConfig -> IO ()
validateConfig :: DHTMaintenanceConfig -> IO ()
validateConfig DHTMaintenanceConfig
config
  | DHTMaintenanceConfig -> Int
dmcProviderRepublishIntervalMicros DHTMaintenanceConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = [Char] -> IO ()
forall {a}. [Char] -> IO a
invalid [Char]
"provider interval must be positive"
  | DHTMaintenanceConfig -> Int
dmcProviderBatchSize DHTMaintenanceConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = [Char] -> IO ()
forall {a}. [Char] -> IO a
invalid [Char]
"provider batch size must be positive"
  | DHTMaintenanceConfig -> Int
dmcValueGCBatchSize DHTMaintenanceConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = [Char] -> IO ()
forall {a}. [Char] -> IO a
invalid [Char]
"value GC batch size must be positive"
  | Bool
otherwise = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  where
    invalid :: [Char] -> IO a
invalid = IOError -> IO a
forall a. IOError -> IO a
ioError (IOError -> IO a) -> ([Char] -> IOError) -> [Char] -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> IOError
userError ([Char] -> IOError) -> ([Char] -> [Char]) -> [Char] -> IOError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char]
"invalid DHT maintenance configuration: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++)

-- | Start the bounded value-record GC loop. Non-positive age or interval
-- disables the worker, matching go-libp2p's configuration semantics.
startValueGCWorker
  :: DHTMaintenanceState
  -> TVar Bool
  -> TVar (Map ByteString DHTRecord)
  -> IO ()
startValueGCWorker :: DHTMaintenanceState
-> TVar Bool -> TVar (Map ByteString DHTRecord) -> IO ()
startValueGCWorker DHTMaintenanceState
state TVar Bool
stopped TVar (Map ByteString DHTRecord)
records
  | DHTMaintenanceConfig -> NominalDiffTime
dmcRecordMaxAge DHTMaintenanceConfig
config NominalDiffTime -> NominalDiffTime -> Bool
forall a. Ord a => a -> a -> Bool
<= NominalDiffTime
0 = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  | DHTMaintenanceConfig -> Int
dmcValueGCIntervalMicros DHTMaintenanceConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  | Bool
otherwise = MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (DHTMaintenanceState -> MVar ()
dmsWorkerLock DHTMaintenanceState
state) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
      existing <- TVar (Maybe (Async ())) -> IO (Maybe (Async ()))
forall a. TVar a -> IO a
readTVarIO (DHTMaintenanceState -> TVar (Maybe (Async ()))
dmsValueGCWorker DHTMaintenanceState
state)
      when (isNothing existing) $ do
        worker <- async (valueGCLoop state stopped records)
        atomically $ writeTVar (dmsValueGCWorker state) (Just worker)
  where
    config :: DHTMaintenanceConfig
config = DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state

valueGCLoop
  :: DHTMaintenanceState
  -> TVar Bool
  -> TVar (Map ByteString DHTRecord)
  -> IO ()
valueGCLoop :: DHTMaintenanceState
-> TVar Bool -> TVar (Map ByteString DHTRecord) -> IO ()
valueGCLoop DHTMaintenanceState
state TVar Bool
stopped TVar (Map ByteString DHTRecord)
records = do
  Int -> IO ()
threadDelay (DHTMaintenanceConfig -> Int
dmcValueGCIntervalMicros (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state))
  isStopped <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO TVar Bool
stopped
  unless isStopped $ do
    runValueGCTick state records
    valueGCLoop state stopped records

-- | Start the provider worker once. After each configured interval it walks
-- every locally provided key in bounded batches, yielding between batches.
ensureProviderWorker :: DHTMaintenanceState -> TVar Bool -> IO Int -> IO ()
ensureProviderWorker :: DHTMaintenanceState -> TVar Bool -> IO Int -> IO ()
ensureProviderWorker DHTMaintenanceState
state TVar Bool
stopped IO Int
tick =
  MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (DHTMaintenanceState -> MVar ()
dmsWorkerLock DHTMaintenanceState
state) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
    isStopped <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO TVar Bool
stopped
    existing <- readTVarIO (dmsProviderWorker state)
    when (not isStopped && isNothing existing) $ do
      worker <- async (providerLoop state stopped tick)
      atomically $ writeTVar (dmsProviderWorker state) (Just worker)

providerLoop :: DHTMaintenanceState -> TVar Bool -> IO Int -> IO ()
providerLoop :: DHTMaintenanceState -> TVar Bool -> IO Int -> IO ()
providerLoop DHTMaintenanceState
state TVar Bool
stopped IO Int
tick = do
  Int -> IO ()
threadDelay (DHTMaintenanceConfig -> Int
dmcProviderRepublishIntervalMicros (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state))
  providerCount <- Map ByteString [Multiaddr] -> Int
forall k a. Map k a -> Int
Map.size (Map ByteString [Multiaddr] -> Int)
-> IO (Map ByteString [Multiaddr]) -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (Map ByteString [Multiaddr])
-> IO (Map ByteString [Multiaddr])
forall a. TVar a -> IO a
readTVarIO (DHTMaintenanceState -> TVar (Map ByteString [Multiaddr])
dmsLocalProviders DHTMaintenanceState
state)
  runCycle providerCount
  where
    runCycle :: Int -> IO ()
runCycle Int
remaining
      | Int
remaining Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = DHTMaintenanceState -> TVar Bool -> IO Int -> IO ()
providerLoop DHTMaintenanceState
state TVar Bool
stopped IO Int
tick
      | Bool
otherwise = do
          isStopped <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO TVar Bool
stopped
          unless isStopped $ do
            processed <- tick
            if processed <= 0
              then providerLoop state stopped tick
              else yield >> runCycle (remaining - processed)

-- | Cancel every maintenance worker and clear their handles.
stopDHTMaintenance :: DHTMaintenanceState -> IO ()
stopDHTMaintenance :: DHTMaintenanceState -> IO ()
stopDHTMaintenance DHTMaintenanceState
state = MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (DHTMaintenanceState -> MVar ()
dmsWorkerLock DHTMaintenanceState
state) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
  workers <- STM [Maybe (Async ())] -> IO [Maybe (Async ())]
forall a. STM a -> IO a
atomically (STM [Maybe (Async ())] -> IO [Maybe (Async ())])
-> STM [Maybe (Async ())] -> IO [Maybe (Async ())]
forall a b. (a -> b) -> a -> b
$ do
    provider <- TVar (Maybe (Async ())) -> STM (Maybe (Async ()))
forall a. TVar a -> STM a
readTVar (DHTMaintenanceState -> TVar (Maybe (Async ()))
dmsProviderWorker DHTMaintenanceState
state)
    valueGC <- readTVar (dmsValueGCWorker state)
    writeTVar (dmsProviderWorker state) Nothing
    writeTVar (dmsValueGCWorker state) Nothing
    pure [provider, valueGC]
  mapM_ (mapM_ cancel) workers

-- | Store a value record with a receiver-controlled timestamp.
storeReceivedRecord
  :: DHTMaintenanceState
  -> TVar (Map ByteString DHTRecord)
  -> DHTRecord
  -> IO ()
storeReceivedRecord :: DHTMaintenanceState
-> TVar (Map ByteString DHTRecord) -> DHTRecord -> IO ()
storeReceivedRecord DHTMaintenanceState
state TVar (Map ByteString DHTRecord)
records DHTRecord
record = do
  now <- DHTMaintenanceConfig -> IO UTCTime
dmcNow (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)
  let stored = DHTRecord
record { recTimeReceived = T.pack (iso8601Show now) }
  atomically $ modifyTVar' records (Map.insert (recKey stored) stored)

-- | Read a live record, deleting malformed, misfiled, or expired data.
lookupLiveRecord
  :: DHTMaintenanceState
  -> TVar (Map ByteString DHTRecord)
  -> ByteString
  -> IO (Maybe DHTRecord)
lookupLiveRecord :: DHTMaintenanceState
-> TVar (Map ByteString DHTRecord)
-> ByteString
-> IO (Maybe DHTRecord)
lookupLiveRecord DHTMaintenanceState
state TVar (Map ByteString DHTRecord)
records ByteString
key = do
  now <- DHTMaintenanceConfig -> IO UTCTime
dmcNow (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)
  atomically $ do
    stored <- readTVar records
    case Map.lookup key stored of
      Maybe DHTRecord
Nothing -> Maybe DHTRecord -> STM (Maybe DHTRecord)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe DHTRecord
forall a. Maybe a
Nothing
      Just DHTRecord
record
        | DHTRecord -> ByteString
recKey DHTRecord
record ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= ByteString
key Bool -> Bool -> Bool
|| DHTMaintenanceState -> UTCTime -> DHTRecord -> Bool
recordIsExpired DHTMaintenanceState
state UTCTime
now DHTRecord
record -> do
            TVar (Map ByteString DHTRecord)
-> Map ByteString DHTRecord -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar (Map ByteString DHTRecord)
records (ByteString -> Map ByteString DHTRecord -> Map ByteString DHTRecord
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete ByteString
key Map ByteString DHTRecord
stored)
            Maybe DHTRecord -> STM (Maybe DHTRecord)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe DHTRecord
forall a. Maybe a
Nothing
        | Bool
otherwise -> Maybe DHTRecord -> STM (Maybe DHTRecord)
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DHTRecord -> Maybe DHTRecord
forall a. a -> Maybe a
Just DHTRecord
record)

-- | Whether a record is older than the configured maximum age. Missing or
-- malformed receive times are expired when age checking is enabled.
recordIsExpired :: DHTMaintenanceState -> UTCTime -> DHTRecord -> Bool
recordIsExpired :: DHTMaintenanceState -> UTCTime -> DHTRecord -> Bool
recordIsExpired DHTMaintenanceState
state UTCTime
now DHTRecord
record
  | NominalDiffTime
maxAge NominalDiffTime -> NominalDiffTime -> Bool
forall a. Ord a => a -> a -> Bool
<= NominalDiffTime
0 = Bool
False
  | Bool
otherwise = case [Char] -> Maybe UTCTime
forall (m :: * -> *) t. (MonadFail m, ISO8601 t) => [Char] -> m t
iso8601ParseM (Text -> [Char]
T.unpack (DHTRecord -> Text
recTimeReceived DHTRecord
record)) of
      Maybe UTCTime
Nothing -> Bool
True
      Just UTCTime
received -> UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
now UTCTime
received NominalDiffTime -> NominalDiffTime -> Bool
forall a. Ord a => a -> a -> Bool
> NominalDiffTime
maxAge
  where
    maxAge :: NominalDiffTime
maxAge = DHTMaintenanceConfig -> NominalDiffTime
dmcRecordMaxAge (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)

-- | Track a key that this node still provides.
rememberLocalProvider
  :: DHTMaintenanceState -> ByteString -> [Multiaddr] -> IO ()
rememberLocalProvider :: DHTMaintenanceState -> ByteString -> [Multiaddr] -> IO ()
rememberLocalProvider DHTMaintenanceState
state ByteString
key [Multiaddr]
addrs = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
  TVar (Map ByteString [Multiaddr])
-> (Map ByteString [Multiaddr] -> Map ByteString [Multiaddr])
-> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (DHTMaintenanceState -> TVar (Map ByteString [Multiaddr])
dmsLocalProviders DHTMaintenanceState
state) (ByteString
-> [Multiaddr]
-> Map ByteString [Multiaddr]
-> Map ByteString [Multiaddr]
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert ByteString
key [Multiaddr]
addrs)

-- | Select the next bounded provider batch, rotating through the keyspace so
-- a large provider set cannot starve keys beyond the first batch.
nextLocalProviderBatch
  :: DHTMaintenanceState -> IO [(ByteString, [Multiaddr])]
nextLocalProviderBatch :: DHTMaintenanceState -> IO [(ByteString, [Multiaddr])]
nextLocalProviderBatch DHTMaintenanceState
state = STM [(ByteString, [Multiaddr])] -> IO [(ByteString, [Multiaddr])]
forall a. STM a -> IO a
atomically (STM [(ByteString, [Multiaddr])] -> IO [(ByteString, [Multiaddr])])
-> STM [(ByteString, [Multiaddr])]
-> IO [(ByteString, [Multiaddr])]
forall a b. (a -> b) -> a -> b
$ do
  providers <- TVar (Map ByteString [Multiaddr])
-> STM (Map ByteString [Multiaddr])
forall a. TVar a -> STM a
readTVar (DHTMaintenanceState -> TVar (Map ByteString [Multiaddr])
dmsLocalProviders DHTMaintenanceState
state)
  cursor <- readTVar (dmsProviderCursor state)
  let batch = Int
-> Maybe ByteString
-> Map ByteString [Multiaddr]
-> [(ByteString, [Multiaddr])]
forall a.
Int -> Maybe ByteString -> Map ByteString a -> [(ByteString, a)]
selectBatch (DHTMaintenanceConfig -> Int
dmcProviderBatchSize (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)) Maybe ByteString
cursor Map ByteString [Multiaddr]
providers
  writeTVar (dmsProviderCursor state) (fst <$> lastMaybe batch)
  pure batch

-- | Delete at most one configured batch of expired records.
runValueGCTick
  :: DHTMaintenanceState -> TVar (Map ByteString DHTRecord) -> IO ()
runValueGCTick :: DHTMaintenanceState -> TVar (Map ByteString DHTRecord) -> IO ()
runValueGCTick DHTMaintenanceState
state TVar (Map ByteString DHTRecord)
records = do
  now <- DHTMaintenanceConfig -> IO UTCTime
dmcNow (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)
  atomically $ do
    stored <- readTVar records
    cursor <- readTVar (dmsValueGCCursor state)
    let batch = Int
-> Maybe ByteString
-> Map ByteString DHTRecord
-> [(ByteString, DHTRecord)]
forall a.
Int -> Maybe ByteString -> Map ByteString a -> [(ByteString, a)]
selectBatch (DHTMaintenanceConfig -> Int
dmcValueGCBatchSize (DHTMaintenanceState -> DHTMaintenanceConfig
dmsConfig DHTMaintenanceState
state)) Maybe ByteString
cursor Map ByteString DHTRecord
stored
        expired =
          [ ByteString
key
          | (ByteString
key, DHTRecord
record) <- [(ByteString, DHTRecord)]
batch
          , DHTRecord -> ByteString
recKey DHTRecord
record ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= ByteString
key Bool -> Bool -> Bool
|| DHTMaintenanceState -> UTCTime -> DHTRecord -> Bool
recordIsExpired DHTMaintenanceState
state UTCTime
now DHTRecord
record
          ]
    writeTVar records (foldr Map.delete stored expired)
    writeTVar (dmsValueGCCursor state) (fst <$> lastMaybe batch)

selectBatch :: Int -> Maybe ByteString -> Map ByteString a -> [(ByteString, a)]
selectBatch :: forall a.
Int -> Maybe ByteString -> Map ByteString a -> [(ByteString, a)]
selectBatch Int
limit Maybe ByteString
Nothing Map ByteString a
entries = Int -> [(ByteString, a)] -> [(ByteString, a)]
forall a. Int -> [a] -> [a]
take Int
limit (Map ByteString a -> [(ByteString, a)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map ByteString a
entries)
selectBatch Int
limit (Just ByteString
previous) Map ByteString a
entries = [(ByteString, a)]
after [(ByteString, a)] -> [(ByteString, a)] -> [(ByteString, a)]
forall a. Semigroup a => a -> a -> a
<> [(ByteString, a)]
wrapped
  where
    (Map ByteString a
_, Maybe a
_, Map ByteString a
greater) = ByteString
-> Map ByteString a
-> (Map ByteString a, Maybe a, Map ByteString a)
forall k a. Ord k => k -> Map k a -> (Map k a, Maybe a, Map k a)
Map.splitLookup ByteString
previous Map ByteString a
entries
    after :: [(ByteString, a)]
after = Int -> [(ByteString, a)] -> [(ByteString, a)]
forall a. Int -> [a] -> [a]
take Int
limit (Map ByteString a -> [(ByteString, a)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map ByteString a
greater)
    wrapped :: [(ByteString, a)]
wrapped = Int -> [(ByteString, a)] -> [(ByteString, a)]
forall a. Int -> [a] -> [a]
take (Int
limit Int -> Int -> Int
forall a. Num a => a -> a -> a
- [(ByteString, a)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(ByteString, a)]
after) (Map ByteString a -> [(ByteString, a)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map ByteString a
entries)

lastMaybe :: [a] -> Maybe a
lastMaybe :: forall a. [a] -> Maybe a
lastMaybe = (Maybe a -> a -> Maybe a) -> Maybe a -> [a] -> Maybe a
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl (\Maybe a
_ a
value -> a -> Maybe a
forall a. a -> Maybe a
Just a
value) Maybe a
forall a. Maybe a
Nothing