module Mercado.RateLimiter
  ( generateDelayAction
  , mercadoDelay
  , mercadoWindow
  , MBInterval(..)
  , MBWindow(..)
  ) where

import Data.Word
import Control.Concurrent.TokenBucket

newtype MBInterval = MBInterval Word64
newtype MBWindow   = MBWindow   Word64

mercadoDelay :: MBInterval
mercadoDelay = MBInterval 1020000 -- 1.02 secs per token (i.e. per request)

mercadoWindow :: MBWindow
mercadoWindow = MBWindow (60 * 1000000) -- 60 second window

generateDelayAction :: MBWindow -> MBInterval -> IO (IO ())
generateDelayAction (MBWindow wnd) (MBInterval delay) = do
    mercadoBucket <- newTokenBucket
    return $ tokenBucketWait mercadoBucket maxBurst delay
  where
    maxBurst = wnd `div` delay
