Understanding a Request

You can often times get away with using Yesod for quite a while without needing to understand its internal workings. However, such an understanding is often times advantageous. This chapter will walk you through the request handling process for a fairly typical Yesod application. Note that a fair amount of this discussion involves code changes in Yesod 1.2. Most of the concepts are the same in previous versions, though the data types involved were a bit messier.

Yesod’s usage of Template Haskell to bypass boilerplate code can make it a bit difficult to understand this process sometimes. If beyond the information in this chapter you wish to further analyze things, it can be useful to view GHC’s generated code using -ddump-splices.

A lot of this information was originally published as a blog series on the 1.2 release. You can see the blog posts at:

Handlers

When trying to understand Yesod request handling, we need to look at two components: how a request is dispatched to the appropriate handler code, and how handler functions are processed. We’ll start off with the latter, and then circle back to understanding the dispatch process itself.

Layers

Yesod builds itself on top of WAI, which provides a protocol for web servers (or, more generally, handlers) and applications to communicate with each other. This is expressed through two datatypes: Request and Response. Then, an Application is defined as type Application = Request -> ResourceT IO Response. A WAI handler will take an application and run it.

Request and Response are both very low-level, trying to represent the HTTP protocol without too much embellishment. This keeps WAI as a generic tool, but also leaves out a lot of the information we need in order to implement a web framework. For example, WAI will provide us with the raw data for all request headers. But Yesod needs to parse that to get cookie information, and then parse the cookies in order to extract session information.

To deal with this dichotomy, Yesod introduces two new data types: YesodRequest and YesodResponse. YesodRequest contains a WAI Request, and also adds in such request information as cookies and session variables, and on the response side can either be a standard WAI Response, or be a higher-level representation of such a response including such things as updated session information and extra response headers. To parallel WAI’s Application, we have type YesodApp = YesodRequest -> ResourceT IO YesodResponse.

But as a Yesod user, you never really see YesodApp. There’s another layer on top of that which you are used to dealing with: Handler. When you write handler functions, you need to have access to three different things:

  • The YesodRequest value for the current request.

  • Some basic environment information, like how to log messages or handle error conditions. This is provided by the datatype RunHandlerEnv.

  • A mutable variable to keep track of updateable information, such as the headers to be returned and the user session state. This is called GHState.

I know that’s not a great name, but it’s there for historical reasons.

So when you’re writing a handler function, you’re essentially just writing in a Reader monad that has access to all of this information. The runHandler function will turn a Handler into a YesodApp. yesodRunner takes this a step further and converts all the way to a WAI Application.

Content

Our example above, and many others you’ve already seen, give a handler with a type of Handler Html. We’ve just described what the Handler means, but how does Yesod know how to deal with Html? The answer lies in the ToTypedContent typeclass. The relevants bit of code are:

  1. data Content = ContentBuilder !BBuilder.Builder !(Maybe Int) -- ^ The content and optional content length.
  2. | ContentSource !(Source (ResourceT IO) (Flush BBuilder.Builder))
  3. | ContentFile !FilePath !(Maybe FilePart)
  4. | ContentDontEvaluate !Content
  5. data TypedContent = TypedContent !ContentType !Content
  6. class ToContent a where
  7. toContent :: a -> Content
  8. class ToContent a => ToTypedContent a where
  9. toTypedContent :: a -> TypedContent

The Content datatype represents the different ways you can provide a response body. The first three mirror WAI’s representation directly. The fourth (ContentDontEvaluate) is used to indicate to Yesod whether response bodies should be fully evaluated before being returned to users. The advantage to fully evaluating is that we can provide meaningful error messages if an exception is thrown from pure code. The downside is possibly increased time and memory usage.

In any event, Yesod knows how to turn a Content into a response body. The ToContent typeclass provides a way to allow many different datatypes to be converted into response bodies. Many commonly used types are already instances of ToContent, including strict and lazy ByteString and Text, and of course Html.

TypedContent adds an extra piece of information: the content type of the value. As you might expect, there are ToTypedContent instances for a number of common datatypes, including HTML, JSON, and plain text.

  1. instance ToTypedContent J.Value where
  2. toTypedContent v = TypedContent typeJson (toContent v)
  3. instance ToTypedContent Html where
  4. toTypedContent h = TypedContent typeHtml (toContent h)
  5. instance ToTypedContent T.Text where
  6. toTypedContent t = TypedContent typePlain (toContent t)

Putting this all together: a Handler is able to return any value which is an instance of ToTypedContent, and Yesod will handle turning it into an appropriate representation and setting the Content-Type response header.

Short-circuit responses

One other oddity is how short-circuiting works. For example, you can call redirect in the middle of a handler function, and the rest of the function will not be called. The mechanism we use is standard Haskell exceptions. Calling redirect just throws an exception of type HandlerContents. The runHandler function will catch any exceptions thrown and produce an appropriate response. For HandlerContents, each constructor gives a clear action to perform, be it redirecting or sending a file. For all other exception types, an error message is displayed to the user.

Dispatch

Dispatch is the act of taking an incoming request and generating an appropriate response. We have a few different constraints regarding how we want to handle dispatch:

  • Dispatch based on path segments (or pieces).

  • Optionally dispatch on request method.

  • Support subsites: packaged collections of functionality providing multiple routes under a specific URL prefix.

  • Support using WAI applications as subsites, while introducing as little runtime overhead to the process as possible. In particular, we want to avoid performing any unnecessary parsing to generate a YesodRequest if it won’t be used.

The lowest common denominator for this would be to simply use a WAI Application. However, this doesn’t provide quite enough information: we need access to the foundation datatype, the logger, and for subsites how a subsite route is converted to a parent site route. To address this, we have two helper data types (YesodRunnerEnv and YesodSubRunnerEnv) providing this extra information for normal sites and subsites.

With those types, dispatch now becomes a relatively simple matter: give me an environment and a request, and I’ll give you a response. This is represented by the typeclasses YesodDispatch and YesodSubDispatch:

  1. class Yesod site => YesodDispatch site where
  2. yesodDispatch :: YesodRunnerEnv site -> W.Application
  3. class YesodSubDispatch sub m where
  4. yesodSubDispatch :: YesodSubRunnerEnv sub (HandlerSite m) m
  5. -> W.Application

We’ll see a bit later how YesodSubDispatch is used. Let’s first understand how YesodDispatch comes into play,__

toWaiApp, toWaiAppPlain, and warp

Let’s assume for the moment that you have a datatype which is an instance of YesodDispatch. You’ll want to now actually run this thing somehow. To do this, we need to convert it into a WAI application and pass it to some kind of a WAI handler/server. To start this journey, we use toWaiAppPlain. It performs any appwide initialization necessary. At the time of writing, this means allocating a logger and setting up the session backend, but more functionality may be added in the future. Using this data, we can now create a YesodRunnerEnv. And when that value is passed to yesodDispatch, we get a WAI application.

We’re almost done. The final remaining modification is path segment cleanup. The Yesod typeclass includes a member function named cleanPath which can be used to create canonical URLs. For example, the default implementation would remove double slashes and redirect a user from /foo//bar to /foo/bar. toWaiAppPlain adds in some pre-processing to the normal WAI request by analyzing the requested path and performing cleanup/redirect as necessary.

At this point, we have a fully functional WAI application. There are two other helper functions included. toWaiApp wraps toWaiAppPlain and additionally includes some commonly used WAI middlewares, including request logging and GZIP compression. (Please see the Haddocks for an up-to-date list.) We finally have the warp function which, as you might guess, runs your application with Warp.

There’s also the warpEnv function, which reads the port number information from the PORT environment variable. This is used for interacting with certain tools, including the Keter deployment manager and the FP Complete School of Haskell.

Generated code

The last remaining black box is the Template Haskell generated code. This generated code is responsible for handling some of the tedious, error-prone pieces of your site. If you want to, you can write these all by hand instead. We’ll demonstrate what that translation would look like, and in the process elucidate how YesodDispatch and YesodSubDispatch work. Let’s start with a fairly typical Yesod application.

  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE QuasiQuotes #-}
  3. {-# LANGUAGE TemplateHaskell #-}
  4. {-# LANGUAGE TypeFamilies #-}
  5. import qualified Data.ByteString.Lazy.Char8 as L8
  6. import Network.HTTP.Types (status200)
  7. import Network.Wai (pathInfo, rawPathInfo,
  8. requestMethod, responseLBS)
  9. import Yesod
  10. data App = App
  11. mkYesod "App" [parseRoutes|
  12. /only-get OnlyGetR GET
  13. /any-method AnyMethodR
  14. /has-param/#Int HasParamR GET
  15. /my-subsite MySubsiteR WaiSubsite getMySubsite
  16. |]
  17. instance Yesod App
  18. getOnlyGetR :: Handler Html
  19. getOnlyGetR = defaultLayout
  20. [whamlet|
  21. <p>Accessed via GET method
  22. <form method=post action=@{AnyMethodR}>
  23. <button>POST to /any-method
  24. |]
  25. handleAnyMethodR :: Handler Html
  26. handleAnyMethodR = do
  27. req <- waiRequest
  28. defaultLayout
  29. [whamlet|
  30. <p>In any-method, method == #{show $ requestMethod req}
  31. |]
  32. getHasParamR :: Int -> Handler String
  33. getHasParamR i = return $ show i
  34. getMySubsite :: App -> WaiSubsite
  35. getMySubsite _ =
  36. WaiSubsite app
  37. where
  38. app req = return $ responseLBS
  39. status200
  40. [("Content-Type", "text/plain")]
  41. $ L8.pack $ concat
  42. [ "pathInfo == "
  43. , show $ pathInfo req
  44. , ", rawPathInfo == "
  45. , show $ rawPathInfo req
  46. ]
  47. main :: IO ()
  48. main = warp 3000 App

For completeness we’ve provided a full listing, but let’s focus on just the Template Haskell portion:

  1. mkYesod "App" [parseRoutes|
  2. /only-get OnlyGetR GET
  3. /any-method AnyMethodR
  4. /has-param/#Int HasParamR GET
  5. /my-subsite MySubsiteR WaiSubsite getMySubsite
  6. |]

While this generates a few pieces of code, we only need to replicate three components to make our site work. Let’s start with the simplest: the Handler type synonym:

  1. type Handler = HandlerT App IO

Next is the type-safe URL and its rendering function. The rendering function is allowed to generate both path segments and query string parameters. Standard Yesod sites never generate query-string parameters, but it is technically possible. And in the case of subsites, this often does happen. Notice how we handle the qs parameter for the MySubsiteR case:

  1. instance RenderRoute App where
  2. data Route App = OnlyGetR
  3. | AnyMethodR
  4. | HasParamR Int
  5. | MySubsiteR (Route WaiSubsite)
  6. deriving (Show, Read, Eq)
  7. renderRoute OnlyGetR = (["only-get"], [])
  8. renderRoute AnyMethodR = (["any-method"], [])
  9. renderRoute (HasParamR i) = (["has-param", toPathPiece i], [])
  10. renderRoute (MySubsiteR subRoute) =
  11. let (ps, qs) = renderRoute subRoute
  12. in ("my-subsite" : ps, qs)

You can see that there’s a fairly simple mapping from the higher-level route syntax and the RenderRoute instance. Each route becomes a constructor, each URL parameter becomes an argument to its constructor, we embed a route for the subsite, and use toPathPiece to render parameters to text.

The final component is the YesodDispatch instance. Let’s look at this in a few pieces.

  1. instance YesodDispatch App where
  2. yesodDispatch env req =
  3. case pathInfo req of
  4. ["only-get"] ->
  5. case requestMethod req of
  6. "GET" -> yesodRunner
  7. getOnlyGetR
  8. env
  9. (Just OnlyGetR)
  10. req
  11. _ -> yesodRunner
  12. (badMethod >> return ())
  13. env
  14. (Just OnlyGetR)
  15. req

As described above, yesodDispatch is handed both an environment and a WAI Request value. We can now perform dispatch based on the requested path, or in WAI terms, the pathInfo. Referring back to our original high-level route syntax, we can see that our first route is going to be the single piece only-get, which we pattern match for.

In reality, Yesod generates a much more efficient data structure to perform routing. We’ve used simple pattern matching here so as not to obscure the point. For more information, please see the Yesod.Routes.Dispatch.

Once that match has succeeded, we additionally pattern match on the request method; if it’s GET, we use the handler function getOnlyGetR. Otherwise, we want to return a 405 bad method response, and therefore use the badMethod handler. At this point, we’ve come full circle to our original handler discussion. You can see that we’re using yesodRunner to execute our handler function. As a reminder, this will take our environment and WAI Request, convert it to a YesodRequest, constructor a RunHandlerEnv, hand that to the handler function, and then convert the resulting YesodResponse into a WAI Response.

Wonderful; one down, three to go. The next one is even easier.

  1. ["any-method"] ->
  2. yesodRunner handleAnyMethodR env (Just AnyMethodR) req

Unlike OnlyGetR, AnyMethodR will work for any request method, so we don’t need to perform any further pattern matching.

  1. ["has-param", t] | Just i <- fromPathPiece t ->
  2. case requestMethod req of
  3. "GET" -> yesodRunner
  4. (getHasParamR i)
  5. env
  6. (Just $ HasParamR i)
  7. req
  8. _ -> yesodRunner
  9. (badMethod >> return ())
  10. env
  11. (Just $ HasParamR i)
  12. req

We add in one extra complication here: a dynamic parameter. While we used toPathPiece to render to a textual value above, we now use fromPathPiece to perform the parsing. Assuming the parse succeeds, we then follow a very similar dispatch system as was used for OnlyGetR. The prime difference is that our parameter needs to be passed to both the handler function and the route data constructor.

Next we’ll look at the subsite, which is quite different.

  1. ("my-subsite":rest) -> yesodSubDispatch
  2. YesodSubRunnerEnv
  3. { ysreGetSub = getMySubsite
  4. , ysreParentRunner = yesodRunner
  5. , ysreToParentRoute = MySubsiteR
  6. , ysreParentEnv = env
  7. }
  8. req { pathInfo = rest }

Unlike the other pattern matches, here we just look to see if our pattern prefix matches. Any route beginning with /my-subsite should be passed off to the subsite for processing. This is where we finally get to use yesodSubDispatch. This function closely mirrors yesodDispatch. We need to construct a new environment to be passed to it. Let’s discuss the four records:

  • ysreGetSub demonstrates how to get the subsite foundation type from the master site. We provide getMySubsite, which is the function we provided in the high-level route syntax.

  • ysreParentRunner provides a means of running a handler function. It may seem a bit boring to just provide yesodRunner, but by having a separate parameter we allow the construction of deeply nested subsites, which will wrap and unwrap many layers of interleaving subsites. (This is a more advanced concept which we won’t be covering in this chapter.)

  • ysreToParentRoute will convert a route for the subsite into a route for the parent site. This is the purpose of the MySubsiteR constructor. This allows subsites to use functions such as getRouteToParent.

  • ysreParentEnv simply passes on the initial environment, which contains a number of things the subsite may need (such as logger).

The other interesting thing is how we modify the pathInfo. This allows subsites to continue dispatching from where the parent site left off. To demonstrate how this works, see some screenshots of various requests in the following figure.

Path info in subsite

Understanding a Request - 图1

And finally, not all requests will be valid routes. For those cases, we just want to respond with a 404 not found.

  1. _ -> yesodRunner (notFound >> return ()) env Nothing req

Complete code

Following is the full code for the non-Template Haskell approach.

  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE QuasiQuotes #-}
  3. {-# LANGUAGE TemplateHaskell #-}
  4. {-# LANGUAGE TypeFamilies #-}
  5. import qualified Data.ByteString.Lazy.Char8 as L8
  6. import Network.HTTP.Types (status200)
  7. import Network.Wai (pathInfo, rawPathInfo,
  8. requestMethod, responseLBS)
  9. import Yesod
  10. import Yesod.Core.Types (YesodSubRunnerEnv (..))
  11. data App = App
  12. instance RenderRoute App where
  13. data Route App = OnlyGetR
  14. | AnyMethodR
  15. | HasParamR Int
  16. | MySubsiteR (Route WaiSubsite)
  17. deriving (Show, Read, Eq)
  18. renderRoute OnlyGetR = (["only-get"], [])
  19. renderRoute AnyMethodR = (["any-method"], [])
  20. renderRoute (HasParamR i) = (["has-param", toPathPiece i], [])
  21. renderRoute (MySubsiteR subRoute) =
  22. let (ps, qs) = renderRoute subRoute
  23. in ("my-subsite" : ps, qs)
  24. type Handler = HandlerT App IO
  25. instance Yesod App
  26. instance YesodDispatch App where
  27. yesodDispatch env req =
  28. case pathInfo req of
  29. ["only-get"] ->
  30. case requestMethod req of
  31. "GET" -> yesodRunner
  32. getOnlyGetR
  33. env
  34. (Just OnlyGetR)
  35. req
  36. _ -> yesodRunner
  37. (badMethod >> return ())
  38. env
  39. (Just OnlyGetR)
  40. req
  41. ["any-method"] ->
  42. yesodRunner handleAnyMethodR env (Just AnyMethodR) req
  43. ["has-param", t] | Just i <- fromPathPiece t ->
  44. case requestMethod req of
  45. "GET" -> yesodRunner
  46. (getHasParamR i)
  47. env
  48. (Just $ HasParamR i)
  49. req
  50. _ -> yesodRunner
  51. (badMethod >> return ())
  52. env
  53. (Just $ HasParamR i)
  54. req
  55. ("my-subsite":rest) -> yesodSubDispatch
  56. YesodSubRunnerEnv
  57. { ysreGetSub = getMySubsite
  58. , ysreParentRunner = yesodRunner
  59. , ysreToParentRoute = MySubsiteR
  60. , ysreParentEnv = env
  61. }
  62. req { pathInfo = rest }
  63. _ -> yesodRunner (notFound >> return ()) env Nothing req
  64. getOnlyGetR :: Handler Html
  65. getOnlyGetR = defaultLayout
  66. [whamlet|
  67. <p>Accessed via GET method
  68. <form method=post action=@{AnyMethodR}>
  69. <button>POST to /any-method
  70. |]
  71. handleAnyMethodR :: Handler Html
  72. handleAnyMethodR = do
  73. req <- waiRequest
  74. defaultLayout
  75. [whamlet|
  76. <p>In any-method, method == #{show $ requestMethod req}
  77. |]
  78. getHasParamR :: Int -> Handler String
  79. getHasParamR i = return $ show i
  80. getMySubsite :: App -> WaiSubsite
  81. getMySubsite _ =
  82. WaiSubsite app
  83. where
  84. app req = return $ responseLBS
  85. status200
  86. [("Content-Type", "text/plain")]
  87. $ L8.pack $ concat
  88. [ "pathInfo == "
  89. , show $ pathInfo req
  90. , ", rawPathInfo == "
  91. , show $ rawPathInfo req
  92. ]
  93. main :: IO ()
  94. main = warp 3000 App

Conclusion

Yesod abstracts away quite a bit of the plumbing from you as a developer. Most of this is boilerplate code that you’ll be happy to ignore. But it can be empowering to understand exactly what’s going on under the surface. At this point, you should hopefully be able- with help from the Haddocks- to write a site without any of the autogenerated Template Haskell code. Not that I’d recommend it; I think using the generated code is easier and safer.

One particular advantage of understanding this material is seeing where Yesod sits in the world of WAI. This makes it easier to see how Yesod will interact with WAI middleware, or how to include code from other WAI framework in a Yesod application (or vice-versa!).