-- | The worker pool's run state and its shutdown signal.
module Arbiter.Worker.WorkerState
  ( WorkerState (..)
  , newWorkerState
  , signalShutdown
  ) where

import Control.Concurrent.STM (TVar)
import Control.Concurrent.STM qualified as STM

-- | Create a new worker state initialized to 'Running'.
newWorkerState :: IO (TVar WorkerState)
newWorkerState :: IO (TVar WorkerState)
newWorkerState = WorkerState -> IO (TVar WorkerState)
forall a. a -> IO (TVar a)
STM.newTVarIO WorkerState
Running

-- | Signal graceful shutdown. The pool stops claiming, finishes what it holds, and exits.
signalShutdown :: TVar WorkerState -> IO ()
signalShutdown :: TVar WorkerState -> IO ()
signalShutdown TVar WorkerState
stateVar = STM () -> IO ()
forall a. STM a -> IO a
STM.atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TVar WorkerState -> WorkerState -> STM ()
forall a. TVar a -> a -> STM ()
STM.writeTVar TVar WorkerState
stateVar WorkerState
ShuttingDown

-- | A worker pool's effective state, read off the shutdown and pause flags on its
-- 'Arbiter.Worker.Config.WorkerConfig'. Shutdown wins, then pause, then running.
data WorkerState
  = Running
  | Paused
  | ShuttingDown
  deriving stock (WorkerState -> WorkerState -> Bool
(WorkerState -> WorkerState -> Bool)
-> (WorkerState -> WorkerState -> Bool) -> Eq WorkerState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: WorkerState -> WorkerState -> Bool
== :: WorkerState -> WorkerState -> Bool
$c/= :: WorkerState -> WorkerState -> Bool
/= :: WorkerState -> WorkerState -> Bool
Eq, Int -> WorkerState -> ShowS
[WorkerState] -> ShowS
WorkerState -> String
(Int -> WorkerState -> ShowS)
-> (WorkerState -> String)
-> ([WorkerState] -> ShowS)
-> Show WorkerState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> WorkerState -> ShowS
showsPrec :: Int -> WorkerState -> ShowS
$cshow :: WorkerState -> String
show :: WorkerState -> String
$cshowList :: [WorkerState] -> ShowS
showList :: [WorkerState] -> ShowS
Show)