--------------------------------------------------------------------------------
-- Rate Limiting Middleware for WAI                                           --
--------------------------------------------------------------------------------
-- This source code is licensed under the MIT license found in the LICENSE    --
-- file in the root directory of this source tree.                            --
--------------------------------------------------------------------------------

{-# LANGUAGE AllowAmbiguousTypes #-}

-- | Implements WAI 'Middleware' for rate limiting. 
module Network.Wai.RateLimit (
    rateLimiting
) where 

--------------------------------------------------------------------------------

import Control.Monad

import Network.HTTP.Types
import Network.Wai
import Network.Wai.RateLimit.Strategy
import Network.Wai.RateLimit.Backend

--------------------------------------------------------------------------------

-- | 'rateLimiting' @strategy@ is a WAI 'Middleware' which limits requests
-- according to the configuration represented by @strategy@.
rateLimiting :: Strategy -> Middleware
rateLimiting :: Strategy -> Middleware
rateLimiting MkStrategy{Request -> IO Bool
strategyOnRequest :: Strategy -> Request -> IO Bool
strategyOnRequest :: Request -> IO Bool
..} Application
app Request
req Response -> IO ResponseReceived
sendResponse = do
    -- check that the client has not exceeded 
    Bool
allowRequest <- Request -> IO Bool
strategyOnRequest Request
req

    if Bool
allowRequest
    -- if not: process the request normally
    then Application
app Request
req Response -> IO ResponseReceived
sendResponse
    -- otherwise: return a 429 response with an appropriate message
    else Response -> IO ResponseReceived
sendResponse (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> ByteString -> Response
responseLBS Status
status429 [] ByteString
"Rate limit exceeded" 

--------------------------------------------------------------------------------