diff options
Diffstat (limited to 'server/src/Thermoprint/Server/Queue')
| -rw-r--r-- | server/src/Thermoprint/Server/Queue/Utils.hs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/server/src/Thermoprint/Server/Queue/Utils.hs b/server/src/Thermoprint/Server/Queue/Utils.hs new file mode 100644 index 0000000..86b0162 --- /dev/null +++ b/server/src/Thermoprint/Server/Queue/Utils.hs | |||
| @@ -0,0 +1,52 @@ | |||
| 1 | {-# LANGUAGE RecordWildCards #-} | ||
| 2 | {-# LANGUAGE FlexibleContexts #-} | ||
| 3 | {-# LANGUAGE TypeOperators #-} | ||
| 4 | |||
| 5 | module Thermoprint.Server.Queue.Utils | ||
| 6 | ( standardCollapse | ||
| 7 | , standardSleep | ||
| 8 | , limitHistorySize | ||
| 9 | , limitHistoryAge | ||
| 10 | ) where | ||
| 11 | |||
| 12 | import Data.Sequence (Seq) | ||
| 13 | import qualified Data.Sequence as Seq | ||
| 14 | |||
| 15 | import Data.Time | ||
| 16 | |||
| 17 | import Control.Monad.State | ||
| 18 | import Control.Monad.IO.Class | ||
| 19 | import Control.Monad.Trans.Identity | ||
| 20 | import Servant.Server.Internal.Enter | ||
| 21 | |||
| 22 | import Thermoprint.Server.Queue | ||
| 23 | |||
| 24 | standardCollapse :: MonadIO m => IdentityT IO :~> m | ||
| 25 | standardCollapse = Nat $ liftIO . runIdentityT | ||
| 26 | |||
| 27 | standardSleep :: Monad (QueueManagerM t) => QueueManager t | ||
| 28 | -- ^ Instruct 'runQM' to sleep some standard amount of time | ||
| 29 | -- | ||
| 30 | -- /TODO/: Investigate implementing a smarter algorithm (PID-controller) | ||
| 31 | standardSleep = return $ 20 | ||
| 32 | |||
| 33 | limitHistorySize :: MonadState Queue (QueueManagerM t) => Int -> QueueManager t | ||
| 34 | -- ^ Limit a 'Queue's 'history's size to some number of 'QueueEntry's | ||
| 35 | limitHistorySize max = modify' limitSize >> standardSleep | ||
| 36 | where | ||
| 37 | limitSize :: Queue -> Queue | ||
| 38 | limitSize q@Queue{..} = q { history = Seq.take max history } | ||
| 39 | |||
| 40 | limitHistoryAge :: ( MonadState Queue (QueueManagerM t) | ||
| 41 | ) => NominalDiffTime -- ^ Maximum age relative to the youngest 'QueueEntry' | ||
| 42 | -> QueueManager t | ||
| 43 | -- ^ Limit a 'Queue's 'history's contents to 'QueueEntry's below a certain age | ||
| 44 | limitHistoryAge maxAge = modify' limitAge >> standardSleep | ||
| 45 | where | ||
| 46 | limitAge :: Queue -> Queue | ||
| 47 | limitAge q@Queue{..} = q { history = Seq.filter (filterAge . created . fst) history} | ||
| 48 | where | ||
| 49 | youngest :: UTCTime | ||
| 50 | youngest = maximum $ created . fst <$> history | ||
| 51 | filterAge :: UTCTime -> Bool | ||
| 52 | filterAge time = not $ (youngest `diffUTCTime` time) > maxAge | ||
