{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if __GLASGOW_HASKELL__ < 710
{-# LANGUAGE OverlappingInstances #-}
#endif
module Servant.Server.Internal
( module Servant.Server.Internal
, module Servant.Server.Internal.PathInfo
, module Servant.Server.Internal.Router
, module Servant.Server.Internal.RoutingApplication
, module Servant.Server.Internal.ServantErr
) where
import Control.Applicative ((<$>))
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad (join, when)
import Data.Bool (bool)
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Builder.Extra as BB
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as BL
import Data.Either (partitionEithers)
import Data.List (foldl')
import Data.Maybe (fromMaybe, isNothing, mapMaybe,
maybeToList)
import Data.Proxy
import Data.String (IsString, fromString)
import Data.String.Conversions (cs, (<>))
import Data.Tagged (Tagged(..), retag)
import qualified Data.Text as T
import Data.Text (Text)
import Data.Typeable (Typeable)
import GHC.Generics
import GHC.TypeLits (KnownNat, KnownSymbol, natVal,
symbolVal)
import Network.HTTP.Types (HeaderName, Method,
Status(..), parseQueryText,
methodGet, methodHead,
hContentType, hAccept)
import qualified Network.HTTP.Media as NHM
import Web.HttpApiData (FromHttpApiData,
parseHeader,
parseQueryParam,
parseUrlPieceMaybe,
parseUrlPieces)
import Snap.Core hiding (Headers, Method,
getResponse, route,
method, withRequest)
import Servant.API ((:<|>) (..), (:>), BasicAuth,
BoundaryStrategy(..),
Capture', CaptureAll,
Description, EmptyAPI,
FramingRender (..),
Header', If, IsSecure(..),
QueryFlag, QueryParam',
QueryParams, Raw, RemoteHost,
ReqBody', ReflectMethod(..),
SBool(..), SBoolI,
Stream, Summary,
ToStreamGenerator (..), Vault,
Verb, getStreamGenerator, sbool)
import Servant.API.ContentTypes (AcceptHeader (..),
AllCTRender (..),
AllCTUnrender (..), AllMime(..),
MimeRender (..),
canHandleAcceptH, contentType)
import Servant.API.Modifiers (FoldLenient, FoldRequired,
RequestArgument, unfoldRequestArgument)
import Servant.API.ResponseHeaders (Headers, getResponse, GetHeaders,
getHeaders)
import qualified System.IO.Streams as IOS
import Servant.Server.Internal.BasicAuth
import Servant.Server.Internal.Context
import Servant.Server.Internal.PathInfo
import Servant.Server.Internal.Router
import Servant.Server.Internal.RoutingApplication
import Servant.Server.Internal.ServantErr
import Servant.Server.Internal.SnapShims
class HasServer api context (m :: * -> *) where
type ServerT api context m :: *
route :: MonadSnap m
=> Proxy api
-> Context context
-> Delayed m env (Server api context m)
-> Router m env
hoistServerWithContext
:: proxy api
-> proxy' context
-> (forall x. m x -> n x)
-> ServerT api context m
-> ServerT api context n
type Server api context m = ServerT api context m
instance (HasServer a ctx m, HasServer b ctx m) => HasServer (a :<|> b) ctx m where
type ServerT (a :<|> b) ctx m = ServerT a ctx m :<|> ServerT b ctx m
route Proxy ctx server = choice (route pa ctx ((\ (a :<|> _) -> a) <$> server))
(route pb ctx ((\ (_ :<|> b) -> b) <$> server))
where pa = Proxy :: Proxy a
pb = Proxy :: Proxy b
hoistServerWithContext _ pc nt (a :<|> b) =
hoistServerWithContext (Proxy :: Proxy a) pc nt a :<|>
hoistServerWithContext (Proxy :: Proxy b) pc nt b
captured :: FromHttpApiData a => proxy (Capture' mods sym a) -> Text -> Maybe a
captured _ = parseUrlPieceMaybe
instance (FromHttpApiData a, HasServer api context m)
=> HasServer (Capture' mods capture a :> api) context m where
type ServerT (Capture' mods capture a :> api) context m =
a -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy ctx d =
CaptureRouter $
route (Proxy :: Proxy api) ctx
(addCapture d $ \ txt -> case parseUrlPieceMaybe txt of
Nothing -> delayedFail err400
Just v -> return v
)
instance (FromHttpApiData a, HasServer api context m)
=> HasServer (CaptureAll capture a :> api) context m where
type ServerT (CaptureAll capture a :> api) context m =
[a] -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy ctx d =
CaptureAllRouter $
route (Proxy :: Proxy api) ctx
(addCapture d $ \ txts -> case parseUrlPieces txts of
Left _ -> delayedFail err400
Right v -> return v
)
allowedMethodHead :: Method -> Request -> Bool
allowedMethodHead method request =
method == methodGet && unSnapMethod (rqMethod request) == methodHead
allowedMethod :: Method -> Request -> Bool
allowedMethod method request =
allowedMethodHead method request || unSnapMethod (rqMethod request) == method
processMethodRouter :: Maybe (BL.ByteString, BL.ByteString) -> Status -> Method
-> Maybe [(HeaderName, B.ByteString)]
-> Request -> RouteResult Response
processMethodRouter handleA status method rHeaders request = case handleA of
Nothing -> FailFatal err406
Just (contentT, body) -> Route $ responseLBS status hdrs bdy
where
bdy = if allowedMethodHead method request then "" else body
hdrs = (hContentType, cs contentT) : fromMaybe [] rHeaders
methodCheck :: MonadSnap m => Method -> Request -> DelayedM m ()
methodCheck method request
| allowedMethod method request = return ()
| otherwise = delayedFail err405
acceptCheck :: (AllMime list, MonadSnap m) => Proxy list -> B.ByteString -> DelayedM m ()
acceptCheck proxy accH
| canHandleAcceptH proxy (AcceptHeader accH) = return ()
| otherwise = delayedFail err406
methodRouter :: (AllCTRender ctypes a, MonadSnap m)
=> Method -> Proxy ctypes -> Status
-> Delayed m env (m a)
-> Router m env
methodRouter method proxy status action = leafRouter route'
where
route' env request respond =
let accH = fromMaybe ct_wildcard $ getHeader hAccept request
in runAction (action `addMethodCheck` methodCheck method request
`addAcceptCheck` acceptCheck proxy accH
) env request respond $ \ output -> do
let handleA = handleAcceptH proxy (AcceptHeader accH) output
processMethodRouter handleA status method Nothing request
methodRouterHeaders :: (GetHeaders (Headers h v), AllCTRender ctypes v, MonadSnap m)
=> Method -> Proxy ctypes -> Status
-> Delayed m env (m (Headers h v))
-> Router m env
methodRouterHeaders method proxy status action = leafRouter route'
where
route' env request respond =
let accH = fromMaybe ct_wildcard $ getHeader hAccept request
in runAction (action `addMethodCheck` methodCheck method request
`addAcceptCheck` acceptCheck proxy accH
) env request respond $ \ output -> do
let hdrs = getHeaders output
handleA = handleAcceptH proxy (AcceptHeader accH) (getResponse output)
processMethodRouter handleA status method (Just hdrs) request
instance {-# OVERLAPPABLE #-} (AllCTRender ctypes a,
ReflectMethod method,
KnownNat status)
=> HasServer (Verb method status ctypes a) context m where
type ServerT (Verb method status ctypes a) context m = m a
hoistServerWithContext _ _ nt s = nt s
route Proxy _ = methodRouter method (Proxy :: Proxy ctypes) status
where method = reflectMethod (Proxy :: Proxy method)
status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
instance {-# OVERLAPPABLE #-} (AllCTRender ctypes a,
ReflectMethod method,
KnownNat status,
GetHeaders (Headers h a))
=> HasServer (Verb method status ctypes (Headers h a)) context m where
type ServerT (Verb method status ctypes (Headers h a)) context m = m (Headers h a)
hoistServerWithContext _ _ nt s = nt s
route Proxy _ = methodRouterHeaders method (Proxy :: Proxy ctypes) status
where method = reflectMethod (Proxy :: Proxy method)
status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
instance {-# OVERLAPPABLE #-} (MimeRender ctype a,
ReflectMethod method,
KnownNat status,
FramingRender framing ctype,
ToStreamGenerator b a)
=> HasServer (Stream method status framing ctype b) context m where
type ServerT (Stream method status framing ctype b) context m = m b
hoistServerWithContext _ _ nt s = nt s
route Proxy _ = streamRouter ([],) method status (Proxy :: Proxy framing) (Proxy :: Proxy ctype)
where method = reflectMethod (Proxy :: Proxy method)
status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
instance {-# OVERLAPPABLE #-} (MimeRender ctype a,
ReflectMethod method,
KnownNat status,
FramingRender framing ctype,
ToStreamGenerator b a,
GetHeaders (Headers h b))
=> HasServer (Stream method status framing ctype (Headers h b)) context m where
type ServerT (Stream method status framing ctype (Headers h b)) context m = m (Headers h b)
hoistServerWithContext _ _ nt s = nt s
route Proxy _ = streamRouter (\x -> (getHeaders x, getResponse x)) method status (Proxy :: Proxy framing) (Proxy :: Proxy ctype)
where method = reflectMethod (Proxy :: Proxy method)
status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
streamRouter :: (MimeRender ctype a,
FramingRender framing ctype,
ToStreamGenerator b a,
MonadSnap m
) =>
(c -> ([(HeaderName, B.ByteString)], b))
-> Method
-> Status
-> Proxy framing
-> Proxy ctype
-> Delayed m env (m c)
-> Router m env
streamRouter splitHeaders method (Status code msg) framingproxy ctypeproxy action = leafRouter $ \env request respond ->
let accH = fromMaybe ct_wildcard $ getHeader hAccept request
cmediatype = NHM.matchAccept [contentType ctypeproxy] accH
accCheck = when (isNothing cmediatype) $ delayedFail err406
contentHeader = (hContentType, NHM.renderHeader . maybeToList $ cmediatype)
in runAction (action `addMethodCheck` methodCheck method request
`addAcceptCheck` accCheck
) env request respond $ \ output ->
let (headerz, fa) = splitHeaders output
k = getStreamGenerator . toStreamGenerator $ fa in
Route $ setResponseStatus code msg
$ (\r -> foldl' (\r' (h,h') -> addHeader h h' r') r $ contentHeader : headerz)
$ flip setResponseBody emptyResponse $ \outStream -> do
let writeAndFlush bb = IOS.write (Just $ bb <> BB.flush) outStream
writeAndFlush (BB.lazyByteString $ header framingproxy ctypeproxy)
case boundary framingproxy ctypeproxy of
BoundaryStrategyBracket f ->
let go x = let bs = mimeRender ctypeproxy x
(before, after) = f bs
in writeAndFlush ( BB.lazyByteString before
<> BB.lazyByteString bs
<> BB.lazyByteString after)
in k go go
BoundaryStrategyIntersperse sep -> k
(\x -> do
writeAndFlush . BB.lazyByteString $ mimeRender ctypeproxy x
)
(\x -> do
writeAndFlush . (BB.lazyByteString sep <>) . BB.lazyByteString $ mimeRender ctypeproxy x
)
BoundaryStrategyGeneral f ->
let go = writeAndFlush . BB.lazyByteString . f . mimeRender ctypeproxy
in k go go
IOS.write (Just . BB.lazyByteString $ trailer framingproxy ctypeproxy) outStream
return outStream
instance (KnownSymbol sym, FromHttpApiData a, HasServer api context m
, SBoolI (FoldRequired mods), SBoolI (FoldLenient mods)
)
=> HasServer (Header' mods sym a :> api) context m where
type ServerT (Header' mods sym a :> api) context m =
RequestArgument mods a -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy ctx subserver = route (Proxy :: Proxy api) ctx $
subserver `addHeaderCheck` withRequest headerCheck
where
headerName :: IsString n => n
headerName = fromString $ symbolVal (Proxy :: Proxy sym)
headerCheck :: Request -> DelayedM m (RequestArgument mods a)
headerCheck req =
unfoldRequestArgument (Proxy :: Proxy mods) errReq errSt mev
where
mev :: Maybe (Either Text a)
mev = fmap parseHeader $ getHeader headerName req
errReq = delayedFailFatal err400
{ errBody = "Header " <> headerName <> " is required"
}
errSt e = delayedFailFatal err400
{ errBody = cs $ "Error parsing header "
<> headerName
<> " failed: " <> e
}
instance (KnownSymbol sym, FromHttpApiData a, HasServer api context m
, SBoolI (FoldRequired mods), SBoolI (FoldLenient mods)
)
=> HasServer (QueryParam' mods sym a :> api) context m where
type ServerT (QueryParam' mods sym a :> api) context m =
RequestArgument mods a -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy ctx subserver =
let querytext r = parseQueryText $ rqQueryString r
paramname = cs $ symbolVal (Proxy :: Proxy sym)
parseParam :: Request -> DelayedM m (RequestArgument mods a)
parseParam req =
unfoldRequestArgument (Proxy :: Proxy mods) errReq errSt mev
where
mev :: Maybe (Either T.Text a)
mev = fmap parseQueryParam $ join $ lookup paramname $ querytext req
errReq = delayedFailFatal err400
{ errBody = cs $ "Query parameter " <> paramname <> " is required"
}
errSt e = delayedFailFatal err400
{ errBody = cs $ "Error parsing query parameter "
<> paramname <> " failed: " <> e
}
delayed = addParameterCheck subserver . withRequest $ parseParam
in route (Proxy :: Proxy api) ctx delayed
instance (KnownSymbol sym, FromHttpApiData a, HasServer api context m)
=> HasServer (QueryParams sym a :> api) context m where
type ServerT (QueryParams sym a :> api) context m =
[a] -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy ctx subserver = route (Proxy :: Proxy api) ctx $
subserver `addParameterCheck` withRequest paramsCheck
where
paramname = cs $ symbolVal (Proxy :: Proxy sym)
paramsCheck req =
case partitionEithers $ fmap parseQueryParam params of
([], parsed) -> return parsed
(errs, _) -> delayedFailFatal err400
{ errBody = cs $ "Error parsing query parameter(s) "
<> paramname <> " failed: "
<> T.intercalate ", " errs
}
where
params :: [T.Text]
params = mapMaybe snd
. filter (looksLikeParam . fst)
. parseQueryText
. rqQueryString
$ req
looksLikeParam name = name == paramname || name == (paramname <> "[]")
instance (KnownSymbol sym, HasServer api context m)
=> HasServer (QueryFlag sym :> api) context m where
type ServerT (QueryFlag sym :> api) context m =
Bool -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy context subserver =
let querytext r = parseQueryText $ rqQueryString r
param r = case lookup paramname (querytext r) of
Just Nothing -> True
Just (Just v) -> examine v
Nothing -> False
in route (Proxy :: Proxy api) context (passToServer subserver param)
where paramname = cs $ symbolVal (Proxy :: Proxy sym)
examine v | v == "true" || v == "1" || v == "" = True
| otherwise = False
instance HasServer Raw context m where
type ServerT Raw context m = m ()
hoistServerWithContext _ _ nt = nt
route Proxy _ rawApplication = RawRouter $ \ env request respond -> do
r <- runDelayed rawApplication env request
case r of
Route app -> (snapToApplication' app) request (respond . Route)
Fail a -> respond $ Fail a
FailFatal e -> respond $ FailFatal e
instance ( AllCTUnrender list a, HasServer api context m, SBoolI (FoldLenient mods), MonadSnap m
) => HasServer (ReqBody' mods list a :> api) context m where
type ServerT (ReqBody' mods list a :> api) context m =
If (FoldLenient mods) (Either String a) a -> ServerT api context m
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
route Proxy context subserver
= route (Proxy :: Proxy api) context $
addBodyCheck subserver ctCheck bodyCheck
where
ctCheck = withRequest $ \ request -> do
let contentTypeH = fromMaybe "application/octet-stream"
$ getHeader hContentType request
case canHandleCTypeH (Proxy :: Proxy list) (cs contentTypeH) :: Maybe (BL.ByteString -> Either String a) of
Nothing -> delayedFail err415
Just f -> return f
bodyCheck f = do
mrqbody <- lift $ runRequestBody $ \ stream -> f <$> BL.fromChunks <$> IOS.toList stream
case sbool :: SBool (FoldLenient mods) of
STrue -> return mrqbody
SFalse -> case mrqbody of
Left e -> delayedFailFatal err400 { errBody = cs e }
Right v -> return v
instance (KnownSymbol path, HasServer api context m) => HasServer (path :> api) context m where
type ServerT (path :> api) context m = ServerT api context m
route Proxy context subserver =
pathRouter
(cs (symbolVal proxyPath))
(route (Proxy :: Proxy api) context subserver)
where proxyPath = Proxy :: Proxy path
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt s
instance HasServer api context m => HasServer (RemoteHost :> api) context m where
type ServerT (RemoteHost :> api) context m = B.ByteString -> ServerT api context m
route Proxy context subserver =
route (Proxy :: Proxy api) context (passToServer subserver rqHostName)
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
instance HasServer api context m => HasServer (IsSecure :> api) context m where
type ServerT (IsSecure :> api) context m = IsSecure -> ServerT api context m
route Proxy context subserver =
route (Proxy :: Proxy api) context (passToServer subserver (bool NotSecure Secure . rqIsSecure))
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
instance HasServer api context m => HasServer (HttpVersion :> api) context m where
type ServerT (HttpVersion :> api) context m = HttpVersion -> ServerT api context m
route Proxy ctx subserver =
route (Proxy :: Proxy api) ctx (passToServer subserver rqVersion)
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
instance HasServer api ctx m => HasServer (Summary desc :> api) ctx m where
type ServerT (Summary desc :> api) ctx m = ServerT api ctx m
route _ = route (Proxy :: Proxy api)
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt s
instance HasServer api ctx m => HasServer (Description desc :> api) ctx m where
type ServerT (Description desc :> api) ctx m = ServerT api ctx m
route _ = route (Proxy :: Proxy api)
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt s
data EmptyServer = EmptyServer deriving (Typeable, Eq, Show, Bounded, Enum)
emptyServer :: ServerT EmptyAPI context m
emptyServer = Tagged EmptyServer
instance HasServer EmptyAPI context m where
type ServerT EmptyAPI context m = Tagged m EmptyServer
route Proxy _ _ = StaticRouter mempty mempty
hoistServerWithContext _ _ _ = retag
instance ( KnownSymbol realm
, HasServer api context m
, HasContextEntry context (BasicAuthCheck m usr)
)
=> HasServer (BasicAuth realm usr :> api) context m where
type ServerT (BasicAuth realm usr :> api) context m = usr -> ServerT api context m
route Proxy context subserver =
route (Proxy :: Proxy api) context (subserver `addAuthCheck` authCheck)
where
realm = B.pack $ symbolVal (Proxy :: Proxy realm)
basicAuthContext = getContextEntry context
authCheck = withRequest $ \ req -> runBasicAuth req realm basicAuthContext
hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
ct_wildcard :: B.ByteString
ct_wildcard = "*" <> "/" <> "*"