varnish_rails 0.1.0

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 6f08804be17b59401c9033b430e15d56df615b2f96f8280079e06968acd967ee
4
+ data.tar.gz: 6e0e358dda404fa3698423feb6ca40311af9db250a1be90e3536c3317772104a
5
+ SHA512:
6
+ metadata.gz: e9dce1c5889833c2fd7a3a996fa3dc07ddf23c197996b77ad1bd5fd96f4792a686246e6ca4ede6efea634ff62b551c41e61d3f5189929df9a40a284bcf2ecf7a
7
+ data.tar.gz: 7b1405fbbf779f4baf52974cbfd702e75676663ee45a524a50bf73aea036dae5470ff7636e1fffef22577fde7d191155b99b2affc49cc36f0c997abca8c62a24
@@ -0,0 +1,20 @@
1
+ Copyright 2019 Mario Bouchard
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,35 @@
1
+ # varnish_rails
2
+ Add Varnish cache headers to controller actions. Automatically purge instances and models on `after_create`, `after_update` and `after_destroy` callbacks.
3
+
4
+ ## Installation
5
+ 1. Add this line to your application's Gemfile:
6
+
7
+ ```ruby
8
+ gem 'varnish_rails'
9
+ ```
10
+
11
+ 2. Run
12
+ ```bash
13
+ $ bundle install
14
+ ```
15
+
16
+ 3. Install VarnishRails
17
+ ```bash
18
+ $ rails generate varnish_rails:install
19
+ ```
20
+
21
+ ## Configuration
22
+ 1. Complete the `config/initializers/varnish_rails.rb` file.
23
+
24
+ ## Usage
25
+ 1. Add `before_action :set_varnish_headers(max_age_in_seconds)` in controllers that you wanna cache.
26
+
27
+ 2. Add calls to `add_to_varnish_xkey_header(my_collection_or_item)` in the cached controller actions to automatically generate the Varnish xkeys.
28
+
29
+ 3. For models that don't have to be purged automatically, add the following line `is_updated_via_import` to the model. You can then call `MyModel::purge_cache_by_varnish_class_name` to purge all cached pages that use this model.
30
+
31
+ ## Contributing
32
+ - Mario Bouchard
33
+
34
+ ## License
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,27 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'VarnishRails'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.md')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+ require 'bundler/gem_tasks'
18
+
19
+ require 'rake/testtask'
20
+
21
+ Rake::TestTask.new(:test) do |t|
22
+ t.libs << 'test'
23
+ t.pattern = 'test/**/*_test.rb'
24
+ t.verbose = false
25
+ end
26
+
27
+ task default: :test
@@ -0,0 +1,11 @@
1
+ module VarnishRails
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
5
+
6
+ def copy_config_file
7
+ template 'varnish_rails.rb', 'config/initializers/varnish_rails.rb'
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,29 @@
1
+ VarnishRails.configure do |config|
2
+
3
+ # To enable the varnish headers and purge calls
4
+ config.enable = ENV['VARNISH'] == "true" ? true : false
5
+
6
+ # The varnish server URL (ex: http://localhost:6081)
7
+ config.url = ENV['VARNISH_URL']
8
+
9
+ # The header max-age key to used
10
+ config.maxage_key = ENV['VARNISH_MAXAGE_KEY'] || 's-maxage'
11
+
12
+ # The default max-age value
13
+ config.maxage_value = ENV['VARNISH_MAXAGE_VALUE'] || 3600
14
+
15
+ # The xkey length that will be generated
16
+ config.xkey_length = ENV['VARNISH_XKEY_LENGTH'] || 12
17
+
18
+ # The header for the xkey purge
19
+ config.header_xkey_purge = ENV['VARNISH_XKEY_PURGE'] || 'xkey-purge'
20
+
21
+ # The header for the ban purge
22
+ config.header_x_ban_url = ENV['VARNISH_X_BAN_URL'] || 'x-ban-url'
23
+
24
+ # Print requests
25
+ config.print_requests = ENV['VARNISH_PRINT_REQUESTS'] == "true" ? true : false
26
+ end
27
+
28
+ # Flush the Varnish cache when the app starts
29
+ VarnishRailsService::ban_cache('.+') unless File.basename($0) == 'rake'
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :varnish_rails do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,44 @@
1
+ require "varnish_rails/railtie"
2
+ require "varnish_rails/action_controller_methods"
3
+ require "varnish_rails/application_record_methods"
4
+ require "varnish_rails/varnish_rails_service"
5
+ require "varnish_rails/varnish_debug_color"
6
+
7
+ module VarnishRails
8
+
9
+ ActionController::Base.class_eval do
10
+ include ActionControllerMethods
11
+ end
12
+
13
+ application_record_class = defined?(ApplicationRecord) ? ApplicationRecord : ActiveRecord::Base
14
+ application_record_class.class_eval do
15
+ include ApplicationRecordMethods
16
+ end
17
+
18
+ # CONFIGURATION -----------------------------------------------------------------
19
+ class << self
20
+ attr_accessor :configuration
21
+ end
22
+
23
+ def self.configure
24
+ self.configuration ||= Configuration.new
25
+ yield(configuration)
26
+ end
27
+
28
+ class Configuration
29
+ attr_accessor :enable, :url, :maxage_key, :maxage_value, :xkey_length, :header_xkey_purge, :header_x_ban_url, :print_requests
30
+
31
+ def initialize
32
+ @enable = false
33
+ @url = 'http://localhost:6081'
34
+ @maxage_key = 's-maxage'
35
+ @maxage_value = 3600
36
+ @xkey_length = 12
37
+ @header_xkey_purge = 'xkey-purge'
38
+ @header_x_ban_url = 'x-ban-url'
39
+ @print_requests = false
40
+ end
41
+ end
42
+ # CONFIGURATION -----------------------------------------------------------------
43
+
44
+ end
@@ -0,0 +1,34 @@
1
+ module ActionControllerMethods
2
+
3
+ private
4
+
5
+ def set_varnish_headers(max_age_in_seconds=VarnishRails.configuration.maxage_value)
6
+ response.headers['Cache-Control'] = "public, #{VarnishRails.configuration.maxage_key}=#{max_age_in_seconds}" if VarnishRails.configuration.enable
7
+ end
8
+
9
+ def add_to_varnish_xkey_header(*collections)
10
+ return if !VarnishRails.configuration.enable
11
+
12
+ xkey_string = response.headers['xkey'] || ''
13
+ xkey = xkey_string.split(' ')
14
+
15
+ collections.each do |collection|
16
+ if collection.is_a?(ActiveRecord::Relation) || collection.is_a?(Array)
17
+ if collection.length > 0
18
+ my_collection = collection.first
19
+ collection.each { |item| xkey << item.varnish_id }
20
+ end
21
+ elsif collection.present?
22
+ my_collection = collection
23
+ xkey << collection.varnish_id
24
+ end
25
+
26
+ xkey << my_collection.varnish_class_name if my_collection.present?
27
+ xkey = xkey.concat(my_collection.varnish_foreign_keys) if my_collection.present?
28
+ end
29
+
30
+ xkey = xkey.uniq
31
+ response.headers['xkey'] = xkey.join(' ') if xkey.length > 0
32
+ end
33
+
34
+ end
@@ -0,0 +1,95 @@
1
+ module ApplicationRecordMethods
2
+
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+
7
+ # == Extensions ===========================================================
8
+
9
+ # == Constants ============================================================
10
+
11
+ # == Attributes ===========================================================
12
+
13
+ class_attribute :varnish_purge_on_commit
14
+
15
+ # == Callbacks ============================================================
16
+
17
+ after_initialize :varnish_configure
18
+
19
+ after_create :purge_cache_by_varnish_class_name
20
+ after_destroy :purge_cache_by_varnish_class_name
21
+ after_update :purge_cache_by_varnish_id
22
+
23
+ # == Relationships ========================================================
24
+
25
+ # == Validations ==========================================================
26
+
27
+ # == Scopes ===============================================================
28
+
29
+ # == Instance Methods =====================================================
30
+
31
+ def varnish_configure
32
+ self.class.varnish_purge_on_commit = true if self.class.varnish_purge_on_commit.nil?
33
+ end
34
+
35
+ def varnish_class_name
36
+ return self.class.varnish_class_name
37
+ end
38
+
39
+ def varnish_class_name_fk
40
+ return self.class.varnish_class_name_fk
41
+ end
42
+
43
+ def varnish_foreign_keys
44
+ return self.class.varnish_foreign_keys
45
+ end
46
+
47
+ def varnish_id
48
+ return self.class.varnish_encode([self.class.name, id].join('-')) if defined?(id)
49
+ end
50
+
51
+ private
52
+
53
+ def purge_cache_by_varnish_class_name
54
+ self.class.purge_cache_by_varnish_class_name
55
+ end
56
+
57
+ def purge_cache_by_varnish_id
58
+ VarnishRailsService::purge_xkey_cache(varnish_id, varnish_class_name_fk) if (varnish_id.present? && !/.+::Translation/.match(self.class.name) && self.class.varnish_purge_on_commit)
59
+ end
60
+
61
+ # == Class Methods ========================================================
62
+
63
+ def self.varnish_class_name(namespace='')
64
+ class_name = namespace.present? ? [self.name, namespace].join('-') : self.name
65
+ return self.varnish_encode(class_name)
66
+ end
67
+
68
+ def self.varnish_class_name_fk
69
+ return self.varnish_class_name('fk')
70
+ end
71
+
72
+ def self.varnish_foreign_keys
73
+ foreign_keys = []
74
+ classes = self.reflect_on_all_associations.map(&:class_name).select{|c| !/.+::Translation/.match(c)}
75
+ foreign_keys = classes.map(&:constantize).map(&:varnish_class_name_fk) if classes.length > 0
76
+ return foreign_keys
77
+ end
78
+
79
+ def self.purge_cache_by_varnish_class_name
80
+ VarnishRailsService::purge_xkey_cache(self::varnish_class_name, self::varnish_class_name_fk) if self::varnish_purge_on_commit
81
+ end
82
+
83
+ def self.varnish_encode(value)
84
+ Digest::MD5.hexdigest([Rails.application.engine_name, Rails.env, value].join('-'))[0,VarnishRails.configuration.xkey_length]
85
+ end
86
+
87
+ end
88
+
89
+ module ClassMethods
90
+ def is_updated_via_import(value=true)
91
+ self.varnish_purge_on_commit = !value
92
+ end
93
+ end
94
+
95
+ end
@@ -0,0 +1,4 @@
1
+ module VarnishRails
2
+ class Railtie < ::Rails::Railtie
3
+ end
4
+ end
@@ -0,0 +1,7 @@
1
+ class String
2
+
3
+ def varnish_debug_color
4
+ "\e[#{33}m#{self}\e[0m"
5
+ end
6
+
7
+ end
@@ -0,0 +1,78 @@
1
+ class VarnishRailsService
2
+
3
+ # == Extensions ===========================================================
4
+
5
+ require 'net/http'
6
+
7
+ include Singleton
8
+
9
+ # == Constants ============================================================
10
+
11
+ # == Attributes ===========================================================
12
+
13
+ # == Callbacks ============================================================
14
+
15
+ # == Relationships ========================================================
16
+
17
+ # == Validations ==========================================================
18
+
19
+ # == Scopes ===============================================================
20
+
21
+ # == Instance Methods =====================================================
22
+
23
+ # == Class Methods ========================================================
24
+
25
+ def self.purge_xkey_cache(*xkeys)
26
+ return if !VarnishRails.configuration.enable
27
+
28
+ xkey_purge = ''
29
+ xkeys.each do |xkey|
30
+ xkey_purge = xkey_purge + xkey + ' '
31
+ end
32
+ xkey_purge = xkey_purge.strip
33
+
34
+ uri = URI.parse(VarnishRails.configuration.url)
35
+ http_request = Net::HTTPGenericRequest.new("PURGE", false, false, uri)
36
+ http_request[VarnishRails.configuration.header_xkey_purge] = xkey_purge
37
+ req_options = { use_ssl: uri.scheme == "https" }
38
+
39
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
40
+ http.request(http_request)
41
+ end
42
+
43
+ puts "Varnish - purge_xkey_cache - #{xkey_purge}".varnish_debug_color if VarnishRails.configuration.print_requests
44
+ puts response.inspect.varnish_debug_color if VarnishRails.configuration.print_requests
45
+ end
46
+
47
+ def self.purge_cache(url)
48
+ return if !VarnishRails.configuration.enable
49
+
50
+ uri = URI.parse("#{VarnishRails.configuration.url}#{url}")
51
+ http_request = Net::HTTPGenericRequest.new("PURGE", false, false, uri)
52
+ req_options = { use_ssl: uri.scheme == "https" }
53
+
54
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
55
+ http.request(http_request)
56
+ end
57
+
58
+ puts "Varnish - purge_cache - #{url}".varnish_debug_color if VarnishRails.configuration.print_requests
59
+ puts response.inspect.varnish_debug_color if VarnishRails.configuration.print_requests
60
+ end
61
+
62
+ def self.ban_cache(pattern)
63
+ return if !VarnishRails.configuration.enable
64
+
65
+ uri = URI.parse(VarnishRails.configuration.url)
66
+ http_request = Net::HTTPGenericRequest.new("BAN", false, false, uri)
67
+ http_request[VarnishRails.configuration.header_x_ban_url] = pattern
68
+ req_options = { use_ssl: uri.scheme == "https" }
69
+
70
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
71
+ http.request(http_request)
72
+ end
73
+
74
+ puts "Varnish - ban_cache - #{pattern}".varnish_debug_color if VarnishRails.configuration.print_requests
75
+ puts response.inspect.varnish_debug_color if VarnishRails.configuration.print_requests
76
+ end
77
+
78
+ end
@@ -0,0 +1,3 @@
1
+ module VarnishRails
2
+ VERSION = '0.1.0'
3
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: varnish_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - iXmedia
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-04-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '4.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '6'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '4.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '6'
33
+ - !ruby/object:Gem::Dependency
34
+ name: sqlite3
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ description: Add Varnish cache headers to controller actions. Automatically purge
48
+ instances and models on after_create, after_update and after_destroy callbacks.
49
+ email:
50
+ - suivi@ixmedia.com
51
+ executables: []
52
+ extensions: []
53
+ extra_rdoc_files: []
54
+ files:
55
+ - MIT-LICENSE
56
+ - README.md
57
+ - Rakefile
58
+ - lib/generators/varnish_rails/install_generator.rb
59
+ - lib/generators/varnish_rails/templates/varnish_rails.rb
60
+ - lib/tasks/varnish_rails_tasks.rake
61
+ - lib/varnish_rails.rb
62
+ - lib/varnish_rails/action_controller_methods.rb
63
+ - lib/varnish_rails/application_record_methods.rb
64
+ - lib/varnish_rails/railtie.rb
65
+ - lib/varnish_rails/varnish_debug_color.rb
66
+ - lib/varnish_rails/varnish_rails_service.rb
67
+ - lib/varnish_rails/version.rb
68
+ homepage: https://github.com/ixmedia/varnish_rails
69
+ licenses:
70
+ - MIT
71
+ metadata: {}
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ required_rubygems_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ requirements: []
87
+ rubyforge_project:
88
+ rubygems_version: 2.7.6
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: Add Varnish cache headers to controller actions.
92
+ test_files: []