{-# LANGUAGE RecursiveDo #-}

-- | A simple, hashed timer wheel.
module TimerWheel
  ( -- * Timer wheel
    TimerWheel,
    create,
    with,
    Config (..),
    register,
    register_,
    recurring,
    recurring_,
  )
where

import Control.Exception (throwIO)
import Control.Monad (when)
import Data.Bool (bool)
import Data.Fixed (E6, Fixed)
import Data.Function (fix)
import Data.IORef (newIORef, readIORef, writeIORef)
import GHC.Exception (errorCallException)
import qualified Ki
import TimerWheel.Internal.Config (Config)
import qualified TimerWheel.Internal.Config as Config
import TimerWheel.Internal.Micros (Micros (Micros))
import qualified TimerWheel.Internal.Micros as Micros
import TimerWheel.Internal.Supply (Supply)
import qualified TimerWheel.Internal.Supply as Supply
import TimerWheel.Internal.Wheel (Wheel)
import qualified TimerWheel.Internal.Wheel as Wheel

-- | A timer wheel is a vector-of-collections-of timers to fire. It is configured with a /spoke count/ and /resolution/.
-- Timers may be scheduled arbitrarily far in the future. A timeout thread is spawned to step through the timer wheel
-- and fire expired timers at regular intervals.
--
-- * The /spoke count/ determines the size of the timer vector.
--
--     * A __larger spoke count__ will result in __less insert contention__ at each spoke and will require
--       __more memory__ to store the timer wheel.
--
--     * A __smaller spoke count__ will result in __more insert contention__ at each spoke and will require
--       __less memory__ to store the timer wheel.
--
-- * The /resolution/ determines both the duration of time that each spoke corresponds to, and how often the timeout
--   thread wakes. For example, with a resolution of __@1s@__, a timer that expires at __@2.5s@__ will not fire until
--   the timeout thread wakes at __@3s@__.
--
--     * A __larger resolution__ will result in __more insert contention__ at each spoke, __less accurate__ timers, and
--       will require __fewer wakeups__ by the timeout thread.
--
--     * A __smaller resolution__ will result in __less insert contention__ at each spoke, __more accurate__ timers, and
--       will require __more wakeups__ by the timeout thread.
--
-- * The timeout thread has some important properties:
--
--     * There is only one, and it fires expired timers synchronously. If your timer actions execute quicky, 'register'
--       them directly. Otherwise, consider registering an action that enqueues the /real/ action to be performed on a
--       job queue.
--
--     * Synchronous exceptions thrown by enqueued @IO@ actions will bring the thread down, and the exception will be
--       propagated to the thread that created the timer wheel. If you want to catch exceptions and log them, for
--       example, you will have to bake this into the registered actions yourself.
--
-- As an example, below is a depiction of a timer wheel with @6@ timers inserted across @8@ spokes, and a resolution of
-- @.1s@. It depicts a cursor at @.3s@, which indicates where the timeout thread currently is.
--
-- @
--  0       .1      .2      .3      .4      .5      .6      .7
-- ┌───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐
-- │       │ A⁰    │       │ B¹ C⁰ │ D⁰    │       │       │ E² F⁰ │
-- └───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘
--                           ↑
-- @
--
-- After @.1s@, the timeout thread will advance to the next spoke and process all of the timers it passed over. In
-- this case, __C__ will fire, and __B__ will be put back with its count decremented to @0@. This is how the timer wheel
-- can schedule a timer to fire arbitrarily far in the future: its count is simply the number of times its delay wraps
-- the entire duration of the timer wheel.
--
-- @
--  0       .1      .2      .3      .4      .5      .6      .7
-- ┌───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐
-- │       │ A⁰    │       │ B⁰    │ D⁰    │       │       │ E² F⁰ │
-- └───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘
--                                   ↑
-- @
data TimerWheel = TimerWheel
  { -- | A supply of unique ints.
    TimerWheel -> Supply
supply :: {-# UNPACK #-} !Supply,
    -- | The array of collections of timers.
    TimerWheel -> Wheel
wheel :: {-# UNPACK #-} !Wheel
    -- thread :: {-# UNPACK #-} !ThreadId
  }

-- | Create a timer wheel in a scope.
--
-- /Throws./
--
--   * Calls 'error' if the config is invalid
create :: Ki.Scope -> Config -> IO TimerWheel
create :: Scope -> Config -> IO TimerWheel
create Scope
scope Config
config = do
  Config -> IO ()
validateConfig Config
config
  Wheel
wheel <- Int -> Micros -> IO Wheel
Wheel.create (Config -> Int
Config.spokes Config
config) (Fixed E6 -> Micros
Micros.fromFixed (Config -> Fixed E6
Config.resolution Config
config))
  Supply
supply <- IO Supply
Supply.new
  Scope -> IO Void -> IO ()
Ki.fork_ Scope
scope (forall a. Wheel -> IO a
Wheel.reap Wheel
wheel)
  forall (f :: * -> *) a. Applicative f => a -> f a
pure TimerWheel {Supply
supply :: Supply
supply :: Supply
supply, Wheel
wheel :: Wheel
wheel :: Wheel
wheel}

-- | Perform an action with a timer wheel.
--
-- /Throws./
--
--   * Calls 'error' if the config is invalid
--   * Throws the exception the given action throws, if any
--   * Throws the exception the timer wheel thread throws, if any
with :: Config -> (TimerWheel -> IO a) -> IO a
with :: forall a. Config -> (TimerWheel -> IO a) -> IO a
with Config
config TimerWheel -> IO a
action =
  forall a. (Scope -> IO a) -> IO a
Ki.scoped \Scope
scope -> do
    TimerWheel
wheel <- Scope -> Config -> IO TimerWheel
create Scope
scope Config
config
    TimerWheel -> IO a
action TimerWheel
wheel

validateConfig :: Config -> IO ()
validateConfig :: Config -> IO ()
validateConfig Config
config =
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Config -> Int
Config.spokes Config
config forall a. Ord a => a -> a -> Bool
<= Int
0 Bool -> Bool -> Bool
|| Config -> Fixed E6
Config.resolution Config
config forall a. Ord a => a -> a -> Bool
<= Fixed E6
0) do
    forall e a. Exception e => e -> IO a
throwIO (String -> SomeException
errorCallException (String
"timer-wheel: invalid config: " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show Config
config))

-- | @register wheel delay action@ registers an action __@action@__ in timer wheel __@wheel@__ to fire after __@delay@__
-- seconds.
--
-- Returns an action that, when called, attempts to cancel the timer, and returns whether or not it was successful
-- (@False@ means the timer has already fired, or was already cancelled).
register ::
  TimerWheel ->
  -- | Delay, in seconds
  Fixed E6 ->
  -- | Action
  IO () ->
  IO (IO Bool)
register :: TimerWheel -> Fixed E6 -> IO () -> IO (IO Bool)
register TimerWheel
wheel Fixed E6
delay =
  TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl TimerWheel
wheel (Fixed E6 -> Micros
Micros.fromSeconds (forall a. Ord a => a -> a -> a
max Fixed E6
0 Fixed E6
delay))

-- | Like 'register', but for when you don't intend to cancel the timer.
register_ ::
  TimerWheel ->
  -- | Delay, in seconds
  Fixed E6 ->
  -- | Action
  IO () ->
  IO ()
register_ :: TimerWheel -> Fixed E6 -> IO () -> IO ()
register_ TimerWheel
wheel Fixed E6
delay IO ()
action = do
  IO Bool
_ <- TimerWheel -> Fixed E6 -> IO () -> IO (IO Bool)
register TimerWheel
wheel Fixed E6
delay IO ()
action
  forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

registerImpl :: TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl :: TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl TimerWheel {Supply
supply :: Supply
supply :: TimerWheel -> Supply
supply, Wheel
wheel :: Wheel
wheel :: TimerWheel -> Wheel
wheel} Micros
delay IO ()
action = do
  Int
key <- Supply -> IO Int
Supply.next Supply
supply
  Wheel -> Int -> Micros -> IO () -> IO (IO Bool)
Wheel.insert Wheel
wheel Int
key Micros
delay IO ()
action

-- | @recurring wheel action delay@ registers an action __@action@__ in timer wheel __@wheel@__ to fire every
-- __@delay@__ seconds.
--
-- Returns an action that, when called, cancels the recurring timer.
recurring ::
  TimerWheel ->
  -- | Delay, in seconds
  Fixed E6 ->
  -- | Action
  IO () ->
  IO (IO ())
recurring :: TimerWheel -> Fixed E6 -> IO () -> IO (IO ())
recurring TimerWheel
wheel (Fixed E6 -> Micros
Micros.fromSeconds -> Micros
delay) IO ()
action = mdo
  let doAction :: IO ()
      doAction :: IO ()
doAction = do
        IO Bool
cancel <- TimerWheel -> Micros -> IO () -> IO (IO Bool)
reregister TimerWheel
wheel Micros
delay IO ()
doAction
        forall a. IORef a -> a -> IO ()
writeIORef IORef (IO Bool)
cancelRef IO Bool
cancel
        IO ()
action
  IO Bool
cancel0 <- TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl TimerWheel
wheel Micros
delay IO ()
doAction
  IORef (IO Bool)
cancelRef <- forall a. a -> IO (IORef a)
newIORef IO Bool
cancel0
  forall (f :: * -> *) a. Applicative f => a -> f a
pure do
    IO Bool -> IO ()
untilTrue do
      IO Bool
cancel <- forall a. IORef a -> IO a
readIORef IORef (IO Bool)
cancelRef
      IO Bool
cancel

-- | Like 'recurring', but for when you don't intend to cancel the timer.
recurring_ ::
  TimerWheel ->
  -- | Delay, in seconds
  Fixed E6 ->
  -- | Action
  IO () ->
  IO ()
recurring_ :: TimerWheel -> Fixed E6 -> IO () -> IO ()
recurring_ TimerWheel
wheel (Fixed E6 -> Micros
Micros.fromSeconds -> Micros
delay) IO ()
action = do
  IO Bool
_ <- TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl TimerWheel
wheel Micros
delay IO ()
doAction
  forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  where
    doAction :: IO ()
    doAction :: IO ()
doAction = do
      IO Bool
_ <- TimerWheel -> Micros -> IO () -> IO (IO Bool)
reregister TimerWheel
wheel Micros
delay IO ()
doAction
      IO ()
action

-- Re-register one bucket early, to account for the fact that timers are
-- expired at the *end* of a bucket.
--
-- +---+---+---+---+
-- { A |   |   |   }
-- +---+---+---+---+
--      |
--      The reaper thread fires 'A' approximately here, so if it's meant
--      to be repeated every two buckets, and we just re-register it at
--      this time, three buckets will pass before it's run again. So, we
--      act as if it's still "one bucket ago" at the moment we re-register
--      it.
reregister :: TimerWheel -> Micros -> IO () -> IO (IO Bool)
reregister :: TimerWheel -> Micros -> IO () -> IO (IO Bool)
reregister TimerWheel
wheel Micros
delay =
  TimerWheel -> Micros -> IO () -> IO (IO Bool)
registerImpl TimerWheel
wheel (if Micros
reso forall a. Ord a => a -> a -> Bool
> Micros
delay then Word64 -> Micros
Micros Word64
0 else Micros
delay Micros -> Micros -> Micros
`Micros.minus` Micros
reso)
  where
    reso :: Micros
    reso :: Micros
reso =
      TimerWheel -> Micros
resolution TimerWheel
wheel

resolution :: TimerWheel -> Micros
resolution :: TimerWheel -> Micros
resolution =
  Wheel -> Micros
Wheel.resolution forall b c a. (b -> c) -> (a -> b) -> a -> c
. TimerWheel -> Wheel
wheel

-- Repeat an IO action until it returns 'True'.
untilTrue :: IO Bool -> IO ()
untilTrue :: IO Bool -> IO ()
untilTrue IO Bool
m =
  forall a. (a -> a) -> a
fix \IO ()
again ->
    IO Bool
m forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. a -> a -> Bool -> a
bool IO ()
again (forall (f :: * -> *) a. Applicative f => a -> f a
pure ())