Repository: phoenixframework/phoenix
Pull request #5457 (2023-05-09 20:48:24)

Add guide: Writing a Channels Client

nathanl: @dsrees @Mazyod @J0 @the-mikedavis @alfredbaudisch - if any of you client authors see ways this guide can be improved, please chime in! (If not interested, feel free to unsubscribe and sorry for bugging you.)

Patch:
diff --git a/guides/contexts.md b/guides/contexts.md
index a7c6a8064..7ce19df4e 100644
--- a/guides/contexts.md
+++ b/guides/contexts.md
@@ -696,7 +696,7 @@ Now that our cart is associated to the items we place in it, let's set up the ca
   end
 ```
 
-First, we replaced the `cart_id` field with a standard `belongs_to` pointing at our `ShoppingCart.Cart` schema. Next, we replaced our `product_id` field by adding our first cross-context data dependency with a `belongs_to` for the `Catalog.Product` schema. Here, we intentionally coupled the data boundaries because it provides exactly what we need. An isolated context API with the bare minimum knowledge necessary to reference a product in our system. Next, we added a new validation to our changeset. With `validate_number/3`, we ensure any quantity provided by user input is between 0 and 100.
+First, we replaced the `cart_id` field with a standard `belongs_to` pointing at our `ShoppingCart.Cart` schema. Next, we replaced our `product_id` field by adding our first cross-context data dependency with a `belongs_to` for the `Catalog.Product` schema. Here, we intentionally coupled the data boundaries because it provides exactly what we need: an isolated context API with the bare minimum knowledge necessary to reference a product in our system. Next, we added a new validation to our changeset. With `validate_number/3`, we ensure any quantity provided by user input is between 0 and 100.
 
 With our schemas in place, we can start integrating the new data structures and `ShoppingCart` context APIs into our web-facing features.
 
@@ -711,7 +711,7 @@ We won't focus on a real user authentication system at this point, but by the ti
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.LayoutView, :root}
+    plug :put_root_layout, html: {HelloWeb.LayoutView, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
 +   plug :fetch_current_user
@@ -1040,9 +1040,9 @@ Let's head back to the browser and try it out. Add a few products to your cart,
 
 ## Adding an Orders context
 
-With our `Catalog` and `ShoppingCart` contexts, we're seeing first-hand how our well-considered modules and function names are yielding clear and maintainable code. Our last order of business is to allow the user to initiate the checkout process. We won't go as far as integrating payment processing or order fulfillment, but we'll get you started in that direction. Like before, we need to decide where code for completing an order should live. Is it part of the catalog? Clearly not, but what about the shopping cart? Shopping carts are related to orders – after all the user has to add items in order to purchase any products, but should the order checkout process be grouped here?
+With our `Catalog` and `ShoppingCart` contexts, we're seeing first-hand how our well-considered modules and function names are yielding clear and maintainable code. Our last order of business is to allow the user to initiate the checkout process. We won't go as far as integrating payment processing or order fulfillment, but we'll get you started in that direction. Like before, we need to decide where code for completing an order should live. Is it part of the catalog? Clearly not, but what about the shopping cart? Shopping carts are related to orders – after all, the user has to add items in order to purchase any products – but should the order checkout process be grouped here?
 
-If we stop and consider the order process, we'll see that orders involve related, but distinctly different data from the cart contents. Also, business rules around the checkout process are much different than carting. For example, we may allow a user to add a back-ordered item to their cart, but we could not allow an order with no inventory to be completed. Additionally, we need to capture point-in-time product information when an order is completed, such as the price of the items *at payment transaction time*. This is essential because a product price may change in the future, but the line items in our order must always record and display what we charged at time of purchase. For these reasons, we can start to see ordering can reasonably stand on its own with its own data concerns and business rules.
+If we stop and consider the order process, we'll see that orders involve related, but distinctly different data from the cart contents. Also, business rules around the checkout process are much different than carting. For example, we may allow a user to add a back-ordered item to their cart, but we could not allow an order with no inventory to be completed. Additionally, we need to capture point-in-time product information when an order is completed, such as the price of the items *at payment transaction time*. This is essential because a product price may change in the future, but the line items in our order must always record and display what we charged at time of purchase. For these reasons, we can start to see that ordering can stand on its own with its own data concerns and business rules.
 
 Naming wise, `Orders` clearly defines the scope of our context, so let's get started by again taking advantage of the context generators. Run the following command in your console:
 
@@ -1063,7 +1063,7 @@ Remember to update your repository by running migrations:
     $ mix ecto.migrate
 ```
 
-We generated a `Orders` context. We added a `user_uuid` field to associate our placeholder current user to an order, along with a `total_price` column. With our starting point in place, let's open up the newly created migration in `priv/repo/migrations/*_create_orders.exs` and make the following changes:
+We generated an `Orders` context. We added a `user_uuid` field to associate our placeholder current user to an order, along with a `total_price` column. With our starting point in place, let's open up the newly created migration in `priv/repo/migrations/*_create_orders.exs` and make the following changes:
 
 ```elixir
   def change do
@@ -1220,7 +1220,7 @@ end
 
 We wrote the `create` action to call an as-yet-implemented `Orders.complete_order/1` function. Our code is technically "creating" an order, but it's important to step back and consider the naming of your interfaces. The act of *completing* an order is extremely important in our system. Money changes hands in a transaction, physical goods could be automatically shipped, etc. Such an operation deserves a better, more obvious function name, such as `complete_order`. If the order is completed successfully we redirect to the show page, otherwise a flash error is shown as we redirect back to the cart page.
 
-Here is also a good opportunity to highlight that contexts can naturally work with data defined by other contexts too. This will be specially common with data that is used throughout the application, such as the cart here (but it can also be the current user or the current project, and so forth, depending on your project).
+Here is also a good opportunity to highlight that contexts can naturally work with data defined by other contexts too. This will be especially common with data that is used throughout the application, such as the cart here (but it can also be the current user or the current project, and so forth, depending on your project).
 
 Now we can implement our `Orders.complete_order/1` function. To complete an order, our job will require a few operations:
 
@@ -1262,7 +1262,7 @@ From our requirements alone, we can start to see why a generic `create_order` fu
   end
 ```
 
-We started by mapping the `%ShoppingCart.CartItem{}`'s in our shopping cart into a map of order line items structs. The job of the order line item record is to capture the price of the product *at payment transaction time*, so we reference the product's price here. Next, we create a bare order changeset with `Ecto.Changeset.change/2` and associate our user UUID, set our total price calculation, and place our order line items in the changeset. With a fresh order changeset ready to be inserted, we can again make use of `Ecto.Multi` to execute our operations in a database transaction. We start by inserting the order, followed by a `run` operation. The `Ecto.Multi.run/3` function allows us to run any code in the function which must either succeed with `{:ok, result}` or error, which halts and rolls back the transaction. Here, we simply can call into our shopping cart context and ask it to prune all items in a cart. Running the transaction will execute the multi as before and we return the result to the caller.
+We started by mapping the `%ShoppingCart.CartItem{}`'s in our shopping cart into a map of order line items structs. The job of the order line item record is to capture the price of the product *at payment transaction time*, so we reference the product's price here. Next, we create a bare order changeset with `Ecto.Changeset.change/2` and associate our user UUID, set our total price calculation, and place our order line items in the changeset. With a fresh order changeset ready to be inserted, we can again make use of `Ecto.Multi` to execute our operations in a database transaction. We start by inserting the order, followed by a `run` operation. The `Ecto.Multi.run/3` function allows us to run any code in the function which must either succeed with `{:ok, result}` or error, which halts and rolls back the transaction. Here, we simply call into our shopping cart context and ask it to prune all items in a cart. Running the transaction will execute the multi as before and we return the result to the caller.
 
 To close out our order completion, we need to implement the `ShoppingCart.prune_cart_items/1` function in `lib/hello/shopping_cart.ex`:
 
@@ -1356,6 +1356,6 @@ As we explored the context API, you might have wondered:
 
 Although Changesets are part of Ecto, they are not tied to the database, and they can be used to map data from and to any source, which makes it a general and useful data structure for tracking field changes, perform validations, and generate error messages.
 
-For those reasons, `%Ecto.Changeset{}` is a good choice to model the data changes between your contexts and your web layer. Regardless if you are talking to an API or the database.
+For those reasons, `%Ecto.Changeset{}` is a good choice to model the data changes between your contexts and your web layer - regardless if you are talking to an API or the database.
 
 Finally, note that your controllers and views are not hardcoded to work exclusively with Ecto either. Instead, Phoenix defines protocols such as `Phoenix.Param` and `Phoenix.HTML.FormData`, which allow any library to extend how Phoenix generates URL parameters or renders forms. Conveniently for us, the `phoenix_ecto` project implements those protocols, but you could as well bring your own data structures and implement them yourself.
diff --git a/guides/controllers.md b/guides/controllers.md
index 85df2c9a9..6ca334642 100644
--- a/guides/controllers.md
+++ b/guides/controllers.md
@@ -216,7 +216,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html", "json"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.LayoutView, :root}
+    plug :put_root_layout, html: {HelloWeb.LayoutView, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end
@@ -380,7 +380,7 @@ The flash functionality is handy when mixed with redirects. Perhaps you want to
   def home(conn, _params) do
     conn
     |> put_flash(:error, "Let's pretend we have an error.")
-    |> redirect(to: ~p"/redirect_test"))
+    |> redirect(to: ~p"/redirect_test")
   end
 ```
 
diff --git a/guides/howto/writing_a_channels_client.md b/guides/howto/writing_a_channels_client.md
new file mode 100644
index 000000000..32a1f5348
--- /dev/null
+++ b/guides/howto/writing_a_channels_client.md
@@ -0,0 +1,81 @@
+# Writing a Channels Client
+
+Client libraries for Phoenix Channels already exist in [several languages](https://hexdocs.pm/phoenix/channels.html#client-libraries), but if you want to write your own, this guide should get you started.
+It may also be useful as a guide for manual testing with a WebSocket client.
+
+## Overview
+
+Because WebSockets are bidirectional, messages can flow in either direction at any time.
+For this reason, clients typically use callbacks to handle incoming messages whenever they come.
+
+A client must join at least one topic to begin sending and receiving messages, and may join any number of topics using the same connection.
+
+## Connecting
+
+To establish a WebSocket connection to Phoenix Channels, first make note of the `socket` declaration in the application's `Endpoint` module.
+For example, if you see: `socket "/mobile", MyAppWeb.MobileSocket`, the path for the initial HTTP request is:
+
+    [host]:[port]/mobile/websocket?vsn=2.0.0
+
+Passing `&vsn=2.0.0` specifies `Phoenix.Socket.V2.JSONSerializer`, which is built into Phoenix, and which expects and returns messages in the form of lists.
+
+You also need to include [the standard header fields for upgrading an HTTP request to a WebSocket connection](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) or use an HTTP library that handles this for you; in Elixir, [mint_web_socket](https://hex.pm/packages/mint_web_socket) is an example.
+
+Other parameters or headers may be expected or required by the specific `connect/3` function in the application's socket module (in the example above, `MyAppWeb.MobileSocket.connect/3`).
+
+## Message Format
+
+The message format is determined by the serializer configured for the application.
+For these examples, `Phoenix.Socket.V2.JSONSerializer` is assumed.
+
+The general format for messages a client sends to a Phoenix Channel is as follows:
+
+```
+[join_reference, message_reference, topic_name, event_name, payload]
+```
+
+- The `message_reference` is chosen by the client and should be a unique value. The server includes it in its reply so that the client knows which message the reply is for.
+- The `join_reference` is also chosen by the client and should also be a unique value. It only needs to be sent for a `"phx_join"` event; for other messages it can be `null`. It is used as a message reference for `push` messages from the server, meaning those that are not replies to a specific client message. For example, imagine something like "a new user just joined the chat room".
+- The `topic_name` must be a known topic for the socket endpoint, and a client must join that topic before sending any messages on it.
+- The `event_name` must match the first argument of a `handle_in` function on the server channel module.
+- The `payload` should be a map and is passed as the second argument to that `handle_in` function.
+
+There are three events that are understood by every Phoenix application.
+
+First, `phx_join` is used join a channel. For example, to join the `miami:weather` channel:
+
+```json
+["0", "0", "miami:weather", "phx_join", {"some": "param"}]
+```
+
+Second, `phx_leave` is used to leave a channel. For example, to leave the `miami:weather` channel:
+
+```json
+[null, "1", "miami:weather", "phx_leave", {}]
+```
+
+Third, `heartbeat` is used to maintain the WebSocket connection. For example:
+
+
+```json
+[null, "2", "phoenix", "heartbeat", {}]
+```
+
+The `heartbeat` message is only needed when no other messages are being sent and prevents Phoenix from closing the connection; the exact `:timeout` is configured in the application's `Endpoint` module.
+
+Other allowed messages depend on the Phoenix application.
+
+For example, if the Channel serving the `miami:weather` can handle a `report_emergency` event:
+
+```elixir
+def handle_in("report_emergency", payload, socket) do
+  MyApp.Emergencies.report(payload) # or whatever
+  {:reply, :ok, socket}
+end
+```
+
+...a client could send:
+
+```json
+[null, "3", "miami:weather", "report_emergency", {"category": "sharknado"}]
+```
diff --git a/guides/introduction/community.md b/guides/introduction/community.md
index b6f0b52a5..64f01a4d6 100644
--- a/guides/introduction/community.md
+++ b/guides/introduction/community.md
@@ -30,7 +30,7 @@ There are a number of places to connect with community members at all experience
 
   * [Phoenix in Action (by Geoffrey Lessel - 2019)](https://manning.com/books/phoenix-in-action)
 
-  * [Phoenix Inside Out - Book Series (by Shankar Dhanasekaran - 2017)](https://shankardevy.com/phoenix-book/)
+  * [Phoenix Inside Out - Book Series (by Shankar Dhanasekaran - 2017)](https://shankardevy.com/phoenix-book/). First book of the series Mastering Phoenix Framework is [free to read online](https://shankardevy.com/phoenix-inside-out-mpf/)
 
   * [Functional Web Development with Elixir, OTP, and Phoenix Rethink the Modern Web App (by Lance Halvorsen - 2017)](https://pragprog.com/titles/lhelph/functional-web-development-with-elixir-otp-and-phoenix/)
 
diff --git a/guides/plug.md b/guides/plug.md
index 469a9b0e5..97d525a9e 100644
--- a/guides/plug.md
+++ b/guides/plug.md
@@ -189,7 +189,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.LayoutView, :root}
+    plug :put_root_layout, html: {HelloWeb.LayoutView, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
     plug HelloWeb.Plugs.Locale, "en"
diff --git a/guides/real_time/channels.md b/guides/real_time/channels.md
index fed1a0d5f..f3d7a01b4 100644
--- a/guides/real_time/channels.md
+++ b/guides/real_time/channels.md
@@ -165,7 +165,7 @@ If your deployment environment does not support distributed Elixir or direct com
 ### Client Libraries
 
 Any networked device can connect to Phoenix Channels as long as it has a client library.
-The following libraries exist today, and new ones are always welcome.
+The following libraries exist today, and new ones are always welcome; to write your own, see our how-to guide "Writing a Channels Client".
 
 #### Official
 
@@ -183,6 +183,7 @@ Phoenix ships with a JavaScript client that is available when generating a new P
   - [PhoenixSharp](https://github.com/Mazyod/PhoenixSharp)
 + Elixir
   - [phoenix_gen_socket_client](https://github.com/Aircloak/phoenix_gen_socket_client)
+  - [slipstream](https://hexdocs.pm/slipstream/Slipstream.html)
 + GDScript (Godot Game Engine)
   - [GodotPhoenixChannels](https://github.com/alfredbaudisch/GodotPhoenixChannels)
 
diff --git a/guides/request_lifecycle.md b/guides/request_lifecycle.md
index 90d5d1a80..79a1e88a7 100644
--- a/guides/request_lifecycle.md
+++ b/guides/request_lifecycle.md
@@ -46,7 +46,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.Layouts, :root}
+    plug :put_root_layout, html: {HelloWeb.Layouts, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end
diff --git a/guides/routing.md b/guides/routing.md
index b2690a591..856982a3c 100644
--- a/guides/routing.md
+++ b/guides/routing.md
@@ -16,7 +16,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.Layouts, :root}
+    plug :put_root_layout, html: {HelloWeb.Layouts, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end
@@ -236,14 +236,14 @@ When building paths for nested routes, we will need to interpolate the IDs where
 ```elixir
 user_id = 42
 post_id = 17
-~p"/users/#{user_id}/#{post_id}"
+~p"/users/#{user_id}/posts/#{post_id}"
 "/users/42/posts/17"
 ```
 
 Verified routes also support the `Phoenix.Param` protocol, but we don't need to concern ourselves with elixir protocols just yet. Just know that once we start building our application with structs like `%User{}` and `%Post{}`, we'll be able to interpolate those data structures directly into our `~p` paths and phoenix will pluck out the correct fields to use in the route.
 
 ```elixir
-~p"/users/#{user}/#{post}"
+~p"/users/#{user}/posts/#{post}"
 "/users/42/posts/17"
 ```
 
@@ -457,7 +457,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.Layouts, :root}
+    plug :put_root_layout, html: {HelloWeb.Layouts, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end
@@ -502,7 +502,7 @@ defmodule HelloWeb.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {HelloWeb.Layouts, :root}
+    plug :put_root_layout, html: {HelloWeb.Layouts, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end
diff --git a/installer/templates/phx_assets/tailwind.config.js b/installer/templates/phx_assets/tailwind.config.js
index 06601557f..856af57c6 100644
--- a/installer/templates/phx_assets/tailwind.config.js
+++ b/installer/templates/phx_assets/tailwind.config.js
@@ -54,6 +54,7 @@ module.exports = {
             [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`,
             "-webkit-mask": `var(--hero-${name})`,
             "mask": `var(--hero-${name})`,
+            "mask-repeat": "no-repeat",
             "background-color": "currentColor",
             "vertical-align": "middle",
             "display": "inline-block",
diff --git a/installer/templates/phx_single/config/prod.exs b/installer/templates/phx_single/config/prod.exs
index f6e8c82ed..a9c197346 100644
--- a/installer/templates/phx_single/config/prod.exs
+++ b/installer/templates/phx_single/config/prod.exs
@@ -1,8 +1,4 @@
-import Config
-
-# For production, don't forget to configure the url host
-# to something meaningful, Phoenix uses this information
-# when generating URLs.<%= if @javascript or @css do %>
+import Config<%= if @javascript or @css do %>
 
 # Note we also include the path to a cache manifest
 # containing the digested version of static files. This
diff --git a/installer/templates/phx_umbrella/apps/app_name_web/config/prod.exs b/installer/templates/phx_umbrella/apps/app_name_web/config/prod.exs
index a3369183b..4acae1147 100644
--- a/installer/templates/phx_umbrella/apps/app_name_web/config/prod.exs
+++ b/installer/templates/phx_umbrella/apps/app_name_web/config/prod.exs
@@ -1,7 +1,3 @@
-# For production, don't forget to configure the url host
-# to something meaningful, Phoenix uses this information
-# when generating URLs.
-#
 # Note we also include the path to a cache manifest
 # containing the digested version of static files. This
 # manifest is generated by the `mix phx.digest` task,
diff --git a/installer/templates/phx_web/components/layouts/root.html.heex b/installer/templates/phx_web/components/layouts/root.html.heex
index aa2e9961b..b9926899e 100644
--- a/installer/templates/phx_web/components/layouts/root.html.heex
+++ b/installer/templates/phx_web/components/layouts/root.html.heex
@@ -1,5 +1,5 @@
 <!DOCTYPE html>
-<html lang="en" style="scrollbar-gutter: stable;">
+<html lang="en" class="[scrollbar-gutter:stable]">
   <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1" />
diff --git a/installer/templates/phx_web/router.ex b/installer/templates/phx_web/router.ex
index 2cc4b1e6b..9d49c3d86 100644
--- a/installer/templates/phx_web/router.ex
+++ b/installer/templates/phx_web/router.ex
@@ -5,7 +5,7 @@ defmodule <%= @web_namespace %>.Router do
     plug :accepts, ["html"]
     plug :fetch_session
     plug :fetch_live_flash
-    plug :put_root_layout, {<%= @web_namespace %>.Layouts, :root}
+    plug :put_root_layout, html: {<%= @web_namespace %>.Layouts, :root}
     plug :protect_from_forgery
     plug :put_secure_browser_headers
   end<% end %>
diff --git a/lib/phoenix/code_reloader/server.ex b/lib/phoenix/code_reloader/server.ex
index 525c1e637..e1146c4a1 100644
--- a/lib/phoenix/code_reloader/server.ex
+++ b/lib/phoenix/code_reloader/server.ex
@@ -89,7 +89,7 @@ defmodule Phoenix.CodeReloader.Server do
 
         :error ->
           write_backup(backup)
-          {:error, out}
+          {:error, IO.iodata_to_binary(out)}
       end
 
     Enum.each(froms, &GenServer.reply(&1, reply))
diff --git a/lib/phoenix/controller.ex b/lib/phoenix/controller.ex
index f2f9be3f6..259123215 100644
--- a/lib/phoenix/controller.ex
+++ b/lib/phoenix/controller.ex
@@ -241,8 +241,6 @@ defmodule Phoenix.Controller do
 
     quote bind_quoted: [opts: opts] do
       import Phoenix.Controller
-
-      # TODO v2: No longer automatically import dependencies
       import Plug.Conn
 
       use Phoenix.Controller.Pipeline
diff --git a/lib/phoenix/endpoint/render_errors.ex b/lib/phoenix/endpoint/render_errors.ex
index f7dd9d93b..b4241dd8e 100644
--- a/lib/phoenix/endpoint/render_errors.ex
+++ b/lib/phoenix/endpoint/render_errors.ex
@@ -53,16 +53,18 @@ defmodule Phoenix.Endpoint.RenderErrors do
 
   @doc false
   def __catch__(conn, kind, reason, stack, opts) do
-    receive do
-      @already_sent ->
-        send(self(), @already_sent)
-        %Plug.Conn{conn | state: :sent}
-    after
-      0 ->
-        instrument_render_and_send(conn, kind, reason, stack, opts)
-    end
+    conn =
+      receive do
+        @already_sent ->
+          send(self(), @already_sent)
+          %Plug.Conn{conn | state: :sent}
+      after
+        0 ->
+          instrument_render_and_send(conn, kind, reason, stack, opts)
+      end
 
-    :erlang.raise(kind, reason, stack)
+    maybe_raise(kind, reason, stack)
+    conn
   end
 
   defp instrument_render_and_send(conn, kind, reason, stack, opts) do
@@ -91,6 +93,9 @@ defmodule Phoenix.Endpoint.RenderErrors do
   defp error_conn(_conn, :error, %NoRouteError{conn: conn}), do: conn
   defp error_conn(conn, _kind, _reason), do: conn
 
+  defp maybe_raise(:error, %NoRouteError{}, _stack), do: :ok
+  defp maybe_raise(kind, reason, stack), do: :erlang.raise(kind, reason, stack)
+
   ## Rendering
 
   @doc false
diff --git a/lib/phoenix/router.ex b/lib/phoenix/router.ex
index 91174dca4..0039ed72f 100644
--- a/lib/phoenix/router.ex
+++ b/lib/phoenix/router.ex
@@ -453,7 +453,7 @@ defmodule Phoenix.Router do
   end
 
   defp match_dispatch() do
-    quote location: :keep do
+    quote location: :keep, generated: true do
       @behaviour Plug
 
       @doc """
@@ -506,10 +506,15 @@ defmodule Phoenix.Router do
     {matches, {pipelines, _}} =
       Enum.map_reduce(routes_with_exprs, {[], %{}}, &build_match/2)
 
-    verifies =
+    routes_per_path =
       routes_with_exprs
       |> Enum.group_by(&elem(&1, 1).path, &elem(&1, 0))
-      |> Enum.map(&build_verify/1)
+
+    verifies =
+      routes_with_exprs
+      |> Enum.map(&elem(&1, 1).path)
+      |> Enum.uniq()
+      |> Enum.map(&build_verify(&1, routes_per_path))
 
     verify_catch_all =
       quote generated: true do
@@ -574,7 +579,9 @@ defmodule Phoenix.Router do
     end
   end
 
-  defp build_verify({path, routes}) do
+  defp build_verify(path, routes_per_path) do
+    routes = Map.get(routes_per_path, path)
+
     forward_plug =
       Enum.find_value(routes, fn
         %{kind: :forward, plug: plug} -> plug
diff --git a/lib/phoenix/token.ex b/lib/phoenix/token.ex
index 46a692fae..932ef6c58 100644
--- a/lib/phoenix/token.ex
+++ b/lib/phoenix/token.ex
@@ -115,9 +115,11 @@ defmodule Phoenix.Token do
       when generating the encryption and signing keys. Defaults to `:sha256`
     * `:signed_at` - set the timestamp of the token in seconds.
       Defaults to `System.system_time(:second)`
+    * `:max_age` - the default maximum age of the token. Defaults to
+      86400 seconds (1 day) and it may be overridden on verify/4.
 
   """
-  @spec sign(context, binary, term, [shared_opt | signed_at_opt]) :: binary
+  @spec sign(context, binary, term, [shared_opt | max_age_opt | signed_at_opt]) :: binary
   def sign(context, salt, data, opts \\ []) when is_binary(salt) do
     context
     |> get_key_base()
@@ -137,9 +139,11 @@ defmodule Phoenix.Token do
       when generating the encryption and signing keys. Defaults to `:sha256`
     * `:signed_at` - set the timestamp of the token in seconds.
       Defaults to `System.system_time(:second)`
+    * `:max_age` - the default maximum age of the token. Defaults to
+      86400 seconds (1 day) and it may be overridden on verify/4.
 
   """
-  @spec encrypt(context, binary, term, [shared_opt | signed_at_opt]) :: binary
+  @spec encrypt(context, binary, term, [shared_opt | max_age_opt | signed_at_opt]) :: binary
   def encrypt(context, secret, data, opts \\ []) when is_binary(secret) do
     context
     |> get_key_base()
diff --git a/mix.exs b/mix.exs
index 171f5cd73..6a37bd37c 100644
--- a/mix.exs
+++ b/mix.exs
@@ -168,6 +168,7 @@ defmodule Phoenix.MixProject do
       "guides/deployment/heroku.md",
       "guides/howto/custom_error_pages.md",
       "guides/howto/using_ssl.md",
+      "guides/howto/writing_a_channels_client.md",
       "CHANGELOG.md"
     ]
   end


Test patch:
diff --git a/guides/testing/testing_channels.md b/guides/testing/testing_channels.md
index 592b88b69..1692e3fba 100644
--- a/guides/testing/testing_channels.md
+++ b/guides/testing/testing_channels.md
@@ -85,7 +85,7 @@ setup do
   {:ok, _, socket} =
     HelloWeb.UserSocket
     |> socket("user_id", %{some: :assign})
-    |> subscribe_and_join(RoomChannel, "room:lobby")
+    |> subscribe_and_join(HelloWeb.RoomChannel, "room:lobby")
 
   %{socket: socket}
 end
@@ -106,7 +106,7 @@ test "ping replies with status ok", %{socket: socket} do
 end
 ```
 
-This tests the following code in our `MyAppWeb.RoomChannel`:
+This tests the following code in our `HelloWeb.RoomChannel`:
 
 ```elixir
 # Channels can be used in a request/response fashion
@@ -124,7 +124,7 @@ We emulate the client pushing a message to the channel with `push/3`. In the lin
 
 ### Testing a Broadcast
 
-It is common to receive messages from the client and broadcast to everyone subscribed to a current topic. This common pattern is simple to express in Phoenix and is one of the generated `handle_in/3` callbacks in our `MyAppWeb.RoomChannel`.
+It is common to receive messages from the client and broadcast to everyone subscribed to a current topic. This common pattern is simple to express in Phoenix and is one of the generated `handle_in/3` callbacks in our `HelloWeb.RoomChannel`.
 
 ```elixir
 def handle_in("shout", payload, socket) do
@@ -150,17 +150,10 @@ Since the `handle_in/3` callback for the `"shout"` event just broadcasts the sam
 
 ### Testing an asynchronous push from the server
 
-The last test in our `MyAppWeb.RoomChannelTest` verifies that broadcasts from the server are pushed to the client. Unlike the previous tests discussed, we are indirectly testing that our channel's `handle_out/3` callback is triggered. This `handle_out/3` is defined in our `MyApp.RoomChannel` as:
-
-```elixir
-def handle_out(event, payload, socket) do
-  push(socket, event, payload)
-  {:noreply, socket}
-end
-```
+The last test in our `HelloWeb.RoomChannelTest` verifies that broadcasts from the server are pushed to the client. Unlike the previous tests discussed, we are indirectly testing that the channel's `handle_out/3` callback is triggered. By default, `handle_out/3` is implemented for us and simply pushes the message on to the client.
 
 Since the `handle_out/3` event is only triggered when we call `broadcast/3` from our channel, we will need to emulate that in our test. We do that by calling `broadcast_from` or `broadcast_from!`. Both serve the same purpose with the only difference of `broadcast_from!` raising an error when broadcast fails.
 
-The line `broadcast_from!(socket, "broadcast", %{"some" => "data"})` will trigger our `handle_out/3` callback above which pushes the same event and payload back to the client. To test this, we do `assert_push "broadcast", %{"some" => "data"}`.
+The line `broadcast_from!(socket, "broadcast", %{"some" => "data"})` will trigger the `handle_out/3` callback which pushes the same event and payload back to the client. To test this, we do `assert_push "broadcast", %{"some" => "data"}`.
 
 That's it. Now you are ready to develop and fully test real-time applications. To learn more about other functionality provided when testing channels, check out the documentation for [`Phoenix.ChannelTest`](https://hexdocs.pm/phoenix/Phoenix.ChannelTest.html).
diff --git a/guides/testing/testing_contexts.md b/guides/testing/testing_contexts.md
index 76082b779..c2b330c21 100644
--- a/guides/testing/testing_contexts.md
+++ b/guides/testing/testing_contexts.md
@@ -21,12 +21,12 @@ $ mix test
 ................
 
 Finished in 0.6 seconds
-19 tests, 0 failures
+21 tests, 0 failures
 
 Randomized with seed 638414
 ```
 
-Great. We've got nineteen tests and they are all passing!
+Great. We've got twenty-one tests and they are all passing!
 
 ## Testing posts
 
@@ -41,18 +41,9 @@ defmodule Hello.BlogTest do
   describe "posts" do
     alias Hello.Blog.Post
 
-    @valid_attrs %{body: "some body", title: "some title"}
-    @update_attrs %{body: "some updated body", title: "some updated title"}
-    @invalid_attrs %{body: nil, title: nil}
-
-    def post_fixture(attrs \\ %{}) do
-      {:ok, post} =
-        attrs
-        |> Enum.into(@valid_attrs)
-        |> Blog.create_post()
+    import Hello.BlogFixtures
 
-      post
-    end
+    @invalid_attrs %{body: nil, title: nil}
 
     test "list_posts/0 returns all posts" do
       post = post_fixture()
@@ -78,7 +69,9 @@ The tests defined for our context are very straight-forward. They call the funct
 
 ```elixir
 test "create_post/1 with valid data creates a post" do
-  assert {:ok, %Post{} = post} = Blog.create_post(@valid_attrs)
+  valid_attrs = %{body: "some body", title: "some title"}
+
+  assert {:ok, %Post{} = post} = Blog.create_post(valid_attrs)
   assert post.body == "some body"
   assert post.title == "some title"
 end
@@ -106,11 +99,15 @@ defmodule Hello.DataCase do
   end
 
   setup tags do
-    pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async])
-    on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
+    Hello.DataCase.setup_sandbox(tags)
     :ok
   end
 
+  def setup_sandbox(tags) do
+    pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Hello.Repo, shared: not tags[:async])
+    on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
+  end
+
   def errors_on(changeset) do
     ...
   end
diff --git a/installer/test/phx_new_umbrella_test.exs b/installer/test/phx_new_umbrella_test.exs
index 2e86d82b9..684c9c735 100644
--- a/installer/test/phx_new_umbrella_test.exs
+++ b/installer/test/phx_new_umbrella_test.exs
@@ -266,7 +266,7 @@ defmodule Mix.Tasks.Phx.New.UmbrellaTest do
 
       assert_file(web_path(@app, "lib/phx_umb_web/router.ex"), fn file ->
         assert file =~ ~s[plug :fetch_live_flash]
-        assert file =~ ~s[plug :put_root_layout, {PhxUmbWeb.Layouts, :root}]
+        assert file =~ ~s[plug :put_root_layout, html: {PhxUmbWeb.Layouts, :root}]
         assert file =~ ~s[get "/", PageController]
       end)
 
diff --git a/test/phoenix/endpoint/render_errors_test.exs b/test/phoenix/endpoint/render_errors_test.exs
index ef2014ff6..cfd24fcb3 100644
--- a/test/phoenix/endpoint/render_errors_test.exs
+++ b/test/phoenix/endpoint/render_errors_test.exs
@@ -96,33 +96,21 @@ defmodule Phoenix.Endpoint.RenderErrorsTest do
     assert_received {:plug_conn, :sent}
   end
 
-  test "call/2 is overridden with no route match as HTML" do
-    assert_raise Phoenix.Router.NoRouteError,
-                 "no route found for GET /unknown (Phoenix.Endpoint.RenderErrorsTest.Router)",
-                 fn ->
-                   call(Router, :get, "/unknown")
-                 end
+  test "call/2 is overridden with no route match as HTML and does not reraise" do
+    call(Router, :get, "/unknown")
 
     assert_received {:plug_conn, :sent}
   end
 
-  test "call/2 is overridden with no route match as JSON" do
-    assert_raise Phoenix.Router.NoRouteError,
-                 "no route found for GET /unknown (Phoenix.Endpoint.RenderErrorsTest.Router)",
-                 fn ->
-                   call(Router, :get, "/unknown?_format=json")
-                 end
+  test "call/2 is overridden with no route match as JSON and does not reraise" do
+    call(Router, :get, "/unknown?_format=json")
 
     assert_received {:plug_conn, :sent}
   end
 
   @tag :capture_log
-  test "call/2 is overridden with no route match while malformed format" do
-    assert_raise Phoenix.Router.NoRouteError,
-                 "no route found for GET /unknown (Phoenix.Endpoint.RenderErrorsTest.Router)",
-                 fn ->
-                   call(Router, :get, "/unknown?_format=unknown")
-                 end
+  test "call/2 is overridden with no route match while malformed format and does not reraise" do
+    call(Router, :get, "/unknown?_format=unknown")
 
     assert_received {:plug_conn, :sent}
   end
@@ -321,12 +309,8 @@ defmodule Phoenix.Endpoint.RenderErrorsTest do
            end) =~ "Could not render errors due to unknown format \"unknown\""
   end
 
-  test "exception page for NoRouteError with plug_status 404" do
-    body =
-      assert_render(404, conn(:get, "/"), [], fn ->
-        raise Phoenix.Router.NoRouteError, conn: conn(:get, "/"), router: nil, plug_status: 404
-      end)
-
-    assert body == "Got 404 from error with GET"
+  test "exception page for NoRouteError with plug_status 404 renders and does not reraise" do
+    conn = call(Router, :get, "/unknown")
+    assert Phoenix.ConnTest.response(conn, 404) =~ "Got 404 from error with GET"
   end
 end
diff --git a/test/phoenix/verified_routes_test.exs b/test/phoenix/verified_routes_test.exs
index 095c0c9b7..c67d7c040 100644
--- a/test/phoenix/verified_routes_test.exs
+++ b/test/phoenix/verified_routes_test.exs
@@ -49,6 +49,14 @@ defmodule Phoenix.VerifiedRoutesTest do
     forward "/plug_forward", UserController
   end
 
+  defmodule CatchAllWarningRouter do
+    use Phoenix.Router
+    alias Phoenix.VerifiedRoutesTest.PostController
+
+    get "/", PostController, :root
+    get "/*path", PostController, :root, warn_on_verify: true
+  end
+
   # Emulate regular endpoint functions
 
   defmodule Endpoint do
@@ -528,6 +536,19 @@ defmodule Phoenix.VerifiedRoutesTest do
         assert warnings =~
                  ~s|no route path for Phoenix.VerifiedRoutesTest.Router matches "/should-warn/foobar"|
       end
+
+      test "~p does not warn if route without warn_on_verify: true matches first" do
+        warnings =
+          ExUnit.CaptureIO.capture_io(:stderr, fn ->
+            defmodule VerifyFalse do
+              use Phoenix.VerifiedRoutes, endpoint: unquote(@endpoint), router: CatchAllWarningRouter
+
+              def test, do: ~p"/"
+            end
+          end)
+
+        assert warnings == ""
+      end
     end
   end
 end