Class: Memcache

Inherits:
Memcached show all
Defined in:
lib/hybrid_memcache.rb

Constant Summary collapse

WRITE_LOCK_WAIT =
1
LOCK_TIMEOUT =
5

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Memcache

Returns a new instance of Memcache.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/hybrid_memcache.rb', line 7

def initialize (opts={})
  servers    = opts[:servers] && opts.delete(:servers)
  @namespace = ""
  
  super(servers, {
    :prefix_key           =>  '',
    :prefix_delimiter     =>  '',
    :support_cas          => true,
    
    :hash                 => :fnv1_32,
    :distribution         => :consistent_ketama,
    :ketama_weighted      => true,
    :server_failure_limit => 2,
    :retry_timeout        => 30,
    
    :default_ttl          => 604800,
  }.merge!(opts))
end

Instance Method Details

#[](key) ⇒ Object



324
325
326
# File 'lib/hybrid_memcache.rb', line 324

def [](key)
  get(key)
end

#[]=(key, value) ⇒ Object



329
330
331
# File 'lib/hybrid_memcache.rb', line 329

def []=(key,value)
  set(key,value)
end

#add(key, value, opts = {}) ⇒ Object



34
35
36
37
38
39
# File 'lib/hybrid_memcache.rb', line 34

def add(key, value, opts={})
  super(normalize_keys(key), value, *opts_to_params(opts))
  return value
rescue Memcached::NotStored
  return nil
end

#append(key, value) ⇒ Object



197
198
199
200
201
202
# File 'lib/hybrid_memcache.rb', line 197

def append(key, value)
  super(normalize_keys(key), value)
  return true
rescue Memcached::NotStored
  return false
end

#cas(key, value, opts = {}) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/hybrid_memcache.rb', line 175

def cas(key, value, opts={})
  ttl, marshal, flags = opts_to_params(opts)
  key  = normalize_keys(key)
  data = marshal ? Marshal.dump(value) : value

  check_return_code(Lib.memcached_cas(@struct, key, data, ttl, flags, opts[:cas]), key)
  value.memcache_cas   = @struct.result.cas
  value.memcache_flags = @struct.result.flags
  return value
rescue Memcached::NotStored
 return nil
end

#cloneObject



27
28
29
30
31
# File 'lib/hybrid_memcache.rb', line 27

def clone
   klone = self.class.new({ :servers => servers }.merge(options))
   klone.set_namespace @namespace
   klone
end

#count(key) ⇒ Object



205
206
207
# File 'lib/hybrid_memcache.rb', line 205

def count(key)
  get(key, :raw => true).to_i
end

#decrement(key, amount = 1) ⇒ Object Also known as: decr



218
219
220
221
222
# File 'lib/hybrid_memcache.rb', line 218

def decrement(key, amount=1)
  super(normalize_keys(key), amount)
rescue Memcached::NotFound
  return nil
end

#delete(key) ⇒ Object



310
311
312
313
314
315
# File 'lib/hybrid_memcache.rb', line 310

def delete(key)
  super(normalize_keys(key))
  return true
rescue Memcached::NotFound
  return nil
end

#flush_all(opts = {}) ⇒ Object Also known as: clear



318
319
320
# File 'lib/hybrid_memcache.rb', line 318

def flush_all(opts={})
  flush
end

#get(keys, opts = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/hybrid_memcache.rb', line 71

def get(keys, opts={})
  marshal = !opts[:raw]
  cas     =  opts[:cas]
  
  unless keys.is_a?(Array)
    ## ninjudd-memcache has a weird behaviour where get can be called with an
    ## expiry and that will transform the get into get+cas. this in turn has
    ## the effect of extending the expiry of the object. 
    if opts[:expiry]
      value = get(keys,        :cas => true)
      value = cas(keys, value, :cas => value.memcache_cas, :expiry => opts[:expiry])
      return value
    end
    
    ## Single get
    value, flags, ret = Lib.memcached_get_rvalue(@struct, normalize_keys(keys))
    
    ## ninjudd-memcache treats broken servers as cache missis, so return nil
    ## check_return_code(ret, keys)
    return nil unless ret == 0
    
    if marshal
      value = Marshal.load(value) 
    end

    value.memcache_cas   = cas ? @struct.result.cas : false
    value.memcache_flags = flags
    return value
  else
    ## Multi get
    return {} if keys.empty?

    ## ninjudd-memcache normalizes keys into the form namespace:index:key
    ## but it hides this form from the caller, so the caller expects to 
    ## get a hash with the keys in their denormalized form. That's what
    ## the norm_to_std hash is all about. 
    normalized  = normalize_keys(keys)
    norm_to_std = {}
    
    ## but note, the keys have to be transformed into strings, even if they
    ## started out as fixnums
    keys.each_with_index {|k,idx| norm_to_std[normalized[idx]] = keys[idx].to_s }
    
    ret = Lib.memcached_mget(@struct, normalized)
    
    ## once again: potentiall braken server == cache miss
    ## check_return_code(ret, normalized)
    return {} unless ret == 0
  
    hash = {}
    keys.each do
      value, key, flags, ret = Lib.memcached_fetch_rvalue(@struct)
      if ret == Lib::MEMCACHED_END
        break 
      end
      
      if ret != 0 
        ## once again: potentiall braken server == cache miss
        ## check_return_code(ret, key) 
        value = nil 
      else  
        # Assign the value
        if marshal
          value = Marshal.load(value) 
        end 
        value.memcache_cas   = cas ? @struct.result.cas : false
        value.memcache_flags = flags
      end
      
      hash[ norm_to_std[key] ] = value
    end
    return hash
  end
rescue Memcached::NotFound
  return nil
end

#get_or_add(key, *args) ⇒ Object



235
236
237
238
239
240
241
242
243
# File 'lib/hybrid_memcache.rb', line 235

def get_or_add(key, *args)
  if block_given?
    opts = args[0] || {}
    get(key) || add(key, yield,   opts) || get(key)
  else
    opts = args[1] || {}
    get(key) || add(key, args[0], opts) || get(key)
  end
end

#get_or_set(key, *args) ⇒ Object



246
247
248
249
250
251
252
253
254
# File 'lib/hybrid_memcache.rb', line 246

def get_or_set(key, *args)
  if block_given?
    opts = args[0] || {}
    get(key) || set(key, yield,   opts) || get(key)
  else
    opts = args[1] || {}
    get(key) || set(key, args[0], opts) || get(key)
  end
end

#get_some(keys, opts = {}) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/hybrid_memcache.rb', line 257

def get_some(keys, opts = {})
  keys    = keys.collect { |k| k.to_s }
  records = opts[:disable] ? {} : self.get(keys, opts)
  
  if opts[:validation]
    records.delete_if do |key, value|
      not opts[:validation].call(key, value)
    end
  end
  
  keys_to_fetch = keys - records.keys
  method        = opts[:overwrite] ? :set : :add
  if keys_to_fetch.any?
    yield(keys_to_fetch).each do |key, value|
      self.send(method, key, value, opts) unless opts[:disable] or opts[:disable_write]
      records[key] = value
    end
  end
  records
end

#in_namespace(ns) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/hybrid_memcache.rb', line 47

def in_namespace(ns)
  # Temporarily change the namespace for convenience.
  begin
    old_namespace = @namespace
    self.set_namespace("#{old_namespace}#{ns}")
    yield
  ensure
    self.set_namespace(old_namespace)
  end
end

#increment(key, amount = 1) ⇒ Object Also known as: incr



210
211
212
213
214
# File 'lib/hybrid_memcache.rb', line 210

def increment(key, amount=1)
  super(normalize_keys(key), amount)
rescue Memcached::NotFound
  return nil
end

#inspectObject



42
43
44
# File 'lib/hybrid_memcache.rb', line 42

def inspect
  "<Memcache: %d servers, ns: %p" % [ servers.length, namespace ]
end

#lock(key, opts = {}) ⇒ Object



284
285
286
287
# File 'lib/hybrid_memcache.rb', line 284

def lock(key, opts={})
  expiry = opts[:expiry] || LOCK_TIMEOUT
  add(lock_key(key), Socket.gethostname, :expiry => expiry, :raw => true)
end

#lock_key(key) ⇒ Object



279
280
281
# File 'lib/hybrid_memcache.rb', line 279

def lock_key(key)
  "lock:#{key}"
end

#locked?(key) ⇒ Boolean

Returns:

  • (Boolean)


305
306
307
# File 'lib/hybrid_memcache.rb', line 305

def locked?(key)
  get(lock_key(key), :raw => true)
end

#namespaceObject



59
60
61
# File 'lib/hybrid_memcache.rb', line 59

def namespace 
  @namespace
end

#normalize_keys(keys) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/hybrid_memcache.rb', line 334

def normalize_keys (keys)
  ns = @namespace.nil? || @namespace.size == 0 ? "" : "#{@namespace}:"
  
  unless keys.is_a?(Array) 
    k = "#{ns}#{keys}"
    k.gsub!(/%/, '%%') if k.include?('%')
    k.gsub!(/ /, '%s') if k.include?(' ')
    return k
  else
    return keys.collect do |k| 
      k = "#{ns}#{k}" 
      k.gsub!(/%/, '%%') if k.include?('%')
      k.gsub!(/ /, '%s') if k.include?(' ')
      k
    end
  end
end

#opts_to_params(opts = {}) ⇒ Object



353
354
355
356
357
358
359
360
361
362
# File 'lib/hybrid_memcache.rb', line 353

def opts_to_params (opts={})
  ## - if no :expiry, use @default_ttl
  ## - fauna-memcached uses marshal which has the opposite meaning of 
  ##   ninjudd's :raw. that is, :raw means DO NOT marshal, so invert
  ##   :raw via ! ... 
  ## - if no :flags,  use FLAGS
  return  opts[:expiry] || @default_ttl,
         !opts[:raw],
          opts[:flags]  || FLAGS
end

#prepend(key, value) ⇒ Object



189
190
191
192
193
194
# File 'lib/hybrid_memcache.rb', line 189

def prepend(key,value)
  super(normalize_keys(key), value)
  return true
rescue Memcached::NotStored
  return false
end

#read(keys, opts = {}) ⇒ Object



149
150
151
# File 'lib/hybrid_memcache.rb', line 149

def read(keys, opts={})
  get(keys, opts.merge(:raw => true))
end

#replace(key, value, opts = {}) ⇒ Object



167
168
169
170
171
172
# File 'lib/hybrid_memcache.rb', line 167

def replace(key, value, opts={})
  super(normalize_keys(key), value, *opts_to_params(opts))
  return value
rescue Memcached::NotStored
  return nil
end

#set(key, value, opts = {}) ⇒ Object



154
155
156
157
158
159
# File 'lib/hybrid_memcache.rb', line 154

def set(key, value, opts={})
  super(normalize_keys(key), value, *opts_to_params(opts))
  return value
rescue Memcached::NotFound
  return nil
end

#set_namespace(ns) ⇒ Object Also known as: namespace=, set_namespace=



64
65
66
# File 'lib/hybrid_memcache.rb', line 64

def set_namespace(ns)
  @namespace = ns
end

#unlock(key) ⇒ Object



290
291
292
# File 'lib/hybrid_memcache.rb', line 290

def unlock(key)
  delete(lock_key(key))
end

#update(key, opts = {}) ⇒ Object



226
227
228
229
230
231
232
# File 'lib/hybrid_memcache.rb', line 226

def update(key, opts={})
  if value = get(key, :cas => true)
    cas(key, yield(value), opts.merge!(:cas => value.memcache_cas))
  else
    add(key, yield(value), opts)
  end
end

#with_lock(key, opts = {}) ⇒ Object



295
296
297
298
299
300
301
302
# File 'lib/hybrid_memcache.rb', line 295

def with_lock(key, opts={})
  until lock(key) do
    return if opts[:ignore]
    sleep(WRITE_LOCK_WAIT)
  end
  yield
  unlock(key) unless opts[:keep]
end

#write(key, value, opts = {}) ⇒ Object



162
163
164
# File 'lib/hybrid_memcache.rb', line 162

def write(key, value, opts={})
  set(key, value, opts.merge(:raw => true))
end