Git Product home page Git Product logo

rack-contrib's Introduction

Rack

Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the bridge between web servers, web frameworks, and web application into a single method call.

The exact details of this are described in the Rack Specification, which all Rack applications should conform to.

Version support

Version Support
3.1.x Bug fixes and security patches.
3.0.x Security patches only.
2.2.x Security patches only.
<= 2.1.x End of support.

Please see the Security Policy for more information.

Rack 3.1

This is the latest version of Rack. It contains bug fixes and security patches. Please check the Change Log for detailed information on specific changes.

Rack 3.0

This version of rack contains significant changes which are detailed in the Upgrade Guide. It is recommended to upgrade to Rack 3 as soon as possible to receive the latest features and security patches.

Rack 2.2

This version of Rack is receiving security patches only, and effort should be made to move to Rack 3.

Starting in Ruby 3.4 the base64 dependency will no longer be a default gem, and may cause a warning or error about base64 being missing. To correct this, add base64 as a dependency to your project.

Installation

Add the rack gem to your application bundle, or follow the instructions provided by a supported web framework:

# Install it generally:
$ gem install rack

# or, add it to your current application gemfile:
$ bundle add rack

If you need features from Rack::Session or bin/rackup please add those gems separately.

$ gem install rack-session rackup

Usage

Create a file called config.ru with the following contents:

run do |env|
  [200, {}, ["Hello World"]]
end

Run this using the rackup gem or another supported web server.

$ gem install rackup
$ rackup

# In another shell:
$ curl http://localhost:9292
Hello World

Supported web servers

Rack is supported by a wide range of servers, including:

You will need to consult the server documentation to find out what features and limitations they may have. In general, any valid Rack app will run the same on all these servers, without changing anything.

Rackup

Rack provides a separate gem, rackup which is a generic interface for running a Rack application on supported servers, which include WEBRick, Puma, Falcon and others.

Supported web frameworks

These frameworks and many others support the Rack Specification:

Available middleware shipped with Rack

Between the server and the framework, Rack can be customized to your applications needs using middleware. Rack itself ships with the following middleware:

  • Rack::CommonLogger for creating Apache-style logfiles.
  • Rack::ConditionalGet for returning Not Modified responses when the response has not changed.
  • Rack::Config for modifying the environment before processing the request.
  • Rack::ContentLength for setting a content-length header based on body size.
  • Rack::ContentType for setting a default content-type header for responses.
  • Rack::Deflater for compressing responses with gzip.
  • Rack::ETag for setting etag header on bodies that can be buffered.
  • Rack::Events for providing easy hooks when a request is received and when the response is sent.
  • Rack::Files for serving static files.
  • Rack::Head for returning an empty body for HEAD requests.
  • Rack::Lint for checking conformance to the Rack Specification.
  • Rack::Lock for serializing requests using a mutex.
  • Rack::MethodOverride for modifying the request method based on a submitted parameter.
  • Rack::Recursive for including data from other paths in the application, and for performing internal redirects.
  • Rack::Reloader for reloading files if they have been modified.
  • Rack::Runtime for including a response header with the time taken to process the request.
  • Rack::Sendfile for working with web servers that can use optimized file serving for file system paths.
  • Rack::ShowException for catching unhandled exceptions and presenting them in a nice and helpful way with clickable backtrace.
  • Rack::ShowStatus for using nice error pages for empty client error responses.
  • Rack::Static for more configurable serving of static files.
  • Rack::TempfileReaper for removing temporary files creating during a request.

All these components use the same interface, which is described in detail in the Rack Specification. These optional components can be used in any way you wish.

Convenience interfaces

If you want to develop outside of existing frameworks, implement your own ones, or develop middleware, Rack provides many helpers to create Rack applications quickly and without doing the same web stuff all over:

  • Rack::Request which also provides query string parsing and multipart handling.
  • Rack::Response for convenient generation of HTTP replies and cookie handling.
  • Rack::MockRequest and Rack::MockResponse for efficient and quick testing of Rack application without real HTTP round-trips.
  • Rack::Cascade for trying additional Rack applications if an application returns a not found or method not supported response.
  • Rack::Directory for serving files under a given directory, with directory indexes.
  • Rack::MediaType for parsing content-type headers.
  • Rack::Mime for determining content-type based on file extension.
  • Rack::RewindableInput for making any IO object rewindable, using a temporary file buffer.
  • Rack::URLMap to route to multiple applications inside the same process.

Configuration

Rack exposes several configuration parameters to control various features of the implementation.

param_depth_limit

Rack::Utils.param_depth_limit = 32 # default

The maximum amount of nesting allowed in parameters. For example, if set to 3, this query string would be allowed:

?a[b][c]=d

but this query string would not be allowed:

?a[b][c][d]=e

Limiting the depth prevents a possible stack overflow when parsing parameters.

multipart_file_limit

Rack::Utils.multipart_file_limit = 128 # default

The maximum number of parts with a filename a request can contain. Accepting too many parts can lead to the server running out of file handles.

The default is 128, which means that a single request can't upload more than 128 files at once. Set to 0 for no limit.

Can also be set via the RACK_MULTIPART_FILE_LIMIT environment variable.

(This is also aliased as multipart_part_limit and RACK_MULTIPART_PART_LIMIT for compatibility)

multipart_total_part_limit

The maximum total number of parts a request can contain of any type, including both file and non-file form fields.

The default is 4096, which means that a single request can't contain more than 4096 parts.

Set to 0 for no limit.

Can also be set via the RACK_MULTIPART_TOTAL_PART_LIMIT environment variable.

Changelog

See CHANGELOG.md.

Contributing

See CONTRIBUTING.md for specific details about how to make a contribution to Rack.

Please post bugs, suggestions and patches to GitHub Issues.

Please check our Security Policy for responsible disclosure and security bug reporting process. Due to wide usage of the library, it is strongly preferred that we manage timing in order to provide viable patches at the time of disclosure. Your assistance in this matter is greatly appreciated.

See Also

rack-contrib

The plethora of useful middleware created the need for a project that collects fresh Rack middleware. rack-contrib includes a variety of add-on components for Rack and it is easy to contribute new modules.

rack-session

Provides convenient session management for Rack.

Thanks

The Rack Core Team, consisting of

and the Rack Alumni

would like to thank:

  • Adrian Madrid, for the LiteSpeed handler.
  • Christoffer Sawicki, for the first Rails adapter and Rack::Deflater.
  • Tim Fletcher, for the HTTP authentication code.
  • Luc Heinrich for the Cookie sessions, the static file handler and bugfixes.
  • Armin Ronacher, for the logo and racktools.
  • Alex Beregszaszi, Alexander Kahn, Anil Wadghule, Aredridel, Ben Alpert, Dan Kubb, Daniel Roethlisberger, Matt Todd, Tom Robinson, Phil Hagelberg, S. Brent Faulkner, Bosko Milekic, Daniel Rodríguez Troitiño, Genki Takiuchi, Geoffrey Grosenbach, Julien Sanchez, Kamal Fariz Mahyuddin, Masayoshi Takahashi, Patrick Aljordm, Mig, Kazuhiro Nishiyama, Jon Bardin, Konstantin Haase, Larry Siden, Matias Korhonen, Sam Ruby, Simon Chiang, Tim Connor, Timur Batyrshin, and Zach Brock for bug fixing and other improvements.
  • Eric Wong, Hongli Lai, Jeremy Kemper for their continuous support and API improvements.
  • Yehuda Katz and Carl Lerche for refactoring rackup.
  • Brian Candler, for Rack::ContentType.
  • Graham Batty, for improved handler loading.
  • Stephen Bannasch, for bug reports and documentation.
  • Gary Wright, for proposing a better Rack::Response interface.
  • Jonathan Buch, for improvements regarding Rack::Response.
  • Armin Röhrl, for tracking down bugs in the Cookie generator.
  • Alexander Kellett for testing the Gem and reviewing the announcement.
  • Marcus Rückert, for help with configuring and debugging lighttpd.
  • The WSGI team for the well-done and documented work they've done and Rack builds up on.
  • All bug reporters and patch contributors not mentioned above.

License

Rack is released under the MIT License.

rack-contrib's People

Contributors

andrykonchin avatar benmanns avatar carlhoerberg avatar cee-dub avatar chrisfrank avatar dentarg avatar gmarik avatar guss77 avatar ioquatix avatar jcrosby avatar jeremy avatar jeremyevans avatar jjb avatar josh avatar judofyr avatar lawrencepit avatar lifo avatar manveru avatar mipearson avatar mpalmer avatar mtodd avatar mynyml avatar olleolleolle avatar paul avatar pka avatar rkh avatar rtomayko avatar runeb avatar sshaw avatar tkareine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rack-contrib's Issues

Doesn't including git-version-bump gem violates MIT license?

it is included git-version-bump in rack-contrib.gemspec file and therefore it is part of any project which rack-contrib use.
Gem git-version-bump is GPL v3. I'm not layer but I guess that this may violates the GPL license of this gem.

Is here anyone who can confirm or disprove it?

lib/rack/contrib.rb not updated for 1.0.0, breaks Rack::ETag autoload

It seems to me like lib/rack/contrib.rb was missed when the 1.0 release was prepared.

It still defines Rack::Contrib.release as "0.9.1" and have an autoload statement for the recently (re)moved Rack::ETag.

The autoload statement seems to break autoloading of Rack::ETag from the rack gem. I'm using latest Ruby Enterprise Edition with Rails 2.3.8, loading Rack::Contrib with a config.gem statement in config/environment.rb.

A workaround for the Rack::ETag issue is to manually 'require "rack/etag"' before you first make use of Rack::ETag, instead of relying on the autoload.

Thread locking errors using Rack::JSONP

I have a very simple API using the Rack::JSONP module and am getting a 503 response with "recursive locking" error on my local development machine, as well as on Heroku. This happens with both Thin and WebBrick. The error happens quite often, sometimes every other request. As soon as I remove the callback= param from the query string, or remove the rack/contrib stuff from config.ru, no more problem. Sorry, don't know much about threads + rack, or why this might be happening.

  • Mac OS 10.7.2 and Heroku Cedar
  • Rails 3.1.3
  • Ruby 1.9.2-p290

My Gemfile (tried several gem versions):

...
gem 'rack-contrib', :git => '[email protected]:rack/rack-contrib.git'
...

My config.ru:

...
require 'rack/contrib'
use Rack::JSONP
...

Sample request:

http://localhost:3000/api/v1/basket_items/new.json?callback=somecallback

My controller is very simple:

class Api::V1::BasketItemsController < Api::V1::BaseController
  respond_to :json

  def new
    respond_with BasketItem.new
  end

end

Sample error from WebBrick:

[2012-01-04 17:53:04] ERROR ThreadError: deadlock; recursive locking
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/lock.rb:14:in `lock'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/lock.rb:14:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.3/lib/action_dispatch/middleware/static.rb:53:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/engine.rb:456:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/railtie/configurable.rb:30:in `method_missing'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/bundler/gems/rack-contrib-acdcb256bb6e/lib/rack/contrib/jsonp.rb:31:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/content_length.rb:14:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/rack/log_tailer.rb:14:in `call'
    /Users/jason/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/handler/webrick.rb:59:in `service'
    /Users/jason/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
    /Users/jason/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
    /Users/jason/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

Sample Heroku error (thin):

2012-01-05T02:03:53+00:00 app[web.1]: !! Unexpected error while processing request: deadlock; recursive locking
2012-01-05T02:03:53+00:00 heroku[router]: Error H13 (Connection closed without response) -> GET grasket-staging.herokuapp.com/api/v1/basket_items/new.json dyno=web.1 queue= wait= service= status=503 bytes=

Undefined method first for nil:NilClass when using Rack::Locale on Safari ("HTTP_ACCEPT_LANGUAGE"=>"en-us")

As detailed in https://github.com/jmettraux/rack_contrib_locale_issue

Previously "reported" in #133

for short:

require 'i18n'
require 'rack'
require 'rack/contrib'

I18n.load_path = Dir['*.yml']
I18n.backend.load_translations

use Rack::Locale

class App

  def self.call(env)

#require 'pp'; pp env
    [ 200, {}, [ 'ok' ] ]
  end
end

run App

with:

GEM
  remote: https://rubygems.org/
  specs:
    i18n (0.8.6)
    rack (1.6.8)
    rack-contrib (1.5.0)
      rack (~> 1.4)

resulting with Safari (HTTP_ACCEPT_LANGUAGE: "en-us") in:

NoMethodError: undefined method `first' for nil:NilClass
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-contrib-1.5.0/lib/rack/contrib/locale.rb:43:in `accept_locale'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-contrib-1.5.0/lib/rack/contrib/locale.rb:13:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/tempfile_reaper.rb:15:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/lint.rb:49:in `_call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/lint.rb:37:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/showexceptions.rb:24:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/commonlogger.rb:33:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/chunked.rb:54:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/content_length.rb:15:in `call'
	/Users/jmettraux/.gem/ruby/2.3.4/gems/rack-1.6.8/lib/rack/handler/webrick.rb:88:in `service'
	/Users/jmettraux/.rubies/ruby-2.3.4/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'
	/Users/jmettraux/.rubies/ruby-2.3.4/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'
	/Users/jmettraux/.rubies/ruby-2.3.4/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'
::1 - - [29/Aug/2017:10:57:33 +0900] "GET / HTTP/1.1" 500 45101 0.0108

Rack::JSONP::VALID_JS_CHARS missing brackets and quotes

Hello,

I'm using callback from Pusher in my app: Pusher.auth_callbacks['1'] and it is currently invalid:

Rack::JSONP::VALID_CALLBACK =~ "Pusher.auth_callbacks['1']"
=> nil

Is there a reason why [, ], ' and " aren't allowed?

Overriding this isn't much of a pain but it takes some time to debug it. I'll be happy to submit a PR if possible.

Cheers.

TryStatic

Hi there,

I'm trying to make use of TryStatic and it seems to work but on every request I get the following:

127.0.0.1 - - [01/Feb/2012 01:44:30] "GET /index.html HTTP/1.1" 304 - 0.0006
ArgumentError: wrong number of arguments (1 for 0)
    /Users/Michael/Desktop/rwm/config.ru:16:in `block (2 levels) in <main>'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-contrib-1.1.0/lib/rack/contrib/try_static.rb:33:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-contrib-1.1.0/lib/rack/contrib/try_static.rb:33:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/lint.rb:48:in `_call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/lint.rb:36:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/showexceptions.rb:24:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/commonlogger.rb:20:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/chunked.rb:43:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/content_length.rb:14:in `call'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:80:in `block in pre_process'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `catch'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `pre_process'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:53:in `process'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:38:in `receive_data'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/backends/base.rb:61:in `start'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/server.rb:159:in `start'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/handler/thin.rb:13:in `run'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/server.rb:265:in `start'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/lib/rack/server.rb:137:in `start'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.4.1/bin/rackup:4:in `<top (required)>'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/bin/rackup:19:in `load'
    /Users/Michael/.rvm/gems/ruby-1.9.3-p0/bin/rackup:19:in `<main>'

The contents of my config.ru are:

require "rack"
require "rack/contrib/try_static"

use Rack::TryStatic,
    :root => "public",
    :urls => ["/"],
    :try  => ['.html', 'index.html', '/index.html']

# otherwise 404 NotFound
run lambda { [404, {'Content-Type' => 'text/html'}, ['Page Not Found']] }

I'm using rack (1.4.1) and rack-contrib (1.1.0) and I run the app using:

rackup

Rack::AcceptFormat has some non-deterministic behaviour

Context: I'm developing a Sinatra application that uses Rack::AcceptFormat to decide which handlers to execute (and so what gets sent back to the user) for an application that processes both YAML and HTML .

On my development/test machine (Ubuntu Hardy), when a request comes through which accepts text/html, the appended extension is .html

On my staging machine (Debian Lenny), the appended extension is instead .htm

The issue is here:
39 extension = Rack::Mime::MIME_TYPES.invert[accept] || @ext

MIME_TYPES has multiple keys with values of 'text/html':
[[".html", "text/html"], [".htm", "text/html"]]

When it's inverted, it seems to be pot luck as to which key ends up on top.

The situation is potentially even worse for text/plain - there are four possible extensions:
[[".log", "text/plain"], [".text", "text/plain"], [".conf", "text/plain"], [".txt", "text/plain"]]

As to how to fix - I guess the simplest behaviour would be to use a subset of Rack::Mime::MIME_TYPES that avoids conflicts. I don't have a patch, because I don't really like the solution - I just can't think of anything else that doesn't change the way this middleware works. Anyone have any other ideas?

Please add a CHANGELOG

I've just ran my weekly bundle outdated, and it signalled 9 gems are outdated in one of my project.
One by one, I reviewed 7 changelogs and updated 7 gems.
The other 2 have no changelogs, so I had to review every single new commit comment, and sometimes diff.
A pain in the keyboard and too much wasted time.
It shouldn't be that way.

JSONP body and headers

Currently, with the JSONP Middleware the client can only retrieve the body of the response (unable to get other headers information)

We are using a customized version of this middleware to get the same structure that Github API uses.

foo({
  "meta": {
    "status": 200,
    "X-RateLimit-Limit": "5000",
    "X-RateLimit-Remaining": "4966",
    "Link": [ // pagination headers and other links
      ["https://api.github.com?page=2", {"rel": "next"}]
    ]
  },
  "data": {
    // the data
  }
})

If you think this could be useful to others I can make the Pull Request.

Obviously, the main problem would be compatibility. So I was thinking adding some configuration:

use Rack::JSONP, format: :body_and_headers

The default would work with the current formatting/padding and the new option would use the other structure.

WDYT?

Problems using a forked branch of this project

I've created a fork of this project, in order to use a modified branch.

In my Rails app, I've set the Gemfile to point to the branch in the fork, as I would normally do it for forked gems:

gem 'rack-contrib', github: '1Pass/rack-contrib', branch: 'jsonp-with-headers'

Due to git-version-bump, I'm having issues deploying this code to Heroku; the push is rejected with the following error message:

remote:        Fetching gem metadata from https://rubygems.org/..............
remote:        Fetching version metadata from https://rubygems.org/...
remote:        Fetching dependency metadata from https://rubygems.org/..
remote:        Fetching git://github.com/1Pass/rack-contrib.git
remote:        Could not find rack-contrib-1.4.0.2.ga7a545a in any of the sources
remote:        Bundler Output: Fetching gem metadata from https://rubygems.org/..............
remote:        Fetching version metadata from https://rubygems.org/...
remote:        Fetching dependency metadata from https://rubygems.org/..
remote:        Fetching git://github.com/1Pass/rack-contrib.git
remote:        Could not find rack-contrib-1.4.0.2.ga7a545a in any of the sources
remote:  !
remote:  !     Failed to install gems via Bundler.
remote:  !
remote:
remote:  !     Push rejected, failed to compile Ruby app

What am I doing wrong?

frozen array: Rack::ResponseHeaders

I'm trying to add a headers to the response.

use Rack::ResponseHeaders do |headers|
  headers['run'] = 'Yes'
end

But an unexpected error was threw

!! Unexpected error while processing request: can't modify frozen array

The value and future of Rack::StaticCache

Rack::StaticCache is sort of reinventing the wheel of middleware that is done better elsewhere. But it's also the sort of thing that is a good candidate to be maintained in rack-contrib (have a good implementation of a widely-used and relatively small feature).

Consider the rails static middleware, https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/static.rb. It is has been actively developed and seems to have identical features and more, and doesn't seem to be rails-specific.

We could...

  1. drop our middleware because it's redundant with rails's (bad option, because then people would have to require action_dispatch in their non-rails projects.)
  2. consider taking ideas from it
  3. copy it entirely because it's better
    a. also submit a patch to rails to use ours for rails 5
    b. a, but put it into rack propper instead of rack-contrib

TBH I haven't thought through if Rack::StaticCache is actually doing anything poorly. But it just seems like the sort of thing that should be well-done by rack-contrib and used in many other places, so I wanted to start a conversation.

Purpose of the project

Background: for a long time there was a maintainer vacuum in rack-contrib. This was brought up in #72, resulting in @chneukirchen adding several people as maintainers. You can see all the maintainers here.

I wonder if we should discuss and document what the purpose of rack-contrib is? If it's for any and all middleware that seem Pretty Useful and are Well Tested, then that means the project can grow and grow, increasing the number of projects that a team of fixed size is responsible for maintaining.

In the rack middleware ecosystem there are three places a middleware can be:

  1. Within rack
  2. In rack-contrib
  3. Out in the wild

n.b. The file structure of the rack project doesn't delineate between code which implements "rack itself" and code which is implementing various middleware, although there isn't really much to "rack itself" anyway I suppose.

What dictates if a library is worthy of being in 1 vs. 2? 2 vs. 3?

I could start to brainstorm some criteria for the future. I wonder if there was any official or unofficial policy which resulted in the current state of the project?

/cc @chneukirchen @rtomayko @jeremy @josh @raggi

Add a default response to Rack::NotFound if no 404 file specified

Currently Rack::NotFound requires that a path to a file be provided, that will be served as the custom 404 page:
https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/not_found.rb

However for some apps a custom 404 page is overkill, so it would be great if Rack::NotFound could provide a default response, to avoid the standard boilerplate seen on so many Stack Overflow posts (most of which also omit the Content-Length, against the recommendation of the spec):

ie this:

use Rack::Static,
  ...
  ...

body = "Not found\n"
headers = {"Content-Type" => "text/html", "Content-Length" => body.size.to_s}
run lambda { |_| [404, headers, [body]] }

Would become:

use Rack::Static,
  ...
  ...

run Rack::NotFound.new

Does this sound like something that would be accepted? :-)

ETag doesn't like a JSON body, even though it's a String

I wrote a quick little Sinatra app to test JSON output, and it works fine, but when I add the Rack::ETag middleware it does not add the ETag header. I suspect the Sinatra and JSON parts of my test may be red herrings, so to speak, but it seems that JSON messes with the ETag middleware.

Content-Length bug of Rack::NotFound

@length = @content.size.to_s
uses size. I think it should be bytesize or use File.binread instead of File.read.

How to reproduce:

config.ru:

# config.ru
require 'rack/contrib'
require 'tempfile'
Tempfile.open do |f|
  f.write '<!DOCTYPE html>'
  f.write '<meta charset=utf-8>'
  f.write '☃ snowman'
  f.close
  run Rack::NotFound.new(f.path)
end

Run rackup and open browser, it shows ☃ snowm (missing last an) in browser, and Read error: #<Rack::Lint::LintError: Content-Length header was 44, but should be 46> in console.

BTW F = ::File is still need instead of using ::File directly? F is used in 1 place now.

TryStatic returns 405 "Method Not Allowed" Error if it can't find the static file

Hi,

I found a bug that when I send a POST/PUT/DELETE request, and TryStatic can't find the static file which matches that path, it will return 405 error instead of going to next middleware.

This is the example how I use it:

  use Rack::TryStatic,
                root: File.expand_path(File.dirname(__FILE__) + '/public'),
                urls: %w[/], try: ['.html', 'index.html', '/index.html']

My gem version:
rack: v1.5.2
rack-contrib: v1.1.0

I've found the root cause is Rack::Static doesn't return 404 error if the request method is not GET or HEAD or OPTION, it returns 405(403 for old version), but in TryStatic, it just judge whether the status code is 404. So bug happens.

Missing value for JSONP callback.

The JSONP middleware will raise a NoMethodError when the callback is nil from the has_callback? method. You can recreate it if you provide a ?callback query string.

I had issues getting the tests running locally, so I'm currently monkey patching it with an added to_s:

require "rack/contrib/jsonp"

module Rack
  class JSONP
    def has_callback?(request)
      request.params.include?("callback") and not request.params["callback"].to_s.empty?
    end
  end
end

bytesize issues

I think

[ 400, { 'Content-Type' => 'text/plain', 'Content-Length' => body.size.to_s }, [body] ]
and
[ 400, { 'Content-Type' => 'text/plain', 'Content-Length' => body.size.to_s }, [body] ]
have same problem of #143 .
And
headers['Content-Length'] = encoded_response.length.to_s
maybe too.

uninitialized constant Rack::CSSHttpRequest

How to replicate?

create new rails app (RoR 3.0.3, ruby 1.8.7)

in config.ru

require ::File.expand_path('../config/environment',  __FILE__)
require 'rack'
require 'rack/contrib'

use Rack::CSSHttpRequest
run Superapp::Application

Rack::JSONP rack-contrib 1.0.1

When specifying the callback parameter with Rack::JSONP in Rails 2.3.x upon the 2nd request an Exception occurs

http://localhost/search-results.json?callback=callme OK 200
http://localhost/fonts/search-results.json?callback=callme
Barfs...
You might have expected an instance of Array.
The error occurred while evaluating nil.include?
/usr/local/lib/ruby/gems/1.8/gems/rack-contrib-1.0.1/lib/rack/contrib/jsonp.rb:44:in is_json?' /usr/local/lib/ruby/gems/1.8/gems/rack-contrib-1.0.1/lib/rack/contrib/jsonp.rb:26:incall'
/usr/local/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/string_coercion.rb:25:in call' /usr/local/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/head.rb:9:incall'
/usr/local/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/methodoverride.rb:24:in `call'

Rack::ProbablyVersioned - Temporary middleware for your APIs to immediately support a /v1/some/path.json prefix to all route calls

New contrib to rack-contrib:

Temporary middleware for your APIs to immediately support a /v1/some/path.json prefix to all route calls.

When you decide to freeze a current API and provide a /v2/ route then you will cease using this middleware and implement /v1/ and /v2/ routing as appropriate to your app.

This middleware provides a placeholder until then so users can be told to use /v1/some/path routes immediately.

Example:

/resource.json -> /resource.json
/v1/resource.json -> /resource.json

Code is on branch http://github.com/drnic/rack-contrib/tree/probably_versioned

JSONP shouldn't change content type in place.

JSONP uses gsub! to change content type. It may have the side effect of changing Rack::Mime::MIME_TYPES['.json'] in place when used, for instance, with Sinatra's content_type :json.

It can be fixed by using gsub instead.

Get rid of tmail dependency....

TMail is a nasty turd pile of poop ;-)

Rack::MailExceptions should be updated to use the new mail gem like ActionMailer 3.x uses. It's a fairly simple fix (I've got a monkey patched version... I can clean it up and update the tests and throw over a pull request).

The main reason for the dependency change is that many Ruby 1.9 users will have issues with TMail (unless they are using the hacked version shipped in in ActionMailer 2.x). The new mail gem works fine on all Ruby versions and with many people now migrating to Rails 3.x and Ruby 1.9 it makes sense to update this.

While ExceptionNotifier exists, it's Rack support was added as an afterthought, and depending on bits of Rails which is not good for users of Sinatra, etc. Further more ExceptionNotifier is not maintained and thus if Rack::MailExceptions was updated, it would be good to encourage users to migrate to it as this works seamlessly across all Rack apps.

Add License information to Gemspec

This will make it show up on rubygems.org. I'm doing due diligence on our gems and need to find out the licenses for all the gems. Having it show up on rubygems.org cuts out the step of having to go to the github repo.

rack-contrib has a runtime dependency for test-spec

rack-contrib has a runtime dependency for test-spec which means that for users with rubygems greater than 1.2.0 (i.e. hopefully everyone) test-spec will be activated when the rack-contrib gem is required. It should be a development dependency like json and tmail.

Rack::Locale doesn't match languages with variants

If my browser sends locales with variants (fr-fr, fr-ca, en-us, en-gb…) they don't match available locales that are generally set with just 2 characters (fr, en…).

> I18n.available_locales
=> [:en, :fr]

> languages_and_qvalues
=> [["fr-fr", "1.0"]]

> I18n.locale
=> :en

It's possible to match like this …

language_and_qvalue = languages_and_qvalues.sort_by { |(locale, qvalue)|
  qvalue.to_f
}.reverse.detect { |(locale, qvalue)|
  if I18n.enforce_available_locales
    locale == '*' \
      || I18n.available_locales.include?(locale.to_sym) \
      || I18n.available_locales.include?(locale[0,2].to_sym)
  else
    true
  end
}

… but the detect method returns the current element fr-ch which is not valid for I18n.locale.

We could truncate the return lang to the first 2 characters, but it would break when fr-ch is an available language with higher precedence than fr-fr or plain fr.

[patch] Rack::Locale : fall into decault_locale if browser's primary locale is not available

Hi,
Thanks a lot for publication of useful tools.

Present Rack::Locale seems to check only primary locale of a browser. I write a patch as follows:

  1. Check a browser's accept languages(locale) in order of priority.
  2. Set the locale of an application to first available one.
  3. If no locale are supported, set it to default_locale.

patch:

--- locale.rb.old       2010-09-26 18:54:43.000000000 +0900
+++ locale.rb   2010-09-26 19:40:04.000000000 +0900
@@ -12,14 +12,14 @@

       # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
       if lang = env["HTTP_ACCEPT_LANGUAGE"]
-        lang = lang.split(",").map { |l|
+        lang.split(",").each { |l|
           l += ';q=1.0' unless l =~ /;q=\d+\.\d+$/
-          l.split(';q=')
-        }.first
-        locale = lang.first.split("-").first
-      else
-        locale = I18n.default_locale
+          locale = l.split(';q=').first.split("-").first.to_sym
+          break if I18n.available_locales.include?(locale)
+          locale = nil
+        }
       end
+      locale ||= I18n.default_locale

       locale = env['rack.locale'] = I18n.locale = locale.to_s
       status, headers, body = @app.call(env)

Rack::Locale strips the culture part of the string, which is useful in some cases

In cases where you would want to display culture specific formatting (like currency between en-US and en-GB) Rack::Locale isn't entirely useful.

In this branch -> http://github.com/rares/rack-contrib/branches/locale_add_full_culture I added some non-default behavior that leaves the culture part of the string intact (so es-MX instead of es).

Also built up the test suite around Rack::Locale a bit.

I apologize for sending a pull request earlier and now this; Just wasn't sure of the contribution policy.

Add times parameter support for Rack::Profiler

Rack::Profiler allows you to set a times parameter globally:

use Rack::Profiler, :times => 100

but this is not granular enough. Some of my pages take 1ms to render, others take 1s. I want to give the times count as part of the URL so I can tune the count per page:

/some_long_page?profile=cpu_time&times=10
/quick?profile=cpu_time&times=10000

StaticCache should allow less than one year expiration

As the cache_duration is given in years it's possible to pass a fraction of a year as :duration parameter, for example 1/365 for one day. But then the Cache-Control header will look like this:

Cache-Control: max-age=86400.0, public

I suggest modifying duration_in_seconds from this

def duration_in_seconds
  60 * 60 * 24 * 365 * @cache_duration
end

to this

def duration_in_seconds
  (60 * 60 * 24 * 365 * @cache_duration).to_i
end

Version bump

Can we get a rack-contrib version bump? The last version bump was over a year ago, but a lot of the files have been changed significantly. For example, Rack::PostBodyContentTypeParser is essentially unusable in the stable version release, but works great on HEAD.

parse_query_parameters behaves differently than Rack::Utils#parse_nested_query

The parse_query_parameters method exhibits behavior different from Rack::Utils#parse_nested_query when receiving a query string containing duplicate keys. Given a params string like "foo=bar&foo=baz", Rack::Utils#parse_nested_query will return the last instance of foo resulting in {"foo" => "baz"}. Given the same parameter string, parse_query_parameters returns the first instance of foo resulting in {"foo" => "bar"}. This difference in behavior causes the Rails check_box form helper to always submit a zero value because of the hidden input rails inserts box the checkbox input.

Rack::ResponseCache wrongly uses 'Content-Type' case-sensitively

I just ran into the following problem with ResponseCache: To ensure that only (x)html and css files are cached, the Content-Type of the response is tested. To this end it checks for res[1]['Content-Type']. But the header fields of the resource I was trying to cache were in lower-case: "content-type" and thus the test failed.

RFC 7230 says that the names of header fields are case-insensitive. Therefore we need to make sure that different casing is allowed in ResponseCache.

As I am still new to Rack and Ruby, I do not know, if a specific function exists for such header fields. As a sufficient fix one could test if res[1]['Content-Type'] existed and else use res[1]['content-type']. I think it is rather unlikely to find other legal versions such as 'cOnTeNt-TyPe'.

Rack::StaticCache should set a Date header

Webkit based browsers still report in Audit panel items are uncacheable, added a Date header and they then respond correctly. Seems this should be part of the StaticCache?

rack/cgi

Hey. Just release rack/cgi guillermo/rack-cgi. It allows you to run cgi scripts, like php, or a more logic thing, git http-backend.

Make sense to clean it and do a pull request here?

undefined method 'instance' with rails 3.1

Hi,

I'm migating a rails 3.0 application to rails 3.1.0.beta1 and I've got an error if I try to use a middleware from rack-contrib.
In config.ru if I require both rack and rack/contrib that work but if I add "use Rack::Locale" the error show's up.

```/home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/railties-3.1.0.beta1/lib/rails/commands/server.rb:46:inapp': undefined method instance' for #Rack::Access:0x00000004e83768 (NoMethodError)
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/rack-1.3.0.beta/lib/rack/server.rb:301:in`wrapped_app'
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/rack-1.3.0.beta/lib/rack/server.rb:252:in `start'
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/railties-3.1.0.beta1/lib/rails/commands/server.rb:69:in`start'
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/railties-3.1.0.beta1/lib/rails/commands.rb:53:in `block in <top (required)>'
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/railties-3.1.0.beta1/lib/rails/commands.rb:48:in`tap'
from /home/titi/.rvm/gems/ruby-1.9.2-p136@boutique/gems/railties-3.1.0.beta1/lib/rails/commands.rb:48:in `<top (required)>'
from script/rails:6:in`require'
from script/rails:6:in `

'


Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.