What is Rack middleware? What is Rack middleware? ruby ruby

What is Rack middleware?


Rack as Design

Rack middleware is more than "a way to filter a request and response" - it's an implementation of the pipeline design pattern for web servers using Rack.

It very cleanly separates out the different stages of processing a request - separation of concerns being a key goal of all well designed software products.

For example with Rack I can have separate stages of the pipeline doing:

  • Authentication: when the request arrives, are the users logon details correct? How do I validate this OAuth, HTTP Basic Authentication, name/password?

  • Authorisation: "is the user authorised to perform this particular task?", i.e. role-based security.

  • Caching: have I processed this request already, can I return a cached result?

  • Decoration: how can I enhance the request to make downstream processing better?

  • Performance & Usage Monitoring: what stats can I get from the request and response?

  • Execution: actually handle the request and provide a response.

Being able to separate the different stages (and optionally include them) is a great help in developing well structured applications.

Community

There's also a great eco-system developing around Rack Middleware - you should be able to find pre-built rack components to do all of the steps above and more. See the Rack GitHub wiki for a list of middleware.

What's Middleware?

Middleware is a dreadful term which refers to any software component/library which assists with but is not directly involved in the execution of some task. Very common examples are logging, authentication and the other common, horizontal processing components. These tend to be the things that everyone needs across multiple applications but not too many people are interested (or should be) in building themselves.

More Information


First of all, Rack is exactly two things:

  • A webserver interface convention
  • A gem

Rack - The Webserver Interface

The very basics of rack is a simple convention. Every rack compliant webserver will always call a call method on an object you give him and serve the result of that method. Rack specifies exactly how this call method has to look like, and what it has to return. That's rack.

Let's give it a simple try. I'll use WEBrick as rack compliant webserver, but any of them will do. Let's create a simple web application that returns a JSON string. For this we'll create a file called config.ru. The config.ru will automatically be called by the rack gem's command rackup which will simply run the contents of the config.ru in a rack-compliant webserver. So let's add the following to the config.ru file:

class JSONServer  def call(env)    [200, {"Content-Type" => "application/json"}, ['{ "message" : "Hello!" }']]  endendmap '/hello.json' do  run JSONServer.newend

As the convention specifies our server has a method called call that accepts an environment hash and returns an array with the form [status, headers, body] for the webserver to serve. Let's try it out by simply calling rackup. A default rack compliant server, maybe WEBrick or Mongrel will start and immediately wait for requests to serve.

$ rackup[2012-02-19 22:39:26] INFO  WEBrick 1.3.1[2012-02-19 22:39:26] INFO  ruby 1.9.3 (2012-01-17) [x86_64-darwin11.2.0][2012-02-19 22:39:26] INFO  WEBrick::HTTPServer#start: pid=16121 port=9292

Let's test our new JSON server by either curling or visiting the url http://localhost:9292/hello.json and voila:

$ curl http://localhost:9292/hello.json{ message: "Hello!" }

It works. Great! That's the basis for every web framework, be it Rails or Sinatra. At some point they implement a call method, work through all the framework code, and finally return a response in the typical [status, headers, body] form.

In Ruby on Rails for example the rack requests hits the ActionDispatch::Routing.Mapper class which looks like this:

module ActionDispatch  module Routing    class Mapper      ...      def initialize(app, constraints, request)        @app, @constraints, @request = app, constraints, request      end      def matches?(env)        req = @request.new(env)        ...        return true      end      def call(env)        matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]      end      ...  endend

So basically Rails checks, dependent on the env hash if any route matches. If so it passes the env hash on to the application to compute the response, otherwise it immediately responds with a 404. So any webserver that is is compliant with the rack interface convention, is able to serve a fully blown Rails application.

Middleware

Rack also supports the creation of middleware layers. They basically intercept a request, do something with it and pass it on. This is very useful for versatile tasks.

Let's say we want to add logging to our JSON server that also measures how long a request takes. We can simply create a middleware logger that does exactly this:

class RackLogger  def initialize(app)    @app = app  end  def call(env)    @start = Time.now    @status, @headers, @body = @app.call(env)    @duration = ((Time.now - @start).to_f * 1000).round(2)    puts "#{env['REQUEST_METHOD']} #{env['REQUEST_PATH']} - Took: #{@duration} ms"    [@status, @headers, @body]  endend

When it gets created, it saves itself a copy of the actual rack application. In our case that's an instance of our JSONServer. Rack automatically calls the call method on the middleware and expects back a [status, headers, body] array, just like our JSONServer returns.

So in this middleware, the start point is taken, then the actual call to the JSONServer is made with @app.call(env), then the logger outputs the logging entry and finally returns the response as [@status, @headers, @body].

To make our little rackup.ru use this middleware, add a use RackLogger to it like this:

class JSONServer  def call(env)    [200, {"Content-Type" => "application/json"}, ['{ "message" : "Hello!" }']]  endendclass RackLogger  def initialize(app)    @app = app  end  def call(env)    @start = Time.now    @status, @headers, @body = @app.call(env)    @duration = ((Time.now - @start).to_f * 1000).round(2)    puts "#{env['REQUEST_METHOD']} #{env['REQUEST_PATH']} - Took: #{@duration} ms"    [@status, @headers, @body]  endenduse RackLoggermap '/hello.json' do  run JSONServer.newend   

Restart the server and voila, it outputs a log on every request. Rack allows you to add multiple middlewares that are called in the order they are added. It's just a great way to add functionality without changing the core of the rack application.

Rack - The Gem

Although rack - first of all - is a convention it also is a gem that provides great functionality. One of them we already used for our JSON server, the rackup command. But there's more! The rack gem provides little applications for lots of use cases, like serving static files or even whole directories. Let's see how we serve a simple file, for example a very basic HTML file located at htmls/index.html:

<!DOCTYPE HTML>  <html>  <head>    <title>The Index</title>  </head>  <body>    <p>Index Page</p>  </body></html>

We maybe want to serve this file from the website root, so let's add the following to our config.ru:

map '/' do  run Rack::File.new "htmls/index.html"end

If we visit http://localhost:9292 we see our html file perfectly rendered. That's was easy, right?

Let's add a whole directory of javascript files by creating some javascript files under /javascripts and adding the following to the config.ru:

map '/javascripts' do  run Rack::Directory.new "javascripts"end

Restart the server and visit http://localhost:9292/javascript and you'll see a list of all javascript files you can include now straight from anywhere.


I had a problem understanding Rack myself for a good amount of time. I only fully understood it after working on making this miniature Ruby web server myself. I've shared my learnings about Rack (in the form of a story) here on my blog: http://blog.gauravchande.com/what-is-rack-in-ruby-rails

Feedback is more than welcome.