Class: Racknga::CacheDatabase — racknga - Ranguba

Class: Racknga::CacheDatabase

Inherits:
Object
  • Object
show all
Defined in:
lib/racknga/cache_database.rb

Overview

This is a cache database based on groonga. It is used by Racknga::Middleware::Cache.

Normally, #purge_old_responses is only used for cache maintenance.

Instance Method Summary (collapse)

Constructor Details

- (CacheDatabase) initialize(database_path)

A new instance of CacheDatabase

Parameters:

  • database_path (String)

    the path for cache database.



31
32
33
34
35
# File 'lib/racknga/cache_database.rb', line 31

def initialize(database_path)
  @database_path = database_path
  @context = Groonga::Context.new(:encoding => :none)
  ensure_database
end

Instance Method Details

- (Object) close_database



89
90
91
# File 'lib/racknga/cache_database.rb', line 89

def close_database
  @database.close
end

- (Object) configuration



45
46
47
# File 'lib/racknga/cache_database.rb', line 45

def configuration
  configurations["default"]
end

- (Object) configurations



41
42
43
# File 'lib/racknga/cache_database.rb', line 41

def configurations
  @context["Configurations"]
end

- (Object) ensure_database



79
80
81
82
83
84
85
86
87
# File 'lib/racknga/cache_database.rb', line 79

def ensure_database
  if File.exist?(@database_path)
    @database = Groonga::Database.open(@database_path, :context => @context)
  else
    create_database
  end
  ensure_tables
  ensure_default_configuration
end

- (Object) purge_old_responses

Purges old responses. To clear old caches, you should call this method periodically or after data update.

You can call this method by the different process from your Rack application process. (e.g. cron.) It’s multi process safe.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/racknga/cache_database.rb', line 55

def purge_old_responses
  age_modulo = 2 ** 31 - 1
  age = configuration.age
  previous_age = (age - 1).modulo(age_modulo)
  next_age = (age + 1).modulo(age_modulo)

  target_responses = responses.select do |record|
    record.age == next_age
  end
  target_responses.each do |response|
    response.key.delete
  end
  configuration.age = next_age

  target_responses = responses.select do |record|
    record.age <= previous_age
  end
  target_responses.each do |response|
    response.key.delete
  end

  responses.defrag if responses.respond_to?(:defrag)
end

- (Object) responses



37
38
39
# File 'lib/racknga/cache_database.rb', line 37

def responses
  @context["Responses"]
end