=encoding utf-8


=head1 Name

lua-resty-memcached - Lua memcached client driver for the ngx_lua based on the cosocket API


=head1 Status

This library is considered production ready.


=head1 Description

This Lua library is a memcached client driver for the ngx_lua nginx module:

http://wiki.nginx.org/HttpLuaModule

This Lua library takes advantage of ngx_lua's cosocket API, which ensures
100% nonblocking behavior.

Note that at least L<ngx_lua 0.5.0rc29|https://github.com/chaoslawful/lua-nginx-module/tags> or L<OpenResty 1.0.15.7|http://openresty.org/#Download> is required.


=head1 Synopsis


        lua_package_path "/path/to/lua-resty-memcached/lib/?.lua;;";
    
        server {
            location /test {
                content_by_lua '
                    local memcached = require "resty.memcached"
                    local memc, err = memcached:new()
                    if not memc then
                        ngx.say("failed to instantiate memc: ", err)
                        return
                    end
    
                    memc:set_timeout(1000) -- 1 sec
    
                    -- or connect to a unix domain socket file listened
                    -- by a memcached server:
                    --     local ok, err = memc:connect("unix:/path/to/memc.sock")
    
                    local ok, err = memc:connect("127.0.0.1", 11211)
                    if not ok then
                        ngx.say("failed to connect: ", err)
                        return
                    end
    
                    local ok, err = memc:flush_all()
                    if not ok then
                        ngx.say("failed to flush all: ", err)
                        return
                    end
    
                    local ok, err = memc:set("dog", 32)
                    if not ok then
                        ngx.say("failed to set dog: ", err)
                        return
                    end
    
                    local res, flags, err = memc:get("dog")
                    if err then
                        ngx.say("failed to get dog: ", err)
                        return
                    end
    
                    if not res then
                        ngx.say("dog not found")
                        return
                    end
    
                    ngx.say("dog: ", res)
    
                    -- put it into the connection pool of size 100,
                    -- with 10 seconds max idle timeout
                    local ok, err = memc:set_keepalive(10000, 100)
                    if not ok then
                        ngx.say("cannot set keepalive: ", err)
                        return
                    end
    
                    -- or just close the connection right away:
                    -- local ok, err = memc:close()
                    -- if not ok then
                    --     ngx.say("failed to close: ", err)
                    --     return
                    -- end
                ';
            }
        }




=head1 Methods

The C<key> argument provided in the following methods will be automatically escaped according to the URI escaping rules before sending to the memcached server.




=head2 new

C<syntax: memc, err = memcached:new(opts?)>

Creates a memcached object. In case of failures, returns C<nil> and a string describing the error.

It accepts an optional C<opts> table argument. The following options are supported:


=over


=item *

C<key_transform>

an array table containing two functions for escaping and unescaping the
memcached keys, respectively. By default,
the memcached keys will be escaped and unescaped as URI components, that is


=back


        memached:new{
            key_transform = { ngx.escape_uri, ngx.unescape_uri }
        }




=head2 connect

C<syntax: ok, err = memc:connect(host, port)>

C<syntax: ok, err = memc:connect("unix:/path/to/unix.sock")>

Attempts to connect to the remote host and port that the memcached server is listening to or a local unix domain socket file listened by the memcached server.

Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.




=head2 set

C<syntax: ok, err = memc:set(key, value, exptime, flags)>

Inserts an entry into memcached unconditionally. If the key already exists, overrides it.

The C<value> argument could also be a Lua table holding multiple Lua
strings that are supposed to be concatenated as a whole
(without any delimiters). For example,


        memc:set("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to


        memc:set("dog", "a kind of animal")

The C<exptime> parameter is optional, defaults to C<0>.

The C<flags> parameter is optional, defaults to C<0>.




=head2 set_timeout

C<syntax: ok, err = memc:set_timeout(time)>

Sets the timeout (in ms) protection for subsequent operations, including the C<connect> method.

Returns 1 when successful and nil plus a string describing the error otherwise.




=head2 set_keepalive

C<syntax: ok, err = memc:set_keepalive(max_idle_timeout, pool_size)>

Puts the current memcached connection immediately into the ngx_lua cosocket connection pool.

You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.

Only call this method in the place you would have called the C<close> method instead. Calling this method will immediately turn the current memcached object into the C<closed> state. Any subsequent operations other than C<connect()> on the current objet will return the C<closed> error.




=head2 get_reused_times

C<syntax: times, err = memc:get_reused_times()>

This method returns the (successfully) reused times for the current connection. In case of error, it returns C<nil> and a string describing the error.

If the current connection does not come from the built-in connection pool, then this method always returns C<0>, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.




=head2 close

C<syntax: ok, err = memc:close()>

Closes the current memcached connection and returns the status.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 add

C<syntax: ok, err = memc:add(key, value, exptime, flags)>

Inserts an entry into memcached if and only if the key does not exist.

The C<value> argument could also be a Lua table holding multiple Lua
strings that are supposed to be concatenated as a whole
(without any delimiters). For example,


        memc:add("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to


        memc:add("dog", "a kind of animal")

The C<exptime> parameter is optional, defaults to C<0>.

The C<flags> parameter is optional, defaults to C<0>.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 replace

C<syntax: ok, err = memc:replace(key, value, exptime, flags)>

Inserts an entry into memcached if and only if the key does exist.

The C<value> argument could also be a Lua table holding multiple Lua
strings that are supposed to be concatenated as a whole
(without any delimiters). For example,


        memc:replace("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to


        memc:replace("dog", "a kind of animal")

The C<exptime> parameter is optional, defaults to C<0>.

The C<flags> parameter is optional, defaults to C<0>.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 append

C<syntax: ok, err = memc:append(key, value, exptime, flags)>

Appends the value to an entry with the same key that already exists in memcached.

The C<value> argument could also be a Lua table holding multiple Lua
strings that are supposed to be concatenated as a whole
(without any delimiters). For example,


        memc:append("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to


        memc:append("dog", "a kind of animal")

The C<exptime> parameter is optional, defaults to C<0>.

The C<flags> parameter is optional, defaults to C<0>.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 prepend

C<syntax: ok, err = memc:prepend(key, value, exptime, flags)>

Prepends the value to an entry with the same key that already exists in memcached.

The C<value> argument could also be a Lua table holding multiple Lua
strings that are supposed to be concatenated as a whole
(without any delimiters). For example,


        memc:prepend("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to


        memc:prepend("dog", "a kind of animal")

The C<exptime> parameter is optional, defaults to C<0>.

The C<flags> parameter is optional, defaults to C<0>.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 get

C<syntax: value, flags, err = memc:get(key)>
C<syntax: results, err = memc:get(keys)>

Get a single entry or multiple entries in the memcached server via a single key or a talbe of keys.

Let us first discuss the case When the key is a single string.

The key's value and associated flags value will be returned if the entry is found and no error happens.

In case of errors, C<nil> values will be turned for C<value> and C<flags> and a 3rd (string) value will also be returned for describing the error.

If the entry is not found, then three C<nil> values will be returned.

Then let us discuss the case when the a Lua table of multiple keys are provided.

In this case, a Lua table holding the key-result pairs will be always returned in case of success. Each value corresponding each key in the table is also a table holding two values, the key's value and the key's flags. If a key does not exist, then there is no responding entries in the C<results> table.

In case of errors, C<nil> will be returned, and the second return value will be a string describing the error.




=head2 gets

C<syntax: value, flags, cas_unique, err = memc:gets(key)>

C<syntax: results, err = memc:gets(keys)>

Just like the C<get> method, but will also return the CAS unique value associated with the entry in addition to the key's value and flags.

This method is usually used together with the C<cas> method.




=head2 cas

C<syntax: ok, err = memc:cas(key, value, cas_unique, exptime?, flags?)>

Just like the C<set> method but does a check and set operation, which means "store this data but
only if no one else has updated since I last fetched it."

The C<cas_unique> argument can be obtained from the C<gets> method.




=head2 touch

C<syntax: ok, err = memc:touch(key, exptime)>

Update the expiration time of an existing key.

Returns C<1> for success or C<nil> with a string describing the error otherwise.

This method was first introduced in the C<v0.11> release.




=head2 flush_all

C<syntax: ok, err = memc:flush_all(time?)>

Flushes (or invalidates) all the existing entries in the memcached server immediately (by default) or after the expiration
specified by the C<time> argument (in seconds).

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 delete

C<syntax: ok, err = memc:delete(key)>

Deletes the key from memcached immediately.

The key to be deleted must already exist in memcached.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.




=head2 incr

C<syntax: new_value, err = memc:incr(key, delta)>

Increments the value of the specified key by the integer value specified in the C<delta> argument.

Returns the new value after incrementation in success, and C<nil> with a string describing the error in case of failures.




=head2 decr

C<syntax: new_value, err = memc:decr(key, value)>

Decrements the value of the specified key by the integer value specified in the C<delta> argument.

Returns the new value after decrementation in success, and C<nil> with a string describing the error in case of failures.




=head2 stats

C<syntax: lines, err = memc:stats(args?)>

Returns memcached server statistics information with an optional C<args> argument.

In case of success, this method returns a lua table holding all of the lines of the output; in case of failures, it returns C<nil> with a string describing the error.

If the C<args> argument is omitted, general server statistics is returned. Possible C<args> argument values are C<items>, C<sizes>, C<slabs>, among others.




=head2 version

C<syntax: version, err = memc:version(args?)>

Returns the server version number, like C<1.2.8>.

In case of error, it returns C<nil> with a string describing the error.




=head2 quit

C<syntax: ok, err = memc:quit()>

Tells the server to close the current memcached connection.

Returns C<1> in case of success and C<nil> other wise. In case of failures, another string value will also be returned to describe the error.

Generally you can just directly call the C<close> method to achieve the same effect.




=head2 verbosity

C<syntax: ok, err = memc:verbosity(level)>

Sets the verbosity level used by the memcached server. The C<level> argument should be given integers only.

Returns C<1> in case of success and C<nil> other wise. In case of failures, another string value will also be returned to describe the error.




=head1 Automatic Error Logging

By default the underlying L<ngx_lua|http://wiki.nginx.org/HttpLuaModule> module
does error logging when socket errors happen. If you are already doing proper error
handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off L<ngx_lua|http://wiki.nginx.org/HttpLuaModule>'s L<lua_socket_log_errors|http://wiki.nginx.org/HttpLuaModule#lua_socket_log_errors> directive, that is,


        lua_socket_log_errors off;




=head1 Limitations


=over


=item *

This library cannot be used in code contexts like set_by_luaI<, log_by_lua>, and
header_filter_by_lua* where the ngx_lua cosocket API is not available.

=item *

The C<resty.memcached> object instance cannot be stored in a Lua variable at the Lua module level,
because it will then be shared by all the concurrent requests handled by the same nginx
worker process (see
http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker ) and
result in bad race conditions when concurrent requests are trying to use the same C<resty.memcached> instance.
You should always initiate C<resty.memcached> objects in function local
variables or in the C<ngx.ctx> table. These places all have their own data copies for
each request.


=back




=head1 TODO


=over


=item *

implement the memcached pipelining API.

=item *

implement the UDP part of the memcached ascii protocol.


=back




=head1 Author

Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, CloudFlare Inc.




=head1 Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2012-2016, by Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, CloudFlare Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:


=over


=item *

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.


=back


=over


=item *

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.


=back

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.




=head1 See Also


=over


=item *

the ngx_lua module: http://wiki.nginx.org/HttpLuaModule

=item *

the memcached wired protocol specification: http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

=item *

the L<lua-resty-redis|https://github.com/agentzh/lua-resty-redis> library.

=item *

the L<lua-resty-mysql|https://github.com/agentzh/lua-resty-mysql> library.


=back



