Class: Moneta::Adapters::MongoMoped

Inherits:
MongoBase
  • Object
show all
Defined in:
lib/moneta/adapters/mongo/moped.rb

Overview

MongoDB backend

Supports expiration, documents will be automatically removed starting with mongodb >= 2.2 (see /).

You can store hashes directly using this adapter.

Examples:

Store hashes

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

Constant Summary

Constants inherited from MongoBase

Moneta::Adapters::MongoBase::DEFAULT_PORT

Instance Attribute Summary

Attributes inherited from MongoBase

#backend

Attributes included from ExpiresSupport

#default_expires

Instance Method Summary collapse

Methods inherited from MongoBase

#fetch_values, #values_at

Methods included from ExpiresSupport

included

Methods included from Defaults

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

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ MongoMoped

Returns a new instance of MongoMoped.

Parameters:

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

Options Hash (options):

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

    MongoDB collection name

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

    MongoDB server host

  • :user (String)

    Username used to authenticate

  • :password (String)

    Password used to authenticate

  • :port (Integer) — default: MongoDB default port

    MongoDB server port

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

    MongoDB database

  • :expires (Integer)

    Default expiration time

  • :expires_field (String) — default: 'expiresAt'

    Document field to store expiration time

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

    Document field to store value

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

    Document field to store value type

  • :backend (::Moped::Session)

    Use existing backend instance

  • Other (Object)

    options passed to ‘Moped::Session#new`



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/moneta/adapters/mongo/moped.rb', line 32

def initialize(options = {})
  super(options)
  collection = options.delete(:collection) || 'moneta'
  db = options.delete(:db) || 'moneta'
  user = options.delete(:user)
  password = options.delete(:password)
  @backend = options[:backend] ||
    begin
      host = options.delete(:host) || '127.0.0.1'
      port = options.delete(:port) || DEFAULT_PORT
      ::Moped::Session.new(["#{host}:#{port}"])
    end
  @backend.use(db)
  @backend.(user, password) if user && password
  @collection = @backend[collection]
  if @backend.command(buildinfo: 1)['version'] >= '2.2'
    @collection.indexes.create({ @expires_field => 1 }, expireAfterSeconds: 0)
  else
    warn 'Moneta::Adapters::Mongo - You are using MongoDB version < 2.2, expired documents will not be deleted'
  end
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

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


115
116
117
118
# File 'lib/moneta/adapters/mongo/moped.rb', line 115

def clear(options = {})
  @collection.find.remove_all
  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



103
104
105
106
107
108
109
110
111
112
# File 'lib/moneta/adapters/mongo/moped.rb', line 103

def create(key, value, options = {})
  key = to_binary(key)
  @backend.with(safe: true, consistency: :strong) do |safe|
    safe[@collection.name].insert(value_to_doc(key, value, options))
  end
  true
rescue ::Moped::Errors::MongoError => ex
  raise if ex.details['code'] != 11000 # duplicate key error
  false
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



81
82
83
84
85
# File 'lib/moneta/adapters/mongo/moped.rb', line 81

def delete(key, options = {})
  value = load(key, options)
  @collection.find(_id: to_binary(key)).remove if value
  value
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)


74
75
76
77
78
# File 'lib/moneta/adapters/mongo/moped.rb', line 74

def each_key
  return enum_for(:each_key) unless block_given?
  @collection.find.each { |doc| yield from_binary(doc[:_id]) }
  self
end

#increment(key, amount = 1, options = {}) ⇒ Object

Note:

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

Atomically increment integer value with key

This method also accepts negative amounts.

Parameters:

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

Options Hash (options):

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value from store



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/moneta/adapters/mongo/moped.rb', line 88

def increment(key, amount = 1, options = {})
  @backend.with(safe: true, consistency: :strong) do |safe|
    safe[@collection.name]
      .find(_id: to_binary(key))
      .modify({ :$inc => { @value_field => amount } },
              new: true, upsert: true)[@value_field]
  end
rescue ::Moped::Errors::OperationFailure
  tries ||= 0
  tries += 1
  retry if tries < 3
  raise # otherwise
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



55
56
57
58
59
60
61
62
63
64
# File 'lib/moneta/adapters/mongo/moped.rb', line 55

def load(key, options = {})
  key = to_binary(key)
  doc = @collection.find(_id: key).one
  if doc && (!doc[@expires_field] || doc[@expires_field] >= Time.now)
    # @expires_field must be a Time object (BSON date datatype)
    expires = expires_at(options, nil)
    @collection.find(_id: key).update(:$set => { @expires_field => expires || nil }) if expires != nil
    doc_to_value(doc)
  end
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 Defaults#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)


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/moneta/adapters/mongo/moped.rb', line 136

def merge!(pairs, options = {})
  @backend.with(safe: true, consistency: :strong) do |safe|
    collection = safe[@collection.name]
    existing = collection
      .find(_id: { :$in => pairs.map { |key, _| to_binary(key) }.to_a })
      .map { |doc| [from_binary(doc[:_id]), doc_to_value(doc)] }
      .to_h

    update_pairs, insert_pairs = pairs.partition { |key, _| existing.key?(key) }
    unless insert_pairs.empty?
      collection.insert(insert_pairs.map do |key, value|
        value_to_doc(to_binary(key), value, options)
      end)
    end

    update_pairs.each do |key, value|
      value = yield(key, existing[key], value) if block_given?
      binary = to_binary(key)
      collection
        .find(_id: binary)
        .update(value_to_doc(binary, value, options))
    end
  end
  self
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 Moneta::Adapters::MongoBase#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.

Returns:

  • (<(Object, Object)>)

    A collection of key-value pairs



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/moneta/adapters/mongo/moped.rb', line 121

def slice(*keys, **options)
  query = @collection.find(_id: { :$in => keys.map(&method(:to_binary)) })
  pairs = query.map do |doc|
    next if doc[@expires_field] && doc[@expires_field] < Time.now
    [from_binary(doc[:_id]), doc_to_value(doc)]
  end.compact

  if (expires = expires_at(options, nil)) != nil
    query.update_all(:$set => { @expires_field => expires || nil })
  end

  pairs
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



67
68
69
70
71
# File 'lib/moneta/adapters/mongo/moped.rb', line 67

def store(key, value, options = {})
  key = to_binary(key)
  @collection.find(_id: key).upsert(value_to_doc(key, value, options))
  value
end