Class: Moneta::Adapters::Couch

Inherits:
Object
  • Object
show all
Includes:
Defaults
Defined in:
lib/moneta/adapters/couch.rb

Overview

CouchDB backend

You can store hashes directly using this adapter.

Examples:

Store hashes

db = Moneta::Adapters::Couch.new
db['key'] = {a: 1, b: 2}

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Defaults

#[], #[]=, #close, #decrement, #features, #fetch, #fetch_values, included, #increment, #supports?, #update

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Couch

Returns a new instance of Couch

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :host (String) — default: '127.0.0.1'

    Couch host

  • :port (String) — default: 5984

    Couch port

  • :db (String) — default: 'moneta'

    Couch database

  • :value_field (String) — default: 'value'

    Document field to store value

  • :type_field (String) — default: 'type'

    Document field to store value type

  • :backend (Faraday connection)

    Use existing backend instance


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/moneta/adapters/couch.rb', line 30

def initialize(options = {})
  @value_field = options[:value_field] || 'value'
  @type_field = options[:type_field] || 'type'
  url = "http://#{options[:host] || '127.0.0.1'}:#{options[:port] || 5984}/#{options[:db] || 'moneta'}"
  @backend = options[:backend] || ::Faraday.new(url: url)
  @rev_cache = Moneta.build do
    use :Lock
    adapter :LRUHash
  end
  create_db
end

Instance Attribute Details

#backendObject (readonly)


19
20
21
# File 'lib/moneta/adapters/couch.rb', line 19

def backend
  @backend
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

  • options (Hash) (defaults to: {})

85
86
87
88
89
# File 'lib/moneta/adapters/couch.rb', line 85

def clear(options = {})
  @backend.delete ''
  create_db
  self
end

#create(key, value, options = {}) ⇒ Boolean

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Atomically sets a key to value if it's not set.

Parameters:

  • key (Object)
  • value (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

Returns:

  • (Boolean)

    key was set


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/moneta/adapters/couch.rb', line 92

def create(key, value, options = {})
  body = value_to_body(value, nil)
  response = @backend.put(key, body, 'Content-Type' => 'application/json')
  update_rev_cache(key, response)
  case response.status
  when 201
    true
  when 409
    false
  else
    raise "HTTP error #{response.status}"
  end
rescue
  tries ||= 0
  (tries += 1) < 10 ? retry : raise
end

#delete(key, options = {}) ⇒ Object

Delete the key from the store and return the current value

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    current value


69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/moneta/adapters/couch.rb', line 69

def delete(key, options = {})
  clear_rev_cache(key)
  get_response = @backend.get(key)
  if get_response.status == 200
    existing_rev = get_response['etag'][1..-2]
    value = body_to_value(get_response.body)
    delete_response = @backend.delete("#{key}?rev=#{existing_rev}")
    raise "HTTP error #{response.status}" unless delete_response.status == 200
    value
  end
rescue
  tries ||= 0
  (tries += 1) < 10 ? retry : raise
end

#each_keyEnumerator #each_key {|key| ... } ⇒ self

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Calls block once for each key in store, passing the key as a parameter. If no block is given, an enumerator is returned instead.

Overloads:

  • #each_keyEnumerator

    Returns An all-the-keys enumerator

    Returns:

    • (Enumerator)

      An all-the-keys enumerator

  • #each_key {|key| ... } ⇒ self

    Yield Parameters:

    • key (Object)

      Each key is yielded to the supplied block

    Returns:

    • (self)

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/moneta/adapters/couch.rb', line 110

def each_key
  return enum_for(:each_key) unless block_given?

  skip = 0
  limit = 1000
  total_rows = 1
  while total_rows > skip do
    response = @backend.get("_all_docs?" + encode_query(limit: limit, skip: skip))
    case response.status
    when 200
      result = MultiJson.load(response.body)
      total_rows = result['total_rows']
      skip += result['rows'].length
      result['rows'].each do |row|
        key = row['id']
        @rev_cache[key] = row['value']['rev']
        yield key
      end
    else
      raise "HTTP error #{response.status}"
    end
  end
  self
end

#key?(key, options = {}) ⇒ Boolean

Exists the value with key

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Boolean)

43
44
45
46
47
# File 'lib/moneta/adapters/couch.rb', line 43

def key?(key, options = {})
  response = @backend.head(key)
  update_rev_cache(key, response)
  response.status == 200
end

#load(key, options = {}) ⇒ Object

Fetch value with key. Return nil if the key doesn't exist

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value


50
51
52
53
54
# File 'lib/moneta/adapters/couch.rb', line 50

def load(key, options = {})
  response = @backend.get(key)
  update_rev_cache(key, response)
  response.status == 200 ? body_to_value(response.body) : nil
end

#merge!(pairs, options = {}) ⇒ self #merge!(pairs, options = {}) {|key, old_value, new_value| ... } ⇒ self

Note:

Some adapters may implement this method atomically, or in two passes when a block is provided. The default implmentation uses #key?, #load and #store.

Stores the pairs in the key-value store, and returns itself. When a block is provided, it will be called before overwriting any existing values with the key, old value and supplied value, and the return value of the block will be used in place of the supplied value.

Overloads:

  • #merge!(pairs, options = {}) ⇒ self

    Parameters:

    • pairs (<(Object, Object)>)

      A collection of key-value pairs to store

    • options (Hash) (defaults to: {})

    Returns:

    • (self)
  • #merge!(pairs, options = {}) {|key, old_value, new_value| ... } ⇒ self

    Parameters:

    • pairs (<(Object, Object)>)

      A collection of key-value pairs to store

    • options (Hash) (defaults to: {})

    Yield Parameters:

    • key (Object)

      A key that whose value is being overwritten

    • old_value (Object)

      The existing value which is being overwritten

    • new_value (Object)

      The value supplied in the method call

    Yield Returns:

    • (Object)

      The value to use for overwriting

    Returns:

    • (self)

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/moneta/adapters/couch.rb', line 153

def merge!(pairs, options = {})
  keys = pairs.map { |key, _| key }.to_a
  cache_revs(*keys.reject { |key| @rev_cache[key] })

  if block_given?
    existing = Hash[slice(*keys, **options)]
    pairs = pairs.map do |key, new_value|
      [
        key,
        if existing.key?(key)
          yield(key, existing[key], new_value)
        else
          new_value
        end
      ]
    end
  end

  docs = pairs.map { |key, value| value_to_doc(value, @rev_cache[key], key) }.to_a
  body = MultiJson.dump(docs: docs)
  response = @backend.post('_bulk_docs', body, "Content-Type" => "application/json")
  raise "HTTP error #{response.status}" unless response.status == 201
  retries = []
  MultiJson.load(response.body).each do |row|
    if row['ok'] == true
      @rev_cache[row['id']] = row['rev']
    elsif row['error'] == 'conflict'
      clear_rev_cache(row['id'])
      retries << pairs.find { |key, _| key == row['id'] }
    else
      raise "Unrecognised response: #{row}"
    end
  end

  # Recursive call with all conflicts
  if retries.empty?
    self
  else
    merge!(retries, options)
  end
end

#slice(*keys, **options) ⇒ <(Object, Object)>

Note:

The keys in the return value may be the same objects that were supplied (i.e. Object#equal?), or may simply be equal (i.e. Object#==).

Note:

Some adapters may implement this method atomically. The default implmentation uses #values_at.

Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values. Only those keys present in the store will have pairs in the return value. The return value can be any enumerable object that yields pairs, so it could be a hash, but needn't be.

Parameters:

  • keys (<Object>)

    The keys for the values to fetch

  • options (Hash)

Options Hash (**options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (<(Object, Object)>)

    A collection of key-value pairs


142
143
144
145
146
147
148
149
150
# File 'lib/moneta/adapters/couch.rb', line 142

def slice(*keys, **options)
  response = @backend.get('_all_docs?' + encode_query(keys: keys, include_docs: true))
  raise "HTTP error #{response.status}" unless response.status == 200
  docs = MultiJson.load(response.body)
  docs["rows"].map do |row|
    next unless row['doc']
    [row['id'], doc_to_value(row['doc'])]
  end.compact
end

#store(key, value, options = {}) ⇒ Object

Store value with key

Parameters:

  • key (Object)
  • value (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Set expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • value


57
58
59
60
61
62
63
64
65
66
# File 'lib/moneta/adapters/couch.rb', line 57

def store(key, value, options = {})
  body = value_to_body(value, rev(key))
  response = @backend.put(key, body, 'Content-Type' => 'application/json')
  update_rev_cache(key, response)
  raise "HTTP error #{response.status} (PUT /#{key})" unless response.status == 201
  value
rescue
  tries ||= 0
  (tries += 1) < 10 ? retry : raise
end

#values_at(*keys, **options) ⇒ Array<Object, nil>

Note:

Some adapters may implement this method atomically, but the default implementation simply makes repeated calls to #load.

Returns an array containing the values associated with the given keys, in the same order as the supplied keys. If a key is not present in the key-value-store, nil is returned in its place.

Parameters:

  • keys (<Object>)

    The keys for the values to fetch

  • options (Hash)

Options Hash (**options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Array<Object, nil>)

    Array containing the values requested, with nil for missing values


136
137
138
139
# File 'lib/moneta/adapters/couch.rb', line 136

def values_at(*keys, **options)
  hash = Hash[slice(*keys, **options)]
  keys.map { |key| hash[key] }
end