memcached-uv 0.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+
2
+ class Memcached
3
+
4
+ #:stopdoc:
5
+
6
+ def self.load_constants(prefix, hash = {})
7
+ Lib.constants.grep(/^#{prefix}/).each do |const_name|
8
+ hash[const_name[prefix.length..-1].downcase.to_sym] = Lib.const_get(const_name)
9
+ end
10
+ hash
11
+ end
12
+
13
+ BEHAVIORS = load_constants("MEMCACHED_BEHAVIOR_")
14
+
15
+ BEHAVIOR_VALUES = {
16
+ false => 0,
17
+ true => 1
18
+ }
19
+
20
+ HASH_VALUES = {}
21
+ BEHAVIOR_VALUES.merge!(load_constants("MEMCACHED_HASH_", HASH_VALUES))
22
+
23
+ DISTRIBUTION_VALUES = {}
24
+ BEHAVIOR_VALUES.merge!(load_constants("MEMCACHED_DISTRIBUTION_", DISTRIBUTION_VALUES))
25
+
26
+ DIRECT_VALUE_BEHAVIORS = [:retry_timeout, :connect_timeout, :rcv_timeout, :socket_recv_size, :poll_timeout, :socket_send_size, :server_failure_limit]
27
+
28
+ CONVERSION_FACTORS = {
29
+ :rcv_timeout => 1_000_000,
30
+ :poll_timeout => 1_000,
31
+ :connect_timeout => 1_000
32
+ }
33
+
34
+ #:startdoc:
35
+
36
+ private
37
+
38
+ # Set a behavior option for this Memcached instance. Accepts a Symbol <tt>behavior</tt> and either <tt>true</tt>, <tt>false</tt>, or a Symbol for <tt>value</tt>. Arguments are validated and converted into integers for the struct setter method.
39
+ def set_behavior(behavior, value) #:doc:
40
+ raise ArgumentError, "No behavior #{behavior.inspect}" unless b_id = BEHAVIORS[behavior]
41
+
42
+ # Scoped validations; annoying
43
+ msg = "Invalid behavior value #{value.inspect} for #{behavior.inspect}"
44
+ case behavior
45
+ when :hash then raise(ArgumentError, msg) unless HASH_VALUES[value]
46
+ when :distribution then raise(ArgumentError, msg) unless DISTRIBUTION_VALUES[value]
47
+ when *DIRECT_VALUE_BEHAVIORS then raise(ArgumentError, msg) unless value.is_a?(Numeric) and value >= 0
48
+ else
49
+ raise(ArgumentError, msg) unless BEHAVIOR_VALUES[value]
50
+ end
51
+
52
+ lib_value = BEHAVIOR_VALUES[value] || (value * (CONVERSION_FACTORS[behavior] || 1)).to_i
53
+ #STDERR.puts "Setting #{behavior}:#{b_id} => #{value} (#{lib_value})"
54
+ Lib.memcached_behavior_set(@struct, b_id, lib_value)
55
+ #STDERR.puts " -> set to #{get_behavior(behavior).inspect}"
56
+ end
57
+
58
+ # Get a behavior value for this Memcached instance. Accepts a Symbol.
59
+ def get_behavior(behavior)
60
+ raise ArgumentError, "No behavior #{behavior.inspect}" unless b_id = BEHAVIORS[behavior]
61
+ value = Lib.memcached_behavior_get(@struct, b_id)
62
+
63
+ if BEHAVIOR_VALUES.invert.has_key?(value)
64
+ # False, nil are valid values so we can not rely on direct lookups
65
+ case behavior
66
+ # Scoped values; still annoying
67
+ when :hash then HASH_VALUES.invert[value]
68
+ when :distribution then DISTRIBUTION_VALUES.invert[value]
69
+ when *DIRECT_VALUE_BEHAVIORS then value
70
+ else
71
+ BEHAVIOR_VALUES.invert[value]
72
+ end
73
+ else
74
+ value
75
+ end
76
+ end
77
+
78
+ end
@@ -0,0 +1,84 @@
1
+
2
+ class Memcached
3
+
4
+ =begin rdoc
5
+
6
+ Superclass for all Memcached runtime exceptions.
7
+
8
+ Subclasses correspond one-to-one with server response strings or libmemcached errors. For example, raising <b>Memcached::NotFound</b> means that the server returned <tt>"NOT_FOUND\r\n"</tt>.
9
+
10
+ == Subclasses
11
+
12
+ * Memcached::ABadKeyWasProvidedOrCharactersOutOfRange
13
+ * Memcached::AKeyLengthOfZeroWasProvided
14
+ * Memcached::ATimeoutOccurred
15
+ * Memcached::ActionNotSupported
16
+ * Memcached::ActionQueued
17
+ * Memcached::ClientError
18
+ * Memcached::ConnectionBindFailure
19
+ * Memcached::ConnectionDataDoesNotExist
20
+ * Memcached::ConnectionDataExists
21
+ * Memcached::ConnectionFailure
22
+ * Memcached::ConnectionSocketCreateFailure
23
+ * Memcached::CouldNotOpenUnixSocket
24
+ * Memcached::EncounteredAnUnknownStatKey
25
+ * Memcached::Failure
26
+ * Memcached::FetchWasNotCompleted
27
+ * Memcached::HostnameLookupFailure
28
+ * Memcached::ItemValue
29
+ * Memcached::MemoryAllocationFailure
30
+ * Memcached::NoServersDefined
31
+ * Memcached::NotFound
32
+ * Memcached::NotStored
33
+ * Memcached::PartialRead
34
+ * Memcached::ProtocolError
35
+ * Memcached::ReadFailure
36
+ * Memcached::ServerDelete
37
+ * Memcached::ServerEnd
38
+ * Memcached::ServerError
39
+ * Memcached::ServerIsMarkedDead
40
+ * Memcached::ServerValue
41
+ * Memcached::SomeErrorsWereReported
42
+ * Memcached::StatValue
43
+ * Memcached::SystemError
44
+ * Memcached::TheHostTransportProtocolDoesNotMatchThatOfTheClient
45
+ * Memcached::UnknownReadFailure
46
+ * Memcached::WriteFailure
47
+
48
+ =end
49
+ class Error < RuntimeError
50
+ attr_accessor :no_backtrace
51
+
52
+ def set_backtrace(*args)
53
+ @no_backtrace ? [] : super
54
+ end
55
+
56
+ def backtrace(*args)
57
+ @no_backtrace ? [] : super
58
+ end
59
+ end
60
+
61
+ #:stopdoc:
62
+
63
+ class << self
64
+ private
65
+ def camelize(string)
66
+ string.downcase.gsub('/', ' or ').split(' ').map {|s| s.capitalize}.join
67
+ end
68
+ end
69
+
70
+ ERRNO_HASH = Hash[*Errno.constants.map{ |c| [Errno.const_get(c)::Errno, Errno.const_get(c).new.message] }.flatten]
71
+
72
+ EXCEPTIONS = []
73
+ EMPTY_STRUCT = Rlibmemcached::MemcachedSt.new
74
+ Rlibmemcached.memcached_create(EMPTY_STRUCT)
75
+
76
+ # Generate exception classes
77
+ Rlibmemcached::MEMCACHED_MAXIMUM_RETURN.times do |index|
78
+ description = Rlibmemcached.memcached_strerror(EMPTY_STRUCT, index).gsub("!", "")
79
+ exception_class = eval("class #{camelize(description)} < Error; self; end")
80
+ EXCEPTIONS << exception_class
81
+ end
82
+
83
+ #:startdoc:
84
+ end
@@ -0,0 +1,6 @@
1
+
2
+ class Integer
3
+ def tv_sec
4
+ self
5
+ end
6
+ end
@@ -0,0 +1,496 @@
1
+
2
+ =begin rdoc
3
+ The Memcached client class.
4
+ =end
5
+ class Memcached
6
+
7
+ FLAGS = 0x0
8
+
9
+ DEFAULTS = {
10
+ :hash => :fnv1_32,
11
+ :no_block => false,
12
+ :distribution => :consistent_ketama,
13
+ :ketama_weighted => true,
14
+ :buffer_requests => false,
15
+ :cache_lookups => true,
16
+ :support_cas => false,
17
+ :tcp_nodelay => false,
18
+ :show_backtraces => false,
19
+ :retry_timeout => 30,
20
+ :timeout => 0.25,
21
+ :rcv_timeout => nil,
22
+ :poll_timeout => nil,
23
+ :connect_timeout => 2,
24
+ :prefix_key => nil,
25
+ :hash_with_prefix_key => true,
26
+ :default_ttl => 604800,
27
+ :default_weight => 8,
28
+ :sort_hosts => false,
29
+ :auto_eject_hosts => true,
30
+ :server_failure_limit => 2,
31
+ :verify_key => true,
32
+ :use_udp => false,
33
+ :binary_protocol => false
34
+ }
35
+
36
+ #:stopdoc:
37
+ IGNORED = 0
38
+ #:startdoc:
39
+
40
+ attr_reader :options # Return the options Hash used to configure this instance.
41
+
42
+ ###### Configuration
43
+
44
+ =begin rdoc
45
+ Create a new Memcached instance. Accepts string or array of server strings, as well an an optional configuration hash.
46
+
47
+ Memcached.new('localhost', ...) # A single server
48
+ Memcached.new(['web001:11212', 'web002:11212'], ...) # Two servers with custom ports
49
+ Memcached.new(['web001:11211:2', 'web002:11211:8'], ...) # Two servers with default ports and explicit weights
50
+
51
+ Weights only affect Ketama hashing. If you use Ketama hashing and don't specify a weight, the client will poll each server's stats and use its size as the weight.
52
+
53
+ Valid option parameters are:
54
+
55
+ <tt>:prefix_key</tt>:: A string to prepend to every key, for namespacing. Max length is 127.
56
+ <tt>:hash</tt>:: The name of a hash function to use. Possible values are: <tt>:crc</tt>, <tt>:default</tt>, <tt>:fnv1_32</tt>, <tt>:fnv1_64</tt>, <tt>:fnv1a_32</tt>, <tt>:fnv1a_64</tt>, <tt>:hsieh</tt>, <tt>:md5</tt>, and <tt>:murmur</tt>. <tt>:fnv1_32</tt> is fast and well known, and is the default. Use <tt>:md5</tt> for compatibility with other ketama clients.
57
+ <tt>:distribution</tt>:: Either <tt>:modula</tt>, <tt>:consistent_ketama</tt>, <tt>:consistent_wheel</tt>, or <tt>:ketama</tt>. Defaults to <tt>:ketama</tt>.
58
+ <tt>:server_failure_limit</tt>:: How many consecutive failures to allow before marking a host as dead. Has no effect unless <tt>:retry_timeout</tt> is also set.
59
+ <tt>:retry_timeout</tt>:: How long to wait until retrying a dead server. Has no effect unless <tt>:server_failure_limit</tt> is non-zero. Defaults to <tt>30</tt>.
60
+ <tt>:auto_eject_hosts</tt>:: Whether to temporarily eject dead hosts from the pool. Defaults to <tt>true</tt>. Note that in the event of an ejection, <tt>:auto_eject_hosts</tt> will remap the entire pool unless <tt>:distribution</tt> is set to <tt>:consistent</tt>.
61
+ <tt>:cache_lookups</tt>:: Whether to cache hostname lookups for the life of the instance. Defaults to <tt>true</tt>.
62
+ <tt>:support_cas</tt>:: Flag CAS support in the client. Accepts <tt>true</tt> or <tt>false</tt>. Defaults to <tt>false</tt> because it imposes a slight performance penalty. Note that your server must also support CAS or you will trigger <b>Memcached::ProtocolError</b> exceptions.
63
+ <tt>:tcp_nodelay</tt>:: Turns on the no-delay feature for connecting sockets. Accepts <tt>true</tt> or <tt>false</tt>. Performance may or may not change, depending on your system.
64
+ <tt>:no_block</tt>:: Whether to use pipelining for writes. Accepts <tt>true</tt> or <tt>false</tt>.
65
+ <tt>:buffer_requests</tt>:: Whether to use an internal write buffer. Accepts <tt>true</tt> or <tt>false</tt>. Calling <tt>get</tt> or closing the connection will force the buffer to flush. Note that <tt>:buffer_requests</tt> might not work well without <tt>:no_block</tt> also enabled.
66
+ <tt>:show_backtraces</tt>:: Whether <b>Memcached::NotFound</b> and <b>Memcached::NotStored</b> exceptions should include backtraces. Generating backtraces is slow, so this is off by default. Turn it on to ease debugging.
67
+ <tt>:connect_timeout</tt>:: How long to wait for a connection to a server. Defaults to 2 seconds. Set to <tt>0</tt> if you want to wait forever.
68
+ <tt>:timeout</tt>:: How long to wait for a response from the server. Defaults to 0.25 seconds. Set to <tt>0</tt> if you want to wait forever.
69
+ <tt>:default_ttl</tt>:: The <tt>ttl</tt> to use on set if no <tt>ttl</tt> is specified, in seconds. Defaults to one week. Set to <tt>0</tt> if you want things to never expire.
70
+ <tt>:default_weight</tt>:: The weight to use if <tt>:ketama_weighted</tt> is <tt>true</tt>, but no weight is specified for a server.
71
+ <tt>:hash_with_prefix_key</tt>:: Whether to include the prefix when calculating which server a key falls on. Defaults to <tt>true</tt>.
72
+ <tt>:use_udp</tt>:: Use the UDP protocol to reduce connection overhead. Defaults to false.
73
+ <tt>:binary_protocol</tt>:: Use the binary protocol to reduce query processing overhead. Defaults to false.
74
+ <tt>:sort_hosts</tt>:: Whether to force the server list to stay sorted. This defeats consistent hashing and is rarely useful.
75
+ <tt>:verify_key</tt>:: Validate keys before accepting them. Never disable this.
76
+
77
+ Please note that when pipelining is enabled, setter and deleter methods do not raise on errors. For example, if you try to set an invalid key with <tt>:no_block => true</tt>, it will appear to succeed. The actual setting of the key occurs after libmemcached has returned control to your program, so there is no way to backtrack and raise the exception.
78
+
79
+ =end
80
+
81
+ def initialize(servers = "localhost:11211", opts = {})
82
+ @struct = Lib::MemcachedSt.new
83
+ Lib.memcached_create(@struct)
84
+
85
+ # Merge option defaults and discard meaningless keys
86
+ @options = DEFAULTS.merge(opts)
87
+ @options.delete_if { |k,v| not DEFAULTS.keys.include? k }
88
+ @default_ttl = options[:default_ttl]
89
+
90
+ # Force :buffer_requests to use :no_block
91
+ # XXX Deleting the :no_block key should also work, but libmemcached doesn't seem to set it
92
+ # consistently
93
+ options[:no_block] = true if options[:buffer_requests]
94
+
95
+ # Disallow weights without ketama
96
+ options.delete(:ketama_weighted) if options[:distribution] != :consistent_ketama
97
+
98
+ # Legacy accessor
99
+ options[:prefix_key] = options.delete(:namespace) if options[:namespace]
100
+
101
+ # Disallow :sort_hosts with consistent hashing
102
+ if options[:sort_hosts] and options[:distribution] == :consistent
103
+ raise ArgumentError, ":sort_hosts defeats :consistent hashing"
104
+ end
105
+
106
+ # Read timeouts
107
+ options[:rcv_timeout] ||= options[:timeout] || 0
108
+ options[:poll_timeout] ||= options[:timeout] || 0
109
+
110
+ # Set the behaviors on the struct
111
+ set_behaviors
112
+ set_callbacks
113
+
114
+ # Freeze the hash
115
+ options.freeze
116
+
117
+ # Set the servers on the struct
118
+ set_servers(servers)
119
+
120
+ # Not found exceptions
121
+ unless options[:show_backtraces]
122
+ @not_found = NotFound.new
123
+ @not_found.no_backtrace = true
124
+ @not_stored = NotStored.new
125
+ @not_stored.no_backtrace = true
126
+ end
127
+ end
128
+
129
+ # Set the server list.
130
+ # FIXME Does not necessarily free any existing server structs.
131
+ def set_servers(servers)
132
+ Array(servers).each_with_index do |server, index|
133
+ # Socket
134
+ if server.is_a?(String) and File.socket?(server)
135
+ args = [@struct, server, options[:default_weight].to_i]
136
+ check_return_code(Lib.memcached_server_add_unix_socket_with_weight(*args))
137
+ # Network
138
+ elsif server.is_a?(String) and server =~ /^[\w\d\.-]+(:\d{1,5}){0,2}$/
139
+ host, port, weight = server.split(":")
140
+ args = [@struct, host, port.to_i, (weight || options[:default_weight]).to_i]
141
+ if options[:use_udp] #
142
+ check_return_code(Lib.memcached_server_add_udp_with_weight(*args))
143
+ else
144
+ check_return_code(Lib.memcached_server_add_with_weight(*args))
145
+ end
146
+ else
147
+ raise ArgumentError, "Servers must be either in the format 'host:port[:weight]' (e.g., 'localhost:11211' or 'localhost:11211:10') for a network server, or a valid path to a Unix domain socket (e.g., /var/run/memcached)."
148
+ end
149
+ end
150
+ # For inspect
151
+ @servers = send(:servers)
152
+ end
153
+
154
+ # Return the array of server strings used to configure this instance.
155
+ def servers
156
+ server_structs.map do |server|
157
+ inspect_server(server)
158
+ end
159
+ end
160
+
161
+ # Safely copy this instance. Returns a Memcached instance.
162
+ #
163
+ # <tt>clone</tt> is useful for threading, since each thread must have its own unshared Memcached
164
+ # object.
165
+ #
166
+ def clone
167
+ # FIXME Memory leak
168
+ # memcached = super
169
+ # struct = Lib.memcached_clone(nil, @struct)
170
+ # memcached.instance_variable_set('@struct', struct)
171
+ # memcached
172
+ self.class.new(servers, options)
173
+ end
174
+
175
+ # Reset the state of the libmemcached struct. This is useful for changing the server list at runtime.
176
+ def reset(current_servers = nil)
177
+ current_servers ||= servers
178
+ @struct = Lib::MemcachedSt.new
179
+ Lib.memcached_create(@struct)
180
+ set_behaviors
181
+ set_callbacks
182
+ set_servers(current_servers)
183
+ end
184
+
185
+ # Disconnect from all currently connected servers
186
+ def quit
187
+ Lib.memcached_quit(@struct)
188
+ self
189
+ end
190
+
191
+ #:stopdoc:
192
+ alias :dup :clone #:nodoc:
193
+ #:startdoc:
194
+
195
+ ### Configuration helpers
196
+
197
+ private
198
+
199
+ # Return an array of raw <tt>memcached_host_st</tt> structs for this instance.
200
+ def server_structs
201
+ array = []
202
+ if @struct.hosts
203
+ @struct.hosts.count.times do |i|
204
+ array << Lib.memcached_select_server_at(@struct, i)
205
+ end
206
+ end
207
+ array
208
+ end
209
+
210
+ ###### Operations
211
+
212
+ public
213
+
214
+ ### Setters
215
+
216
+ # Set a key/value pair. Accepts a String <tt>key</tt> and an arbitrary Ruby object. Overwrites any existing value on the server.
217
+ #
218
+ # Accepts an optional <tt>ttl</tt> value to specify the maximum lifetime of the key on the server. <tt>ttl</tt> can be either an integer number of seconds, or a Time elapsed time object. <tt>0</tt> means no ttl. Note that there is no guarantee that the key will persist as long as the <tt>ttl</tt>, but it will not persist longer.
219
+ #
220
+ # Also accepts a <tt>marshal</tt> value, which defaults to <tt>true</tt>. Set <tt>marshal</tt> to <tt>false</tt> if you want the <tt>value</tt> to be set directly.
221
+ #
222
+ def set(key, value, ttl=@default_ttl, marshal=true, flags=FLAGS)
223
+ value = marshal ? Marshal.dump(value) : value.to_s
224
+ check_return_code(
225
+ Lib.memcached_set(@struct, key, value, ttl, flags),
226
+ key
227
+ )
228
+ rescue ClientError
229
+ # FIXME Memcached 1.2.8 occasionally rejects valid sets
230
+ tried = 1 and retry unless defined?(tried)
231
+ raise
232
+ end
233
+
234
+ # Add a key/value pair. Raises <b>Memcached::NotStored</b> if the key already exists on the server. The parameters are the same as <tt>set</tt>.
235
+ def add(key, value, ttl=@default_ttl, marshal=true, flags=FLAGS)
236
+ value = marshal ? Marshal.dump(value) : value.to_s
237
+ check_return_code(
238
+ Lib.memcached_add(@struct, key, value, ttl, flags),
239
+ key
240
+ )
241
+ end
242
+
243
+ # Increment a key's value. Accepts a String <tt>key</tt>. Raises <b>Memcached::NotFound</b> if the key does not exist.
244
+ #
245
+ # Also accepts an optional <tt>offset</tt> paramater, which defaults to 1. <tt>offset</tt> must be an integer.
246
+ #
247
+ # Note that the key must be initialized to an unmarshalled integer first, via <tt>set</tt>, <tt>add</tt>, or <tt>replace</tt> with <tt>marshal</tt> set to <tt>false</tt>.
248
+ def increment(key, offset=1)
249
+ ret, value = Lib.memcached_increment(@struct, key, offset)
250
+ check_return_code(ret, key)
251
+ value
252
+ end
253
+
254
+ # Decrement a key's value. The parameters and exception behavior are the same as <tt>increment</tt>.
255
+ def decrement(key, offset=1)
256
+ ret, value = Lib.memcached_decrement(@struct, key, offset)
257
+ check_return_code(ret, key)
258
+ value
259
+ end
260
+
261
+ #:stopdoc:
262
+ alias :incr :increment
263
+ alias :decr :decrement
264
+ #:startdoc:
265
+
266
+ # Replace a key/value pair. Raises <b>Memcached::NotFound</b> if the key does not exist on the server. The parameters are the same as <tt>set</tt>.
267
+ def replace(key, value, ttl=@default_ttl, marshal=true, flags=FLAGS)
268
+ value = marshal ? Marshal.dump(value) : value.to_s
269
+ check_return_code(
270
+ Lib.memcached_replace(@struct, key, value, ttl, flags),
271
+ key
272
+ )
273
+ end
274
+
275
+ # Appends a string to a key's value. Accepts a String <tt>key</tt> and a String <tt>value</tt>. Raises <b>Memcached::NotFound</b> if the key does not exist on the server.
276
+ #
277
+ # Note that the key must be initialized to an unmarshalled string first, via <tt>set</tt>, <tt>add</tt>, or <tt>replace</tt> with <tt>marshal</tt> set to <tt>false</tt>.
278
+ def append(key, value)
279
+ # Requires memcached 1.2.4
280
+ check_return_code(
281
+ Lib.memcached_append(@struct, key, value.to_s, IGNORED, IGNORED),
282
+ key
283
+ )
284
+ end
285
+
286
+ # Prepends a string to a key's value. The parameters and exception behavior are the same as <tt>append</tt>.
287
+ def prepend(key, value)
288
+ # Requires memcached 1.2.4
289
+ check_return_code(
290
+ Lib.memcached_prepend(@struct, key, value.to_s, IGNORED, IGNORED),
291
+ key
292
+ )
293
+ end
294
+
295
+ # Reads a key's value from the server and yields it to a block. Replaces the key's value with the result of the block as long as the key hasn't been updated in the meantime, otherwise raises <b>Memcached::NotStored</b>. Accepts a String <tt>key</tt> and a block.
296
+ #
297
+ # Also accepts an optional <tt>ttl</tt> value.
298
+ #
299
+ # CAS stands for "compare and swap", and avoids the need for manual key mutexing. CAS support must be enabled in Memcached.new or a <b>Memcached::ClientError</b> will be raised. Note that CAS may be buggy in memcached itself.
300
+ #
301
+ def cas(key, ttl=@default_ttl, marshal=true, flags=FLAGS)
302
+ raise ClientError, "CAS not enabled for this Memcached instance" unless options[:support_cas]
303
+
304
+ value, flags, ret = Lib.memcached_get_rvalue(@struct, key)
305
+ check_return_code(ret, key)
306
+ cas = @struct.result.cas
307
+
308
+ value = Marshal.load(value) if marshal
309
+ value = yield value
310
+ value = Marshal.dump(value) if marshal
311
+
312
+ check_return_code(Lib.memcached_cas(@struct, key, value, ttl, flags, cas), key)
313
+ end
314
+
315
+ alias :compare_and_swap :cas
316
+
317
+ ### Deleters
318
+
319
+ # Deletes a key/value pair from the server. Accepts a String <tt>key</tt>. Raises <b>Memcached::NotFound</b> if the key does not exist.
320
+ def delete(key)
321
+ check_return_code(
322
+ Lib.memcached_delete(@struct, key, IGNORED),
323
+ key
324
+ )
325
+ end
326
+
327
+ # Flushes all key/value pairs from all the servers.
328
+ def flush
329
+ check_return_code(
330
+ Lib.memcached_flush(@struct, IGNORED)
331
+ )
332
+ end
333
+
334
+ ### Getters
335
+
336
+ # Gets a key's value from the server. Accepts a String <tt>key</tt> or array of String <tt>keys</tt>.
337
+ #
338
+ # Also accepts a <tt>marshal</tt> value, which defaults to <tt>true</tt>. Set <tt>marshal</tt> to <tt>false</tt> if you want the <tt>value</tt> to be returned directly as a String. Otherwise it will be assumed to be a marshalled Ruby object and unmarshalled.
339
+ #
340
+ # If you pass a String key, and the key does not exist on the server, <b>Memcached::NotFound</b> will be raised. If you pass an array of keys, memcached's <tt>multiget</tt> mode will be used, and a hash of key/value pairs will be returned. The hash will contain only the keys that were found.
341
+ #
342
+ # The multiget behavior is subject to change in the future; however, for multiple lookups, it is much faster than normal mode.
343
+ #
344
+ # Note that when you rescue Memcached::NotFound exceptions, you should use a the block rescue syntax instead of the inline syntax. Block rescues are very fast, but inline rescues are very slow.
345
+ #
346
+ def get(keys, marshal=true)
347
+ if keys.is_a? Array
348
+ # Multi get
349
+ ret = Lib.memcached_mget(@struct, keys);
350
+ check_return_code(ret, keys)
351
+
352
+ hash = {}
353
+ keys.each do
354
+ value, key, flags, ret = Lib.memcached_fetch_rvalue(@struct)
355
+ break if ret == Lib::MEMCACHED_END
356
+ check_return_code(ret, key)
357
+ # Assign the value
358
+ hash[key] = (marshal ? Marshal.load(value) : value)
359
+ end
360
+ hash
361
+ else
362
+ # Single get
363
+ value, flags, ret = Lib.memcached_get_rvalue(@struct, keys)
364
+ check_return_code(ret, keys)
365
+ marshal ? Marshal.load(value) : value
366
+ end
367
+ end
368
+
369
+ ### Information methods
370
+
371
+ # Return the server used by a particular key.
372
+ def server_by_key(key)
373
+ ret = Lib.memcached_server_by_key(@struct, key)
374
+ if ret.is_a?(Array)
375
+ string = inspect_server(ret.first)
376
+ Rlibmemcached.memcached_server_free(ret.first)
377
+ string
378
+ end
379
+ end
380
+
381
+ # Return a Hash of statistics responses from the set of servers. Each value is an array with one entry for each server, in the same order the servers were defined.
382
+ def stats
383
+ stats = Hash.new([])
384
+
385
+ stat_struct, ret = Lib.memcached_stat(@struct, "")
386
+ check_return_code(ret)
387
+
388
+ keys, ret = Lib.memcached_stat_get_keys(@struct, stat_struct)
389
+ check_return_code(ret)
390
+
391
+ keys.each do |key|
392
+ server_structs.size.times do |index|
393
+
394
+ value, ret = Lib.memcached_stat_get_rvalue(
395
+ @struct,
396
+ Lib.memcached_select_stat_at(@struct, stat_struct, index),
397
+ key)
398
+ check_return_code(ret, key)
399
+
400
+ value = case value
401
+ when /^\d+\.\d+$/ then value.to_f
402
+ when /^\d+$/ then value.to_i
403
+ else value
404
+ end
405
+
406
+ stats[key.to_sym] += [value]
407
+ end
408
+ end
409
+
410
+ Lib.memcached_stat_free(@struct, stat_struct)
411
+ stats
412
+ rescue Memcached::SomeErrorsWereReported => _
413
+ e = _.class.new("Error getting stats")
414
+ e.set_backtrace(_.backtrace)
415
+ raise e
416
+ end
417
+
418
+ ### Operations helpers
419
+
420
+ private
421
+
422
+ # Checks the return code from Rlibmemcached against the exception list. Raises the corresponding exception if the return code is not Memcached::Success or Memcached::ActionQueued. Accepts an integer return code and an optional key, for exception messages.
423
+ def check_return_code(ret, key = nil) #:doc:
424
+ if ret == 0 # Memcached::Success
425
+ elsif ret == Lib::MEMCACHED_BUFFERED # Memcached::ActionQueued
426
+ elsif ret == Lib::MEMCACHED_NOTFOUND and @not_found
427
+ raise @not_found
428
+ elsif ret == Lib::MEMCACHED_NOTSTORED and @not_stored
429
+ raise @not_stored
430
+ else
431
+ message = "Key #{inspect_keys(key, (detect_failure if ret == Lib::MEMCACHED_SERVER_MARKED_DEAD)).inspect}"
432
+ if key.is_a?(String)
433
+ if ret == Lib::MEMCACHED_ERRNO
434
+ server = Lib.memcached_server_by_key(@struct, key)
435
+ errno = server.first.cached_errno
436
+ message = "Errno #{errno}: #{ERRNO_HASH[errno].inspect}. #{message}"
437
+ elsif ret == Lib::MEMCACHED_SERVER_ERROR
438
+ server = Lib.memcached_server_by_key(@struct, key)
439
+ message = "\"#{server.first.cached_server_error}\". #{message}."
440
+ end
441
+ end
442
+ raise EXCEPTIONS[ret], message
443
+ end
444
+ end
445
+
446
+ # Turn an array of keys into a hash of keys to servers.
447
+ def inspect_keys(keys, server = nil)
448
+ Hash[*Array(keys).map do |key|
449
+ [key, server || server_by_key(key)]
450
+ end.flatten]
451
+ end
452
+
453
+ # Find which server failed most recently.
454
+ # FIXME Is this still necessary with cached_errno?
455
+ def detect_failure
456
+ time = Time.now
457
+ server = server_structs.detect do |server|
458
+ server.next_retry > time
459
+ end
460
+ inspect_server(server) if server
461
+ end
462
+
463
+ # Set the behaviors on the struct from the current options.
464
+ def set_behaviors
465
+ BEHAVIORS.keys.each do |behavior|
466
+ set_behavior(behavior, options[behavior]) if options.key?(behavior)
467
+ end
468
+ # BUG Hash must be last due to the weird Libmemcached multi-behaviors
469
+ set_behavior(:hash, options[:hash])
470
+ end
471
+
472
+ # Set the callbacks on the struct from the current options.
473
+ def set_callbacks
474
+ # Only support prefix_key for now
475
+ if options[:prefix_key]
476
+ unless options[:prefix_key].size < Lib::MEMCACHED_PREFIX_KEY_MAX_SIZE
477
+ raise ArgumentError, "Max prefix_key size is #{Lib::MEMCACHED_PREFIX_KEY_MAX_SIZE - 1}"
478
+ end
479
+ Lib.memcached_callback_set(@struct, Lib::MEMCACHED_CALLBACK_PREFIX_KEY, options[:prefix_key])
480
+ end
481
+ end
482
+
483
+ def is_unix_socket?(server)
484
+ server.type == Lib::MEMCACHED_CONNECTION_UNIX_SOCKET
485
+ end
486
+
487
+ # Stringify an opaque server struct
488
+ def inspect_server(server)
489
+ strings = [server.hostname]
490
+ if !is_unix_socket?(server)
491
+ strings << ":#{server.port}"
492
+ strings << ":#{server.weight}" if options[:ketama_weighted]
493
+ end
494
+ strings.join
495
+ end
496
+ end