urbit/pkg/hs/urbit-king/lib/Urbit/Vere/Behn.hs

67 lines
1.7 KiB
Haskell
Raw Normal View History

2020-01-23 07:16:09 +03:00
{-|
Behn: Timer Driver
-}
2019-08-01 03:27:13 +03:00
module Urbit.Vere.Behn (behn, DriverApi(..), behn') where
2019-08-01 03:27:13 +03:00
import Urbit.Arvo hiding (Behn)
import Urbit.Prelude
import Urbit.Vere.Pier.Types
2019-08-01 03:27:13 +03:00
import Urbit.King.App (HasKingId(..), HasPierEnv(..))
import Urbit.Noun.Time (Wen)
import Urbit.Timer (Timer)
2020-01-23 07:16:09 +03:00
import qualified Urbit.Noun.Time as Time
import qualified Urbit.Timer as Timer
2019-08-01 03:27:13 +03:00
-- Behn Stuff ------------------------------------------------------------------
behn' :: HasPierEnv e => RIO e ([Ev], RAcquire e (DriverApi BehnEf))
behn' = do
env <- ask
pure ([bornEv (fromIntegral (env ^. kingIdL))], runDriver env)
where
runDriver env = do
ventQ :: TQueue EvErr <- newTQueueIO
diOnEffect <- liftAcquire (behn env (writeTQueue ventQ))
let diEventSource = fmap RRWork <$> tryReadTQueue ventQ
pure (DriverApi {..})
bornEv :: KingId -> Ev
bornEv king = EvBlip $ BlipEvBehn $ BehnEvBorn (king, ()) ()
2019-08-01 03:27:13 +03:00
wakeEv :: Ev
wakeEv = EvBlip $ BlipEvBehn $ BehnEvWake () ()
sysTime = view Time.systemTime
wakeErr :: WorkError -> IO ()
wakeErr _ = pure ()
behn
:: HasKingId e
=> e
-> (EvErr -> STM ())
-> Acquire (BehnEf -> IO ())
behn env enqueueEv = runBehn
2019-08-01 03:27:13 +03:00
where
2020-05-13 22:35:57 +03:00
king = fromIntegral (env ^. kingIdL)
2020-06-07 02:34:27 +03:00
runBehn :: Acquire (BehnEf -> IO ())
2019-08-01 03:27:13 +03:00
runBehn = do
tim <- mkAcquire Timer.init Timer.stop
2020-06-07 02:34:27 +03:00
pure (runRIO env . handleEf tim)
2019-08-01 03:27:13 +03:00
2019-08-29 03:26:59 +03:00
handleEf :: Timer -> BehnEf -> RIO e ()
handleEf b = io . \case
2019-08-01 03:27:13 +03:00
BehnEfVoid v -> absurd v
BehnEfDoze (i, ()) mWen -> do
when (i == king) (doze b mWen)
2019-08-01 03:27:13 +03:00
doze :: Timer -> Maybe Wen -> IO ()
doze tim = \case
Nothing -> Timer.stop tim
Just t -> Timer.start tim (sysTime t) $ atomically (enqueueEv (EvErr wakeEv wakeErr))