{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE PatternGuards       #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE RecordWildCards     #-}
{-# LANGUAGE TemplateHaskell     #-}
{-# LANGUAGE TupleSections       #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Yesod.Core.Internal.Run
  ( toErrorHandler
  , errFromShow
  , basicRunHandler
  , handleError
  , handleContents
  , evalFallback
  , runHandler
  , safeEh
  , runFakeHandler
  , yesodRunner
  , yesodRender
  , resolveApproot
  )
  where

import qualified Control.Exception as EUnsafe
import Yesod.Core.Internal.Response
import           Data.ByteString.Builder      (toLazyByteString)
import qualified Data.ByteString.Lazy         as BL
import           Control.Monad.IO.Class       (MonadIO, liftIO)
import           Control.Monad.Logger         (LogLevel (LevelError), LogSource,
                                               liftLoc)
import           Control.Monad.Trans.Resource (runResourceT, withInternalState, runInternalState, InternalState)
import qualified Data.ByteString              as S
import qualified Data.ByteString.Char8        as S8
import qualified Data.IORef                   as I
import qualified Data.Map                     as Map
import           Data.Maybe                   (isJust, fromMaybe)
import           Data.Monoid                  (appEndo)
import           Data.Text                    (Text)
import qualified Data.Text                    as T
import           Data.Text.Encoding           (encodeUtf8, decodeUtf8With)
import           Data.Text.Encoding.Error     (lenientDecode)
import           Language.Haskell.TH.Syntax   (Loc, qLocation)
import qualified Network.HTTP.Types           as H
import           Network.Wai
import           Network.Wai.Internal
import           System.Log.FastLogger        (LogStr, toLogStr)
import           Yesod.Core.Content
import           Yesod.Core.Class.Yesod
import           Yesod.Core.Types
import           Yesod.Core.Internal.Request  (parseWaiRequest,
                                               tooLargeResponse)
import           Yesod.Core.Internal.Util     (getCurrentMaxExpiresRFC1123)
import           Yesod.Routes.Class           (Route, renderRoute)
import           Control.DeepSeq              (($!!), NFData)
import           UnliftIO.Exception
import           UnliftIO(MonadUnliftIO, withRunInIO)
import           Data.Proxy(Proxy(..))

-- | Convert a synchronous exception into an ErrorResponse
toErrorHandler :: SomeException -> IO ErrorResponse
toErrorHandler :: SomeException -> IO ErrorResponse
toErrorHandler SomeException
e0 = forall (m :: * -> *) a.
MonadUnliftIO m =>
(SomeException -> m a) -> m a -> m a
handleAny SomeException -> IO ErrorResponse
errFromShow forall a b. (a -> b) -> a -> b
$
    case forall e. Exception e => SomeException -> Maybe e
fromException SomeException
e0 of
        Just (HCError ErrorResponse
x) -> forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate forall a b. NFData a => (a -> b) -> a -> b
$!! ErrorResponse
x
        Maybe HandlerContents
_ -> SomeException -> IO ErrorResponse
errFromShow SomeException
e0

-- | Generate an @ErrorResponse@ based on the shown version of the exception
errFromShow :: SomeException -> IO ErrorResponse
errFromShow :: SomeException -> IO ErrorResponse
errFromShow SomeException
x = do
  LogSource
text <- forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate ([Char] -> LogSource
T.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> [Char]
show SomeException
x) forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
`catchAny` \SomeException
_ ->
          forall (m :: * -> *) a. Monad m => a -> m a
return ([Char] -> LogSource
T.pack [Char]
"Yesod.Core.Internal.Run.errFromShow: show of an exception threw an exception")
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ LogSource -> ErrorResponse
InternalError LogSource
text

-- | Do a basic run of a handler, getting some contents and the final
-- @GHState@. The @GHState@ unfortunately may contain some impure
-- exceptions, but all other synchronous exceptions will be caught and
-- represented by the @HandlerContents@.
basicRunHandler :: ToTypedContent c
                => RunHandlerEnv site site
                -> HandlerFor site c
                -> YesodRequest
                -> InternalState
                -> IO (GHState, HandlerContents)
basicRunHandler :: forall c site.
ToTypedContent c =>
RunHandlerEnv site site
-> HandlerFor site c
-> YesodRequest
-> InternalState
-> IO (GHState, HandlerContents)
basicRunHandler RunHandlerEnv site site
rhe HandlerFor site c
handler YesodRequest
yreq InternalState
resState = do
    -- Create a mutable ref to hold the state. We use mutable refs so
    -- that the updates will survive runtime exceptions.
    IORef GHState
istate <- forall a. a -> IO (IORef a)
I.newIORef GHState
defState

    -- Run the handler itself, capturing any runtime exceptions and
    -- converting them into a @HandlerContents@
    HandlerContents
contents' <- forall child site.
RunHandlerEnv child site
-> forall a (m :: * -> *).
   MonadUnliftIO m =>
   m a -> (SomeException -> m a) -> m a
rheCatchHandlerExceptions RunHandlerEnv site site
rhe
        (do
            c
res <- forall site a. HandlerFor site a -> HandlerData site site -> IO a
unHandlerFor HandlerFor site c
handler (IORef GHState -> HandlerData site site
hd IORef GHState
istate)
            TypedContent
tc <- forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate (forall a. ToTypedContent a => a -> TypedContent
toTypedContent c
res)
            -- Success! Wrap it up in an @HCContent@
            forall (m :: * -> *) a. Monad m => a -> m a
return (Status -> TypedContent -> HandlerContents
HCContent Status
defaultStatus TypedContent
tc))
        (\SomeException
e ->
            case forall e. Exception e => SomeException -> Maybe e
fromException SomeException
e of
                Just HandlerContents
e' -> forall (m :: * -> *) a. Monad m => a -> m a
return HandlerContents
e'
                Maybe HandlerContents
Nothing -> ErrorResponse -> HandlerContents
HCError forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SomeException -> IO ErrorResponse
toErrorHandler SomeException
e)

    -- Get the raw state and return
    GHState
state <- forall a. IORef a -> IO a
I.readIORef IORef GHState
istate
    forall (m :: * -> *) a. Monad m => a -> m a
return (GHState
state, HandlerContents
contents')
  where
    defState :: GHState
defState = GHState
        { ghsSession :: SessionMap
ghsSession = YesodRequest -> SessionMap
reqSession YesodRequest
yreq
        , ghsRBC :: Maybe RequestBodyContents
ghsRBC = forall a. Maybe a
Nothing
        , ghsIdent :: Int
ghsIdent = Int
1
        , ghsCache :: TypeMap
ghsCache = forall a. Monoid a => a
mempty
        , ghsCacheBy :: KeyedTypeMap
ghsCacheBy = forall a. Monoid a => a
mempty
        , ghsHeaders :: Endo [Header]
ghsHeaders = forall a. Monoid a => a
mempty
        }
    hd :: IORef GHState -> HandlerData site site
hd IORef GHState
istate = HandlerData
        { handlerRequest :: YesodRequest
handlerRequest = YesodRequest
yreq
        , handlerEnv :: RunHandlerEnv site site
handlerEnv     = RunHandlerEnv site site
rhe
        , handlerState :: IORef GHState
handlerState   = IORef GHState
istate
        , handlerResource :: InternalState
handlerResource = InternalState
resState
        }

-- | Convert an @ErrorResponse@ into a @YesodResponse@
handleError :: RunHandlerEnv sub site
            -> YesodRequest
            -> InternalState
            -> Map.Map Text S8.ByteString
            -> [Header]
            -> ErrorResponse
            -> IO YesodResponse
handleError :: forall sub site.
RunHandlerEnv sub site
-> YesodRequest
-> InternalState
-> SessionMap
-> [Header]
-> ErrorResponse
-> IO YesodResponse
handleError RunHandlerEnv sub site
rhe YesodRequest
yreq InternalState
resState SessionMap
finalSession [Header]
headers ErrorResponse
e0 = do
    -- Find any evil hidden impure exceptions
    ErrorResponse
e <- (forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate forall a b. NFData a => (a -> b) -> a -> b
$!! ErrorResponse
e0) forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
`catchAny` SomeException -> IO ErrorResponse
errFromShow

    -- Generate a response, leveraging the updated session and
    -- response headers
    forall a b c. (a -> b -> c) -> b -> a -> c
flip forall (m :: * -> *) a. ResourceT m a -> InternalState -> m a
runInternalState InternalState
resState forall a b. (a -> b) -> a -> b
$ do
        YesodResponse
yar <- forall child site.
RunHandlerEnv child site -> ErrorResponse -> YesodApp
rheOnError RunHandlerEnv sub site
rhe ErrorResponse
e YesodRequest
yreq
            { reqSession :: SessionMap
reqSession = SessionMap
finalSession
            }
        case YesodResponse
yar of
            YRPlain Status
status' [Header]
hs ByteString
ct Content
c SessionMap
sess ->
                let hs' :: [Header]
hs' = [Header]
headers forall a. [a] -> [a] -> [a]
++ [Header]
hs
                    status :: Status
status
                        | Status
status' forall a. Eq a => a -> a -> Bool
== Status
defaultStatus = ErrorResponse -> Status
getStatus ErrorResponse
e
                        | Bool
otherwise = Status
status'
                in forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain Status
status [Header]
hs' ByteString
ct Content
c SessionMap
sess
            YRWai Response
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return YesodResponse
yar
            YRWaiApp Application
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return YesodResponse
yar

-- | Convert a @HandlerContents@ into a @YesodResponse@
handleContents :: (ErrorResponse -> IO YesodResponse)
               -> Map.Map Text S8.ByteString
               -> [Header]
               -> HandlerContents
               -> IO YesodResponse
handleContents :: (ErrorResponse -> IO YesodResponse)
-> SessionMap -> [Header] -> HandlerContents -> IO YesodResponse
handleContents ErrorResponse -> IO YesodResponse
handleError' SessionMap
finalSession [Header]
headers HandlerContents
contents =
    case HandlerContents
contents of
        HCContent Status
status (TypedContent ByteString
ct Content
c) -> do
            -- Check for impure exceptions hiding in the contents
            Either ErrorResponse Content
ec' <- Content -> IO (Either ErrorResponse Content)
evaluateContent Content
c
            case Either ErrorResponse Content
ec' of
                Left ErrorResponse
e -> ErrorResponse -> IO YesodResponse
handleError' ErrorResponse
e
                Right Content
c' -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain Status
status [Header]
headers ByteString
ct Content
c' SessionMap
finalSession
        HCError ErrorResponse
e -> ErrorResponse -> IO YesodResponse
handleError' ErrorResponse
e
        HCRedirect Status
status LogSource
loc -> do
            let disable_caching :: [Header] -> [Header]
disable_caching [Header]
x =
                      CI ByteString -> ByteString -> Header
Header CI ByteString
"Cache-Control" ByteString
"no-cache, must-revalidate"
                    forall a. a -> [a] -> [a]
: CI ByteString -> ByteString -> Header
Header CI ByteString
"Expires" ByteString
"Thu, 01 Jan 1970 05:05:05 GMT"
                    forall a. a -> [a] -> [a]
: [Header]
x
                hs :: [Header]
hs = (if Status
status forall a. Eq a => a -> a -> Bool
/= Status
H.movedPermanently301 then [Header] -> [Header]
disable_caching else forall a. a -> a
id)
                      forall a b. (a -> b) -> a -> b
$ CI ByteString -> ByteString -> Header
Header CI ByteString
"Location" (LogSource -> ByteString
encodeUtf8 LogSource
loc) forall a. a -> [a] -> [a]
: [Header]
headers
            forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain
                Status
status [Header]
hs ByteString
typePlain Content
emptyContent
                SessionMap
finalSession
        HCSendFile ByteString
ct [Char]
fp Maybe FilePart
p -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain
            Status
H.status200
            [Header]
headers
            ByteString
ct
            ([Char] -> Maybe FilePart -> Content
ContentFile [Char]
fp Maybe FilePart
p)
            SessionMap
finalSession
        HCCreated LogSource
loc -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain
            Status
H.status201
            (CI ByteString -> ByteString -> Header
Header CI ByteString
"Location" (LogSource -> ByteString
encodeUtf8 LogSource
loc) forall a. a -> [a] -> [a]
: [Header]
headers)
            ByteString
typePlain
            Content
emptyContent
            SessionMap
finalSession
        HCWai Response
r -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Response -> YesodResponse
YRWai Response
r
        HCWaiApp Application
a -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Application -> YesodResponse
YRWaiApp Application
a

-- | Evaluate the given value. If an exception is thrown, use it to
-- replace the provided contents and then return @mempty@ in place of the
-- evaluated value.
--
-- Note that this also catches async exceptions.
evalFallback :: (Monoid w, NFData w)
             => (forall a. IO a -> (SomeException -> IO a) -> IO a)
             -> HandlerContents
             -> w
             -> IO (w, HandlerContents)
evalFallback :: forall w.
(Monoid w, NFData w) =>
(forall a. IO a -> (SomeException -> IO a) -> IO a)
-> HandlerContents -> w -> IO (w, HandlerContents)
evalFallback forall a. IO a -> (SomeException -> IO a) -> IO a
catcher HandlerContents
contents w
val = forall a. IO a -> (SomeException -> IO a) -> IO a
catcher
    (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (, HandlerContents
contents) (forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate forall a b. NFData a => (a -> b) -> a -> b
$!! w
val))
    (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((forall a. Monoid a => a
mempty, ) forall b c a. (b -> c) -> (a -> b) -> a -> c
. ErrorResponse -> HandlerContents
HCError) forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeException -> IO ErrorResponse
toErrorHandler)

-- | Function used internally by Yesod in the process of converting a
-- 'HandlerFor' into an 'Application'. Should not be needed by users.
runHandler :: ToTypedContent c
           => RunHandlerEnv site site
           -> HandlerFor site c
           -> YesodApp
runHandler :: forall c site.
ToTypedContent c =>
RunHandlerEnv site site -> HandlerFor site c -> YesodApp
runHandler rhe :: RunHandlerEnv site site
rhe@RunHandlerEnv {site
Maybe (Route site)
LogSource
Loc -> LogSource -> LogLevel -> LogStr -> IO ()
RequestBodyLength -> FileUpload
Route site -> Route site
Route site -> [(LogSource, LogSource)] -> LogSource
ErrorResponse -> YesodApp
forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheMaxExpires :: forall child site. RunHandlerEnv child site -> LogSource
rheLog :: forall child site.
RunHandlerEnv child site
-> Loc -> LogSource -> LogLevel -> LogStr -> IO ()
rheUpload :: forall child site.
RunHandlerEnv child site -> RequestBodyLength -> FileUpload
rheChild :: forall child site. RunHandlerEnv child site -> child
rheSite :: forall child site. RunHandlerEnv child site -> site
rheRouteToMaster :: forall child site.
RunHandlerEnv child site -> Route child -> Route site
rheRoute :: forall child site. RunHandlerEnv child site -> Maybe (Route child)
rheRender :: forall child site.
RunHandlerEnv child site
-> Route site -> [(LogSource, LogSource)] -> LogSource
rheCatchHandlerExceptions :: forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheMaxExpires :: LogSource
rheOnError :: ErrorResponse -> YesodApp
rheLog :: Loc -> LogSource -> LogLevel -> LogStr -> IO ()
rheUpload :: RequestBodyLength -> FileUpload
rheChild :: site
rheSite :: site
rheRouteToMaster :: Route site -> Route site
rheRoute :: Maybe (Route site)
rheRender :: Route site -> [(LogSource, LogSource)] -> LogSource
rheOnError :: forall child site.
RunHandlerEnv child site -> ErrorResponse -> YesodApp
rheCatchHandlerExceptions :: forall child site.
RunHandlerEnv child site
-> forall a (m :: * -> *).
   MonadUnliftIO m =>
   m a -> (SomeException -> m a) -> m a
..} HandlerFor site c
handler YesodRequest
yreq = forall (m :: * -> *) a. (InternalState -> m a) -> ResourceT m a
withInternalState forall a b. (a -> b) -> a -> b
$ \InternalState
resState -> do
    -- Get the raw state and original contents
    (GHState
state, HandlerContents
contents0) <- forall c site.
ToTypedContent c =>
RunHandlerEnv site site
-> HandlerFor site c
-> YesodRequest
-> InternalState
-> IO (GHState, HandlerContents)
basicRunHandler RunHandlerEnv site site
rhe HandlerFor site c
handler YesodRequest
yreq InternalState
resState

    -- Evaluate the unfortunately-lazy session and headers,
    -- propagating exceptions into the contents
    (SessionMap
finalSession, HandlerContents
contents1) <- forall w.
(Monoid w, NFData w) =>
(forall a. IO a -> (SomeException -> IO a) -> IO a)
-> HandlerContents -> w -> IO (w, HandlerContents)
evalFallback forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheCatchHandlerExceptions HandlerContents
contents0 (GHState -> SessionMap
ghsSession GHState
state)
    ([Header]
headers, HandlerContents
contents2) <- forall w.
(Monoid w, NFData w) =>
(forall a. IO a -> (SomeException -> IO a) -> IO a)
-> HandlerContents -> w -> IO (w, HandlerContents)
evalFallback forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheCatchHandlerExceptions HandlerContents
contents1 (forall a. Endo a -> a -> a
appEndo (GHState -> Endo [Header]
ghsHeaders GHState
state) [])
    HandlerContents
contents3 <- (forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate HandlerContents
contents2) forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
`catchAny` (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ErrorResponse -> HandlerContents
HCError forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeException -> IO ErrorResponse
toErrorHandler)

    -- Convert the HandlerContents into the final YesodResponse
    (ErrorResponse -> IO YesodResponse)
-> SessionMap -> [Header] -> HandlerContents -> IO YesodResponse
handleContents
        (forall sub site.
RunHandlerEnv sub site
-> YesodRequest
-> InternalState
-> SessionMap
-> [Header]
-> ErrorResponse
-> IO YesodResponse
handleError RunHandlerEnv site site
rhe YesodRequest
yreq InternalState
resState SessionMap
finalSession [Header]
headers)
        SessionMap
finalSession
        [Header]
headers
        HandlerContents
contents3

safeEh :: (Loc -> LogSource -> LogLevel -> LogStr -> IO ())
       -> ErrorResponse
       -> YesodApp
safeEh :: (Loc -> LogSource -> LogLevel -> LogStr -> IO ())
-> ErrorResponse -> YesodApp
safeEh Loc -> LogSource -> LogLevel -> LogStr -> IO ()
log' ErrorResponse
er YesodRequest
req = do
    forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ Loc -> LogSource -> LogLevel -> LogStr -> IO ()
log' $(qLocation >>= liftLoc) LogSource
"yesod-core" LogLevel
LevelError
           forall a b. (a -> b) -> a -> b
$ forall msg. ToLogStr msg => msg -> LogStr
toLogStr forall a b. (a -> b) -> a -> b
$ [Char]
"Error handler errored out: " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> [Char]
show ErrorResponse
er
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain
        Status
H.status500
        []
        ByteString
typePlain
        (forall a. ToContent a => a -> Content
toContent (ByteString
"Internal Server Error" :: S.ByteString))
        (YesodRequest -> SessionMap
reqSession YesodRequest
req)

-- | Run a 'HandlerFor' completely outside of Yesod.  This
-- function comes with many caveats and you shouldn't use it
-- unless you fully understand what it's doing and how it works.
--
-- As of now, there's only one reason to use this function at
-- all: in order to run unit tests of functions inside 'HandlerFor'
-- but that aren't easily testable with a full HTTP request.
-- Even so, it's better to use @wai-test@ or @yesod-test@ instead
-- of using this function.
--
-- This function will create a fake HTTP request (both @wai@'s
-- 'Request' and @yesod@'s 'Request') and feed it to the
-- @HandlerFor@.  The only useful information the @HandlerFor@ may
-- get from the request is the session map, which you must supply
-- as argument to @runFakeHandler@.  All other fields contain
-- fake information, which means that they can be accessed but
-- won't have any useful information.  The response of the
-- @HandlerFor@ is completely ignored, including changes to the
-- session, cookies or headers.  We only return you the
-- @HandlerFor@'s return value.
runFakeHandler :: forall site m a . (Yesod site, MonadIO m) =>
                  SessionMap
               -> (site -> Logger)
               -> site
               -> HandlerFor site a
               -> m (Either ErrorResponse a)
runFakeHandler :: forall site (m :: * -> *) a.
(Yesod site, MonadIO m) =>
SessionMap
-> (site -> Logger)
-> site
-> HandlerFor site a
-> m (Either ErrorResponse a)
runFakeHandler SessionMap
fakeSessionMap site -> Logger
logger site
site HandlerFor site a
handler = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ do
  IORef (Either ErrorResponse a)
ret <- forall a. a -> IO (IORef a)
I.newIORef (forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ LogSource -> ErrorResponse
InternalError LogSource
"runFakeHandler: no result")
  LogSource
maxExpires <- IO LogSource
getCurrentMaxExpiresRFC1123
  let handler' :: HandlerFor site ()
handler' = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. IORef a -> a -> IO ()
I.writeIORef IORef (Either ErrorResponse a)
ret forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. b -> Either a b
Right forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< HandlerFor site a
handler
  let yapp :: YesodApp
yapp = forall c site.
ToTypedContent c =>
RunHandlerEnv site site -> HandlerFor site c -> YesodApp
runHandler
         RunHandlerEnv
            { rheRender :: Route site -> [(LogSource, LogSource)] -> LogSource
rheRender = forall y.
Yesod y =>
y -> LogSource -> Route y -> [(LogSource, LogSource)] -> LogSource
yesodRender site
site forall a b. (a -> b) -> a -> b
$ forall master. Yesod master => master -> Request -> LogSource
resolveApproot site
site Request
fakeWaiRequest
            , rheRoute :: Maybe (Route site)
rheRoute = forall a. Maybe a
Nothing
            , rheRouteToMaster :: Route site -> Route site
rheRouteToMaster = forall a. a -> a
id
            , rheChild :: site
rheChild = site
site
            , rheSite :: site
rheSite = site
site
            , rheUpload :: RequestBodyLength -> FileUpload
rheUpload = forall site. Yesod site => site -> RequestBodyLength -> FileUpload
fileUpload site
site
            , rheLog :: Loc -> LogSource -> LogLevel -> LogStr -> IO ()
rheLog = forall site.
Yesod site =>
site -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO ()
messageLoggerSource site
site forall a b. (a -> b) -> a -> b
$ site -> Logger
logger site
site
            , rheOnError :: ErrorResponse -> YesodApp
rheOnError = forall {m :: * -> *}.
MonadIO m =>
ErrorResponse -> YesodRequest -> m YesodResponse
errHandler
            , rheMaxExpires :: LogSource
rheMaxExpires = LogSource
maxExpires
            , rheCatchHandlerExceptions :: forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheCatchHandlerExceptions = forall site (m :: * -> *) a.
(Yesod site, MonadUnliftIO m) =>
site -> m a -> (SomeException -> m a) -> m a
catchHandlerExceptions site
site
            }
        HandlerFor site ()
handler'
      errHandler :: ErrorResponse -> YesodRequest -> m YesodResponse
errHandler ErrorResponse
err YesodRequest
req = do
          forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ forall a. IORef a -> a -> IO ()
I.writeIORef IORef (Either ErrorResponse a)
ret (forall a b. a -> Either a b
Left ErrorResponse
err)
          forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Status
-> [Header] -> ByteString -> Content -> SessionMap -> YesodResponse
YRPlain
                     Status
H.status500
                     []
                     ByteString
typePlain
                     (forall a. ToContent a => a -> Content
toContent (ByteString
"runFakeHandler: errHandler" :: S8.ByteString))
                     (YesodRequest -> SessionMap
reqSession YesodRequest
req)
      fakeWaiRequest :: Request
fakeWaiRequest = Request
          { requestMethod :: ByteString
requestMethod  = ByteString
"POST"
          , httpVersion :: HttpVersion
httpVersion    = HttpVersion
H.http11
          , rawPathInfo :: ByteString
rawPathInfo    = ByteString
"/runFakeHandler/pathInfo"
          , rawQueryString :: ByteString
rawQueryString = ByteString
""
          , requestHeaderHost :: Maybe ByteString
requestHeaderHost = forall a. Maybe a
Nothing
          , requestHeaders :: RequestHeaders
requestHeaders = []
          , isSecure :: Bool
isSecure       = Bool
False
          , remoteHost :: SockAddr
remoteHost     = forall a. HasCallStack => [Char] -> a
error [Char]
"runFakeHandler-remoteHost"
          , pathInfo :: [LogSource]
pathInfo       = [LogSource
"runFakeHandler", LogSource
"pathInfo"]
          , queryString :: Query
queryString    = []
          , requestBody :: IO ByteString
requestBody    = forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Monoid a => a
mempty
          , vault :: Vault
vault          = forall a. Monoid a => a
mempty
          , requestBodyLength :: RequestBodyLength
requestBodyLength = Word64 -> RequestBodyLength
KnownLength Word64
0
          , requestHeaderRange :: Maybe ByteString
requestHeaderRange = forall a. Maybe a
Nothing
          , requestHeaderReferer :: Maybe ByteString
requestHeaderReferer = forall a. Maybe a
Nothing
          , requestHeaderUserAgent :: Maybe ByteString
requestHeaderUserAgent = forall a. Maybe a
Nothing
          }
      fakeRequest :: YesodRequest
fakeRequest =
        YesodRequest
          { reqGetParams :: [(LogSource, LogSource)]
reqGetParams  = []
          , reqCookies :: [(LogSource, LogSource)]
reqCookies    = []
          , reqWaiRequest :: Request
reqWaiRequest = Request
fakeWaiRequest
          , reqLangs :: [LogSource]
reqLangs      = []
          , reqToken :: Maybe LogSource
reqToken      = forall a. a -> Maybe a
Just LogSource
"NaN" -- not a nonce =)
          , reqAccept :: [ByteString]
reqAccept     = []
          , reqSession :: SessionMap
reqSession    = SessionMap
fakeSessionMap
          }
  YesodResponse
_ <- forall (m :: * -> *) a. MonadUnliftIO m => ResourceT m a -> m a
runResourceT forall a b. (a -> b) -> a -> b
$ YesodApp
yapp YesodRequest
fakeRequest
  forall a. IORef a -> IO a
I.readIORef IORef (Either ErrorResponse a)
ret

yesodRunner :: forall res site . (ToTypedContent res, Yesod site)
            => HandlerFor site res
            -> YesodRunnerEnv site
            -> Maybe (Route site)
            -> Application
yesodRunner :: forall res site.
(ToTypedContent res, Yesod site) =>
HandlerFor site res
-> YesodRunnerEnv site -> Maybe (Route site) -> Application
yesodRunner HandlerFor site res
handler' YesodRunnerEnv {site
Maybe SessionBackend
IO Int
IO LogSource
Logger
yreGetMaxExpires :: forall site. YesodRunnerEnv site -> IO LogSource
yreGen :: forall site. YesodRunnerEnv site -> IO Int
yreSessionBackend :: forall site. YesodRunnerEnv site -> Maybe SessionBackend
yreSite :: forall site. YesodRunnerEnv site -> site
yreLogger :: forall site. YesodRunnerEnv site -> Logger
yreGetMaxExpires :: IO LogSource
yreGen :: IO Int
yreSessionBackend :: Maybe SessionBackend
yreSite :: site
yreLogger :: Logger
..} Maybe (Route site)
route Request
req Response -> IO ResponseReceived
sendResponse = do
  Maybe Word64
mmaxLen <- forall site.
Yesod site =>
site -> Maybe (Route site) -> IO (Maybe Word64)
maximumContentLengthIO site
yreSite Maybe (Route site)
route
  case (Maybe Word64
mmaxLen, Request -> RequestBodyLength
requestBodyLength Request
req) of
    (Just Word64
maxLen, KnownLength Word64
len) | Word64
maxLen forall a. Ord a => a -> a -> Bool
< Word64
len -> Response -> IO ResponseReceived
sendResponse (Word64 -> Word64 -> Response
tooLargeResponse Word64
maxLen Word64
len)
    (Maybe Word64, RequestBodyLength)
_ -> do
      let dontSaveSession :: p -> m [a]
dontSaveSession p
_ = forall (m :: * -> *) a. Monad m => a -> m a
return []
      (SessionMap
session, SessionMap -> IO [Header]
saveSession) <- forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$
          forall b a. b -> (a -> b) -> Maybe a -> b
maybe (forall (m :: * -> *) a. Monad m => a -> m a
return (forall k a. Map k a
Map.empty, forall {m :: * -> *} {p} {a}. Monad m => p -> m [a]
dontSaveSession)) (SessionBackend
-> Request -> IO (SessionMap, SessionMap -> IO [Header])
`sbLoadSession` Request
req) Maybe SessionBackend
yreSessionBackend
      LogSource
maxExpires <- IO LogSource
yreGetMaxExpires
      let mkYesodReq :: Either (IO YesodRequest) (IO Int -> IO YesodRequest)
mkYesodReq = Request
-> SessionMap
-> Bool
-> Maybe Word64
-> Either (IO YesodRequest) (IO Int -> IO YesodRequest)
parseWaiRequest Request
req SessionMap
session (forall a. Maybe a -> Bool
isJust Maybe SessionBackend
yreSessionBackend) Maybe Word64
mmaxLen
      let yreq :: IO YesodRequest
yreq =
              case Either (IO YesodRequest) (IO Int -> IO YesodRequest)
mkYesodReq of
                  Left IO YesodRequest
yreq' -> IO YesodRequest
yreq'
                  Right IO Int -> IO YesodRequest
needGen -> IO Int -> IO YesodRequest
needGen IO Int
yreGen
      let ra :: LogSource
ra = forall master. Yesod master => master -> Request -> LogSource
resolveApproot site
yreSite Request
req
      let log' :: Loc -> LogSource -> LogLevel -> LogStr -> IO ()
log' = forall site.
Yesod site =>
site -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO ()
messageLoggerSource site
yreSite Logger
yreLogger
          -- We set up two environments: the first one has a "safe" error handler
          -- which will never throw an exception. The second one uses the
          -- user-provided errorHandler function. If that errorHandler function
          -- errors out, it will use the safeEh below to recover.
          rheSafe :: RunHandlerEnv site site
rheSafe = RunHandlerEnv
              { rheRender :: Route site -> [(LogSource, LogSource)] -> LogSource
rheRender = forall y.
Yesod y =>
y -> LogSource -> Route y -> [(LogSource, LogSource)] -> LogSource
yesodRender site
yreSite LogSource
ra
              , rheRoute :: Maybe (Route site)
rheRoute = Maybe (Route site)
route
              , rheRouteToMaster :: Route site -> Route site
rheRouteToMaster = forall a. a -> a
id
              , rheChild :: site
rheChild = site
yreSite
              , rheSite :: site
rheSite = site
yreSite
              , rheUpload :: RequestBodyLength -> FileUpload
rheUpload = forall site. Yesod site => site -> RequestBodyLength -> FileUpload
fileUpload site
yreSite
              , rheLog :: Loc -> LogSource -> LogLevel -> LogStr -> IO ()
rheLog = Loc -> LogSource -> LogLevel -> LogStr -> IO ()
log'
              , rheOnError :: ErrorResponse -> YesodApp
rheOnError = (Loc -> LogSource -> LogLevel -> LogStr -> IO ())
-> ErrorResponse -> YesodApp
safeEh Loc -> LogSource -> LogLevel -> LogStr -> IO ()
log'
              , rheMaxExpires :: LogSource
rheMaxExpires = LogSource
maxExpires
              , rheCatchHandlerExceptions :: forall a (m :: * -> *).
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
rheCatchHandlerExceptions = forall site (m :: * -> *) a.
(Yesod site, MonadUnliftIO m) =>
site -> m a -> (SomeException -> m a) -> m a
catchHandlerExceptions site
yreSite
              }
          rhe :: RunHandlerEnv site site
rhe = RunHandlerEnv site site
rheSafe
              { rheOnError :: ErrorResponse -> YesodApp
rheOnError = forall c site.
ToTypedContent c =>
RunHandlerEnv site site -> HandlerFor site c -> YesodApp
runHandler RunHandlerEnv site site
rheSafe forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall site.
Yesod site =>
ErrorResponse -> HandlerFor site TypedContent
errorHandler
              }

      forall site a.
Yesod site =>
site -> Maybe (Route site) -> (InternalState -> IO a) -> IO a
yesodWithInternalState site
yreSite Maybe (Route site)
route forall a b. (a -> b) -> a -> b
$ \InternalState
is -> do
          YesodRequest
yreq' <- IO YesodRequest
yreq
          YesodResponse
yar <- forall (m :: * -> *) a. ResourceT m a -> InternalState -> m a
runInternalState (forall c site.
ToTypedContent c =>
RunHandlerEnv site site -> HandlerFor site c -> YesodApp
runHandler RunHandlerEnv site site
rhe HandlerFor site res
handler YesodRequest
yreq') InternalState
is
          YesodResponse
-> (SessionMap -> IO [Header])
-> YesodRequest
-> Request
-> InternalState
-> (Response -> IO ResponseReceived)
-> IO ResponseReceived
yarToResponse YesodResponse
yar SessionMap -> IO [Header]
saveSession YesodRequest
yreq' Request
req InternalState
is Response -> IO ResponseReceived
sendResponse
  where
    mmaxLen :: Maybe Word64
mmaxLen = forall site.
Yesod site =>
site -> Maybe (Route site) -> Maybe Word64
maximumContentLength site
yreSite Maybe (Route site)
route
    handler :: HandlerFor site res
handler = forall site res.
(Yesod site, ToTypedContent res) =>
HandlerFor site res -> HandlerFor site res
yesodMiddleware HandlerFor site res
handler'

yesodRender :: Yesod y
            => y
            -> ResolvedApproot
            -> Route y
            -> [(Text, Text)] -- ^ url query string
            -> Text
yesodRender :: forall y.
Yesod y =>
y -> LogSource -> Route y -> [(LogSource, LogSource)] -> LogSource
yesodRender y
y LogSource
ar Route y
url [(LogSource, LogSource)]
params =
    OnDecodeError -> ByteString -> LogSource
decodeUtf8With OnDecodeError
lenientDecode forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString
BL.toStrict forall a b. (a -> b) -> a -> b
$ Builder -> ByteString
toLazyByteString forall a b. (a -> b) -> a -> b
$
    forall a. a -> Maybe a -> a
fromMaybe
        (forall site.
Yesod site =>
site
-> LogSource -> [LogSource] -> [(LogSource, LogSource)] -> Builder
joinPath y
y LogSource
ar [LogSource]
ps
          forall a b. (a -> b) -> a -> b
$ [(LogSource, LogSource)]
params forall a. [a] -> [a] -> [a]
++ [(LogSource, LogSource)]
params')
        (forall site.
Yesod site =>
site -> Route site -> [(LogSource, LogSource)] -> Maybe Builder
urlParamRenderOverride y
y Route y
url [(LogSource, LogSource)]
params)
  where
    ([LogSource]
ps, [(LogSource, LogSource)]
params') = forall a.
RenderRoute a =>
Route a -> ([LogSource], [(LogSource, LogSource)])
renderRoute Route y
url

resolveApproot :: Yesod master => master -> Request -> ResolvedApproot
resolveApproot :: forall master. Yesod master => master -> Request -> LogSource
resolveApproot master
master Request
req =
    case forall site. Yesod site => Approot site
approot of
        Approot master
ApprootRelative -> LogSource
""
        ApprootStatic LogSource
t -> LogSource
t
        ApprootMaster master -> LogSource
f -> master -> LogSource
f master
master
        ApprootRequest master -> Request -> LogSource
f -> master -> Request -> LogSource
f master
master Request
req