Repository: phoenixframework/phoenix
Pull request #3276 (2019-02-13 09:04:15)

Add note to assert_broadcast documentation to prevent confusion
Related to issue #3271 

EskiMag: Any idea, why the check failed just on the `Elixir: 1.5 OTP Release: 20.3`?

Patch:
diff --git a/assets/js/phoenix.js b/assets/js/phoenix.js
index df78c0dd8..2bc742947 100644
--- a/assets/js/phoenix.js
+++ b/assets/js/phoenix.js
@@ -115,7 +115,7 @@
  * pass your channel in to track lifecycle events:
  *
  * ```javascript
- * let channel = new socket.channel("some:topic")
+ * let channel = socket.channel("some:topic")
  * let presence = new Presence(channel)
  * ```
  *
@@ -773,6 +773,9 @@ export class Socket {
   /**
    *
    * @param {Object} params - The params to send when connecting, for example `{user_id: userToken}`
+   *
+   * Passing params to connect is deprecated; pass them in the Socket constructor instead:
+   * `new Socket("/socket", {params: {user_id: userToken}})`.
    */
   connect(params){
     if(params){
@@ -847,7 +850,7 @@ export class Socket {
    * @private
    */
 
-  resetHeartbeat(){ if(this.conn.skipHeartbeat){ return }
+  resetHeartbeat(){ if(this.conn && this.conn.skipHeartbeat){ return }
     this.pendingHeartbeatRef = null
     clearInterval(this.heartbeatTimer)
     this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs)
diff --git a/guides/channels.md b/guides/channels.md
index aaada208a..e0dfe06d4 100644
--- a/guides/channels.md
+++ b/guides/channels.md
@@ -54,7 +54,7 @@ Once the connection is established, each incoming message from a client is route
 If the channel server asks to broadcast a message, that message is sent to the local PubSub, which sends it out to any clients connected to the same server and subscribed to that topic.
 
 If there are other nodes in the cluster, the local PubSub also forwards the message to their PubSubs, which send it out to their own subscribers.
-Because only one message has to be sent per additional node, the performance cost of adding nodes in negligible, while each new node supports many more subscribers.
+Because only one message has to be sent per additional node, the performance cost of adding nodes is negligible, while each new node supports many more subscribers.
 
 The message flow looks something like this:
 
diff --git a/guides/contexts.md b/guides/contexts.md
index 232002763..38c800dc5 100644
--- a/guides/contexts.md
+++ b/guides/contexts.md
@@ -1021,15 +1021,14 @@ Open up your CMS context (`lib/hello/cms.ex`), and add this new function:
 ```elixir
 def inc_page_views(%Page{} = page) do
   {1, [%Page{views: views}]} =
-    Repo.update_all(
-      from(p in Page, where: p.id == ^page.id),
-      [inc: [views: 1]], returning: [:views])
+    from(p in Page, where: p.id == ^page.id, select: [:views])
+    |> Repo.update_all(inc: [views: 1])
 
   put_in(page.views, views)
 end
 ```
 
-We built a query for fetching the current page given its ID which we pass to `Repo.update_all`. Ecto's `Repo.update_all` allows us to perform batch updates against the database, and is perfect for atomically updating values, such as incrementing our views count. The result of the repo operation returns the number of updated records, along with the selected schema values specified by the `returning` option. When we receive the new page views, we use `put_in(page.views, views)` to place the new view count within the page.
+We built a query for fetching the current page given its ID which we pass to `Repo.update_all`. Ecto's `Repo.update_all` allows us to perform batch updates against the database, and is perfect for atomically updating values, such as incrementing our views count. The result of the repo operation returns the number of updated records, along with the selected schema values specified by the `select` option. When we receive the new page views, we use `put_in(page.views, views)` to place the new view count within the page.
 
 With our context function in place, let's make use of it in our CMS page controller. Update your `show` action in `lib/hello_web/controllers/cms/page_controller.ex` to call our new function:
 
diff --git a/guides/deployment/deployment.md b/guides/deployment/deployment.md
index 668f6ac46..aa6d417d7 100644
--- a/guides/deployment/deployment.md
+++ b/guides/deployment/deployment.md
@@ -65,7 +65,7 @@ This step is required only if you have static assets like images, JavaScript, st
 Compilation of static assets happens in two steps:
 
 ```console
-$ cd assets && webpack --mode production
+$ npm run deploy --prefix ./assets
 
 $ mix phx.digest
 
@@ -122,7 +122,7 @@ $ mix deps.get --only prod
 $ MIX_ENV=prod mix compile
 
 # Compile assets
-$ cd assets && webpack --mode production && cd ..
+$ npm run deploy --prefix ./assets
 
 $ mix phx.digest
 
diff --git a/guides/deployment/heroku.md b/guides/deployment/heroku.md
index d7319087a..5ef88cfac 100644
--- a/guides/deployment/heroku.md
+++ b/guides/deployment/heroku.md
@@ -85,13 +85,23 @@ Git remote heroku added
 
 > Note: the name of the Heroku application is the random string after "Creating" in the output above (mysterious-meadow-6277). This will be unique, so expect to see a different name from "mysterious-meadow-6277".
 
-The `--buildpack` option we are passing allows us to specify the [Elixir buildpack](https://github.com/HashNuke/heroku-buildpack-elixir) we want Heroku to use.
-A [buildpack](https://devcenter.heroku.com/articles/buildpacks) is a convenient way of packaging framework and/or runtime support. In our case it's installing Erlang, Elixir, fetching our application dependencies, and so on, before we run it.
+The `--buildpack` option we are passing allows us to specify the [Elixir buildpack](https://github.com/HashNuke/heroku-buildpack-elixir) we want Heroku to use. A [buildpack](https://devcenter.heroku.com/articles/buildpacks) is a convenient way of packaging framework and/or runtime support. In our case it's installing Erlang, Elixir, fetching our application dependencies, and so on, before we run it.
 
 The URL in the output is the URL to our application. If we open it in our browser now, we will get the default Heroku welcome page.
 
 > Note: if we hadn't initialized our Git repository before we ran the `heroku create` command, we wouldn't have our Heroku remote repository properly set up at this point. We can set that up manually by running: `heroku git:remote -a [our-app-name].`
 
+The buildpack uses a predefined Elixir and Erlang version but to avoid surprises when deploying, it is best to explicitly list the Elixir and Erlang version we want in production to be the same we are using during development or in your continuous integration servers. This can be done by creating a config file named `elixir_buildpack.config` in the root directory of your project with your target version of Elixir and Erlang:
+
+```
+# Elixir version
+elixir_version=1.8.1
+
+# Erlang version
+# available versions https://github.com/HashNuke/heroku-buildpack-elixir-otp-builds/blob/master/otp-versions
+erlang_version=21.2.5
+```
+
 ## Adding the Phoenix Static Buildpack
 
 We need to compile static assets for a successful Phoenix deployment. The [Phoenix static buildpack](https://github.com/gjaldon/heroku-buildpack-phoenix-static) can take care of that for us, so let's add it now.
@@ -136,7 +146,7 @@ First, let's make sure our secret key is loaded from Heroku's environment variab
 config :hello, HelloWeb.Endpoint,
   url: [host: "example.com", port: 80],
   cache_static_manifest: "priv/static/cache_manifest.json",
-  secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE")
+  secret_key_base: System.get_env("SECRET_KEY_BASE") || raise("missing SECRET_KEY_BASE env var")
 ```
 
 Then, we'll add the production database configuration to `config/prod.exs`:
@@ -192,7 +202,7 @@ config :hello, HelloWeb.Endpoint,
   url: [scheme: "https", host: "mysterious-meadow-6277.herokuapp.com", port: 443],
   force_ssl: [rewrite_on: [:x_forwarded_proto]],
   cache_static_manifest: "priv/static/cache_manifest.json",
-  secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE")
+  secret_key_base: System.get_env("SECRET_KEY_BASE") || raise "missing SECRET_KEY_BASE env var"
 
 # Do not print debug messages in production
 config :logger, level: :info
@@ -266,8 +276,6 @@ Setting config vars and restarting mysterious-meadow-6277... done, v3
 SECRET_KEY_BASE: xvafzY4y01jYuzLm3ecJqo008dVnU3CN4f+MamNd1Zue4pXvfvUjbiXT8akaIF53
 ```
 
-If you need to make any of your config variables available at compile time, you will need to explicitly define which ones in a configuration file. Create a file `elixir_buildpack.config` in your application's root directory and add a line like: `config_vars_to_export=(MY_VAR)`. See [here](https://github.com/HashNuke/heroku-buildpack-elixir#specifying-config-vars-to-export-at-compile-time) for more information.
-
 ## Deploy Time!
 
 Our project is now ready to be deployed on Heroku.
@@ -276,6 +284,7 @@ Let's commit all our changes:
 
 ```
 $ git add config/prod.exs
+$ git add elixir_buildpack.config
 $ git add phoenix_static_buildpack.config
 $ git add compile
 $ git add Procfile
diff --git a/guides/ecto.md b/guides/ecto.md
index a28855fa3..a6e536e7c 100644
--- a/guides/ecto.md
+++ b/guides/ecto.md
@@ -264,7 +264,7 @@ iex> changeset.errors
  bio: {"can't be blank", [validation: :required]}]
 ```
 
-What happens if we pass a key/value pair that is in neither defined in the schema nor required?
+What happens if we pass a key/value pair that is neither defined in the schema nor required?
 
 Inside our existing IEx shell, let's create a `params` map with valid values plus an extra `random_key: "random value"`.
 
diff --git a/guides/phoenix_mix_tasks.md b/guides/phoenix_mix_tasks.md
index 846b9189e..a656ac2dd 100644
--- a/guides/phoenix_mix_tasks.md
+++ b/guides/phoenix_mix_tasks.md
@@ -205,8 +205,8 @@ $ mix phx.gen.html Blog Post posts body:string word_count:integer
 * creating test/hello_web/controllers/post_controller_test.exs
 * creating lib/hello/blog/post.ex
 * creating priv/repo/migrations/20170906150129_create_posts.exs
-* creating lib/hello/blog/blog.ex
-* injecting lib/hello/blog/blog.ex
+* creating lib/hello/blog.ex
+* injecting lib/hello/blog.ex
 * creating test/hello/blog/blog_test.exs
 * injecting test/hello/blog/blog_test.exs
 ```
@@ -277,8 +277,8 @@ $ mix phx.gen.html Blog Post posts body:string word_count:integer --no-schema
 * creating lib/hello_web/templates/post/show.html.eex
 * creating lib/hello_web/views/post_view.ex
 * creating test/hello_web/controllers/post_controller_test.exs
-* creating lib/hello/blog/blog.ex
-* injecting lib/hello/blog/blog.ex
+* creating lib/hello/blog.ex
+* injecting lib/hello/blog.ex
 * creating test/hello/blog/blog_test.exs
 * injecting test/hello/blog/blog_test.exs
 ```
@@ -316,8 +316,8 @@ $ mix phx.gen.json Blog Post posts title:string content:string
 * creating lib/hello_web/controllers/fallback_controller.ex
 * creating lib/hello/blog/post.ex
 * creating priv/repo/migrations/20170906153323_create_posts.exs
-* creating lib/hello/blog/blog.ex
-* injecting lib/hello/blog/blog.ex
+* creating lib/hello/blog.ex
+* injecting lib/hello/blog.ex
 * creating test/hello/blog/blog_test.exs
 * injecting test/hello/blog/blog_test.exs
 ```
@@ -388,8 +388,8 @@ $ mix phx.gen.json Blog Post posts title:string content:string --no-schema
 * creating test/hello_web/controllers/post_controller_test.exs
 * creating lib/hello_web/views/changeset_view.ex
 * creating lib/hello_web/controllers/fallback_controller.ex
-* creating lib/hello/blog/blog.ex
-* injecting lib/hello/blog/blog.ex
+* creating lib/hello/blog.ex
+* injecting lib/hello/blog.ex
 * creating test/hello/blog/blog_test.exs
 * injecting test/hello/blog/blog_test.exs
 ```
@@ -408,9 +408,9 @@ Important: If we don't do this, our application won't compile, and we'll get an
 $ mix phx.server
 Compiling 18 files (.ex)
 
-== Compilation error in file lib/hello/blog/blog.ex ==
-** (CompileError) lib/hello/blog/blog.ex:65: Hello.Blog.Post.__struct__/0 is undefined, cannot expand struct Hello.Blog.Post
-    lib/hello/blog/blog.ex:65: (module)
+== Compilation error in file lib/hello/blog.ex ==
+** (CompileError) lib/hello/blog.ex:65: Hello.Blog.Post.__struct__/0 is undefined, cannot expand struct Hello.Blog.Post
+    lib/hello/blog.ex:65: (module)
     (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
     (elixir) lib/kernel/parallel_compiler.ex:121: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1
 ```
@@ -425,8 +425,8 @@ The `mix phx.gen.context` task takes a number of arguments, the module name of t
 $ mix phx.gen.context Accounts User users name:string age:integer
 * creating lib/hello/accounts/user.ex
 * creating priv/repo/migrations/20170906161158_create_users.exs
-* creating lib/hello/accounts/accounts.ex
-* injecting lib/hello/accounts/accounts.ex
+* creating lib/hello/accounts.ex
+* injecting lib/hello/accounts.ex
 * creating test/hello/accounts/accounts_test.exs
 * injecting test/hello/accounts/accounts_test.exs
 ```
@@ -436,8 +436,8 @@ $ mix phx.gen.context Accounts User users name:string age:integer
 ```console
 * creating lib/hello/admin/accounts/user.ex
 * creating priv/repo/migrations/20170906161246_create_users.exs
-* creating lib/hello/admin/accounts/accounts.ex
-* injecting lib/hello/admin/accounts/accounts.ex
+* creating lib/hello/admin/accounts.ex
+* injecting lib/hello/admin/accounts.ex
 * creating test/hello/admin/accounts/accounts_test.exs
 * injecting test/hello/admin/accounts/accounts_test.exs
 ```
diff --git a/guides/presence.md b/guides/presence.md
index f3bb602f9..4569107fe 100644
--- a/guides/presence.md
+++ b/guides/presence.md
@@ -97,7 +97,7 @@ end
 
 Finally we can use the client-side Presence library included in `phoenix.js` to manage the state and presence diffs that come down the socket. It listens for the `"presence_state"` and `"presence_diff"` events and provides a simple callback for you to handle the events as they happen, with the `onSync` callback.
 
-The `onSync` callback allows you to easily react to presence state changes, which most often results in re-rendering an updated list of active users. You can use the `list` method is to format and return each individual presence based on the needs of your application.
+The `onSync` callback allows you to easily react to presence state changes, which most often results in re-rendering an updated list of active users. You can use the `list` method to format and return each individual presence based on the needs of your application.
 
 To iterate users, we use the `presences.list()` function which accepts a callback. The callback will be called for each presence item with 2 arguments, the presence id and a list of metas (one for each presence for that presence id). We use this to display the users and the number of devices they are online with.
 
diff --git a/guides/routing.md b/guides/routing.md
index 79edd7107..e4a62cbc7 100644
--- a/guides/routing.md
+++ b/guides/routing.md
@@ -32,7 +32,7 @@ defmodule HelloWeb.Router do
   # end
 end
 ```
-The name you gave your application will appear instead of `Hello` for both the router module and controller name.
+The name you gave your application will appear instead of `HelloWeb` for both the router module and controller name.
 
 The first line of this module, `use HelloWeb, :router`, simply makes Phoenix router functions available in our particular router.
 
@@ -115,7 +115,7 @@ user_path  PATCH   /users/:id       HelloWeb.UserController :update
 user_path  DELETE  /users/:id       HelloWeb.UserController :delete
 ```
 
-Of course, the name of your project will replace `Hello`.
+Of course, the name of your project will replace `HelloWeb`.
 
 This is the standard matrix of HTTP verbs, paths, and controller actions. Let's look at them individually, in a slightly different order.
 
diff --git a/guides/views.md b/guides/views.md
index 5f00d3041..3c0bd6e5d 100644
--- a/guides/views.md
+++ b/guides/views.md
@@ -73,20 +73,20 @@ When we `use HelloWeb, :view`, we get other conveniences as well. Since `view/0`
 Let's open up the `lib/hello_web/templates/page/index.html.eex` and locate this stanza.
 
 ```html
-<div class="phx-hero">
-  <h2><%= gettext("Welcome to %{name}!", name: "Phoenix") %></h2>
-  <p class="lead">A productive web framework that<br>does not compromise speed and maintainability.</p>
-</div>
+<section class="phx-hero">
+  <h1><%= gettext "Welcome to %{name}!", name: "Phoenix" %></h1>
+  <p>A productive web framework that<br/>does not compromise speed and maintainability.</p>
+</section>
 ```
 
 Then let's add a line with a link back to the same page. (The objective is to see how path helpers respond in a template, not to add any functionality.)
 
 ```html
-<div class="phx-hero">
-  <h2><%= gettext("Welcome to %{name}!", name: "Phoenix") %></h2>
-  <p class="lead">A productive web framework that<br>does not compromise speed and maintainability.</p>
+<section class="phx-hero">
+  <h1><%= gettext "Welcome to %{name}!", name: "Phoenix" %></h1>
+  <p>A productive web framework that<br/>does not compromise speed and maintainability.</p>
   <p><a href="<%= Routes.page_path(@conn, :index) %>">Link back to this page</a></p>
-</div>
+</section>
 ```
 
 Now we can reload the page and view source to see what we have.
diff --git a/installer/templates/phx_assets/webpack/webpack.config.js b/installer/templates/phx_assets/webpack/webpack.config.js
index d63d8e799..40b8fa684 100644
--- a/installer/templates/phx_assets/webpack/webpack.config.js
+++ b/installer/templates/phx_assets/webpack/webpack.config.js
@@ -13,7 +13,7 @@ module.exports = (env, options) => ({
     ]
   },
   entry: {
-      './js/app.js': ['./js/app.js'].concat(glob.sync('./vendor/**/*.js'))
+    './js/app.js': ['./js/app.js'].concat(glob.sync('./vendor/**/*.js'))
   },
   output: {
     filename: 'app.js',
diff --git a/lib/mix/tasks/phx.gen.context.ex b/lib/mix/tasks/phx.gen.context.ex
index 083bd90dc..b257cd45b 100644
--- a/lib/mix/tasks/phx.gen.context.ex
+++ b/lib/mix/tasks/phx.gen.context.ex
@@ -22,7 +22,7 @@ defmodule Mix.Tasks.Phx.Gen.Context do
 
   Overall, this generator will add the following files to `lib/your_app`:
 
-    * a context module in `accounts/accounts.ex`, serving as the API boundary
+    * a context module in `accounts.ex`, serving as the API boundary
     * a schema in `accounts/user.ex`, with a `users` table
 
   A migration file for the repository and test files for the context
diff --git a/lib/mix/tasks/phx.gen.html.ex b/lib/mix/tasks/phx.gen.html.ex
index 35398f17d..826b8585b 100644
--- a/lib/mix/tasks/phx.gen.html.ex
+++ b/lib/mix/tasks/phx.gen.html.ex
@@ -22,7 +22,7 @@ defmodule Mix.Tasks.Phx.Gen.Html do
 
   Overall, this generator will add the following files to `lib/`:
 
-    * a context module in `lib/app/accounts/accounts.ex` for the accounts API
+    * a context module in `lib/app/accounts.ex` for the accounts API
     * a schema in `lib/app/accounts/user.ex`, with an `users` table
     * a view in `lib/app_web/views/user_view.ex`
     * a controller in `lib/app_web/controllers/user_controller.ex`
diff --git a/lib/mix/tasks/phx.gen.json.ex b/lib/mix/tasks/phx.gen.json.ex
index 33245a448..b42e9606b 100644
--- a/lib/mix/tasks/phx.gen.json.ex
+++ b/lib/mix/tasks/phx.gen.json.ex
@@ -22,7 +22,7 @@ defmodule Mix.Tasks.Phx.Gen.Json do
 
   Overall, this generator will add the following files to `lib/`:
 
-    * a context module in `lib/app/accounts/accounts.ex` for the accounts API
+    * a context module in `lib/app/accounts.ex` for the accounts API
     * a schema in `lib/app/accounts/user.ex`, with an `users` table
     * a view in `lib/app_web/views/user_view.ex`
     * a controller in `lib/app_web/controllers/user_controller.ex`
diff --git a/lib/phoenix/channel/server.ex b/lib/phoenix/channel/server.ex
index bc3542f5c..6082d2882 100644
--- a/lib/phoenix/channel/server.ex
+++ b/lib/phoenix/channel/server.ex
@@ -38,10 +38,23 @@ defmodule Phoenix.Channel.Server do
     args = [channel, {payload, from, socket}]
 
     case PoolSupervisor.start_child(socket.endpoint, socket.handler, from, args) do
-      {:ok, :undefined} ->
-        receive do: ({^ref, reply} -> {:error, reply})
       {:ok, pid} ->
-        receive do: ({^ref, reply} -> {:ok, reply, pid})
+        mon_ref = Process.monitor(pid)
+
+        receive do
+          {^ref, {:ok, reply}} ->
+            Process.demonitor(mon_ref, [:flush])
+            {:ok, reply, pid}
+
+          {^ref, {:error, reply}} ->
+            Process.demonitor(mon_ref, [:flush])
+            {:error, reply}
+
+          {:DOWN, ^mon_ref, _, _, reason} ->
+            Logger.error fn -> Exception.format_exit(reason) end
+            {:error, %{reason: "join crashed"}}
+        end
+
       {:error, reason} ->
         Logger.error fn -> Exception.format_exit(reason) end
         {:error, %{reason: "join crashed"}}
@@ -194,6 +207,23 @@ defmodule Phoenix.Channel.Server do
 
   @doc false
   def init({auth_payload, from, socket}) do
+    # TODO: Use handle_continue when we support Erlang/OTP 21+.
+    send(self(), {:join, __MODULE__})
+    {:ok, {auth_payload, from, socket}}
+  end
+
+  @doc false
+  def handle_call(:socket, _from, socket) do
+    {:reply, socket, socket}
+  end
+
+  @doc false
+  def handle_cast(:close, socket) do
+    {:stop, {:shutdown, :closed}, socket}
+  end
+
+  @doc false
+  def handle_info({:join, __MODULE__}, {auth_payload, from, socket}) do
     %{channel: channel, topic: topic, private: private} = socket
 
     socket = %{socket
@@ -202,13 +232,13 @@ defmodule Phoenix.Channel.Server do
 
     case channel_join(socket, channel, topic, auth_payload) do
       {:ok, socket} ->
-        init(socket, channel, topic, %{}, from)
+        init_info(socket, channel, topic, %{}, from)
       {:ok, reply, socket} ->
-        init(socket, channel, topic, reply, from)
+        init_info(socket, channel, topic, reply, from)
       {:error, reply} ->
         log_join socket, topic, fn -> "Replied #{topic} :error" end
-        GenServer.reply(from, reply)
-        :ignore
+        GenServer.reply(from, {:error, reply})
+        {:stop, :shutdown, socket}
       other ->
         raise """
         channel #{inspect socket.channel}.join/3 is expected to return one of:
@@ -222,40 +252,6 @@ defmodule Phoenix.Channel.Server do
     end
   end
 
-  defp channel_join(socket, channel, topic, auth_payload) do
-    instrument = %{params: auth_payload, socket: socket}
-
-    Phoenix.Endpoint.instrument socket, :phoenix_channel_join, instrument, fn ->
-      channel.join(topic, auth_payload, socket)
-    end
-  end
-
-  defp init(socket, channel, topic, reply, from) do
-    %{transport_pid: transport_pid, serializer: serializer, pubsub_server: pubsub_server} = socket
-    Process.monitor(transport_pid)
-
-    fastlane = {transport_pid, serializer, channel.__intercepts__()}
-    PubSub.subscribe(pubsub_server, topic, link: true, fastlane: fastlane)
-
-    log_join socket, topic, fn -> "Replied #{topic} :ok" end
-    GenServer.reply(from, reply)
-    {:ok, %{socket | joined: true}}
-  end
-
-  defp log_join(%{private: %{log_join: false}}, _topic, _func), do: :noop
-  defp log_join(%{private: %{log_join: level}}, _topic, func), do: Logger.log(level, func)
-
-  @doc false
-  def handle_call(:socket, _from, socket) do
-    {:reply, socket, socket}
-  end
-
-  @doc false
-  def handle_cast(:close, socket) do
-    {:stop, {:shutdown, :closed}, socket}
-  end
-
-  @doc false
   def handle_info(%Message{topic: topic, event: "phx_leave", ref: ref}, %{topic: topic} = socket) do
     handle_in({:stop, {:shutdown, :left}, :ok, put_in(socket.ref, ref)})
   end
@@ -318,6 +314,10 @@ defmodule Phoenix.Channel.Server do
     end
   end
 
+  def terminate(_reason, _socket) do
+    :ok
+  end
+
   @doc false
   def fastlane(subscribers, from, %Broadcast{event: event} = msg) do
     Enum.reduce(subscribers, %{}, fn
@@ -353,6 +353,31 @@ defmodule Phoenix.Channel.Server do
     end)
   end
 
+  ## Joins
+
+  defp channel_join(socket, channel, topic, auth_payload) do
+    instrument = %{params: auth_payload, socket: socket}
+
+    Phoenix.Endpoint.instrument socket, :phoenix_channel_join, instrument, fn ->
+      channel.join(topic, auth_payload, socket)
+    end
+  end
+
+  defp init_info(socket, channel, topic, reply, from) do
+    %{transport_pid: transport_pid, serializer: serializer, pubsub_server: pubsub_server} = socket
+    Process.monitor(transport_pid)
+
+    fastlane = {transport_pid, serializer, channel.__intercepts__()}
+    PubSub.subscribe(pubsub_server, topic, link: true, fastlane: fastlane)
+
+    log_join socket, topic, fn -> "Replied #{topic} :ok" end
+    GenServer.reply(from, {:ok, reply})
+    {:noreply, %{socket | joined: true}}
+  end
+
+  defp log_join(%{private: %{log_join: false}}, _topic, _func), do: :noop
+  defp log_join(%{private: %{log_join: level}}, _topic, func), do: Logger.log(level, func)
+
   ## Handle results
 
   defp handle_result({:stop, reason, socket}, _callback) do
diff --git a/lib/phoenix/controller.ex b/lib/phoenix/controller.ex
index 90d71add9..3e6ea6d6c 100644
--- a/lib/phoenix/controller.ex
+++ b/lib/phoenix/controller.ex
@@ -806,7 +806,7 @@ defmodule Phoenix.Controller do
   end
 
   @doc """
-  Puts the URL or `%URI{}` to be used for route generation.
+  Puts the url string or `%URI{}` to be used for route generation.
 
   This function overrides the default URL generation pulled
   from the `%Plug.Conn{}`'s endpoint configuration.
@@ -824,8 +824,8 @@ defmodule Phoenix.Controller do
 
   Now when you call `Routes.some_route_url(conn, ...)`, it will use
   the router url set above. Keep in mind that, if you want to generate
-  routes to the current domain, it is preferred to use `Routes.some_route_path`
-  helpers, as those are always relative.
+  routes to the *current* domain, it is preferred to use
+  `Routes.some_route_path` helpers, as those are always relative.
   """
   def put_router_url(conn, %URI{} = uri) do
     put_private(conn, :phoenix_router_url, uri)
@@ -837,12 +837,22 @@ defmodule Phoenix.Controller do
   @doc """
   Puts the format in the connection.
 
+  This format is used when rendering a template as an atom.
+  For example, `render(conn, :foo)` will render `"foo.FORMAT"`
+  where the format is the one set here. The default format
+  is typically set from the negotiation done in `accepts/2`.
+
   See `get_format/1` for retrieval.
   """
   def put_format(conn, format), do: put_private(conn, :phoenix_format, format)
 
   @doc """
   Returns the request format, such as "json", "html".
+
+  This format is used when rendering a template as an atom.
+  For example, `render(conn, :foo)` will render `"foo.FORMAT"`
+  where the format is the one set here. The default format
+  is typically set from the negotiation done in `accepts/2`.
   """
   def get_format(conn) do
     conn.private[:phoenix_format] || conn.params["_format"]
@@ -1344,12 +1354,26 @@ defmodule Phoenix.Controller do
   end
 
   @doc """
-  Returns the current request path, with and without query params.
+  Returns the current request path with its default query parameters:
+
+      iex> current_path(conn)
+      "/users/123?existing=param"
+
+  See `current_path/2` to override the default parameters.
+  """
+  def current_path(%Plug.Conn{query_string: ""} = conn) do
+    conn.request_path
+  end
+
+  def current_path(%Plug.Conn{query_string: query_string} = conn) do
+    conn.request_path <> "?" <> query_string
+  end
+
+  @doc """
+  Returns the current path with the given query parameters.
 
-  By default, the connection's query params are included in
-  the generated path. Custom query params may be used instead
-  by providing a map of your own params. You may also retrieve
-  only the request path by passing an empty map of params.
+  You may also retrieve only the request path by passing an
+  empty map of params.
 
   ## Examples
 
@@ -1366,12 +1390,6 @@ defmodule Phoenix.Controller do
       "/users/123"
 
   """
-  def current_path(%Plug.Conn{query_string: ""} = conn) do
-    conn.request_path
-  end
-  def current_path(%Plug.Conn{query_string: query_string} = conn) do
-    conn.request_path <> "?" <> query_string
-  end
   def current_path(%Plug.Conn{} = conn, params) when params == %{} do
     conn.request_path
   end
@@ -1379,8 +1397,20 @@ defmodule Phoenix.Controller do
     conn.request_path <> "?" <> Plug.Conn.Query.encode(params)
   end
 
+  @doc """
+  Returns the current request url with its default query parameters:
+
+      iex> current_url(conn)
+      "https://www.example.com/users/123?existing=param"
+
+  See `current_url/2` to override the default parameters.
+  """
+  def current_url(%Plug.Conn{} = conn) do
+    Phoenix.Router.Helpers.url(router_module(conn), conn) <> current_path(conn)
+  end
+
   @doc ~S"""
-  Returns the current request URL, with and without query params.
+  Returns the current request URL with query params.
 
   The path will be retrieved from the currently requested path via
   `current_path/1`. The scheme, host and others will be received from
@@ -1420,11 +1450,8 @@ defmodule Phoenix.Controller do
       end
 
   However, if you want all generated URLs to always have a certain schema,
-  host, etc, you may invoke `put_router_url/2`.
+  host, etc, you may use `put_router_url/2`.
   """
-  def current_url(%Plug.Conn{} = conn) do
-    Phoenix.Router.Helpers.url(router_module(conn), conn) <> current_path(conn)
-  end
   def current_url(%Plug.Conn{} = conn, %{} = params) do
     Phoenix.Router.Helpers.url(router_module(conn), conn) <> current_path(conn, params)
   end
diff --git a/lib/phoenix/endpoint.ex b/lib/phoenix/endpoint.ex
index af6b93e4e..c4030ce47 100644
--- a/lib/phoenix/endpoint.ex
+++ b/lib/phoenix/endpoint.ex
@@ -562,7 +562,7 @@ defmodule Phoenix.Endpoint do
 
   defp plug() do
     quote location: :keep do
-      use Plug.Builder
+      use Plug.Builder, init_mode: Phoenix.plug_init_mode()
       import Phoenix.Endpoint
 
       Module.register_attribute(__MODULE__, :phoenix_sockets, accumulate: true)
@@ -789,6 +789,7 @@ defmodule Phoenix.Endpoint do
 
   defp socket_path(path, config) do
     end_path_fragment = Keyword.fetch!(config, :path)
+
     {vars, path} =
       String.split(path <> "/" <> end_path_fragment, "/", trim: true)
       |> Enum.join("/")
@@ -834,9 +835,10 @@ defmodule Phoenix.Endpoint do
       of options. See "Shared configuration" and
       "Longpoll configuration" for the whole list
 
-    * `:shutdown` - the maximum shutdown time of each channel
-      when the endpoint is shutting down. Applies only to
-      channel-based sockets
+  If your socket is implemented using `Phoenix.Socket`,
+  you can also pass here all options accepted on
+  `use Phoenix.Socket`. An option given here will override
+  the value in `Phoenix.Socket`.
 
   ## Examples
 
@@ -911,7 +913,6 @@ defmodule Phoenix.Endpoint do
               connect_info: [:uri, signing_salt: "NZIguRPO"]
             ]
 
-
   ## Websocket configuration
 
   The following configuration applies only to `:websocket`.
diff --git a/lib/phoenix/router.ex b/lib/phoenix/router.ex
index af260cd73..fdecd0b93 100644
--- a/lib/phoenix/router.ex
+++ b/lib/phoenix/router.ex
@@ -323,6 +323,13 @@ defmodule Phoenix.Router do
     Helpers.define(env, routes_with_exprs)
     {matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match/2)
 
+    checks =
+      for {%{line: line}, %{dispatch: {plug, _}}} <- routes_with_exprs, into: %{} do
+        quote line: line do
+          {unquote(plug).init([]), true}
+        end
+      end
+
     # @anno is used here to avoid warnings if forwarding to root path
     match_404 =
       quote @anno do
@@ -335,6 +342,9 @@ defmodule Phoenix.Router do
       @doc false
       def __routes__,  do: unquote(Macro.escape(routes))
 
+      @doc false
+      def __checks__, do: unquote({:__block__, [], Map.keys(checks)})
+
       @doc false
       def __helpers__, do: __MODULE__.Helpers
 
@@ -361,7 +371,6 @@ defmodule Phoenix.Router do
       host: host
     } = exprs
 
-
     {pipe_name, pipe_definition, known_pipelines} =
       case known_pipelines do
         %{^pipe_through => name} ->
@@ -671,7 +680,9 @@ defmodule Phoenix.Router do
 
     * `:path` - a string containing the path scope
     * `:as` - a string or atom containing the named helper scope
-    * `:alias` - an alias (atom) containing the controller scope
+    * `:alias` - an alias (atom) containing the controller scope.
+      When set, this value may be overridden per route by passing `alias: false`
+      to route definitions, such as `get`, `post`, etc.
     * `:host` - a string containing the host scope, or prefix host scope,
       ie `"foo.bar.com"`, `"foo."`
     * `:private` - a map of private data to merge into the connection when a route matches
@@ -745,6 +756,22 @@ defmodule Phoenix.Router do
     end
   end
 
+  @doc """
+  Returns the full alias with the current scope's aliased prefix.
+
+  Useful for applying the same short-hand alias handling to
+  other values besides the second argument in route definitions.
+
+  ## Examples
+
+      scope "/", MyPrefix do
+        get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
+      end
+  """
+  def scoped_alias(router_module, alias) do
+    Scope.expand_alias(router_module, alias)
+  end
+
   @doc """
   Forwards a request at the given path to a plug.
 
diff --git a/lib/phoenix/router/helpers.ex b/lib/phoenix/router/helpers.ex
index c6a1704cc..ccdfb7466 100644
--- a/lib/phoenix/router/helpers.ex
+++ b/lib/phoenix/router/helpers.ex
@@ -3,7 +3,6 @@ defmodule Phoenix.Router.Helpers do
   @moduledoc false
 
   alias Phoenix.Router.Route
-  alias Phoenix.Socket
   alias Plug.Conn
 
   @anno (if :erlang.system_info(:otp_release) >= '19' do
@@ -23,7 +22,7 @@ defmodule Phoenix.Router.Helpers do
     end
   end
 
-  def url(_router, %Socket{endpoint: endpoint}) do
+  def url(_router, %_{endpoint: endpoint}) do
     endpoint.url()
   end
 
@@ -37,8 +36,8 @@ defmodule Phoenix.Router.Helpers do
 
   def url(router, other) do
     raise ArgumentError,
-      "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{} or a Phoenix.Endpoint " <>
-      "when building url for #{inspect router}, got: #{inspect other}"
+      "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{}, a struct with an :endpoint key, " <>
+      "or a Phoenix.Endpoint when building url for #{inspect(router)}, got: #{inspect(other)}"
   end
 
   @doc """
@@ -55,7 +54,7 @@ defmodule Phoenix.Router.Helpers do
     (uri.path || "") <> path
   end
 
-  def path(_router, %Socket{endpoint: endpoint}, path) do
+  def path(_router, %_{endpoint: endpoint}, path) do
     endpoint.path(path)
   end
 
@@ -65,8 +64,8 @@ defmodule Phoenix.Router.Helpers do
 
   def path(router, other, _path) do
     raise ArgumentError,
-      "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{} or a Phoenix.Endpoint " <>
-      "when building path for #{inspect router}, got: #{inspect other}"
+      "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{}, a struct with an :endpoint key, " <>
+      "or a Phoenix.Endpoint when building path for #{inspect(router)}, got: #{inspect(other)}"
   end
 
   ## Helpers
@@ -208,7 +207,7 @@ defmodule Phoenix.Router.Helpers do
         private.phoenix_endpoint.static_path(path)
       end
 
-      def static_path(%Socket{endpoint: endpoint} = conn, path) do
+      def static_path(%_{endpoint: endpoint} = conn, path) do
         endpoint.static_path(path)
       end
 
@@ -223,7 +222,7 @@ defmodule Phoenix.Router.Helpers do
         static_url(private.phoenix_endpoint, path)
       end
 
-      def static_url(%Socket{endpoint: endpoint} = conn, path) do
+      def static_url(%_{endpoint: endpoint} = conn, path) do
         static_url(endpoint, path)
       end
 
diff --git a/lib/phoenix/router/scope.ex b/lib/phoenix/router/scope.ex
index 32ca4000f..9e8af044a 100644
--- a/lib/phoenix/router/scope.ex
+++ b/lib/phoenix/router/scope.ex
@@ -4,14 +4,16 @@ defmodule Phoenix.Router.Scope do
 
   @stack :phoenix_router_scopes
   @pipes :phoenix_pipeline_scopes
+  @top :phoenix_top_scopes
 
-  defstruct path: nil, alias: nil, as: nil, pipes: [], host: nil, private: %{}, assigns: %{}
+  defstruct path: [], alias: [], as: [], pipes: [], host: nil, private: %{}, assigns: %{}
 
   @doc """
   Initializes the scope.
   """
   def init(module) do
-    Module.put_attribute(module, @stack, [%Scope{}])
+    Module.put_attribute(module, @stack, [])
+    Module.put_attribute(module, @top, %Scope{})
     Module.put_attribute(module, @pipes, MapSet.new)
   end
 
@@ -23,9 +25,10 @@ defmodule Phoenix.Router.Scope do
     private = Keyword.get(opts, :private, %{})
     assigns = Keyword.get(opts, :assigns, %{})
     as      = Keyword.get(opts, :as, Phoenix.Naming.resource_name(plug, "Controller"))
+    alias?  = Keyword.get(opts, :alias, true)
 
     {path, host, alias, as, pipes, private, assigns} =
-      join(module, path, plug, as, private, assigns)
+      join(module, path, plug, alias?, as, private, assigns)
     Phoenix.Router.Route.build(line, kind, verb, path, host, alias, plug_opts, as, pipes, private, assigns)
   end
 
@@ -57,25 +60,15 @@ defmodule Phoenix.Router.Scope do
   """
   def pipe_through(module, new_pipes) do
     new_pipes = List.wrap(new_pipes)
-    stack_pipes =
-      module
-      |> get_stack()
-      |> Enum.flat_map(fn scope -> scope.pipes end)
-
-    update_stack(module, fn [scope | stack] ->
-      pipes = collect_pipes(new_pipes, stack_pipes, scope.pipes)
-      [put_in(scope.pipes, pipes) | stack]
-    end)
-  end
-  defp collect_pipes([] = _new_pipes, _stack_pipes, acc), do: acc
-  defp collect_pipes([pipe | new_pipes], stack_pipes, acc) do
-    if pipe in new_pipes or pipe in stack_pipes do
-      raise ArgumentError, """
-      duplicate pipe_through for #{inspect pipe}.
-      A plug may only be used once inside a scoped pipe_through
-      """
+    %{pipes: pipes} = top = get_top(module)
+
+    if pipe = Enum.find(new_pipes, & &1 in pipes) do
+      raise ArgumentError,
+            "duplicate pipe_through for #{inspect pipe}. " <>
+              "A plug may only be used once inside a scoped pipe_through"
     end
-    collect_pipes(new_pipes, stack_pipes, acc ++ [pipe])
+
+    put_top(module, %{top | pipes: pipes ++ new_pipes})
   end
 
   @doc """
@@ -86,36 +79,43 @@ defmodule Phoenix.Router.Scope do
   end
 
   def push(module, opts) when is_list(opts) do
-    path = with path when not is_nil(path) <- Keyword.get(opts, :path),
-                path <- validate_path(path),
-                do: String.split(path, "/", trim: true)
-
-    alias = Keyword.get(opts, :alias)
-    alias = alias && Atom.to_string(alias)
+    path =
+      if path = Keyword.get(opts, :path) do
+        path |> validate_path() |> String.split("/", trim: true)
+      else
+        []
+      end
+
+    alias = Keyword.get(opts, :alias) |> List.wrap() |> Enum.map(&Atom.to_string/1)
+    as = Keyword.get(opts, :as) |> List.wrap()
+    host = Keyword.get(opts, :host)
+    private = Keyword.get(opts, :private, %{})
+    assigns = Keyword.get(opts, :assigns, %{})
 
-    scope = %Scope{path: path,
-                   alias: alias,
-                   as: Keyword.get(opts, :as),
-                   host: Keyword.get(opts, :host),
-                   pipes: [],
-                   private: Keyword.get(opts, :private, %{}),
-                   assigns: Keyword.get(opts, :assigns, %{})}
+    top = get_top(module)
+    update_stack(module, fn stack -> [top | stack] end)
 
-    update_stack(module, fn stack -> [scope|stack] end)
+    put_top(module, %Scope{
+      path: top.path ++ path,
+      alias: top.alias ++ alias,
+      as: top.as ++ as,
+      host: host || top.host,
+      pipes: top.pipes,
+      private: Map.merge(top.private, private),
+      assigns: Map.merge(top.assigns, assigns)
+    })
   end
 
   @doc """
   Pops a scope from the module stack.
   """
   def pop(module) do
-    update_stack(module, fn [_|stack] -> stack end)
+    update_stack(module, fn [top | stack] ->
+      put_top(module, top)
+      stack
+    end)
   end
 
-  @doc """
-  Returns true if the module's definition is currently within a scope block.
-  """
-  def inside_scope?(module), do: length(get_stack(module)) > 1
-
   @doc """
   Add a forward to the router.
   """
@@ -132,70 +132,39 @@ defmodule Phoenix.Router.Scope do
     raise ArgumentError, "forward expects a module as the second argument, #{inspect plug} given"
   end
 
-  defp expand_alias(module, alias) do
-    if inside_scope?(module) do
-      module
-      |> get_stack()
-      |> join_alias(alias)
-    else
-      alias
-    end
-  end
-
-  defp join(module, path, alias, as, private, assigns) do
-    stack = get_stack(module)
-    {join_path(stack, path), find_host(stack), join_alias(stack, alias),
-     join_as(stack, as), join_pipe_through(stack), join_private(stack, private),
-     join_assigns(stack, assigns)}
-  end
-
-  defp join_path(stack, path) do
-    "/" <>
-      ([String.split(path, "/", trim: true) | extract(stack, :path)]
-       |> Enum.reverse()
-       |> Enum.concat()
-       |> Enum.join("/"))
-  end
-
-  defp join_alias(stack, alias) when is_atom(alias) do
-    [alias|extract(stack, :alias)]
-    |> Enum.reverse()
-    |> Module.concat()
-  end
-
-  defp join_as(_stack, nil), do: nil
-  defp join_as(stack, as) when is_atom(as) or is_binary(as) do
-    [as|extract(stack, :as)]
-    |> Enum.reverse()
-    |> Enum.join("_")
+  @doc """
+  Expands the alias in the current router scope.
+  """
+  def expand_alias(module, alias) do
+    join_alias(get_top(module), alias)
   end
 
-  defp join_private(stack, private) do
-    Enum.reduce stack, private, &Map.merge(&1.private, &2)
-  end
+  defp join(module, path, alias, alias?, as, private, assigns) do
+    top = get_top(module)
+    joined_alias =
+      if alias? do
+        join_alias(top, alias)
+      else
+        alias
+      end
 
-  defp join_assigns(stack, assigns) do
-    Enum.reduce stack, assigns, &Map.merge(&1.assigns, &2)
+    {join_path(top, path), top.host, joined_alias, join_as(top, as), top.pipes,
+     Map.merge(top.private, private), Map.merge(top.assigns, assigns)}
   end
 
-  defp join_pipe_through(stack) do
-    for scope <- Enum.reverse(stack),
-        item <- scope.pipes,
-        do: item
+  defp join_path(top, path) do
+    "/" <> Enum.join(top.path ++ String.split(path, "/", trim: true), "/")
   end
 
-  defp find_host(stack) do
-    Enum.find_value(stack, & &1.host)
+  defp join_alias(top, alias) when is_atom(alias) do
+    Module.concat(top.alias ++ [alias])
   end
 
-  defp extract(stack, attr) do
-    for scope <- stack,
-        item = Map.fetch!(scope, attr),
-        do: item
-  end
+  defp join_as(_top, nil), do: nil
+  defp join_as(top, as) when is_atom(as) or is_binary(as), do: Enum.join(top.as ++ [as], "_")
 
-  defp get_stack(module) do
-    get_attribute(module, @stack)
+  defp get_top(module) do
+    get_attribute(module, @top)
   end
 
   defp update_stack(module, fun) do
@@ -206,6 +175,11 @@ defmodule Phoenix.Router.Scope do
     update_attribute(module, @pipes, fun)
   end
 
+  defp put_top(module, value) do
+    Module.put_attribute(module, @top, value)
+    value
+  end
+
   defp get_attribute(module, attr) do
     Module.get_attribute(module, attr) ||
       raise "Phoenix router scope was not initialized"
diff --git a/lib/phoenix/socket.ex b/lib/phoenix/socket.ex
index 01234dad2..d415e1483 100644
--- a/lib/phoenix/socket.ex
+++ b/lib/phoenix/socket.ex
@@ -68,13 +68,20 @@ defmodule Phoenix.Socket do
     * `:transport_pid` - The pid of the socket's transport process
     * `:serializer` - The serializer for socket messages
 
-  ## Logging
+  ## Using options
 
-  Logging for socket connections is set via the `:log` option, for example:
+  On `use Phoenix.Socket`, the following options are accepted:
 
-      use Phoenix.Socket, log: :debug
+    * `:log` - the default level to log socket actions. Defaults
+      to `:info`. May be set to `false` to disable it
 
-  Defaults to the `:info` log level. Pass `false` to disable logging.
+    * `:shutdown` - the maximum shutdown time of each channel
+      when the endpoint is shutting down. Applies only to
+      channel-based sockets
+
+    * `:partitions` - each channel is spawned under a supervisor.
+      This option controls how many supervisors will be spawned
+      to handlle channels. Defaults to the number of cores.
 
   ## Garbage collection
 
@@ -131,9 +138,9 @@ defmodule Phoenix.Socket do
       {auth_payload, from, socket}
 
   A custom channel implementation MUST invoke
-  `GenServer.reply(from, reply_payload)` during its initialization
-  with a custom `reply_payload` that will be sent as a reply to the
-  client. Failing to do so will block the socket forever.
+  `GenServer.reply(from, {:ok | :error, reply_payload})` during its
+  initialization with a custom `reply_payload` that will be sent as
+  a reply to the client. Failing to do so will block the socket forever.
 
   A custom channel receives `Phoenix.Socket.Message` structs as regular
   messages from the transport. Replies to those messages and custom
@@ -269,7 +276,7 @@ defmodule Phoenix.Socket do
       @behaviour Phoenix.Socket
       @before_compile Phoenix.Socket
       Module.register_attribute(__MODULE__, :phoenix_channels, accumulate: true)
-      @phoenix_log Keyword.get(unquote(opts), :log, :info)
+      @phoenix_socket_options unquote(opts)
 
       ## Callbacks
 
@@ -277,11 +284,11 @@ defmodule Phoenix.Socket do
 
       @doc false
       def child_spec(opts) do
-        Phoenix.Socket.__child_spec__(__MODULE__, opts)
+        Phoenix.Socket.__child_spec__(__MODULE__, opts, @phoenix_socket_options)
       end
 
       @doc false
-      def connect(map), do: Phoenix.Socket.__connect__(__MODULE__, map, @phoenix_log)
+      def connect(map), do: Phoenix.Socket.__connect__(__MODULE__, map, @phoenix_socket_options)
 
       @doc false
       def init(state), do: Phoenix.Socket.__init__(state)
@@ -400,11 +407,13 @@ defmodule Phoenix.Socket do
 
   ## CALLBACKS IMPLEMENTATION
 
-  def __child_spec__(handler, opts) do
+  def __child_spec__(handler, opts, socket_options) do
     import Supervisor.Spec
     endpoint = Keyword.fetch!(opts, :endpoint)
+
+    opts = Keyword.merge(socket_options, opts)
     shutdown = Keyword.get(opts, :shutdown, 5_000)
-    partitions = Keyword.get(opts, :partitions) || System.schedulers_online()
+    partitions = Keyword.get(opts, :partitions, System.schedulers_online())
 
     worker_opts = [shutdown: shutdown, restart: :temporary]
     worker = worker(Phoenix.Channel.Server, [], worker_opts)
@@ -412,7 +421,7 @@ defmodule Phoenix.Socket do
     supervisor(Phoenix.Socket.PoolSupervisor, [args], id: handler)
   end
 
-  def __connect__(user_socket, map, log) do
+  def __connect__(user_socket, map, socket_options) do
     %{
       endpoint: endpoint,
       options: options,
@@ -420,7 +429,10 @@ defmodule Phoenix.Socket do
       params: params,
       connect_info: connect_info
     } = map
+
     vsn = params["vsn"] || "1.0.0"
+    options = Keyword.merge(socket_options, options)
+    log = Keyword.get(options, :log, :info)
     meta = Map.merge(map, %{vsn: vsn, user_socket: user_socket, log: log})
 
     Phoenix.Endpoint.instrument(endpoint, :phoenix_socket_connect, meta, fn ->
diff --git a/lib/phoenix/template/eex_engine.ex b/lib/phoenix/template/eex_engine.ex
index 4c76eea30..43fbc373a 100644
--- a/lib/phoenix/template/eex_engine.ex
+++ b/lib/phoenix/template/eex_engine.ex
@@ -6,21 +6,22 @@ defmodule Phoenix.Template.EExEngine do
   @behaviour Phoenix.Template.Engine
 
   def compile(path, name) do
-    EEx.compile_file(path, engine: engine_for(name), line: 1, trim: true)
+    EEx.compile_file(path, [line: 1] ++ options_for(name))
   end
 
-  defp engine_for(name) do
+  defp options_for(name) do
     case Phoenix.Template.format_encoder(name) do
       Phoenix.HTML.Engine ->
         unless Code.ensure_loaded?(Phoenix.HTML.Engine) do
           raise "could not load Phoenix.HTML.Engine to use with .html.eex templates. " <>
-                "You can configure your own format encoder for HTML but we recommend " <>
-                "adding phoenix_html as a dependency as it provides XSS protection."
+                  "You can configure your own format encoder for HTML but we recommend " <>
+                  "adding phoenix_html as a dependency as it provides XSS protection."
         end
 
-        Phoenix.HTML.Engine
+        [engine: Phoenix.HTML.Engine, trim: true]
+
       _ ->
-        EEx.SmartEngine
+        [engine: EEx.SmartEngine]
     end
   end
 end


Test patch:
diff --git a/guides/testing/testing.md b/guides/testing/testing.md
index 67e286d8c..f4b243ecb 100644
--- a/guides/testing/testing.md
+++ b/guides/testing/testing.md
@@ -443,8 +443,8 @@ $ mix phx.gen.html Users User users name:string email:string bio:string number_o
 * creating test/hello_web/controllers/user_controller_test.exs
 * creating lib/hello/users/user.ex
 * creating priv/repo/migrations/20180904210841_create_users.exs
-* creating lib/hello/users/users.ex
-* injecting lib/hello/users/users.ex
+* creating lib/hello/users.ex
+* injecting lib/hello/users.ex
 * creating test/hello/users/users_test.exs
 * injecting test/hello/users/users_test.exs
 
diff --git a/guides/testing/testing_channels.md b/guides/testing/testing_channels.md
index 17b947ef1..8acb11f95 100644
--- a/guides/testing/testing_channels.md
+++ b/guides/testing/testing_channels.md
@@ -168,6 +168,8 @@ Since the `handle_in/3` callback for the `"shout"` event just broadcasts the sam
 all subscribers in the `"room:lobby"` should receive the message. To check that, we do
 `assert_broadcast "shout", %{"hello" => "all"}`.
 
+**NOTE:** `assert_broadcast/3` tests that the message was broadcast in the PubSub system.
+  For testing if a client receives a message, use `assert_push/3`
 
 #### Testing an Asynchronous Push from the Server
 
diff --git a/guides/testing/testing_controllers.md b/guides/testing/testing_controllers.md
index 02f1b5031..b70ec844d 100644
--- a/guides/testing/testing_controllers.md
+++ b/guides/testing/testing_controllers.md
@@ -35,8 +35,8 @@ $ mix phx.gen.context Accounts User users name:string email:string:unique passwo
 
 * creating lib/hello/accounts/user.ex
 * creating priv/repo/migrations/20170913155721_create_users.exs
-* creating lib/hello/accounts/accounts.ex
-* injecting lib/hello/accounts/accounts.ex
+* creating lib/hello/accounts.ex
+* injecting lib/hello/accounts.ex
 * creating test/hello/accounts/accounts_test.exs
 * injecting test/hello/accounts/accounts_test.exs
 
@@ -401,7 +401,7 @@ end
 
 We want a HTTP status code of 404 to notify the requester that this resource was not found, as well as an accompanying error message. Notice that we use [`text_response/2`](https://hexdocs.pm/phoenix/Phoenix.ConnTest.html#text_response/2) instead of [`json_response/2`](https://hexdocs.pm/phoenix/Phoenix.ConnTest.html#json_response/2) to assert that the status code is 404 and the response body matches the accompanying error message. You can run this test now to see what happens. You should see that an `Ecto.NoResultsError` is thrown, because there is no such user in the database.
 
-Our controller action needs to handle the error thrown by Ecto. We have two choices here. By default, this will be handled by the [phoenix_ecto](https://github.com/phoenixframework/phoenix_ecto) library, returning a 404. However if we want to show a custom error message, we can create a new `get_user/1` function that does not throw an Ecto error. For this example, we'll take the second path and implement a new `get_user/1` function in the file `lib/hello/accounts/accounts.ex`, just before the `get_user!/1` function:
+Our controller action needs to handle the error thrown by Ecto. We have two choices here. By default, this will be handled by the [phoenix_ecto](https://github.com/phoenixframework/phoenix_ecto) library, returning a 404. However if we want to show a custom error message, we can create a new `get_user/1` function that does not throw an Ecto error. For this example, we'll take the second path and implement a new `get_user/1` function in the file `lib/hello/accounts.ex`, just before the `get_user!/1` function:
 
 ```elixir
 @doc """
diff --git a/guides/testing/testing_schemas.md b/guides/testing/testing_schemas.md
index 71ebfbfc2..bc8cc871e 100644
--- a/guides/testing/testing_schemas.md
+++ b/guides/testing/testing_schemas.md
@@ -476,8 +476,8 @@ bio:string number_of_pets:integer
 * creating test/hello_web/controllers/user_controller_test.exs
 * creating lib/hello/accounts/user.ex
 * creating priv/repo/migrations/20180906212909_create_users.exs
-* creating lib/hello/accounts/accounts.ex
-* injecting lib/hello/accounts/accounts.ex
+* creating lib/hello/accounts.ex
+* injecting lib/hello/accounts.ex
 * creating test/hello/accounts/accounts_test.exs
 * injecting test/hello/accounts/accounts_test.exs
 
diff --git a/lib/phoenix/test/conn_test.ex b/lib/phoenix/test/conn_test.ex
index d7a08b245..ffd002a58 100644
--- a/lib/phoenix/test/conn_test.ex
+++ b/lib/phoenix/test/conn_test.ex
@@ -370,7 +370,7 @@ defmodule Phoenix.ConnTest do
     if given == status do
       body
     else
-      raise "expected response with status #{given}, got: #{status}, with body:\n#{body}"
+      raise "expected response with status #{given}, got: #{status}, with body:\n#{inspect(body)}"
     end
   end
 
diff --git a/test/fixtures/templates/no_trim.text.eex b/test/fixtures/templates/no_trim.text.eex
new file mode 100644
index 000000000..6178391d9
--- /dev/null
+++ b/test/fixtures/templates/no_trim.text.eex
@@ -0,0 +1,3 @@
+<%= 123 %>
+<%= 456 %>
+<%= 789 %>
diff --git a/test/fixtures/templates/trim.html.eex b/test/fixtures/templates/trim.html.eex
new file mode 100644
index 000000000..6178391d9
--- /dev/null
+++ b/test/fixtures/templates/trim.html.eex
@@ -0,0 +1,3 @@
+<%= 123 %>
+<%= 456 %>
+<%= 789 %>
diff --git a/test/phoenix/integration/websocket_channels_test.exs b/test/phoenix/integration/websocket_channels_test.exs
index 526a495e4..66c6bc76e 100644
--- a/test/phoenix/integration/websocket_channels_test.exs
+++ b/test/phoenix/integration/websocket_channels_test.exs
@@ -70,12 +70,13 @@ defmodule Phoenix.Integration.WebSocketChannelsTest do
     def init({payload, from, socket}) do
       case payload["action"] do
         "ok" ->
-          GenServer.reply(from, %{"action" => "ok"})
+          GenServer.reply(from, {:ok, %{"action" => "ok"}})
           {:ok, socket}
 
         "ignore" ->
-          GenServer.reply(from, %{"action" => "ignore"})
-          :ignore
+          GenServer.reply(from, {:error, %{"action" => "ignore"}})
+          send(self(), :stop)
+          {:ok, socket}
 
         "error" ->
           raise "oops"
@@ -86,6 +87,10 @@ defmodule Phoenix.Integration.WebSocketChannelsTest do
       send socket.transport_pid, {:socket_close, self(), :shutdown}
       {:stop, :shutdown, socket}
     end
+
+    def handle_info(:stop, socket) do
+      {:stop, :shutdown, socket}
+    end
   end
 
   defmodule UserSocketConnectInfo do
diff --git a/test/phoenix/router/pipeline_test.exs b/test/phoenix/router/pipeline_test.exs
index 1e0fa83a5..4268857ab 100644
--- a/test/phoenix/router/pipeline_test.exs
+++ b/test/phoenix/router/pipeline_test.exs
@@ -142,7 +142,8 @@ defmodule Phoenix.Router.PipelineTest do
         pipeline :browser do
         end
         scope "/" do
-          pipe_through [:browser, :auth, :browser]
+          pipe_through [:browser, :auth]
+          pipe_through [:browser]
         end
       end
     end
diff --git a/test/phoenix/router/scope_test.exs b/test/phoenix/router/scope_test.exs
index 8adb2974f..1a5d1826c 100644
--- a/test/phoenix/router/scope_test.exs
+++ b/test/phoenix/router/scope_test.exs
@@ -11,6 +11,10 @@ defmodule Phoenix.Router.ScopedRoutingTest do
     def edit(conn, _params), do: text(conn, "api v1 users edit")
     def foo_host(conn, _params), do: text(conn, "foo request from #{conn.host}")
     def baz_host(conn, _params), do: text(conn, "baz request from #{conn.host}")
+    def proxy(conn, _) do
+      {controller, action} = conn.private.proxy_to
+      controller.call(conn, controller.init(action))
+    end
   end
 
   defmodule Router do
@@ -42,6 +46,9 @@ defmodule Phoenix.Router.ScopedRoutingTest do
 
       scope "/v1", alias: V1 do
         resources "/users", UserController, only: [:delete], private: %{private_token: "baz"}
+        get "/noalias", Api.V1.UserController, :proxy,
+          private: %{proxy_to: {scoped_alias(__MODULE__, UserController), :show}},
+          alias: false
       end
     end
 
@@ -192,4 +199,10 @@ defmodule Phoenix.Router.ScopedRoutingTest do
       end
     end
   end
+
+  test "alias false with expanded scoped alias" do
+    conn = call(Router, :get, "/api/v1/noalias")
+    assert conn.status == 200
+    assert conn.resp_body == "api v1 users show"
+  end
 end
diff --git a/test/phoenix/template_test.exs b/test/phoenix/template_test.exs
index 39ea44ed7..d0e60b6f7 100644
--- a/test/phoenix/template_test.exs
+++ b/test/phoenix/template_test.exs
@@ -60,6 +60,11 @@ defmodule Phoenix.TemplateTest do
     end
   end
 
+  test "render eex templates only trim html" do
+    assert {:safe, ["123", "456" | _]} = View.render("trim.html", %{})
+    assert "123\n456\n789\n" = View.render("no_trim.text", %{})
+  end
+
   test "render eex templates sanitizes against xss by default" do
     assert View.render("show.html", %{message: ""}) ==
            {:safe, ["<div>Show! ", [], "</div>\n"]}
diff --git a/test/phoenix/test/conn_test.exs b/test/phoenix/test/conn_test.exs
index d256db748..2269aaee0 100644
--- a/test/phoenix/test/conn_test.exs
+++ b/test/phoenix/test/conn_test.exs
@@ -264,9 +264,14 @@ defmodule Phoenix.Test.ConnTest do
     end
 
     assert_raise RuntimeError,
-                 "expected response with status 200, got: 404, with body:\noops", fn ->
+                 "expected response with status 200, got: 404, with body:\n\"oops\"", fn ->
       build_conn(:get, "/") |> resp(404, "oops") |> response(200)
     end
+
+    assert_raise RuntimeError,
+                 "expected response with status 200, got: 404, with body:\n<<192>>", fn ->
+      build_conn(:get, "/") |> resp(404, <<192>>) |> response(200)
+    end
   end
 
   test "html_response/2" do
@@ -313,7 +318,7 @@ defmodule Phoenix.Test.ConnTest do
       |> json_response(200)
     end
 
-    assert_raise RuntimeError, ~s(expected response with status 200, got: 400, with body:\n{"error": "oh oh"}), fn ->
+    assert_raise RuntimeError, ~s(expected response with status 200, got: 400, with body:\n) <> inspect(~s({"error": "oh oh"})), fn ->
       build_conn(:get, "/")
       |> put_resp_content_type("application/json")
       |> resp(400, ~s({"error": "oh oh"}))