{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NondecreasingIndentation #-} module Announcer ( Announcer() , AnnounceKey , scheduleAbs , scheduleToList , packAnnounceKey , unpackAnnounceKey , forkAnnouncer , stopAnnouncer , cancel , itemStatusNum , runAction -- lower level, Announcer.Tox needs these. , scheduleImmediately , ScheduledItem(ScheduledItem) ) where import qualified Data.MinMaxPSQ as MM import Data.Wrapper.PSQ as PSQ import Network.Kademlia.Routing as R import Network.Kademlia.Search import Control.Concurrent.Lifted.Instrument import Control.Concurrent.STM import Control.Monad import Control.Applicative import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as Char8 import Data.Function import Data.Hashable import Data.Maybe import Data.Ord import Data.Time.Clock.POSIX import qualified GHC.Generics as Generics -- import Generic.Data.Internal.Meta as Lyxia import System.IO newtype AnnounceKey = AnnounceKey ByteString deriving (Hashable,Ord,Eq) instance Show AnnounceKey where show (AnnounceKey bs) = "AnnounceKey " ++ show (Char8.unpack bs) packAnnounceKey :: Announcer -> String -> STM AnnounceKey packAnnounceKey _ = return . AnnounceKey . Char8.pack unpackAnnounceKey :: Announcer -> AnnounceKey -> STM String unpackAnnounceKey _ (AnnounceKey bs) = return $ Char8.unpack bs -- | Actions that can be scheduled to occur at some particular time in the -- future. Since periodic event handlers are responsible for re-scheduling -- themselves, they are typically bootstrapped using 'scheduleImmediately' with -- 'NewAnnouncement' which triggers the ordinary recurring scheduling of -- 'Announce'. data ScheduledItem = DeleteAnnouncement | ScheduledItem (Announcer -> AnnounceKey -> POSIXTime -> STM (IO ())) | StopAnnouncer -- Can't use Data because STM and IO. :( -- deriving Data {- itemStatusNum sch = constrIndex $ toConstr sch -} -- Using Generic works with Lyxia's generic-data package... -- {- itemStatusNum sch = Lyxia.conIdToInt $ Lyxia.conId sch -} -- For now, make sure to keep 'itemStatusNum' up to date with 'ScheduledItem'. deriving Generics.Generic itemStatusNum :: ScheduledItem -> Int itemStatusNum (DeleteAnnouncement ) = 0 itemStatusNum (ScheduledItem {}) = 1 itemStatusNum (StopAnnouncer ) = 2 itemStatusNum _ = error "itemStatusNum not in sync with ScheduledItem declaration." newtype Schedule = Schedule { unSchedule :: PSQ' AnnounceKey POSIXTime ScheduledItem } emptySchedule :: Schedule emptySchedule = Schedule PSQ.empty type KPS = (AnnounceKey, POSIXTime, ScheduledItem) scheduleToList :: Announcer -> STM [KPS] scheduleToList announcer = PSQ.toList . unSchedule <$> readTVar (scheduled announcer) data Announcer = Announcer { -- | The queue of scheduled events. The priority is the time at which an -- event is supposed to occur. Do not write to this TVar ever. scheduled :: TVar Schedule -- | This TVar is False when the Announcer thread has finished. , announcerActive :: TVar Bool -- | This delay is used to wait until it's time to act on the earliest -- scheduled item. It will be interrupted whenever a new item is -- scheduled. , commander :: TChan SchedulerCommand } -- | Schedules an event to occur long ago at the epoch (which effectively makes -- the event happen as soon as possible). Note that the caller will usually -- also want to interrupt the 'interrutible' delay so that it finds this item -- immediately. scheduleImmediately :: Announcer -> AnnounceKey -> ScheduledItem -> STM () scheduleImmediately announcer k item = scheduleAbs announcer k item 0 scheduleAbs :: Announcer -> AnnounceKey -> ScheduledItem -> POSIXTime -> STM () scheduleAbs announcer k item absTime = writeTChan (commander announcer) $ ScheduleAction (k, absTime, item) runAction :: Announcer -> IO () -> STM () runAction announcer = writeTChan (commander announcer) . RunAction -- | Terminate the 'Announcer' thread. Don't use the Announcer after this. stopAnnouncer :: Announcer -> IO () stopAnnouncer announcer = do atomically $ writeTChan (commander announcer) ShutdownScheduler atomically $ readTVar (announcerActive announcer) >>= check . not cancel :: Announcer -> AnnounceKey -> IO () cancel announcer k = do atomically $ writeTChan (commander announcer) $ ScheduleAction (k, 0, (ScheduledItem (\a k p -> return $ atomically $ return ()))) -- | Construct an 'Announcer' object and fork a thread in which to perform the -- Kademlia searches and announces. forkAnnouncer :: IO Announcer forkAnnouncer = do announcer <- atomically $ Announcer <$> newTVar emptySchedule <*> newTVar True <*> newTChan fork $ announceThread announcer return announcer readTChanTimeout :: TVar Bool -> TChan a -> STM (Maybe a) readTChanTimeout delay pktChannel = do -- delay <- registerDelay (toMicroseconds timeout) Just <$> readTChan pktChannel <|> pure Nothing <* (readTVar >=> check) delay toMicroseconds :: POSIXTime -> Int toMicroseconds = round . (* 1000) . (* 1000) data SchedulerCommand = ShutdownScheduler | ScheduleAction KPS | RunAction (IO ()) listener :: Announcer -> IO () listener announcer = relisten -- This function assumes it is the only writer to the (scheduled announcer :: TVar Schedule). -- If that TVar is written in another thread, the changes may be overwritten here. where chan = commander announcer note :: String -> IO () note = if False then print else const (return ()) relisten = do queue <- fmap unSchedule $ atomically $ readTVar $ scheduled announcer case minView queue of Nothing -> do note "queue empty - listening indefinitely" atomically (readTChan chan) >>= handleCommand Just ((k, p, s), queue') -> do now <- getPOSIXTime note $ "queue full - listening with timeout - " ++ show (p, now) delay <- registerDelay (toMicroseconds (p - now)) join $ atomically $ do readTChanTimeout delay chan >>= \case Just cmd -> return $ handleCommand cmd Nothing -> do writeTVar (scheduled announcer) (Schedule queue') case s of DeleteAnnouncement -> return relisten StopAnnouncer -> declareInactive >> return (return ()) ScheduledItem f -> (fmap (>> relisten) (fmap fork (f announcer k now))) where declareInactive = writeTVar (announcerActive announcer) False handleCommand = \case ShutdownScheduler -> atomically declareInactive RunAction io -> io >> relisten ScheduleAction (k, p, s) -> do atomically $ modifyTVar (scheduled announcer) (Schedule . PSQ.insert' k s p . unSchedule) relisten announceThread :: Announcer -> IO () announceThread announcer = do myThreadId >>= flip labelThread "announcer" listener announcer -- | Returns 'Nothing' to stop the announcer thread (when the event is -- StopAnnouncer). Otherwise, returns an action that will be performed in the -- announcer thread before looping for the next scheduled item. -- -- Note that the returned action is responsible for re-scheduled another event -- for periodic tasks. Otherwise, as is the case for the 'DeleteAnnouncement' -- event, the item associated with a particular announce key will be removed -- from the queue. performScheduledItem :: Announcer -> POSIXTime -> Binding' AnnounceKey POSIXTime ScheduledItem -> STM (Maybe (IO ())) performScheduledItem announcer now = \case (Binding _ StopAnnouncer _) -> return Nothing -- announcement removed: (Binding _ DeleteAnnouncement _) -> return $ Just $ return () (Binding k (ScheduledItem action) _) -> Just <$> action announcer k now