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

#initialize(database_path) ⇒ CacheDatabase

Returns 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

#close_databaseObject



79
80
81
# File 'lib/racknga/cache_database.rb', line 79

def close_database
  @database.close
end

#configurationObject



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

def configuration
  configurations["default"]
end

#configurationsObject



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

def configurations
  @context["Configurations"]
end

#ensure_databaseObject



69
70
71
72
73
74
75
76
77
# File 'lib/racknga/cache_database.rb', line 69

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

#purge_old_responsesObject

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
# File 'lib/racknga/cache_database.rb', line 55

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

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

#responsesObject



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

def responses
  @context["Responses"]
end