memcache-0.6.0.0: README.md
# memcache: Haskell Memcached Client
[](https://hackage.haskell.org/package/memcache)
[][tl;dr Legal: BSD3]
[](https://github.com/dterei/memcache-hs/actions/workflows/ci.yml)
[tl;dr Legal: BSD3]: https://tldrlegal.com/license/bsd-3-clause-license-(revised) "BSD3 License"
A client library for a memcached cluster.
It supports the Meta Text memcached protocol and username/password
authentication. Keys containing whitespace or control bytes are sent using its
base64 binary-key mode. The encoded key must still fit within 250 bytes. It
supports connecting to a single, or a cluster of memcached servers. When
connecting to a cluster, keys are routed by ketama consistent hashing,
compatible with libmemcached's weighted ketama distribution, so a key goes to
the same server as from libmemcached-based clients given the same server list.
Version 0.5 changed the routing, so upgrading moves keys to different servers,
once; see [Upgrading from 0.4](#upgrading-from-04).
**This library requires memcached 1.6.10 or newer.** Older servers reject the
meta set command this library stores values with, without reading the value
that follows it, and then run the value's bytes as commands. So each new
connection asks the server for its version before it is used: until that check
passes, the only requests sent are the authentication exchange, when
credentials are set, and `version`. Unless the server reports 1.6.10 or later,
the connection is closed and the operation fails with
`ProtocolError (UnknownOp message)`, where the message quotes the server's
reply, or, if the server answered with an error such as
`CLIENT_ERROR unauthenticated`, with the error that reply gives any request. A
refused version isn't retried, and doesn't mark the server as failed. The
check sees only the server the client connects to: through a proxy, such as
memcached's own `-o proxy_config` mode, it sees the proxy's version, so every
memcached behind a proxy must be 1.6.10 or newer too.
Authentication uses a memcached auth file with `-Y authfile`, an experimental
ASCII-protocol auth mode added in memcached 1.5.15; the old binary protocol
`-S` SASL mode is not supported. Enabling `-Y` also disables binary and UDP
protocols on the server. `getMany` uses quiet misses, so a server connection
failure can be indistinguishable from a cache miss.
The client operations, including `getMany`, use direct Meta Text encoders and
the `Response` type; the former request and response wrapper types are no longer
provided.
## Usage
Add `memcache` to your package's `build-depends`. Everything most programs need
is exported from `Database.Memcache.Client`:
```haskell
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Database.Memcache.Client as M
main :: IO ()
main = do
-- Connect to memcached on 127.0.0.1:11211 with the default options.
mc <- M.newClient [M.def] M.def
-- Store a value with flags 0 that never expires, then read it back along
-- with its flags and CAS version.
_ <- M.set mc "greeting" "hello" 0 0
hit <- M.get mc "greeting"
case hit of
Nothing -> putStrLn "miss"
Just (value, _flags, version) -> do
print value
-- Only overwrite the value if it hasn't changed since we read it.
updated <- M.cas mc "greeting" "hello again" 0 0 version
putStrLn (maybe "changed by someone else" (const "updated") updated)
-- Create the counter as 1 if it is missing, otherwise add 1 to it.
visits <- M.increment mc "visits" 1 (Just (1, 0)) Nothing
print (fst <$> visits)
M.quit mc
```
Keys and values are strict `ByteString`s. Misses are returned as `Nothing`,
while unexpected failures are thrown as a `MemcacheError` or a network
`IOException`.
Settings the client can't use throw an `ErrorCall` instead: server options
that resource-pool rejects, such as `soNumResources` smaller than
`soNumStripes` with resource-pool 0.4 or later, when the client is created,
and a [Unix socket](#unix-sockets) path too long for the system, when an
operation connects to it.
Operations that take a `Maybe Version` send it when it is `Just`, and `cas`
always sends its `Version`. On a memcached started with `-C`, every version
is `0`, so `cas` never stores. `increment` and `decrement` create a missing
key only when given an initial value and an expiration. The
[`Database.Memcache.Client`](https://hackage.haskell.org/package/memcache/docs/Database-Memcache-Client.html)
documentation covers every operation, along with the timeouts, retries and
failover configured through `Options`.
Create one client when your program starts and share it: it is safe to use
from many threads, and it keeps its connections to each server open between
requests. A client created for each request opens a new connection to every
server it uses (and authenticates, if credentials are set) every time.
`M.withClient` closes a client's connections when an action ends, so use it
around your whole program, a worker or a test, not around single requests.
Each server's pool holds up to four connections by default, so more concurrent
requests than that to the same server wait for a free one; see
[Architecture Notes](#architecture-notes) to allow more. The wait counts
towards each attempt's `optsTimeout`. An attempt that runs out of time
while still waiting is retried like any failed attempt, but if it was the last
attempt, the operation fails with `Timeout` and the server isn't marked dead.
An attempt that runs out of time afterwards, while opening, authenticating or
using its connection, counts as a server failure, however long it waited
first.
A failed operation is retried, except that a request that mustn't be sent
twice (`increment`, `decrement`, `append`, `prepend`, `add`, `delete`, `cas`,
and `replace` with a version) isn't sent again once it may have reached
the server: the failure is thrown, and the server is marked dead. Other
operations are retried after any failure, so the server may carry out their
request twice. Set `optsServerRetries` to 0 for no retries.
A `SERVER_ERROR` reply is a failure too, as a timeout is, unless its text
names a status, such as running out of memory. One that names a status, and
the other error replies, such as `CLIENT_ERROR`, are thrown at once and don't
count against the server. memcached's proxy sends a `SERVER_ERROR` when a
backend fails, so behind it, a request for a key on a failed backend marks the
whole proxy dead: at once if the request mustn't be sent twice, and otherwise
once its retries get the same reply.
memcached at its connection limit (`-c`, 1024 by default) answers a new
connection with `ERROR Too many open connections` and closes it. That is a
failure too, as a refused connection is. Nothing has been sent yet, so the
operation is retried, even one that mustn't be sent twice. Once every attempt
has got that reply, it fails with `ServerError` and the server is marked dead,
so in a cluster its keys go to other servers until `optsDeadTimeout` has
passed. Other `ERROR` replies, which memcached sends for a command it doesn't
know, fail at once with `UnknownOp`.
### Servers and authentication
`newClient` takes one `ServerSpec` per server, and routes each key to one of
them. Credentials are set per server:
```haskell
mc <- M.newClient
[ M.ServerSpec "cache1.internal" "11211" (M.Auth "user" "secret")
, M.ServerSpec "cache2.internal" "11211" (M.Auth "user" "secret")
]
M.def
```
`parseServerSpec`, from `Database.Memcache.Types`, reads a server from a
`memcached://[user:password@]host[:port]` URI instead. The host defaults to
`127.0.0.1` and the port to `11211`:
```haskell
import Database.Memcache.Types (parseServerSpec)
spec <- either fail pure (parseServerSpec "memcached://user:secret@cache1.internal:11211")
mc <- M.newClient [spec] M.def
```
The `//` is required. Without it, as in `memcached:cache.example:11211` or
`memcached:/run/memcached.sock`, a URI has no host, port or credentials, so
`parseServerSpec` returns an error rather than the default server.
The server must be started with `-Y <authfile>`, where the auth file holds one
`username:password` line per user. This library connects without TLS, so
credentials and all data are sent unencrypted; only rely on them within a
trusted network.
### Unix sockets
A host that begins with `/` is the path of a Unix socket instead, for a
memcached on the same machine. Start memcached with `-s <path>` to listen on
the socket, which stops it listening on the network, and with `-a <mode>` to
set the socket's permissions: the default, `0700`, lets only memcached's own
user connect.
```haskell
mc <- M.newClient [M.ServerSpec "/run/memcached/memcached.sock" "11211" M.NoAuth] M.def
```
As a URI, the path follows an empty host, and there is no port:
`memcached:///run/memcached/memcached.sock`, or
`memcached://user:secret@/run/memcached/memcached.sock` with credentials. An
`@` in the path is written `%40`; a raw one is an error, so that a URI with one
slash too many, such as `memcached:///user:secret@cache.example`, is never
taken for a socket path holding the password. The error says that credentials
go right after `memcached://`: such a URI needs a slash fewer, not its `@`
written `%40`, which would make it that socket path after all.
The client doesn't use a socket's port to connect, but the port still names
the server, along with the path, when keys are routed, so changing it moves
keys to other servers. `"11211"`, which a URI gives, names the socket by its
path alone, as libmemcached's `memcached_server_add` does, and `"0"` names it
`path:0`, as libmemcached's `memcached_server_add_unix_socket` and pylibmc do.
The operating system limits the path's length: 108 bytes on Linux and 104 on
macOS, including the terminating NUL.
### Amazon ElastiCache
`Database.Memcache.ElastiCacheClient` creates a client from an ElastiCache
configuration endpoint (the address containing `.cfg`). It discovers the
cluster's nodes, then refreshes the node list in a background thread on the
given interval, in seconds:
```haskell
import qualified Database.Memcache.ElastiCacheClient as EC
endpoint <- either fail pure $
EC.parseConfigurationEndpoint "memcached://mycluster.abc123.cfg.use1.cache.amazonaws.com:11211"
mc <- EC.newClient M.def endpoint 60
```
`M.quit` stops the thread, so that no refresh replaces the servers once their
connections are closed. The thread also stops once the client has been garbage
collected.
Discovery connects to the configuration endpoint like any other server, so it
fails for a cluster running a memcached older than 1.6.10.
Each configuration has a version, which goes up as nodes are added or
removed. A refresh applies a configuration only if its version is higher than
that of the one applied last, the first discovery's included, so that a reply
from an endpoint that hasn't caught up yet can't roll the node list back. A
version that goes backwards is then ignored until it passes the one applied
last, or the client is made again. AWS's own cluster client does the same,
except that its refreshes don't count the configuration it was made with, so
the first of them to read a configuration applies it even at a lower or the
same version.
### Upgrading from 0.5
Version 0.6 changes the API, so code written for 0.5 needs these changes. Keys
go to the same servers as with 0.5.
- The `Options` durations are `NominalDiffTime`s in seconds, under new names:
`optsServerTimeout` is now `optsTimeout`, `optsFailRetryDelay` is
`optsRetryDelay` and `optsDeadRetryDelay` is `optsDeadTimeout`, with the
same defaults. They were in milliseconds, so
`M.def { M.optsServerTimeout = 500 }` becomes
`M.def { M.optsTimeout = 0.5 }`.
- ElastiCache's `newClient` takes the refresh interval last, in seconds:
`EC.newClient M.def (60 * 1000000) endpoint` becomes
`EC.newClient M.def endpoint 60`.
- `soKeepAlive` is a `NominalDiffTime` with every resource-pool version, where
resource-pool 0.4 and later made it a `Double`. It is still in seconds.
- `replace`, `append`, `prepend`, `delete`, `increment` and `decrement` take a
`Maybe Version`: pass `Nothing` wherever 0.5 code passed a version of `0`,
even one that is `0` only at run time (`fromMaybe 0 mv` becomes `mv`), and
`Just v` to check `v`.
- `increment` and `decrement` take the delta first, and the initial value,
which came before it, moves into a `Maybe` pair with the expiration:
`M.increment mc "points" 0 5 3600 0` becomes
`M.increment mc "points" 5 (Just (0, 3600)) Nothing`. `Nothing` for the pair
leaves a missing key missing, as an expiration of `maxBound` did.
- `Auth` is positional, without the `username` and `password` fields:
`M.Auth { M.username = "user", M.password = "secret" }` becomes
`M.Auth "user" "secret"`, and code that read the fields matches
`M.Auth user password` instead.
- `Database.Memcache.Socket`, `Cluster`, `Server`, `Ketama` and `Auth` are now
`Database.Memcache.Internal.Socket`, `Cluster`, `Server`, `Ketama` and
`Auth`, which the PVP doesn't cover. `Database.Memcache.Client` now exports
what a custom `optsGetServerForKey` needs (`ketamaServerForKey`,
`getServers`, `isAlive`, `serverHost` and `serverPort`; write `Client` for
`Cluster` in its type), and `Database.Memcache.Types` exports
`validateCredentials`.
- `KeyTooLong` is gone: an invalid key throws `InvalidKey`, and an invalid
`stats` argument `InvalidArgument`.
- `legacyServerForKey` is gone, so finish any switch from 0.4's router with
0.5.x first (see [Upgrading from 0.4](#upgrading-from-04)).
Some changes still compile, but behave differently:
- `cas` with version `0` stored unconditionally in 0.5, but now never stores,
as memcached never matches `0`; use `set` for that. `replace` with `Just 0`
doesn't store either, so on a memcached started with `-C`, where every
version is `0`, a `cas` or `replace` with the version from `get` never
stores.
- A handler for `StringException` no longer catches ElastiCache discovery
failures, which throw `MemcacheError`'s `DiscoveryError`.
- `getMany` and `setMany` return their results in the order of the keys
given, not grouped by server.
- Each server's pool holds up to four connections by default, where it held
one.
- An expiration over 2147483647 throws `InvalidArgument` before anything is
sent.
The [changelog](CHANGELOG.md) lists every change.
### Upgrading from 0.4
Version 0.5 requires memcached 1.6.10 or newer and refuses an older server, so
upgrade any older memcached first, including any behind a proxy.
Version 0.5 routes keys with ketama consistent hashing, where 0.4 sent keys to
no more than two servers at a time. With n servers, upgrading moves all but
about one key in n to a different server, once: about half the keys with 2
servers, 70% with 3 and 88% with 8. Expect a burst of cache misses.
While old and new versions run side by side, as in a rolling deploy, they read
and write a moved key on different servers. One can then read a stale copy of
a key that the other has changed or deleted, until the copy expires. To avoid
that, either switch every instance at once, at a quiet time, optionally
flushing the cache afterwards, or switch in stages with 0.5.x, the last
version with 0.4's router, deploying each step to every instance before
starting the next:
1. Upgrade to 0.5.x with `optsGetServerForKey = legacyServerForKey`, 0.4's
router, deprecated there, from `Database.Memcache.Cluster`. Keys stay
where they are, as long as the build uses the same `hashable` version and
platform as before. With `-Werror`, also pass `-Wno-deprecations`.
2. Add a second client for the same servers that uses `ketamaServerForKey`.
Whenever a key is changed or deleted, also delete it through that client,
unless both clients send it to the same server.
3. If a server was marked failed less than your longest expiry time ago,
flush the cache first. Then swap the two clients' routers.
4. Once your longest expiry time has passed since step 3 was on every
instance, remove the second client. If some keys never expire, flush the
cache instead of waiting, and then remove the second client.
5. Upgrade from 0.5.x.
The 0.5.1.0
[`Database.Memcache.Cluster`](https://hackage.haskell.org/package/memcache-0.5.1.0/docs/Database-Memcache-Cluster.html)
documentation has the details.
`optsServerRetries` changed too. It now counts the retries after an
operation's first attempt, where 0.4 counted the attempts, so a value of 1 or
more that you set yourself makes one more attempt than in 0.4. Set it one
lower to keep the old number of attempts. The default went from 2 to 1, which
still means two attempts.
When a server's host name resolves to several addresses, the client now tries
each in turn, where 0.4 tried only the first. If the addresses are separate
memcached instances, give each its own `ServerSpec`: while the first refuses
connections, new connections go to the next one that accepts, and so to another
cache.
## Licensing
This library is BSD-licensed.
## Tools
This library also includes a few tools for manipulating and experimenting with
memcached servers.
- `OpGen` -- A load generator for memcached. Doesn't collect timing statistics,
other tools like [mutilate](https://github.com/leverich/mutilate) already do
that very well. This tool is useful in conjunction with mutilate.
- `Loader` -- A tool to load random data of a certain size into a memcached
server. Useful for priming a server for testing.
## Architecture Notes
We're relying on `Data.Pool` for thread safety right now. Each server has its
own pool, and grabbing a connection from it (`Internal.Server.withSocket`)
blocks other requests using that connection until the operation completes.
`getMany`, `setMany` and `deleteMany` are the exception: they pipeline Meta
Text requests to each server in batches of up to 256, each batch over one
pooled connection.
Each reply in a batch has its own `optsTimeout`, as the single requests
the batch stands for would: the first reply's also covers waiting for a
connection and sending the batch, and each later reply's starts once the reply
before it has been read. So a server that sends each reply just in time can
hold a batch of n requests for about n + 1 timeouts per attempt. Meanwhile the
batch keeps its connection, so once every connection in the pool (see below)
is in use, other requests to that server wait for one, and those that run out
of time waiting throw `Timeout` without marking the server down.
By default each server's pool holds up to four connections
(`soNumResources = 4`), so up to four operations against the same server run
at once, and others wait for a free connection. Raising `soNumResources` in
the `ServerOptions` set through `optsServerOptions` allows more concurrent
operations without requiring a separate pool implementation.
Either way, a pool is fine for now.
The package's bounds leave out resource-pool 0.3, whose pools have a stripe
for each capability, whatever `soNumStripes` is: a thread could then wait for
a connection while other stripes had room, or for one it held itself.
## Other clients
- [C: libmemcached](http://libmemcached.org/libMemcached.html)
- [Java: SpyMemcached](http://code.google.com/p/spymemcached/)
- [Ruby: Dalli](https://github.com/mperham/dalli)
## Get involved!
We are happy to receive bug reports, fixes, documentation enhancements, and
other improvements.
Please report bugs via the
[github issue tracker](https://github.com/dterei/memcache-hs/issues), and
security issues as described in the
[security policy](https://github.com/dterei/memcache-hs/security/policy).
Master [git repository](https://github.com/dterei/memcache-hs):
- `git clone https://github.com/dterei/memcache-hs.git`
## Development
The package builds with [Stack](https://docs.haskellstack.org/) or
[cabal](https://www.haskell.org/cabal/), on GHC 9.2 or newer:
```sh
stack build
stack test
cabal build
cabal test all
```
`stack.yaml` uses Stackage LTS 22.14 (GHC 9.6). The oldest and newest snapshots
CI tests against have their own files, for example
`stack --stack-yaml stack-lts-20.26.yaml test` for GHC 9.2.
There are two test suites:
- `spec` holds the unit and property tests, which run against an in-process
mock server and need nothing installed.
- `integration` starts its own `memcached` servers on free local ports and
tests against them, so it needs memcached 1.6.13 or newer on your `PATH`.
Without it, the suite reports a single pending test instead of failing.
With 1.6.10 to 1.6.12, which the library accepts, two of its tests fail,
as those servers answer an `append` or `prepend` with the version the
request carried, or 0, rather than the new one.
memcached refuses to run as root without `-u`, so run the suite as an
ordinary user.
CI lints with [HLint](https://github.com/ndmitchell/hlint) 3.10, so please
check that `hlint .` prints `No hints` before opening a pull request. For any
user-visible change, propose a line for [CHANGELOG.md](CHANGELOG.md) in the
pull request's description; don't edit the file, as the next release's pull
request adds the lines.
CI runs both build tools on every pull request. The `CI` workflow builds and
tests with Stack against each `stack*.yaml` snapshot, and runs HLint and
weeder. The `Cabal` workflow builds and tests with cabal on GHC 9.2 to 9.14,
builds the library against the oldest dependency versions its bounds allow,
and builds and tests the source distribution; it also runs every Monday, so a
new dependency release that breaks the build shows up without a push. Both
install memcached, so the integration suite runs in full.
## Authors
This library is written and maintained by David Terei (<code@davidterei.com>).
Contributions have been made by the following great people:
- Alfredo Di Napoli (<alfredo.dinapoli@gmail.com>)
- Amit Levy
- Chris Martin
- drlkf
- Joel McCracken
- Steven Leiva