rack-cachely 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitignore ADDED
@@ -0,0 +1,20 @@
1
+ *.log
2
+ .DS_Store
3
+ doc
4
+ tmp
5
+ pkg
6
+ *.gem
7
+ *.pid
8
+ coverage
9
+ coverage.data
10
+ build/*
11
+ *.pbxuser
12
+ *.mode1v3
13
+ .svn
14
+ profile
15
+ .console_history
16
+ .sass-cache/*
17
+ .rake_tasks~
18
+ *.log.lck
19
+ solr/
20
+ myapp/
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rack-cachely.gemspec
4
+ gemspec
5
+
6
+ gem 'activesupport'
7
+ gem 'rspec'
8
+ gem 'fakeweb'
9
+ gem 'vcr'
data/Gemfile.lock ADDED
@@ -0,0 +1,36 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rack-cachely (0.0.1)
5
+ rack
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (3.2.8)
11
+ i18n (~> 0.6)
12
+ multi_json (~> 1.0)
13
+ diff-lcs (1.1.3)
14
+ fakeweb (1.3.0)
15
+ i18n (0.6.1)
16
+ multi_json (1.3.6)
17
+ rack (1.4.1)
18
+ rspec (2.11.0)
19
+ rspec-core (~> 2.11.0)
20
+ rspec-expectations (~> 2.11.0)
21
+ rspec-mocks (~> 2.11.0)
22
+ rspec-core (2.11.1)
23
+ rspec-expectations (2.11.3)
24
+ diff-lcs (~> 1.1.3)
25
+ rspec-mocks (2.11.3)
26
+ vcr (2.2.5)
27
+
28
+ PLATFORMS
29
+ ruby
30
+
31
+ DEPENDENCIES
32
+ activesupport
33
+ fakeweb
34
+ rack-cachely!
35
+ rspec
36
+ vcr
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Mark Bates
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # Rack::Cachely
2
+
3
+ THIS IS A WORK IN PROGRESS!!! DO NOT USE!!!
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'rack-cachely'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install rack-cachely
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Contributing
24
+
25
+ 1. Fork it
26
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
27
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
28
+ 4. Push to the branch (`git push origin my-new-feature`)
29
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ desc "Run tests"
5
+ task :default do
6
+ system "bundle exec rspec"
7
+ end
@@ -0,0 +1,33 @@
1
+ require 'singleton'
2
+ require 'net/http'
3
+ require 'timeout'
4
+ require 'logger'
5
+ require 'fileutils'
6
+ require 'cgi'
7
+ require 'rack'
8
+ require "rack-cachely/version"
9
+ require "rack-cachely/config"
10
+ require "rack-cachely/context"
11
+ require "rack-cachely/store"
12
+ require "rack-cachely/key"
13
+
14
+ module Rack
15
+ class Cachely
16
+
17
+ def initialize(app, options = {})
18
+ @app = app
19
+ self.class.config = Rack::Cachely::Config.new(options)
20
+ end
21
+
22
+ def call(env)
23
+ Context.new(@app).call(env)
24
+ end
25
+
26
+ class << self
27
+
28
+ attr_accessor :config
29
+
30
+ end
31
+
32
+ end
33
+ end
@@ -0,0 +1,36 @@
1
+ module Rack
2
+ class Cachely
3
+ class Config
4
+
5
+ attr_accessor :options
6
+
7
+ def initialize(options = {})
8
+ self.options = options
9
+ self.options[:cachely_api_key] ||= ENV["CACHELY_API_KEY"]
10
+ self.options[:cachely_url] = "#{(self.options[:cachely_url] ||= ENV["CACHELY_URL"])}/v1/cache?_token=#{self.options[:cachely_api_key]}"
11
+ end
12
+
13
+ def method_missing(sym, *args, &block)
14
+ if /(.+)=$/.match(sym.to_s)
15
+ self.options[$1.to_sym] = args[0]
16
+ else
17
+ self.options[sym]
18
+ end
19
+ end
20
+
21
+ def logger
22
+ self.options[:logger] ||= begin
23
+ if Object.const_defined?(:Rails)
24
+ logger = Rails.logger
25
+ else
26
+ path = ::File.expand_path("log", ::File.dirname(__FILE__))
27
+ FileUtils.mkdir_p(path)
28
+ logger = ::Logger.new(::File.join(path, "#{ENV['RACK_ENV']}.log"))
29
+ end
30
+ logger
31
+ end
32
+ end
33
+
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,59 @@
1
+ module Rack
2
+ class Cachely
3
+ class Context
4
+
5
+ def initialize(app)
6
+ @app = app
7
+ end
8
+
9
+ def request
10
+ @request ||= Rack::Request.new(@env.dup.freeze)
11
+ end
12
+
13
+ def call(env)
14
+ @env = env
15
+ if self.perform_caching?
16
+ results = Rack::Cachely::Store.get(key)
17
+ if results
18
+ return results
19
+ end
20
+ end
21
+ results = @app.call(@env)
22
+ if self.perform_caching? && is_cacheable?(results)
23
+ Rack::Cachely::Store.post(key, results, age: @age.to_i)
24
+ end
25
+ return results
26
+ end
27
+
28
+ def perform_caching?
29
+ config = if Kernel.const_defined?(:Rails)
30
+ Rails.application.config.action_controller.perform_caching
31
+ else
32
+ @env['rack-cachely.perform_caching'].to_s == 'true'
33
+ end
34
+ config && request.request_method == 'GET'
35
+ end
36
+
37
+ def is_cacheable?(results)
38
+ return false if results[0].to_i != 200
39
+ headers = results[1]
40
+ control = headers["Cache-Control"]
41
+ if /public/.match(control) && /max-age=(\d+)/.match(control)
42
+ @age = $1
43
+ return true
44
+ end
45
+ return false
46
+ end
47
+
48
+ def key
49
+ @key ||= Rack::Cachely::Key.new(request)
50
+ end
51
+
52
+ def config
53
+ Rack::Cachely.config
54
+ end
55
+
56
+ end
57
+
58
+ end
59
+ end
@@ -0,0 +1,56 @@
1
+ require 'rack/utils'
2
+
3
+ # Borrowed from Rache::Cache
4
+ module Rack
5
+ class Cachely
6
+ class Key
7
+ include Rack::Utils
8
+
9
+ def initialize(request)
10
+ @request = request
11
+ end
12
+
13
+ # Generate a normalized cache key for the request.
14
+ def generate
15
+ @key ||= begin
16
+ parts = []
17
+ parts << @request.scheme << "://"
18
+ parts << @request.host
19
+
20
+ if @request.scheme == "https" && @request.port != 443 ||
21
+ @request.scheme == "http" && @request.port != 80
22
+ parts << ":" << @request.port.to_s
23
+ end
24
+
25
+ parts << @request.script_name
26
+ parts << @request.path_info
27
+
28
+ if qs = query_string
29
+ parts << "?"
30
+ parts << qs
31
+ end
32
+
33
+ parts.join
34
+ end
35
+ end
36
+
37
+ def to_s
38
+ self.generate
39
+ end
40
+
41
+ private
42
+ # Build a normalized query string by alphabetizing all keys/values
43
+ # and applying consistent escaping.
44
+ def query_string
45
+ return nil if @request.query_string.nil?
46
+
47
+ @request.query_string.split(/[&;] */n).
48
+ map { |p| unescape(p).split('=', 2) }.
49
+ sort.
50
+ map { |k,v| "#{escape(k)}=#{escape(v)}" }.
51
+ join('&')
52
+ end
53
+ end
54
+
55
+ end
56
+ end
@@ -0,0 +1,77 @@
1
+ module Rack
2
+ class Cachely
3
+ class Store
4
+ include Singleton
5
+
6
+ def self.method_missing(sym, *args, &block)
7
+ self.instance.send(sym, *args, &block)
8
+ end
9
+
10
+ def get(key)
11
+ remote do
12
+ uri = URI("#{config.cachely_url}&url=#{CGI.escape(key.to_s)}")
13
+ response = Net::HTTP.get_response(uri)
14
+ if config.verbose
15
+ logger.info "Cachely [uri]: #{uri}"
16
+ logger.info "Cachely [response.code]: #{response.code}"
17
+ logger.info "Cachely [response.body]: #{response.body}"
18
+ end
19
+ if response.code.to_i == 200
20
+ headers = {}
21
+ response.each_header do |key, value|
22
+ headers[key] = value
23
+ end
24
+ return [response.code.to_i, headers, StringIO.new(response.body)]
25
+ end
26
+ end
27
+ return nil
28
+ end
29
+
30
+ def post(key, rack, options = {})
31
+ remote do
32
+ body = rack[2].respond_to?(:body) ? rack[2].body : rack[2]
33
+ data = {
34
+ "document[url]" => key,
35
+ "document[status]" => rack[0].to_i,
36
+ "document[body]" => body,
37
+ "document[age]" => options[:age] || 0,
38
+ "_token" => Rack::Cachely.config.cachely_api_key
39
+ }
40
+ rack[1].each do |key, value|
41
+ data["document[headers][#{key}]"] = value
42
+ end
43
+ if config.verbose
44
+ logger.debug "Cachely [data]: #{data.inspect}"
45
+ end
46
+ response = Net::HTTP.post_form(URI(config.cachely_url), data)
47
+ if config.verbose
48
+ logger.debug "Cachely [response.code]: #{response.code}"
49
+ logger.debug "Cachely [response.body]: #{response.body}"
50
+ end
51
+ end
52
+ return true
53
+ end
54
+
55
+ def delete(pattern)
56
+ Net::HTTP.post_form(URI(config.cachely_url), {_method: "DELETE", pattern: pattern, _token: config.cachely_api_key})
57
+ end
58
+
59
+ def remote(&block)
60
+ begin
61
+ Timeout::timeout(0.5, &block)
62
+ rescue Timeout::Error, Errno::ECONNREFUSED => e
63
+ logger.error(e)
64
+ end
65
+ end
66
+
67
+ def config
68
+ Rack::Cachely.config
69
+ end
70
+
71
+ def logger
72
+ Rack::Cachely.config.logger
73
+ end
74
+
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,5 @@
1
+ module Rack
2
+ class Cachely
3
+ VERSION = "0.0.1"
4
+ end
5
+ end
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rack-cachely/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "rack-cachely"
8
+ gem.version = Rack::Cachely::VERSION
9
+ gem.authors = ["Mark Bates"]
10
+ gem.email = ["mark@markbates.com"]
11
+ gem.description = %q{Rack middleware for interfacing with the Cachely page caching service.}
12
+ gem.summary = %q{Rack middleware for interfacing with the Cachely page caching service.}
13
+ gem.homepage = "http://www.cachelyapp.com"
14
+
15
+ gem.files = `git ls-files`.split($/)
16
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.require_paths = ["lib"]
19
+
20
+ gem.add_dependency("rack")
21
+ end
@@ -0,0 +1,24 @@
1
+ require 'spec_helper'
2
+
3
+ describe Rack::Cachely::Config do
4
+
5
+ let(:config) { Rack::Cachely::Config.new(foo: 'bar') }
6
+
7
+ describe "method_missing" do
8
+
9
+ it "returns a value from the options" do
10
+ config.foo.should eql("bar")
11
+ end
12
+
13
+ it "returns nil if there is no value" do
14
+ config.bar.should be_nil
15
+ end
16
+
17
+ it "sets a value into the options" do
18
+ config.foo = 'FOO'
19
+ config.foo.should eql("FOO")
20
+ end
21
+
22
+ end
23
+
24
+ end
@@ -0,0 +1,7 @@
1
+ require 'spec_helper'
2
+
3
+ describe Rack::Cachely::Context do
4
+
5
+
6
+
7
+ end
@@ -0,0 +1,17 @@
1
+ require 'spec_helper'
2
+
3
+ describe Rack::Cachely::Key do
4
+
5
+ let(:key) { Rack::Cachely::Key.new(request) }
6
+
7
+ describe "generate" do
8
+
9
+ let(:request) { double(scheme: "http", host: "example.com", port: 80, script_name: "/foo", path_info: "/bar", query_string: "b=B&a=A") }
10
+
11
+ it "returns a uniformed url" do
12
+ key.to_s.should eql("http://example.com/foo/bar?a=A&b=B")
13
+ end
14
+
15
+ end
16
+
17
+ end
@@ -0,0 +1,80 @@
1
+ require "spec_helper"
2
+
3
+ describe Rack::Cachely::Store do
4
+
5
+ let(:key) { "http://example.com" }
6
+ let(:store) { Rack::Cachely::Store }
7
+
8
+ describe "get" do
9
+
10
+ it "retreives a page from the service" do
11
+ mock = double(code: "200", body: "hello!")
12
+ mock.stub!(:each_header).and_yield("Content-Type", "text/html")
13
+ Net::HTTP.stub!(:get_response).and_return(mock)
14
+
15
+ res = store.get(key)
16
+ res[0].should eql(200)
17
+ res[1].should eql("Content-Type" => "text/html")
18
+ res[2].read.should eql("hello!")
19
+ end
20
+
21
+ it "returns nil if no page is found" do
22
+ Net::HTTP.stub!(:get_response).and_return(double(code: "404"))
23
+
24
+ store.get(key).should be_nil
25
+ end
26
+
27
+ it "rescues from a timeout" do
28
+ Net::HTTP.stub!(:get_response).and_raise(Timeout::Error)
29
+ expect {
30
+ store.get(key).should be_nil
31
+ }.to_not raise_error(Timeout::Error)
32
+ end
33
+
34
+ end
35
+
36
+ describe "post" do
37
+
38
+ let(:rack) { [200, {"Content-Type" => "text/html"}, "hello!"] }
39
+ let(:data) do
40
+ {
41
+ "document[url]" => "http://example.com",
42
+ "document[status]" => 200,
43
+ "document[body]" => "hello!",
44
+ "document[age]" => 30,
45
+ "document[headers][Content-Type]"=>"text/html",
46
+ "_token" => Rack::Cachely.config.cachely_api_key
47
+ }
48
+ end
49
+
50
+ context "pure string" do
51
+
52
+ it "adds a page to the service" do
53
+ Net::HTTP.should_receive(:post_form).with(URI(Rack::Cachely.config.cachely_url), data)
54
+
55
+ store.post(key, rack, age: 30)
56
+ end
57
+
58
+ end
59
+
60
+ context "with .body" do
61
+
62
+ it "adds a page to the service" do
63
+ rack[2] = double(body: "hello!")
64
+ Net::HTTP.should_receive(:post_form).with(URI(Rack::Cachely.config.cachely_url), data)
65
+
66
+ store.post(key, rack, age: 30)
67
+ end
68
+
69
+ end
70
+
71
+ it "rescues from a timeout" do
72
+ Net::HTTP.stub!(:post_form).and_raise(Timeout::Error)
73
+ expect {
74
+ store.post(key, rack, age: 30)
75
+ }.to_not raise_error(Timeout::Error)
76
+ end
77
+
78
+ end
79
+
80
+ end
@@ -0,0 +1,17 @@
1
+ ENV["RACK_ENV"] ||= "test"
2
+
3
+ require 'bundler/setup'
4
+
5
+ require 'rack-cachely' # and any other gems you need
6
+ require 'active_support/core_ext'
7
+ require 'vcr'
8
+
9
+ Dir[File.expand_path(File.join("support", "**", "*.rb"), File.dirname(__FILE__))].each {|f| require f}
10
+
11
+ RSpec.configure do |config|
12
+
13
+ config.before do
14
+ Rack::Cachely.config = Rack::Cachely::Config.new(cachely_api_key: '1234567890', cachely_url: "http://localhost:9292")
15
+ end
16
+
17
+ end
metadata ADDED
@@ -0,0 +1,84 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-cachely
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Mark Bates
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-10-17 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rack
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ description: Rack middleware for interfacing with the Cachely page caching service.
31
+ email:
32
+ - mark@markbates.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - .gitignore
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - lib/rack-cachely.rb
44
+ - lib/rack-cachely/config.rb
45
+ - lib/rack-cachely/context.rb
46
+ - lib/rack-cachely/key.rb
47
+ - lib/rack-cachely/store.rb
48
+ - lib/rack-cachely/version.rb
49
+ - rack-cachely.gemspec
50
+ - spec/rack-cachely/config_spec.rb
51
+ - spec/rack-cachely/context_spec.rb
52
+ - spec/rack-cachely/key_spec.rb
53
+ - spec/rack-cachely/store_spec.rb
54
+ - spec/spec_helper.rb
55
+ homepage: http://www.cachelyapp.com
56
+ licenses: []
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ! '>='
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubyforge_project:
75
+ rubygems_version: 1.8.24
76
+ signing_key:
77
+ specification_version: 3
78
+ summary: Rack middleware for interfacing with the Cachely page caching service.
79
+ test_files:
80
+ - spec/rack-cachely/config_spec.rb
81
+ - spec/rack-cachely/context_spec.rb
82
+ - spec/rack-cachely/key_spec.rb
83
+ - spec/rack-cachely/store_spec.rb
84
+ - spec/spec_helper.rb