packages feed

pykinos-core-0.1.1.0: src/Pykinos/Queue/TimingWheel.hs

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}
-- | Module: Pykinos.Queue.TimingWheel
-- Description: 4-level × 64-slot hierarchical hashed timing wheel
--
-- Provides an unboxed hierarchical timing wheel timer multiplexer. Supports
-- $O(1)$ timer arming and $O(1)$ amortized tick advancement with cascading across
-- 4 levels of 64-slot wheels ($64^4 = 16,777,216$ ticks capacity).
module Pykinos.Queue.TimingWheel
  ( TimingWheel
  , newTimingWheel
  , armTimer
  , advanceTick
  , currentTick
  ) where

import Control.Monad (forM_, when)
import Control.Monad.ST (ST)
import Data.Bits (shiftR, (.&.))
import Data.Primitive.Array
  ( MutableArray
  , newArray
  , readArray
  , writeArray
  )
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)
import Data.Word (Word32, Word64)

-- | An entry in the timing wheel: deadline tick and handle payload.
data TimerEntry = TimerEntry
  { teDeadline :: {-# UNPACK #-} !Word64
  , teHandle   :: {-# UNPACK #-} !Word32
  } deriving stock (Eq, Show)

-- | 4-level × 64-slot hierarchical timing wheel in @ST s@.
data TimingWheel s = TimingWheel
  { twCurrentTick :: !(STRef s Word64)
  , twLevel0      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 1 tick/slot
  , twLevel1      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 64 ticks/slot
  , twLevel2      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 4096 ticks/slot
  , twLevel3      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 262144 ticks/slot
  }

-- | Allocates an empty 'TimingWheel' initialized at tick 0.
newTimingWheel :: ST s (TimingWheel s)
newTimingWheel = do
  curRef <- newSTRef 0
  l0 <- newArray 64 []
  l1 <- newArray 64 []
  l2 <- newArray 64 []
  l3 <- newArray 64 []
  pure (TimingWheel curRef l0 l1 l2 l3)

-- | Returns the current monotonic tick of the timing wheel.
currentTick :: TimingWheel s -> ST s Word64
currentTick (TimingWheel curRef _ _ _ _) = readSTRef curRef

-- | Arms a timer to fire at absolute tick @deadline@ with handle @payload@.
armTimer :: TimingWheel s -> Word64 -> Word32 -> ST s ()
armTimer (TimingWheel curRef l0 l1 l2 l3) !deadline !h = do
  !now <- readSTRef curRef
  let !target = max now deadline
      !delta  = target - now
      !entry  = TimerEntry target h
  if delta < 64
    then addEntry l0 (target .&. 63) entry
    else if delta < 4096
      then addEntry l1 ((target `shiftR` 6) .&. 63) entry
      else if delta < 262144
        then addEntry l2 ((target `shiftR` 12) .&. 63) entry
        else addEntry l3 ((target `shiftR` 18) .&. 63) entry
  where
    addEntry arr !slot !e = do
      let !s = fromIntegral slot
      entries <- readArray arr s
      writeArray arr s (e : entries)

-- | Advances the wheel by 1 tick, cascading higher-level wheels as slots wrap,
-- and returns all expired handles.
advanceTick :: TimingWheel s -> ST s [Word32]
advanceTick tw@(TimingWheel curRef l0 l1 l2 l3) = do
  !now <- readSTRef curRef
  let !nextTick = now + 1
  writeSTRef curRef nextTick
  let !slot0 = fromIntegral (nextTick .&. 63)
  -- If slot0 wrapped to 0, cascade L1
  when (slot0 == 0) $ cascadeLevel tw l1 6
  -- If L1 also wrapped, cascade L2
  when ((nextTick .&. 4095) == 0) $ cascadeLevel tw l2 12
  -- If L2 also wrapped, cascade L3
  when ((nextTick .&. 262143) == 0) $ cascadeLevel tw l3 18
  -- Collect expired entries from L0 at slot0
  entries <- readArray l0 slot0
  writeArray l0 slot0 []
  let (!expired, !remaining) = partitionEntries nextTick entries
  -- Re-arm any non-expired (should be rare/empty in L0)
  forM_ remaining $ \(TimerEntry d h) -> armTimer tw d h
  pure (map teHandle expired)
  where
    partitionEntries _ [] = ([], [])
    partitionEntries !target (e : es)
      | teDeadline e <= target =
          let (!expList, !remList) = partitionEntries target es
          in (e : expList, remList)
      | otherwise =
          let (!expList, !remList) = partitionEntries target es
          in (expList, e : remList)

-- | Re-arms entries from a higher level down into lower levels.
cascadeLevel :: TimingWheel s -> MutableArray s [TimerEntry] -> Int -> ST s ()
cascadeLevel tw arr !shift = do
  !now <- currentTick tw
  let !slot = fromIntegral ((now `shiftR` shift) .&. 63)
  entries <- readArray arr slot
  writeArray arr slot []
  forM_ entries $ \(TimerEntry d h) -> armTimer tw d h