SlideShare una empresa de Scribd logo
1 de 49
Rails Request
&
Middlewares
Santosh Wadghule | @mechanicles
BigBinary
What is a request?
Request is a…
• It is set of instructions that tells a server what kind
of response we want.
• In simple way, when we hit any url in the browser
for some file, that is your actual request :)
• It is a part of HTTP (request/response) protocol.
• HTTP uses one of the verbs like GET, POST,
PUT & DELETE when you perform the request to
the server.
Rails Request Life Cycle
The Greatest of the Great Greek Geniuses!
Rails Request Life Cycle
Browser
Web Server
App Server
Routes
Controller
Model
View
Database
Rails App
Middlewares
What is a Web Server?
• Web Server is strictly HTTP based, it just takes
HTTP requests and sends back HTTP responses
to the clients(browsers).
• It is mostly designed to serve static files.
• It also has other functionality like request pipeline,
load balancing etc. App servers lack these
functionalities.
• E.g. Ngnix, Apache
What is an App Server?
• App Server actually runs your Rails app.
• App Server is mostly known for to serve dynamic pages.
• Web Server forwards its request to the App Server, and
App Server in turn forwards that request to the Rails app.
• In development mode, App Server can play role of web
server. In production it does not scale too much so we
need web server in between.
• Webrick, Passenger, Mongrel, Unicorn, Thin & etc.
Request to Rails app
• Rails isn’t just one application, it has lots of independent Rack
applications (middlewares).
• When request comes to the Rails app, it goes through the list of
middleware series.
• Last part of that series, sends request to the routes file.
• Based on request, Rails decides which controller & action need to be
executed from the routes.
• After executing the controller’s action, Rails sends back response to the
the client.
• Web Server & App Server actually handle the job of sending response to
the proper client.
What is a Middleware?
• Middleware is Rack application.
• Middleware is basically a filter for request and
response.
• So middlewares isolate the different stages of
processing on the request and response.
Rails Middlewares
Web
Server
Rails App
A B C D
Routes
Controller
Models
Views
Here A, B, C & D are middlewares
Each of these does processing on request & response
Why Rails uses Middlewares?
• Before Rails 3, Rails provides, like handling of session,
parsing for parameters and etc were very tightly coupled.
• As Rails was growing, apps built on Rails had more
demanding requirements. For some apps, Rails gave lots
of additional stuffs by default, which was not required like
cookies/flash. For some other apps, to implement new
filter on the the request/response was not possible.
• In Rails 3 and after, all these issues have got solved by
using a concept of Rack.
Rack
What is a Rack?
• Rack is simple but powerful spec. Yes it is just spec.
• It is not web framework or web server.
• It is an interface that sits between your web server and your application.
It wraps HTTP requests and responses in the simplest way possible, it
unifies and distills the API for web servers, web frameworks and
software in between (i.e. middleware) into a single method call.
• Specification: A Rack application is a Ruby object (not a class) that
responds to `call`. It takes exactly one argument, the environment
and returns an Array of three values, The status, the headers, and the
body. That’s it.
• Rack is created by Christian Neukirchen.
Simple Rack App
Rack it up
What is Rack::Builder?
• Rack::Builder implements a small DSL to iteratively
construct Rack applications.
• Rack::Builder is the thing that glues Rack middlewares and
application together and convert them into single entity/rack
application.
• Under the hood, ‘rackup’ command converts your config.ru
script to an instance of Rack::Builder.
• Think of Rack::Builder object as stack in which your actual
rack application is at bottom and all middlewares on top of
it. The whole stack you can call it as rack application too.
Rails’ Rack::Builder
• Same like Rack::Builder, we have similar concept in Rails,
it is called as ActionDispatch::MiddlewareStack.
• Better flexibility and more features to meet Rails’
requirement.
• Many of Action Dispatcher’s internal components are
implemented as Rack middleware.
• Rails::Application uses
ActionDispatch::MiddlewareStack to combine various
internal and external middlewares to form a complete Rails
Rack application.
Inspecting Rails Middlewares
• Rails provides a task for inspecting the
middleware stack in use.
• $ bin/rake middleware
$ bin/rake middleware
Note: List of the middlewares may be different for your Rails app
Request’s entry to MVC
• When request comes to your Rails app, it goes
through these middlewares. From top to
bottom.
• At the bottom, request enters into the your
Rails’ MVC area.
Lets go through these middlewares and
understand what these middlewares do
Rack::Sendfile
• Sets server specific X-Sendfile header.
• Configure this via
config.action_dispatch.x_sendfile_header option
• The Sendfile middleware intercepts responses whose body
is being served from a file and replaces it with a server
specific X-Sendfile header. The web server is then
responsible for writing the file contents to the client.
• This reduces the amount of work required by the Ruby
backend and takes advantage of the web server's
optimized file delivery code.
ActionDispatch::Static
• This middleware will attempt to return the
contents of a file's body from disk in the
response. If a file is not found on disk, the
request will be delegated to the application
stack. This middleware is commonly initialized
to serve assets from a server's `public/`
directory.
• Used to serve static files. Disabled if
config.serve_static_files is false.
Rack::Lock
• Sets env["rack.multithread"] flag to false
and wraps the application within a Mutex.
• Rack::Lock locks every request inside a mutex,
so that every request will effectively be
executed synchronously.
ActiveSupport::Cache::Strategy::LocalCache::Middleware
• From doc It says, “Caches that implement
LocalCache will be backed by an in-memory
cache for the duration of a block. Repeated
calls to the cache for the same key will hit the
in-memory cache for faster access”.
• This cache is not thread safe.
Rack::Runtime
• Sets an "X-Runtime" response header,
indicating the response time of the request, in
seconds.
Rack::MethodOverride
• Allows the method to be overridden if
params[:_method] is set. This is the middleware
which supports the PUT and DELETE HTTP method
types.
• Rails forms convert PUT/DELTE request into the
POST request and passes the param[:_method]
which may be has values like ‘PUT’ & ‘DELETE’ etc.
• Then this middle converts the post request, into
proper request PUT/DELETE which user has initiated
for.
ActionDispatch::RequestId
• Assigns a unique id to the request.
• Sends back this unique id in X-Request-ID
response header.
Rails::Rack::Logger
• Notifies the logs that the request has began.
After request is complete, flushes all the logs.
ActionDispatch::ShowExceptions
• This middleware rescues any exception
returned by the application and calls an
exceptions app that will wrap it in a format for
the end user.
ActionDispatch::DebugExceptions
• This middleware is responsible for logging
exceptions and showing a debugging page in
case the request is local.
ActionDispatch::RemoteIp
• It captures the remote IP address.
• Checks for IP spoofing attacks.
ActionDispatch::Reloader
• Provides prepare and cleanup callbacks,
intended to assist with code reloading during
development.
ActionDispatch::Callbacks
• Provides callbacks to be executed before and
after dispatching the request.
ActiveRecord::Migration::CheckPending
• Checks pending migrations and raises
ActiveRecord::PendingMigrationError if any
migrations are pending.
ActiveRecord::ConnectionAdapters::ConnectionManagement
• Cleans active connections after each request.
• It will not clean the active connections if
env[‘rack.test’] set to true.
ActiveRecord::QueryCache
• Enables the Active Record query cache for
request.
• It clears the cache after executing the request.
ActionDispatch::Cookies
• Sets cookies for the request.
ActionDispatch::Session::CookieStore
• Responsible for storing the session in cookies.
• It is dramatically faster than the alternatives.
ActionDispatch::Flash
• Sets up the flash keys.
• Only available if
config.action_controller.session_store is
set to a value.
ActionDispatch::ParamsParser
• Parses out parameters from the request into
params.
Rack::Head
• Rack::Head returns an empty body for all
HEAD requests. It leaves all other requests
unchanged.
• Converts HEAD requests to GET requests and
serves them as so.
Rack::ConditionalGet
• Adds support for "Conditional GET" so that
server responds with nothing if page wasn't
changed.
Rack::ETag
• Adds ETag header on all String bodies. ETags
are used to validate cache.
Warden::Manager
• The middleware for Rack Authentication.
• It injects an authentication object into the rack
environment hash
Rack::Deflater
• This middleware enables compression of http
responses.
• Supports these compression algorithms(gzip,
deflate, identity)
RailsRequest::Application.routes
• Here RailsRequest will be different based on your Rails app
• This code returns the instance of ActionDispatch::Routing::RouteSet class
which is also a Rack application.
• After this, request goes to config/routes.rb file and from there it enters into
your MVC.
• Controller creates response & sends back it again to these middlewares stack.
• Middlewares may be can filter that response if necessary.
• Finally response goes to client through the app server & web server.
• How does Rails handle the routes and create the response in a way of [status,
header, body]? Well, that’s the topic for another talk.
Thanks :)

Más contenido relacionado

La actualidad más candente

Winston - Netflix's event driven auto remediation and diagnostics tool
Winston - Netflix's event driven auto remediation and diagnostics toolWinston - Netflix's event driven auto remediation and diagnostics tool
Winston - Netflix's event driven auto remediation and diagnostics toolVinay Shah
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud VMware Tanzu
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarOWASP Delhi
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSAbul Hasan
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails BasicsAmit Solanki
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)iFour Technolab Pvt. Ltd.
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ....NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...NETFest
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdfDevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdfKAI CHU CHUNG
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content RepositoriesCarsten Ziegeler
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 

La actualidad más candente (20)

Winston - Netflix's event driven auto remediation and diagnostics tool
Winston - Netflix's event driven auto remediation and diagnostics toolWinston - Netflix's event driven auto remediation and diagnostics tool
Winston - Netflix's event driven auto remediation and diagnostics tool
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang Bhatnagar
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails Basics
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 
Nodejs vatsal shah
Nodejs vatsal shahNodejs vatsal shah
Nodejs vatsal shah
 
Angular
AngularAngular
Angular
 
Laravel Presentation
Laravel PresentationLaravel Presentation
Laravel Presentation
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ....NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
.NET Fest 2019. Alexandre Malavasi. The future of Web: what Microsoft Blazor ...
 
Log4j2
Log4j2Log4j2
Log4j2
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdfDevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content Repositories
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 

Destacado

Rails Request Response Lifecycle
Rails Request Response LifecycleRails Request Response Lifecycle
Rails Request Response LifecycleIvan Storck
 
Request-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppRequest-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppNathalie Steinmetz
 
Web : Request-Response Lifecycle (Ruby on Rails)
Web : Request-Response Lifecycle (Ruby on Rails)Web : Request-Response Lifecycle (Ruby on Rails)
Web : Request-Response Lifecycle (Ruby on Rails)Rakesh Jha
 
Ruby application based on http
Ruby application based on httpRuby application based on http
Ruby application based on httpRichard Huang
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
React.js & Om: A hands-on walkthrough of better ways to build web UIs
React.js & Om: A hands-on walkthrough of better ways to build web UIsReact.js & Om: A hands-on walkthrough of better ways to build web UIs
React.js & Om: A hands-on walkthrough of better ways to build web UIsAdam Solove
 
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...WalmartLabs
 
Make GUI Apps with Shoes
Make GUI Apps with ShoesMake GUI Apps with Shoes
Make GUI Apps with ShoesBrian Hogan
 
Deployment with Ruby on Rails
Deployment with Ruby on RailsDeployment with Ruby on Rails
Deployment with Ruby on RailsJonathan Weiss
 

Destacado (9)

Rails Request Response Lifecycle
Rails Request Response LifecycleRails Request Response Lifecycle
Rails Request Response Lifecycle
 
Request-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppRequest-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails App
 
Web : Request-Response Lifecycle (Ruby on Rails)
Web : Request-Response Lifecycle (Ruby on Rails)Web : Request-Response Lifecycle (Ruby on Rails)
Web : Request-Response Lifecycle (Ruby on Rails)
 
Ruby application based on http
Ruby application based on httpRuby application based on http
Ruby application based on http
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
React.js & Om: A hands-on walkthrough of better ways to build web UIs
React.js & Om: A hands-on walkthrough of better ways to build web UIsReact.js & Om: A hands-on walkthrough of better ways to build web UIs
React.js & Om: A hands-on walkthrough of better ways to build web UIs
 
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...
How We Do DevOps at Walmart: OneOps OSS Application Lifecycle Management Plat...
 
Make GUI Apps with Shoes
Make GUI Apps with ShoesMake GUI Apps with Shoes
Make GUI Apps with Shoes
 
Deployment with Ruby on Rails
Deployment with Ruby on RailsDeployment with Ruby on Rails
Deployment with Ruby on Rails
 

Similar a Rails Request & Middlewares

Rails request & middlewares
Rails request & middlewaresRails request & middlewares
Rails request & middlewaresSantosh Wadghule
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Rails in the bowels
Rails in the bowelsRails in the bowels
Rails in the bowelsCreditas
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureToru Kawamura
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React EcosystemFITC
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionLecole Cole
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Editionecobold
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt20521742
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemRami Sayar
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 

Similar a Rails Request & Middlewares (20)

Rails request & middlewares
Rails request & middlewaresRails request & middlewares
Rails request & middlewares
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlets
ServletsServlets
Servlets
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Rails in the bowels
Rails in the bowelsRails in the bowels
Rails in the bowels
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the future
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React Ecosystem
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Edition
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Edition
 
Servlets
ServletsServlets
Servlets
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
 
Rack
RackRack
Rack
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 

Último

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Rails Request & Middlewares

  • 2. What is a request?
  • 3. Request is a… • It is set of instructions that tells a server what kind of response we want. • In simple way, when we hit any url in the browser for some file, that is your actual request :) • It is a part of HTTP (request/response) protocol. • HTTP uses one of the verbs like GET, POST, PUT & DELETE when you perform the request to the server.
  • 5. The Greatest of the Great Greek Geniuses!
  • 6. Rails Request Life Cycle Browser Web Server App Server Routes Controller Model View Database Rails App Middlewares
  • 7. What is a Web Server? • Web Server is strictly HTTP based, it just takes HTTP requests and sends back HTTP responses to the clients(browsers). • It is mostly designed to serve static files. • It also has other functionality like request pipeline, load balancing etc. App servers lack these functionalities. • E.g. Ngnix, Apache
  • 8. What is an App Server? • App Server actually runs your Rails app. • App Server is mostly known for to serve dynamic pages. • Web Server forwards its request to the App Server, and App Server in turn forwards that request to the Rails app. • In development mode, App Server can play role of web server. In production it does not scale too much so we need web server in between. • Webrick, Passenger, Mongrel, Unicorn, Thin & etc.
  • 9. Request to Rails app • Rails isn’t just one application, it has lots of independent Rack applications (middlewares). • When request comes to the Rails app, it goes through the list of middleware series. • Last part of that series, sends request to the routes file. • Based on request, Rails decides which controller & action need to be executed from the routes. • After executing the controller’s action, Rails sends back response to the the client. • Web Server & App Server actually handle the job of sending response to the proper client.
  • 10. What is a Middleware? • Middleware is Rack application. • Middleware is basically a filter for request and response. • So middlewares isolate the different stages of processing on the request and response.
  • 11. Rails Middlewares Web Server Rails App A B C D Routes Controller Models Views Here A, B, C & D are middlewares Each of these does processing on request & response
  • 12. Why Rails uses Middlewares? • Before Rails 3, Rails provides, like handling of session, parsing for parameters and etc were very tightly coupled. • As Rails was growing, apps built on Rails had more demanding requirements. For some apps, Rails gave lots of additional stuffs by default, which was not required like cookies/flash. For some other apps, to implement new filter on the the request/response was not possible. • In Rails 3 and after, all these issues have got solved by using a concept of Rack.
  • 13. Rack
  • 14. What is a Rack? • Rack is simple but powerful spec. Yes it is just spec. • It is not web framework or web server. • It is an interface that sits between your web server and your application. It wraps HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks and software in between (i.e. middleware) into a single method call. • Specification: A Rack application is a Ruby object (not a class) that responds to `call`. It takes exactly one argument, the environment and returns an Array of three values, The status, the headers, and the body. That’s it. • Rack is created by Christian Neukirchen.
  • 17. What is Rack::Builder? • Rack::Builder implements a small DSL to iteratively construct Rack applications. • Rack::Builder is the thing that glues Rack middlewares and application together and convert them into single entity/rack application. • Under the hood, ‘rackup’ command converts your config.ru script to an instance of Rack::Builder. • Think of Rack::Builder object as stack in which your actual rack application is at bottom and all middlewares on top of it. The whole stack you can call it as rack application too.
  • 18. Rails’ Rack::Builder • Same like Rack::Builder, we have similar concept in Rails, it is called as ActionDispatch::MiddlewareStack. • Better flexibility and more features to meet Rails’ requirement. • Many of Action Dispatcher’s internal components are implemented as Rack middleware. • Rails::Application uses ActionDispatch::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.
  • 19. Inspecting Rails Middlewares • Rails provides a task for inspecting the middleware stack in use. • $ bin/rake middleware
  • 20. $ bin/rake middleware Note: List of the middlewares may be different for your Rails app
  • 21. Request’s entry to MVC • When request comes to your Rails app, it goes through these middlewares. From top to bottom. • At the bottom, request enters into the your Rails’ MVC area.
  • 22. Lets go through these middlewares and understand what these middlewares do
  • 23. Rack::Sendfile • Sets server specific X-Sendfile header. • Configure this via config.action_dispatch.x_sendfile_header option • The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. The web server is then responsible for writing the file contents to the client. • This reduces the amount of work required by the Ruby backend and takes advantage of the web server's optimized file delivery code.
  • 24. ActionDispatch::Static • This middleware will attempt to return the contents of a file's body from disk in the response. If a file is not found on disk, the request will be delegated to the application stack. This middleware is commonly initialized to serve assets from a server's `public/` directory. • Used to serve static files. Disabled if config.serve_static_files is false.
  • 25. Rack::Lock • Sets env["rack.multithread"] flag to false and wraps the application within a Mutex. • Rack::Lock locks every request inside a mutex, so that every request will effectively be executed synchronously.
  • 26. ActiveSupport::Cache::Strategy::LocalCache::Middleware • From doc It says, “Caches that implement LocalCache will be backed by an in-memory cache for the duration of a block. Repeated calls to the cache for the same key will hit the in-memory cache for faster access”. • This cache is not thread safe.
  • 27. Rack::Runtime • Sets an "X-Runtime" response header, indicating the response time of the request, in seconds.
  • 28. Rack::MethodOverride • Allows the method to be overridden if params[:_method] is set. This is the middleware which supports the PUT and DELETE HTTP method types. • Rails forms convert PUT/DELTE request into the POST request and passes the param[:_method] which may be has values like ‘PUT’ & ‘DELETE’ etc. • Then this middle converts the post request, into proper request PUT/DELETE which user has initiated for.
  • 29. ActionDispatch::RequestId • Assigns a unique id to the request. • Sends back this unique id in X-Request-ID response header.
  • 30. Rails::Rack::Logger • Notifies the logs that the request has began. After request is complete, flushes all the logs.
  • 31. ActionDispatch::ShowExceptions • This middleware rescues any exception returned by the application and calls an exceptions app that will wrap it in a format for the end user.
  • 32. ActionDispatch::DebugExceptions • This middleware is responsible for logging exceptions and showing a debugging page in case the request is local.
  • 33. ActionDispatch::RemoteIp • It captures the remote IP address. • Checks for IP spoofing attacks.
  • 34. ActionDispatch::Reloader • Provides prepare and cleanup callbacks, intended to assist with code reloading during development.
  • 35. ActionDispatch::Callbacks • Provides callbacks to be executed before and after dispatching the request.
  • 36. ActiveRecord::Migration::CheckPending • Checks pending migrations and raises ActiveRecord::PendingMigrationError if any migrations are pending.
  • 37. ActiveRecord::ConnectionAdapters::ConnectionManagement • Cleans active connections after each request. • It will not clean the active connections if env[‘rack.test’] set to true.
  • 38. ActiveRecord::QueryCache • Enables the Active Record query cache for request. • It clears the cache after executing the request.
  • 40. ActionDispatch::Session::CookieStore • Responsible for storing the session in cookies. • It is dramatically faster than the alternatives.
  • 41. ActionDispatch::Flash • Sets up the flash keys. • Only available if config.action_controller.session_store is set to a value.
  • 42. ActionDispatch::ParamsParser • Parses out parameters from the request into params.
  • 43. Rack::Head • Rack::Head returns an empty body for all HEAD requests. It leaves all other requests unchanged. • Converts HEAD requests to GET requests and serves them as so.
  • 44. Rack::ConditionalGet • Adds support for "Conditional GET" so that server responds with nothing if page wasn't changed.
  • 45. Rack::ETag • Adds ETag header on all String bodies. ETags are used to validate cache.
  • 46. Warden::Manager • The middleware for Rack Authentication. • It injects an authentication object into the rack environment hash
  • 47. Rack::Deflater • This middleware enables compression of http responses. • Supports these compression algorithms(gzip, deflate, identity)
  • 48. RailsRequest::Application.routes • Here RailsRequest will be different based on your Rails app • This code returns the instance of ActionDispatch::Routing::RouteSet class which is also a Rack application. • After this, request goes to config/routes.rb file and from there it enters into your MVC. • Controller creates response & sends back it again to these middlewares stack. • Middlewares may be can filter that response if necessary. • Finally response goes to client through the app server & web server. • How does Rails handle the routes and create the response in a way of [status, header, body]? Well, that’s the topic for another talk.