Rack Middleware

Introduction

I want to quickly cover how Rack Middleware works. It's actually much simpler than you probably realise to write your own middleware to handle all sorts of functional requirements.

If you're unsure of what Rack is then this post probably isn't the best starting point. I'll give a very brief description of it (along with a basic example), but I want to focus more on Rack middleware.

To quote the official site (rack.github.io):

Rack provides a minimal interface between webservers supporting Ruby and Ruby frameworks. To use Rack, provide an "app": an object that responds to the call method, taking the environment hash as a parameter, and returning an Array with three elements: the HTTP response code, a Hash of headers, the response body, which must respond to each

Typically you'll have a config.ru file with content like:

run -> env {[200, {"Content-Type" => "text/html"}, ["<h1>Hello World</h1>"]]}

...and to run the webserver (WEBrick by default, but you can use many others) you need to execute rackup via your terminal's shell/command line interface.

If I wanted to use the Puma webserver, instead of the default WEBrick, then I would run rackup -s Puma (as long as I had run gem install puma prior).

The above example demonstrates the most minimalistic implementation by using a Lambda function (that link is to a Gist I wrote a while ago demonstrating Lambda shorthand syntax and other concepts such as partial application and currying).

This works because Ruby's Proc has an internal call method (remember in the above description it stated the object that handles incoming requests must have a call method)

How middleware works

Middleware is a Ruby class whose initialize method is passed the web request handler (in this case our Lambda). The class also needs to have a call method. The call method (when executed) takes the Lambda function we've stored off inside our middleware class, and executes it.

The Lambda is passed the relevant "environment" details of the request as a Hash. The response that's returned by our request handler Lambda is then saved in a variable; and the rest of the call function will consist of code that manipulates that content somehow, before returning it to the client who made the request.

To use our middleware class, we pass the name of the class to Rack's use method like so: use MyMiddleware.

An example will demonstrate this better. The following is a hypothetical config.ru file...

class A
  def self.call(env)
    [200, {"Content-Type" => "text/html"}, ["<h1>Hello World</h1>"]]
  end
end
use D # pass C into this middleware third  (D runs C and manipulates the response from C)
use C # pass B into this middleware second (C runs B and manipulates the response from B)
use B # pass A into this middleware first  (B runs A and manipulates the response from A)
run A

...in this example we can see we have three middleware classes: B, C and D.

When we execute rackup the Rack interface passes our request handler A (this time we're using a Class with a call method rather than the minimalistic Lambda) into the B middleware (remember, middleware is just a Class that stores off the request handler inside the class and has a call method to manipulate the content).

The B middleware will run A from inside its call method, then manipulate the response from A and return that manipulated response; which is then passed into the C middleware and so on up.

We could theorectically inline the use and run calls into the following example...

D(
  C(
    B(A)
  )
)

...the run and use functions work together to create a nested set of calls like seen above.

This means we execute B(A) first and the result is passed to C. From there the result of C is passed into D.

Rack::Builder

The reason we have functions such as use is because the built-in rackup command you use to execute the config.ru is a standalone Rack::Builder runner, which provides use and other methods as a custom DSL.

If we didn't want to use a config.ru file, we could have a Ruby script that uses Rack::Builder directly, like so:

class A
  def self.call(env)
    [200, {"Content-Type" => "text/html"}, ["<h1>Hello World</h1>"]]
  end
end

app = Rack::Builder.new do
  use D
  use C
  use B
  run A
end

Simple example

use Rack::Lint # gives more descriptive error messages when responses aren't valid

class LogIt
  def initialize(app)
    @app = app
  end
  def call(env)
    status, headers, body  = @app.call(env)
    body.map { |chunk| p "LogIt: #{chunk}" }
    [status, headers, body]
  end
end

class Upper
  def initialize(app)
    @app = app
  end
  def call(env)
    # Execute our main application (store off its return value)
    status, headers, body  = @app.call(env)

    # Transform the returned value(s)
    # Remember the body is an Array
    upcased_body = body.map { |chunk| chunk.upcase }

    # Return the newly filtered response
    [status, headers, upcased_body]
  end
end

use LogIt # Does nothing with uppercase'd response, just logs it to stdout
use Upper # Modifies response to be uppercase

run -> env {[200, {"Content-Type" => "text/html"}, ["<h1>Hello World</h1>"]]}

In this example, we're back to using a Lambda, which is passed into our Upper class and the response from that is passed into our LogIt class.

The response from LogIt (which in our example is the same response that came from Upper as we didn't manipulate it in any way, we simply used the LogIt class as a proxy for logging to stdout) is then passed into the 3rd party Rack middleware Rack::Lint which will let us know if our final response is valid or not.

If we were to run this application using rackup -s Puma -p 9293 (or bundle exec puma --port 9293 up to you) then we could use Curl to make a request to the locally running server like so: curl 0.0.0.0:9293.

The response we would get back is: <H1>HELLO WORLD</H1> (and if you were to look at your terminal's stdout you should also see something like:

"LogIt: <H1>HELLO WORLD</H1>"
127.0.0.1 - - [15/Nov/2014 11:21:07] "GET / HTTP/1.1" 200 - 0.0006

Custom Cache Middleware

The inspiration for this section came from @vhokstad who wrote a post about creating your own static asset caching middleware way back in 2008 (http://www.hokstad.com/rack-middleware-adding-cache-headers).

I cleaned up the code a bit and merged it into some test Rack code I have on GitHub.

Fundamentally it comes down to registering the use of the Cache middleware (we'll take a look at that in a moment):

cache_headers = {
  :cache_control => "max-age=2678400, public", # 86400 seconds == 1 day * 31
  :expires => 2678400
}

use Cache, { :assets => cache_headers }

In this example we're passing a Hash into our Middleware class that it'll use as a pattern for matching resources that should be cached. In this case I only have a single key :assets because all my static assets (images, stylesheets and scripts) are kept within that directory:

├── Assets
│   ├── Images
│   │   └── rack-logo.png
│   ├── Scripts
│   │   └── test.js
│   └── Styles
│       └── base.css

But imagine for a moment that you have a different structure (no Assets parent directory):

├── Images
│   ├── rack-logo.png
├── Scripts
│   ├── test.js
├── Styles
│   ├── base.css

...then you would need to change the Hash to:

{
  :images  => cache_headers,
  :scripts => cache_headers,
  :styles  => cache_headers
}

...admittedly we have duplication here because we're specifying the cache_headers variable multiple times (hence why I have all my static assets inside an Assets folder) but it does give you the freedom to apply different caching strategies depending on the type of asset being requested.

Note: you could modify the key to use the Regular Expression alternator character and then reduce the Hash back down to a single key. Something along the lines of :"images|scripts|styles" (you would need to modify the generated_pattern function slightly)

The Cache middleware looks like this...

class Cache
  attr_reader :app, :pattern

  def initialize(app, pattern)
    @app = app
    @pattern = pattern
  end

  def call(env)
    app.call(env).tap do |res|
      pattern.each do |p, config|
        if env["REQUEST_PATH"] =~ generated_pattern(p)
          res[1]["Cache-Control"] = config[:cache_control] if config.has_key? :cache_control
          res[1]["Expires"] = (Time.now + config[:expires]).utc.rfc2822 if config.has_key? :expires
        end
      end
    end
  end

  private

  def generated_pattern(pattern)
    Regexp.new pattern.to_s.capitalize
  end
end

It's the same pattern we've seen before: we store off the app (but this time we also store off the Hash as pattern) and then the call method executes the app and returns it.

But we use tap to access the app object and to modify the headers for each asset requested (i.e. for each image, stylesheet and javascript file).


Links