@@ -1,29 +1,29 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
1+{-# LANGUAGE CPP #-}
22{-# LANGUAGE ConstraintKinds #-}
33{-# LANGUAGE DataKinds #-}
44{-# LANGUAGE DeriveDataTypeable #-}
55{-# LANGUAGE FlexibleContexts #-}
66{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE InstanceSigs #-}
87{-# LANGUAGE MultiParamTypeClasses #-}
98{-# LANGUAGE OverloadedStrings #-}
109{-# LANGUAGE PolyKinds #-}
11−{-# LANGUAGE QuantifiedConstraints #-}
1210{-# LANGUAGE RankNTypes #-}
1311{-# LANGUAGE ScopedTypeVariables #-}
1412{-# LANGUAGE TupleSections #-}
15−{-# LANGUAGE TypeApplications #-}
1613{-# LANGUAGE TypeFamilies #-}
1714{-# LANGUAGE TypeOperators #-}
1815{-# LANGUAGE UndecidableInstances #-}
1916
17+#if MIN_VERSION_base(4,9,0) && __GLASGOW_HASKELL__ >= 802
18+#define HAS_TYPE_ERROR
19+#endif
20+
2021module Servant.Server.Internal
2122 ( module Servant.Server.Internal
2223 , module Servant.Server.Internal.BasicAuth
2324 , module Servant.Server.Internal.Context
2425 , module Servant.Server.Internal.Delayed
2526 , module Servant.Server.Internal.DelayedIO
26− , module Servant.Server.Internal.ErrorFormatter
2727 , module Servant.Server.Internal.Handler
2828 , module Servant.Server.Internal.Router
2929 , module Servant.Server.Internal.RouteResult
@@ -41,11 +41,12 @@ import qualified Data.ByteString as B
4141import qualified Data.ByteString.Builder as BB
4242import qualified Data.ByteString.Char8 as BC8
4343import qualified Data.ByteString.Lazy as BL
44−import Data.Constraint (Constraint, Dict(..))
4544import Data.Either
4645 (partitionEithers)
4746import Data.Maybe
4847 (fromMaybe, isNothing, mapMaybe, maybeToList)
48+import Data.Semigroup
49+ ((<>))
4950import Data.String
5051 (IsString (..))
5152import Data.String.Conversions
@@ -54,9 +55,8 @@ import Data.Tagged
5455 (Tagged (..), retag, untag)
5556import qualified Data.Text as T
5657import Data.Typeable
57−import GHC.Generics
5858import GHC.TypeLits
59− (KnownNat, KnownSymbol, TypeError, symbolVal)
59+ (KnownNat, KnownSymbol, natVal, symbolVal)
6060import qualified Network.HTTP.Media as NHM
6161import Network.HTTP.Types hiding
6262 (Header, ResponseHeaders)
@@ -64,52 +64,45 @@ import Network.Socket
6464 (SockAddr)
6565import Network.Wai
6666 (Application, Request, httpVersion, isSecure, lazyRequestBody,
67− queryString, remoteHost, getRequestBodyChunk, requestHeaders,
67+ rawQueryString, remoteHost, requestBody, requestHeaders,
6868 requestMethod, responseLBS, responseStream, vault)
6969import Prelude ()
7070import Prelude.Compat
7171import Servant.API
7272 ((:<|>) (..), (:>), Accept (..), BasicAuth, Capture',
73− CaptureAll, Description, EmptyAPI, Fragment,
74− FramingRender (..), FramingUnrender (..), FromSourceIO (..),
75− Header', If, IsSecure (..), NoContentVerb, QueryFlag,
76− QueryParam', QueryParams, Raw, ReflectMethod (reflectMethod),
77− RemoteHost, ReqBody', SBool (..), SBoolI (..), SourceIO,
78− Stream, StreamBody', Summary, ToSourceIO (..), Vault, Verb,
79− WithNamedContext, NamedRoutes)
80−import Servant.API.Generic (GenericMode(..), ToServant, ToServantApi, GServantProduct, toServant, fromServant)
73+ CaptureAll, Description, EmptyAPI, FramingRender (..),
74+ FramingUnrender (..), FromSourceIO (..), Header', If,
75+ IsSecure (..), QueryFlag, QueryParam', QueryParams, Raw,
76+ ReflectMethod (reflectMethod), RemoteHost, ReqBody',
77+ SBool (..), SBoolI (..), SourceIO, Stream, StreamBody',
78+ Summary, ToSourceIO (..), Vault, Verb, WithNamedContext)
8179import Servant.API.ContentTypes
8280 (AcceptHeader (..), AllCTRender (..), AllCTUnrender (..),
83− AllMime, MimeRender (..), MimeUnrender (..), NoContent,
84− canHandleAcceptH)
81+ AllMime, MimeRender (..), MimeUnrender (..), canHandleAcceptH)
8582import Servant.API.Modifiers
8683 (FoldLenient, FoldRequired, RequestArgument,
8784 unfoldRequestArgument)
8885import Servant.API.ResponseHeaders
8986 (GetHeaders, Headers, getHeaders, getResponse)
90−import Servant.API.Status
91− (statusFromNat)
9287import qualified Servant.Types.SourceT as S
93−import Servant.API.TypeErrors
9488import Web.HttpApiData
95− (FromHttpApiData, parseHeader, parseQueryParam, parseUrlPiece,
96− parseUrlPieces)
89+ (FromHttpApiData, parseHeader, parseQueryParam,
90+ parseUrlPieceMaybe, parseUrlPieces)
9791
9892import Servant.Server.Internal.BasicAuth
9993import Servant.Server.Internal.Context
10094import Servant.Server.Internal.Delayed
10195import Servant.Server.Internal.DelayedIO
102−import Servant.Server.Internal.ErrorFormatter
10396import Servant.Server.Internal.Handler
10497import Servant.Server.Internal.Router
10598import Servant.Server.Internal.RouteResult
10699import Servant.Server.Internal.RoutingApplication
107100import Servant.Server.Internal.ServerError
108101
102+#ifdef HAS_TYPE_ERROR
109103import GHC.TypeLits
110104 (ErrorMessage (..), TypeError)
111−import Servant.API.TypeLevel
112− (AtLeastOneFragment, FragmentUnique)
105+#endif
113106
114107class HasServer api context where
115108 type ServerT api (m :: * -> *) :: *
@@ -173,31 +166,22 @@ instance (HasServer a context, HasServer b context) => HasServer (a :<|> b) cont
173166-- > server = getBook
174167-- > where getBook :: Text -> Handler Book
175168-- > getBook isbn = ...
176−instance (KnownSymbol capture, FromHttpApiData a, Typeable a
177− , HasServer api context, SBoolI (FoldLenient mods)
178− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters
179− )
169+instance (KnownSymbol capture, FromHttpApiData a, HasServer api context)
180170 => HasServer (Capture' mods capture a :> api) context where
181171
182172 type ServerT (Capture' mods capture a :> api) m =
183− If (FoldLenient mods) (Either String a) a -> ServerT api m
173+ a -> ServerT api m
184174
185175 hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
186176
187177 route Proxy context d =
188− CaptureRouter [hint] $
178+ CaptureRouter $
189179 route (Proxy :: Proxy api)
190180 context
191− (addCapture d $ \ txt -> withRequest $ \ request ->
192− case ( sbool :: SBool (FoldLenient mods)
193− , parseUrlPiece txt :: Either T.Text a) of
194− (SFalse, Left e) -> delayedFail $ formatError rep request $ cs e
195− (SFalse, Right v) -> return v
196− (STrue, piece) -> return $ (either (Left . cs) Right) piece)
197− where
198− rep = typeRep (Proxy :: Proxy Capture')
199− formatError = urlParseErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
200− hint = CaptureHint (T.pack $ symbolVal $ Proxy @capture) (typeRep (Proxy :: Proxy a))
181+ (addCapture d $ \ txt -> case parseUrlPieceMaybe txt of
182+ Nothing -> delayedFail err400
183+ Just v -> return v
184+ )
201185
202186-- | If you use 'CaptureAll' in one of the endpoints for your API,
203187-- this automatically requires your server-side handler to be a
@@ -216,10 +200,7 @@ instance (KnownSymbol capture, FromHttpApiData a, Typeable a
216200-- > server = getSourceFile
217201-- > where getSourceFile :: [Text] -> Handler Book
218202-- > getSourceFile pathSegments = ...
219−instance (KnownSymbol capture, FromHttpApiData a, Typeable a
220− , HasServer api context
221− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters
222− )
203+instance (KnownSymbol capture, FromHttpApiData a, HasServer api context)
223204 => HasServer (CaptureAll capture a :> api) context where
224205
225206 type ServerT (CaptureAll capture a :> api) m =
@@ -228,18 +209,14 @@ instance (KnownSymbol capture, FromHttpApiData a, Typeable a
228209 hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
229210
230211 route Proxy context d =
231− CaptureAllRouter [hint] $
212+ CaptureAllRouter $
232213 route (Proxy :: Proxy api)
233214 context
234− (addCapture d $ \ txts -> withRequest $ \ request ->
235− case parseUrlPieces txts of
236− Left e -> delayedFail $ formatError rep request $ cs e
237− Right v -> return v
215+ (addCapture d $ \ txts -> case parseUrlPieces txts of
216+ Left _ -> delayedFail err400
217+ Right v -> return v
238218 )
239− where
240− rep = typeRep (Proxy :: Proxy CaptureAll)
241− formatError = urlParseErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
242− hint = CaptureHint (T.pack $ symbolVal $ Proxy @capture) (typeRep (Proxy :: Proxy [a]))
219+
243220
244221allowedMethodHead :: Method -> Request -> Bool
245222allowedMethodHead method request = method == methodGet && requestMethod request == methodHead
@@ -259,10 +236,10 @@ methodCheck method request
259236-- body check is no longer an option. However, we now run the accept
260237-- check before the body check and can therefore afford to make it
261238-- recoverable.
262−acceptCheck :: (AllMime list) => Proxy list -> AcceptHeader -> DelayedIO ()
239+acceptCheck :: (AllMime list) => Proxy list -> B.ByteString -> DelayedIO ()
263240acceptCheck proxy accH
264− | canHandleAcceptH proxy accH = return ()
265− | otherwise = delayedFail err406
241+ | canHandleAcceptH proxy (AcceptHeader accH) = return ()
242+ | otherwise = delayedFail err406
266243
267244methodRouter :: (AllCTRender ctypes a)
268245 => (b -> ([(HeaderName, B.ByteString)], a))
@@ -272,28 +249,17 @@ methodRouter :: (AllCTRender ctypes a)
272249methodRouter splitHeaders method proxy status action = leafRouter route'
273250 where
274251 route' env request respond =
275− let accH = getAcceptHeader request
252+ let accH = fromMaybe ct_wildcard $ lookup hAccept $ requestHeaders request
276253 in runAction (action `addMethodCheck` methodCheck method request
277254 `addAcceptCheck` acceptCheck proxy accH
278255 ) env request respond $ \ output -> do
279256 let (headers, b) = splitHeaders output
280− case handleAcceptH proxy accH b of
257+ case handleAcceptH proxy (AcceptHeader accH) b of
281258 Nothing -> FailFatal err406 -- this should not happen (checked before), so we make it fatal if it does
282259 Just (contentT, body) ->
283260 let bdy = if allowedMethodHead method request then "" else body
284261 in Route $ responseLBS status ((hContentType, cs contentT) : headers) bdy
285262
286−noContentRouter :: Method
287− -> Status
288− -> Delayed env (Handler b)
289− -> Router env
290−noContentRouter method status action = leafRouter route'
291− where
292− route' env request respond =
293− runAction (action `addMethodCheck` methodCheck method request)
294− env request respond $ \ _output ->
295− Route $ responseLBS status [] ""
296−
297263instance {-# OVERLAPPABLE #-}
298264 ( AllCTRender ctypes a, ReflectMethod method, KnownNat status
299265 ) => HasServer (Verb method status ctypes a) context where
@@ -303,7 +269,7 @@ instance {-# OVERLAPPABLE #-}
303269
304270 route Proxy _ = methodRouter ([],) method (Proxy :: Proxy ctypes) status
305271 where method = reflectMethod (Proxy :: Proxy method)
306− status = statusFromNat (Proxy :: Proxy status)
272+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
307273
308274instance {-# OVERLAPPING #-}
309275 ( AllCTRender ctypes a, ReflectMethod method, KnownNat status
@@ -315,16 +281,8 @@ instance {-# OVERLAPPING #-}
315281
316282 route Proxy _ = methodRouter (\x -> (getHeaders x, getResponse x)) method (Proxy :: Proxy ctypes) status
317283 where method = reflectMethod (Proxy :: Proxy method)
318− status = statusFromNat (Proxy :: Proxy status)
319−
320−instance (ReflectMethod method) =>
321− HasServer (NoContentVerb method) context where
284+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
322285
323− type ServerT (NoContentVerb method) m = m NoContent
324− hoistServerWithContext _ _ nt s = nt s
325−
326− route Proxy _ = noContentRouter method status204
327− where method = reflectMethod (Proxy :: Proxy method)
328286
329287instance {-# OVERLAPPABLE #-}
330288 ( MimeRender ctype chunk, ReflectMethod method, KnownNat status,
@@ -336,7 +294,7 @@ instance {-# OVERLAPPABLE #-}
336294
337295 route Proxy _ = streamRouter ([],) method status (Proxy :: Proxy framing) (Proxy :: Proxy ctype)
338296 where method = reflectMethod (Proxy :: Proxy method)
339− status = statusFromNat (Proxy :: Proxy status)
297+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
340298
341299
342300instance {-# OVERLAPPING #-}
@@ -350,7 +308,7 @@ instance {-# OVERLAPPING #-}
350308
351309 route Proxy _ = streamRouter (\x -> (getHeaders x, getResponse x)) method status (Proxy :: Proxy framing) (Proxy :: Proxy ctype)
352310 where method = reflectMethod (Proxy :: Proxy method)
353− status = statusFromNat (Proxy :: Proxy status)
311+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
354312
355313
356314streamRouter :: forall ctype a c chunk env framing. (MimeRender ctype chunk, FramingRender framing, ToSourceIO chunk a) =>
@@ -362,7 +320,7 @@ streamRouter :: forall ctype a c chunk env framing. (MimeRender ctype chunk, Fra
362320 -> Delayed env (Handler c)
363321 -> Router env
364322streamRouter splitHeaders method status framingproxy ctypeproxy action = leafRouter $ \env request respond ->
365− let AcceptHeader accH = getAcceptHeader request
323+ let accH = fromMaybe ct_wildcard $ lookup hAccept $ requestHeaders request
366324 cmediatype = NHM.matchAccept [contentType ctypeproxy] accH
367325 accCheck = when (isNothing cmediatype) $ delayedFail err406
368326 contentHeader = (hContentType, NHM.renderHeader . maybeToList $ cmediatype)
@@ -407,7 +365,6 @@ streamRouter splitHeaders method status framingproxy ctypeproxy action = leafRou
407365instance
408366 (KnownSymbol sym, FromHttpApiData a, HasServer api context
409367 , SBoolI (FoldRequired mods), SBoolI (FoldLenient mods)
410− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters
411368 )
412369 => HasServer (Header' mods sym a :> api) context where
413370------
@@ -419,9 +376,6 @@ instance
419376 route Proxy context subserver = route (Proxy :: Proxy api) context $
420377 subserver `addHeaderCheck` withRequest headerCheck
421378 where
422− rep = typeRep (Proxy :: Proxy Header')
423− formatError = headerParseErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
424−
425379 headerName :: IsString n => n
426380 headerName = fromString $ symbolVal (Proxy :: Proxy sym)
427381
@@ -432,13 +386,15 @@ instance
432386 mev :: Maybe (Either T.Text a)
433387 mev = fmap parseHeader $ lookup headerName (requestHeaders req)
434388
435− errReq = delayedFailFatal $ formatError rep req
436− $ "Header " <> headerName <> " is required"
389+ errReq = delayedFailFatal err400
390+ { errBody = "Header " <> headerName <> " is required"
391+ }
437392
438− errSt e = delayedFailFatal $ formatError rep req
439− $ cs $ "Error parsing header "
440− <> headerName
441− <> " failed: " <> e
393+ errSt e = delayedFailFatal err400
394+ { errBody = cs $ "Error parsing header "
395+ <> headerName
396+ <> " failed: " <> e
397+ }
442398
443399-- | If you use @'QueryParam' "author" Text@ in one of the endpoints for your API,
444400-- this automatically requires your server-side handler to be a function
@@ -464,7 +420,6 @@ instance
464420instance
465421 ( KnownSymbol sym, FromHttpApiData a, HasServer api context
466422 , SBoolI (FoldRequired mods), SBoolI (FoldLenient mods)
467− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters
468423 )
469424 => HasServer (QueryParam' mods sym a :> api) context where
470425------
@@ -474,12 +429,9 @@ instance
474429 hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
475430
476431 route Proxy context subserver =
477− let querytext = queryToQueryText . queryString
432+ let querytext req = parseQueryText $ rawQueryString req
478433 paramname = cs $ symbolVal (Proxy :: Proxy sym)
479434
480− rep = typeRep (Proxy :: Proxy QueryParam')
481− formatError = urlParseErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
482−
483435 parseParam :: Request -> DelayedIO (RequestArgument mods a)
484436 parseParam req =
485437 unfoldRequestArgument (Proxy :: Proxy mods) errReq errSt mev
@@ -487,12 +439,14 @@ instance
487439 mev :: Maybe (Either T.Text a)
488440 mev = fmap parseQueryParam $ join $ lookup paramname $ querytext req
489441
490− errReq = delayedFailFatal $ formatError rep req
491− $ cs $ "Query parameter " <> paramname <> " is required"
442+ errReq = delayedFailFatal err400
443+ { errBody = cs $ "Query parameter " <> paramname <> " is required"
444+ }
492445
493− errSt e = delayedFailFatal $ formatError rep req
494− $ cs $ "Error parsing query parameter "
495− <> paramname <> " failed: " <> e
446+ errSt e = delayedFailFatal err400
447+ { errBody = cs $ "Error parsing query parameter "
448+ <> paramname <> " failed: " <> e
449+ }
496450
497451 delayed = addParameterCheck subserver . withRequest $ \req ->
498452 parseParam req
@@ -518,8 +472,7 @@ instance
518472-- > server = getBooksBy
519473-- > where getBooksBy :: [Text] -> Handler [Book]
520474-- > getBooksBy authors = ...return all books by these authors...
521−instance (KnownSymbol sym, FromHttpApiData a, HasServer api context
522− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters)
475+instance (KnownSymbol sym, FromHttpApiData a, HasServer api context)
523476 => HasServer (QueryParams sym a :> api) context where
524477
525478 type ServerT (QueryParams sym a :> api) m =
@@ -530,23 +483,21 @@ instance (KnownSymbol sym, FromHttpApiData a, HasServer api context
530483 route Proxy context subserver = route (Proxy :: Proxy api) context $
531484 subserver `addParameterCheck` withRequest paramsCheck
532485 where
533− rep = typeRep (Proxy :: Proxy QueryParams)
534− formatError = urlParseErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
535−
536486 paramname = cs $ symbolVal (Proxy :: Proxy sym)
537487 paramsCheck req =
538488 case partitionEithers $ fmap parseQueryParam params of
539489 ([], parsed) -> return parsed
540− (errs, _) -> delayedFailFatal $ formatError rep req
541− $ cs $ "Error parsing query parameter(s) "
542− <> paramname <> " failed: "
543− <> T.intercalate ", " errs
490+ (errs, _) -> delayedFailFatal err400
491+ { errBody = cs $ "Error parsing query parameter(s) "
492+ <> paramname <> " failed: "
493+ <> T.intercalate ", " errs
494+ }
544495 where
545496 params :: [T.Text]
546497 params = mapMaybe snd
547498 . filter (looksLikeParam . fst)
548− . queryToQueryText
549− . queryString
499+ . parseQueryText
500+ . rawQueryString
550501 $ req
551502
552503 looksLikeParam name = name == paramname || name == (paramname <> "[]")
@@ -572,7 +523,7 @@ instance (KnownSymbol sym, HasServer api context)
572523 hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt . s
573524
574525 route Proxy context subserver =
575− let querytext = queryToQueryText . queryString
526+ let querytext r = parseQueryText $ rawQueryString r
576527 param r = case lookup paramname (querytext r) of
577528 Just Nothing -> True -- param is there, with no value
578529 Just (Just v) -> examine v -- param with a value
@@ -614,7 +565,7 @@ instance HasServer Raw context where
614565-- The @Content-Type@ header is inspected, and the list provided is used to
615566-- attempt deserialization. If the request does not have a @Content-Type@
616567-- header, it is treated as @application/octet-stream@ (as specified in
617−-- [RFC 7231 section 3.1.1.5](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)).
568+-- <http://tools.ietf.org/html/rfc7231#section-3.1.1.5 RFC7231>.
618569-- This lets servant worry about extracting it from the request and turning
619570-- it into a value of the type you specify.
620571--
@@ -630,7 +581,6 @@ instance HasServer Raw context where
630581-- > where postBook :: Book -> Handler Book
631582-- > postBook book = ...insert into your db...
632583instance ( AllCTUnrender list a, HasServer api context, SBoolI (FoldLenient mods)
633− , HasContextEntry (MkContextWithErrorFormatter context) ErrorFormatters
634584 ) => HasServer (ReqBody' mods list a :> api) context where
635585
636586 type ServerT (ReqBody' mods list a :> api) m =
@@ -642,9 +592,6 @@ instance ( AllCTUnrender list a, HasServer api context, SBoolI (FoldLenient mods
642592 = route (Proxy :: Proxy api) context $
643593 addBodyCheck subserver ctCheck bodyCheck
644594 where
645− rep = typeRep (Proxy :: Proxy ReqBody')
646− formatError = bodyParserErrorFormatter $ getContextEntry (mkContextWithErrorFormatter context)
647−
648595 -- Content-Type check, we only lookup we can try to parse the request body
649596 ctCheck = withRequest $ \ request -> do
650597 -- See HTTP RFC 2616, section 7.2.1
@@ -663,7 +610,7 @@ instance ( AllCTUnrender list a, HasServer api context, SBoolI (FoldLenient mods
663610 case sbool :: SBool (FoldLenient mods) of
664611 STrue -> return mrqbody
665612 SFalse -> case mrqbody of
666− Left e -> delayedFailFatal $ formatError rep request e
613+ Left e -> delayedFailFatal err400 { errBody = cs e }
667614 Right v -> return v
668615
669616instance
@@ -686,7 +633,7 @@ instance
686633 bodyCheck fromRS = withRequest $ \req -> do
687634 let mimeUnrender' = mimeUnrender (Proxy :: Proxy ctype) :: BL.ByteString -> Either String chunk
688635 let framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender' :: SourceIO B.ByteString -> SourceIO chunk
689− let body = getRequestBodyChunk req
636+ let body = requestBody req
690637 let rs = S.fromAction B.null body
691638 let rs' = fromRS $ framingUnrender' rs
692639 return rs'
@@ -755,12 +702,12 @@ data EmptyServer = EmptyServer deriving (Typeable, Eq, Show, Bounded, Enum)
755702emptyServer :: ServerT EmptyAPI m
756703emptyServer = Tagged EmptyServer
757704
758−-- | The server for an `EmptyAPI` is `emptyServer`.
705+-- | The server for an `EmptyAPI` is `emptyAPIServer`.
759706--
760707-- > type MyApi = "nothing" :> EmptyApi
761708-- >
762709-- > server :: Server MyApi
763−-- > server = emptyServer
710+-- > server = emptyAPIServer
764711instance HasServer EmptyAPI context where
765712 type ServerT EmptyAPI m = Tagged m EmptyServer
766713
@@ -789,10 +736,7 @@ instance ( KnownSymbol realm
789736-- * helpers
790737
791738ct_wildcard :: B.ByteString
792−ct_wildcard = "*" <> "/" <> "*"
793−
794−getAcceptHeader :: Request -> AcceptHeader
795−getAcceptHeader = AcceptHeader . fromMaybe ct_wildcard . lookup hAccept . requestHeaders
739+ct_wildcard = "*" <> "/" <> "*" -- Because CPP
796740
797741-- * General Authentication
798742
@@ -817,15 +761,39 @@ instance (HasContextEntry context (NamedContext name subContext), HasServer subA
817761 hoistServerWithContext _ _ nt s = hoistServerWithContext (Proxy :: Proxy subApi) (Proxy :: Proxy subContext) nt s
818762
819763-------------------------------------------------------------------------------
820−-- Custom type errors
764+-- TypeError helpers
821765-------------------------------------------------------------------------------
822766
823−-- Erroring instance for 'HasServer' when a combinator is not fully applied
824−instance TypeError (PartialApplication HasServer arr) => HasServer ((arr :: a -> b) :> sub) context
767+#ifdef HAS_TYPE_ERROR
768+-- | This instance catches mistakes when there are non-saturated
769+-- type applications on LHS of ':>'.
770+--
771+-- >>> serve (Proxy :: Proxy (Capture "foo" :> Get '[JSON] Int)) (error "...")
772+-- ...
773+-- ...Expected something of kind Symbol or *, got: k -> l on the LHS of ':>'.
774+-- ...Maybe you haven't applied enough arguments to
775+-- ...Capture' '[] "foo"
776+-- ...
777+--
778+-- >>> undefined :: Server (Capture "foo" :> Get '[JSON] Int)
779+-- ...
780+-- ...Expected something of kind Symbol or *, got: k -> l on the LHS of ':>'.
781+-- ...Maybe you haven't applied enough arguments to
782+-- ...Capture' '[] "foo"
783+-- ...
784+--
785+instance TypeError (HasServerArrowKindError arr) => HasServer ((arr :: k -> l) :> api) context
825786 where
826− type ServerT (arr :> sub) _ = TypeError (PartialApplication (HasServer :: * -> [*] -> Constraint) arr)
827− route = error "unreachable"
828− hoistServerWithContext _ _ _ _ = error "unreachable"
787+ type ServerT (arr :> api) m = TypeError (HasServerArrowKindError arr)
788+ -- it doens't really matter what sub route we peak
789+ route _ _ _ = error "servant-server panic: impossible happened in HasServer (arr :> api)"
790+ hoistServerWithContext _ _ _ = id
791+
792+-- Cannot have TypeError here, otherwise use of this symbol will error :)
793+type HasServerArrowKindError arr =
794+ 'Text "Expected something of kind Symbol or *, got: k -> l on the LHS of ':>'."
795+ ':$$: 'Text "Maybe you haven't applied enough arguments to"
796+ ':$$: 'ShowType arr
829797
830798-- | This instance prevents from accidentally using '->' instead of ':>'
831799--
@@ -859,103 +827,7 @@ type HasServerArrowTypeError a b =
859827 ':$$: 'ShowType a
860828 ':$$: 'Text "and"
861829 ':$$: 'ShowType b
862−
863−-- Erroring instances for 'HasServer' for unknown API combinators
864−
865−-- XXX: This omits the @context@ parameter, e.g.:
866−--
867−-- "There is no instance for HasServer (Bool :> …)". Do we care ?
868−instance {-# OVERLAPPABLE #-} TypeError (NoInstanceForSub HasServer ty) => HasServer (ty :> sub) context
869−
870−instance {-# OVERLAPPABLE #-} TypeError (NoInstanceFor (HasServer api context)) => HasServer api context
871−
872−-- | Ignore @'Fragment'@ in server handlers.
873−-- See <https://ietf.org/rfc/rfc2616.html#section-15.1.3> for more details.
874−--
875−-- Example:
876−--
877−-- > type MyApi = "books" :> Fragment Text :> Get '[JSON] [Book]
878−-- >
879−-- > server :: Server MyApi
880−-- > server = getBooks
881−-- > where getBooks :: Handler [Book]
882−-- > getBooks = ...return all books...
883−instance (AtLeastOneFragment api, FragmentUnique (Fragment a1 :> api), HasServer api context)
884− => HasServer (Fragment a1 :> api) context where
885− type ServerT (Fragment a1 :> api) m = ServerT api m
886−
887− route _ = route (Proxy :: Proxy api)
888−
889− hoistServerWithContext _ = hoistServerWithContext (Proxy :: Proxy api)
830+#endif
890831
891832-- $setup
892833-- >>> import Servant
893−
894−-- | A type that specifies that an API record contains a server implementation.
895−data AsServerT (m :: * -> *)
896−instance GenericMode (AsServerT m) where
897− type AsServerT m :- api = ServerT api m
898−
899−type AsServer = AsServerT Handler
900−
901−
902−-- | Set of constraints required to convert to / from vanilla server types.
903−type GServerConstraints api m =
904− ( ToServant api (AsServerT m) ~ ServerT (ToServantApi api) m
905− , GServantProduct (Rep (api (AsServerT m)))
906− )
907−
908−-- | This class is a necessary evil: in the implementation of 'HasServer' for
909−-- @'NamedRoutes' api@, we essentially need the quantified constraint @forall
910−-- m. 'GServerConstraints' m@ to hold.
911−--
912−-- We cannot require do that directly as the definition of 'GServerConstraints'
913−-- contains type family applications ('Rep' and 'ServerT'). The trick is to hide
914−-- those type family applications behind a typeclass providing evidence for
915−-- @'GServerConstraints' api m@ in the form of a dictionary, and require that
916−-- @forall m. 'GServer' api m@ instead.
917−--
918−-- Users shouldn't have to worry about this class, as the only possible instance
919−-- is provided in this module for all record APIs.
920−
921−class GServer (api :: * -> *) (m :: * -> *) where
922− gServerProof :: Dict (GServerConstraints api m)
923−
924−instance
925− ( ToServant api (AsServerT m) ~ ServerT (ToServantApi api) m
926− , GServantProduct (Rep (api (AsServerT m)))
927− ) => GServer api m where
928− gServerProof = Dict
929−
930−instance
931− ( HasServer (ToServantApi api) context
932− , forall m. Generic (api (AsServerT m))
933− , forall m. GServer api m
934− ) => HasServer (NamedRoutes api) context where
935−
936− type ServerT (NamedRoutes api) m = api (AsServerT m)
937−
938− route
939− :: Proxy (NamedRoutes api)
940− -> Context context
941− -> Delayed env (api (AsServerT Handler))
942− -> Router env
943− route _ ctx delayed =
944− case gServerProof @api @Handler of
945− Dict -> route (Proxy @(ToServantApi api)) ctx (toServant <$> delayed)
946−
947− hoistServerWithContext
948− :: forall m n. Proxy (NamedRoutes api)
949− -> Proxy context
950− -> (forall x. m x -> n x)
951− -> api (AsServerT m)
952− -> api (AsServerT n)
953− hoistServerWithContext _ pctx nat server =
954− case (gServerProof @api @m, gServerProof @api @n) of
955− (Dict, Dict) ->
956− fromServant servantSrvN
957− where
958− servantSrvM :: ServerT (ToServantApi api) m =
959− toServant server
960− servantSrvN :: ServerT (ToServantApi api) n =
961− hoistServerWithContext (Proxy @(ToServantApi api)) pctx nat servantSrvM