caching.rb 22.3 KB
Newer Older
1 2 3
require 'fileutils'

module ActionController #:nodoc:
4 5 6 7 8 9
  # Caching is a cheap way of speeding up slow applications by keeping the result of calculations, renderings, and database calls
  # around for subsequent requests. Action Controller affords you three approaches in varying levels of granularity: Page, Action, Fragment.
  #
  # You can read more about each approach and the sweeping assistance by clicking the modules below.
  #
  # Note: To turn off all caching and sweeping, set Base.perform_caching = false.
10
  module Caching
11
    def self.included(base) #:nodoc:
12
      base.send(:include, Pages, Actions, Fragments, Sweeping)
13

14 15 16 17
      base.class_eval do
        @@perform_caching = true
        cattr_accessor :perform_caching
      end
18 19
    end

20
    # Page caching is an approach to caching where the entire action output of is stored as a HTML file that the web server
21
    # can serve without going through the Action Pack. This can be as much as 100 times faster than going through the process of dynamically
22 23 24 25
    # generating the content. Unfortunately, this incredible speed-up is only available to stateless pages where all visitors
    # are treated the same. Content management systems -- including weblogs and wikis -- have many pages that are a great fit
    # for this approach, but account-based systems where people log in and manipulate their own data are often less likely candidates.
    #
26
    # Specifying which actions to cache is done through the <tt>caches</tt> class method:
27 28
    #
    #   class WeblogController < ActionController::Base
29
    #     caches_page :show, :new
30 31 32 33 34 35 36 37 38 39 40
    #   end
    #
    # This will generate cache files such as weblog/show/5 and weblog/new, which match the URLs used to trigger the dynamic
    # generation. This is how the web server is able pick up a cache file when it exists and otherwise let the request pass on to
    # the Action Pack to generate it.
    #
    # Expiration of the cache is handled by deleting the cached file, which results in a lazy regeneration approach where the cache
    # is not restored before another hit is made against it. The API for doing so mimics the options from url_for and friends:
    #
    #   class WeblogController < ActionController::Base
    #     def update
41 42 43
    #       List.update(params[:list][:id], params[:list])
    #       expire_page :action => "show", :id => params[:list][:id]
    #       redirect_to :action => "show", :id => params[:list][:id]
44 45 46
    #     end
    #   end
    #
47 48
    # Additionally, you can expire caches using Sweepers that act on changes in the model to determine when a cache is supposed to be
    # expired.
49 50 51 52 53
    #
    # == Setting the cache directory
    #
    # The cache directory should be the document root for the web server and is set using Base.page_cache_directory = "/document/root".
    # For Rails, this directory has already been set to RAILS_ROOT + "/public".
54 55 56 57 58
    #
    # == Setting the cache extension
    #
    # By default, the cache extension is .html, which makes it easy for the cached files to be picked up by the web server. If you want
    # something else, like .php or .shtml, just set Base.page_cache_extension.
59
    module Pages
60
      def self.included(base) #:nodoc:
61 62 63 64
        base.extend(ClassMethods)
        base.class_eval do
          @@page_cache_directory = defined?(RAILS_ROOT) ? "#{RAILS_ROOT}/public" : ""
          cattr_accessor :page_cache_directory
65 66 67

          @@page_cache_extension = '.html'
          cattr_accessor :page_cache_extension
68 69 70 71
        end
      end

      module ClassMethods
72 73 74 75
        # Expires the page that was cached with the +path+ as a key. Example:
        #   expire_page "/lists/show"
        def expire_page(path)
          return unless perform_caching
76 77 78 79

          benchmark "Expired page: #{page_cache_file(path)}" do
            File.delete(page_cache_path(path)) if File.exists?(page_cache_path(path))
          end
80
        end
81

82 83
        # Manually cache the +content+ in the key determined by +path+. Example:
        #   cache_page "I'm the cached content", "/lists/show"
84
        def cache_page(content, path)
85
          return unless perform_caching
86 87 88

          benchmark "Cached page: #{page_cache_file(path)}" do
            FileUtils.makedirs(File.dirname(page_cache_path(path)))
89
            File.open(page_cache_path(path), "wb+") { |f| f.write(content) }
90
          end
91 92
        end

93 94
        # Caches the +actions+ using the page-caching approach that'll store the cache in a path within the page_cache_directory that
        # matches the triggering url.
95
        def caches_page(*actions)
96
          return unless perform_caching
97
          actions.each do |action|
98 99 100
            class_eval "after_filter { |c| c.cache_page if c.action_name == '#{action}' }"
          end
        end
101

102
        private
103
          def page_cache_file(path)
104
            name = ((path.empty? || path == "/") ? "/index" : URI.unescape(path))
105
            name << page_cache_extension unless (name.split('/').last || name).include? '.'
106
            return name
107
          end
108

109
          def page_cache_path(path)
110
            page_cache_directory + page_cache_file(path)
111
          end
112 113
      end

114 115
      # Expires the page that was cached with the +options+ as a key. Example:
      #   expire_page :controller => "lists", :action => "show"
116
      def expire_page(options = {})
117
        return unless perform_caching
118 119
        if options[:action].is_a?(Array)
          options[:action].dup.each do |action|
120
            self.class.expire_page(url_for(options.merge({ :only_path => true, :skip_relative_url_root => true, :action => action })))
121 122
          end
        else
123
          self.class.expire_page(url_for(options.merge({ :only_path => true, :skip_relative_url_root => true })))
124
        end
125 126
      end

127 128 129
      # Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of @response.body is used
      # If no options are provided, the current +options+ for this action is used. Example:
      #   cache_page "I'm the cached content", :controller => "lists", :action => "show"
130
      def cache_page(content = nil, options = {})
131
        return unless perform_caching && caching_allowed
132
        self.class.cache_page(content || @response.body, url_for(options.merge({ :only_path => true, :skip_relative_url_root => true })))
133
      end
134

135 136
      private
        def caching_allowed
137
          !@request.post? && @response.headers['Status'] && @response.headers['Status'].to_i < 400
138
        end
139 140
    end

141
    # Action caching is similar to page caching by the fact that the entire output of the response is cached, but unlike page caching,
142
    # every request still goes through the Action Pack. The key benefit of this is that filters are run before the cache is served, which
143
    # allows for authentication and other restrictions on whether someone is allowed to see the cache. Example:
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    #
    #   class ListsController < ApplicationController
    #     before_filter :authenticate, :except => :public
    #     caches_page   :public
    #     caches_action :show, :feed
    #   end
    #
    # In this example, the public action doesn't require authentication, so it's possible to use the faster page caching method. But both the
    # show and feed action are to be shielded behind the authenticate filter, so we need to implement those as action caches.
    #
    # Action caching internally uses the fragment caching and an around filter to do the job. The fragment cache is named according to both
    # the current host and the path. So a page that is accessed at http://david.somewhere.com/lists/show/1 will result in a fragment named
    # "david.somewhere.com/lists/show/1". This allows the cacher to differentiate between "david.somewhere.com/lists/" and
    # "jamis.somewhere.com/lists/" -- which is a helpful way of assisting the subdomain-as-account-key pattern.
    module Actions
159
      def self.included(base) #:nodoc:
160 161 162 163
        base.extend(ClassMethods)
        base.send(:attr_accessor, :rendered_action_cache)
      end

164
      module ClassMethods #:nodoc:
165
        def caches_action(*actions)
166
          return unless perform_caching
167 168 169 170 171
          around_filter(ActionCacheFilter.new(*actions))
        end
      end

      def expire_action(options = {})
172
        return unless perform_caching
D
David Heinemeier Hansson 已提交
173 174 175 176 177 178 179
        if options[:action].is_a?(Array)
          options[:action].dup.each do |action|
            expire_fragment(url_for(options.merge({ :action => action })).split("://").last)
          end
        else
          expire_fragment(url_for(options).split("://").last)
        end
180 181
      end

D
David Heinemeier Hansson 已提交
182
      class ActionCacheFilter #:nodoc:
183 184 185
        def initialize(*actions)
          @actions = actions
        end
186

187 188
        def before(controller)
          return unless @actions.include?(controller.action_name.intern)
189
          if cache = controller.read_fragment(controller.url_for.split("://").last)
190 191 192 193 194
            controller.rendered_action_cache = true
            controller.send(:render_text, cache)
            false
          end
        end
195

196 197
        def after(controller)
          return if !@actions.include?(controller.action_name.intern) || controller.rendered_action_cache
198
          controller.write_fragment(controller.url_for.split("://").last, controller.response.body)
199 200 201 202 203 204 205 206 207
        end
      end
    end

    # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when
    # certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple
    # parties. The caching is doing using the cache helper available in the Action View. A template with caching might look something like:
    #
    #   <b>Hello <%= @name %></b>
208
    #   <% cache do %>
209 210 211 212
    #     All the topics in the system:
    #     <%= render_collection_of_partials "topic", Topic.find_all %>
    #   <% end %>
    #
213
    # This cache will bind to the name of action that called it. So you would be able to invalidate it using
214 215 216 217
    # <tt>expire_fragment(:controller => "topics", :action => "list")</tt> -- if that was the controller/action used. This is not too helpful
    # if you need to cache multiple fragments per action or if the action itself is cached using <tt>caches_action</tt>. So instead we should
    # qualify the name of the action used with something like:
    #
218
    #   <% cache(:action => "list", :action_suffix => "all_topics") do %>
219 220 221 222 223 224 225 226
    #
    # That would result in a name such as "/topics/list/all_topics", which wouldn't conflict with any action cache and neither with another
    # fragment using a different suffix. Note that the URL doesn't have to really exist or be callable. We're just using the url_for system
    # to generate unique cache names that we can refer to later for expirations. The expiration call for this example would be
    # <tt>expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics")</tt>.
    #
    # == Fragment stores
    #
227 228 229
    # In order to use the fragment caching, you need to designate where the caches should be stored. This is done by assigning a fragment store
    # of which there are four different kinds:
    #
230
    # * FileStore: Keeps the fragments on disk in the +cache_path+, which works well for all types of environments and shares the fragments for
231 232 233 234 235 236
    #   all the web server processes running off the same application directory.
    # * MemoryStore: Keeps the fragments in memory, which is fine for WEBrick and for FCGI (if you don't care that each FCGI process holds its
    #   own fragment store). It's not suitable for CGI as the process is thrown away at the end of each request. It can potentially also take
    #   up a lot of memory since each process keeps all the caches in memory.
    # * DRbStore: Keeps the fragments in the memory of a separate, shared DRb process. This works for all environments and only keeps one cache
    #   around for all processes, but requires that you run and manage a separate DRb process.
237
    # * MemCacheStore: Works like DRbStore, but uses Danga's MemCache instead.
238
    #   Requires the ruby-memcache library:  gem install ruby-memcache.
239 240 241
    #
    # Configuration examples (MemoryStore is the default):
    #
242 243 244 245 246
    #   ActionController::Base.fragment_cache_store = :memory_store
    #   ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
    #   ActionController::Base.fragment_cache_store = :drb_store, "druby://localhost:9192"
    #   ActionController::Base.fragment_cache_store = :mem_cache_store, "localhost"
    #   ActionController::Base.fragment_cache_store = MyOwnStore.new("parameter")
247
    module Fragments
248
      def self.included(base) #:nodoc:
249
        base.class_eval do
250
          @@fragment_cache_store = MemoryStore.new
251 252 253 254 255 256 257
          cattr_reader :fragment_cache_store

          def self.fragment_cache_store=(store_option)
            store, *parameters = *([ store_option ].flatten)
            @@fragment_cache_store = if store.is_a?(Symbol)
              store_class_name = (store == :drb_store ? "DRbStore" : store.to_s.camelize)
              store_class = ActionController::Caching::Fragments.const_get(store_class_name)
258
              store_class.new(*parameters)
259 260 261 262
            else
              store
            end
          end
263 264 265
        end
      end

266
      def fragment_cache_key(name)
267
        name.is_a?(Hash) ? url_for(name).split("://").last : name
268 269
      end

270
      # Called by CacheHelper#cache
271
      def cache_erb_fragment(block, name = {}, options = nil)
272
        unless perform_caching then block.call; return end
273

274
        buffer = eval("_erbout", block.binding)
275 276

        if cache = read_fragment(name, options)
277 278 279
          buffer.concat(cache)
        else
          pos = buffer.length
280
          block.call
281
          write_fragment(name, buffer[pos..-1], options)
282 283
        end
      end
284

285
      def write_fragment(name, content, options = nil)
286 287
        return unless perform_caching

288
        key = fragment_cache_key(name)
289
        self.class.benchmark "Cached fragment: #{key}" do
290 291
          fragment_cache_store.write(key, content, options)
        end
292 293
        content
      end
294

295
      def read_fragment(name, options = nil)
296 297
        return unless perform_caching

298
        key = fragment_cache_key(name)
299
        self.class.benchmark "Fragment read: #{key}" do
300
          fragment_cache_store.read(key, options)
301 302
        end
      end
303

304 305 306
      # Name can take one of three forms:
      # * String: This would normally take the form of a path like "pages/45/notes"
      # * Hash: Is treated as an implicit call to url_for, like { :controller => "pages", :action => "notes", :id => 45 }
307
      # * Regexp: Will destroy all the matched fragments, example: %r{pages/\d*/notes} Ensure you do not specify start and finish in the regex (^$) because the actual filename matched looks like ./cache/filename/path.cache
308
      def expire_fragment(name, options = nil)
309 310
        return unless perform_caching

311
        key = fragment_cache_key(name)
312 313

        if key.is_a?(Regexp)
314
          self.class.benchmark "Expired fragments matching: #{key.source}" do
315 316
            fragment_cache_store.delete_matched(key, options)
          end
317
        else
318
          self.class.benchmark "Expired fragment: #{key}" do
319 320
            fragment_cache_store.delete(key, options)
          end
321
        end
322
      end
323

324
      # Deprecated -- just call expire_fragment with a regular expression
325
      def expire_matched_fragments(matcher = /.*/, options = nil) #:nodoc:
326
        expire_fragment(matcher, options)
327 328
      end

329 330 331 332

      class UnthreadedMemoryStore #:nodoc:
        def initialize #:nodoc:
          @data = {}
333
        end
334

335 336
        def read(name, options=nil) #:nodoc:
          @data[name]
337 338
        end

339 340
        def write(name, value, options=nil) #:nodoc:
          @data[name] = value
341 342
        end

343 344
        def delete(name, options=nil) #:nodoc:
          @data.delete(name)
345
        end
346

347 348 349 350 351
        def delete_matched(matcher, options=nil) #:nodoc:
          @data.delete_if { |k,v| k =~ matcher }
        end
      end

352
      module ThreadSafety #:nodoc:
353 354 355
        def read(name, options=nil) #:nodoc:
          @mutex.synchronize { super }
        end
356

357 358 359
        def write(name, value, options=nil) #:nodoc:
          @mutex.synchronize { super }
        end
360

361 362 363
        def delete(name, options=nil) #:nodoc:
          @mutex.synchronize { super }
        end
364

365 366 367 368 369 370 371 372 373 374 375 376
        def delete_matched(matcher, options=nil) #:nodoc:
          @mutex.synchronize { super }
        end
      end

      class MemoryStore < UnthreadedMemoryStore #:nodoc:
        def initialize #:nodoc:
          super
          if ActionController::Base.allow_concurrency
            @mutex = Mutex.new
            MemoryStore.send(:include, ThreadSafety)
          end
377
        end
378 379
      end

380
      class DRbStore < MemoryStore #:nodoc:
381 382
        attr_reader :address

383
        def initialize(address = 'druby://localhost:9192')
384
          super()
385
          @address = address
386
          @data = DRbObject.new(nil, address)
387
        end
388 389
      end

390
      class MemCacheStore < MemoryStore #:nodoc:
391
        attr_reader :addresses
392

393
        def initialize(*addresses)
394
          super()
395 396 397 398 399
          addresses = addresses.flatten
          addresses = ["localhost"] if addresses.empty?
          @addresses = addresses
          @data = MemCache.new(*addresses)
        end
400 401
      end

402
      class UnthreadedFileStore #:nodoc:
403
        attr_reader :cache_path
404

405 406 407
        def initialize(cache_path)
          @cache_path = cache_path
        end
408

409
        def write(name, value, options = nil) #:nodoc:
410
          ensure_cache_path(File.dirname(real_file_path(name)))
411
          File.open(real_file_path(name), "wb+") { |f| f.write(value) }
412
        rescue => e
413
          Base.logger.error "Couldn't create cache directory: #{name} (#{e.message})" if Base.logger
414 415
        end

416
        def read(name, options = nil) #:nodoc:
417
          File.open(real_file_path(name), 'rb') { |f| f.read } rescue nil
418 419
        end

420
        def delete(name, options) #:nodoc:
421 422
          File.delete(real_file_path(name))
        rescue SystemCallError => e
423
          # If there's no cache, then there's nothing to complain about
424
        end
425

426
        def delete_matched(matcher, options) #:nodoc:
427
          search_dir(@cache_path) do |f|
428
            if f =~ matcher
429
              begin
430 431
                File.delete(f)
              rescue Object => e
432
                # If there's no cache, then there's nothing to complain about
433 434
              end
            end
435 436
          end
        end
437

438
        private
439
          def real_file_path(name)
440
            '%s/%s.cache' % [@cache_path, name.gsub('?', '.').gsub(':', '.')]
441
          end
442

443 444 445
          def ensure_cache_path(path)
            FileUtils.makedirs(path) unless File.exists?(path)
          end
446

447 448 449 450 451 452 453 454
          def search_dir(dir, &callback)
            Dir.foreach(dir) do |d|
              next if d == "." || d == ".."
              name = File.join(dir, d)
              if File.directory?(name)
                search_dir(name, &callback)
              else
                callback.call name
455 456 457
              end
            end
          end
458 459 460 461 462 463 464 465 466 467 468
        end

        class FileStore < UnthreadedFileStore #:nodoc:
          def initialize(cache_path)
            super(cache_path)
            if ActionController::Base.allow_concurrency
              @mutex = Mutex.new
              FileStore.send(:include, ThreadSafety)
            end
          end
        end
469
    end
470

471 472
    # Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change.
    # They do this by being half-observers, half-filters and implementing callbacks for both roles. A Sweeper example:
473
    #
474
    #   class ListSweeper < ActionController::Caching::Sweeper
475
    #     observe List, Item
476
    #
477
    #     def after_save(record)
478 479 480 481
    #       list = record.is_a?(List) ? record : record.list
    #       expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
    #       expire_action(:controller => "lists", :action => "all")
    #       list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
482 483 484
    #     end
    #   end
    #
485
    # The sweeper is assigned in the controllers that wish to have its job performed using the <tt>cache_sweeper</tt> class method:
486 487 488 489 490 491
    #
    #   class ListsController < ApplicationController
    #     caches_action :index, :show, :public, :feed
    #     cache_sweeper :list_sweeper, :only => [ :edit, :destroy, :share ]
    #   end
    #
492
    # In the example above, four actions are cached and three actions are responsible for expiring those caches.
493
    module Sweeping
494
      def self.included(base) #:nodoc:
495 496 497
        base.extend(ClassMethods)
      end

498
      module ClassMethods #:nodoc:
499
        def cache_sweeper(*sweepers)
500
          return unless perform_caching
501
          configuration = sweepers.last.is_a?(Hash) ? sweepers.pop : {}
502
          sweepers.each do |sweeper|
503
            observer(sweeper)
504 505 506 507 508 509 510 511

            sweeper_instance = Object.const_get(Inflector.classify(sweeper)).instance

            if sweeper_instance.is_a?(Sweeper)
              around_filter(sweeper_instance, :only => configuration[:only])
            else
              after_filter(sweeper_instance, :only => configuration[:only])
            end
512 513 514 515
          end
        end
      end
    end
516

517
    if defined?(ActiveRecord) and defined?(ActiveRecord::Observer)
518
      class Sweeper < ActiveRecord::Observer #:nodoc:
519
        attr_accessor :controller
520

521 522
        # ActiveRecord::Observer will mark this class as reloadable even though it should not be.
        # However, subclasses of ActionController::Caching::Sweeper should be Reloadable
523
        include Reloadable::Subclasses
524
        
525 526 527 528 529 530 531
        def before(controller)
          self.controller = controller
          callback(:before)
        end

        def after(controller)
          callback(:after)
532 533
          # Clean up, so that the controller can be collected after this request
          self.controller = nil
534
        end
535

536 537 538 539
        private
          def callback(timing)
            controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}"
            action_callback_method_name     = "#{controller_callback_method_name}_#{controller.action_name}"
540

541 542 543
            send(controller_callback_method_name) if respond_to?(controller_callback_method_name)
            send(action_callback_method_name)     if respond_to?(action_callback_method_name)
          end
544

545
          def method_missing(method, *arguments)
546
            return if @controller.nil?
547 548 549 550
            @controller.send(method, *arguments)
          end
      end
    end
551
  end
552
end