ruevaughn

ruevaughn

Elixir Plugs - question about Plug Modules

Hi everyone, I am very new to the Erlang / Elixir / Phoenix scene, so sorry if i’m posting this in the wrong spot, or my terminology is off, feel free to correct me on anything since i’d rather learn.

I’m currently reading and following along with the “Programming Phoenix” book and have a few question about module plugs.

So far, what I understand is that for a module plug to be a ‘module plug’, it needs two functions, init/1 and call/2.

In the book, we make a module called Rumbl.Auth. This module uses the expected init/1 and call/2 functions, but also adds others, such as login/2, login_by_username_and_pass/4 and some others.

Are these ‘other’ functions (login, and login_by_username_and_pass) relying on call/2 in order to operate properly? Or are they completely isolated and ran independently?

Here is the Plug i’m working on… auth module plug

My question is due to me trying to understand when ‘call’ is actually being executed by Phoenix.

I understand I add the module to my router like so

defmodule Rumbl.Router do
use Rumbl.Web, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug Rumbl.Auth, repo: Rumbl.Repo
  end

But i’m not sure when ‘call’ is actually getting called since I never explicitly call it. Is it getting called every time I run another function within that module? Or does it get called once? I understand init gets called during compile time to set things up for call, and call/2 gets executed at runtime.

I guess i’m confused why ‘call’ is even needed in this case, and why I can’t just treat the module (other than the fact that it needs call/2 to be considered a plug) as a module. Is call there just for the sake of being called a ‘plug’?

I hope my question makes sense. Sorry if it’s something blatant i’m missing. Excited to read any replies. Been really enjoying Functional / Erlang / Elixir / Phoenix so far… I haven’t been this excited to learn something in a long time.

Most Liked

hubertlepicki

hubertlepicki

Phoenix actually never performs the “call” itself as far as I can tell. Phoenix is nothing more than a set of plugs and supporting libraries.

You are right about the init function, it gets called only when app stars. The call function, on the other hand, will be called on each request.

When a HTTP request comes in, Cowboy server is the first that starts handling such request. plug library adds hooks, builds up the chain of plug middlewares, and calls it, I believe here: plug/lib/plug/adapters/cowboy/handler.ex at 2df667389dbaebb0e2102343c8d7a6ed4de6e280 · elixir-plug/plug · GitHub

So, calling “call” happens on each and every request. Moreover, those calls get nested so a pipeline of plugs get processed by some macro (plug/lib/plug/builder.ex at main · elixir-plug/plug · GitHub) and when one call finishes, another call is executed, until some plug returns a valid response, in such case it is halted, response returned to the browser by cowboy. You don’t have to manually call upstream plugs because of smart macros that do it for us.

Basically, a request comes in → cowboy handler executed → plug1.call() → plug2.call() → plug3.call() etc.

OvermindDL1

OvermindDL1

Actually closer to this (still not perfectly accurate, but keeps the init in this idea):

conn # the initial conn handled by cowboy, passed on to Phoenix
|> accepts(["html"]))
|> fetch_session()
|> fetch_flash()
|> protect_from_forgery()
|> put_secure_browser_headers()
|> Rumbl.Auth.call(Rumbl.Auth.init(repo: Rumbl.Repo))

But yeah, it is the ‘pipeline’ call that does the plugs there. In something like Endpoint the plugs are run via the plug builder that builds the ‘state’. :slight_smile:

bobbypriambodo

bobbypriambodo

You can think of this:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug Rumbl.Auth, repo: Rumbl.Repo
end

will generate this:

conn # the initial conn handled by cowboy, passed on to Phoenix
|> accepts(["html"])
|> fetch_session
|> fetch_flash
|> protect_from_forgery
|> put_secure_browser_headers
|> Rumbl.Auth.call(repo: Rumbl.Repo)

Any request that goes to your app will be run through that pipeline first. You don’t have to explicitly call call/2.

Edit: actually my explanation is missing some details. Before going through the pipeline, the connection from first arrives at the Endpoint and went through a series of Plugs before going to the Router and, subsequently, the pipeline.

Does that make sense?

Where Next?

Popular in Discussions Top

matthias_toepp
I’d love to hear what people think about Wisp, the new Gleam web framework started by Gleam’s primary creator Louis Pilfold. Gleam, alon...
New
vans163
So useless benchmarks aside, Its possible to write a webserver that can serve 300k requests per second (perhaps more with optimizations)....
New
andre1sk
A big advantage to Elixir is all the distributed goodness but for many applications running on multiple nodes having integrated Etcd, Zoo...
New
jeramyRR
This is an interesting article to read. Elixir’s performance, like usual, is excellent. However, it seems like the high CPU usage is co...
New
Fl4m3Ph03n1x
Background This question comes mainly from my ignorance. Today is Black Friday, one of my favorite days of the year to buy books. One boo...
New
nburkley
AWS re:Invent is on at the moment with some interesting announcements. One new feature in particular is the Lambda Runtime API for AWS La...
New
ejpcmac
I have discovered Nix last month and I am currently on my way to migrating to it—both on macOS at home and the full NixOS distrubution at...
New
Qqwy
I would like to spark a discussion about the static access operator: .. For whom does not know: it is used in Elixir to access fields of...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127089 1222
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement