1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
|
{-# 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
-- lower level, Announcer.Tox needs these.
, scheduleImmediately
, ScheduledItem(..)
, interrutible
) where
import qualified Data.MinMaxPSQ as MM
import Data.Wrapper.PSQ as PSQ
import InterruptibleDelay
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)
findNextScheduled :: Announcer -> STM KPS
findNextScheduled announcer = maybe retry return =<< (findMin . unSchedule) <$> readTVar (scheduled announcer)
removeFromSchedule :: Announcer -> KPS -> STM ()
removeFromSchedule announcer item = modifyTVar' (scheduled announcer) (Schedule . PSQ.delete (key item) . unSchedule)
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.
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.
, interrutible :: InterruptibleDelay
}
-- | 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
= modifyTVar' (scheduled announcer) (Schedule . PSQ.insert' k item 0 . unSchedule)
scheduleAbs :: Announcer -> AnnounceKey -> ScheduledItem -> POSIXTime -> STM ()
scheduleAbs announcer k item absTime =
modifyTVar (scheduled announcer)
(Schedule . PSQ.insert' k item absTime . unSchedule)
-- | Terminate the 'Announcer' thread. Don't use the Announcer after this.
stopAnnouncer :: Announcer -> IO ()
stopAnnouncer announcer = do
atomically $ scheduleImmediately announcer (AnnounceKey "*stop*") StopAnnouncer
interruptDelay (interrutible announcer)
atomically $ readTVar (announcerActive announcer) >>= check . not
cancel :: Announcer -> AnnounceKey -> IO ()
cancel announcer k = do
atomically $ scheduleImmediately announcer k $ DeleteAnnouncement
interruptDelay (interrutible announcer)
-- | Construct an 'Announcer' object and fork a thread in which to perform the
-- Kademlia searches and announces.
forkAnnouncer :: IO Announcer
forkAnnouncer = do
delay <- interruptibleDelay
announcer <- atomically $ Announcer <$> newTVar emptySchedule
<*> newTVar True
<*> pure delay
fork $ announceThread announcer
return announcer
readTChanTimeout :: POSIXTime -> TChan a -> IO (Maybe a)
readTChanTimeout timeout pktChannel = do
delay <- registerDelay (toMicroseconds timeout)
atomically $
Just <$> readTChan pktChannel
<|> pure Nothing <* (readTVar >=> check) delay
where
toMicroseconds :: POSIXTime -> Int
toMicroseconds = undefined
listener :: TChan KPS -> IO ()
listener chan = relisten PSQ.empty
where
note :: String -> IO ()
note = if False then print else const (return ())
relisten queue = do
case minView queue of
Nothing -> do
note "queue empty - listening indefinitely"
(k, p, s) <- atomically $ readTChan chan
note "handling new event"
relisten $ PSQ.insert' k s p queue
Just ((k, p, s), queue') -> do
note "queue full - listening with timeout"
now <- getPOSIXTime
readTChanTimeout (p - now) chan >>= \case
Just (k, p, s) -> do
note "handling new event (event occurred before timeout)"
relisten $ PSQ.insert' k s p queue
Nothing -> do
note "timed out - executing from queue"
runAction s
mapM id =<< atomically (performScheduledItem undefined now (k, p, s))
relisten queue'
runAction :: Monad m => ScheduledItem -> m ()
runAction DeleteAnnouncement = return ()
runAction StopAnnouncer = return ()
runAction (ScheduledItem a) = undefined
announceThread :: Announcer -> IO ()
announceThread announcer = do
myThreadId >>= flip labelThread "announcer"
fix $ \loop -> do
item <- atomically $ findNextScheduled announcer
now <- getPOSIXTime
-- Is it time to do something?
if (prio item <= now)
then do -- Yes. Dequeue and handle this event.
action <- atomically $ do
removeFromSchedule announcer item
performScheduledItem announcer now item
-- Are we finished?
mapM_ (>> loop) -- No? Okay, perform scheduled op and loop.
action
else do -- No. Wait a bit.
startDelay (interrutible announcer) (microseconds $ prio item - now)
loop
-- We're done. Let 'stopAnnouncer' know that it can stop blocking.
atomically $ writeTVar (announcerActive announcer) False
-- | 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
|