packages feed

memcache 0.5.1.0 → 0.6.0.0

raw patch · 28 files changed

+3068/−2776 lines, 28 filesdep ~hashable

Dependency ranges changed: hashable

Files

CHANGELOG.md view
@@ -1,3 +1,72 @@+# 0.6.0.0 - December 1st, 2026++Breaking API changes, most of them from #117, so code written for 0.5 needs+changes; see "Upgrading from 0.5" in the README. Two of them don't show up as+compile errors: `cas` with `0` never stores, and discovery failures are no+longer a `StringException`. Keys go to the same servers as with 0.5.++## Breaking changes++- The timeouts and delays in `Options` are `NominalDiffTime`s in seconds:+  `optsServerTimeout` is now `optsTimeout`, `optsFailRetryDelay` is+  `optsRetryDelay` and `optsDeadRetryDelay` is `optsDeadTimeout`, where they+  were in milliseconds, with the same defaults. ElastiCache's `newClient`+  takes the refresh interval last, in seconds, where it was the second+  argument, in microseconds. `soKeepAlive` is a `NominalDiffTime` with every+  resource-pool version (#126).+- `replace`, `append`, `prepend`, `delete`, `increment` and `decrement` take+  a `Maybe Version`: `Nothing` skips the check, as `0` did, and `Just` sends+  the version, `0` included. The request encoders change to match (#124).+- `increment` and `decrement` take the delta, then a+  `Maybe (Initial, Expiration)` for creating a missing key, instead of an+  initial value before the delta and an expiration after it. `Nothing`+  creates none, as an expiration of `maxBound` did (#124).+- `Auth` is positional, `Auth !Username !Password`, so the partial `username`+  and `password` fields are gone; `show` gives `Auth "user" <redacted>`+  (#122).+- `Database.Memcache.Socket`, `Cluster`, `Server`, `Ketama` and `Auth` are+  now `Database.Memcache.Internal.Socket`, `Cluster`, `Server`, `Ketama` and+  `Auth`: still exposed, but not covered by the PVP (#129).+- `ClientError`'s `KeyTooLong` is replaced by `InvalidKey`, for a key that is+  empty or over 250 bytes as given or encoded, and `InvalidArgument`, for an+  invalid `stats` argument (#119).+- ElastiCache's `newClient` throws `DiscoveryError`, a new `MemcacheError`+  constructor, where discovery threw a `StringException`; running out of+  time is still `ClientError Timeout` (#120).+- `legacyServerForKey`, 0.4's router, is removed, so switching from 0.4 in+  stages needs 0.5.x first (#125).++## Behaviour changes++- `cas` always sends its version, and memcached never matches `0`, so `cas`+  with `0` never stores, where it stored unconditionally; 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 (#124).+- `getMany`, `setMany` and `keyedBatchOp` return their results in the order+  given, not grouped by server; `getMany` still returns only the hits+  (#121).+- `defaultServerOptions` has `soNumResources = 4`, where it was 1, so each+  server's pool holds up to four connections by default (#123).+- An expiration over 2147483647 throws+  `ClientError (InvalidArgument "expiration exceeds 2147483647")` before+  anything is sent, in every operation that takes one. It used to be sent,+  and memcached rejected it or read it as a time in the past (#128).++## New++- `Database.Memcache.Client` exports `ketamaServerForKey`, `getServers`,+  `isAlive`, `serverHost` and `serverPort`, for a custom+  `optsGetServerForKey`, and `Database.Memcache.Types` exports+  `validateCredentials`. The new `Database.Memcache.Internal.Lookup` runs+  host lookups (#129).++## Fixes++- A host lookup runs in a thread of its own, so with the threaded runtime an+  attempt's timeout ends the wait for a slow lookup, which used to overrun+  it. A server's attempts share the lookup in flight (#127).+ # 0.5.1.0 - November 29th, 2026  Fixes found after 0.5.0.0 (#46), with one new function. Some change
− Database/Memcache/Auth.hs
@@ -1,87 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{-|-Module      : Database.Memcache.Auth-Description : Meta Text auth-file authentication-Copyright   : (c) David Terei, 2016-License     : BSD-Maintainer  : code@davidterei.com-Stability   : stable-Portability : GHC--Authentication for Memcached's experimental text-protocol auth-file mode.--}-module Database.Memcache.Auth-  ( Authentication(..)-  , Username-  , Password-  , authenticate-  , validateCredentials-  ) where--import Database.Memcache.Errors-import Database.Memcache.Socket-import Database.Memcache.Types-import Database.Memcache.Types.Authentication (validateCredentials)--import Control.Monad (void, when)-import qualified Data.ByteString.Char8 as B8-import UnliftIO.Exception (catch, throwIO)---- | Authenticate a connection using text-protocol credentials.------ The credentials are sent only to a server in auth-file mode: first this--- sends @version@, which such a server rejects with @CLIENT_ERROR@ until the--- connection has authenticated. A server that answers it with @VERSION@--- isn't in that mode, and would store the credentials as an ordinary item,--- so this throws 'InvalidAuthentication' instead, as it does, before sending--- anything, for credentials that contain a forbidden delimiter. An @ERROR@--- or @SERVER_ERROR@ reply throws what it would as the reply to any request--- (see 'responseStatus'), such as 'ServerError' for the--- @ERROR Too many open connections@ that memcached sends to a new connection--- when it is at its connection limit. Any other reply throws 'UnknownOp',--- quoting it, as the same reply does in the version check that every new--- connection makes.------ Once the credentials are sent, this throws @'OpError' 'TextAuthFail'@ when--- the server rejects them, and another 'MemcacheError', such as--- 'UnexpectedResponse', for any other reply but @STORED@.-authenticate :: Connection -> Authentication -> IO ()-authenticate _ NoAuth = return ()-authenticate socket (Auth user pass) = do-  case validateCredentials user pass of-    Left message -> throwIO $ ClientError (InvalidAuthentication message)-    Right () -> return ()-  -- Without -Y authfile, "set auth ..." is just a normal store, so credentials-  -- would be readable via "get auth"; probe with a real command first so we-  -- never send them to a server that isn't gating on auth-file mode.-  sendRaw socket versionRequest-  probe <- recvResponse socket-  case responseCode probe of-    "CLIENT_ERROR" -> return ()-    "VERSION" -> throwIO $ ClientError-      (InvalidAuthentication "server is not in auth-file mode; refusing to send credentials")-    -- Any other reply doesn't show the mode either way, and fails as it would-    -- fail the version check that follows: an error reply throws as it would-    -- for any request, so that memcached at its connection limit is a server-    -- failure, and anything else throws UnknownOp, a client fault, as a retry-    -- would get the same reply.-    code -> do-      when (code `elem` ["ERROR", "SERVER_ERROR"]) $ void (responseStatus probe)-      throwIO $ ProtocolError UnknownOp-        { protocolError = "Expected VERSION or CLIENT_ERROR, got: "-            <> show (B8.unwords (code : responseTokens probe)) }-  let credentials = user <> B8.singleton ' ' <> pass-  sendRaw socket (authRequest credentials)-  response <- recvResponse socket-  result <- responseStatus response `catch` handleAuthFailure-  case result of-    NoError | responseCode response == "STORED" -> return ()-    -- Any other reply could leave the connection out of step, so it must not-    -- reach the pool.-    NoError -> throwIO $ ProtocolError UnexpectedResponse-      { protocolError = "Expected AUTH, got: " <> show (responseCode response) }-    status -> throwIO $ OpError status-  where-    handleAuthFailure (ProtocolError BadCommand{}) = throwIO $ OpError TextAuthFail-    handleAuthFailure err = throwIO (err :: MemcacheError)
Database/Memcache/Client.hs view
@@ -13,7 +13,7 @@ key-value store typically used as a distributed and shared cache. Clients can connect to a single Memcached server or a cluster of servers; clusters route each key to a server by ketama consistent hashing, compatible with-libmemcached (see "Database.Memcache.Cluster").+libmemcached (see "Database.Memcache.Internal.Cluster").  This requires memcached 1.6.10 or newer. Older servers reject the meta set command this client stores values with, without reading the value that@@ -33,20 +33,16 @@  Expected return values (like misses) are returned as part of the return type, while unexpected errors are thrown as exceptions. Exceptions are either of type-'MemcacheError' or an 'IO' exception thrown by the network, except when-ElastiCache discovery fails on the configuration endpoint's reply, such as an-error reply or a configuration it can't use:-"Database.Memcache.ElastiCacheClient"'s @newClient@ then throws a-@StringException@ from "UnliftIO.Exception", and its documentation lists the-cases. 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 a client is created, and-a Unix socket path too long for the system, when an operation connects to it.+'MemcacheError' or an 'IO' exception thrown by the network. 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 a client is created, and a Unix socket path+too long for the system, when an operation connects to it.  We support the following logic for handling failure in operations:  * __Timeouts__: we time out any attempt at an operation that takes longer-                than 'optsServerTimeout', including time spent waiting for a+                than 'optsTimeout', including time spent waiting for a                 free connection to the server, and consider it failed. The                 batches of 'getMany', 'setMany' and 'deleteMany' have that                 time for each reply instead, as their single requests would.@@ -70,8 +66,8 @@              failure before any of it was sent, such as a refused              connection or a timeout while waiting for a free connection.              That is 'increment', 'decrement', 'append', 'prepend', 'add',-             'delete', and 'cas' and 'replace' with a version other than-             @0@. Once such a request may have reached the server, a+             'delete' and 'cas', and 'replace' with a version. Once such a+             request may have reached the server, a              failure is thrown, and the server is marked dead as if every              attempt had failed: the server may have carried out the              request, and a retry could apply it twice, or report failure@@ -105,12 +101,15 @@ Some of this behavior can be configured through the 'Options' data type. We also have the following concepts exposed by Memcached: -  [@version@] Each value has a 'Version' associated with it. This is simply a-              numeric, monotonically increasing value. The version field-              allows for a primitive version of 'cas' to be implemented.-              Operations that take a 'Version' only change a value whose-              version matches it, except that a 'Version' of @0@ skips the-              check.+  [@version@] Each value has a 'Version' associated with it, a number that+              changes each time the value is stored or changed. The version+              field allows for a primitive version of 'cas' to be+              implemented. 'cas' only changes a value whose version matches+              the one given, and so do the operations that take a+              @Maybe Version@ when given @Just@ one. memcached never matches+              a version of @0@ in 'cas' and 'replace', though, and doesn't+              check it in 'increment', 'decrement', 'append' and 'prepend'.+              On a memcached started with @-C@, every version is @0@.    [@expiration@] Each value pair has an 'Expiration' associated with it. Once                  a value expires, it will no longer be returned from the cache@@ -125,28 +124,9 @@                  which the value should expire, so one in the past expires it                  at once. memcached takes an expiration as a signed 32-bit                  number, so the latest timestamp it takes is @2147483647@-                 (2^31 - 1), 03:14:07 UTC on 19 January 2038: use that or-                 less. This client sends a larger one, up to 'maxBound', as-                 it is, and what memcached does with it depends on its-                 version. memcached 1.6.45 and later reject the request with-                 @CLIENT_ERROR@, which the operation throws as-                 v'ProtocolError' 'BadCommand', and carry out none of it:-                 'touch' and 'gat' leave the value's expiration as it was,-                 and 'increment' and 'decrement' fail even for a key that-                 exists. Earlier releases do the same on a 32-bit system, but-                 on a 64-bit one read such a number as negative, and so in-                 the past: they report success, but the value expires at-                 once. 'set', 'setMany', 'add', 'replace' and 'cas' return a-                 version for a value that is already gone, 'touch' returns a-                 version too, and 'gat' returns the value it finds, which-                 then expires. 'increment' and 'decrement' create a missing-                 key with the 'Initial' value and return it, but the key-                 expires at once, so each call returns the 'Initial' value-                 again. For those two, though, 'maxBound' isn't sent: it-                 means that a missing key isn't created. For 'flush',-                 memcached rejects such a time from 1.6.40 on, and 'flush'-                 throws, flushing nothing; read as negative, the time-                 flushes at once.+                 (2^31 - 1), 03:14:07 UTC on 19 January 2038. A larger one+                 throws v'ClientError' 'InvalidArgument' before anything is+                 sent.    [@flags@] Each value can have a small amount of fixed metadata associated             with it beyond the value itself, these are the 'Flags'.@@ -161,7 +141,7 @@                  which holds the key and a header as well as the value, so                  even at @-I 1024m@ memcached refuses a value of exactly                  1 GiB. An attempt must send or read the whole value within-                 'optsServerTimeout', so over a network, a value of more+                 'optsTimeout', so over a network, a value of more                  than a few tens of MiB can need more than the default                  750 ms: at 1 Gbit/s, 750 ms carries less than 90 MiB. @@ -198,6 +178,10 @@         -- ** Configuration types         Retries, ServerOptions(..), defaultServerOptions, Server, +        -- ** Routing+        -- | The default 'optsGetServerForKey', and what a custom one can use.+        ketamaServerForKey, getServers, isAlive, serverHost, serverPort,+         -- * Fields & Values         Key, Value, Initial, Delta, Expiration, Flags, Version, @@ -222,10 +206,10 @@         MemcacheError(..), Status(..), ClientError(..), ProtocolError(..)     ) where -import           Database.Memcache.Cluster import           Database.Memcache.Errors-import           Database.Memcache.Server-import           Database.Memcache.Socket+import           Database.Memcache.Internal.Cluster+import           Database.Memcache.Internal.Server+import           Database.Memcache.Internal.Socket import           Database.Memcache.Types import           Database.Memcache.Types.Cluster (Cluster (cStopRefresh)) import           Database.Memcache.Util    (maxValueLength)@@ -253,9 +237,9 @@ -- opened on first use and reused across requests. A client created for each -- request instead opens (and, with credentials, authenticates) a new -- connection to every server it uses, every time. Each pool holds as many--- connections as 'soNumResources' and 'soNumStripes' allow, one by default,+-- connections as 'soNumResources' and 'soNumStripes' allow, four by default, -- so concurrent requests to a server beyond that wait for a free connection.--- The wait counts towards each attempt's 'optsServerTimeout'. If the last+-- The wait counts towards each attempt's 'optsTimeout'. If the last -- attempt runs out of time while still waiting, the server isn't marked down; -- running out of time afterwards is a server failure, however long the wait -- was.@@ -288,8 +272,7 @@ -- 'quit' first stops the thread that refreshes the client's servers, for good, -- so that no refresh replaces them once their connections are closed. A -- refresh in progress is abandoned, and its connection to the configuration--- endpoint closed. 'quit' doesn't wait for the thread to end, as the thread--- can't be interrupted while it looks up the endpoint's name. If the client is+-- endpoint closed. 'quit' doesn't wait for the thread to end. If the client is -- used after 'quit', it keeps the servers it had. quit :: Client -> IO () quit c = do@@ -330,10 +313,11 @@     (_, ErrKeyNotFound) -> return Nothing     _ -> failResponse response "GET" --- | Fetch many keys. Missing keys are omitted from the result.+-- | Fetch many keys, returning the hits in the order of the keys given.+-- Missing keys are omitted from the result. -- -- The requests to each server are pipelined, in batches of up to 256 keys.--- Each reply in a batch has its own 'optsServerTimeout', as a 'get' would:+-- Each reply in a batch has its own 'optsTimeout', as a 'get' 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@@ -357,6 +341,7 @@ -- expiration value of @0@ to store forever. gat :: Client -> Key -> Expiration -> IO (Maybe (Value, Flags, Version)) gat c k e = do+  checkExpiration e   response <- keyedOpExpecting c "GAT" getReplies k (`gatRequest` e)   status <- responseStatus response   case (responseCode response, status) of@@ -369,6 +354,7 @@ -- Use an expiration value of @0@ to store forever. touch :: Client -> Key -> Expiration -> IO (Maybe Version) touch c k e = do+  checkExpiration e   response <- keyedOpExpecting c "TOUCH" touchReplies k (`touchRequest` e)   status <- responseStatus response   case status of@@ -383,21 +369,20 @@ -- 'OpError' 'ErrValueTooLarge' before anything is sent, as it does in every -- operation that stores a value. set :: Client -> Key -> Value -> Flags -> Expiration -> IO Version-set c k v f e = store c k v f e 0 Set "SET"+set c k v f e = store c k v f e Nothing Set "SET"  -- | Store many key-value pairs, as 'set' does, returning the new @Version@ of--- each. Like 'getMany', the requests to each server are pipelined, and the--- results are grouped by server rather than in the order given; within a--- server they keep the input order. A key given more than once is stored--- once per occurrence, in order, so its last entry in the result is the--- version now stored. Use an expiration value of @0@ to store forever.+-- each, in the order given. Like 'getMany', the requests to each server are+-- pipelined. A key given more than once is stored once per occurrence, in+-- order, so its last entry in the result is the version now stored. Use an+-- expiration value of @0@ to store forever. ----- Every key, and the length of every value, is checked before anything is--- sent, so an invalid key or a value larger than 1 GiB stores nothing. Every--- value is therefore evaluated before the first request is sent. Each+-- Every key, value length and expiration is checked before anything is+-- sent, so an invalid one stores nothing. Every value is therefore evaluated+-- before the first request is sent. Each -- server's pairs are sent in batches of up to 256 that close early once their -- requests reach 1 MiB (a larger request goes alone). Each reply in a batch--- has its own 'optsServerTimeout', as a 'set' would: the first reply's also+-- has its own 'optsTimeout', as a 'set' 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/ pairs for about@@ -407,7 +392,7 @@ -- throws, some of the pairs may have been stored. setMany :: Client -> [(Key, Value, Flags, Expiration)] -> IO [(Key, Version)] setMany c items = do-  mapM_ (\(_, v, _, _) -> checkValue v) items+  mapM_ (\(_, v, _, e) -> checkValue v >> checkExpiration e) items   replies <- keyedBatchOp c [(k, \wire -> setManyRequest wire v f e) | (k, v, f, e) <- items]   mapM stored replies   where@@ -423,12 +408,13 @@ -- exist or the version match fails, @Nothing@ is returned. Use an expiration -- value of @0@ to store forever. ----- A version of @0@ skips the check, so the value is stored unconditionally, as--- with 'set'.+-- A version of @0@ never matches, so on a memcached started with @-C@, where+-- every version is @0@, nothing is stored. cas :: Client -> Key -> Value -> Flags -> Expiration -> Version -> IO (Maybe Version) cas c k v f e ver = do   checkValue v-  response <- resendUnlessVersioned ver c "SET" storeReplies k (\wire -> storeRequest Set wire v f e ver)+  checkExpiration e+  response <- keyedOpExpectingOnce c "SET" storeReplies k (\wire -> storeRequest Set wire v f e (Just ver))   status <- responseStatus response   case status of     NoError -> return $ Just (responseCas response)@@ -442,7 +428,8 @@ add :: Client -> Key -> Value -> Flags -> Expiration -> IO (Maybe Version) add c k v f e = do   checkValue v-  response <- keyedOpExpectingOnce c "ADD" storeReplies k (\wire -> storeRequest Add wire v f e 0)+  checkExpiration e+  response <- keyedOpExpectingOnce c "ADD" storeReplies k (\wire -> storeRequest Add wire v f e Nothing)   status <- responseStatus response   case status of     NoError -> return $ Just (responseCas response)@@ -453,11 +440,13 @@ -- identifier. If the key doesn't already exist, then fail and return 'Nothing'. -- Use an expiration value of @0@ to store forever. ----- A non-zero version must match the @Version@ of the key-value pair at the--- server, otherwise 'Nothing' is returned. A version of @0@ skips the check.-replace :: Client -> Key -> Value -> Flags -> Expiration -> Version -> IO (Maybe Version)+-- A version given as @Just@ must match the @Version@ of the key-value pair at+-- the server, otherwise 'Nothing' is returned. 'Nothing' skips the check, and+-- @Just 0@ never matches.+replace :: Client -> Key -> Value -> Flags -> Expiration -> Maybe Version -> IO (Maybe Version) replace c k v f e ver = do   checkValue v+  checkExpiration e   response <- resendUnlessVersioned ver c "REPLACE" storeReplies k (\wire -> storeRequest Replace wire v f e ver)   status <- responseStatus response   case status of@@ -467,9 +456,10 @@     ErrItemNotStored -> return Nothing     _ -> failResponse response "REPLACE" -store :: Cluster -> Key -> Value -> Flags -> Expiration -> Version -> StoreMode -> String -> IO Version+store :: Cluster -> Key -> Value -> Flags -> Expiration -> Maybe Version -> StoreMode -> String -> IO Version store c k v f e ver mode operation = do   checkValue v+  checkExpiration e   response <- keyedOpExpecting c operation storeReplies k (\wire -> storeRequest mode wire v f e ver)   status <- responseStatus response   case status of@@ -483,35 +473,44 @@ checkValue :: Value -> IO () checkValue value = when (B.length value > maxValueLength) $ throwStatus ErrValueTooLarge +-- | Reject an expiration over 2147483647, the most memcached takes, before+-- anything is sent.+checkExpiration :: Expiration -> IO ()+checkExpiration e = when (e > 2147483647) $+  throwIO $ ClientError (InvalidArgument "expiration exceeds 2147483647")+ -- | Increment a numeric value stored against a key, returning the incremented -- value and the @Version@ identifier of the key-value pair. Throws -- 'OpError' 'ErrValueNonNumeric' if the stored value isn't a number. ----- If the key doesn't exist, it is created with the 'Initial' value, which is--- returned without the delta applied. The expiration is only used for a key--- created this way, and doesn't change the expiration of an existing key; use--- @0@ for a created key that never expires. To leave a missing key missing--- instead, pass an expiration of 'maxBound': nothing is created and 'Nothing'--- is returned.+-- Given an 'Initial' value and an 'Expiration', a missing key is created with+-- the 'Initial' value, which is returned without the delta applied. The+-- expiration is only used for a key created this way, and doesn't change the+-- expiration of an existing key; use @0@ for a created key that never+-- expires. Given 'Nothing', a missing key stays missing, and 'Nothing' is+-- returned. ----- A non-zero version must match the @Version@ of an existing key-value pair,--- otherwise 'Nothing' is returned. A version of @0@ skips the check.-increment :: Client -> Key -> Initial -> Delta -> Expiration -> Version -> IO (Maybe (Word64, Version))-increment c k i d e ver = arithmetic c k i d e ver Incr "INCREMENT"+-- A version given as @Just@ must match the @Version@ of an existing key-value+-- pair, otherwise 'Nothing' is returned. 'Nothing' skips the check, and so+-- does @Just 0@, as memcached doesn't check a version of @0@ here.+increment :: Client -> Key -> Delta -> Maybe (Initial, Expiration) -> Maybe Version -> IO (Maybe (Word64, Version))+increment c k d create ver = arithmetic c k d create ver Incr "INCREMENT"  -- | Decrement a numeric value stored against a key, returning the decremented -- value and the @Version@ identifier of the key-value pair. Memcached doesn't -- decrement below @0@. ----- Otherwise this behaves like 'increment': a missing key is created with the--- 'Initial' value unless the expiration is 'maxBound', a version of @0@ skips--- the check, and a non-numeric value throws 'OpError' 'ErrValueNonNumeric'.-decrement :: Client -> Key -> Initial -> Delta -> Expiration -> Version -> IO (Maybe (Word64, Version))-decrement c k i d e ver = arithmetic c k i d e ver Decr "DECREMENT"+-- Otherwise this behaves like 'increment': a missing key is created only when+-- given an 'Initial' value and an 'Expiration', a version is checked only when+-- given as @Just@, and a non-numeric value throws 'OpError'+-- 'ErrValueNonNumeric'.+decrement :: Client -> Key -> Delta -> Maybe (Initial, Expiration) -> Maybe Version -> IO (Maybe (Word64, Version))+decrement c k d create ver = arithmetic c k d create ver Decr "DECREMENT" -arithmetic :: Cluster -> Key -> Initial -> Delta -> Expiration -> Version -> ArithMode -> String -> IO (Maybe (Word64, Version))-arithmetic c k i d e ver mode operation = do-  response <- keyedOpExpectingOnce c operation arithmeticReplies k (\wire -> arithmeticRequest mode wire i d e ver)+arithmetic :: Cluster -> Key -> Delta -> Maybe (Initial, Expiration) -> Maybe Version -> ArithMode -> String -> IO (Maybe (Word64, Version))+arithmetic c k d create ver mode operation = do+  mapM_ (checkExpiration . snd) create+  response <- keyedOpExpectingOnce c operation arithmeticReplies k (\wire -> arithmeticRequest mode wire d create ver)   status <- responseStatus response   case status of     NoError -> return $ Just (responseNumber response, responseCas response)@@ -524,29 +523,29 @@ -- identifier of the key-value pair when successful, or 'Nothing' if the key -- doesn't exist. ----- A non-zero version must match the @Version@ of the key-value pair at the--- server, otherwise 'Nothing' is returned. A version of @0@ skips the check.+-- A version given as @Just@ must match the @Version@ of the key-value pair at+-- the server, otherwise 'Nothing' is returned. 'Nothing' skips the check, and+-- so does @Just 0@, as memcached doesn't check a version of @0@ here. -- -- memcached 1.6.10 to 1.6.12 return the version given instead of the new one,--- so @0@ if the check was skipped. Passing that @0@ back as a version skips--- the check.-append :: Client -> Key -> Value -> Version -> IO (Maybe Version)+-- so @0@ if the check was skipped.+append :: Client -> Key -> Value -> Maybe Version -> IO (Maybe Version) append c k v ver = modify c k v ver Append "APPEND"  -- | Prepend a value to an existing key-value pair, returning the new @Version@ -- identifier of the key-value pair when successful, or 'Nothing' if the key -- doesn't exist. ----- A non-zero version must match the @Version@ of the key-value pair at the--- server, otherwise 'Nothing' is returned. A version of @0@ skips the check.+-- A version given as @Just@ must match the @Version@ of the key-value pair at+-- the server, otherwise 'Nothing' is returned. 'Nothing' skips the check, and+-- so does @Just 0@, as memcached doesn't check a version of @0@ here. -- -- memcached 1.6.10 to 1.6.12 return the version given instead of the new one,--- so @0@ if the check was skipped. Passing that @0@ back as a version skips--- the check.-prepend :: Client -> Key -> Value -> Version -> IO (Maybe Version)+-- so @0@ if the check was skipped.+prepend :: Client -> Key -> Value -> Maybe Version -> IO (Maybe Version) prepend c k v ver = modify c k v ver Prepend "PREPEND" -modify :: Cluster -> Key -> Value -> Version -> StoreMode -> String -> IO (Maybe Version)+modify :: Cluster -> Key -> Value -> Maybe Version -> StoreMode -> String -> IO (Maybe Version) modify c k v ver mode operation = do   checkValue v   response <- keyedOpExpectingOnce c operation storeReplies k (\wire -> modifyRequest mode wire v ver)@@ -560,10 +559,10 @@  -- | Delete a key, returning whether it was deleted. ----- A non-zero version must match the @Version@ of the key-value pair at the--- server, otherwise the key isn't deleted and 'False' is returned. A version--- of @0@ deletes the key unconditionally.-delete :: Client -> Key -> Version -> IO Bool+-- A version given as @Just@ must match the @Version@ of the key-value pair at+-- the server, otherwise the key isn't deleted and 'False' is returned.+-- 'Nothing' deletes the key unconditionally.+delete :: Client -> Key -> Maybe Version -> IO Bool delete c k ver = do   response <- keyedOpExpectingOnce c "DELETE" deleteReplies k (`deleteRequest` ver)   status <- responseStatus response@@ -574,10 +573,10 @@     _ -> failResponse response "DELETE"  -- | Delete many keys, pipelining the requests to each server as 'getMany'--- does. The deletes are unconditional, like 'delete' with a version of @0@.+-- does. The deletes are unconditional, like 'delete' with 'Nothing'. -- -- As in 'getMany', each reply in a batch of up to 256 keys has its own--- 'optsServerTimeout', the first reply's also covering waiting for a+-- 'optsTimeout', the first reply's also covering waiting for a -- connection and sending the batch. So a server that sends each reply just in -- time can hold a batch of /n/ keys for about /n/ + 1 timeouts per attempt, -- as /n/ calls to 'delete' would.@@ -606,23 +605,18 @@ -- rather than immediately. -- -- As with an 'Expiration', a time of up to 30 days (@2592000@) is a number of--- seconds from now, and a larger one a Unix time, up to @2147483647@--- (2^31 - 1), since memcached takes it as a signed 32-bit number. memcached--- 1.6.40 and later reject a time of @2147483648@ or more, 'maxBound'--- included, with @CLIENT_ERROR@, and flush nothing; 'flush' then throws--- v'ProtocolError' 'BadCommand'. Earlier releases do the same on a 32-bit--- system, but on a 64-bit one read such a time as negative, and flush at--- once, as with 'Nothing'. memcached flushes nothing, though, for a Unix time--- from before it started.+-- seconds from now, and a larger one a Unix time, up to @2147483647@; a later+-- one throws v'ClientError' 'InvalidArgument' before anything is sent.+-- memcached flushes nothing, though, for a Unix time from before it started. -- -- @flush_all@ is sent to every server in turn, including servers marked dead, -- which would otherwise keep their values and serve them once they are used -- again. As for any operation, each server's request is retried after a -- failure, and a server whose attempts all fail is marked dead, or, if it was -- marked already, marked again from then. A server marked dead that answers--- stays marked until 'optsDeadRetryDelay' has passed since it was marked. So+-- stays marked until 'optsDeadTimeout' has passed since it was marked. So -- a server that is down delays every flush, even while it is marked dead: by--- 'optsFailRetryDelay' before each retry, and by 'optsServerTimeout' for each+-- 'optsRetryDelay' before each retry, and by 'optsTimeout' for each -- attempt it doesn't answer. -- -- A server that fails, or gives a reply other than @OK@, doesn't stop the@@ -631,6 +625,7 @@ -- flushed. 'NoServersReady' is thrown only when the client has no servers. flush :: Client -> Maybe Expiration -> IO () flush c e = do+  mapM_ checkExpiration e   servers <- getServers c   when (null servers) $ throwIO (ClientError NoServersReady)   outcomes <- mapM flushServer servers@@ -695,7 +690,7 @@       | B.null args ||         B.length args > 250 ||         B.any (\byte -> byte < 0x20 || byte == 0x7f) args =-          throwIO $ ClientError (KeyTooLong "invalid stats argument")+          throwIO $ ClientError (InvalidArgument "stats argument")       | otherwise = return ()      -- Each line counts as sent, line end included. The entries kept are@@ -784,9 +779,9 @@ -- again: it stores the same value. A store with one is sent once, as -- 'keyedOpExpectingOnce' describes: its success changes the item's version, -- so a second one would find it changed and report failure.-resendUnlessVersioned :: Version -> Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response-resendUnlessVersioned 0 = keyedOpExpecting-resendUnlessVersioned _ = keyedOpExpectingOnce+resendUnlessVersioned :: Maybe Version -> Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response+resendUnlessVersioned Nothing = keyedOpExpecting+resendUnlessVersioned (Just _) = keyedOpExpectingOnce  -- | The value, flags and CAS version carried by a @VA@ response. valueResult :: Response -> (Value, Flags, Version)
− Database/Memcache/Cluster.hs
@@ -1,938 +0,0 @@-{-# LANGUAGE RecordWildCards   #-}-{-# LANGUAGE OverloadedStrings #-}--{-|-Module      : Database.Memcache.Cluster-Description : Cluster Handling-Copyright   : (c) David Terei, 2016-License     : BSD-Maintainer  : code@davidterei.com-Stability   : stable-Portability : GHC--Handles a group of connections to different Memcached servers.--= Routing--Keys are spread over the servers by ketama consistent hashing, computed-exactly as libmemcached does for @MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@ (see-"Database.Memcache.Ketama"). Each server gets 160 points on a 32-bit ring-(156 for some numbers of servers), taken from MD5 digests of its name, and a-key goes to the server owning the first point at or after the MD5 hash of the-key. Adding or removing a server only moves the keys on that server's points,-unless it changes the number of points each server gets (from 24 servers to-25, say), which moves a few percent of the other keys too.--Every server has weight 1, and is named from the host and port strings of its-'ServerSpec' exactly as written: the host alone for port @\"11211\"@,-otherwise @host:port@. Hosts are not resolved, so @localhost@ and @127.0.0.1@-are different names. A Unix socket is named by its path in the same way, as-the bytes the client connects to, one per 'Char' (see 'ssHost'), whereas a-host is named in UTF-8. The client doesn't use a socket's port to connect,-but port @\"11211\"@ names it by the 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 key is hashed as given,-not in its base64 form on the wire. Other clients using libmemcached's-weighted ketama distribution therefore choose the same server for every key,-as long as they are given the same host strings and ports in the same order-and equal weights: libmemcached with @MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@,-php-memcached with @OPT_LIBKETAMA_COMPATIBLE@, pylibmc with the-@ketama_weighted@ behavior, and twemproxy with @hash: md5@ and-@distribution: ketama@ and its servers listed without node names.--The order of the servers only matters in the rare case that two of them have-a point with the same value. The server listed first then owns the point, as-in libmemcached 1.1 and later. Earlier versions of libmemcached, and-twemproxy, leave such a tie to their C library's sort, so they may choose-differently for the keys just below that point.--'ketamaServerForKey' routes keys this way, and is the default-'optsGetServerForKey'.--= Failures--When every attempt at an operation against a server fails, we mark the-server as failed and remove it temporarily from the set of servers available,-unless the last attempt only ran out of time waiting for a free connection to-it (see 'optsServerRetries'). An operation whose request mustn't be sent-twice, such as an increment, makes no more attempts once one has failed after-its request may have reached the server, so that failure marks the server-failed (see 'keyedOpExpectingOnce'). A key whose server is marked failed goes-to the next live server found walking forward round the ring, so keys on live-servers stay where they are, and 'NoServersReady' is thrown only when every-server is marked failed. This is where libmemcached's auto-eject sends the key too,-except when the number of live servers changes how many points each server-gets (from 26 servers to 25, say): libmemcached rebuilds the ring from the-live servers, while we keep every server's points.--A server marked failed still gets the requests of 'serverOpExpecting', which-runs a request against the server it is given. @flush@ uses it to send-@flush_all@ to every server, so that a server marked failed doesn't serve-values from before the flush once it is used again.--= Upgrading from 0.4--Versions before 0.5 compared a @hashable@ hash of the key with hashes of the-servers. They sent keys to no more than two servers at a time, and the-mapping could change with the @hashable@ version. That router is kept for-one release, deprecated, as 'legacyServerForKey'.--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. A single server is unaffected.--While old and new versions run side by side, as in a rolling deploy, they-read and write a moved key on different servers. A change or delete made by-one is not seen by the other, which can read a stale copy until the copy-expires, even after the deploy.--One way to switch is all at once, at a quiet time. Copies stored under the-old mapping stay on their servers, where failover can still find them, so-you may want to flush the cache afterwards.--The other way avoids the stale reads of a rolling deploy by switching in-stages. Deploy each step to every instance before starting the next:--1. Upgrade with @optsGetServerForKey = legacyServerForKey@. Keys stay where-   they are, as long as the build uses the same @hashable@ version and-   platform as before, and the servers come from 'newCluster' or from-   ElastiCache discovery (see 'legacyServerForKey'). GHC warns that it is-   deprecated, so a build with @-Werror@ also needs @-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 the second-   client, unless both clients send it to the same server: compare the-   'serverHost' and 'serverPort' of the servers their routers return for-   the key.--3. If a server was marked failed less than your longest expiry time ago,-   flush the cache first. Then swap the two clients' routers. Every change-   still deletes the key under the other mapping, so neither version reads a-   stale copy of a key the other has changed or deleted.--4. Once your longest expiry time has passed since step 3 was on every-   instance, remove the second client. Until then, copies stored under the-   old mapping can still be on a key's old server, where failover can find-   them, and the second client's deletes keep them from going stale. If-   some keys never expire, flush the cache instead of waiting, and then-   remove the second client.--The flush in step 3 removes copies that a failover stored on a key's new-server before step 2 was on every instance. Step 2's deletes remove such a-copy only when the key next changes. Counters and locks kept in memcached-can't be moved this way: while instances use different mappings, they-update them on different servers.--'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, after one-more 'optsFailRetryDelay'. Set it one lower to keep the old number of-attempts. The default went from 2 to 1, which still means two attempts.--}-module Database.Memcache.Cluster (-        -- * Cluster-        -- | A collection of Memcached servers with retry and routing state.-        Cluster, ServerSpec(..), Options(..), defaultOptions, newCluster,-        getServers, setServers,--        -- * Routing-        -- | Routers for 'optsGetServerForKey', and 'isAlive' for writing one.-        ketamaServerForKey, isAlive, legacyServerForKey,--        -- * Operations-        Retries, keyedOp, keyedOpExpecting, keyedOpExpectingOnce, keyedBatchOp,-        anyOp, anyOpExpecting, allOp, allOpExpecting, allOp', serverOpExpecting-    ) where--import           Database.Memcache.Errors-import qualified Database.Memcache.Ketama as Ketama-import           Database.Memcache.Server-import           Database.Memcache.Timeout (timeoutRestartable)-import           Database.Memcache.Types-import           Database.Memcache.Types.Cluster (Cluster (..))-import           Database.Memcache.Types.Server (Server (slotTaken))--import           Control.Concurrent       (threadDelay)-import           Control.Concurrent.MVar  (MVar, readMVar)-import           Control.Monad            (foldM, unless, void, when, (<=<))-import           Data.ByteString          (ByteString)-import qualified Data.ByteString          as B-import qualified Data.ByteString.Char8    as C-import           Data.Default-import           Data.Fixed               (Milli)-import           Data.Hashable            (hash)-import           Data.IORef-import           Data.List                (find)-import           Data.Maybe               (isJust)-import qualified Data.Text                as T-import qualified Data.Text.Encoding       as T-import           Data.Time.Clock          (NominalDiffTime)-import           Data.Time.Clock.POSIX    (getPOSIXTime)-import qualified Data.Vector              as V-import           System.Timeout-import           UnliftIO.Exception       (Exception, SomeException, fromException, handle, throwIO, try)-import           Database.Memcache.Socket (Response(..), WireKey, checkIdle, encodeKey, noOpRequest, recvResponse,-                                           responseStatus, sendRaw)---- | Number of times to retry an operation against a server after its first--- attempt fails, before giving up (see 'optsServerRetries').-type Retries = Int---- | Options specifies how a Memcached cluster should be configured.-data Options = Options {-        -- | Number of times to retry an operation against a server after it-        -- fails, so each operation is tried at most @1 + optsServerRetries@-        -- times. Zero or a negative value means it is tried once. If every-        -- attempt fails, we mark the server as down and failover to a-        -- different server for the next operation. An attempt that only ran-        -- out of time waiting for a free connection to the server uses up a-        -- retry like any failed attempt, but the last attempt decides: if it-        -- was such an attempt, the server isn't marked down, whatever the-        -- earlier attempts did (see 'optsServerTimeout').-        ---        -- A @SERVER_ERROR@ reply whose text names no status, such as-        -- memcached's proxy sends when a backend fails, is a failed attempt,-        -- as a timeout or a network error is: it closes the server's idle-        -- connections, and counts towards marking the server down. So is the-        -- @ERROR Too many open connections@ that memcached sends to a new-        -- connection, and then closes it, when it is at its connection limit-        -- (@-c@); the client reads it while authenticating or checking the-        -- server's version. Other error replies are answers, thrown at once-        -- without counting against the server: any other @ERROR@,-        -- @CLIENT_ERROR@, and a @SERVER_ERROR@ whose text names a status,-        -- such as running out of memory.-        ---        -- A request that mustn't be sent twice is retried only after a-        -- failure before any of it was sent: while waiting for a free-        -- connection, connecting, authenticating or checking the server's-        -- version, or on finding that the server has closed or reset the-        -- connection, or that bytes from the server are already waiting on-        -- it. Those are @increment@, @decrement@, @append@, @prepend@, @add@-        -- and @delete@, and @cas@ and @replace@ with a version other than 0.-        -- Once the request may have reached the server, a failure such as a-        -- timeout, a network error, the server closing the connection, a-        -- reply that can't be read or a @SERVER_ERROR@ that names no status-        -- is thrown as it is, and the server is marked down as if every-        -- attempt had failed, whatever retries are left. The server may have-        -- carried out the request, and a retry could apply it twice, or-        -- report failure because the first one succeeded (see-        -- 'keyedOpExpectingOnce'). So behind memcached's proxy, a request for-        -- a key on a failed backend marks the whole proxy down: at once if it-        -- mustn't be sent twice, and otherwise once every attempt gets that-        -- reply.-        ---        -- Every other operation is retried after any failure, so the server-        -- may carry out its request more than once: gets, @touch@, @set@,-        -- @cas@ and @replace@ with version 0, the batches of @getMany@,-        -- @setMany@ and @deleteMany@, @flush@, @stats@ and @version@, and-        -- the operations of 'keyedOp', 'anyOp', 'allOp' and 'allOp''. Sent-        -- again, these leave the same data and get an answer as true as the-        -- first, but a store or delete repeated after another client has-        -- changed the key undoes that change. Set this to 0 for no retries.-        ---        -- Default is 1, so an operation is tried at most twice. Before-        -- version 0.5 this was the number of attempts, not retries, and-        -- defaulted to 2, which also meant two attempts.-        optsServerRetries        :: Retries,-        -- | After an operation has failed, how long to wait before retrying it-        -- while still within the 'optsServerRetries' count?-        ---        -- Default is 200ms.-        optsFailRetryDelay       :: Milli,-        -- | How long to wait after a server has been marked down, before-        -- trying to use it again. @flush@ doesn't wait: it is sent to every-        -- server, marked down or not (see 'serverOpExpecting').-        ---        -- Default is 1500ms.-        optsDeadRetryDelay       :: Milli,-        -- | How long each attempt at an operation may take before it is-        -- considered failed. @stats@ and @flush@ make their attempts for each-        -- server in turn. The time counts from the start of the attempt: it-        -- covers waiting for a free connection in the server's pool, opening-        -- a new connection if one is needed (connecting, authenticating when-        -- there are credentials, and asking the server for its version),-        -- sending the request and reading the reply.-        ---        -- @getMany@, @setMany@ and @deleteMany@ make their attempts for each-        -- batch of up to 256 requests to a server, and give each reply this-        -- time, as the single requests the batch stands for would have. The-        -- first reply's time counts from the start of the attempt, as above,-        -- so it also covers sending the whole batch; each later reply's-        -- counts from when the reply before it was read. So a server that-        -- sends each reply just in time can hold a batch of /n/ requests for-        -- about /n/ + 1 times this per attempt, as /n/ single requests would.-        -- The batch keeps its connection all the while. Other requests to the-        -- server then wait for a free one if its pool has no other (it holds-        -- one by default; see 'soNumResources'), and those that run out of-        -- time waiting throw v'Timeout' without marking the server down, as-        -- below.-        ---        -- An attempt that runs out of time while it is still waiting for a-        -- free connection never reached the server. It is retried like any-        -- failed attempt, but if it was the last attempt, the operation-        -- throws v'Timeout' without marking the server down. Running out of-        -- time afterwards, while opening (including authenticating and-        -- checking the version) or using the connection, is a server failure-        -- like any other, however long the attempt waited first.-        ---        -- A large value must be sent or read whole within this time too, so-        -- over a network, values of more than a few tens of MiB can need-        -- more than the default: at 1 Gbit/s, 750 ms carries less than-        -- 90 MiB.-        ---        -- Default is 750ms.-        optsServerTimeout        :: Milli,-        -- | Figure out which server to talk to for a given key.-        ---        -- Default is 'ketamaServerForKey'. A custom router can use 'isAlive'-        -- to skip servers marked failed.-        optsGetServerForKey      :: Cluster -> Key -> IO (Maybe Server),-        -- | Convert server specifications into servers.-        ---        -- Default uses 'newServerDefault'.-        optsServerSpecsToServers :: ServerOptions -> [ServerSpec] -> IO [Server],--        -- | Connection-pool options for each server.-        optsServerOptions :: ServerOptions-    }---- | The default cluster options:------ * 'optsServerRetries': 1 (one retry, so an operation is tried at most twice)--- * 'optsFailRetryDelay': 200ms--- * 'optsDeadRetryDelay': 1500ms--- * 'optsServerTimeout': 750ms--- * 'optsGetServerForKey': 'ketamaServerForKey'--- * 'optsServerSpecsToServers': 'newServerDefault' for each server--- * 'optsServerOptions': 'defaultServerOptions'------ Change individual fields with a record update, for example--- @defaultOptions { optsServerTimeout = 250 }@.-defaultOptions :: Options-defaultOptions = Options {-            optsServerRetries  = 1,-            optsFailRetryDelay = 200,-            optsDeadRetryDelay = 1500,-            optsServerTimeout  = 750,-            optsGetServerForKey = ketamaServerForKey,-            optsServerSpecsToServers = mapM . newServerDefault,-            optsServerOptions = defaultServerOptions-        }---- | 'def' is 'defaultOptions'.-instance Default Options where-  def = defaultOptions---- | Get the currently configured servers.-getServers :: Cluster -> IO (V.Vector Server)-getServers = either readMVar (pure . fst) . cServers---- | Replace the cluster's server set, preserving its routing and retry options.------ Servers are kept in the order given, which breaks ties on the ketama ring--- (see "Database.Memcache.Cluster"). A cluster given an 'MVar' caches the ring--- for the servers in it, rebuilding it only when their hosts or ports change.--- Every cluster made by 'setServers' shares that cache with the one it was--- made from, so alternating between two clusters with different hosts in--- their 'MVar's rebuilds the ring on each switch.------ A client made by ElastiCache discovery has a thread that replaces its--- servers, which @quit@ stops. That thread doesn't replace the servers given--- here, so @quit@ on a cluster made from such a client by 'setServers' leaves--- the thread running.-setServers :: Cluster -> Either (MVar (V.Vector Server)) (V.Vector Server) -> Cluster-setServers c servers = c { cServers = fmap withRing servers, cStopRefresh = pure () }---- | Establish a new connection to a group of Memcached servers.-newCluster :: [ServerSpec] -> Options -> IO Cluster-newCluster []    _ = throwIO $ ClientError NoServersReady-newCluster hosts Options{..} = do-    s <- optsServerSpecsToServers optsServerOptions hosts-    let fixed = withRing (V.fromList s)-    cache <- newIORef fixed-    return $-        Cluster {-            cServers   = Right fixed,-            cRingCache = cache,-            cRetries   = optsServerRetries ,-            cFailDelay = toMicroseconds optsFailRetryDelay,-            cDeadDelay = fromRational $ toRational optsDeadRetryDelay / 1000,-            cTimeout   = toMicroseconds optsServerTimeout,-            cGetServerForKey = optsGetServerForKey,-            cStopRefresh = pure ()-        }---- | Convert a duration in milliseconds to the microseconds that 'threadDelay'--- and 'timeout' take. 'Milli' has three decimal places, so the product is a--- whole number and 'truncate' loses nothing.-toMicroseconds :: Milli -> Int-toMicroseconds ms = truncate (toRational ms * 1000)---- | Check if server is alive.-serverAlive :: NominalDiffTime -> Server -> IO Bool-{-# INLINE serverAlive #-}-serverAlive deadDelay s = do-    t <- readIORef (failed s)-    if t == 0-        then return True-        else do-            t' <- getPOSIXTime-            if (t' - t) < deadDelay-                then return False-                else do-                    writeIORef (failed s) 0-                    return True---- | Whether a server can be used: it isn't marked failed, or it was marked--- failed at least 'optsDeadRetryDelay' ago, in which case this clears the--- mark. A custom 'optsGetServerForKey' can use it to skip servers marked--- failed, as 'ketamaServerForKey' does.-isAlive :: Cluster -> Server -> IO Bool-{-# INLINE isAlive #-}-isAlive c = serverAlive (cDeadDelay c)---- | The servers not currently marked as failed.-aliveServers :: Cluster -> IO (V.Vector Server)-{-# INLINE aliveServers #-}-aliveServers c = getServers c >>= V.filterM (serverAlive $ cDeadDelay c)---- | The default router: a key goes to its owner on the ketama ring, or if--- that server is marked failed, to the next live server walking forward round--- the ring (see the module description). 'Nothing' if the cluster has no--- servers or every server is marked failed.-ketamaServerForKey :: Cluster -> Key -> IO (Maybe Server)-{-# INLINE ketamaServerForKey #-}-ketamaServerForKey c k = do-    (servers, ring) <- either (cachedRing c <=< readMVar) pure (cServers c)-    let firstAlive [] = return Nothing-        firstAlive (i:is) = do-            let s = servers V.! i-            alive <- isAlive c s-            if alive then return (Just s) else firstAlive is-    firstAlive $ Ketama.owners ring $ Ketama.keyHash k---- | Servers read from the cluster's 'MVar', with their ketama ring. The ring--- last built is cached with the servers it was built for, and reused while the--- 'MVar' holds the same 'Server' values, as it does after an ElastiCache--- refresh that finds the same nodes. Otherwise the ring is reused if the--- hosts and ports are the same, and rebuilt only if they differ.-cachedRing :: Cluster -> V.Vector Server -> IO (V.Vector Server, Ketama.Ring)-cachedRing c servers = do-    cached@(builtFor, _) <- readIORef (cRingCache c)-    if sameServers builtFor servers-        then return cached-        -- Install the new ring before building it, so concurrent requests-        -- share one build.-        else atomicModifyIORef' (cRingCache c) $ \(builtFor', ring) ->-            let new | sameNames builtFor' servers = (servers, ring)-                    | otherwise = withRing servers-            in (new, new)---- | Whether two vectors hold the same 'Server' values in the same order. Each--- 'Server' has its own 'failed' 'IORef', so this compares a pointer per server,--- and allocates nothing.-sameServers :: V.Vector Server -> V.Vector Server -> Bool-sameServers = pairwise (\x y -> failed x == failed y)---- | Whether two vectors hold servers with the same hosts and ports in the same--- order, and so the same ketama ring.-sameNames :: V.Vector Server -> V.Vector Server -> Bool-sameNames = pairwise (\x y -> serverHost x == serverHost y && serverPort x == serverPort y)---- | Whether two vectors are the same length and every pair of servers at the--- same position passes the test, checked with a loop so nothing is allocated.-pairwise :: (Server -> Server -> Bool) -> V.Vector Server -> V.Vector Server -> Bool-{-# INLINE pairwise #-}-pairwise same xs ys = V.length xs == V.length ys && go 0-  where-    go i = i == V.length xs || (same (V.unsafeIndex xs i) (V.unsafeIndex ys i) && go (i + 1))---- | Servers with their ketama ring, all with weight 1, named from the host and--- port they were configured with. The ring is built when it is first used.-withRing :: V.Vector Server -> (V.Vector Server, Ketama.Ring)-withRing servers = (servers, Ketama.ring (map named (V.toList servers)))-  where-    named s = (Ketama.serverName (hostBytes (serverHost s)) (utf8 (serverPort s)), 1)-    -- A Unix socket's path holds a byte per Char, the bytes the client-    -- connects to, and libmemcached names a socket by those bytes. Encoding-    -- them in UTF-8, as a host's characters are, would give a path outside-    -- ASCII another name.-    hostBytes path@('/' : _) = C.pack path-    hostBytes host = utf8 host-    utf8 = T.encodeUtf8 . T.pack---- | The router of versions before 0.5. It is kept for one release, so that--- a fleet can switch to 'ketamaServerForKey' in stages (see the module--- description).------ Like those versions, it sends a key to the live server with the lowest--- @sid@ if that @sid@ is below the key's @hashable@ hash, and otherwise to--- the live server with the highest @sid@. It gives the same server as 0.4--- only when built with the same @hashable@ version on the same platform, as--- @hashable@'s hashes can differ between them. 0.4 also kept the servers of--- 'newCluster' and of ElastiCache discovery sorted by @sid@, but searched--- servers given to 'setServers' in the order given, so for those this--- router can choose a different server than 0.4 did.-legacyServerForKey :: Cluster -> Key -> IO (Maybe Server)-legacyServerForKey c k = do-    servers' <- aliveServers c-    -- 0.4 kept the servers sorted by sid, and sent the key to the first one-    -- whose sid is below its hash, or else to the last one: so to the first-    -- server with the lowest sid, if that is below the hash, or else to the-    -- last one with the highest. The servers are no longer sorted, so find-    -- those two, in one pass each.-    let lowest = V.foldl1' (\s s' -> if sid s' < sid s then s' else s) servers'-        highest = V.foldl1' (\s s' -> if sid s' >= sid s then s' else s) servers'-    return $ if V.null servers'-        then Nothing-        else Just $ if sid lowest < hash k then lowest else highest-{-# DEPRECATED legacyServerForKey "It sends keys to no more than two servers \-    \at a time. Use ketamaServerForKey, the default; this will be removed in \-    \the next major version." #-}---- | Whether a request can be sent again after a failure that may have come--- after the server received it.-data Resend-  -- | Sending it again leaves the same data and gets an answer as true as the-  -- first: a get, an unconditional set, a flush.-  = Resend-  -- | It is sent at most once: a retry could carry it out twice, or answer-  -- for the first one's effect, as an increment or an @add@ would.-  | SendOnce-  deriving Eq---- | Run a Memcached operation against a particular server, handling any--- failures that occur, retrying the specified number of times. The reply is--- checked with the given function while the connection is held, so that a--- reply it rejects closes the connection.------ A request sent once is retried only after a failure before it was sent.--- So that a connection the server closed while it sat idle in the pool--- doesn't count as one, the connection is checked just before sending.-serverOp :: Cluster -> Server -> Resend -> (Response -> IO ()) -> ByteString -> IO Response-{-# INLINE serverOp #-}-serverOp c s resend check req = handle (\(OutOfStep err) -> throwIO err) $-  retryOp c s PerAttempt $ \sent s' _ -> withSocket s' $ \connection -> do-    when (resend == SendOnce) $ do-      checkIdle connection-      writeIORef sent True-    sendRaw connection req-    response <- recvResponse connection-    check response-    return response--rejectProtocolError :: Response -> IO ()-rejectProtocolError response-  | responseCode response `elem` ["ERROR", "CLIENT_ERROR", "SERVER_ERROR"] =-    void (responseStatus response)-  | otherwise = return ()---- | Reject a reply whose code is none of the given ones, as--- 'keyedOpExpecting' describes.-expectReply :: String -> [ByteString] -> Response -> IO ()-expectReply operation codes response = do-  rejectProtocolError response-  unless (responseCode response `elem` codes) $ handle (throwIO . OutOfStep) $ do-    -- An unknown code throws 'UnknownStatus' here.-    void (responseStatus response)-    throwIO $ ProtocolError UnexpectedResponse-      { protocolError = "Expected " <> operation <> ", got: " <> show (responseCode response) }---- | An error for a reply that shows its connection is out of step with its--- requests. @expectReply@ throws it inside 'withSocket', so that the--- connection is closed, and @serverOp@ throws the error it carries once--- @retryOp@ has let it through.-newtype OutOfStep = OutOfStep MemcacheError-  deriving Show--instance Exception OutOfStep---- | Run a keyed request against the server selected for the key. Of the--- replies it can read, only an error reply throws: @ERROR@ throws--- 'UnknownOp', and @CLIENT_ERROR@ and @SERVER_ERROR@ throw 'BadCommand' and--- 'ServerError', or an 'OpError' when their text names a status, such as--- 'ErrValueTooLarge'. Each is an answer, thrown at once, except 'ServerError':--- a @SERVER_ERROR@ whose text names no status is a server failure, as a--- timeout is. So is memcached's @ERROR Too many open connections@, which--- throws 'ServerError' too (see 'optsServerRetries'). Any other reply is--- returned, and the connection goes back to the pool, so a reply the request--- cannot get leaves it out of step; 'keyedOpExpecting' rejects such a reply.------ After a failure the request is sent again, even if the server may have--- carried it out (see 'optsServerRetries'), so use it only for requests that--- can be repeated. 'keyedOpExpectingOnce' is for those that can't.-keyedOp :: Cluster -> Key -> (WireKey -> ByteString) -> IO Response-{-# INLINE keyedOp #-}-keyedOp c = keyedOpWith c Resend rejectProtocolError---- | Like 'keyedOp', for a request whose reply can only have one of the given--- codes, such as @[\"VA\", \"EN\"]@ for a get with the @v@ flag. A reply with--- any other code shows that the connection is out of step with its requests:--- the reply is likely an earlier request's, and this request's own reply is--- still to come. Such a reply throws while the connection is held, so the--- connection is closed rather than returned to the pool, where later requests--- would read the replies left on it. A code that 'responseStatus' doesn't--- know throws 'UnknownStatus'. Any other throws 'UnexpectedResponse', whose--- message names the given operation and the code, as in--- @Expected GET, got: \"HD\"@. The server has received the request, so it--- is not sent again, and the error doesn't count towards marking the server--- dead. Error replies (@ERROR@, @CLIENT_ERROR@ and @SERVER_ERROR@) throw as--- they do for 'keyedOp', where a @SERVER_ERROR@ whose text names no status--- is a server failure. After a server failure, the request is sent again, as--- with 'keyedOp'.-keyedOpExpecting :: Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response-{-# INLINE keyedOpExpecting #-}-keyedOpExpecting c operation codes = keyedOpWith c Resend (expectReply operation codes)---- | Like 'keyedOpExpecting', for a request that mustn't be sent twice, such--- as an increment, an @add@, a delete, or a store with a CAS version. Once--- the request may have reached the server, a failure, such as a timeout, a--- network error, the server closing the connection, a reply that can't be--- read or a @SERVER_ERROR@ whose text names no status, isn't retried: the--- server may have carried out the request, and a second one could apply it--- twice, or report failure because the first one succeeded. The failure is--- thrown as it is, and still counts against the server: its idle connections--- are closed, and it is marked dead, as when the last of an operation's--- attempts fails. A failure before any of the request is sent, such as--- waiting for a connection, connecting, authenticating or checking the--- server's version, is retried as for 'keyedOpExpecting'.------ Before sending, the connection is checked, without waiting, for the server--- having closed or reset it, as memcached closes idle connections when it--- restarts or after @-o idle_timeout@, and for bytes from the server already--- waiting on it. Such a connection is closed, and as after any failure--- before sending, the request is retried on another if retries are left.--- With 'optsServerRetries' at 0, the failure is thrown instead, and the--- server is marked dead (see 'Database.Memcache.Socket.checkIdle').-keyedOpExpectingOnce :: Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response-{-# INLINE keyedOpExpectingOnce #-}-keyedOpExpectingOnce c operation codes = keyedOpWith c SendOnce (expectReply operation codes)---- | Run a keyed request, checking its reply with the given function.-keyedOpWith :: Cluster -> Resend -> (Response -> IO ()) -> Key -> (WireKey -> ByteString) -> IO Response-{-# INLINE keyedOpWith #-}-keyedOpWith c resend check k makeReq = do-    wire <- either (throwIO . ClientError) return (encodeKey k)-    s' <- cGetServerForKey c c k-    case s' of-        Just s  -> serverOp c s resend check (makeReq wire)-        Nothing -> throwIO $ ClientError NoServersReady---- | Run keyed requests grouped by their selected server, pipelining each--- server's requests in batches. Each request is built from its key's wire--- form and an opaque. The request must send the opaque unchanged as its @O@--- flag, in decimal, as the batch encoders in "Database.Memcache.Socket" do.--- memcached copies it into the reply, and that matches the reply to its--- request. A request may get no reply, as a quiet miss does. The results are--- grouped by server, and keep the order given within a server.------ Like 'keyedOp', a batch is sent again after a failure, even one after the--- server may have carried out some of its requests, so use it only for--- requests that can be repeated.------ A batch holds up to 256 requests, and closes early once its requests reach--- 1 MiB. Each reply has its own 'optsServerTimeout', as the single requests--- the batch stands for would: the first reply's counts from the start of the--- attempt, so it also covers waiting for a connection, opening one and--- sending the batch, and each later reply's counts from when the reply before--- it was 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, the reply--- that ends the batch included, as /n/ single requests would.------ A miss reply (@EN@) with no opaque is skipped, as there is nothing to--- return for it. memcached sends one when a read from extstore misses (for--- quiet gets too, from 1.6.40) and, before 1.6.18, for any get miss that is--- not quiet. As memcached answers in order, it counts as the reply to the--- next request, after the one the previous reply answered. Error replies--- (@ERROR@, @CLIENT_ERROR@ and @SERVER_ERROR@) throw as they do for--- 'keyedOp', and here too a @SERVER_ERROR@ whose text names no status is a--- server failure. A reply with an unknown code throws 'UnknownStatus', as its--- length can't be known. Any other reply with no opaque, with the opaque of--- no request in its batch, or out of order throws 'UnexpectedResponse', as--- does a bare @EN@ after the reply to the batch's last request. Either way--- the connection is closed rather than reused. Like any server failure, the--- batch is then sent again on a new connection, and the failure counts--- towards marking the server dead.-keyedBatchOp :: Cluster -> [(Key, WireKey -> Int -> ByteString)] -> IO [(Key, Response)]-keyedBatchOp c requests = do-    groups <- foldM add [] (zip [0..] requests)-    concat <$> mapM run groups-  where-    add groups (opaque, (key, makeRequest)) = do-      wire <- either (throwIO . ClientError) return (encodeKey key)-      server <- cGetServerForKey c c key-      case server of-        Nothing -> throwIO $ ClientError NoServersReady-        Just s -> return (insertGroup s (key, opaqueFlag opaque, makeRequest wire opaque) groups)--    opaqueFlag opaque = C.pack ('O' : show opaque)--    insertGroup s item [] = [(s, [item])]-    insertGroup s item ((s', items):rest)-      | s == s' = (s', item:items) : rest-      | otherwise = (s', items) : insertGroup s item rest--    run (server, items) = concat <$> mapM (runBatch server) (batches (reverse items))--    -- Write the whole batch in one go, then read it back. Batches are bounded-    -- so the server's replies cannot fill the socket buffers while we are-    -- still writing, which would deadlock both ends until the op times out.-    -- Each reply has a timeout of its own, which recvUntilMN starts once it-    -- has read the reply before.-    runBatch server items = retryOp c server PerReply $ \_ server' restartTimeout ->-      withSocket server' $ \connection -> do-        sendRaw connection (B.concat (map request items ++ [noOpRequest]))-        recvUntilMN restartTimeout connection items []--    -- memcached answers in order, so each reply must carry the opaque of a-    -- request after the one the previous reply answered; the requests in-    -- between got no reply. A bare EN is a miss whose opaque memcached-    -- dropped: we can't tell which request it answers, but it is one line-    -- with nothing to return, so skip it. Later replies answer later-    -- requests, so count it as the next request's reply. With no request-    -- left it is one reply too many, and a server sending bare ENs without-    -- end would otherwise keep the batch reading. Anything else means the-    -- replies are out of step with the requests, as may a reply with an-    -- unknown code, whose length we can't know. So throw while the connection-    -- is held, and it is closed rather than returned to the pool. Echoed keys-    -- can't be matched instead: memcached echoes a key raw or as base64-    -- according to how its item was stored, not how the request sent it, and-    -- a raw key can contain a newline.-    recvUntilMN restartTimeout connection pending acc = do-      response <- recvResponse connection <* restartTimeout-      void (responseStatus response)-      case (responseCode response, find (B.isPrefixOf "O") (responseTokens response)) of-        ("MN", _) -> return (reverse acc)-        ("EN", Nothing) | _ : rest <- pending -> recvUntilMN restartTimeout connection rest acc-        (_, opaque) -> case dropWhile (\(_, opaque', _) -> Just opaque' /= opaque) pending of-          (key, _, _) : rest -> recvUntilMN restartTimeout connection rest ((key, response) : acc)-          [] -> throwIO $ ProtocolError UnexpectedResponse-            { protocolError = "Expected a reply to a request in the batch, got: "-                <> show (C.unwords (responseCode response : responseTokens response)) }--    request (_, _, req) = req--    batchSize = 256 :: Int--    -- The whole batch must be sent within the timeout of its first reply, so-    -- a batch also closes once its requests reach 1 MiB, memcached's default-    -- item size limit. Sending a batch then takes no longer than sending a-    -- single large store; a request over the limit goes in a batch of its-    -- own. The limit counts the requests only: the values that come back in-    -- the replies have a timeout each, as a single get's does.-    batchBytes = 1048576 :: Int--    batches [] = []-    batches xs = batch : batches rest-      where (batch, rest) = splitBatch 0 0 xs--    splitBatch n bytes (x:xs)-      | n == 0 || (n < batchSize && bytes' <= batchBytes) =-          let (batch, rest) = splitBatch (n + 1) bytes' xs in (x : batch, rest)-      where bytes' = bytes + B.length (request x)-    splitBatch _ _ xs = ([], xs)---- | Run a Memcached operation against any single server in the cluster,--- handling any failures that occur, retrying the specified number of times.--- As with 'keyedOp', of the replies it can read, only an error reply throws;--- 'anyOpExpecting' also rejects a reply the request cannot get. Also as with--- 'keyedOp', the request is sent again after a failure, so it must be one--- that can be repeated.-anyOp :: Cluster -> ByteString -> IO Response-{-# INLINE anyOp #-}-anyOp c = anyOpWith c rejectProtocolError---- | Like 'anyOp', but rejects a reply whose code is none of the given ones,--- as 'keyedOpExpecting' does.-anyOpExpecting :: Cluster -> String -> [ByteString] -> ByteString -> IO Response-{-# INLINE anyOpExpecting #-}-anyOpExpecting c operation codes = anyOpWith c (expectReply operation codes)---- | Run a request against any single server, checking its reply with the--- given function.-anyOpWith :: Cluster -> (Response -> IO ()) -> ByteString -> IO Response-{-# INLINE anyOpWith #-}-anyOpWith c check req = do-    servers' <- aliveServers c-    case V.uncons servers' of-        Nothing     -> throwIO $ ClientError NoServersReady-        Just (s, _) -> serverOp c s Resend check req---- | Run a Memcached operation against every server not marked failed, in--- turn, handling any failures that occur, retrying the specified number of--- times. A server that fails ends the operation, and the servers after it are--- not sent the request. As with 'keyedOp', of the replies it can read, only--- an error reply throws; 'allOpExpecting' also rejects a reply the request--- cannot get. Also as with 'keyedOp', the request is sent again after a--- failure, so it must be one that can be repeated.-allOp :: Cluster -> ByteString -> IO [(Server, Response)]-{-# INLINE allOp #-}-allOp c req = forAliveServers c $ \s -> serverOp c s Resend rejectProtocolError req---- | Like 'allOp', but rejects a reply whose code is none of the given ones,--- as 'keyedOpExpecting' does. The servers after one whose reply is rejected--- are not sent the request, as with a server that fails. To send a request--- to every server, including servers marked failed, and carry on past a--- failure, run 'serverOpExpecting' for each server from 'getServers'.-allOpExpecting :: Cluster -> String -> [ByteString] -> ByteString -> IO [(Server, Response)]-{-# INLINE allOpExpecting #-}-allOpExpecting c operation codes req =-    forAliveServers c $ \s -> serverOp c s Resend (expectReply operation codes) req---- | Run a request against the given server, such as one from 'getServers',--- whether or not it is marked failed, rejecting a reply whose code is none--- of the given ones, as 'keyedOpExpecting' does. As with 'keyedOp', the--- request is sent again after a failure, so it must be one that can be--- repeated. If every attempt fails, the server is marked failed, as by any--- operation, and a server already marked failed is marked again from then. A--- server marked failed that answers stays marked: the other operations skip--- it until 'optsDeadRetryDelay' has passed since it was marked. @flush@ uses--- this to send @flush_all@ to every server.-serverOpExpecting :: Cluster -> String -> [ByteString] -> Server -> ByteString -> IO Response-{-# INLINE serverOpExpecting #-}-serverOpExpecting c operation codes s = serverOp c s Resend (expectReply operation codes)---- | Run a Memcached operation against every server not marked failed, handling--- any failures that occur, retrying the specified number of times. Similar to--- 'anyOp' but allows more flexible interaction with the 'Server' than a single--- request and response. The operation must make its requests with--- 'withSocket' on the 'Server' it is given, not on another value for the same--- server, or its timeouts never mark the server down (see--- 'optsServerTimeout'). Once one of its 'withSocket' calls has got a--- connection, a timeout is a server failure, even while a later call waits--- for one. So is any exception the operation throws other than an--- 'OpError', a 'BadCommand' or 'UnknownOp' protocol error, or an--- 'InvalidAuthentication' client error, which are rethrown at once. Each--- server failure closes the server's idle connections, before the operation--- is retried or the server marked down. The operation is run again from the--- start after a failure, whatever requests it had sent, so its requests must--- be ones that can be repeated.-allOp' :: Cluster -> (Server -> IO a) -> IO [(Server, a)]-{-# INLINE allOp' #-}-allOp' c op = forAliveServers c $ \s -> retryOp c s PerAttempt (\_ s' _ -> op s')---- | Run an action against every server not marked as failed, pairing each--- result with its server. Throws 'NoServersReady' if there are none.-forAliveServers :: Cluster -> (Server -> IO a) -> IO [(Server, a)]-{-# INLINE forAliveServers #-}-forAliveServers c f = do-    servers' <- aliveServers c-    if V.null servers'-        then throwIO $ ClientError NoServersReady-        else do-            res <- V.mapM f servers'-            return $ V.toList $ V.zip servers' res---- | How an attempt's time is limited (see 'optsServerTimeout').-data Timing-  -- | The attempt has one timeout.-  = PerAttempt-  -- | Each reply has its own: the first counts from the start of the-  -- attempt, and the attempt starts each later one once it has read the-  -- reply before, with the action it is given.-  | PerReply---- | Run an IO operation, retrying it up to the allowed number of retries if an--- exception is thrown, and marking the server as dead if every attempt fails.--- Each attempt's time is limited as the @Timing@ says, and the attempt is--- given an action that starts the next reply's timeout, which does nothing--- for @PerAttempt@. Each attempt is given the server with a new @slotTaken@,--- which 'withSocket' sets once it holds a slot in the server's pool. An--- attempt that runs out of time before that never reached the server. It is--- retried like any failure, but if it is the last attempt, it throws--- v'Timeout' without marking the server dead: the last attempt alone decides,--- whatever the earlier ones did. Every other failure but a client fault first--- closes the server's idle connections, before the operation is retried or--- the server marked dead.------ Each attempt is also given an 'IORef' that it sets just before it sends a--- request that mustn't be sent twice. A failure after that isn't retried,--- whatever retries are left: it marks the server dead, as the last attempt's--- failure does, and is rethrown.-retryOp :: forall a. Cluster -> Server -> Timing -> (IORef Bool -> Server -> IO () -> IO a) -> IO a-{-# INLINE retryOp #-}-retryOp Cluster{..} s timing op = go cRetries-  where-    -- An attempt's exception is handled once 'try' has returned it, rather-    -- than in a handler. A handler runs with asynchronous exceptions masked,-    -- and so would the retry it started: nothing could then interrupt the-    -- retry until it blocked, not even its own timeout. This 'try' is-    -- unliftio's, which lets asynchronous exceptions through, so that the-    -- caller can still interrupt the operation.-    go :: Int -> IO a-    {-# INLINE go #-}-    go !n = do-        sent <- newIORef False-        try (attempt sent) >>= either (handleErrs n sent) return--    -- One attempt at the operation, with its own timeout or timeouts and-    -- @slotTaken@.-    attempt :: IORef Bool -> IO a-    attempt sent = do-        taken <- newIORef False-        let run = op sent s { slotTaken = Just taken }-        mr <- case timing of-            PerAttempt -> timeout cTimeout (run (return ()))-            PerReply   -> timeoutRestartable cTimeout run-        case mr of-            Just r  -> return r-            Nothing -> do-                held <- readIORef taken-                if held-                    then throwIO (ClientError Timeout)-                    else throwIO WaitedForSlot--    handleErrs :: Int -> IORef Bool -> SomeException -> IO a-    {-# INLINE handleErrs #-}-    handleErrs n sent err-        | clientFault err = throwIO err-        | otherwise = case fromException err of-            Just WaitedForSlot -> retryOr n $ throwIO (ClientError Timeout)-            Nothing -> do-                -- The attempt's own connection, if it had one, is closed-                -- already, unless the operation had given it back before-                -- failing. What made the attempt fail, such as a restart of-                -- the server, may have broken the idle ones too, and the-                -- retry, or the next operation once the server is back,-                -- would take one of those.-                close s-                -- The server may have carried out a request that mustn't be-                -- sent twice, so its failure ends the operation, like the-                -- last attempt's.-                once <- readIORef sent-                let giveUp = do-                      writeIORef (failed s) =<< getPOSIXTime-                      throwIO err-                if once then giveUp else retryOr n giveUp--    -- Retry the operation if it has retries left, or else give up.-    retryOr :: Int -> IO a -> IO a-    {-# INLINE retryOr #-}-    retryOr n giveUp-        | n <= 0 = giveUp-        | otherwise = threadDelay cFailDelay >> go (n - 1)---- | Thrown by an attempt that runs out of time while it waits for a slot in--- the server's pool. @retryOp@ retries it like a failure, but without closing--- the idle connections, and if it is the last attempt, throws v'Timeout'--- instead, without marking the server dead.-data WaitedForSlot = WaitedForSlot-  deriving Show--instance Exception WaitedForSlot---- | A rejected command or a reported operation status is an answer, not a--- server failure: retrying it will fail identically and must not count towards--- marking the server dead. That includes the 'UnknownOp' a new connection--- throws when it refuses the server's version: a retry would find the same--- version. memcached's @ERROR Too many open connections@ is no answer, though:--- it throws 'ServerError', as the server may take a connection later. Nor is--- a reply out of step retried or counted: the server has the request, and may--- have carried it out.-clientFault :: SomeException -> Bool-clientFault err = case fromException err of-    Just (ProtocolError BadCommand{}) -> True-    Just (ProtocolError UnknownOp{})  -> True-    Just (OpError _)                  -> True-    Just (ClientError InvalidAuthentication{}) -> True-    _                                 -> isJust (fromException err :: Maybe OutOfStep)
Database/Memcache/ElastiCacheClient.hs view
@@ -32,25 +32,26 @@ import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T+import Data.Time.Clock (NominalDiffTime) import qualified Data.Vector as V import Data.Version (Version, makeVersion) import qualified Data.Version as Version import Data.Word (Word64)-import Database.Memcache.Client (Client, optsServerSpecsToServers, optsServerOptions, optsServerTimeout)+import Database.Memcache.Client (Client, optsServerSpecsToServers, optsServerOptions, optsTimeout) import qualified Database.Memcache.Client as Client-import Database.Memcache.Cluster (Options, getServers, setServers)-import Database.Memcache.Errors (ClientError (Timeout), MemcacheError (ClientError))-import Database.Memcache.Server (Server, closeAll, withSocket)-import Database.Memcache.Socket (Connection, crlf, recvRawUntil, sendRaw, versionRequest)+import Database.Memcache.Errors (ClientError (Timeout), MemcacheError (ClientError, DiscoveryError))+import Database.Memcache.Internal.Cluster (Options, getServers, setServers)+import Database.Memcache.Internal.Server (Server, closeAll, withSocket)+import Database.Memcache.Internal.Socket (Connection, crlf, recvRawUntil, sendRaw, versionRequest) import Database.Memcache.Types.Authentication (Authentication (NoAuth)) import Database.Memcache.Types.Cluster (Cluster (cStopRefresh)) import Database.Memcache.Types.ServerSpec (ServerSpec (..), parseServerSpec)-import Database.Memcache.Util (note, readDecimal, withDetail)+import Database.Memcache.Util (note, readDecimal, toMicroseconds, withDetail) import Network.Socket (HostName, ServiceName) import System.Mem.Weak (Weak, deRefWeak) import System.Timeout (timeout) import Text.ParserCombinators.ReadP (readP_to_S)-import UnliftIO.Exception (bracket, finally, mask_, throwIO, throwString, tryAny, uninterruptibleMask_)+import UnliftIO.Exception (bracket, finally, mask_, throwIO, tryAny, uninterruptibleMask_)  -- | Parse an ElastiCache configuration endpoint. --@@ -111,20 +112,20 @@ -- The thread runs with asynchronous exceptions unmasked, even if this is -- called with them masked, as in the acquire action of a @bracket@. ----- The first discovery must finish within 'optsServerTimeout' (connecting,+-- The first discovery must finish within 'optsTimeout' (connecting, -- which asks for the version, then asking for it again and for the cluster -- configuration), or this throws v'ClientError' 'Timeout'. If the endpoint -- sends an error reply, such as the @ERROR@ that plain memcached sends as it--- has no @config@ command, this throws a @StringException@ from--- "UnliftIO.Exception", as it does for a reply that can't be parsed, a--- version of more than 64 bytes, and a configuration whose version can't be--- read, or that lists no nodes, more than 1,000, an empty node, the same host--- and port twice, or a node that isn't a plain host and port: one whose host--- or port is empty, or whose host has a character, such as @\/@, @?@ or @\@@,--- that would change the host or port, add credentials or make the node a Unix--- socket on this machine. A host given as an IPv6 address in brackets is--- rejected too. If a reply goes on for more than 1 MiB without the line end--- or the @END@ line that discovery is waiting for, this throws+-- has no @config@ command, this throws 'DiscoveryError', as it does for a+-- reply that can't be parsed, a version of more than 64 bytes, and a+-- configuration whose version can't be read, or that lists no nodes, more+-- than 1,000, an empty node, the same host and port twice, or a node that+-- isn't a plain host and port: one whose host or port is empty, or whose host+-- has a character, such as @\/@, @?@ or @\@@, that would change the host or+-- port, add credentials or make the node a Unix socket on this machine. A+-- host given as an IPv6 address in brackets is rejected too. If a reply goes+-- on for more than 1 MiB without the line end or the @END@ line that+-- discovery is waiting for, this throws -- v'Database.Memcache.Errors.ProtocolError' -- 'Database.Memcache.Errors.BadLength'. --@@ -187,9 +188,9 @@ -- like any other refresh, and the connections the client opens to the nodes -- it discovers are checked in the same way. ----- N.B. The interval is in the same units as 'threadDelay'.-newClient :: Options -> Int -> ConfigurationEndpoint -> IO Client-newClient options interval cfgEndpoint = bracket acquireCfgClient releaseCfgClient resolveCluster'+-- N.B. The interval is in seconds.+newClient :: Options -> ConfigurationEndpoint -> NominalDiffTime -> IO Client+newClient options cfgEndpoint interval = bracket acquireCfgClient releaseCfgClient resolveCluster'   where     acquireCfgClient = Client.newClient [unConfigurationEndpoint cfgEndpoint] options     -- This quits the first discovery's client, not the client returned, so@@ -219,8 +220,7 @@       -- a swap: it can land after one, or be caught, as by a server       -- constructor that catches every exception. Another thread sends the       -- kill, so that quit doesn't wait while the refresh thread can't be-      -- interrupted, as when it looks up the endpoint's name. Masked, so-      -- that once the flag is set, the kill is sent.+      -- interrupted. Masked, so that once the flag is set, the kill is sent.       let stop = mask_ $ do             atomicWriteIORef stopped True             void $ forkIO $ killThread thread@@ -238,7 +238,7 @@ -- the first discovery's version keeps that refresh from rolling the servers -- back as well. repeatAutoDiscover-  :: Options -> Int -> ConfigurationEndpoint -> Weak (MVar (V.Vector Server)) -> IORef Bool+  :: Options -> NominalDiffTime -> ConfigurationEndpoint -> Weak (MVar (V.Vector Server)) -> IORef Bool   -> ConfigVersion -> Nodes -> IO () repeatAutoDiscover opts interval cfgEndpoint servers stopped initialVersion initialNodes = do   cfgClient <- Client.newClient [unConfigurationEndpoint cfgEndpoint] opts@@ -246,7 +246,7 @@   -- garbage collected meanwhile. The 'MVar' is dropped at once, so that the   -- thread doesn't keep it reachable while it waits.   let next version nodes = do-        threadDelay interval+        threadDelay (toMicroseconds interval)         quitting <- readIORef stopped         reachable <- isJust <$> deRefWeak servers         when (reachable && not quitting) $ refresh version nodes@@ -333,7 +333,7 @@    server <-     case V.uncons servers of-      Nothing -> throwString "No servers were found"+      Nothing -> throwIO $ DiscoveryError "No servers were found"       Just (s, _) -> pure s    withSocket server $ \socket -> do@@ -355,14 +355,11 @@  -- Run 'resolveCluster', throwing 'ClientError' 'Timeout' unless it finishes, -- connecting and both requests included, within the options'--- 'optsServerTimeout'.+-- 'optsTimeout'. resolveClusterWithin :: Options -> Client -> IO (ConfigVersion, [(ServerSpec, Text)]) resolveClusterWithin opts cfgClient = do-  found <- timeout serverTimeout $ resolveCluster cfgClient+  found <- timeout (toMicroseconds (optsTimeout opts)) $ resolveCluster cfgClient   maybe (throwIO $ ClientError Timeout) pure found-  where-    -- 'optsServerTimeout' is in milliseconds; 'timeout' takes microseconds.-    serverTimeout = truncate (optsServerTimeout opts * 1000)  -- Handle the raw response from /memcached/, returning the configuration's -- version and its line of nodes. Both requests get the configuration in the@@ -514,7 +511,7 @@   line <- recvRawUntil crlf socket   let text = C.dropEnd (C.length crlf) line   when (C.takeWhile (/= ' ') text `elem` ["ERROR", "CLIENT_ERROR", "SERVER_ERROR"]) $-    throwString $ "Configuration endpoint replied" `withDetail` C.unpack text+    throwIO $ DiscoveryError $ "Configuration endpoint replied" `withDetail` C.unpack text   -- Otherwise read through the first END. This line can end with it: when   -- the cluster key is missing, the reply is the END line alone.   if end `C.isSuffixOf` line@@ -524,4 +521,4 @@     end = "END" <> crlf  unTry :: Either String a -> IO a-unTry = either throwString pure+unTry = either (throwIO . DiscoveryError) pure
Database/Memcache/Errors.hs view
@@ -26,12 +26,10 @@ import           UnliftIO.Exception  -- | The exceptions that a Memcached client throws, other than an--- 'IOException' from the network and those below. ElastiCache's--- 'Database.Memcache.ElastiCacheClient.newClient' throws a @StringException@--- when discovery fails on the configuration endpoint's reply. Settings the--- client can't use throw an @ErrorCall@: server options that resource-pool--- rejects, such as 'Database.Memcache.Server.soNumResources' smaller than--- 'Database.Memcache.Server.soNumStripes' with resource-pool 0.4 or later,+-- 'IOException' from the network and those below. Settings the client can't+-- use throw an @ErrorCall@: server options that resource-pool rejects, such+-- as 'Database.Memcache.Client.soNumResources' smaller than+-- 'Database.Memcache.Client.soNumStripes' with resource-pool 0.4 or later, -- when a client is created, and a Unix socket path too long for the system, -- when an operation connects to it. --@@ -46,6 +44,10 @@     | ClientError ClientError     -- | Errors occurring communicating with Memcached server.     | ProtocolError ProtocolError+    -- | ElastiCache discovery failed (see+    -- 'Database.Memcache.ElastiCacheClient.newClient'). Any text from the+    -- endpoint in the message is already escaped and cut.+    | DiscoveryError String     deriving (Eq, Show)  instance Exception MemcacheError where@@ -55,15 +57,17 @@         "memcache client error: " <> describeClientError e     displayException (ProtocolError e) =         "memcached protocol error: " <> describeProtocolError e+    displayException (DiscoveryError m) =+        "ElastiCache discovery failed: " <> m  -- | Errors that occur on the client. data ClientError     -- | No server is available: the cluster has none, every server is marked-    -- failed, or the router ('Database.Memcache.Cluster.optsGetServerForKey')+    -- failed, or the router ('Database.Memcache.Client.optsGetServerForKey')     -- chose none.     = NoServersReady     -- | The attempt that ended an operation ran out of time-    -- ('Database.Memcache.Cluster.optsServerTimeout'): the last attempt, or,+    -- ('Database.Memcache.Client.optsTimeout'): the last attempt, or,     -- for a request that mustn't be sent twice, the attempt that had started     -- sending it. The attempt may have been waiting for a free connection to     -- the server, connecting, authenticating, checking the server's version,@@ -78,9 +82,13 @@     -- forbidden delimiter, or the server is not in auth-file mode, as it     -- answered the @version@ request sent before them with @VERSION@.     | InvalidAuthentication String-    -- | A key or stats argument was rejected before being sent: it is empty,-    -- too long, or contains forbidden bytes.-    | KeyTooLong String+    -- | A key was rejected before being sent: it is empty, or longer than 250+    -- bytes as given or once encoded.+    | InvalidKey String+    -- | An argument was rejected before being sent: an expiration over+    -- 2147483647, or a 'Database.Memcache.Client.stats' argument that is+    -- empty, longer than 250 bytes, or contains control bytes.+    | InvalidArgument String     deriving (Eq, Show)  -- | Errors related to Memcached protocol and bytes on the wire.@@ -109,7 +117,7 @@     -- connection, and then closes it, when it is at its connection limit     -- (@-c@), with the message @\"Too many open connections\"@. Unlike other     -- error replies, it counts against the server, as a timeout does (see-    -- 'Database.Memcache.Cluster.optsServerRetries').+    -- 'Database.Memcache.Client.optsServerRetries').     | ServerError   { protocolError :: String }     -- | Memcached rejected the command.     | BadCommand    { protocolError :: String }@@ -137,7 +145,8 @@     NoServersReady          -> "no servers ready"     Timeout                 -> "request timed out"     InvalidAuthentication m -> "invalid authentication" `withDetail` m-    KeyTooLong m            -> "invalid key or argument" `withDetail` m+    InvalidKey m            -> "invalid key" `withDetail` m+    InvalidArgument m       -> "invalid argument" `withDetail` m  -- The library throws 'UnknownPkt' with no detail for an empty response line. describeProtocolError :: ProtocolError -> String
+ Database/Memcache/Internal/Auth.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Auth+Description : Meta Text auth-file authentication+Copyright   : (c) David Terei, 2016+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Authentication for Memcached's experimental text-protocol auth-file mode.+-}+module Database.Memcache.Internal.Auth+  ( Authentication(..)+  , Username+  , Password+  , authenticate+  , validateCredentials+  ) where++import Database.Memcache.Errors+import Database.Memcache.Internal.Socket+import Database.Memcache.Types++import Control.Monad (void, when)+import qualified Data.ByteString.Char8 as B8+import UnliftIO.Exception (catch, throwIO)++-- | Authenticate a connection using text-protocol credentials.+--+-- The credentials are sent only to a server in auth-file mode: first this+-- sends @version@, which such a server rejects with @CLIENT_ERROR@ until the+-- connection has authenticated. A server that answers it with @VERSION@+-- isn't in that mode, and would store the credentials as an ordinary item,+-- so this throws 'InvalidAuthentication' instead, as it does, before sending+-- anything, for credentials that contain a forbidden delimiter. An @ERROR@+-- or @SERVER_ERROR@ reply throws what it would as the reply to any request+-- (see 'responseStatus'), such as 'ServerError' for the+-- @ERROR Too many open connections@ that memcached sends to a new connection+-- when it is at its connection limit. Any other reply throws 'UnknownOp',+-- quoting it, as the same reply does in the version check that every new+-- connection makes.+--+-- Once the credentials are sent, this throws @'OpError' 'TextAuthFail'@ when+-- the server rejects them, and another 'MemcacheError', such as+-- 'UnexpectedResponse', for any other reply but @STORED@.+authenticate :: Connection -> Authentication -> IO ()+authenticate _ NoAuth = return ()+authenticate socket (Auth user pass) = do+  case validateCredentials user pass of+    Left message -> throwIO $ ClientError (InvalidAuthentication message)+    Right () -> return ()+  -- Without -Y authfile, "set auth ..." is just a normal store, so credentials+  -- would be readable via "get auth"; probe with a real command first so we+  -- never send them to a server that isn't gating on auth-file mode.+  sendRaw socket versionRequest+  probe <- recvResponse socket+  case responseCode probe of+    "CLIENT_ERROR" -> return ()+    "VERSION" -> throwIO $ ClientError+      (InvalidAuthentication "server is not in auth-file mode; refusing to send credentials")+    -- Any other reply doesn't show the mode either way, and fails as it would+    -- fail the version check that follows: an error reply throws as it would+    -- for any request, so that memcached at its connection limit is a server+    -- failure, and anything else throws UnknownOp, a client fault, as a retry+    -- would get the same reply.+    code -> do+      when (code `elem` ["ERROR", "SERVER_ERROR"]) $ void (responseStatus probe)+      throwIO $ ProtocolError UnknownOp+        { protocolError = "Expected VERSION or CLIENT_ERROR, got: "+            <> show (B8.unwords (code : responseTokens probe)) }+  let credentials = user <> B8.singleton ' ' <> pass+  sendRaw socket (authRequest credentials)+  response <- recvResponse socket+  result <- responseStatus response `catch` handleAuthFailure+  case result of+    NoError | responseCode response == "STORED" -> return ()+    -- Any other reply could leave the connection out of step, so it must not+    -- reach the pool.+    NoError -> throwIO $ ProtocolError UnexpectedResponse+      { protocolError = "Expected AUTH, got: " <> show (responseCode response) }+    status -> throwIO $ OpError status+  where+    handleAuthFailure (ProtocolError BadCommand{}) = throwIO $ OpError TextAuthFail+    handleAuthFailure err = throwIO (err :: MemcacheError)
+ Database/Memcache/Internal/Cluster.hs view
@@ -0,0 +1,878 @@+{-# LANGUAGE RecordWildCards   #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Cluster+Description : Cluster Handling+Copyright   : (c) David Terei, 2016+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Handles a group of connections to different Memcached servers.++= Routing++Keys are spread over the servers by ketama consistent hashing, computed+exactly as libmemcached does for @MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@ (see+"Database.Memcache.Internal.Ketama"). Each server gets 160 points on a 32-bit+ring (156 for some numbers of servers), taken from MD5 digests of its name,+and a key goes to the server owning the first point at or after the MD5 hash+of the key. Adding or removing a server only moves the keys on that server's+points, unless it changes the number of points each server gets (from 24+servers to 25, say), which moves a few percent of the other keys too.++Every server has weight 1, and is named from the host and port strings of its+'ServerSpec' exactly as written: the host alone for port @\"11211\"@,+otherwise @host:port@. Hosts are not resolved, so @localhost@ and @127.0.0.1@+are different names. A Unix socket is named by its path in the same way, as+the bytes the client connects to, one per 'Char' (see 'ssHost'), whereas a+host is named in UTF-8. The client doesn't use a socket's port to connect,+but port @\"11211\"@ names it by the 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 key is hashed as given,+not in its base64 form on the wire. Other clients using libmemcached's+weighted ketama distribution therefore choose the same server for every key,+as long as they are given the same host strings and ports in the same order+and equal weights: libmemcached with @MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@,+php-memcached with @OPT_LIBKETAMA_COMPATIBLE@, pylibmc with the+@ketama_weighted@ behavior, and twemproxy with @hash: md5@ and+@distribution: ketama@ and its servers listed without node names.++The order of the servers only matters in the rare case that two of them have+a point with the same value. The server listed first then owns the point, as+in libmemcached 1.1 and later. Earlier versions of libmemcached, and+twemproxy, leave such a tie to their C library's sort, so they may choose+differently for the keys just below that point.++'ketamaServerForKey' routes keys this way, and is the default+'optsGetServerForKey'.++= Failures++When every attempt at an operation against a server fails, we mark the+server as failed and remove it temporarily from the set of servers available,+unless the last attempt only ran out of time waiting for a free connection to+it (see 'optsServerRetries'). An operation whose request mustn't be sent+twice, such as an increment, makes no more attempts once one has failed after+its request may have reached the server, so that failure marks the server+failed (see 'keyedOpExpectingOnce'). A key whose server is marked failed goes+to the next live server found walking forward round the ring, so keys on live+servers stay where they are, and 'NoServersReady' is thrown only when every+server is marked failed. This is where libmemcached's auto-eject sends the key too,+except when the number of live servers changes how many points each server+gets (from 26 servers to 25, say): libmemcached rebuilds the ring from the+live servers, while we keep every server's points.++A server marked failed still gets the requests of 'serverOpExpecting', which+runs a request against the server it is given. @flush@ uses it to send+@flush_all@ to every server, so that a server marked failed doesn't serve+values from before the flush once it is used again.++= Upgrading from 0.4++Versions before 0.5 compared a @hashable@ hash of the key with hashes of the+servers. They sent keys to no more than two servers at a time, and the+mapping could change with the @hashable@ version. 0.5.x kept that router,+deprecated, as @legacyServerForKey@.++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. A single server is unaffected.++While old and new versions run side by side, as in a rolling deploy, they+read and write a moved key on different servers. A change or delete made by+one is not seen by the other, which can read a stale copy until the copy+expires, even after the deploy.++One way to switch is all at once, at a quiet time. Copies stored under the+old mapping stay on their servers, where failover can still find them, so+you may want to flush the cache afterwards.++The other way avoids the stale reads of a rolling deploy by switching in+stages with 0.5.x, as+<https://hackage.haskell.org/package/memcache-0.5.1.0/docs/Database-Memcache-Cluster.html its documentation of this module>+describes, and then upgrading from 0.5.x.++'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, after one+more 'optsRetryDelay'. Set it one lower to keep the old number of+attempts. The default went from 2 to 1, which still means two attempts.+-}+module Database.Memcache.Internal.Cluster (+        -- * Cluster+        -- | A collection of Memcached servers with retry and routing state.+        Cluster, ServerSpec(..), Options(..), defaultOptions, newCluster,+        getServers, setServers,++        -- * Routing+        -- | Routers for 'optsGetServerForKey', and 'isAlive' for writing one.+        ketamaServerForKey, isAlive,++        -- * Operations+        Retries, keyedOp, keyedOpExpecting, keyedOpExpectingOnce, keyedBatchOp,+        anyOp, anyOpExpecting, allOp, allOpExpecting, allOp', serverOpExpecting+    ) where++import           Database.Memcache.Errors+import qualified Database.Memcache.Internal.Ketama as Ketama+import           Database.Memcache.Internal.Server+import           Database.Memcache.Timeout (timeoutRestartable)+import           Database.Memcache.Types+import           Database.Memcache.Types.Cluster (Cluster (..))+import           Database.Memcache.Types.Server (Server (slotTaken))+import           Database.Memcache.Util   (toMicroseconds)++import           Control.Concurrent       (threadDelay)+import           Control.Concurrent.MVar  (MVar, readMVar)+import           Control.Monad            (foldM, unless, void, when, (<=<))+import           Data.ByteString          (ByteString)+import qualified Data.ByteString          as B+import qualified Data.ByteString.Char8    as C+import           Data.Default+import           Data.IORef+import           Data.List                (find, sortOn)+import           Data.Maybe               (isJust)+import qualified Data.Text                as T+import qualified Data.Text.Encoding       as T+import           Data.Time.Clock          (NominalDiffTime)+import           Data.Time.Clock.POSIX    (getPOSIXTime)+import qualified Data.Vector              as V+import           System.Timeout+import           UnliftIO.Exception       (Exception, SomeException, fromException, handle, throwIO, try)+import           Database.Memcache.Internal.Socket (Response(..), WireKey, checkIdle, encodeKey, noOpRequest,+                                                    recvResponse, responseStatus, sendRaw)++-- | Number of times to retry an operation against a server after its first+-- attempt fails, before giving up (see 'optsServerRetries').+type Retries = Int++-- | Options specifies how a Memcached cluster should be configured.+data Options = Options {+        -- | Number of times to retry an operation against a server after it+        -- fails, so each operation is tried at most @1 + optsServerRetries@+        -- times. Zero or a negative value means it is tried once. If every+        -- attempt fails, we mark the server as down and failover to a+        -- different server for the next operation. An attempt that only ran+        -- out of time waiting for a free connection to the server uses up a+        -- retry like any failed attempt, but the last attempt decides: if it+        -- was such an attempt, the server isn't marked down, whatever the+        -- earlier attempts did (see 'optsTimeout').+        --+        -- A @SERVER_ERROR@ reply whose text names no status, such as+        -- memcached's proxy sends when a backend fails, is a failed attempt,+        -- as a timeout or a network error is: it closes the server's idle+        -- connections, and counts towards marking the server down. So is the+        -- @ERROR Too many open connections@ that memcached sends to a new+        -- connection, and then closes it, when it is at its connection limit+        -- (@-c@); the client reads it while authenticating or checking the+        -- server's version. Other error replies are answers, thrown at once+        -- without counting against the server: any other @ERROR@,+        -- @CLIENT_ERROR@, and a @SERVER_ERROR@ whose text names a status,+        -- such as running out of memory.+        --+        -- A request that mustn't be sent twice is retried only after a+        -- failure before any of it was sent: while waiting for a free+        -- connection, connecting, authenticating or checking the server's+        -- version, or on finding that the server has closed or reset the+        -- connection, or that bytes from the server are already waiting on+        -- it. Those are @increment@, @decrement@, @append@, @prepend@, @add@,+        -- @delete@ and @cas@, and @replace@ with a version.+        -- Once the request may have reached the server, a failure such as a+        -- timeout, a network error, the server closing the connection, a+        -- reply that can't be read or a @SERVER_ERROR@ that names no status+        -- is thrown as it is, and the server is marked down as if every+        -- attempt had failed, whatever retries are left. The server may have+        -- carried out the request, and a retry could apply it twice, or+        -- report failure because the first one succeeded (see+        -- 'keyedOpExpectingOnce'). So behind memcached's proxy, a request for+        -- a key on a failed backend marks the whole proxy down: at once if it+        -- mustn't be sent twice, and otherwise once every attempt gets that+        -- reply.+        --+        -- Every other operation is retried after any failure, so the server+        -- may carry out its request more than once: gets, @touch@, @set@,+        -- @replace@ without a version, the batches of @getMany@,+        -- @setMany@ and @deleteMany@, @flush@, @stats@ and @version@, and+        -- the operations of 'keyedOp', 'anyOp', 'allOp' and 'allOp''. Sent+        -- again, these leave the same data and get an answer as true as the+        -- first, but a store or delete repeated after another client has+        -- changed the key undoes that change. Set this to 0 for no retries.+        --+        -- Default is 1, so an operation is tried at most twice. Before+        -- version 0.5 this was the number of attempts, not retries, and+        -- defaulted to 2, which also meant two attempts.+        optsServerRetries        :: Retries,+        -- | After an operation has failed, how long to wait before retrying it+        -- while still within the 'optsServerRetries' count?+        --+        -- Default is 0.2 seconds.+        optsRetryDelay           :: NominalDiffTime,+        -- | How long to wait after a server has been marked down, before+        -- trying to use it again. @flush@ doesn't wait: it is sent to every+        -- server, marked down or not (see 'serverOpExpecting').+        --+        -- Default is 1.5 seconds.+        optsDeadTimeout          :: NominalDiffTime,+        -- | How long each attempt at an operation may take before it is+        -- considered failed. @stats@ and @flush@ make their attempts for each+        -- server in turn. The time counts from the start of the attempt: it+        -- covers waiting for a free connection in the server's pool, opening+        -- a new connection if one is needed (connecting, authenticating when+        -- there are credentials, and asking the server for its version),+        -- sending the request and reading the reply.+        --+        -- @getMany@, @setMany@ and @deleteMany@ make their attempts for each+        -- batch of up to 256 requests to a server, and give each reply this+        -- time, as the single requests the batch stands for would have. The+        -- first reply's time counts from the start of the attempt, as above,+        -- so it also covers sending the whole batch; each later reply's+        -- counts from when the reply before it was read. So a server that+        -- sends each reply just in time can hold a batch of /n/ requests for+        -- about /n/ + 1 times this per attempt, as /n/ single requests would.+        -- The batch keeps its connection all the while. Other requests to the+        -- server then wait for a free one if its pool has no other (it holds+        -- up to four by default; see 'soNumResources'), and those that run+        -- out of time waiting throw v'Timeout' without marking the server+        -- down, as below.+        --+        -- An attempt that runs out of time while it is still waiting for a+        -- free connection never reached the server. It is retried like any+        -- failed attempt, but if it was the last attempt, the operation+        -- throws v'Timeout' without marking the server down. Running out of+        -- time afterwards, while opening (including authenticating and+        -- checking the version) or using the connection, is a server failure+        -- like any other, however long the attempt waited first.+        --+        -- A large value must be sent or read whole within this time too, so+        -- over a network, values of more than a few tens of MiB can need+        -- more than the default: at 1 Gbit/s, 750 ms carries less than+        -- 90 MiB.+        --+        -- Default is 0.75 seconds.+        optsTimeout              :: NominalDiffTime,+        -- | Figure out which server to talk to for a given key.+        --+        -- Default is 'ketamaServerForKey'. A custom router can use 'isAlive'+        -- to skip servers marked failed.+        optsGetServerForKey      :: Cluster -> Key -> IO (Maybe Server),+        -- | Convert server specifications into servers.+        --+        -- Default uses 'newServerDefault'.+        optsServerSpecsToServers :: ServerOptions -> [ServerSpec] -> IO [Server],++        -- | Connection-pool options for each server.+        optsServerOptions :: ServerOptions+    }++-- | The default cluster options:+--+-- * 'optsServerRetries': 1 (one retry, so an operation is tried at most twice)+-- * 'optsRetryDelay': 0.2 seconds+-- * 'optsDeadTimeout': 1.5 seconds+-- * 'optsTimeout': 0.75 seconds+-- * 'optsGetServerForKey': 'ketamaServerForKey'+-- * 'optsServerSpecsToServers': 'newServerDefault' for each server+-- * 'optsServerOptions': 'defaultServerOptions'+--+-- Change individual fields with a record update, for example+-- @defaultOptions { optsTimeout = 0.25 }@.+defaultOptions :: Options+defaultOptions = Options {+            optsServerRetries  = 1,+            optsRetryDelay     = 0.2,+            optsDeadTimeout    = 1.5,+            optsTimeout        = 0.75,+            optsGetServerForKey = ketamaServerForKey,+            optsServerSpecsToServers = mapM . newServerDefault,+            optsServerOptions = defaultServerOptions+        }++-- | 'def' is 'defaultOptions'.+instance Default Options where+  def = defaultOptions++-- | Get the currently configured servers.+getServers :: Cluster -> IO (V.Vector Server)+getServers = either readMVar (pure . fst) . cServers++-- | Replace the cluster's server set, preserving its routing and retry options.+--+-- Servers are kept in the order given, which breaks ties on the ketama ring+-- (see "Database.Memcache.Internal.Cluster"). A cluster given an 'MVar' caches+-- the ring for the servers in it, rebuilding it only when their hosts or ports+-- change. Every cluster made by 'setServers' shares that cache with the one+-- it was made from, so alternating between two clusters with different hosts+-- in their 'MVar's rebuilds the ring on each switch.+--+-- A client made by ElastiCache discovery has a thread that replaces its+-- servers, which @quit@ stops. That thread doesn't replace the servers given+-- here, so @quit@ on a cluster made from such a client by 'setServers' leaves+-- the thread running.+setServers :: Cluster -> Either (MVar (V.Vector Server)) (V.Vector Server) -> Cluster+setServers c servers = c { cServers = fmap withRing servers, cStopRefresh = pure () }++-- | Establish a new connection to a group of Memcached servers.+newCluster :: [ServerSpec] -> Options -> IO Cluster+newCluster []    _ = throwIO $ ClientError NoServersReady+newCluster hosts Options{..} = do+    s <- optsServerSpecsToServers optsServerOptions hosts+    let fixed = withRing (V.fromList s)+    cache <- newIORef fixed+    return $+        Cluster {+            cServers   = Right fixed,+            cRingCache = cache,+            cRetries   = optsServerRetries ,+            cFailDelay = toMicroseconds optsRetryDelay,+            cDeadDelay = optsDeadTimeout,+            cTimeout   = toMicroseconds optsTimeout,+            cGetServerForKey = optsGetServerForKey,+            cStopRefresh = pure ()+        }++-- | Check if server is alive.+serverAlive :: NominalDiffTime -> Server -> IO Bool+{-# INLINE serverAlive #-}+serverAlive deadDelay s = do+    t <- readIORef (failed s)+    if t == 0+        then return True+        else do+            t' <- getPOSIXTime+            if (t' - t) < deadDelay+                then return False+                else do+                    writeIORef (failed s) 0+                    return True++-- | Whether a server can be used: it isn't marked failed, or it was marked+-- failed at least 'optsDeadTimeout' ago, in which case this clears the+-- mark. A custom 'optsGetServerForKey' can use it to skip servers marked+-- failed, as 'ketamaServerForKey' does.+isAlive :: Cluster -> Server -> IO Bool+{-# INLINE isAlive #-}+isAlive c = serverAlive (cDeadDelay c)++-- | The servers not currently marked as failed.+aliveServers :: Cluster -> IO (V.Vector Server)+{-# INLINE aliveServers #-}+aliveServers c = getServers c >>= V.filterM (serverAlive $ cDeadDelay c)++-- | The default router: a key goes to its owner on the ketama ring, or if+-- that server is marked failed, to the next live server walking forward round+-- the ring (see "Database.Memcache.Internal.Cluster"). 'Nothing' if the+-- cluster has no servers or every server is marked failed.+ketamaServerForKey :: Cluster -> Key -> IO (Maybe Server)+{-# INLINE ketamaServerForKey #-}+ketamaServerForKey c k = do+    (servers, ring) <- either (cachedRing c <=< readMVar) pure (cServers c)+    let firstAlive [] = return Nothing+        firstAlive (i:is) = do+            let s = servers V.! i+            alive <- isAlive c s+            if alive then return (Just s) else firstAlive is+    firstAlive $ Ketama.owners ring $ Ketama.keyHash k++-- | Servers read from the cluster's 'MVar', with their ketama ring. The ring+-- last built is cached with the servers it was built for, and reused while the+-- 'MVar' holds the same 'Server' values, as it does after an ElastiCache+-- refresh that finds the same nodes. Otherwise the ring is reused if the+-- hosts and ports are the same, and rebuilt only if they differ.+cachedRing :: Cluster -> V.Vector Server -> IO (V.Vector Server, Ketama.Ring)+cachedRing c servers = do+    cached@(builtFor, _) <- readIORef (cRingCache c)+    if sameServers builtFor servers+        then return cached+        -- Install the new ring before building it, so concurrent requests+        -- share one build.+        else atomicModifyIORef' (cRingCache c) $ \(builtFor', ring) ->+            let new | sameNames builtFor' servers = (servers, ring)+                    | otherwise = withRing servers+            in (new, new)++-- | Whether two vectors hold the same 'Server' values in the same order. Each+-- 'Server' has its own 'failed' 'IORef', so this compares a pointer per server,+-- and allocates nothing.+sameServers :: V.Vector Server -> V.Vector Server -> Bool+sameServers = pairwise (\x y -> failed x == failed y)++-- | Whether two vectors hold servers with the same hosts and ports in the same+-- order, and so the same ketama ring.+sameNames :: V.Vector Server -> V.Vector Server -> Bool+sameNames = pairwise (\x y -> serverHost x == serverHost y && serverPort x == serverPort y)++-- | Whether two vectors are the same length and every pair of servers at the+-- same position passes the test, checked with a loop so nothing is allocated.+pairwise :: (Server -> Server -> Bool) -> V.Vector Server -> V.Vector Server -> Bool+{-# INLINE pairwise #-}+pairwise same xs ys = V.length xs == V.length ys && go 0+  where+    go i = i == V.length xs || (same (V.unsafeIndex xs i) (V.unsafeIndex ys i) && go (i + 1))++-- | Servers with their ketama ring, all with weight 1, named from the host and+-- port they were configured with. The ring is built when it is first used.+withRing :: V.Vector Server -> (V.Vector Server, Ketama.Ring)+withRing servers = (servers, Ketama.ring (map named (V.toList servers)))+  where+    named s = (Ketama.serverName (hostBytes (serverHost s)) (utf8 (serverPort s)), 1)+    -- A Unix socket's path holds a byte per Char, the bytes the client+    -- connects to, and libmemcached names a socket by those bytes. Encoding+    -- them in UTF-8, as a host's characters are, would give a path outside+    -- ASCII another name.+    hostBytes path@('/' : _) = C.pack path+    hostBytes host = utf8 host+    utf8 = T.encodeUtf8 . T.pack++-- | Whether a request can be sent again after a failure that may have come+-- after the server received it.+data Resend+  -- | Sending it again leaves the same data and gets an answer as true as the+  -- first: a get, an unconditional set, a flush.+  = Resend+  -- | It is sent at most once: a retry could carry it out twice, or answer+  -- for the first one's effect, as an increment or an @add@ would.+  | SendOnce+  deriving Eq++-- | Run a Memcached operation against a particular server, handling any+-- failures that occur, retrying the specified number of times. The reply is+-- checked with the given function while the connection is held, so that a+-- reply it rejects closes the connection.+--+-- A request sent once is retried only after a failure before it was sent.+-- So that a connection the server closed while it sat idle in the pool+-- doesn't count as one, the connection is checked just before sending.+serverOp :: Cluster -> Server -> Resend -> (Response -> IO ()) -> ByteString -> IO Response+{-# INLINE serverOp #-}+serverOp c s resend check req = handle (\(OutOfStep err) -> throwIO err) $+  retryOp c s PerAttempt $ \sent s' _ -> withSocket s' $ \connection -> do+    when (resend == SendOnce) $ do+      checkIdle connection+      writeIORef sent True+    sendRaw connection req+    response <- recvResponse connection+    check response+    return response++rejectProtocolError :: Response -> IO ()+rejectProtocolError response+  | responseCode response `elem` ["ERROR", "CLIENT_ERROR", "SERVER_ERROR"] =+    void (responseStatus response)+  | otherwise = return ()++-- | Reject a reply whose code is none of the given ones, as+-- 'keyedOpExpecting' describes.+expectReply :: String -> [ByteString] -> Response -> IO ()+expectReply operation codes response = do+  rejectProtocolError response+  unless (responseCode response `elem` codes) $ handle (throwIO . OutOfStep) $ do+    -- An unknown code throws 'UnknownStatus' here.+    void (responseStatus response)+    throwIO $ ProtocolError UnexpectedResponse+      { protocolError = "Expected " <> operation <> ", got: " <> show (responseCode response) }++-- | An error for a reply that shows its connection is out of step with its+-- requests. @expectReply@ throws it inside 'withSocket', so that the+-- connection is closed, and @serverOp@ throws the error it carries once+-- @retryOp@ has let it through.+newtype OutOfStep = OutOfStep MemcacheError+  deriving Show++instance Exception OutOfStep++-- | Run a keyed request against the server selected for the key. Of the+-- replies it can read, only an error reply throws: @ERROR@ throws+-- 'UnknownOp', and @CLIENT_ERROR@ and @SERVER_ERROR@ throw 'BadCommand' and+-- 'ServerError', or an 'OpError' when their text names a status, such as+-- 'ErrValueTooLarge'. Each is an answer, thrown at once, except 'ServerError':+-- a @SERVER_ERROR@ whose text names no status is a server failure, as a+-- timeout is. So is memcached's @ERROR Too many open connections@, which+-- throws 'ServerError' too (see 'optsServerRetries'). Any other reply is+-- returned, and the connection goes back to the pool, so a reply the request+-- cannot get leaves it out of step; 'keyedOpExpecting' rejects such a reply.+--+-- After a failure the request is sent again, even if the server may have+-- carried it out (see 'optsServerRetries'), so use it only for requests that+-- can be repeated. 'keyedOpExpectingOnce' is for those that can't.+keyedOp :: Cluster -> Key -> (WireKey -> ByteString) -> IO Response+{-# INLINE keyedOp #-}+keyedOp c = keyedOpWith c Resend rejectProtocolError++-- | Like 'keyedOp', for a request whose reply can only have one of the given+-- codes, such as @[\"VA\", \"EN\"]@ for a get with the @v@ flag. A reply with+-- any other code shows that the connection is out of step with its requests:+-- the reply is likely an earlier request's, and this request's own reply is+-- still to come. Such a reply throws while the connection is held, so the+-- connection is closed rather than returned to the pool, where later requests+-- would read the replies left on it. A code that 'responseStatus' doesn't+-- know throws 'UnknownStatus'. Any other throws 'UnexpectedResponse', whose+-- message names the given operation and the code, as in+-- @Expected GET, got: \"HD\"@. The server has received the request, so it+-- is not sent again, and the error doesn't count towards marking the server+-- dead. Error replies (@ERROR@, @CLIENT_ERROR@ and @SERVER_ERROR@) throw as+-- they do for 'keyedOp', where a @SERVER_ERROR@ whose text names no status+-- is a server failure. After a server failure, the request is sent again, as+-- with 'keyedOp'.+keyedOpExpecting :: Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response+{-# INLINE keyedOpExpecting #-}+keyedOpExpecting c operation codes = keyedOpWith c Resend (expectReply operation codes)++-- | Like 'keyedOpExpecting', for a request that mustn't be sent twice, such+-- as an increment, an @add@, a delete, or a store with a CAS version. Once+-- the request may have reached the server, a failure, such as a timeout, a+-- network error, the server closing the connection, a reply that can't be+-- read or a @SERVER_ERROR@ whose text names no status, isn't retried: the+-- server may have carried out the request, and a second one could apply it+-- twice, or report failure because the first one succeeded. The failure is+-- thrown as it is, and still counts against the server: its idle connections+-- are closed, and it is marked dead, as when the last of an operation's+-- attempts fails. A failure before any of the request is sent, such as+-- waiting for a connection, connecting, authenticating or checking the+-- server's version, is retried as for 'keyedOpExpecting'.+--+-- Before sending, the connection is checked, without waiting, for the server+-- having closed or reset it, as memcached closes idle connections when it+-- restarts or after @-o idle_timeout@, and for bytes from the server already+-- waiting on it. Such a connection is closed, and as after any failure+-- before sending, the request is retried on another if retries are left.+-- With 'optsServerRetries' at 0, the failure is thrown instead, and the+-- server is marked dead (see 'Database.Memcache.Internal.Socket.checkIdle').+keyedOpExpectingOnce :: Cluster -> String -> [ByteString] -> Key -> (WireKey -> ByteString) -> IO Response+{-# INLINE keyedOpExpectingOnce #-}+keyedOpExpectingOnce c operation codes = keyedOpWith c SendOnce (expectReply operation codes)++-- | Run a keyed request, checking its reply with the given function.+keyedOpWith :: Cluster -> Resend -> (Response -> IO ()) -> Key -> (WireKey -> ByteString) -> IO Response+{-# INLINE keyedOpWith #-}+keyedOpWith c resend check k makeReq = do+    wire <- either (throwIO . ClientError) return (encodeKey k)+    s' <- cGetServerForKey c c k+    case s' of+        Just s  -> serverOp c s resend check (makeReq wire)+        Nothing -> throwIO $ ClientError NoServersReady++-- | Run keyed requests grouped by their selected server, pipelining each+-- server's requests in batches. Each request is built from its key's wire+-- form and an opaque. The request must send the opaque unchanged as its @O@+-- flag, in decimal, as the batch encoders in+-- "Database.Memcache.Internal.Socket" do. memcached copies it into the reply,+-- and that matches the reply to its request. A request may get no reply, as a+-- quiet miss does. The results are in the order of the requests.+--+-- Like 'keyedOp', a batch is sent again after a failure, even one after the+-- server may have carried out some of its requests, so use it only for+-- requests that can be repeated.+--+-- A batch holds up to 256 requests, and closes early once its requests reach+-- 1 MiB. Each reply has its own 'optsTimeout', as the single requests+-- the batch stands for would: the first reply's counts from the start of the+-- attempt, so it also covers waiting for a connection, opening one and+-- sending the batch, and each later reply's counts from when the reply before+-- it was 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, the reply+-- that ends the batch included, as /n/ single requests would.+--+-- A miss reply (@EN@) with no opaque is skipped, as there is nothing to+-- return for it. memcached sends one when a read from extstore misses (for+-- quiet gets too, from 1.6.40) and, before 1.6.18, for any get miss that is+-- not quiet. As memcached answers in order, it counts as the reply to the+-- next request, after the one the previous reply answered. Error replies+-- (@ERROR@, @CLIENT_ERROR@ and @SERVER_ERROR@) throw as they do for+-- 'keyedOp', and here too a @SERVER_ERROR@ whose text names no status is a+-- server failure. A reply with an unknown code throws 'UnknownStatus', as its+-- length can't be known. Any other reply with no opaque, with the opaque of+-- no request in its batch, or out of order throws 'UnexpectedResponse', as+-- does a bare @EN@ after the reply to the batch's last request. Either way+-- the connection is closed rather than reused. Like any server failure, the+-- batch is then sent again on a new connection, and the failure counts+-- towards marking the server dead.+keyedBatchOp :: Cluster -> [(Key, WireKey -> Int -> ByteString)] -> IO [(Key, Response)]+keyedBatchOp c requests = do+    groups <- foldM add [] (zip [0..] requests)+    map snd . sortOn fst . concat <$> mapM run groups+  where+    add groups (opaque, (key, makeRequest)) = do+      wire <- either (throwIO . ClientError) return (encodeKey key)+      server <- cGetServerForKey c c key+      case server of+        Nothing -> throwIO $ ClientError NoServersReady+        Just s -> return (insertGroup s (opaque, key, opaqueFlag opaque, makeRequest wire opaque) groups)++    opaqueFlag opaque = C.pack ('O' : show opaque)++    insertGroup s item [] = [(s, [item])]+    insertGroup s item ((s', items):rest)+      | s == s' = (s', item:items) : rest+      | otherwise = (s', items) : insertGroup s item rest++    run (server, items) = concat <$> mapM (runBatch server) (batches (reverse items))++    -- Write the whole batch in one go, then read it back. Batches are bounded+    -- so the server's replies cannot fill the socket buffers while we are+    -- still writing, which would deadlock both ends until the op times out.+    -- Each reply has a timeout of its own, which recvUntilMN starts once it+    -- has read the reply before.+    runBatch server items = retryOp c server PerReply $ \_ server' restartTimeout ->+      withSocket server' $ \connection -> do+        sendRaw connection (B.concat (map request items ++ [noOpRequest]))+        recvUntilMN restartTimeout connection items []++    -- memcached answers in order, so each reply must carry the opaque of a+    -- request after the one the previous reply answered; the requests in+    -- between got no reply. A bare EN is a miss whose opaque memcached+    -- dropped: we can't tell which request it answers, but it is one line+    -- with nothing to return, so skip it. Later replies answer later+    -- requests, so count it as the next request's reply. With no request+    -- left it is one reply too many, and a server sending bare ENs without+    -- end would otherwise keep the batch reading. Anything else means the+    -- replies are out of step with the requests, as may a reply with an+    -- unknown code, whose length we can't know. So throw while the connection+    -- is held, and it is closed rather than returned to the pool. Echoed keys+    -- can't be matched instead: memcached echoes a key raw or as base64+    -- according to how its item was stored, not how the request sent it, and+    -- a raw key can contain a newline.+    recvUntilMN restartTimeout connection pending acc = do+      response <- recvResponse connection <* restartTimeout+      void (responseStatus response)+      case (responseCode response, find (B.isPrefixOf "O") (responseTokens response)) of+        ("MN", _) -> return (reverse acc)+        ("EN", Nothing) | _ : rest <- pending -> recvUntilMN restartTimeout connection rest acc+        (_, opaque) -> case dropWhile (\(_, _, opaque', _) -> Just opaque' /= opaque) pending of+          (n, key, _, _) : rest -> recvUntilMN restartTimeout connection rest ((n, (key, response)) : acc)+          [] -> throwIO $ ProtocolError UnexpectedResponse+            { protocolError = "Expected a reply to a request in the batch, got: "+                <> show (C.unwords (responseCode response : responseTokens response)) }++    request (_, _, _, req) = req++    batchSize = 256 :: Int++    -- The whole batch must be sent within the timeout of its first reply, so+    -- a batch also closes once its requests reach 1 MiB, memcached's default+    -- item size limit. Sending a batch then takes no longer than sending a+    -- single large store; a request over the limit goes in a batch of its+    -- own. The limit counts the requests only: the values that come back in+    -- the replies have a timeout each, as a single get's does.+    batchBytes = 1048576 :: Int++    batches [] = []+    batches xs = batch : batches rest+      where (batch, rest) = splitBatch 0 0 xs++    splitBatch n bytes (x:xs)+      | n == 0 || (n < batchSize && bytes' <= batchBytes) =+          let (batch, rest) = splitBatch (n + 1) bytes' xs in (x : batch, rest)+      where bytes' = bytes + B.length (request x)+    splitBatch _ _ xs = ([], xs)++-- | Run a Memcached operation against any single server in the cluster,+-- handling any failures that occur, retrying the specified number of times.+-- As with 'keyedOp', of the replies it can read, only an error reply throws;+-- 'anyOpExpecting' also rejects a reply the request cannot get. Also as with+-- 'keyedOp', the request is sent again after a failure, so it must be one+-- that can be repeated.+anyOp :: Cluster -> ByteString -> IO Response+{-# INLINE anyOp #-}+anyOp c = anyOpWith c rejectProtocolError++-- | Like 'anyOp', but rejects a reply whose code is none of the given ones,+-- as 'keyedOpExpecting' does.+anyOpExpecting :: Cluster -> String -> [ByteString] -> ByteString -> IO Response+{-# INLINE anyOpExpecting #-}+anyOpExpecting c operation codes = anyOpWith c (expectReply operation codes)++-- | Run a request against any single server, checking its reply with the+-- given function.+anyOpWith :: Cluster -> (Response -> IO ()) -> ByteString -> IO Response+{-# INLINE anyOpWith #-}+anyOpWith c check req = do+    servers' <- aliveServers c+    case V.uncons servers' of+        Nothing     -> throwIO $ ClientError NoServersReady+        Just (s, _) -> serverOp c s Resend check req++-- | Run a Memcached operation against every server not marked failed, in+-- turn, handling any failures that occur, retrying the specified number of+-- times. A server that fails ends the operation, and the servers after it are+-- not sent the request. As with 'keyedOp', of the replies it can read, only+-- an error reply throws; 'allOpExpecting' also rejects a reply the request+-- cannot get. Also as with 'keyedOp', the request is sent again after a+-- failure, so it must be one that can be repeated.+allOp :: Cluster -> ByteString -> IO [(Server, Response)]+{-# INLINE allOp #-}+allOp c req = forAliveServers c $ \s -> serverOp c s Resend rejectProtocolError req++-- | Like 'allOp', but rejects a reply whose code is none of the given ones,+-- as 'keyedOpExpecting' does. The servers after one whose reply is rejected+-- are not sent the request, as with a server that fails. To send a request+-- to every server, including servers marked failed, and carry on past a+-- failure, run 'serverOpExpecting' for each server from 'getServers'.+allOpExpecting :: Cluster -> String -> [ByteString] -> ByteString -> IO [(Server, Response)]+{-# INLINE allOpExpecting #-}+allOpExpecting c operation codes req =+    forAliveServers c $ \s -> serverOp c s Resend (expectReply operation codes) req++-- | Run a request against the given server, such as one from 'getServers',+-- whether or not it is marked failed, rejecting a reply whose code is none+-- of the given ones, as 'keyedOpExpecting' does. As with 'keyedOp', the+-- request is sent again after a failure, so it must be one that can be+-- repeated. If every attempt fails, the server is marked failed, as by any+-- operation, and a server already marked failed is marked again from then. A+-- server marked failed that answers stays marked: the other operations skip+-- it until 'optsDeadTimeout' has passed since it was marked. @flush@ uses+-- this to send @flush_all@ to every server.+serverOpExpecting :: Cluster -> String -> [ByteString] -> Server -> ByteString -> IO Response+{-# INLINE serverOpExpecting #-}+serverOpExpecting c operation codes s = serverOp c s Resend (expectReply operation codes)++-- | Run a Memcached operation against every server not marked failed, handling+-- any failures that occur, retrying the specified number of times. Similar to+-- 'anyOp' but allows more flexible interaction with the 'Server' than a single+-- request and response. The operation must make its requests with+-- 'withSocket' on the 'Server' it is given, not on another value for the same+-- server, or its timeouts never mark the server down (see+-- 'optsTimeout'). Once one of its 'withSocket' calls has got a+-- connection, a timeout is a server failure, even while a later call waits+-- for one. So is any exception the operation throws other than an+-- 'OpError', a 'BadCommand' or 'UnknownOp' protocol error, or an+-- 'InvalidAuthentication' client error, which are rethrown at once. Each+-- server failure closes the server's idle connections, before the operation+-- is retried or the server marked down. The operation is run again from the+-- start after a failure, whatever requests it had sent, so its requests must+-- be ones that can be repeated.+allOp' :: Cluster -> (Server -> IO a) -> IO [(Server, a)]+{-# INLINE allOp' #-}+allOp' c op = forAliveServers c $ \s -> retryOp c s PerAttempt (\_ s' _ -> op s')++-- | Run an action against every server not marked as failed, pairing each+-- result with its server. Throws 'NoServersReady' if there are none.+forAliveServers :: Cluster -> (Server -> IO a) -> IO [(Server, a)]+{-# INLINE forAliveServers #-}+forAliveServers c f = do+    servers' <- aliveServers c+    if V.null servers'+        then throwIO $ ClientError NoServersReady+        else do+            res <- V.mapM f servers'+            return $ V.toList $ V.zip servers' res++-- | How an attempt's time is limited (see 'optsTimeout').+data Timing+  -- | The attempt has one timeout.+  = PerAttempt+  -- | Each reply has its own: the first counts from the start of the+  -- attempt, and the attempt starts each later one once it has read the+  -- reply before, with the action it is given.+  | PerReply++-- | Run an IO operation, retrying it up to the allowed number of retries if an+-- exception is thrown, and marking the server as dead if every attempt fails.+-- Each attempt's time is limited as the @Timing@ says, and the attempt is+-- given an action that starts the next reply's timeout, which does nothing+-- for @PerAttempt@. Each attempt is given the server with a new @slotTaken@,+-- which 'withSocket' sets once it holds a slot in the server's pool. An+-- attempt that runs out of time before that never reached the server. It is+-- retried like any failure, but if it is the last attempt, it throws+-- v'Timeout' without marking the server dead: the last attempt alone decides,+-- whatever the earlier ones did. Every other failure but a client fault first+-- closes the server's idle connections, before the operation is retried or+-- the server marked dead.+--+-- Each attempt is also given an 'IORef' that it sets just before it sends a+-- request that mustn't be sent twice. A failure after that isn't retried,+-- whatever retries are left: it marks the server dead, as the last attempt's+-- failure does, and is rethrown.+retryOp :: forall a. Cluster -> Server -> Timing -> (IORef Bool -> Server -> IO () -> IO a) -> IO a+{-# INLINE retryOp #-}+retryOp Cluster{..} s timing op = go cRetries+  where+    -- An attempt's exception is handled once 'try' has returned it, rather+    -- than in a handler. A handler runs with asynchronous exceptions masked,+    -- and so would the retry it started: nothing could then interrupt the+    -- retry until it blocked, not even its own timeout. This 'try' is+    -- unliftio's, which lets asynchronous exceptions through, so that the+    -- caller can still interrupt the operation.+    go :: Int -> IO a+    {-# INLINE go #-}+    go !n = do+        sent <- newIORef False+        try (attempt sent) >>= either (handleErrs n sent) return++    -- One attempt at the operation, with its own timeout or timeouts and+    -- @slotTaken@.+    attempt :: IORef Bool -> IO a+    attempt sent = do+        taken <- newIORef False+        let run = op sent s { slotTaken = Just taken }+        mr <- case timing of+            PerAttempt -> timeout cTimeout (run (return ()))+            PerReply   -> timeoutRestartable cTimeout run+        case mr of+            Just r  -> return r+            Nothing -> do+                held <- readIORef taken+                if held+                    then throwIO (ClientError Timeout)+                    else throwIO WaitedForSlot++    handleErrs :: Int -> IORef Bool -> SomeException -> IO a+    {-# INLINE handleErrs #-}+    handleErrs n sent err+        | clientFault err = throwIO err+        | otherwise = case fromException err of+            Just WaitedForSlot -> retryOr n $ throwIO (ClientError Timeout)+            Nothing -> do+                -- The attempt's own connection, if it had one, is closed+                -- already, unless the operation had given it back before+                -- failing. What made the attempt fail, such as a restart of+                -- the server, may have broken the idle ones too, and the+                -- retry, or the next operation once the server is back,+                -- would take one of those.+                close s+                -- The server may have carried out a request that mustn't be+                -- sent twice, so its failure ends the operation, like the+                -- last attempt's.+                once <- readIORef sent+                let giveUp = do+                      writeIORef (failed s) =<< getPOSIXTime+                      throwIO err+                if once then giveUp else retryOr n giveUp++    -- Retry the operation if it has retries left, or else give up.+    retryOr :: Int -> IO a -> IO a+    {-# INLINE retryOr #-}+    retryOr n giveUp+        | n <= 0 = giveUp+        | otherwise = threadDelay cFailDelay >> go (n - 1)++-- | Thrown by an attempt that runs out of time while it waits for a slot in+-- the server's pool. @retryOp@ retries it like a failure, but without closing+-- the idle connections, and if it is the last attempt, throws v'Timeout'+-- instead, without marking the server dead.+data WaitedForSlot = WaitedForSlot+  deriving Show++instance Exception WaitedForSlot++-- | A rejected command or a reported operation status is an answer, not a+-- server failure: retrying it will fail identically and must not count towards+-- marking the server dead. That includes the 'UnknownOp' a new connection+-- throws when it refuses the server's version: a retry would find the same+-- version. memcached's @ERROR Too many open connections@ is no answer, though:+-- it throws 'ServerError', as the server may take a connection later. Nor is+-- a reply out of step retried or counted: the server has the request, and may+-- have carried it out.+clientFault :: SomeException -> Bool+clientFault err = case fromException err of+    Just (ProtocolError BadCommand{}) -> True+    Just (ProtocolError UnknownOp{})  -> True+    Just (OpError _)                  -> True+    Just (ClientError InvalidAuthentication{}) -> True+    _                                 -> isJust (fromException err :: Maybe OutOfStep)
+ Database/Memcache/Internal/Ketama.hs view
@@ -0,0 +1,189 @@+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Ketama+Description : libmemcached-compatible consistent hashing+Copyright   : (c) David Terei, 2026+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Ketama consistent hashing, computed exactly as libmemcached does for+@MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@. The cluster uses this to choose the+server for each key. It is exposed for working out which server a key belongs+to, and for building rings with weights, which the cluster does not use.++A ring has 160 points per server on a 32-bit circle, shared out in proportion+to the servers' weights. The points of a server named @n@ come from the MD5+digests of @n-0@, @n-1@, and so on, each digest giving four little-endian+32-bit points. A key hashes to the first four bytes of its MD5 digest, read+little-endian, and belongs to the server owning the first point at or after+that hash, wrapping round to the lowest point.++With equal weights, adding or removing a server only moves the keys on that+server's points, unless it changes the number of points each server gets+(from 24 servers to 25, say). With unequal weights, it changes the other+servers' numbers of points too, so some of their keys move between them.++The details follow libmemcached so that both choose the same server:++* The number of points is computed in single precision, which gives 156+  rather than 160 points per server for some numbers of equally weighted+  servers, such as 25.++* Points with the same value are ordered by server position, so the earlier+  server in the list wins the tie, as in libmemcached 1.1 and later.++* A server's name is its host alone on port 11211 and @host:port@ on any other+  port (see 'serverName').+-}+module Database.Memcache.Internal.Ketama (+        -- * Rings+        Ring, ring, serverName,++        -- * Lookup+        keyHash, owner, owners,++        -- * Inspection+        ringPoints+    ) where++import           Control.Monad.ST            (runST)+import qualified Crypto.Hash.MD5             as MD5+import           Data.Bits                   (shiftL, (.|.))+import           Data.ByteString             (ByteString)+import qualified Data.ByteString             as B+import qualified Data.ByteString.Char8       as C+import           Data.List                   (sort)+import qualified Data.Vector.Unboxed         as VU+import qualified Data.Vector.Unboxed.Mutable as VUM+import           Data.Word                   (Word32)++-- | A ketama ring (libmemcached calls it the continuum) over a list of+-- servers. Servers are identified by their position in the list the ring was+-- built from, starting at 0.+data Ring = Ring {+        -- | Point values, in ascending order.+        rValues  :: !(VU.Vector Word32),+        -- | The position of the server owning each point.+        rOwners  :: !(VU.Vector Int),+        -- | How many servers the ring was built from.+        rSize    :: !Int,+        -- | How many servers have at least one point.+        rServers :: !Int+    }++-- | Build a ring from each server's name (see 'serverName') and weight, in+-- the order that decides ties. Weights below 1 count as 1, as libmemcached+-- treats a weight of 0. Give every server the same weight to match clients+-- that are not configured with weights.+ring :: [(ByteString, Int)] -> Ring+ring servers = Ring values owners' (length servers) (length (filter (> 0) counts))+  where+    weights = map (max 1 . snd) servers+    total = sum weights+    counts = [pointsPerServer w total (length servers) | w <- weights]+    (values, owners') = VU.unzip $ VU.fromList $ sort+        [ (point, index)+        | (index, (name, _), count) <- zip3 [0 ..] servers counts+        , i <- [0 .. count `quot` 4 - 1]+        , point <- digestPoints (name <> "-" <> C.pack (show (i :: Int)))+        ]++-- | The name libmemcached derives a server's points from, given its host and+-- port as written in its configuration: the host alone for the default port+-- 11211, otherwise @host:port@. Hosts are not resolved, so @localhost@ and+-- @127.0.0.1@ are different servers on the ring.+serverName :: ByteString -> ByteString -> ByteString+serverName host port+    | port == "11211" = host+    | otherwise       = host <> ":" <> port++-- | The number of points a server gets: libmemcached's+-- @floor(weight / total * 160 / 4 * servers + 1e-10) * 4@, evaluated left to+-- right in single precision as the C code does.+pointsPerServer :: Int -> Int -> Int -> Int+pointsPerServer weight total servers =+    4 * floor (share * 160 / 4 * fromIntegral servers + 1.0e-10 :: Float)+  where+    share = fromIntegral weight / fromIntegral total :: Float++-- | The four points of a name: its MD5 digest read as four little-endian+-- 32-bit words.+digestPoints :: ByteString -> [Word32]+digestPoints name = [littleEndian digest offset | offset <- [0, 4, 8, 12]]+  where+    digest = MD5.hash name++-- | The position of a key on the ring: the first four bytes of the MD5 digest+-- of the key, read little-endian. This is libmemcached's MD5 key hash; it is+-- taken over the key as given, not its base64 form on the wire.+keyHash :: ByteString -> Word32+keyHash key = littleEndian (MD5.hash key) 0++littleEndian :: ByteString -> Int -> Word32+littleEndian bytes offset =+    byte 0 .|. byte 1 `shiftL` 8 .|. byte 2 `shiftL` 16 .|. byte 3 `shiftL` 24+  where+    byte i = fromIntegral (B.index bytes (offset + i))++-- | The server owning a hash: the owner of the first point at or after it,+-- wrapping round to the lowest point. 'Nothing' only for a ring with no+-- servers.+owner :: Ring -> Word32 -> Maybe Int+owner r hash+    | VU.null (rOwners r) = Nothing+    | otherwise           = Just (VU.unsafeIndex (rOwners r) (firstPoint r hash))++-- | Every server on the ring, in the order a key with this hash falls back to+-- them: the 'owner' first, then each other server in the order its first point+-- comes walking forward round the ring from the hash. Keeping the ring and+-- skipping servers that are down this way leaves every other key where it was.+-- Taking only the head costs no more than 'owner'; the rest of the list takes+-- one walk round the ring, which stops once every server has been found.+owners :: Ring -> Word32 -> [Int]+owners r hash+    | n == 0    = []+    | otherwise = first : others+  where+    points = rOwners r+    n = VU.length points+    start = firstPoint r hash+    first = VU.unsafeIndex points start+    others = runST $ do+        seen <- VUM.replicate (rSize r) False+        VUM.unsafeWrite seen first True+        let walk i found acc+                | found == rServers r || i == start + n = return (reverse acc)+                | otherwise = do+                    let server = VU.unsafeIndex points (if i < n then i else i - n)+                    known <- VUM.unsafeRead seen server+                    if known+                        then walk (i + 1) found acc+                        else do+                            VUM.unsafeWrite seen server True+                            walk (i + 1) (found + 1) (server : acc)+        walk (start + 1) (1 :: Int) []++-- | The index of the first point at or after the hash, or 0 if there is none.+firstPoint :: Ring -> Word32 -> Int+firstPoint r hash = if found == VU.length values then 0 else found+  where+    values = rValues r+    found = search 0 (VU.length values)+    search lo hi+        | lo >= hi = lo+        | VU.unsafeIndex values mid < hash = search (mid + 1) hi+        | otherwise = search lo mid+      where+        mid = (lo + hi) `quot` 2++-- | Every point on the ring in ascending order, with the position of the+-- server that owns it.+ringPoints :: Ring -> [(Word32, Int)]+ringPoints r = VU.toList (VU.zip (rValues r) (rOwners r))
+ Database/Memcache/Internal/Lookup.hs view
@@ -0,0 +1,63 @@+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Lookup+Description : Host lookups that a timeout can end+Copyright   : (c) David Terei, 2026+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Host lookups in a thread of their own, so that a timeout can end the wait.+-}+module Database.Memcache.Internal.Lookup (+        Lookup, newLookup, addressesOf+    ) where++import           Control.Concurrent       (forkIO)+import           Control.Concurrent.MVar  (MVar, modifyMVarMasked, newEmptyMVar, newMVar, putMVar,+                                           readMVar, swapMVar)+import           Control.Exception        (SomeException, throwIO, try)+import           Network.Socket           (AddrInfo, HostName, ServiceName)+import qualified Network.Socket           as S++-- | A server's host lookup, while one runs: where it will put its result.+newtype Lookup = Lookup (MVar (Maybe (MVar (Either SomeException [AddrInfo]))))++-- | A 'Lookup' with no lookup running, for a new server.+newLookup :: IO Lookup+newLookup = Lookup <$> newMVar Nothing++-- | The addresses to try for a host and port; a path is a Unix socket. The+-- resolver runs in a thread of its own, so that a timeout ends the wait at+-- once, though it can't interrupt the foreign call, which is left to finish.+-- Calls made meanwhile wait for it rather than start another lookup.+addressesOf+    :: Lookup+    -> (Maybe AddrInfo -> Maybe HostName -> Maybe ServiceName -> IO [AddrInfo])+    -> HostName -> ServiceName -> IO [AddrInfo]+addressesOf (Lookup running) resolve host port = case host of+    '/' : _ -> return [S.defaultHints {+        S.addrFamily = S.AF_UNIX,+        S.addrSocketType = S.Stream,+        S.addrAddress = S.SockAddrUnix host+      }]+    _ -> do+        result <- modifyMVarMasked running $ \current -> case current of+            Just started -> return (current, started)+            Nothing -> do+                new <- newEmptyMVar+                -- Cleared before the result is out, so later calls look up+                -- afresh.+                _ <- forkIO $ do+                    addresses <- try $ resolve (Just hints) (Just host) (Just port)+                    _ <- swapMVar running Nothing+                    putMVar new addresses+                return (Just new, new)+        readMVar result >>= either throwIO return+  where+    hints = S.defaultHints { S.addrSocketType = S.Stream }
+ Database/Memcache/Internal/Server.hs view
@@ -0,0 +1,330 @@+{-# LANGUAGE RecordWildCards   #-}+{-# LANGUAGE CPP               #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Server+Description : Server Handling+Copyright   : (c) David Terei, 2016+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Handles the connections between a Memcached client and a single server.++Each new connection is authenticated, when its 'ServerSpec' has credentials,+and then asks the server for its version before it is used. Unless the server+reports memcached 1.6.10 or later, the connection is closed, having sent+nothing but the authentication exchange, when there are credentials, and+@version@, and v'ProtocolError' 'UnknownOp' is thrown (or, for an error reply,+what that reply throws for any request).++Memcached expected errors (part of the protocol) are returned in the Response;+unexpected errors, such as network failures, are thrown as exceptions. The+server's 'failed' timestamp is used by cluster retry handling.+-}+module Database.Memcache.Internal.Server (+      -- * Server+        Server(sid, failed), serverHost, serverPort, newServerDefault,+        withSocket, close, closeAll,++      -- * ServerOptions+        ServerOptions(..), defaultServerOptions+    ) where++import           Database.Memcache.Errors+import           Database.Memcache.Internal.Auth+import           Database.Memcache.Internal.Lookup (Lookup, addressesOf, newLookup)+import           Database.Memcache.Internal.Socket+import           Database.Memcache.Types.Server++import           Control.Monad            (void, when)+import qualified Data.ByteString.Char8    as C+import           Data.Char                (isDigit)+import           Data.Default+import           Data.Hashable+import           Data.IORef+import qualified Data.Pool as P+import           Data.Pool (Pool)+import           Data.Time.Clock          (NominalDiffTime)+import           Database.Memcache.Types  (ServerSpec (..))+import           UnliftIO.Exception++import           Network.Socket           (HostName, ServiceName, getAddrInfo)+import qualified Network.Socket           as S++-- | The host the server was configured with, as given in its 'ServerSpec'.+serverHost :: Server -> HostName+serverHost = addr++-- | The port or service name the server was configured with, as given in its+-- 'ServerSpec'.+serverPort :: Server -> ServiceName+serverPort = port++-- | Configurable options when creating a @Server@.+--+-- At the moment, this only applies to the @Pool@ information. This can be expanded in the future.+--+-- The package's bounds allow resource-pool 0.2, and 0.4 or later, but not+-- 0.3. With 0.3, a pool has a stripe for each capability, whatever+-- 'soNumStripes' is, and each stripe holds a share of the connections. A+-- thread takes connections only from its own capability's stripe, so a+-- request could wait for one while other stripes had room, and an operation+-- that holds a connection and asks for another could wait, until it ran out+-- of time, for the one it holds itself.+--+data ServerOptions+  = ServerOptions+  -- | Maximum number of pooled connections per stripe. With resource-pool 0.4+  -- or later, it is split between the stripes instead, and must be at least+  -- 'soNumStripes', or creating the server (and so a client) throws an+  -- @ErrorCall@. Each stripe then holds up to 'soNumResources' divided by+  -- 'soNumStripes', rounded up with 0.4, and rounded down or up with 0.5 so+  -- that the total is 'soNumResources'.+  { soNumResources :: Int+  -- | Number of pool stripes. With resource-pool 0.4 and 0.5.0.0, stripes+  -- beyond the number of capabilities are never used.+  , soNumStripes :: Int+  -- | Connection keep-alive duration.+  , soKeepAlive :: NominalDiffTime+  }++-- | The default server options:+--+-- * 'soNumResources': 4+-- * 'soNumStripes': 1+-- * 'soKeepAlive': 300 seconds+--+-- That is, at most four connections to each server, each closed once it has+-- been idle for 300 seconds.+defaultServerOptions :: ServerOptions+defaultServerOptions = ServerOptions+      { soNumResources = 4+      , soNumStripes = 1+      , soKeepAlive = 300+      }++-- | 'def' is 'defaultServerOptions'.+instance Default ServerOptions where+  def = defaultServerOptions++-- | Create a server using the default socket-pool implementation.+newServerDefault :: ServerOptions -> ServerSpec -> IO Server+newServerDefault serverOptions ServerSpec{..} = do+    fat <- newIORef 0+    gen <- newIORef 0+    pSock <- getNewPool serverOptions+    hl <- newLookup+    return Server+        { sid      = serverHash+        , pool     = pSock+        , addr     = ssHost+        , port     = ssPort+        , auth     = ssAuth+        , failed   = fat+        , generation = gen+        , slotTaken = Nothing+        , hostLookup = hl+        }+  where+    serverHash = hash (ssHost, ssPort)+++-- | Run a function with access to a pooled server connection. Afterwards the+-- connection goes back to the pool, unless the function threw or 'closeAll'+-- has run since the connection was opened, in which case it is closed. The+-- function is never given a connection opened before the latest 'closeAll'.+withSocket :: Server -> (Connection -> IO a) -> IO a+{-# INLINE withSocket #-}+withSocket svr act = mask $ \restore -> do+    (slot, local) <- P.takeResource (pool svr)+    -- Record that the request has stopped waiting (see 'slotTaken').+    mapM_ (`writeIORef` True) (slotTaken svr)+    (born, conn) <- connectionIn slot `onException` P.destroyResource (pool svr) local slot+    r <- restore (act conn) `onException` P.destroyResource (pool svr) local slot+    stale <- (/= born) <$> currentGeneration svr+    if stale+      then P.destroyResource (pool svr) local slot+      else do+        P.putResource local slot+        -- 'closeAll' may have run between the check and the put, and closed+        -- the idle connections before this one was back. If so, close them+        -- again, without letting an exception cut that short.+        raced <- (/= born) <$> currentGeneration svr+        when raced $ uninterruptibleMask_ $ P.destroyAllResources (pool svr)+    return r+  where+    -- The slot's connection, opening one if the slot has none or closing and+    -- replacing one opened before the latest 'closeAll'. 'closeAll' may run+    -- while a connection is being opened, so check the new one too.+    connectionIn slot = do+      held <- readIORef slot+      current <- currentGeneration svr+      case held of+        Just res@(born, _) | born == current -> return res+        _ -> do+          releaseSlot slot+          writeIORef slot Nothing+          res <- connectTagged (generation svr) (hostLookup svr) (ServerSpec (addr svr) (port svr) (auth svr))+          writeIORef slot (Just res)+          connectionIn slot++-- | Close the connections that are idle in the pool. Connections in use stay+-- open and go back to the pool when their request finishes; 'closeAll' closes+-- those too. A later request re-establishes connections as needed. An+-- asynchronous exception can't cut 'close' short: it is delivered once every+-- idle connection is closed.+close :: Server -> IO ()+{-# INLINE close #-}+close srv = uninterruptibleMask_ $ P.destroyAllResources $ pool srv++-- | Close every connection to the server: idle connections now, and each+-- connection in use as soon as the request using it finishes, instead of+-- returning it to the pool. It doesn't wait for those requests or interrupt+-- them, and it never connects or throws. Requests that start later never use+-- a connection opened before 'closeAll'; they open new ones. Like 'close', it+-- can't be cut short by an asynchronous exception.+closeAll :: Server -> IO ()+closeAll srv = uninterruptibleMask_ $ do+    atomicModifyIORef' (generation srv) (\g -> (g + 1, ()))+    P.destroyAllResources (pool srv)++-- | Read the generation. The read is atomic for simplicity; what makes the+-- checks in 'withSocket' sound is that it and 'closeAll' both go through the+-- pool's per-stripe lock, which orders the bump against a returned connection.+currentGeneration :: Server -> IO Int+currentGeneration svr = atomicModifyIORef' (generation svr) (\g -> (g, g))++-- Slots start empty: 'withSocket' opens a connection in a slot once it holds+-- the slot, so that connecting isn't part of waiting for one.+#if MIN_VERSION_resource_pool(0,4,0)+getNewPool :: ServerOptions -> IO (Pool Slot)+getNewPool serverOptions =+  P.newPool+    $ P.setNumStripes (Just $ soNumStripes serverOptions)+    $ P.defaultPoolConfig (newIORef Nothing) releaseSlot+        (realToFrac (soKeepAlive serverOptions)) (soNumResources serverOptions)+#else+getNewPool :: ServerOptions -> IO (Pool Slot)+getNewPool serverOptions =+  P.createPool (newIORef Nothing) releaseSlot (soNumStripes serverOptions) (soKeepAlive serverOptions) (soNumResources serverOptions)+#endif++-- | Close the slot's connection, if it has one.+releaseSlot :: Slot -> IO ()+releaseSlot slot = readIORef slot >>= mapM_ (releaseSocket . snd)++-- | Open a connection, paired with the generation current when it was opened.+connectTagged :: IORef Int -> Lookup -> ServerSpec -> IO (Int, Connection)+connectTagged gen hl ss = do+    born <- atomicModifyIORef' gen (\g -> (g, g))+    conn <- connectSocket hl ss+    return (born, conn)++connectSocket :: Lookup -> ServerSpec -> IO Connection+connectSocket hl ServerSpec{..} = do+    addr:addrs <- addressesOf hl getAddrInfo ssHost ssPort+    bracketOnError+        (connectFirst addr addrs)+        S.close+        (\s -> do+            -- A Unix socket rejects NoDelay, and has no TCP connection to+            -- keep alive.+            when (S.addrFamily addr /= S.AF_UNIX) $ do+                S.setSocketOption s S.KeepAlive 1+                S.setSocketOption s S.NoDelay 1+            buffered <- newConnection s+            authenticate buffered ssAuth+            checkVersion buffered+            return buffered+        )++-- | The oldest memcached this client works with. From 1.6.10, the meta set+-- command that every store sends takes the data length as the token after+-- the key. Older servers reject the command without reading the data that+-- follows it, and then run the stored value's bytes as commands.+minimumVersion :: (Integer, Integer, Integer)+minimumVersion = (1, 6, 10)++-- | Ask the server for its version, and throw unless it is at least+-- @minimumVersion@. Every new connection does this, after authenticating when+-- there are credentials, before it is used for anything else, whichever of+-- the host's addresses it connected to, or through a Unix socket;+-- @connectSocket@ closes the connection when this throws.+--+-- An error reply, such as @CLIENT_ERROR unauthenticated@ from a server in+-- auth-file mode when no credentials are set, throws what it throws as the+-- reply to any request. So the @ERROR Too many open connections@ that+-- memcached sends to a new connection, and then closes it, when it is at its+-- connection limit throws 'ServerError', a server failure: the operation is+-- retried, and the server is marked as failed if every attempt gets it. With+-- credentials, 'authenticate' reads that line first, and throws the same.+-- Any other reply that isn't @VERSION@ and a version of at least+-- @minimumVersion@ throws v'ProtocolError' 'UnknownOp', quoting the reply and+-- naming the minimum. Retries treat that as a client fault, like a rejected+-- command: the server's version won't change on a retry, so the operation+-- fails at once and the server isn't marked as failed.+checkVersion :: Connection -> IO ()+checkVersion connection = do+    sendRaw connection versionRequest+    response <- recvResponse connection+    when (responseCode response `elem` ["ERROR", "CLIENT_ERROR", "SERVER_ERROR"]) $+        void (responseStatus response)+    case responseVersion response of+        Just v | v >= minimumVersion -> return ()+        _ -> throwIO $ ProtocolError UnknownOp+            { protocolError = "memcached " <> showVersion minimumVersion+                <> " or later is required, but the server answered version with "+                <> show (C.unwords (responseCode response : responseTokens response))+            }+  where+    showVersion (major, minor, patch) =+        show major <> "." <> show minor <> "." <> show patch++-- | The version in a @VERSION@ reply, as its first three numbers: major,+-- minor and patch, separated by dots. Anything after the third number, such+-- as a @-rc1@ suffix or a word after the version, is ignored.+responseVersion :: Response -> Maybe (Integer, Integer, Integer)+responseVersion (Response "VERSION" (token:_) _) = do+    (major, afterMajor) <- number token+    (minor, afterMinor) <- number =<< C.stripPrefix "." afterMajor+    (patch, _)          <- number =<< C.stripPrefix "." afterMinor+    return (major, minor, patch)+  where+    number bytes = case C.span isDigit bytes of+        (digits, remainder) | not (C.null digits) -> Just (read (C.unpack digits), remainder)+        _ -> Nothing+responseVersion _ = Nothing++-- | Connect a socket to the first of the resolved addresses that accepts,+-- trying them in order, so a host whose first address refuses the connection+-- (such as ::1 when the server listens on 127.0.0.1 only) can still be reached+-- through the others. If none accepts, rethrows the first address's error:+-- the resolver sorts addresses this host cannot use, such as IPv6 where it is+-- disabled, last, so the later errors are often just about those.+--+-- Only an 'IOException' from creating or connecting a socket moves on to the+-- next address, so the attempt's timeout ends the loop. Errors once+-- connected, such as rejected credentials, are raised after this returns:+-- they come from the server, and trying another address would hide them.+connectFirst :: S.AddrInfo -> [S.AddrInfo] -> IO S.Socket+connectFirst addr addrs = do+    result <- tryIO $ connectTo addr+    case result of+        Right s  -> return s+        Left err -> foldr orElse (throwIO err) addrs+  where+    orElse next rest = tryIO (connectTo next) >>= either (const rest) return+    connectTo a = bracketOnError+        (S.socket (S.addrFamily a) (S.addrSocketType a) (S.addrProtocol a))+        S.close+        (\s -> S.connect s (S.addrAddress a) >> return s)++releaseSocket :: Connection -> IO ()+releaseSocket = closeConnection
+ Database/Memcache/Internal/Socket.hs view
@@ -0,0 +1,582 @@+{-# LANGUAGE CApiFFI           #-}+{-# LANGUAGE CPP               #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+Module      : Database.Memcache.Internal.Socket+Description : Meta Text protocol socket handling+Copyright   : (c) David Terei, 2016+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+Portability : GHC++This module is internal: it isn't covered by the PVP, and may change in any+release.++Low-level connections, replies, and request encoders for Memcached's Meta Text+protocol. Authentication uses the text auth-file command.+-}+module Database.Memcache.Internal.Socket (+        -- * Types+        ArithMode(..), Connection, Response(..), StoreMode(..), WireKey(..),+        crlf,++        -- * Operations+        newConnection, closeConnection, checkIdle,+        sendRaw,+        recvExact, recvLine, recvRawUntil, recvResponse,++        -- * Response readers+        responseStatus, responseCas, responseFlags, responseNumber,++        -- * Constructors+        encodeKey, getRequest, getManyRequest, gatRequest, touchRequest,+        storeRequest, setManyRequest, arithmeticRequest, deleteRequest,+        deleteManyRequest, flushRequest, versionRequest, modifyRequest,+        statsRequest, quitRequest, authRequest, noOpRequest+    ) where++import           Database.Memcache.Errors+import           Database.Memcache.Types+import           Database.Memcache.Util    (maxValueLength, readDecimal)++import           Control.Monad             (unless)+import           Data.ByteString           (ByteString)+import qualified Data.ByteString           as B+import qualified Data.ByteString.Base64    as Base64+import           Data.ByteString.Builder   (Builder, byteString, intDec, word32Dec, word64Dec)+import           Data.ByteString.Builder.Extra (byteStringCopy, smallChunkSize, toLazyByteStringWith,+                                                untrimmedStrategy)+import qualified Data.ByteString.Char8     as C+import qualified Data.ByteString.Lazy      as BL+import           Data.Char                 (toLower)+import           Data.IORef+import           Data.List                 (find, isInfixOf)+import           Data.Maybe                (fromMaybe)+import           Data.Word                 (Word64)+import qualified Network.Socket            as N+import qualified Network.Socket.ByteString as N+import           UnliftIO.Exception        (throwIO)+#if !defined(mingw32_HOST_OS)+import           Data.Bits                 ((.|.))+import           Foreign.C.Error           (eAGAIN, eINTR, eWOULDBLOCK, errnoToIOError, getErrno)+import           Foreign.C.Types           (CChar, CInt (..), CSize (..))+import           Foreign.Marshal.Alloc     (allocaBytes)+import           Foreign.Ptr               (Ptr)+import           System.Posix.Types        (CSsize (..))+#endif++-- | A connected Memcached socket and its receive buffer.+data Connection = Connection N.Socket (IORef ByteString)++-- | A decoded Meta Text response.+data Response = Response+  -- | The response code, such as @VA@ or @HD@.+  { responseCode :: ByteString+  -- | Tokens following the response code. As in memcached, only spaces+  -- separate tokens, so a token can contain other whitespace bytes, such as+  -- a tab or 0xa0.+  , responseTokens :: [ByteString]+  -- | The response value, when the response contains one.+  , responseValue :: ByteString+  } deriving (Eq, Show)++-- | Create a connection wrapper around a socket.+--+-- This doesn't check the server's version. Connections that+-- "Database.Memcache.Internal.Server" makes are checked, and refuse a server+-- older than memcached 1.6.10; a connection made here directly is not, so+-- check the server's version before sending it 'storeRequest',+-- 'setManyRequest' or 'modifyRequest'.+newConnection :: N.Socket -> IO Connection+newConnection s = Connection s <$> newIORef B.empty++-- | Close the underlying socket.+closeConnection :: Connection -> IO ()+closeConnection (Connection s _) = N.close s++-- | Check, without waiting, that the connection is as a finished exchange+-- leaves it: everything the server sent has been read, and the server hasn't+-- closed the connection. Throws as reading from it would, if the server has+-- closed it ('UnexpectedEOF') or reset it (an+-- t'Control.Exception.IOException'), and throws 'UnexpectedResponse' if bytes+-- are waiting to be read, which would be taken as the reply to the next+-- request.+--+-- Use it on a connection taken from a pool before sending a request that+-- mustn't be sent twice. memcached closes idle connections when it restarts+-- or after @-o idle_timeout@, and a request sent on one of those never+-- reaches it but fails as if it might have, with 'UnexpectedEOF'. It costs a+-- system call, and it can't see a connection that the network dropped+-- without telling either end, or one the server closes after the check.+-- On Windows it only checks the bytes already read from the socket.+checkIdle :: Connection -> IO ()+checkIdle (Connection s ref) = do+  buffered <- readIORef ref+  waiting <- if B.null buffered then peekSocket s else return (Just (B.length buffered))+  case waiting of+    Nothing -> return ()+    Just 0 -> throwIO eofError+    Just _ -> throwIO $ ProtocolError UnexpectedResponse+      { protocolError = "Expected no data on an idle connection" }++-- | Look, without waiting or taking anything, at what the socket has received:+-- 'Nothing' if nothing, @Just 0@ if the peer has closed the connection, and+-- otherwise how many bytes are waiting (here at most 1). Throws the error of a+-- connection that was reset.+peekSocket :: N.Socket -> IO (Maybe Int)+#if defined(mingw32_HOST_OS)+-- Windows has no MSG_DONTWAIT, so there is no look that can't wait.+peekSocket _ = return Nothing+#else+peekSocket s = N.withFdSocket s $ \fd -> allocaBytes 1 $ \buffer -> peekInto fd buffer+  where+    peekInto fd buffer = do+      n <- c_recv fd buffer 1 (msgPeek .|. msgDontWait)+      if n >= 0 then return (Just (fromIntegral n)) else getErrno >>= failed fd buffer+    failed fd buffer errno+      | errno == eINTR = peekInto fd buffer+      | errno == eAGAIN || errno == eWOULDBLOCK = return Nothing+      | otherwise = throwIO (errnoToIOError "recv" errno Nothing Nothing)++foreign import ccall unsafe "recv"+  c_recv :: CInt -> Ptr CChar -> CSize -> CInt -> IO CSsize++foreign import capi "sys/socket.h value MSG_PEEK" msgPeek :: CInt++foreign import capi "sys/socket.h value MSG_DONTWAIT" msgDontWait :: CInt+#endif++-- | Send raw bytes on the underlying socket.+sendRaw :: Connection -> ByteString -> IO ()+sendRaw (Connection s _) = N.sendAll s++-- | Receive and decode one Meta Text response.+--+-- A @VA@ reply's value is read if it is at most 1 GiB long, the longest value+-- the operations in "Database.Memcache.Client" send; no memcached server can+-- store a value that long. A reply that claims a longer value throws+-- 'BadLength' before any of the value is read, as does one whose length is+-- missing or malformed.+recvResponse :: Connection -> IO Response+recvResponse s = do+  line <- recvLine s+  case splitTokens line of+    [] -> throwIO $ ProtocolError UnknownPkt { protocolError = "" }+    code:tokens -> case tokens of+      n:_ | code == "VA" -> do+        value <- recvExact s =<< parseLength n+        trailer <- recvLine s+        unless (trailer == "\r") $ throwIO $ ProtocolError BadLength+          { protocolError = "value is not followed by an empty line" }+        return $ Response code tokens value+      [] | code == "VA" -> throwIO $ ProtocolError BadLength { protocolError = "invalid value length" }+      _ -> return $ Response code tokens B.empty+  where+    -- 'recvExact' reads the value as it arrives, at most 64 KiB at a time, so+    -- the memory it holds grows with the bytes that arrive, not with the+    -- length claimed.+    parseLength x = case readDecimal x of+      Just n | n <= maxValueLength -> return n+      _ -> throwIO $ ProtocolError BadLength { protocolError = "invalid value length" }++    -- Split the line as memcached does: on spaces alone, after removing the+    -- CR that 'recvLine' leaves on it. 'C.words' would also split on tabs+    -- and on byte 0xa0, which a key the server echoes can contain: it is+    -- part of many UTF-8 characters, such as U+00E0 (C3 A0).+    splitTokens line =+      filter (not . B.null) (C.split ' ' (fromMaybe line (B.stripSuffix "\r" line)))++-- | Convert a response code and tokens to the corresponding status, or throw+-- for an error reply. @SERVER_ERROR@ and @CLIENT_ERROR@ throw an 'OpError'+-- when their text names a status, such as 'ErrValueTooLarge', and otherwise+-- 'ServerError' and 'BadCommand', with the text as the message. @ERROR@,+-- which memcached sends for a command it doesn't know, throws 'UnknownOp',+-- with the whole line as the message, such as @\"ERROR\"@. The exception is+-- @ERROR Too many open connections@, which memcached sends to a new+-- connection, and then closes it, when it is at its connection limit+-- (@-c@): it throws 'ServerError', with the text after @ERROR@ as the+-- message, so that "Database.Memcache.Internal.Cluster" counts it against+-- the server, as it does a refused connection. Any other code this doesn't+-- know throws 'UnknownStatus'.+responseStatus :: Response -> IO Status+responseStatus (Response code tokens _) = case code of+  "VA"           -> return NoError+  "HD"           -> return NoError+  "EN"           -> return ErrKeyNotFound+  "NF"           -> return ErrKeyNotFound+  "EX"           -> return ErrKeyExists+  "NS"           -> return ErrItemNotStored+  "ST"           -> return NoError+  "STORED"       -> return NoError+  "VERSION"      -> return NoError+  "STAT"         -> return NoError+  "OK"           -> return NoError+  "END"          -> return NoError+  "MN"           -> return NoError+  "SERVER_ERROR" -> serverFailure+  "CLIENT_ERROR" -> clientFailure+  "ERROR"+    | message == connectionLimit -> throwIO $ ProtocolError ServerError { protocolError = message }+    | otherwise -> throwIO $ ProtocolError UnknownOp { protocolError = line }+  _              -> throwIO $ ProtocolError UnknownStatus { protocolError = C.unpack code }+  where+    message = C.unpack $ C.unwords tokens+    line = C.unpack $ C.unwords (code : tokens)++    -- What memcached sends after ERROR at its connection limit. It is+    -- matched exactly, as other servers may send text after ERROR for a+    -- command they don't know.+    connectionLimit = "Too many open connections"++    -- Meta Text reports these as free-form error text where the binary+    -- protocol had dedicated status codes; match them back so callers keep+    -- seeing 'OpError' rather than an opaque protocol failure. memcached+    -- capitalises some of its out-of-memory errors, such as "Out of memory+    -- during read", so that match ignores case.+    serverFailure+      | "object too large" `isInfixOf` message = throwStatus ErrValueTooLarge+      | "out of memory"    `isInfixOf` map toLower message = throwStatus ErrOutOfMemory+      | otherwise = throwIO $ ProtocolError ServerError { protocolError = message }++    clientFailure+      | "non-numeric" `isInfixOf` message = throwStatus ErrValueNonNumeric+      | otherwise = throwIO $ ProtocolError BadCommand { protocolError = message }++-- | Extract the CAS version from a response, or zero when absent or invalid.+responseCas :: Response -> Version+responseCas = tokenNumber "c" . responseTokens++-- | Extract the flags from a response, or zero when absent or invalid.+responseFlags :: Response -> Flags+responseFlags = tokenNumber "f" . responseTokens++-- | Parse the numeric value in a response, or zero when it is absent or invalid.+responseNumber :: Response -> Word64+responseNumber = fromMaybe 0 . readDecimal . responseValue++tokenNumber :: (Integral a, Bounded a) => ByteString -> [ByteString] -> a+tokenNumber prefix xs = fromMaybe 0 $ do+  token <- find (B.isPrefixOf prefix) xs+  readDecimal (B.drop (B.length prefix) token)++-- | Longest response line accepted before assuming the stream is desynchronised.+maxLineLength :: Int+maxLineLength = 8 * 1024++-- | Receive one CRLF-terminated line, without the line-feed byte.+recvLine :: Connection -> IO ByteString+recvLine s = do+  buffer <- readBuffer s+  case B.elemIndex 10 buffer of+    Just i -> writeBuffer s (B.drop (i + 1) buffer) >> return (B.take i buffer)+    Nothing+      | B.length buffer > maxLineLength ->+        throwIO $ ProtocolError BadLength { protocolError = "response line too long" }+      | otherwise -> readChunk 0 s >> recvLine s++-- | Receive exactly the requested number of bytes.+recvExact :: Connection -> Int -> IO ByteString+recvExact s n+  | n < 0 = throwIO $ ProtocolError BadLength { protocolError = "negative length" }+  | otherwise = B.concat <$> go n []+  where+    go 0 acc = return (reverse acc)+    go wanted acc = do+      buffer <- readBuffer s+      let takeN = min wanted (B.length buffer)+      if takeN > 0+        then writeBuffer s (B.drop takeN buffer) >> go (wanted - takeN) (B.take takeN buffer : acc)+        else readChunk wanted s >> go wanted acc++-- | Receive through the first occurrence of a delimiter, including it. Throws+-- 'BadLength' once it has read more than 1 MiB without the delimiter.+recvRawUntil :: ByteString -> Connection -> IO ByteString+recvRawUntil end s = go B.empty+  where+    go acc = do+      buffer <- readBuffer s+      let combined = acc <> buffer+      case B.breakSubstring end combined of+        (before, rest) | not (B.null rest) -> do+          writeBuffer s (B.drop (B.length end) rest)+          return (before <> end)+        _ | B.length combined > maxRawLength ->+            throwIO $ ProtocolError BadLength { protocolError = "response too long" }+          | otherwise -> writeBuffer s B.empty >> readChunk 0 s >> go combined++-- | 'recvRawUntil' gives up once it has read more than this without its+-- delimiter. ElastiCache discovery reads its cluster configuration with it,+-- which lists each node as a host name (at most 253 bytes), an IP address and+-- a port: at most about 300 bytes a node, so this holds over 3,000 nodes.+-- ElastiCache allows 60 nodes in a Memcached cluster unless that quota is+-- raised. A node can take as little as a few bytes, though, so discovery also+-- refuses a configuration that lists more than 1,000 nodes (@maxNodes@ in+-- "Database.Memcache.ElastiCacheClient"): that limit, not this one, bounds+-- the servers it makes.+maxRawLength :: Int+maxRawLength = 1024 * 1024++readChunk :: Int -> Connection -> IO ()+readChunk n (Connection s ref) = do+  chunk <- N.recv s (max 4096 (min maxRecvSize n))+  if B.null chunk then throwIO eofError else modifyIORef' ref (<> chunk)++-- | Largest single receive. 'N.recv' allocates a buffer of the full requested+-- size on every call, so asking for the whole remainder of a large value+-- turns reading it into quadratic allocation.+maxRecvSize :: Int+maxRecvSize = 64 * 1024++readBuffer :: Connection -> IO ByteString+readBuffer (Connection _ ref) = readIORef ref++writeBuffer :: Connection -> ByteString -> IO ()+writeBuffer (Connection _ ref) = writeIORef ref++eofError :: MemcacheError+eofError = ProtocolError UnexpectedEOF { protocolError = "" }++-- | A key encoded for the Meta Text wire protocol.+data WireKey = WireKey+  -- | The bytes sent as the key.+  { wireKey :: !ByteString+  -- | Whether the key uses the protocol's base64 binary-key mode.+  , wireB64 :: !Bool+  } deriving (Eq, Show)++-- | Encode a key, using base64 when it contains protocol-invalid bytes.+encodeKey :: Key -> Either ClientError WireKey+encodeKey key+  | B.null key = Left (InvalidKey "empty key")+  | B.length key > 250 = Left (InvalidKey "key exceeds 250 bytes")+  | B.length wire > 250 = Left (InvalidKey "encoded key exceeds 250 bytes")+  | otherwise = Right (WireKey wire b64)+  where+    b64 = B.any (\c -> c <= 0x20 || c == 0x7f) key+    wire = if b64 then Base64.encode key else key++keyArgs :: WireKey -> ByteString+keyArgs (WireKey wire b64) = wire <> if b64 then " b" else B.empty++keyFlag :: WireKey -> ByteString+keyFlag (WireKey _ b64) = if b64 then " b" else B.empty++-- | Write a request that carries a value or a number into one buffer. The+-- value is copied once (each strict 'ByteString' append copies both sides, so+-- a value at the end of a chain of appends is copied once per piece before+-- it), and numbers are written in place rather than through 'show'. The size+-- is the length of the request's key and value. Values go in with+-- 'byteStringCopy', as 'byteString' would add a large one as a chunk of its+-- own for 'BL.toStrict' to copy again. Inlined so the pieces are written+-- directly instead of first being allocated as closures.+--+-- Requests with neither keep plain appends, which are cheaper for a few short+-- strings than running a 'Builder'.+render :: Int -> Builder -> ByteString+{-# INLINE render #-}+render size = BL.toStrict . toLazyByteStringWith strategy BL.empty+  where strategy = untrimmedStrategy (size + requestHeadroom) smallChunkSize++-- | Room for everything in a request besides its key and value: the command,+-- its meta flags and up to four numbers of at most 20 digits. Room left over+-- stays with the request rather than being trimmed off by another copy. A+-- request that needed more would still be encoded correctly, but copied once+-- more.+requestHeadroom :: Int+requestHeadroom = 128++-- | A piece of a request. Fixed pieces are 'ByteString' literals passed+-- through this rather than 'Builder' literals, which are encoded a character+-- at a time and measured noticeably slower.+bytes :: ByteString -> Builder+bytes = byteString++-- | CRLF used to terminate Meta Text requests.+crlf :: ByteString+crlf = "\r\n"++-- | Meta Text storage operation.+data StoreMode+  -- | Store whether or not the key exists.+  = Set+  -- | Store only when the key does not exist.+  | Add+  -- | Store only when the key exists.+  | Replace+  -- | Add bytes to the end of an existing value.+  | Append+  -- | Add bytes to the beginning of an existing value.+  | Prepend+  deriving (Eq, Show)++-- | Meta Text arithmetic operation.+data ArithMode+  -- | Increment a numeric value.+  = Incr+  -- | Decrement a numeric value.+  | Decr+  deriving (Eq, Show)++storeMode :: StoreMode -> ByteString+storeMode Set = "S"+storeMode Add = "E"+storeMode Replace = "R"+storeMode Append = "A"+storeMode Prepend = "P"++arithMode :: ArithMode -> ByteString+arithMode Incr = "I"+arithMode Decr = "D"++cmdMetaGet, cmdMetaSet, cmdMetaDelete, cmdMetaArith, cmdMetaNoOp :: ByteString+cmdMetaGet = "mg"+cmdMetaSet = "ms"+cmdMetaDelete = "md"+cmdMetaArith = "ma"+cmdMetaNoOp = "mn"++cmdFlush, cmdVersion, cmdQuit, cmdStats, cmdSet :: ByteString+cmdFlush = "flush_all"+cmdVersion = "version"+cmdQuit = "quit"+cmdStats = "stats"+cmdSet = "set"++cas :: Maybe Version -> Builder+cas = maybe mempty (\n -> bytes " C" <> word64Dec n)++-- | Encode a get request for one key.+getRequest :: WireKey -> ByteString+getRequest key = cmdMetaGet <> " " <> keyArgs key <> " v f c" <> crlf++-- | Encode a get request for a pipelined batch. It is 'getRequest' plus the+-- @q@ flag, so a miss gets no reply, and the given opaque as the @O@ flag,+-- which memcached copies into the reply so that it can be matched to its+-- request.+getManyRequest :: WireKey -> Int -> ByteString+getManyRequest key opaque = render (B.length (wireKey key)) $+  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " v f c q O" <> intDec opaque+  <> bytes crlf++-- | Encode a get-and-touch request.+gatRequest :: WireKey -> Expiration -> ByteString+gatRequest key expiry = render (B.length (wireKey key)) $+  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " v f c T" <> word32Dec expiry+  <> bytes crlf++-- | Encode a touch request.+touchRequest :: WireKey -> Expiration -> ByteString+touchRequest key expiry = render (B.length (wireKey key)) $+  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " T" <> word32Dec expiry+  <> bytes " c" <> bytes crlf++-- | Encode a storage request.+--+-- Send this only to memcached 1.6.10 or later. Older servers reject it without+-- reading the value, and then run the value's bytes as commands. Connections+-- that "Database.Memcache.Internal.Server" makes check the server's version,+-- but a connection made with 'newConnection' directly does not.+--+-- Nor send it with a value longer than 1 GiB, more than any memcached server+-- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs+-- the value's bytes as commands. The operations in "Database.Memcache.Client"+-- check the length before sending anything, but this encodes a value of any+-- length.+storeRequest :: StoreMode -> WireKey -> Value -> Flags -> Expiration -> Maybe Version -> ByteString+storeRequest mode key value flags expiry version = render (B.length (wireKey key) + B.length value) $+  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)+  <> bytes " F" <> word32Dec flags <> bytes " T" <> word32Dec expiry <> cas version+  <> bytes " M" <> bytes (storeMode mode) <> bytes (keyFlag key) <> bytes " c"+  <> bytes crlf <> byteStringCopy value <> bytes crlf++-- | Encode a set request for a pipelined batch. It is 'storeRequest' in 'Set'+-- mode without a CAS, plus the given opaque as the @O@ flag, which memcached+-- copies into the reply so that it can be matched to its request.+--+-- Send this only to memcached 1.6.10 or later. Older servers reject it without+-- reading the value, and then run the value's bytes as commands. Connections+-- that "Database.Memcache.Internal.Server" makes check the server's version,+-- but a connection made with 'newConnection' directly does not.+--+-- Nor send it with a value longer than 1 GiB, more than any memcached server+-- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs+-- the value's bytes as commands. The operations in "Database.Memcache.Client"+-- check the length before sending anything, but this encodes a value of any+-- length.+setManyRequest :: WireKey -> Value -> Flags -> Expiration -> Int -> ByteString+setManyRequest key value flags expiry opaque = render (B.length (wireKey key) + B.length value) $+  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)+  <> bytes " F" <> word32Dec flags <> bytes " T" <> word32Dec expiry+  <> bytes " M" <> bytes (storeMode Set) <> bytes (keyFlag key) <> bytes " c O" <> intDec opaque+  <> bytes crlf <> byteStringCopy value <> bytes crlf++-- | Encode an increment or decrement request. Given an initial value and an+-- expiration, the request asks the server to create a missing key with them.+arithmeticRequest :: ArithMode -> WireKey -> Delta -> Maybe (Initial, Expiration) -> Maybe Version -> ByteString+arithmeticRequest mode key delta create version = render (B.length (wireKey key)) $+  bytes cmdMetaArith <> bytes " " <> bytes (keyArgs key) <> bytes " D" <> word64Dec delta+  <> cas version <> bytes " M" <> bytes (arithMode mode) <> bytes " v c"+  <> (case create of+        Nothing -> mempty+        Just (initial, expiry) -> bytes " N" <> word32Dec expiry <> bytes " J" <> word64Dec initial)+  <> bytes crlf++-- | Encode an append or prepend request.+--+-- Send this only to memcached 1.6.10 or later. Older servers reject it without+-- reading the value, and then run the value's bytes as commands. Connections+-- that "Database.Memcache.Internal.Server" makes check the server's version,+-- but a connection made with 'newConnection' directly does not.+--+-- Nor send it with a value longer than 1 GiB, more than any memcached server+-- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs+-- the value's bytes as commands. The operations in "Database.Memcache.Client"+-- check the length before sending anything, but this encodes a value of any+-- length.+modifyRequest :: StoreMode -> WireKey -> Value -> Maybe Version -> ByteString+modifyRequest mode key value version = render (B.length (wireKey key) + B.length value) $+  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)+  <> bytes " M" <> bytes (storeMode mode) <> bytes (keyFlag key) <> cas version <> bytes " c"+  <> bytes crlf <> byteStringCopy value <> bytes crlf++-- | Encode a delete request.+deleteRequest :: WireKey -> Maybe Version -> ByteString+deleteRequest key Nothing = cmdMetaDelete <> " " <> keyArgs key <> crlf+deleteRequest key version = render (B.length (wireKey key)) $+  bytes cmdMetaDelete <> bytes " " <> bytes (keyArgs key) <> cas version <> bytes crlf++-- | Encode a delete request for a pipelined batch. It is 'deleteRequest'+-- without a CAS, plus the given opaque as the @O@ flag, which memcached copies+-- into the reply so that it can be matched to its request.+deleteManyRequest :: WireKey -> Int -> ByteString+deleteManyRequest key opaque = render (B.length (wireKey key)) $+  bytes cmdMetaDelete <> bytes " " <> bytes (keyArgs key) <> bytes " O" <> intDec opaque <> bytes crlf++-- | Encode a flush request, optionally delayed until the given expiration.+flushRequest :: Maybe Expiration -> ByteString+flushRequest Nothing = cmdFlush <> crlf+flushRequest (Just expiry) = render 0 $ bytes cmdFlush <> bytes " " <> word32Dec expiry <> bytes crlf++-- | Encode a version request.+versionRequest, quitRequest :: ByteString+versionRequest = cmdVersion <> crlf+quitRequest = cmdQuit <> crlf++-- | Encode a stats request, optionally scoped to a key.+statsRequest :: Maybe Key -> ByteString+statsRequest Nothing = cmdStats <> crlf+statsRequest (Just key) = cmdStats <> " " <> key <> crlf++-- | Encode the text auth-file request, authenticating using the value as its+-- space-separated credentials.+authRequest :: Value -> ByteString+authRequest value = render (B.length value) $+  bytes cmdSet <> bytes " auth 0 0 " <> intDec (B.length value)+  <> bytes crlf <> byteStringCopy value <> bytes crlf++-- | Encode a Meta Text no-op request.+noOpRequest :: ByteString+noOpRequest = cmdMetaNoOp <> crlf
− Database/Memcache/Ketama.hs
@@ -1,185 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{-|-Module      : Database.Memcache.Ketama-Description : libmemcached-compatible consistent hashing-Copyright   : (c) David Terei, 2026-License     : BSD-Maintainer  : code@davidterei.com-Stability   : stable-Portability : GHC--Ketama consistent hashing, computed exactly as libmemcached does for-@MEMCACHED_BEHAVIOR_KETAMA_WEIGHTED@. The cluster uses this to choose the-server for each key. It is exposed for working out which server a key belongs-to, and for building rings with weights, which the cluster does not use.--A ring has 160 points per server on a 32-bit circle, shared out in proportion-to the servers' weights. The points of a server named @n@ come from the MD5-digests of @n-0@, @n-1@, and so on, each digest giving four little-endian-32-bit points. A key hashes to the first four bytes of its MD5 digest, read-little-endian, and belongs to the server owning the first point at or after-that hash, wrapping round to the lowest point.--With equal weights, adding or removing a server only moves the keys on that-server's points, unless it changes the number of points each server gets-(from 24 servers to 25, say). With unequal weights, it changes the other-servers' numbers of points too, so some of their keys move between them.--The details follow libmemcached so that both choose the same server:--* The number of points is computed in single precision, which gives 156-  rather than 160 points per server for some numbers of equally weighted-  servers, such as 25.--* Points with the same value are ordered by server position, so the earlier-  server in the list wins the tie, as in libmemcached 1.1 and later.--* A server's name is its host alone on port 11211 and @host:port@ on any other-  port (see 'serverName').--}-module Database.Memcache.Ketama (-        -- * Rings-        Ring, ring, serverName,--        -- * Lookup-        keyHash, owner, owners,--        -- * Inspection-        ringPoints-    ) where--import           Control.Monad.ST            (runST)-import qualified Crypto.Hash.MD5             as MD5-import           Data.Bits                   (shiftL, (.|.))-import           Data.ByteString             (ByteString)-import qualified Data.ByteString             as B-import qualified Data.ByteString.Char8       as C-import           Data.List                   (sort)-import qualified Data.Vector.Unboxed         as VU-import qualified Data.Vector.Unboxed.Mutable as VUM-import           Data.Word                   (Word32)---- | A ketama ring (libmemcached calls it the continuum) over a list of--- servers. Servers are identified by their position in the list the ring was--- built from, starting at 0.-data Ring = Ring {-        -- | Point values, in ascending order.-        rValues  :: !(VU.Vector Word32),-        -- | The position of the server owning each point.-        rOwners  :: !(VU.Vector Int),-        -- | How many servers the ring was built from.-        rSize    :: !Int,-        -- | How many servers have at least one point.-        rServers :: !Int-    }---- | Build a ring from each server's name (see 'serverName') and weight, in--- the order that decides ties. Weights below 1 count as 1, as libmemcached--- treats a weight of 0. Give every server the same weight to match clients--- that are not configured with weights.-ring :: [(ByteString, Int)] -> Ring-ring servers = Ring values owners' (length servers) (length (filter (> 0) counts))-  where-    weights = map (max 1 . snd) servers-    total = sum weights-    counts = [pointsPerServer w total (length servers) | w <- weights]-    (values, owners') = VU.unzip $ VU.fromList $ sort-        [ (point, index)-        | (index, (name, _), count) <- zip3 [0 ..] servers counts-        , i <- [0 .. count `quot` 4 - 1]-        , point <- digestPoints (name <> "-" <> C.pack (show (i :: Int)))-        ]---- | The name libmemcached derives a server's points from, given its host and--- port as written in its configuration: the host alone for the default port--- 11211, otherwise @host:port@. Hosts are not resolved, so @localhost@ and--- @127.0.0.1@ are different servers on the ring.-serverName :: ByteString -> ByteString -> ByteString-serverName host port-    | port == "11211" = host-    | otherwise       = host <> ":" <> port---- | The number of points a server gets: libmemcached's--- @floor(weight / total * 160 / 4 * servers + 1e-10) * 4@, evaluated left to--- right in single precision as the C code does.-pointsPerServer :: Int -> Int -> Int -> Int-pointsPerServer weight total servers =-    4 * floor (share * 160 / 4 * fromIntegral servers + 1.0e-10 :: Float)-  where-    share = fromIntegral weight / fromIntegral total :: Float---- | The four points of a name: its MD5 digest read as four little-endian--- 32-bit words.-digestPoints :: ByteString -> [Word32]-digestPoints name = [littleEndian digest offset | offset <- [0, 4, 8, 12]]-  where-    digest = MD5.hash name---- | The position of a key on the ring: the first four bytes of the MD5 digest--- of the key, read little-endian. This is libmemcached's MD5 key hash; it is--- taken over the key as given, not its base64 form on the wire.-keyHash :: ByteString -> Word32-keyHash key = littleEndian (MD5.hash key) 0--littleEndian :: ByteString -> Int -> Word32-littleEndian bytes offset =-    byte 0 .|. byte 1 `shiftL` 8 .|. byte 2 `shiftL` 16 .|. byte 3 `shiftL` 24-  where-    byte i = fromIntegral (B.index bytes (offset + i))---- | The server owning a hash: the owner of the first point at or after it,--- wrapping round to the lowest point. 'Nothing' only for a ring with no--- servers.-owner :: Ring -> Word32 -> Maybe Int-owner r hash-    | VU.null (rOwners r) = Nothing-    | otherwise           = Just (VU.unsafeIndex (rOwners r) (firstPoint r hash))---- | Every server on the ring, in the order a key with this hash falls back to--- them: the 'owner' first, then each other server in the order its first point--- comes walking forward round the ring from the hash. Keeping the ring and--- skipping servers that are down this way leaves every other key where it was.--- Taking only the head costs no more than 'owner'; the rest of the list takes--- one walk round the ring, which stops once every server has been found.-owners :: Ring -> Word32 -> [Int]-owners r hash-    | n == 0    = []-    | otherwise = first : others-  where-    points = rOwners r-    n = VU.length points-    start = firstPoint r hash-    first = VU.unsafeIndex points start-    others = runST $ do-        seen <- VUM.replicate (rSize r) False-        VUM.unsafeWrite seen first True-        let walk i found acc-                | found == rServers r || i == start + n = return (reverse acc)-                | otherwise = do-                    let server = VU.unsafeIndex points (if i < n then i else i - n)-                    known <- VUM.unsafeRead seen server-                    if known-                        then walk (i + 1) found acc-                        else do-                            VUM.unsafeWrite seen server True-                            walk (i + 1) (found + 1) (server : acc)-        walk (start + 1) (1 :: Int) []---- | The index of the first point at or after the hash, or 0 if there is none.-firstPoint :: Ring -> Word32 -> Int-firstPoint r hash = if found == VU.length values then 0 else found-  where-    values = rValues r-    found = search 0 (VU.length values)-    search lo hi-        | lo >= hi = lo-        | VU.unsafeIndex values mid < hash = search (mid + 1) hi-        | otherwise = search lo mid-      where-        mid = (lo + hi) `quot` 2---- | Every point on the ring in ascending order, with the position of the--- server that owns it.-ringPoints :: Ring -> [(Word32, Int)]-ringPoints r = VU.toList (VU.zip (rValues r) (rOwners r))
− Database/Memcache/Server.hs
@@ -1,341 +0,0 @@-{-# LANGUAGE RecordWildCards   #-}-{-# LANGUAGE CPP               #-}-{-# LANGUAGE OverloadedStrings #-}--{-|-Module      : Database.Memcache.Server-Description : Server Handling-Copyright   : (c) David Terei, 2016-License     : BSD-Maintainer  : code@davidterei.com-Stability   : stable-Portability : GHC--Handles the connections between a Memcached client and a single server.--Each new connection is authenticated, when its 'ServerSpec' has credentials,-and then asks the server for its version before it is used. Unless the server-reports memcached 1.6.10 or later, the connection is closed, having sent-nothing but the authentication exchange, when there are credentials, and-@version@, and v'ProtocolError' 'UnknownOp' is thrown (or, for an error reply,-what that reply throws for any request).--Memcached expected errors (part of the protocol) are returned in the Response;-unexpected errors, such as network failures, are thrown as exceptions. The-server's 'failed' timestamp is used by cluster retry handling.--}-module Database.Memcache.Server (-      -- * Server-        Server(sid, failed), serverHost, serverPort, newServerDefault,-        withSocket, close, closeAll,--      -- * ServerOptions-        ServerOptions(..), defaultServerOptions-    ) where--import           Database.Memcache.Auth-import           Database.Memcache.Errors-import           Database.Memcache.Socket-import           Database.Memcache.Types.Server--import           Control.Monad            (void, when)-import qualified Data.ByteString.Char8    as C-import           Data.Char                (isDigit)-import           Data.Default-import           Data.Hashable-import           Data.IORef-import qualified Data.Pool as P-import           Data.Pool (Pool)-import           Database.Memcache.Types  (ServerSpec (..))-import           UnliftIO.Exception--import           Network.Socket           (HostName, ServiceName, getAddrInfo)-import qualified Network.Socket           as S-#if MIN_VERSION_resource_pool(0,4,0)-#else-import           Data.Time.Clock          (NominalDiffTime)-#endif---- | The host the server was configured with, as given in its 'ServerSpec'.-serverHost :: Server -> HostName-serverHost = addr---- | The port or service name the server was configured with, as given in its--- 'ServerSpec'.-serverPort :: Server -> ServiceName-serverPort = port---- | Configurable options when creating a @Server@.------ At the moment, this only applies to the @Pool@ information. This can be expanded in the future.------ The package's bounds allow resource-pool 0.2, and 0.4 or later, but not--- 0.3. With 0.3, a pool has a stripe for each capability, whatever--- 'soNumStripes' is, and each stripe holds a share of the connections. A--- thread takes connections only from its own capability's stripe, so a--- request could wait for one while other stripes had room, and an operation--- that holds a connection and asks for another could wait, until it ran out--- of time, for the one it holds itself.----data ServerOptions-  = ServerOptions-  -- | Maximum number of pooled connections per stripe. With resource-pool 0.4-  -- or later, it is split between the stripes instead, and must be at least-  -- 'soNumStripes', or creating the server (and so a client) throws an-  -- @ErrorCall@. Each stripe then holds up to 'soNumResources' divided by-  -- 'soNumStripes', rounded up with 0.4, and rounded down or up with 0.5 so-  -- that the total is 'soNumResources'.-  { soNumResources :: Int-  -- | Number of pool stripes. With resource-pool 0.4 and 0.5.0.0, stripes-  -- beyond the number of capabilities are never used.-  , soNumStripes :: Int-#if MIN_VERSION_resource_pool(0,4,0)-  -- | Connection keep-alive duration.-  , soKeepAlive :: Double-#else-  -- | Connection keep-alive duration.-  , soKeepAlive :: NominalDiffTime-#endif-  }---- | The default server options:------ * 'soNumResources': 1--- * 'soNumStripes': 1--- * 'soKeepAlive': 300 seconds------ That is, at most one connection to each server, closed once it has been--- idle for 300 seconds.-defaultServerOptions :: ServerOptions-defaultServerOptions = ServerOptions-      { soNumResources = 1-      , soNumStripes = 1-      , soKeepAlive = 300-      }---- | 'def' is 'defaultServerOptions'.-instance Default ServerOptions where-  def = defaultServerOptions---- | Create a server using the default socket-pool implementation.-newServerDefault :: ServerOptions -> ServerSpec -> IO Server-newServerDefault serverOptions ServerSpec{..} = do-    fat <- newIORef 0-    gen <- newIORef 0-    pSock <- getNewPool serverOptions-    return Server-        { sid      = serverHash-        , pool     = pSock-        , addr     = ssHost-        , port     = ssPort-        , auth     = ssAuth-        , failed   = fat-        , generation = gen-        , slotTaken = Nothing-        }-  where-    serverHash = hash (ssHost, ssPort)----- | Run a function with access to a pooled server connection. Afterwards the--- connection goes back to the pool, unless the function threw or 'closeAll'--- has run since the connection was opened, in which case it is closed. The--- function is never given a connection opened before the latest 'closeAll'.-withSocket :: Server -> (Connection -> IO a) -> IO a-{-# INLINE withSocket #-}-withSocket svr act = mask $ \restore -> do-    (slot, local) <- P.takeResource (pool svr)-    -- Record that the request has stopped waiting (see 'slotTaken').-    mapM_ (`writeIORef` True) (slotTaken svr)-    (born, conn) <- connectionIn slot `onException` P.destroyResource (pool svr) local slot-    r <- restore (act conn) `onException` P.destroyResource (pool svr) local slot-    stale <- (/= born) <$> currentGeneration svr-    if stale-      then P.destroyResource (pool svr) local slot-      else do-        P.putResource local slot-        -- 'closeAll' may have run between the check and the put, and closed-        -- the idle connections before this one was back. If so, close them-        -- again, without letting an exception cut that short.-        raced <- (/= born) <$> currentGeneration svr-        when raced $ uninterruptibleMask_ $ P.destroyAllResources (pool svr)-    return r-  where-    -- The slot's connection, opening one if the slot has none or closing and-    -- replacing one opened before the latest 'closeAll'. 'closeAll' may run-    -- while a connection is being opened, so check the new one too.-    connectionIn slot = do-      held <- readIORef slot-      current <- currentGeneration svr-      case held of-        Just res@(born, _) | born == current -> return res-        _ -> do-          releaseSlot slot-          writeIORef slot Nothing-          res <- connectTagged (generation svr) (ServerSpec (addr svr) (port svr) (auth svr))-          writeIORef slot (Just res)-          connectionIn slot---- | Close the connections that are idle in the pool. Connections in use stay--- open and go back to the pool when their request finishes; 'closeAll' closes--- those too. A later request re-establishes connections as needed. An--- asynchronous exception can't cut 'close' short: it is delivered once every--- idle connection is closed.-close :: Server -> IO ()-{-# INLINE close #-}-close srv = uninterruptibleMask_ $ P.destroyAllResources $ pool srv---- | Close every connection to the server: idle connections now, and each--- connection in use as soon as the request using it finishes, instead of--- returning it to the pool. It doesn't wait for those requests or interrupt--- them, and it never connects or throws. Requests that start later never use--- a connection opened before 'closeAll'; they open new ones. Like 'close', it--- can't be cut short by an asynchronous exception.-closeAll :: Server -> IO ()-closeAll srv = uninterruptibleMask_ $ do-    atomicModifyIORef' (generation srv) (\g -> (g + 1, ()))-    P.destroyAllResources (pool srv)---- | Read the generation. The read is atomic for simplicity; what makes the--- checks in 'withSocket' sound is that it and 'closeAll' both go through the--- pool's per-stripe lock, which orders the bump against a returned connection.-currentGeneration :: Server -> IO Int-currentGeneration svr = atomicModifyIORef' (generation svr) (\g -> (g, g))---- Slots start empty: 'withSocket' opens a connection in a slot once it holds--- the slot, so that connecting isn't part of waiting for one.-#if MIN_VERSION_resource_pool(0,4,0)-getNewPool :: ServerOptions -> IO (Pool Slot)-getNewPool serverOptions =-  P.newPool-    $ P.setNumStripes (Just $ soNumStripes serverOptions)-    $ P.defaultPoolConfig (newIORef Nothing) releaseSlot (soKeepAlive serverOptions) (soNumResources serverOptions)-#else-getNewPool :: ServerOptions -> IO (Pool Slot)-getNewPool serverOptions =-  P.createPool (newIORef Nothing) releaseSlot (soNumStripes serverOptions) (soKeepAlive serverOptions) (soNumResources serverOptions)-#endif---- | Close the slot's connection, if it has one.-releaseSlot :: Slot -> IO ()-releaseSlot slot = readIORef slot >>= mapM_ (releaseSocket . snd)---- | Open a connection, paired with the generation current when it was opened.-connectTagged :: IORef Int -> ServerSpec -> IO (Int, Connection)-connectTagged gen ss = do-    born <- atomicModifyIORef' gen (\g -> (g, g))-    conn <- connectSocket ss-    return (born, conn)--connectSocket :: ServerSpec -> IO Connection-connectSocket ServerSpec{..} = do-    let hints = S.defaultHints {-      S.addrSocketType = S.Stream-    }-    -- A path is a Unix socket: there is nothing to look up, so it is the-    -- only address to try.-    addr:addrs <- case ssHost of-        '/' : _ -> return [S.defaultHints {-            S.addrFamily = S.AF_UNIX,-            S.addrSocketType = S.Stream,-            S.addrAddress = S.SockAddrUnix ssHost-          }]-        _ -> getAddrInfo (Just hints) (Just ssHost) (Just ssPort)-    bracketOnError-        (connectFirst addr addrs)-        S.close-        (\s -> do-            -- A Unix socket rejects NoDelay, and has no TCP connection to-            -- keep alive.-            when (S.addrFamily addr /= S.AF_UNIX) $ do-                S.setSocketOption s S.KeepAlive 1-                S.setSocketOption s S.NoDelay 1-            buffered <- newConnection s-            authenticate buffered ssAuth-            checkVersion buffered-            return buffered-        )---- | The oldest memcached this client works with. From 1.6.10, the meta set--- command that every store sends takes the data length as the token after--- the key. Older servers reject the command without reading the data that--- follows it, and then run the stored value's bytes as commands.-minimumVersion :: (Integer, Integer, Integer)-minimumVersion = (1, 6, 10)---- | Ask the server for its version, and throw unless it is at least--- @minimumVersion@. Every new connection does this, after authenticating when--- there are credentials, before it is used for anything else, whichever of--- the host's addresses it connected to, or through a Unix socket;--- @connectSocket@ closes the connection when this throws.------ An error reply, such as @CLIENT_ERROR unauthenticated@ from a server in--- auth-file mode when no credentials are set, throws what it throws as the--- reply to any request. So the @ERROR Too many open connections@ that--- memcached sends to a new connection, and then closes it, when it is at its--- connection limit throws 'ServerError', a server failure: the operation is--- retried, and the server is marked as failed if every attempt gets it. With--- credentials, 'authenticate' reads that line first, and throws the same.--- Any other reply that isn't @VERSION@ and a version of at least--- @minimumVersion@ throws v'ProtocolError' 'UnknownOp', quoting the reply and--- naming the minimum. Retries treat that as a client fault, like a rejected--- command: the server's version won't change on a retry, so the operation--- fails at once and the server isn't marked as failed.-checkVersion :: Connection -> IO ()-checkVersion connection = do-    sendRaw connection versionRequest-    response <- recvResponse connection-    when (responseCode response `elem` ["ERROR", "CLIENT_ERROR", "SERVER_ERROR"]) $-        void (responseStatus response)-    case responseVersion response of-        Just v | v >= minimumVersion -> return ()-        _ -> throwIO $ ProtocolError UnknownOp-            { protocolError = "memcached " <> showVersion minimumVersion-                <> " or later is required, but the server answered version with "-                <> show (C.unwords (responseCode response : responseTokens response))-            }-  where-    showVersion (major, minor, patch) =-        show major <> "." <> show minor <> "." <> show patch---- | The version in a @VERSION@ reply, as its first three numbers: major,--- minor and patch, separated by dots. Anything after the third number, such--- as a @-rc1@ suffix or a word after the version, is ignored.-responseVersion :: Response -> Maybe (Integer, Integer, Integer)-responseVersion (Response "VERSION" (token:_) _) = do-    (major, afterMajor) <- number token-    (minor, afterMinor) <- number =<< C.stripPrefix "." afterMajor-    (patch, _)          <- number =<< C.stripPrefix "." afterMinor-    return (major, minor, patch)-  where-    number bytes = case C.span isDigit bytes of-        (digits, remainder) | not (C.null digits) -> Just (read (C.unpack digits), remainder)-        _ -> Nothing-responseVersion _ = Nothing---- | Connect a socket to the first of the resolved addresses that accepts,--- trying them in order, so a host whose first address refuses the connection--- (such as ::1 when the server listens on 127.0.0.1 only) can still be reached--- through the others. If none accepts, rethrows the first address's error:--- the resolver sorts addresses this host cannot use, such as IPv6 where it is--- disabled, last, so the later errors are often just about those.------ Only an 'IOException' from creating or connecting a socket moves on to the--- next address, so the attempt's timeout ends the loop. Errors once--- connected, such as rejected credentials, are raised after this returns:--- they come from the server, and trying another address would hide them.-connectFirst :: S.AddrInfo -> [S.AddrInfo] -> IO S.Socket-connectFirst addr addrs = do-    result <- tryIO $ connectTo addr-    case result of-        Right s  -> return s-        Left err -> foldr orElse (throwIO err) addrs-  where-    orElse next rest = tryIO (connectTo next) >>= either (const rest) return-    connectTo a = bracketOnError-        (S.socket (S.addrFamily a) (S.addrSocketType a) (S.addrProtocol a))-        S.close-        (\s -> S.connect s (S.addrAddress a) >> return s)--releaseSocket :: Connection -> IO ()-releaseSocket = closeConnection
− Database/Memcache/Socket.hs
@@ -1,579 +0,0 @@-{-# LANGUAGE CApiFFI           #-}-{-# LANGUAGE CPP               #-}-{-# LANGUAGE OverloadedStrings #-}--{-|-Module      : Database.Memcache.Socket-Description : Meta Text protocol socket handling-Copyright   : (c) David Terei, 2016-License     : BSD-Maintainer  : code@davidterei.com-Stability   : stable-Portability : GHC--Low-level connections, replies, and request encoders for Memcached's Meta Text-protocol. Authentication uses the text auth-file command.--}-module Database.Memcache.Socket (-        -- * Types-        ArithMode(..), Connection, Response(..), StoreMode(..), WireKey(..),-        crlf,--        -- * Operations-        newConnection, closeConnection, checkIdle,-        sendRaw,-        recvExact, recvLine, recvRawUntil, recvResponse,--        -- * Response readers-        responseStatus, responseCas, responseFlags, responseNumber,--        -- * Constructors-        encodeKey, getRequest, getManyRequest, gatRequest, touchRequest,-        storeRequest, setManyRequest, arithmeticRequest, deleteRequest,-        deleteManyRequest, flushRequest, versionRequest, modifyRequest,-        statsRequest, quitRequest, authRequest, noOpRequest-    ) where--import           Database.Memcache.Errors-import           Database.Memcache.Types-import           Database.Memcache.Util    (maxValueLength, readDecimal)--import           Control.Monad             (unless)-import           Data.ByteString           (ByteString)-import qualified Data.ByteString           as B-import qualified Data.ByteString.Base64    as Base64-import           Data.ByteString.Builder   (Builder, byteString, intDec, word32Dec, word64Dec)-import           Data.ByteString.Builder.Extra (byteStringCopy, smallChunkSize, toLazyByteStringWith,-                                                untrimmedStrategy)-import qualified Data.ByteString.Char8     as C-import qualified Data.ByteString.Lazy      as BL-import           Data.Char                 (toLower)-import           Data.IORef-import           Data.List                 (find, isInfixOf)-import           Data.Maybe                (fromMaybe)-import           Data.Word                 (Word64)-import qualified Network.Socket            as N-import qualified Network.Socket.ByteString as N-import           UnliftIO.Exception        (throwIO)-#if !defined(mingw32_HOST_OS)-import           Data.Bits                 ((.|.))-import           Foreign.C.Error           (eAGAIN, eINTR, eWOULDBLOCK, errnoToIOError, getErrno)-import           Foreign.C.Types           (CChar, CInt (..), CSize (..))-import           Foreign.Marshal.Alloc     (allocaBytes)-import           Foreign.Ptr               (Ptr)-import           System.Posix.Types        (CSsize (..))-#endif---- | A connected Memcached socket and its receive buffer.-data Connection = Connection N.Socket (IORef ByteString)---- | A decoded Meta Text response.-data Response = Response-  -- | The response code, such as @VA@ or @HD@.-  { responseCode :: ByteString-  -- | Tokens following the response code. As in memcached, only spaces-  -- separate tokens, so a token can contain other whitespace bytes, such as-  -- a tab or 0xa0.-  , responseTokens :: [ByteString]-  -- | The response value, when the response contains one.-  , responseValue :: ByteString-  } deriving (Eq, Show)---- | Create a connection wrapper around a socket.------ This doesn't check the server's version. Connections that--- "Database.Memcache.Server" makes are checked, and refuse a server older than--- memcached 1.6.10; a connection made here directly is not, so check the--- server's version before sending it 'storeRequest', 'setManyRequest' or--- 'modifyRequest'.-newConnection :: N.Socket -> IO Connection-newConnection s = Connection s <$> newIORef B.empty---- | Close the underlying socket.-closeConnection :: Connection -> IO ()-closeConnection (Connection s _) = N.close s---- | Check, without waiting, that the connection is as a finished exchange--- leaves it: everything the server sent has been read, and the server hasn't--- closed the connection. Throws as reading from it would, if the server has--- closed it ('UnexpectedEOF') or reset it (an--- t'Control.Exception.IOException'), and throws 'UnexpectedResponse' if bytes--- are waiting to be read, which would be taken as the reply to the next--- request.------ Use it on a connection taken from a pool before sending a request that--- mustn't be sent twice. memcached closes idle connections when it restarts--- or after @-o idle_timeout@, and a request sent on one of those never--- reaches it but fails as if it might have, with 'UnexpectedEOF'. It costs a--- system call, and it can't see a connection that the network dropped--- without telling either end, or one the server closes after the check.--- On Windows it only checks the bytes already read from the socket.-checkIdle :: Connection -> IO ()-checkIdle (Connection s ref) = do-  buffered <- readIORef ref-  waiting <- if B.null buffered then peekSocket s else return (Just (B.length buffered))-  case waiting of-    Nothing -> return ()-    Just 0 -> throwIO eofError-    Just _ -> throwIO $ ProtocolError UnexpectedResponse-      { protocolError = "Expected no data on an idle connection" }---- | Look, without waiting or taking anything, at what the socket has received:--- 'Nothing' if nothing, @Just 0@ if the peer has closed the connection, and--- otherwise how many bytes are waiting (here at most 1). Throws the error of a--- connection that was reset.-peekSocket :: N.Socket -> IO (Maybe Int)-#if defined(mingw32_HOST_OS)--- Windows has no MSG_DONTWAIT, so there is no look that can't wait.-peekSocket _ = return Nothing-#else-peekSocket s = N.withFdSocket s $ \fd -> allocaBytes 1 $ \buffer -> peekInto fd buffer-  where-    peekInto fd buffer = do-      n <- c_recv fd buffer 1 (msgPeek .|. msgDontWait)-      if n >= 0 then return (Just (fromIntegral n)) else getErrno >>= failed fd buffer-    failed fd buffer errno-      | errno == eINTR = peekInto fd buffer-      | errno == eAGAIN || errno == eWOULDBLOCK = return Nothing-      | otherwise = throwIO (errnoToIOError "recv" errno Nothing Nothing)--foreign import ccall unsafe "recv"-  c_recv :: CInt -> Ptr CChar -> CSize -> CInt -> IO CSsize--foreign import capi "sys/socket.h value MSG_PEEK" msgPeek :: CInt--foreign import capi "sys/socket.h value MSG_DONTWAIT" msgDontWait :: CInt-#endif---- | Send raw bytes on the underlying socket.-sendRaw :: Connection -> ByteString -> IO ()-sendRaw (Connection s _) = N.sendAll s---- | Receive and decode one Meta Text response.------ A @VA@ reply's value is read if it is at most 1 GiB long, the longest value--- the operations in "Database.Memcache.Client" send; no memcached server can--- store a value that long. A reply that claims a longer value throws--- 'BadLength' before any of the value is read, as does one whose length is--- missing or malformed.-recvResponse :: Connection -> IO Response-recvResponse s = do-  line <- recvLine s-  case splitTokens line of-    [] -> throwIO $ ProtocolError UnknownPkt { protocolError = "" }-    code:tokens -> case tokens of-      n:_ | code == "VA" -> do-        value <- recvExact s =<< parseLength n-        trailer <- recvLine s-        unless (trailer == "\r") $ throwIO $ ProtocolError BadLength-          { protocolError = "value is not followed by an empty line" }-        return $ Response code tokens value-      [] | code == "VA" -> throwIO $ ProtocolError BadLength { protocolError = "invalid value length" }-      _ -> return $ Response code tokens B.empty-  where-    -- 'recvExact' reads the value as it arrives, at most 64 KiB at a time, so-    -- the memory it holds grows with the bytes that arrive, not with the-    -- length claimed.-    parseLength x = case readDecimal x of-      Just n | n <= maxValueLength -> return n-      _ -> throwIO $ ProtocolError BadLength { protocolError = "invalid value length" }--    -- Split the line as memcached does: on spaces alone, after removing the-    -- CR that 'recvLine' leaves on it. 'C.words' would also split on tabs-    -- and on byte 0xa0, which a key the server echoes can contain: it is-    -- part of many UTF-8 characters, such as U+00E0 (C3 A0).-    splitTokens line =-      filter (not . B.null) (C.split ' ' (fromMaybe line (B.stripSuffix "\r" line)))---- | Convert a response code and tokens to the corresponding status, or throw--- for an error reply. @SERVER_ERROR@ and @CLIENT_ERROR@ throw an 'OpError'--- when their text names a status, such as 'ErrValueTooLarge', and otherwise--- 'ServerError' and 'BadCommand', with the text as the message. @ERROR@,--- which memcached sends for a command it doesn't know, throws 'UnknownOp',--- with the whole line as the message, such as @\"ERROR\"@. The exception is--- @ERROR Too many open connections@, which memcached sends to a new--- connection, and then closes it, when it is at its connection limit--- (@-c@): it throws 'ServerError', with the text after @ERROR@ as the--- message, so that "Database.Memcache.Cluster" counts it against the server,--- as it does a refused connection. Any other code this doesn't know throws--- 'UnknownStatus'.-responseStatus :: Response -> IO Status-responseStatus (Response code tokens _) = case code of-  "VA"           -> return NoError-  "HD"           -> return NoError-  "EN"           -> return ErrKeyNotFound-  "NF"           -> return ErrKeyNotFound-  "EX"           -> return ErrKeyExists-  "NS"           -> return ErrItemNotStored-  "ST"           -> return NoError-  "STORED"       -> return NoError-  "VERSION"      -> return NoError-  "STAT"         -> return NoError-  "OK"           -> return NoError-  "END"          -> return NoError-  "MN"           -> return NoError-  "SERVER_ERROR" -> serverFailure-  "CLIENT_ERROR" -> clientFailure-  "ERROR"-    | message == connectionLimit -> throwIO $ ProtocolError ServerError { protocolError = message }-    | otherwise -> throwIO $ ProtocolError UnknownOp { protocolError = line }-  _              -> throwIO $ ProtocolError UnknownStatus { protocolError = C.unpack code }-  where-    message = C.unpack $ C.unwords tokens-    line = C.unpack $ C.unwords (code : tokens)--    -- What memcached sends after ERROR at its connection limit. It is-    -- matched exactly, as other servers may send text after ERROR for a-    -- command they don't know.-    connectionLimit = "Too many open connections"--    -- Meta Text reports these as free-form error text where the binary-    -- protocol had dedicated status codes; match them back so callers keep-    -- seeing 'OpError' rather than an opaque protocol failure. memcached-    -- capitalises some of its out-of-memory errors, such as "Out of memory-    -- during read", so that match ignores case.-    serverFailure-      | "object too large" `isInfixOf` message = throwStatus ErrValueTooLarge-      | "out of memory"    `isInfixOf` map toLower message = throwStatus ErrOutOfMemory-      | otherwise = throwIO $ ProtocolError ServerError { protocolError = message }--    clientFailure-      | "non-numeric" `isInfixOf` message = throwStatus ErrValueNonNumeric-      | otherwise = throwIO $ ProtocolError BadCommand { protocolError = message }---- | Extract the CAS version from a response, or zero when absent or invalid.-responseCas :: Response -> Version-responseCas = tokenNumber "c" . responseTokens---- | Extract the flags from a response, or zero when absent or invalid.-responseFlags :: Response -> Flags-responseFlags = tokenNumber "f" . responseTokens---- | Parse the numeric value in a response, or zero when it is absent or invalid.-responseNumber :: Response -> Word64-responseNumber = fromMaybe 0 . readDecimal . responseValue--tokenNumber :: (Integral a, Bounded a) => ByteString -> [ByteString] -> a-tokenNumber prefix xs = fromMaybe 0 $ do-  token <- find (B.isPrefixOf prefix) xs-  readDecimal (B.drop (B.length prefix) token)---- | Longest response line accepted before assuming the stream is desynchronised.-maxLineLength :: Int-maxLineLength = 8 * 1024---- | Receive one CRLF-terminated line, without the line-feed byte.-recvLine :: Connection -> IO ByteString-recvLine s = do-  buffer <- readBuffer s-  case B.elemIndex 10 buffer of-    Just i -> writeBuffer s (B.drop (i + 1) buffer) >> return (B.take i buffer)-    Nothing-      | B.length buffer > maxLineLength ->-        throwIO $ ProtocolError BadLength { protocolError = "response line too long" }-      | otherwise -> readChunk 0 s >> recvLine s---- | Receive exactly the requested number of bytes.-recvExact :: Connection -> Int -> IO ByteString-recvExact s n-  | n < 0 = throwIO $ ProtocolError BadLength { protocolError = "negative length" }-  | otherwise = B.concat <$> go n []-  where-    go 0 acc = return (reverse acc)-    go wanted acc = do-      buffer <- readBuffer s-      let takeN = min wanted (B.length buffer)-      if takeN > 0-        then writeBuffer s (B.drop takeN buffer) >> go (wanted - takeN) (B.take takeN buffer : acc)-        else readChunk wanted s >> go wanted acc---- | Receive through the first occurrence of a delimiter, including it. Throws--- 'BadLength' once it has read more than 1 MiB without the delimiter.-recvRawUntil :: ByteString -> Connection -> IO ByteString-recvRawUntil end s = go B.empty-  where-    go acc = do-      buffer <- readBuffer s-      let combined = acc <> buffer-      case B.breakSubstring end combined of-        (before, rest) | not (B.null rest) -> do-          writeBuffer s (B.drop (B.length end) rest)-          return (before <> end)-        _ | B.length combined > maxRawLength ->-            throwIO $ ProtocolError BadLength { protocolError = "response too long" }-          | otherwise -> writeBuffer s B.empty >> readChunk 0 s >> go combined---- | 'recvRawUntil' gives up once it has read more than this without its--- delimiter. ElastiCache discovery reads its cluster configuration with it,--- which lists each node as a host name (at most 253 bytes), an IP address and--- a port: at most about 300 bytes a node, so this holds over 3,000 nodes.--- ElastiCache allows 60 nodes in a Memcached cluster unless that quota is--- raised. A node can take as little as a few bytes, though, so discovery also--- refuses a configuration that lists more than 1,000 nodes (@maxNodes@ in--- "Database.Memcache.ElastiCacheClient"): that limit, not this one, bounds--- the servers it makes.-maxRawLength :: Int-maxRawLength = 1024 * 1024--readChunk :: Int -> Connection -> IO ()-readChunk n (Connection s ref) = do-  chunk <- N.recv s (max 4096 (min maxRecvSize n))-  if B.null chunk then throwIO eofError else modifyIORef' ref (<> chunk)---- | Largest single receive. 'N.recv' allocates a buffer of the full requested--- size on every call, so asking for the whole remainder of a large value--- turns reading it into quadratic allocation.-maxRecvSize :: Int-maxRecvSize = 64 * 1024--readBuffer :: Connection -> IO ByteString-readBuffer (Connection _ ref) = readIORef ref--writeBuffer :: Connection -> ByteString -> IO ()-writeBuffer (Connection _ ref) = writeIORef ref--eofError :: MemcacheError-eofError = ProtocolError UnexpectedEOF { protocolError = "" }---- | A key encoded for the Meta Text wire protocol.-data WireKey = WireKey-  -- | The bytes sent as the key.-  { wireKey :: !ByteString-  -- | Whether the key uses the protocol's base64 binary-key mode.-  , wireB64 :: !Bool-  } deriving (Eq, Show)---- | Encode a key, using base64 when it contains protocol-invalid bytes.-encodeKey :: Key -> Either ClientError WireKey-encodeKey key-  | B.null key = Left (KeyTooLong "empty key")-  | B.length key > 250 = Left (KeyTooLong "key exceeds 250 bytes")-  | B.length wire > 250 = Left (KeyTooLong "encoded key exceeds 250 bytes")-  | otherwise = Right (WireKey wire b64)-  where-    b64 = B.any (\c -> c <= 0x20 || c == 0x7f) key-    wire = if b64 then Base64.encode key else key--keyArgs :: WireKey -> ByteString-keyArgs (WireKey wire b64) = wire <> if b64 then " b" else B.empty--keyFlag :: WireKey -> ByteString-keyFlag (WireKey _ b64) = if b64 then " b" else B.empty---- | Write a request that carries a value or a number into one buffer. The--- value is copied once (each strict 'ByteString' append copies both sides, so--- a value at the end of a chain of appends is copied once per piece before--- it), and numbers are written in place rather than through 'show'. The size--- is the length of the request's key and value. Values go in with--- 'byteStringCopy', as 'byteString' would add a large one as a chunk of its--- own for 'BL.toStrict' to copy again. Inlined so the pieces are written--- directly instead of first being allocated as closures.------ Requests with neither keep plain appends, which are cheaper for a few short--- strings than running a 'Builder'.-render :: Int -> Builder -> ByteString-{-# INLINE render #-}-render size = BL.toStrict . toLazyByteStringWith strategy BL.empty-  where strategy = untrimmedStrategy (size + requestHeadroom) smallChunkSize---- | Room for everything in a request besides its key and value: the command,--- its meta flags and up to four numbers of at most 20 digits. Room left over--- stays with the request rather than being trimmed off by another copy. A--- request that needed more would still be encoded correctly, but copied once--- more.-requestHeadroom :: Int-requestHeadroom = 128---- | A piece of a request. Fixed pieces are 'ByteString' literals passed--- through this rather than 'Builder' literals, which are encoded a character--- at a time and measured noticeably slower.-bytes :: ByteString -> Builder-bytes = byteString---- | CRLF used to terminate Meta Text requests.-crlf :: ByteString-crlf = "\r\n"---- | Meta Text storage operation.-data StoreMode-  -- | Store whether or not the key exists.-  = Set-  -- | Store only when the key does not exist.-  | Add-  -- | Store only when the key exists.-  | Replace-  -- | Add bytes to the end of an existing value.-  | Append-  -- | Add bytes to the beginning of an existing value.-  | Prepend-  deriving (Eq, Show)---- | Meta Text arithmetic operation.-data ArithMode-  -- | Increment a numeric value.-  = Incr-  -- | Decrement a numeric value.-  | Decr-  deriving (Eq, Show)--storeMode :: StoreMode -> ByteString-storeMode Set = "S"-storeMode Add = "E"-storeMode Replace = "R"-storeMode Append = "A"-storeMode Prepend = "P"--arithMode :: ArithMode -> ByteString-arithMode Incr = "I"-arithMode Decr = "D"--cmdMetaGet, cmdMetaSet, cmdMetaDelete, cmdMetaArith, cmdMetaNoOp :: ByteString-cmdMetaGet = "mg"-cmdMetaSet = "ms"-cmdMetaDelete = "md"-cmdMetaArith = "ma"-cmdMetaNoOp = "mn"--cmdFlush, cmdVersion, cmdQuit, cmdStats, cmdSet :: ByteString-cmdFlush = "flush_all"-cmdVersion = "version"-cmdQuit = "quit"-cmdStats = "stats"-cmdSet = "set"--cas :: Version -> Builder-cas n = if n == 0 then mempty else bytes " C" <> word64Dec n---- | Encode a get request for one key.-getRequest :: WireKey -> ByteString-getRequest key = cmdMetaGet <> " " <> keyArgs key <> " v f c" <> crlf---- | Encode a get request for a pipelined batch. It is 'getRequest' plus the--- @q@ flag, so a miss gets no reply, and the given opaque as the @O@ flag,--- which memcached copies into the reply so that it can be matched to its--- request.-getManyRequest :: WireKey -> Int -> ByteString-getManyRequest key opaque = render (B.length (wireKey key)) $-  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " v f c q O" <> intDec opaque-  <> bytes crlf---- | Encode a get-and-touch request.-gatRequest :: WireKey -> Expiration -> ByteString-gatRequest key expiry = render (B.length (wireKey key)) $-  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " v f c T" <> word32Dec expiry-  <> bytes crlf---- | Encode a touch request.-touchRequest :: WireKey -> Expiration -> ByteString-touchRequest key expiry = render (B.length (wireKey key)) $-  bytes cmdMetaGet <> bytes " " <> bytes (keyArgs key) <> bytes " T" <> word32Dec expiry-  <> bytes " c" <> bytes crlf---- | Encode a storage request.------ Send this only to memcached 1.6.10 or later. Older servers reject it without--- reading the value, and then run the value's bytes as commands. Connections--- that "Database.Memcache.Server" makes check the server's version, but a--- connection made with 'newConnection' directly does not.------ Nor send it with a value longer than 1 GiB, more than any memcached server--- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs--- the value's bytes as commands. The operations in "Database.Memcache.Client"--- check the length before sending anything, but this encodes a value of any--- length.-storeRequest :: StoreMode -> WireKey -> Value -> Flags -> Expiration -> Version -> ByteString-storeRequest mode key value flags expiry version = render (B.length (wireKey key) + B.length value) $-  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)-  <> bytes " F" <> word32Dec flags <> bytes " T" <> word32Dec expiry <> cas version-  <> bytes " M" <> bytes (storeMode mode) <> bytes (keyFlag key) <> bytes " c"-  <> bytes crlf <> byteStringCopy value <> bytes crlf---- | Encode a set request for a pipelined batch. It is 'storeRequest' in 'Set'--- mode without a CAS, plus the given opaque as the @O@ flag, which memcached--- copies into the reply so that it can be matched to its request.------ Send this only to memcached 1.6.10 or later. Older servers reject it without--- reading the value, and then run the value's bytes as commands. Connections--- that "Database.Memcache.Server" makes check the server's version, but a--- connection made with 'newConnection' directly does not.------ Nor send it with a value longer than 1 GiB, more than any memcached server--- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs--- the value's bytes as commands. The operations in "Database.Memcache.Client"--- check the length before sending anything, but this encodes a value of any--- length.-setManyRequest :: WireKey -> Value -> Flags -> Expiration -> Int -> ByteString-setManyRequest key value flags expiry opaque = render (B.length (wireKey key) + B.length value) $-  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)-  <> bytes " F" <> word32Dec flags <> bytes " T" <> word32Dec expiry-  <> bytes " M" <> bytes (storeMode Set) <> bytes (keyFlag key) <> bytes " c O" <> intDec opaque-  <> bytes crlf <> byteStringCopy value <> bytes crlf---- | Encode an increment or decrement request. Unless the expiration is--- 'maxBound', the request asks the server to create a missing key with the--- initial value and that expiration.-arithmeticRequest :: ArithMode -> WireKey -> Initial -> Delta -> Expiration -> Version -> ByteString-arithmeticRequest mode key initial delta expiry version = render (B.length (wireKey key)) $-  bytes cmdMetaArith <> bytes " " <> bytes (keyArgs key) <> bytes " D" <> word64Dec delta-  <> cas version <> bytes " M" <> bytes (arithMode mode) <> bytes " v c"-  <> (if expiry == maxBound-        then mempty-        else bytes " N" <> word32Dec expiry <> bytes " J" <> word64Dec initial)-  <> bytes crlf---- | Encode an append or prepend request.------ Send this only to memcached 1.6.10 or later. Older servers reject it without--- reading the value, and then run the value's bytes as commands. Connections--- that "Database.Memcache.Server" makes check the server's version, but a--- connection made with 'newConnection' directly does not.------ Nor send it with a value longer than 1 GiB, more than any memcached server--- can store: from 2147483646 bytes, every memcached release up to 1.6.45 runs--- the value's bytes as commands. The operations in "Database.Memcache.Client"--- check the length before sending anything, but this encodes a value of any--- length.-modifyRequest :: StoreMode -> WireKey -> Value -> Version -> ByteString-modifyRequest mode key value version = render (B.length (wireKey key) + B.length value) $-  bytes cmdMetaSet <> bytes " " <> bytes (wireKey key) <> bytes " " <> intDec (B.length value)-  <> bytes " M" <> bytes (storeMode mode) <> bytes (keyFlag key) <> cas version <> bytes " c"-  <> bytes crlf <> byteStringCopy value <> bytes crlf---- | Encode a delete request.-deleteRequest :: WireKey -> Version -> ByteString-deleteRequest key 0 = cmdMetaDelete <> " " <> keyArgs key <> crlf-deleteRequest key version = render (B.length (wireKey key)) $-  bytes cmdMetaDelete <> bytes " " <> bytes (keyArgs key) <> cas version <> bytes crlf---- | Encode a delete request for a pipelined batch. It is 'deleteRequest'--- without a CAS, plus the given opaque as the @O@ flag, which memcached copies--- into the reply so that it can be matched to its request.-deleteManyRequest :: WireKey -> Int -> ByteString-deleteManyRequest key opaque = render (B.length (wireKey key)) $-  bytes cmdMetaDelete <> bytes " " <> bytes (keyArgs key) <> bytes " O" <> intDec opaque <> bytes crlf---- | Encode a flush request, optionally delayed until the given expiration.-flushRequest :: Maybe Expiration -> ByteString-flushRequest Nothing = cmdFlush <> crlf-flushRequest (Just expiry) = render 0 $ bytes cmdFlush <> bytes " " <> word32Dec expiry <> bytes crlf---- | Encode a version request.-versionRequest, quitRequest :: ByteString-versionRequest = cmdVersion <> crlf-quitRequest = cmdQuit <> crlf---- | Encode a stats request, optionally scoped to a key.-statsRequest :: Maybe Key -> ByteString-statsRequest Nothing = cmdStats <> crlf-statsRequest (Just key) = cmdStats <> " " <> key <> crlf---- | Encode the text auth-file request, authenticating using the value as its--- space-separated credentials.-authRequest :: Value -> ByteString-authRequest value = render (B.length value) $-  bytes cmdSet <> bytes " auth 0 0 " <> intDec (B.length value)-  <> bytes crlf <> byteStringCopy value <> bytes crlf---- | Encode a Meta Text no-op request.-noOpRequest :: ByteString-noOpRequest = cmdMetaNoOp <> crlf
Database/Memcache/Timeout.hs view
@@ -10,12 +10,12 @@ Portability : GHC  A timeout that the action it limits can start again, with which the batches of-"Database.Memcache.Cluster" give each reply a timeout of its own. Not exposed.+"Database.Memcache.Internal.Cluster" give each reply a timeout of its own. Not+exposed.  This module uses CPP, to leave out "GHC.Event" on Windows, and that is why it is a module of its own: CPP joins each line that ends in a backslash to the-next, which breaks a string continued across lines with a string gap, as the-deprecation message in "Database.Memcache.Cluster" is.+next, which breaks a string continued across lines with a string gap. -} module Database.Memcache.Timeout (         timeoutRestartable
Database/Memcache/Types.hs view
@@ -12,7 +12,7 @@ -} module Database.Memcache.Types (         -- * Authentication-        Authentication(..), Username, Password,+        Authentication(..), Username, Password, validateCredentials,          -- * Fields & Values         Key, Value, Initial, Delta, Expiration, Flags,@@ -22,7 +22,7 @@  import           Data.ByteString (ByteString) import           Data.Word-import           Database.Memcache.Types.Authentication (Authentication(..), Username, Password)+import           Database.Memcache.Types.Authentication (Authentication(..), Username, Password, validateCredentials) import           Database.Memcache.Types.ServerSpec (ServerSpec(..), defaultServerSpec, parseServerSpec)  -- | Memcached key bytes.@@ -38,24 +38,15 @@ -- that one in the past expires the value at once. -- -- memcached takes an expiration as a signed 32-bit number, so the latest Unix--- time it takes is @2147483647@ (2^31 - 1), 03:14:07 UTC on 19 January 2038:--- use that or less. This client sends @2147483648@ or more as it is, except--- that 'Database.Memcache.Client.increment' and--- 'Database.Memcache.Client.decrement' take 'maxBound' to mean that a missing--- key isn't created, and don't send it. memcached 1.6.45 and later (1.6.40--- for 'Database.Memcache.Client.flush') reject such a number with--- @CLIENT_ERROR@, which the operation throws as--- v'Database.Memcache.Errors.ProtocolError'--- 'Database.Memcache.Errors.BadCommand', having changed nothing. Earlier--- releases do the same on a 32-bit system, but on a 64-bit one read such a--- number as negative, and so in the past: the value expires at once, though--- the operation reports success. The notes on expiration in--- "Database.Memcache.Client" say what each operation does.+-- time it takes is @2147483647@ (2^31 - 1), 03:14:07 UTC on 19 January 2038.+-- "Database.Memcache.Client" throws v'Database.Memcache.Errors.ClientError'+-- 'Database.Memcache.Errors.InvalidArgument' for a larger one, before sending+-- anything. type Expiration = Word32 -- | Application-defined value flags. type Flags      = Word32--- | CAS version associated with a value. Operations that take a version skip--- the CAS check when it is @0@.+-- | CAS version associated with a value. On a memcached started with @-C@,+-- every version is @0@. type Version    = Word64  -- | Status reported by a Memcached operation.
Database/Memcache/Types/Authentication.hs view
@@ -20,12 +20,8 @@ -- server specification holding them, does not reveal it. The username is -- shown. data Authentication-    = Auth-        { -- | Username to send to the server.-          username :: !Username-          -- | Password to send to the server.-        , password :: !Password-        }+    -- | Authenticate the connection with this username and password.+    = Auth !Username !Password     -- | Do not authenticate the connection.     | NoAuth     deriving (Eq)@@ -33,8 +29,7 @@ -- | The derived format, with the password replaced by @\<redacted\>@. instance Show Authentication where     showsPrec d (Auth user _) = showParen (d >= 11) $-        showString "Auth {username = " . shows user-            . showString ", password = <redacted>}"+        showString "Auth " . showsPrec 11 user . showString " <redacted>"     showsPrec _ NoAuth = showString "NoAuth"  -- | Username for text authentication.
Database/Memcache/Types/Cluster.hs view
@@ -7,15 +7,15 @@ Stability   : stable Portability : GHC -The 'Cluster' type, with all its fields. "Database.Memcache.Cluster" exports-it abstractly; "Database.Memcache.ElastiCacheClient" also sets+The 'Cluster' type, with all its fields. "Database.Memcache.Internal.Cluster"+exports it abstractly; "Database.Memcache.ElastiCacheClient" also sets 'cStopRefresh', which @quit@ in "Database.Memcache.Client" runs. Not exposed. -} module Database.Memcache.Types.Cluster (         Cluster(..)     ) where -import qualified Database.Memcache.Ketama       as Ketama+import qualified Database.Memcache.Internal.Ketama as Ketama import           Database.Memcache.Types        (Key) import           Database.Memcache.Types.Server (Server) 
Database/Memcache/Types/Server.hs view
@@ -9,15 +9,16 @@ Stability   : stable Portability : GHC -The 'Server' type, with all its fields. "Database.Memcache.Server" exports it-with only some of them; "Database.Memcache.Cluster" also sets 'slotTaken'.-Not exposed.+The 'Server' type, with all its fields. "Database.Memcache.Internal.Server"+exports it with only some of them; "Database.Memcache.Internal.Cluster" also+sets 'slotTaken'. Not exposed. -} module Database.Memcache.Types.Server (         Server(..), Slot     ) where -import           Database.Memcache.Socket       (Connection)+import           Database.Memcache.Internal.Lookup (Lookup)+import           Database.Memcache.Internal.Socket (Connection) import           Database.Memcache.Types        (Authentication)  import           Data.IORef@@ -30,9 +31,7 @@ data Server = Server {         -- | Hash of the server's host and port. The 'Eq' and 'Ord' instances         -- compare it first, and then the host and port, so two servers whose-        -- hashes collide are still different servers. Only the deprecated-        -- @legacyServerForKey@ routes keys by this value; see-        -- "Database.Memcache.Cluster".+        -- hashes collide are still different servers.         sid    :: {-# UNPACK #-} !Int,         -- | Connection pool to server. It holds slots rather than         -- connections, so that waiting for a free slot is all a request does@@ -54,7 +53,10 @@         -- so that a timeout can tell an attempt still waiting for a slot,         -- which never reached the server, from one that has taken a slot.         -- 'Nothing' on the server itself.-        slotTaken :: Maybe (IORef Bool)+        slotTaken :: Maybe (IORef Bool),+        -- | The server's host lookup, while one runs. New connections wait+        -- for it rather than start another.+        hostLookup :: Lookup     }  -- | A place in a server's pool for one connection, which @withSocket@ opens
Database/Memcache/Types/ServerSpec.hs view
@@ -39,7 +39,7 @@     -- addresses, each is tried in turn until one accepts the connection. If     -- each refuses it or fails in some other way, connecting fails with the     -- first address's error. The addresses share the time an attempt at an-    -- operation has (@optsServerTimeout@): an address that doesn't answer in+    -- operation has (@optsTimeout@): an address that doesn't answer in     -- that time uses it up, and that attempt then tries none of the later     -- ones.     --@@ -52,8 +52,9 @@     -- | Port number server is running on. A Unix socket has none, and the     -- client doesn't use this to connect to one, but it still names the     -- server, as it does any other: the host and port make the server's name-    -- on the hash ring that routes keys (see "Database.Memcache.Cluster") and-    -- its @sid@, so changing a socket's port moves keys to other servers.+    -- on the hash ring that routes keys (see+    -- "Database.Memcache.Internal.Cluster") and its @sid@, so changing a+    -- socket's port moves keys to other servers.     -- @\"11211\"@ names a 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.
Database/Memcache/Util.hs view
@@ -13,12 +13,14 @@         maxValueLength,         note,         readDecimal,+        toMicroseconds,         withDetail     ) where  import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Char (isAscii, isPrint, showLitChar)+import Data.Time.Clock (NominalDiffTime)  -- | Turn a 'Nothing' into an error. note :: e -> Maybe a -> Either e a@@ -43,6 +45,11 @@         where digit = fromIntegral (byte - 0x30)     (limit, lastDigit) = maxBound `quotRem` 10 +-- | A duration in the microseconds that @threadDelay@ and @timeout@ take,+-- rounded up, so that a positive duration never becomes 0.+toMicroseconds :: NominalDiffTime -> Int+toMicroseconds d = ceiling (d * 1000000)+ -- | Append a detail, which may hold bytes a server sent, keeping the message -- on one line of ASCII: characters outside printable ASCII and backslashes are -- escaped as in a Haskell string literal, and only the first 200 characters@@ -63,8 +70,8 @@ -- An item holds its key and a header as well as its value, so no memcached -- server can store a value this long. The operations in -- "Database.Memcache.Client" that store a value reject a longer one before--- anything is sent, and 'Database.Memcache.Socket.recvResponse' rejects a--- reply that claims a longer one before reading any of it, so that the--- client can read back any value it can store.+-- anything is sent, and 'Database.Memcache.Internal.Socket.recvResponse'+-- rejects a reply that claims a longer one before reading any of it, so that+-- the client can read back any value it can store. maxValueLength :: Int maxValueLength = 1024 * 1024 * 1024
README.md view
@@ -73,7 +73,7 @@       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 1 0 0+  visits <- M.increment mc "visits" 1 (Just (1, 0)) Nothing   print (fst <$> visits)    M.quit mc@@ -81,18 +81,16 @@  Keys and values are strict `ByteString`s. Misses are returned as `Nothing`, while unexpected failures are thrown as a `MemcacheError` or a network-`IOException`. ElastiCache's `newClient` (see-[Amazon ElastiCache](#amazon-elasticache)) also throws a `StringException`,-from `UnliftIO.Exception`, when discovery fails on the configuration-endpoint's reply, such as an error reply or a configuration it can't use.+`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 CAS `Version` skip the check when it is `0`.-`increment` and `decrement` create a missing key with the given initial-value, unless the expiration is `maxBound`. The+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`.@@ -103,10 +101,10 @@ 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 one connection by default, so concurrent requests to-the same server wait for each other; see+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 `optsServerTimeout`. An attempt that runs out of time+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@@ -114,8 +112,8 @@ first.  A failed operation is retried, except that a request that mustn't be sent-twice (`increment`, `decrement`, `append`, `prepend`, `add`, `delete`, and-`cas` or `replace` with a version) isn't sent again once it may have reached+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.@@ -133,7 +131,7 @@ 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 `optsDeadRetryDelay` has+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`. @@ -205,14 +203,14 @@ `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 microseconds as for `threadDelay`:+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 (60 * 1000000) endpoint+  mc <- EC.newClient M.def endpoint 60 ```  `M.quit` stops the thread, so that no refresh replaces the servers once their@@ -232,6 +230,65 @@ 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@@ -246,13 +303,14 @@ 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, deploying each step to-every instance before starting the next:+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 with `optsGetServerForKey = legacyServerForKey`, 0.4's router,-   now deprecated, 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`.+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.@@ -261,9 +319,10 @@ 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-[`Database.Memcache.Cluster`](https://hackage.haskell.org/package/memcache/docs/Database-Memcache-Cluster.html)+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@@ -296,24 +355,25 @@ ## 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 (`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 `optsServerTimeout`, as the single requests+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 with the default pool of one connection (see-below), other requests to that server wait for it, and those that run out of-time waiting throw `Timeout` without marking the server down.+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 a single connection-(`soNumResources = 1`), so concurrent operations against the same server wait-for each other. Raising `soNumResources` in the `ServerOptions` set through-`optsServerOptions` allows concurrent operations without requiring a separate-pool implementation.+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. 
bench/Parser.hs view
@@ -9,9 +9,9 @@ import qualified Data.ByteString           as B import qualified Data.ByteString.Char8     as C import qualified Database.Memcache.Client  as Client-import           Database.Memcache.Cluster (Options (..), newCluster)-import qualified Database.Memcache.Ketama  as Ketama-import           Database.Memcache.Socket+import           Database.Memcache.Internal.Cluster (Options (..), newCluster)+import qualified Database.Memcache.Internal.Ketama  as Ketama+import           Database.Memcache.Internal.Socket import           Database.Memcache.Types   (Authentication (NoAuth), ServerSpec (..))  main :: IO ()@@ -23,9 +23,9 @@     ]   , bgroup "request"     [ bench "get" $ whnf getRequest key-    , bench "set 100 B" $ whnf (storeRequest Set key (C.replicate 100 'v') 10 0) 0-    , bench "set 64 KiB" $ whnf (storeRequest Set key (C.replicate 65536 'v') 10 0) 0-    , bench "increment" $ whnf (arithmeticRequest Incr key 0 1 0) 0+    , bench "set 100 B" $ whnf (storeRequest Set key (C.replicate 100 'v') 10 0) Nothing+    , bench "set 64 KiB" $ whnf (storeRequest Set key (C.replicate 65536 'v') 10 0) Nothing+    , bench "increment" $ whnf (arithmeticRequest Incr key 1 (Just (0, 0))) Nothing     ]   , bgroup "response"     [ bench "cas" $ whnf responseCas valueResponse
memcache.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name:          memcache-version:       0.5.1.0+version:       0.6.0.0 synopsis:      A memcached client library. description:   A client library for a Memcached cluster. Memcached is an in-memory key-value@@ -38,12 +38,15 @@   >     print v    You should only need to import 'Database.Memcache.Client', but other modules-  are exposed for lower-level use. Version 0.5 is a breaking change from 0.4.-  Keys are now routed by ketama, so with /n/ servers, upgrading moves all but-  about one key in /n/ to a different server, once. The @optsServerRetries@-  option now counts retries, not attempts. Version 0.5, like 0.4.2.1, needs-  memcached 1.6.10 or later. See /Upgrading from 0.4/ in the README, and the-  changelog, for details.+  are exposed for lower-level use: those under @Database.Memcache.Internal@+  aren't covered by the PVP, and may change in any release. Version 0.6 is a+  breaking change from 0.5, but keys go to the same servers; see+  /Upgrading from 0.5/ in the README. Version 0.5 was a breaking change from+  0.4: keys are routed by ketama, so with /n/ servers, upgrading from 0.4 moves+  all but about one key in /n/ to a different server, once. The+  @optsServerRetries@ option now counts retries, not attempts.+  Version 0.5, like 0.4.2.1, needs memcached 1.6.10 or later. See+  /Upgrading from 0.4/ in the README, and the changelog, for details.  category:      Database homepage:      https://github.com/dterei/memcache-hs#readme@@ -85,14 +88,15 @@   import:           shared   hs-source-dirs:   .   exposed-modules:-    Database.Memcache.Auth     Database.Memcache.Client-    Database.Memcache.Cluster     Database.Memcache.ElastiCacheClient     Database.Memcache.Errors-    Database.Memcache.Ketama-    Database.Memcache.Server-    Database.Memcache.Socket+    Database.Memcache.Internal.Auth+    Database.Memcache.Internal.Cluster+    Database.Memcache.Internal.Ketama+    Database.Memcache.Internal.Lookup+    Database.Memcache.Internal.Server+    Database.Memcache.Internal.Socket     Database.Memcache.Types    other-modules:@@ -121,7 +125,7 @@     , network            >=3.1.4.0     , network-uri        >=2.6.4.2     -- 0.3 gives a pool a stripe for each capability, and no CI job builds-    -- with it; see ServerOptions in Database.Memcache.Server.+    -- with it; see ServerOptions in Database.Memcache.Internal.Server.     , resource-pool      >=0.2.3.2 && (<0.3 || >=0.4)     , text               >=1.2.5.0     , time               >=1.11.1.1@@ -145,7 +149,6 @@   build-depends:     , base64-bytestring  >=1.2.1.0     , directory-    , hashable     , hspec     , memcache     , network
test-integration/Integration.hs view
@@ -12,10 +12,10 @@ import           Data.Maybe               (isJust) import           Data.Time.Clock.POSIX    (getPOSIXTime) import qualified Database.Memcache.Client as M-import qualified Database.Memcache.Cluster as Cluster import qualified Database.Memcache.ElastiCacheClient as EC-import qualified Database.Memcache.Ketama as K-import qualified Database.Memcache.Server as Server+import qualified Database.Memcache.Internal.Cluster as Cluster+import qualified Database.Memcache.Internal.Ketama as K+import qualified Database.Memcache.Internal.Server as Server import           Database.Memcache.Types  (ServerSpec (..)) import           Network.Socket           (Family (AF_INET), SocketOption (ReuseAddr),                                            SocketType (Stream), bind, close, defaultProtocol,@@ -35,7 +35,7 @@ import           System.Timeout           (timeout) import           Test.Hspec import qualified UnliftIO.Async           as Async-import           UnliftIO.Exception       (StringException (..), try)+import           UnliftIO.Exception       (try)  main :: IO () main = do@@ -62,6 +62,7 @@           describe "Unix socket" $ unixSocketSpecs path           describe "server out of memory" $ outOfMemorySpecs fullPort           describe "server with a 256 MiB item size limit" $ largeItemSpecs path+          describe "server without CAS" $ noCasSpecs path           describe "ElastiCache discovery" $ elastiCacheSpecs port  integrationSpecs :: Int -> Spec@@ -84,7 +85,7 @@      M.add client key "two" 0 0 `shouldReturn` Nothing -    M.replace client "integration-no-replace" "two" 0 0 0 `shouldReturn` Nothing+    M.replace client "integration-no-replace" "two" 0 0 Nothing `shouldReturn` Nothing    it "updates values with CAS" $ \client -> do     old <- M.set client "integration-cas" "old" 0 0@@ -97,8 +98,8 @@   it "deletes values" $ \client -> do     _ <- M.set client "integration-delete" "value" 0 0 -    M.delete client "integration-delete" 0 `shouldReturn` True-    M.delete client "integration-delete" 0 `shouldReturn` False+    M.delete client "integration-delete" Nothing `shouldReturn` True+    M.delete client "integration-delete" Nothing `shouldReturn` False    it "touches and gets with expiry" $ \client -> do     _ <- M.set client "integration-touch" "value" 0 0@@ -136,7 +137,6 @@     let items = [("integration-set-many", "one", 1, 0), ("integration set many", "two", 2, 0)]         keys = [key | (key, _, _, _) <- items]     versions <- M.setMany client items-    -- One server, so the results are in the order given.     map fst versions `shouldBe` keys     values <- M.getMany client keys     values `shouldMatchList`@@ -177,7 +177,7 @@     -- the request sent it as base64. Echoed, "integration-x\ny" would end its     -- reply line at the newline and pass for "integration-x".     let keys = ["integration-incr-many", "integration incr many", "integration-x\ny"]-    created <- mapM (\key -> M.increment client key 5 1 0 0) keys+    created <- mapM (\key -> M.increment client key 1 (Just (5, 0)) Nothing) keys     map (fmap fst) created `shouldBe` replicate 3 (Just 5)     plain <- M.set client "integration-x" "plain" 0 0     M.getMany client (keys ++ ["integration-x"]) `shouldReturn`@@ -188,31 +188,31 @@     -- An append replaces the item, and memcached then echoes an encoded key raw.     let keys = ["integration-append-many", "integration append many"]     forM_ keys $ \key -> M.set client key "x" 0 0-    appended <- mapM (\key -> M.append client key "y" 0) keys+    appended <- mapM (\key -> M.append client key "y" Nothing) keys     appended `shouldSatisfy` all isJust     M.getMany client keys `shouldReturn`       [(key, ("xy", 0, version)) | (key, Just version) <- zip keys appended]    it "increments and decrements counters" $ \client -> do-    _ <- M.delete client "integration-counter" 0-    incremented <- M.increment client "integration-counter" 10 2 0 0+    _ <- M.delete client "integration-counter" Nothing+    incremented <- M.increment client "integration-counter" 2 (Just (10, 0)) Nothing     incremented `shouldSatisfy` maybe False ((== 10) . fst) -    decremented <- M.decrement client "integration-counter" 0 3 0 0+    decremented <- M.decrement client "integration-counter" 3 (Just (0, 0)) Nothing     decremented `shouldSatisfy` isJust    it "reads the largest counter and flags values" $ \client -> do     _ <- M.set client "integration-max" "18446744073709551614" maxBound 0-    fmap fst <$> M.increment client "integration-max" 0 1 0 0 `shouldReturn` Just maxBound+    fmap fst <$> M.increment client "integration-max" 1 (Just (0, 0)) Nothing `shouldReturn` Just maxBound     result <- M.get client "integration-max"     fmap (\(_, flags, _) -> flags) result `shouldBe` Just maxBound    it "appends and prepends" $ \client -> do     cas <- M.set client "integration-modify" "middle" 0 0-    appended <- M.append client "integration-modify" "-end" cas+    appended <- M.append client "integration-modify" "-end" (Just cas)     appended `shouldSatisfy` isJust -    prepended <- M.prepend client "integration-modify" "start-" 0+    prepended <- M.prepend client "integration-modify" "start-" Nothing     prepended `shouldSatisfy` isJust      result <- M.get client "integration-modify"@@ -220,20 +220,20 @@    it "appends and prepends only when the key exists and the CAS matches" $ \client -> do     old <- M.set client "integration-modify-cas" "middle" 0 0-    Just appended <- M.append client "integration-modify-cas" "-end" old-    M.append client "integration-modify-cas" "-stale" old `shouldReturn` Nothing+    Just appended <- M.append client "integration-modify-cas" "-end" (Just old)+    M.append client "integration-modify-cas" "-stale" (Just old) `shouldReturn` Nothing -    Just prepended <- M.prepend client "integration-modify-cas" "start-" appended-    M.prepend client "integration-modify-cas" "stale-" old `shouldReturn` Nothing+    Just prepended <- M.prepend client "integration-modify-cas" "start-" (Just appended)+    M.prepend client "integration-modify-cas" "stale-" (Just old) `shouldReturn` Nothing      M.get client "integration-modify-cas" `shouldReturn` Just ("start-middle-end", 0, prepended) -    M.append client "integration-no-modify" "-end" old `shouldReturn` Nothing-    M.prepend client "integration-no-modify" "start-" old `shouldReturn` Nothing+    M.append client "integration-no-modify" "-end" (Just old) `shouldReturn` Nothing+    M.prepend client "integration-no-modify" "start-" (Just old) `shouldReturn` Nothing    it "modifies encoded keys" $ \client -> do     _ <- M.set client "integration modify key" "middle" 0 0-    _ <- M.append client "integration modify key" "-end" 0+    _ <- M.append client "integration modify key" "-end" Nothing     result <- M.get client "integration modify key"     fmap first result `shouldBe` Just "middle-end" @@ -344,16 +344,16 @@     held `shouldSatisfy` (not . any null)     held `shouldBe` [filter ((== Just port) . owner) keys | port <- ports] -  it "gets many keys" $ \client -> do+  it "gets many keys in the order given" $ \client -> do     storeKeys client     values <- M.getMany client keys-    map fst values `shouldMatchList` keys+    map fst values `shouldBe` keys    it "sets and deletes many keys" $ \client -> do     versions <- M.setMany client [(key, key, 0, 0) | key <- keys]-    map fst versions `shouldMatchList` keys+    map fst versions `shouldBe` keys     values <- M.getMany client keys-    values `shouldMatchList` [(key, (key, 0, version)) | (key, version) <- versions]+    values `shouldBe` [(key, (key, 0, version)) | (key, version) <- versions]     M.deleteMany client keys     M.getMany client keys `shouldReturn` [] @@ -430,7 +430,7 @@     withMemcachedOn executable [] port $ do       other <- M.newClient [ServerSpec "127.0.0.1" (show port) M.NoAuth] M.def       _ <- M.set other "integration-restart-counter" "5" 0 0-      fmap fst <$> M.increment client "integration-restart-counter" 0 1 0 0 `shouldReturn` Just 6+      fmap fst <$> M.increment client "integration-restart-counter" 1 (Just (0, 0)) Nothing `shouldReturn` Just 6       readIORef (Server.failed server) `shouldReturn` 0       fmap first <$> M.get other "integration-restart-counter" `shouldReturn` Just "6" @@ -441,7 +441,7 @@ pausedSpecs executable = do   it "doesn't send an increment again after its reply times out" $     withPaused "integration-paused-counter" (Just "0") "incr_hits"-      (\client key -> void (M.increment client key 0 1 0 0)) (Just "1")+      (\client key -> void (M.increment client key 1 (Just (0, 0)) Nothing)) (Just "1")    it "doesn't send an add again after its reply times out" $     withPaused "integration-paused-add" Nothing "cmd_set"@@ -462,7 +462,7 @@     withMemcachedProcess executable [] $ \(port, process) -> do       let spec = ServerSpec "127.0.0.1" (show port) M.NoAuth       client <- M.newClient [spec]-        M.def { M.optsServerTimeout = 300, M.optsFailRetryDelay = 1000 }+        M.def { M.optsTimeout = 0.3, M.optsRetryDelay = 1 }       other <- M.newClient [spec] M.def       [server] <- toList <$> Cluster.getServers client       mapM_ (\value -> M.set other key value 0 0) initial@@ -510,7 +510,7 @@       -- A server marked dead is tried again at once, so that a get shows       -- when memcached has room again.       client <- M.newClient [ServerSpec "127.0.0.1" (show port) auth]-        M.def { M.optsFailRetryDelay = 10, M.optsDeadRetryDelay = 0 }+        M.def { M.optsRetryDelay = 0.01, M.optsDeadTimeout = 0 }       [server] <- toList <$> Cluster.getServers client       withConnectionsHeld port $ do         M.get client "integration-limit"@@ -569,7 +569,7 @@     mapM_ (M.setMany client . batch) [0 .. 199 :: Int] `shouldThrow` (== M.OpError M.ErrOutOfMemory)     -- The counter needs as much memory as one of the values, so there is none     -- left for it either: memcached replies "Out of memory allocating new item".-    M.increment client "integration-counter" 0 1 0 0 `shouldThrow` (== M.OpError M.ErrOutOfMemory)+    M.increment client "integration-counter" 1 (Just (0, 0)) Nothing `shouldThrow` (== M.OpError M.ErrOutOfMemory)     fmap first <$> M.get client "integration-fill-0" `shouldReturn` Just "x"  -- | Tests against a memcached started with -I 256m, which stores values over@@ -582,7 +582,7 @@       -- Each attempt has 10 s, as sending or reading the value can take       -- longer than the default 750 ms on a busy machine.       client <- M.newClient [ServerSpec "127.0.0.1" (show port) M.NoAuth]-        M.def { M.optsServerTimeout = 10000 }+        M.def { M.optsTimeout = 10 }       let key = "integration-over-128-mib"           value = B.replicate (128 * 1024 * 1024 + 1) 'v'       version <- M.set client key value 5 0@@ -591,6 +591,24 @@       M.getMany client [key] `shouldReturn` [(key, (value, 5, version))]       M.quit client +-- | Tests against a memcached started with -C, which gives every value+-- version 0.+noCasSpecs :: FilePath -> Spec+noCasSpecs executable =+  it "doesn't store a cas or replace with the version 0 that get returns" $+    withMemcached executable ["-C"] $ \port -> do+      -- Not newClient, which flushes: without CAS, a flush also hides values+      -- stored later in the same second.+      client <- M.newClient [ServerSpec "127.0.0.1" (show port) M.NoAuth] M.def+      let key = "integration-no-cas"+      _ <- M.set client key "old" 0 0+      Just (_, _, version) <- M.get client key+      version `shouldBe` 0+      M.cas client key "new" 0 0 version `shouldReturn` Nothing+      M.replace client key "new" 0 0 (Just version) `shouldReturn` Nothing+      M.get client key `shouldReturn` Just ("old", 0, 0)+      M.quit client+ -- | ElastiCache discovery against plain memcached, which has no config -- command: it answers config get cluster with ERROR and keeps the connection -- open.@@ -601,8 +619,8 @@     endpoint <- either fail pure $       EC.parseConfigurationEndpoint ("memcached://127.0.0.1:" <> show port <> "/x.cfg")     -- The outer timeout turns a hang into a failure.-    timeout 5000000 (EC.newClient M.def (3600 * 1000000) endpoint) `shouldThrow`-      \(StringException message _) -> message == "Configuration endpoint replied: ERROR"+    timeout 5000000 (EC.newClient M.def endpoint 3600) `shouldThrow`+      (== M.DiscoveryError "Configuration endpoint replied: ERROR")  newClient :: Int -> IO M.Client newClient port = do
test/RoutingSpec.hs view
@@ -1,29 +1,24 @@ {-# LANGUAGE OverloadedStrings #-}--- The tests of legacyServerForKey use it, although it is deprecated.-{-# OPTIONS_GHC -Wno-deprecations #-}  -- | Key routing: the ketama ring checked against libmemcached's choices, and--- the cluster's use of it, including servers marked failed; and the router of--- 0.4, checked against a copy of its code.+-- the cluster's use of it, including servers marked failed. module RoutingSpec (routingSpec) where  import           Control.Concurrent.MVar   (newMVar, swapMVar) import           Control.Monad             (void) import qualified Data.ByteString.Char8     as C import           Data.Foldable             (for_, toList)-import qualified Data.Hashable             as Hashable import           Data.IORef                (readIORef, writeIORef)-import           Data.List                 (find, findIndex, group, nub, sort, sortOn)-import           Data.Maybe                (fromMaybe, listToMaybe, maybeToList)+import           Data.List                 (group, nub, sort)+import           Data.Maybe                (listToMaybe, maybeToList) import           Data.Time.Clock.POSIX     (getPOSIXTime) import           Data.Word                 (Word32) import qualified Database.Memcache.Client  as Client-import           Database.Memcache.Cluster (Cluster, Options (..), getServers, isAlive,-                                            ketamaServerForKey, legacyServerForKey,-                                            newCluster, setServers) import           Database.Memcache.Errors-import qualified Database.Memcache.Ketama  as K-import           Database.Memcache.Server  (Server, failed, serverHost, serverPort, sid)+import           Database.Memcache.Internal.Cluster (Cluster, Options (..), getServers, isAlive,+                                                     ketamaServerForKey, newCluster, setServers)+import qualified Database.Memcache.Internal.Ketama  as K+import           Database.Memcache.Internal.Server  (Server, failed, serverHost, serverPort) import           Database.Memcache.Types   (Authentication (NoAuth), Key, ServerSpec (..)) import           KetamaVectors import           Test.Hspec@@ -212,7 +207,7 @@       -- Every live server gets keys.       length (nub byName) `shouldBe` 7 -    it "isAlive counts a failed server as down until optsDeadRetryDelay has passed" $ do+    it "isAlive counts a failed server as down until optsDeadTimeout has passed" $ do       -- The cluster's delay is an hour, and the default 1.5 s.       cluster <- clusterOf (scenarioServers "host4")       server <- serverNamed cluster "cache3.example.com:11211"@@ -315,33 +310,6 @@       length counts `shouldBe` 8       map share counts `shouldSatisfy` all (\s -> s >= 0.09 && s <= 0.16) -  -- 0.4 sorted the servers by sid when it made a cluster and when ElastiCache-  -- discovery found them. Neither sorts them now, and legacyServerForKey must-  -- still pick the server 0.4 did.-  describe "legacyServerForKey" $ do-    prop "routes keys as 0.4 did" $-      forAll legacyServers $ \servers -> ioProperty $ do-        cluster <- clusterOf [(host, port, 1) | ((host, port), _) <- servers]-        configured <- toList <$> getServers cluster-        sequence_ [markFailed server | (server, (_, True)) <- zip configured servers]-        let live = [server | (server, (_, False)) <- zip configured servers]-            -- Servers named twice are told apart by position.-            position server = findIndex ((== failed server) . failed) configured-            legacyKeys = take 1000 manyKeys-        routed <- mapM (legacyServerForKey cluster) legacyKeys-        return $ map (>>= position) routed-          === [router04 live key >>= position | key <- legacyKeys]--    it "sends every key to one of two servers" $ do-      cluster <- clusterOf [(host, 11211, 1) | host <- equalHosts 8]-      routed <- mapM (fmap (fmap serverLabel) . legacyServerForKey cluster) manyKeys-      length (nub routed) `shouldSatisfy` (<= 2)--    it "returns no server once every server is marked failed" $ do-      cluster <- clusterOf (scenarioServers "host4")-      mapM_ markFailed . toList =<< getServers cluster-      legacyServerForKey cluster "key" `shouldReturn` Nothing- -- | Look up a scenario's servers or expected routes by name. scenarioServers :: String -> [(String, Int, Int)] scenarioServers name = concat [servers | (n, servers, _) <- scenarios, n == name]@@ -389,36 +357,12 @@ manyKeys :: [Key] manyKeys = [C.pack ("key:" <> show i) | i <- [1 .. 20000 :: Int]] --- | 0.4's router, getServerForKeyDefault, with lists for vectors: of the live--- servers, sorted by sid as 0.4 kept them, the first whose sid is below the--- key's hash, or else the last.-router04 :: [Server] -> Key -> Maybe Server-router04 live k =-  let hashedKey = Hashable.hash k-      searchF s = sid s < hashedKey-      -- 0.4 sorted them with a stable sort and an Ord instance that compared-      -- sid alone, so servers with the same sid kept the order given.-      servers' = sortOn sid live-  in if null servers'-      then Nothing-      else Just $ fromMaybe (last servers') (find searchF servers')---- | One to eight servers, each marked failed or not, from a few hosts and--- ports, so that some lists name a server twice.-legacyServers :: Gen [((String, Int), Bool)]-legacyServers = do-  n <- choose (1, 8)-  vectorOf n ((,) <$> server <*> frequency [(3, pure False), (1, pure True)])-  where-    server = (,) <$> elements ["cache" <> show i <> ".example" | i <- [1 .. 10 :: Int]]-                 <*> elements [11211, 11212]- -- | A cluster of servers given as (host, port, weight); weights are ignored. -- No connections are made until a request is sent. clusterOf :: [(String, Int, Int)] -> IO Cluster clusterOf servers =   newCluster [ServerSpec host (show port) NoAuth | (host, port, _) <- servers]-    Client.def { optsDeadRetryDelay = 3600000 }+    Client.def { optsDeadTimeout = 3600 }  -- | The server the cluster's default router picks for a key, as host:port. route :: Cluster -> Key -> IO (Maybe String)
test/Spec.hs view
@@ -5,15 +5,16 @@ import           FileLimit import           MockServer import           RoutingSpec-import qualified Database.Memcache.Auth    as Auth import qualified Database.Memcache.Client  as Client-import qualified Database.Memcache.Cluster as Cluster import qualified Database.Memcache.ElastiCacheClient as EC import           Database.Memcache.Errors import qualified Database.Memcache.Errors  as E-import qualified Database.Memcache.Server  as Server-import           Database.Memcache.Socket-import           Database.Memcache.Types   (ServerSpec (..), parseServerSpec)+import qualified Database.Memcache.Internal.Auth    as Auth+import qualified Database.Memcache.Internal.Cluster as Cluster+import           Database.Memcache.Internal.Lookup  (addressesOf, newLookup)+import qualified Database.Memcache.Internal.Server  as Server+import           Database.Memcache.Internal.Socket+import           Database.Memcache.Types   (ServerSpec (..), parseServerSpec, validateCredentials) import           Test.Hspec import           Test.Hspec.QuickCheck     (modifyMaxSuccess, prop) import           Test.QuickCheck@@ -30,8 +31,8 @@ import           Control.Exception         (MaskingState (..), SomeException, bracket,                                             displayException, finally, getMaskingState, mask_,                                             try, uninterruptibleMask_)-import           Control.Monad             (forM_, forever, replicateM_, unless, void, when,-                                            (>=>))+import           Control.Monad             (filterM, forM_, forever, replicateM_, unless, void,+                                            when, (>=>)) import           Data.Either               (isLeft, isRight) import           Data.Foldable             (toList) import           Data.IORef                (atomicModifyIORef', newIORef, readIORef,@@ -45,7 +46,7 @@ import           System.Timeout            (timeout) import           UnliftIO.Async            (Async, AsyncCancelled (..), async, asyncOn,                                             asyncThreadId, cancel, mapConcurrently, wait)-import           UnliftIO.Exception        (StringException (..), tryIO)+import           UnliftIO.Exception        (tryIO)  main :: IO () main = hspec $ do@@ -55,7 +56,7 @@       fmap wireKey (encodeKey "a b") `shouldBe` Right (Base64.encode "a b")      it "terminates arithmetic commands" $-      arithmeticRequest Incr (wire "counter") 0 1 maxBound 0 `shouldSatisfy` C.isSuffixOf "\r\n"+      arithmeticRequest Incr (wire "counter") 1 Nothing Nothing `shouldSatisfy` C.isSuffixOf "\r\n"      it "validates encoded key length" $       encodeKey (C.replicate 251 'a') `shouldSatisfy` isLeft@@ -77,7 +78,7 @@     it "rejects a key whose base64 form exceeds 250 bytes" $ do       -- 186 bytes encode to 248 base64 bytes; 187 bytes encode to 252.       fmap (B.length . wireKey) (encodeKey (C.replicate 186 ' ')) `shouldBe` Right 248-      encodeKey (C.replicate 187 ' ') `shouldSatisfy` isLeft+      encodeKey (C.replicate 187 ' ') `shouldBe` Left (InvalidKey "encoded key exceeds 250 bytes")      prop "round-trips every key it accepts" $       forAll keyGen $ \key -> case encodeKey key of@@ -101,9 +102,9 @@           , oneLine (getManyRequest w 7)           , oneLine (gatRequest w 30)           , oneLine (touchRequest w 30)-          , oneLine (deleteRequest w 7)+          , oneLine (deleteRequest w (Just 7))           , oneLine (deleteManyRequest w 7)-          , oneLine (arithmeticRequest Incr w 1 2 30 7)+          , oneLine (arithmeticRequest Incr w 2 (Just (1, 30)) (Just 7))           ]      prop "encodes batch requests as the single-key request plus an opaque" $@@ -114,26 +115,26 @@           Right w -> conjoin             [ getManyRequest w opaque === addFlags (" q O" <> C.pack (show opaque)) (getRequest w)             , setManyRequest w value flags expiry opaque-                === addFlags (" O" <> C.pack (show opaque)) (storeRequest Set w value flags expiry 0)-            , deleteManyRequest w opaque === addFlags (" O" <> C.pack (show opaque)) (deleteRequest w 0)+                === addFlags (" O" <> C.pack (show opaque)) (storeRequest Set w value flags expiry Nothing)+            , deleteManyRequest w opaque === addFlags (" O" <> C.pack (show opaque)) (deleteRequest w Nothing)             ]      it "rejects over-long keys without contacting the server" $       withClient [MR "VA 3 f2 c7\r\nfoo\r\n"] $ \client -> do-        Client.get client (C.replicate 251 'a') `shouldThrow` isKeyTooLong+        Client.get client (C.replicate 251 'a') `shouldThrow` isInvalidKey         Client.get client "key" `shouldReturn` Just ("foo", 2, 7)      it "rejects unsafe stats keys before sending them" $ do       client <- Client.newClient [Client.def] Client.def       Client.stats client (Just "items\r\nset injected 0 0 1\r\nx")-        `shouldThrow` isKeyTooLong+        `shouldThrow` isInvalidArgument      it "encodes all core request forms" $ do       getRequest (wire "key") `shouldBe` "mg key v f c\r\n"       getManyRequest (wire "key") 3 `shouldBe` "mg key v f c q O3\r\n"       gatRequest (wire "key") 30 `shouldBe` "mg key v f c T30\r\n"       touchRequest (wire "key") 30 `shouldBe` "mg key T30 c\r\n"-      deleteRequest (wire "key") 9 `shouldBe` "md key C9\r\n"+      deleteRequest (wire "key") (Just 9) `shouldBe` "md key C9\r\n"       deleteManyRequest (wire "key") 3 `shouldBe` "md key O3\r\n"       flushRequest Nothing `shouldBe` "flush_all\r\n"       flushRequest (Just 30) `shouldBe` "flush_all 30\r\n"@@ -147,44 +148,54 @@     it "flags encoded keys on every keyed request" $ do       let encoded = Base64.encode "a b"       getRequest (wire "a b") `shouldBe` "mg " <> encoded <> " b v f c\r\n"-      deleteRequest (wire "a b") 0 `shouldBe` "md " <> encoded <> " b\r\n"-      modifyRequest Append (wire "a b") "x" 0 `shouldBe` "ms " <> encoded <> " 1 MA b c\r\nx\r\n"+      deleteRequest (wire "a b") Nothing `shouldBe` "md " <> encoded <> " b\r\n"+      modifyRequest Append (wire "a b") "x" Nothing `shouldBe` "ms " <> encoded <> " 1 MA b c\r\nx\r\n"       getManyRequest (wire "a b") 0 `shouldBe` "mg " <> encoded <> " b v f c q O0\r\n"       setManyRequest (wire "a b") "x" 0 0 0 `shouldBe` "ms " <> encoded <> " 1 F0 T0 MS b c O0\r\nx\r\n"       deleteManyRequest (wire "a b") 0 `shouldBe` "md " <> encoded <> " b O0\r\n"      it "places the binary-key flag after the data length" $-       storeRequest Set (wire "a b") "value" 3 20 0+       storeRequest Set (wire "a b") "value" 3 20 Nothing          `shouldBe` "ms " <> Base64.encode "a b" <> " 5 F3 T20 MS b c\r\nvalue\r\n"      it "encodes store modes and CAS" $ do-      storeRequest Add (wire "key") "v" 1 2 0 `shouldBe` "ms key 1 F1 T2 ME c\r\nv\r\n"-      storeRequest Replace (wire "key") "v" 1 2 5 `shouldBe` "ms key 1 F1 T2 C5 MR c\r\nv\r\n"-      modifyRequest Append (wire "key") "xyz" 5 `shouldBe` "ms key 3 MA C5 c\r\nxyz\r\n"-      modifyRequest Prepend (wire "key") "xyz" 0 `shouldBe` "ms key 3 MP c\r\nxyz\r\n"+      storeRequest Add (wire "key") "v" 1 2 Nothing `shouldBe` "ms key 1 F1 T2 ME c\r\nv\r\n"+      storeRequest Replace (wire "key") "v" 1 2 (Just 5) `shouldBe` "ms key 1 F1 T2 C5 MR c\r\nv\r\n"+      modifyRequest Append (wire "key") "xyz" (Just 5) `shouldBe` "ms key 3 MA C5 c\r\nxyz\r\n"+      modifyRequest Prepend (wire "key") "xyz" Nothing `shouldBe` "ms key 3 MP c\r\nxyz\r\n"       setManyRequest (wire "key") "v" 1 2 5 `shouldBe` "ms key 1 F1 T2 MS c O5\r\nv\r\n"      it "encodes arithmetic with auto-creation" $-      arithmeticRequest Decr (wire "n") 10 2 60 7 `shouldBe` "ma n D2 C7 MD v c N60 J10\r\n"+      arithmeticRequest Decr (wire "n") 2 (Just (10, 60)) (Just 7) `shouldBe` "ma n D2 C7 MD v c N60 J10\r\n" -    it "omits arithmetic defaults at the maximum expiration" $-      arithmeticRequest Incr (wire "key") 0 1 maxBound 0+    it "encodes arithmetic without auto-creation" $+      arithmeticRequest Incr (wire "key") 1 Nothing Nothing       `shouldBe` "ma key D1 MI v c\r\n" -    it "omits zero CAS values" $-      storeRequest Set (wire "key") "v" 0 0 0 `shouldBe` "ms key 1 F0 T0 MS c\r\nv\r\n"+    it "sends the maximum expiration for arithmetic auto-creation" $+      arithmeticRequest Incr (wire "key") 1 (Just (0, maxBound)) Nothing+      `shouldBe` "ma key D1 MI v c N4294967295 J0\r\n" +    it "omits an absent CAS" $+      storeRequest Set (wire "key") "v" 0 0 Nothing `shouldBe` "ms key 1 F0 T0 MS c\r\nv\r\n"++    it "sends a CAS of zero" $ do+      storeRequest Set (wire "key") "v" 0 0 (Just 0) `shouldBe` "ms key 1 F0 T0 C0 MS c\r\nv\r\n"+      modifyRequest Append (wire "key") "v" (Just 0) `shouldBe` "ms key 1 MA C0 c\r\nv\r\n"+      arithmeticRequest Incr (wire "key") 1 Nothing (Just 0) `shouldBe` "ma key D1 C0 MI v c\r\n"+      deleteRequest (wire "key") (Just 0) `shouldBe` "md key C0\r\n"+     -- Most encoders write into a single buffer for speed; check them all     -- against the plainest possible spelling of each request.     prop "encodes every request as the concatenation of its pieces" $       forAll wireKeyGen $ \key ->       forAll requestValueGen $ \value ->-      forAll ((,,) <$> numberGen <*> numberGen <*> numberGen) $ \(flags, expiry, version) ->-      forAll ((,,) <$> numberGen <*> numberGen <*> numberGen) $ \(initial, delta, opaque) ->+      forAll ((,,) <$> numberGen <*> numberGen <*> liftArbitrary numberGen) $ \(flags, expiry, version) ->+      forAll ((,,) <$> liftArbitrary ((,) <$> numberGen <*> numberGen) <*> numberGen <*> numberGen) $ \(create, delta, opaque) ->       forAll ((,) <$> elements [Set, Add, Replace, Append, Prepend] <*> elements [Incr, Decr]) $ \(mode, arith) ->         let keyArgs = wireKey key <> binaryFlag key             binaryFlag k = if wireB64 k then " b" else ""-            casArg n = if n == 0 then "" else " C" <> decimal n+            casArg = maybe "" (\n -> " C" <> decimal n)             decimal :: Show a => a -> B.ByteString             decimal = C.pack . show             modeLetter m = case m of@@ -212,9 +223,9 @@           , modifyRequest mode key value version === B.concat               [ "ms ", wireKey key, " ", decimal (B.length value), " M", modeLetter mode               , binaryFlag key, casArg version, " c\r\n", value, "\r\n" ]-          , arithmeticRequest arith key initial delta expiry version === B.concat+          , arithmeticRequest arith key delta create version === B.concat               [ "ma ", keyArgs, " D", decimal delta, casArg version, " M", arithLetter arith, " v c"-              , if expiry == maxBound then "" else " N" <> decimal expiry <> " J" <> decimal initial+              , maybe "" (\(initial, e) -> " N" <> decimal e <> " J" <> decimal initial) create               , "\r\n" ]           , deleteRequest key version === B.concat ["md ", keyArgs, casArg version, "\r\n"]           , deleteManyRequest key opaque === B.concat ["md ", keyArgs, " O", decimal opaque, "\r\n"]@@ -476,12 +487,14 @@           checkIdle c `shouldThrow` anyIOException    describe "error messages" $ do+    -- Not DiscoveryError, as discovery escapes its message itself.     let everyError detail =           map OpError             [ NoError, ErrKeyNotFound, ErrKeyExists, ErrValueTooLarge             , ErrItemNotStored, ErrValueNonNumeric, ErrOutOfMemory, TextAuthFail ] ++           map ClientError-            [ NoServersReady, Timeout, InvalidAuthentication detail, KeyTooLong detail ] +++            [ NoServersReady, Timeout, InvalidAuthentication detail, InvalidKey detail+            , InvalidArgument detail ] ++           map (ProtocolError . ($ detail))             [ UnknownPkt, UnknownOp, UnknownStatus, BadLength, UnexpectedResponse             , E.ServerError, E.BadCommand, UnexpectedEOF ]@@ -496,10 +509,14 @@         `shouldBe` "memcached operation failed: key not found"       displayException (ClientError NoServersReady)         `shouldBe` "memcache client error: no servers ready"-      displayException (ClientError (KeyTooLong "empty key"))-        `shouldBe` "memcache client error: invalid key or argument: empty key"+      displayException (ClientError (InvalidKey "empty key"))+        `shouldBe` "memcache client error: invalid key: empty key"+      displayException (ClientError (InvalidArgument "stats argument"))+        `shouldBe` "memcache client error: invalid argument: stats argument"       displayException (ProtocolError (UnknownStatus "XX"))         `shouldBe` "memcached protocol error: unknown response code: XX"+      displayException (DiscoveryError "Configuration lists no nodes")+        `shouldBe` "ElastiCache discovery failed: Configuration lists no nodes"      it "describes an empty response line" $       recvResponseFrom "\r\n" `shouldThrow` displays "memcached protocol error: empty response line"@@ -581,6 +598,13 @@       withClient [MR "VA 1 f0 c1 O0\r\na\r\n", Noop, MR "VA 1 f0 c1 O2\r\na\r\n", MR "MN\r\n"] $ \client ->         Client.getMany client ["key", "other", "key"] `shouldReturn` [("key", ("a", 0, 1)), ("key", ("a", 0, 1))] +    it "returns the hits in the order of the keys, across servers" $+      withTwoServerClient+        [MR "VA 2 f0 c1 O0\r\na1\r\n", Noop, MR "VA 2 f0 c5 O4\r\na3\r\n", MR "MN\r\n"]+        [MR "VA 2 f0 c2 O1\r\nb1\r\n", MR "VA 2 f0 c4 O3\r\nb2\r\n", MR "MN\r\n"] $ \_ _ client ->+          Client.getMany client ["a1", "b1", "a2", "b2", "a3"] `shouldReturn`+            [("a1", ("a1", 0, 1)), ("b1", ("b1", 0, 2)), ("b2", ("b2", 0, 4)), ("a3", ("a3", 0, 5))]+     -- A server's sid hashes its host and port, so two servers can have the     -- same sid. They are still two servers, and each gets its own keys.     -- Where the requests went is checked first, as the batch fails if both@@ -782,12 +806,12 @@           [ "version\r\n"           , "ms key 3 F0 T0 MS c O0\r\nold\r\n", "ms key 3 F0 T0 MS c O1\r\nnew\r\n", "mn\r\n" ] -    it "groups results by server, keeping each server's keys in order" $+    it "returns the versions in the order given, across servers" $       withTwoServerClient         [MR "HD c1 O0\r\n", MR "HD c2 O2\r\n", MR "MN\r\n"]         [MR "HD c3 O1\r\n", MR "MN\r\n"] $ \a b client -> do           Client.setMany client [("a1", "x", 0, 0), ("b1", "y", 0, 0), ("a2", "z", 0, 0)]-            `shouldReturn` [("a1", 1), ("a2", 2), ("b1", 3)]+            `shouldReturn` [("a1", 1), ("b1", 3), ("a2", 2)]           mockRequests a `shouldReturn`             [ "version\r\n"             , "ms a1 1 F0 T0 MS c O0\r\nx\r\n", "ms a2 1 F0 T0 MS c O2\r\nz\r\n", "mn\r\n" ]@@ -804,8 +828,8 @@     it "checks every key before sending anything" $       withServerAndClient [MR "HD c1 O0\r\n", MR "MN\r\n"] $ \server client -> do         Client.setMany client [("key", "v", 0, 0), (C.replicate 251 'a', "v", 0, 0)]-          `shouldThrow` isKeyTooLong-        Client.setMany client [("key", "v", 0, 0), ("", "v", 0, 0)] `shouldThrow` isKeyTooLong+          `shouldThrow` isInvalidKey+        Client.setMany client [("key", "v", 0, 0), ("", "v", 0, 0)] `shouldThrow` isInvalidKey         mockRequests server `shouldReturn` []      it "sends nothing for an empty list" $@@ -894,8 +918,8 @@      it "checks every key before sending anything" $       withServerAndClient [MR "HD O0\r\n", MR "MN\r\n"] $ \server client -> do-        Client.deleteMany client ["key", C.replicate 251 'a'] `shouldThrow` isKeyTooLong-        Client.deleteMany client ["key", ""] `shouldThrow` isKeyTooLong+        Client.deleteMany client ["key", C.replicate 251 'a'] `shouldThrow` isInvalidKey+        Client.deleteMany client ["key", ""] `shouldThrow` isInvalidKey         mockRequests server `shouldReturn` []      it "sends nothing for an empty list" $@@ -982,10 +1006,10 @@      it "replaces only when the key exists and the CAS matches" $       withClient [MR "HD c8\r\n", MR "NS\r\n", MR "NF\r\n", MR "EX\r\n"] $ \client -> do-        Client.replace client "key" "v" 0 0 0 `shouldReturn` Just 8-        Client.replace client "key" "v" 0 0 0 `shouldReturn` Nothing-        Client.replace client "key" "v" 0 0 4 `shouldReturn` Nothing-        Client.replace client "key" "v" 0 0 4 `shouldReturn` Nothing+        Client.replace client "key" "v" 0 0 Nothing `shouldReturn` Just 8+        Client.replace client "key" "v" 0 0 Nothing `shouldReturn` Nothing+        Client.replace client "key" "v" 0 0 (Just 4) `shouldReturn` Nothing+        Client.replace client "key" "v" 0 0 (Just 4) `shouldReturn` Nothing      it "compares and swaps" $       withServerAndClient [MR "HD c3\r\n", MR "EX\r\n", MR "NF\r\n"] $ \server client -> do@@ -997,13 +1021,32 @@      it "deletes a present key" $       withClient [MR "HD\r\n"] $ \client ->-        Client.delete client "key" 0 `shouldReturn` True+        Client.delete client "key" Nothing `shouldReturn` True      it "reports a delete of a missing key or with a stale CAS" $       withClient [MR "NF\r\n", MR "EX\r\n"] $ \client -> do-        Client.delete client "key" 0 `shouldReturn` False-        Client.delete client "key" 5 `shouldReturn` False+        Client.delete client "key" Nothing `shouldReturn` False+        Client.delete client "key" (Just 5) `shouldReturn` False +    -- Every version is 0 on a memcached started with -C, so a version of 0+    -- is sent as it is, not taken to mean no check: a cas with it mustn't+    -- become a set.+    it "sends a version of 0 rather than skipping the check" $+      withServerAndClient+        [ MR "EX c0\r\n", MR "EX c0\r\n", MR "HD c5\r\n", MR "HD c6\r\n", MR "EX\r\n"+        , MR "VA 1 c7\r\n1\r\n", MR "VA 1 c8\r\n0\r\n" ] $ \server client -> do+          Client.cas client "key" "v" 0 0 0 `shouldReturn` Nothing+          Client.replace client "key" "v" 0 0 (Just 0) `shouldReturn` Nothing+          Client.append client "key" "v" (Just 0) `shouldReturn` Just 5+          Client.prepend client "key" "v" (Just 0) `shouldReturn` Just 6+          Client.delete client "key" (Just 0) `shouldReturn` False+          Client.increment client "key" 1 Nothing (Just 0) `shouldReturn` Just (1, 7)+          Client.decrement client "key" 1 Nothing (Just 0) `shouldReturn` Just (0, 8)+          mockRequests server `shouldReturn`+            [ "version\r\n", "ms key 1 F0 T0 C0 MS c\r\nv\r\n", "ms key 1 F0 T0 C0 MR c\r\nv\r\n"+            , "ms key 1 MA C0 c\r\nv\r\n", "ms key 1 MP C0 c\r\nv\r\n", "md key C0\r\n"+            , "ma key D1 C0 MI v c\r\n", "ma key D1 C0 MD v c\r\n" ]+     it "does not retry a command the server rejected" $       withClient [MR "CLIENT_ERROR bad\r\n", MR "VA 3 f2 c7\r\nfoo\r\n"] $ \client ->         Client.get client "key" `shouldThrow` isBadCommand@@ -1098,7 +1141,7 @@     -- ready.     it "fails the server over a SERVER_ERROR on the stats reply's first line" $       withServerAndClientOpts-        Client.def { Client.optsServerRetries = 0, Client.optsDeadRetryDelay = 60000 }+        Client.def { Client.optsServerRetries = 0, Client.optsDeadTimeout = 60 }         [MR "SERVER_ERROR x\r\n"] $ \_ client -> do         Client.stats client Nothing `shouldThrow` isServerError         Client.get client "key" `shouldThrow` (== ClientError NoServersReady)@@ -1110,7 +1153,7 @@     it "fails the server over a dump that keys' line breaks take over the entry limit" $ do       let item = "ITEM k" <> B.concat (replicate 90 "\nx") <> " [1 b; 0 s]\r\n"       withServerAndClientOpts-        (slowStats Client.def { Client.optsServerRetries = 0, Client.optsDeadRetryDelay = 60000 })+        (slowStats Client.def { Client.optsServerRetries = 0, Client.optsDeadTimeout = 60 })         [MR (B.concat (replicate 2900 item) <> "END\r\n")] $ \_ client -> do         Client.stats client (Just "cachedump 1 0") `shouldThrow` isBadLength         Client.get client "key" `shouldThrow` (== ClientError NoServersReady)@@ -1153,47 +1196,49 @@      it "returns Nothing when arithmetic cannot create the item" $       withClient [MR "NS\r\n"] $ \client ->-        Client.increment client "counter" 0 1 30 0 `shouldReturn` Nothing+        Client.increment client "counter" 1 (Just (0, 30)) Nothing `shouldReturn` Nothing      it "returns Nothing for arithmetic on a missing key it may not create, or with a stale CAS" $-      withClient [MR "NF\r\n", MR "EX\r\n"] $ \client -> do-        Client.increment client "counter" 0 1 maxBound 0 `shouldReturn` Nothing-        Client.decrement client "counter" 0 1 0 5 `shouldReturn` Nothing+      withServerAndClient [MR "NF\r\n", MR "EX\r\n"] $ \server client -> do+        Client.increment client "counter" 1 Nothing Nothing `shouldReturn` Nothing+        Client.decrement client "counter" 1 (Just (0, 0)) (Just 5) `shouldReturn` Nothing+        mockRequests server `shouldReturn`+          ["version\r\n", "ma counter D1 MI v c\r\n", "ma counter D1 C5 MD v c N0 J0\r\n"]      it "returns the new counter value and CAS" $       withServerAndClient [MR "VA 1 c2\r\n0\r\n"] $ \server client -> do-        Client.decrement client "counter" 10 1 60 0 `shouldReturn` Just (0, 2)+        Client.decrement client "counter" 1 (Just (10, 60)) Nothing `shouldReturn` Just (0, 2)         mockRequests server `shouldReturn` ["version\r\n", "ma counter D1 MD v c N60 J10\r\n"]      it "reads a malformed counter value as zero" $       withClient [MR "VA 4 c3\r\n(42)\r\n"] $ \client ->-        Client.increment client "counter" 0 1 0 0 `shouldReturn` Just (0, 3)+        Client.increment client "counter" 1 (Just (0, 0)) Nothing `shouldReturn` Just (0, 3)      it "reports arithmetic on a non-numeric value" $       withClient [MR "CLIENT_ERROR cannot increment or decrement non-numeric value\r\n"] $ \client ->-        Client.increment client "key" 0 1 0 0 `shouldThrow` (== OpError ErrValueNonNumeric)+        Client.increment client "key" 1 (Just (0, 0)) Nothing `shouldThrow` (== OpError ErrValueNonNumeric)      it "returns Nothing appending to a missing key" $       withClient [MR "NS\r\n"] $ \client ->-        Client.append client "key" "more" 0 `shouldReturn` Nothing+        Client.append client "key" "more" Nothing `shouldReturn` Nothing      it "prepends to an existing key" $       withServerAndClient [MR "HD c4\r\n"] $ \server client -> do-        Client.prepend client "key" "pre" 0 `shouldReturn` Just 4+        Client.prepend client "key" "pre" Nothing `shouldReturn` Just 4         mockRequests server `shouldReturn` ["version\r\n", "ms key 3 MP c\r\npre\r\n"]      it "appends only when the key exists and the CAS matches" $       withServerAndClient [MR "HD c6\r\n", MR "EX c0\r\n", MR "NS c0\r\n"] $ \server client -> do-        Client.append client "key" "more" 5 `shouldReturn` Just 6-        Client.append client "key" "more" 5 `shouldReturn` Nothing-        Client.append client "key" "more" 5 `shouldReturn` Nothing+        Client.append client "key" "more" (Just 5) `shouldReturn` Just 6+        Client.append client "key" "more" (Just 5) `shouldReturn` Nothing+        Client.append client "key" "more" (Just 5) `shouldReturn` Nothing         mockRequests server `shouldReturn` "version\r\n" : replicate 3 "ms key 4 MA C5 c\r\nmore\r\n"      it "prepends only when the key exists and the CAS matches" $       withServerAndClient [MR "HD c6\r\n", MR "EX c0\r\n", MR "NS c0\r\n"] $ \server client -> do-        Client.prepend client "key" "pre" 5 `shouldReturn` Just 6-        Client.prepend client "key" "pre" 5 `shouldReturn` Nothing-        Client.prepend client "key" "pre" 5 `shouldReturn` Nothing+        Client.prepend client "key" "pre" (Just 5) `shouldReturn` Just 6+        Client.prepend client "key" "pre" (Just 5) `shouldReturn` Nothing+        Client.prepend client "key" "pre" (Just 5) `shouldReturn` Nothing         mockRequests server `shouldReturn` "version\r\n" : replicate 3 "ms key 3 MP C5 c\r\npre\r\n"      it "flushes" $@@ -1226,7 +1271,7 @@     it "reports a counter the server ran out of memory creating as a status, sending it once" $       withServerAndClient [MR "SERVER_ERROR Out of memory allocating new item\r\n", MR "VA 3 f2 c7\r\nfoo\r\n"] $         \server client -> do-          Client.increment client "counter" 0 1 0 0 `shouldThrow` (== OpError ErrOutOfMemory)+          Client.increment client "counter" 1 (Just (0, 0)) Nothing `shouldThrow` (== OpError ErrOutOfMemory)           Client.get client "key" `shouldReturn` Just ("foo", 2, 7)           mockRequests server `shouldReturn`             ["version\r\n", "ma counter D1 MI v c N0 J0\r\n", "version\r\n", "mg key v f c\r\n"]@@ -1245,10 +1290,10 @@     forM_       [ ("set", \c v -> void (Client.set c "key" v 0 0))       , ("add", \c v -> void (Client.add c "key" v 0 0))-      , ("replace", \c v -> void (Client.replace c "key" v 0 0 0))+      , ("replace", \c v -> void (Client.replace c "key" v 0 0 Nothing))       , ("cas", \c v -> void (Client.cas c "key" v 0 0 1))-      , ("append", \c v -> void (Client.append c "key" v 0))-      , ("prepend", \c v -> void (Client.prepend c "key" v 0)) ] $ \(operation, run) ->+      , ("append", \c v -> void (Client.append c "key" v Nothing))+      , ("prepend", \c v -> void (Client.prepend c "key" v Nothing)) ] $ \(operation, run) ->       it ("rejects an over-limit value from " <> operation <> " without sending anything") $ \over ->         withRefusingClient Client.def $ \client ->           run client over `shouldThrow` (== OpError ErrValueTooLarge)@@ -1271,6 +1316,32 @@         Client.set client "key" (B.take valueLimit over) 0 0           `shouldThrow` (== ClientError NoServersReady) +  -- Every connection attempt is refused, as for oversized values, so an+  -- operation that sent its request would throw "Connection refused" instead.+  describe "oversized expirations" $ do+    forM_+      [ ("set", \c e -> void (Client.set c "key" "v" 0 e))+      , ("setMany", \c e -> void (Client.setMany c [("one", "v", 0, 0), ("two", "v", 0, e)]))+      , ("add", \c e -> void (Client.add c "key" "v" 0 e))+      , ("replace", \c e -> void (Client.replace c "key" "v" 0 e Nothing))+      , ("cas", \c e -> void (Client.cas c "key" "v" 0 e 1))+      , ("touch", \c e -> void (Client.touch c "key" e))+      , ("gat", \c e -> void (Client.gat c "key" e))+      , ("increment", \c e -> void (Client.increment c "key" 1 (Just (0, e)) Nothing))+      , ("decrement", \c e -> void (Client.decrement c "key" 1 (Just (0, e)) Nothing))+      , ("flush", \c e -> Client.flush c (Just e)) ] $ \(operation, run) ->+      it ("rejects an expiration over 2147483647 from " <> operation <> " without sending anything") $+        withRefusingClient Client.def $ \client ->+          forM_ [2147483648, maxBound] $ \e ->+            run client e `shouldThrow` (== ClientError (InvalidArgument "expiration exceeds 2147483647"))++    it "sends an expiration of 2147483647" $+      withServerAndClient [MR "HD c1\r\n", MR "OK\r\n"] $ \server client -> do+        Client.set client "key" "v" 0 2147483647 `shouldReturn` 1+        Client.flush client (Just 2147483647)+        mockRequests server `shouldReturn`+          ["version\r\n", "ms key 1 F0 T2147483647 MS c\r\nv\r\n", "flush_all 2147483647\r\n"]+   -- A reply the request cannot get is likely an earlier request's, so the   -- connection must be closed. Kept, it would answer the next request with   -- the stale reply scripted after it, such as "VA 3 f9 c9\r\nold\r\n".@@ -1289,14 +1360,14 @@       , ("a touch", "TOUCH", "OK\r\n", \c -> void (Client.touch c "key" 0))       , ("a set", "SET", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.set c "key" "v" 0 0))       , ("an add", "ADD", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.add c "key" "v" 0 0))-      , ("a replace", "REPLACE", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.replace c "key" "v" 0 0 0))+      , ("a replace", "REPLACE", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.replace c "key" "v" 0 0 Nothing))       , ("a cas", "SET", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.cas c "key" "v" 0 0 1))-      , ("an append", "APPEND", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.append c "key" "v" 0))-      , ("a prepend", "PREPEND", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.prepend c "key" "v" 0))-      , ("an increment", "INCREMENT", "HD c1\r\n", \c -> void (Client.increment c "key" 0 1 0 0))-      , ("a decrement", "DECREMENT", "HD c1\r\n", \c -> void (Client.decrement c "key" 0 1 0 0))-      , ("a delete", "DELETE", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.delete c "key" 0))-      , ("a delete", "DELETE", "EN\r\n", \c -> void (Client.delete c "key" 0))+      , ("an append", "APPEND", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.append c "key" "v" Nothing))+      , ("a prepend", "PREPEND", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.prepend c "key" "v" Nothing))+      , ("an increment", "INCREMENT", "HD c1\r\n", \c -> void (Client.increment c "key" 1 (Just (0, 0)) Nothing))+      , ("a decrement", "DECREMENT", "HD c1\r\n", \c -> void (Client.decrement c "key" 1 (Just (0, 0)) Nothing))+      , ("a delete", "DELETE", "VA 1 f0 c1\r\nx\r\n", \c -> void (Client.delete c "key" Nothing))+      , ("a delete", "DELETE", "EN\r\n", \c -> void (Client.delete c "key" Nothing))       , ("a flush", "FLUSH", "HD\r\n", (`Client.flush` Nothing))       , ("a version", "VERSION", "OK\r\n", void . Client.version) ] $       \(request, operation, reply, run) -> do@@ -1315,7 +1386,7 @@         [MR "VALUE key 0 3\r\nfoo\r\nEND\r\n", MR "HD c9\r\n", MR "NF\r\n", MR "EN\r\n"] $ \server client -> do           Client.get client "a" `shouldThrow` (== ProtocolError (UnknownStatus "VALUE"))           Client.set client "b" "v" 0 0 `shouldReturn` 9-          Client.delete client "c" 0 `shouldReturn` False+          Client.delete client "c" Nothing `shouldReturn` False           Client.get client "d" `shouldReturn` Nothing           mockRequests server `shouldReturn`             [ "version\r\n", "mg a v f c\r\n"@@ -1326,7 +1397,7 @@     it "takes OK as success for stores and deletes" $       withClient [MR "OK c5\r\n", MR "OK\r\n"] $ \client -> do         Client.set client "key" "v" 0 0 `shouldReturn` 5-        Client.delete client "key" 0 `shouldReturn` True+        Client.delete client "key" Nothing `shouldReturn` True      -- These take any command, such as the classic delete, which gets DELETED.     it "returns any reply but an error from keyedOp, anyOp and allOp" $@@ -1339,18 +1410,18 @@    describe "retries and failover" $ do     let fast = Client.def-          { Client.optsServerTimeout = 300-          , Client.optsFailRetryDelay = 10-          , Client.optsDeadRetryDelay = 300+          { Client.optsTimeout = 0.3+          , Client.optsRetryDelay = 0.01+          , Client.optsDeadTimeout = 0.3           }         -- A server marked dead stays dead for the rest of the test.-        fastStaysDead = fast { Client.optsDeadRetryDelay = 60000 }+        fastStaysDead = fast { Client.optsDeadTimeout = 60 }         -- Options for the attempts helper below. Each attempt fails as soon         -- as the mock drops its connection; its 5 s are only so that a slow         -- machine can't turn the drop into a timeout.-        dropping = fastStaysDead { Client.optsServerTimeout = 5000 }+        dropping = fastStaysDead { Client.optsTimeout = 5 }         withRetries n = dropping { Client.optsServerRetries = n }-        -- Up to three connections to the server, rather than one.+        -- Up to three connections to the server.         threeConnections opts = opts           { Client.optsServerOptions = Client.defaultServerOptions { Client.soNumResources = 3 } }         -- Leave three connections idle in the pool, each closed by the mock,@@ -1472,6 +1543,53 @@         mockRequests server `shouldReturn` ["version\r\n", "mn\r\n", "version\r\n", "mn\r\n"]         readIORef (Server.failed s) `shouldReturn` 0 +    -- The resolver ignores asynchronous exceptions until let go (after 5 s at+    -- most). Run as connecting runs, masked and holding a slot, the attempt+    -- must still time out on time, as a server failure.+    it "times out an attempt whose host lookup can't be interrupted" $+      withServerAndClientOpts oneAttempt { Client.optsTimeout = 0.3 } [Noop] $ \_ client -> do+        [s] <- toList <$> Cluster.getServers client+        hostLookup <- newLookup+        held <- newEmptyMVar+        finished <- newEmptyMVar+        let resolve _ _ _ = uninterruptibleMask_ (readMVar held) >> putMVar finished () >> return []+            connecting s' = Server.withSocket s' $ \_ -> mask_ (addressesOf hostLookup resolve "memcached.test" "11211")+        release <- forkIO $ threadDelay 5000000 >> void (tryPutMVar held ())+        start <- getMonotonicTime+        Cluster.allOp' client connecting `shouldThrow` (== ClientError Timeout)+        end <- getMonotonicTime+        (end - start) `shouldSatisfy` (< 2)+        readIORef (Server.failed s) >>= (`shouldNotBe` 0)+        void (tryPutMVar held ())+        killThread release+        timeout 1000000 (takeMVar finished) `shouldReturn` Just ()++    -- An attempt that finds a lookup left running by a timeout waits for it.+    it "waits for the host lookup that a timed-out attempt left running" $ do+      hostLookup <- newLookup+      calls <- newIORef (0 :: Int)+      held <- newEmptyMVar+      let resolve _ _ _ = atomicModifyIORef' calls (\n -> (n + 1, ())) >> readMVar held >> return []+          lookUp = addressesOf hostLookup resolve "memcached.test" "11211"+      timeout 100000 lookUp `shouldReturn` Nothing+      waiting <- async lookUp+      timeout 1000000 (waitUntilBlocked waiting) `shouldReturn` Just ()+      putMVar held ()+      timeout 1000000 (wait waiting) `shouldReturn` Just []+      readIORef calls `shouldReturn` 1++    -- A failed lookup's error reaches its waiters and isn't kept.+    it "rethrows the error of a host lookup that fails, then looks it up again" $ do+      hostLookup <- newLookup+      firstCall <- newIORef True+      let resolve _ _ _ = do+            first <- atomicModifyIORef' firstCall (False,)+            if first then ioError (userError "no such host") else return []+          lookUp = addressesOf hostLookup resolve "memcached.test" "11211"+      timeout 1000000 (try lookUp)+        `shouldReturn` Just (Left (userError "no such host") :: Either IOError [N.AddrInfo])+      timeout 1000000 lookUp `shouldReturn` Just []+     -- Each attempt runs with asynchronous exceptions as the caller has them:     -- a caller that masks them gets every attempt masked, and one that     -- doesn't, none. The first attempt fails as the mock drops its@@ -1562,7 +1680,7 @@     -- reads. The mock serves one connection at a time: it answers that     -- thread once it has sent the late reply, 250 ms after the get gives up.     it "doesn't hand the connection of a request that timed out to a waiting thread" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 500 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 0.5 })         [DelayMS 750 (MR "VA 3 f9 c9\r\nold\r\n"), MR "VA 3 f2 c7\r\nfoo\r\n"] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           timingOut <- async $ Client.get client "key"@@ -1589,7 +1707,7 @@           [DelayMS 300 CloseConnection], ["version\r\n", "mg key v f c\r\n"], isUnexpectedEOF)       ] $ \(request, run, replies, requests, failure) ->       it ("doesn't hand the connection of " <> request <> " to a waiting thread") $-        withServerAndClientOpts oneAttempt (replies ++ [MR "VA 3 f2 c7\r\nfoo\r\n"]) $ \server client -> do+        withServerAndClientOpts (oneConnection oneAttempt) (replies ++ [MR "VA 3 f2 c7\r\nfoo\r\n"]) $ \server client -> do           [s] <- toList <$> Cluster.getServers client           failing <- async $ run client           waitForRequests server (length requests) `shouldReturn` requests@@ -1605,12 +1723,12 @@     -- The holder lets go after 3 s at the latest, so a wait with no limit     -- fails the test rather than hanging it.     forM_-      [ ("a request", \c -> void (Client.delete c "key" 0), [MR "HD\r\n"], ["md key\r\n"])+      [ ("a request", \c -> void (Client.delete c "key" Nothing), [MR "HD\r\n"], ["md key\r\n"])       , ("a batch", \c -> void (Client.getMany c ["key"]), [Noop, MR "MN\r\n"], ["mg key v f c q O0\r\n", "mn\r\n"])       , ("stats", \c -> void (Client.stats c Nothing), [MR "END\r\n"], ["stats\r\n"])       ] $ \(operation, run, replies, requests) ->       it ("doesn't mark a server dead when " <> operation <> " times out waiting for its only connection") $-        withServerAndClientOpts fastStaysDead replies $ \server client -> do+        withServerAndClientOpts (oneConnection fastStaysDead) replies $ \server client -> do           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar           done <- newEmptyMVar@@ -1631,17 +1749,17 @@     -- An attempt that runs out of time before it holds a slot never reached     -- the server, so unlike a server failure it closes no idle connection.     -- With one stripe, an attempt waits only while every slot is taken, so-    -- none is idle then. But with optsServerTimeout = 0, every attempt runs+    -- none is idle then. But with optsTimeout = 0, every attempt runs     -- out of time before it starts. Here the client with that timeout shares     -- the server with one that has left a connection idle in the pool. If-    -- optsServerTimeout = 0 is ever given another meaning, this test needs+    -- optsTimeout = 0 is ever given another meaning, this test needs     -- another way to reach that path.     it "doesn't close the idle connections when a request runs out of time before it gets one" $       withServerAndClientOpts fastStaysDead [Noop] $ \_ client -> do         servers <- Cluster.getServers client         [s] <- return (toList servers)         idle <- Server.withSocket s return-        impatient <- Client.newClient [] fastStaysDead { Client.optsServerTimeout = 0 }+        impatient <- Client.newClient [] fastStaysDead { Client.optsTimeout = 0 }         Client.get (Cluster.setServers impatient (Right servers)) "key"           `shouldThrow` (== ClientError Timeout)         readIORef (Server.failed s) `shouldReturn` 0@@ -1714,13 +1832,13 @@     -- against the server although it waited first: its only attempt marks     -- the server dead.     it "marks a server dead when a request that waited for its connection times out using it" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0 } [Noop, Noop] $ \server client -> do+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsServerRetries = 0 }) [Noop, Noop] $ \server client -> do         [s] <- toList <$> Cluster.getServers client         held <- newEmptyMVar         release <- newEmptyMVar         holder <- async $ Server.withSocket s $ \_ -> putMVar held () >> takeMVar release         takeMVar held-        deleting <- async $ Client.delete client "key" 0+        deleting <- async $ Client.delete client "key" Nothing         waitUntilBlocked deleting         putMVar release ()         wait holder@@ -1734,14 +1852,14 @@     -- the connection, and its only attempt marks the server dead. With a new     -- 1 s once it had the connection, it would get the reply.     it "counts the wait for the connection towards the attempt's timeout" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 1000 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 1 })         [DelayMS 800 (MR "HD\r\n")] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar           release <- newEmptyMVar           holder <- async $ Server.withSocket s $ \_ -> putMVar held () >> takeMVar release           takeMVar held-          deleting <- async $ Client.delete client "key" 0+          deleting <- async $ Client.delete client "key" Nothing           waitUntilBlocked deleting           threadDelay 500000           putMVar release ()@@ -1757,7 +1875,7 @@     -- marks the server dead. The mock may read the batch's mn once that     -- reply is sent.     it "counts the wait for the connection towards the timeout of a batch's first reply" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 1000 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 1 })         [DelayMS 800 (MR "VA 1 c1 O0\r\na\r\n"), MR "MN\r\n"] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar@@ -1795,7 +1913,7 @@           ["md one O0\r\n", "md two O1\r\n", "md three O2\r\n"])       ] $ \(operation, run, replies, requests) ->       it ("gives each reply to a " <> operation <> " batch a timeout of its own") $-        withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 500 }+        withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 0.5 }           (map (DelayMS 200 . MR) (replies ++ ["MN\r\n"])) $ \server client -> do             [s] <- toList <$> Cluster.getServers client             run client@@ -1810,7 +1928,7 @@     -- the mock reading, so the attempt times out rather than reading the end     -- of the connection.     it "times out a batch whose next reply never comes, a timeout after the reply before it" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 500 }+      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 0.5 }         [DelayMS 200 (MR "VA 1 c1 O0\r\na\r\n"), Noop, Noop, Noop] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           start <- getMonotonicTime@@ -1826,7 +1944,7 @@     -- a byte at a time, 250 ms apart, as the mock reads each of the batch's     -- later requests: it would take 1 s, twice the reply's 500 ms.     it "times out a batch reply that trickles in for longer than its timeout" $-      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsServerTimeout = 500 }+      withServerAndClientOpts fastStaysDead { Client.optsServerRetries = 0, Client.optsTimeout = 0.5 }         (MR "VA 4 c1 O0\r\n" : replicate 3 (DelayMS 250 (MR "x")) ++ [DelayMS 250 (MR "x\r\nMN\r\n")]) $         \_ client ->           timeout 5000000 (Client.getMany client ["one", "two", "three", "four"])@@ -1837,17 +1955,17 @@     -- thread holds for 800 ms. The second attempt starts 1 s later, gets the     -- connection, and the mock drops it.     it "marks a server dead when a wait timeout is followed by a server failure" $-      withServerAndClientOpts fastStaysDead { Client.optsFailRetryDelay = 1000 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsRetryDelay = 1 })         [CloseConnection] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar           holder <- async $ Server.withSocket s $ \_ -> putMVar held () >> threadDelay 800000           takeMVar held-          Client.delete client "key" 0 `shouldThrow` isUnexpectedEOF+          Client.delete client "key" Nothing `shouldThrow` isUnexpectedEOF           wait holder           mockRequests server `shouldReturn` ["version\r\n", "md key\r\n"]           readIORef (Server.failed s) >>= (`shouldNotBe` 0)-          Client.delete client "key" 0 `shouldThrow` (== ClientError NoServersReady)+          Client.delete client "key" Nothing `shouldThrow` (== ClientError NoServersReady)      -- The first attempt fails after 300 ms, as the mock drops its connection     -- or its time runs out: a server failure either way. Another thread,@@ -1855,7 +1973,7 @@     -- touch has given up. The second attempt starts 300 ms later and times     -- out waiting. A touch can be sent again; a delete would not be.     it "doesn't mark a server dead when a server failure is followed by a wait timeout" $-      withServerAndClientOpts fastStaysDead { Client.optsFailRetryDelay = 300 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsRetryDelay = 0.3 })         [DelayMS 300 CloseConnection, MR "HD\r\n"] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           touching <- async $ Client.touch client "key" 0@@ -1880,7 +1998,7 @@     -- the server isn't marked dead. A touch can be sent again; a delete     -- would not be.     it "doesn't mark a server dead when retries clear a burst queued for its only connection" $-      withServerAndClientOpts fastStaysDead { Client.optsServerTimeout = 600 }+      withServerAndClientOpts (oneConnection fastStaysDead { Client.optsTimeout = 0.6 })         (repeat (DelayMS 90 (MR "HD\r\n"))) $ \_ client -> do           results <- mapConcurrently             (\i -> try @MemcacheError (Client.touch client (C.pack (show i)) 0)) [1 .. 8 :: Int]@@ -1899,7 +2017,7 @@         ([DelayMS 300 CloseConnection] ++ authExchange ++ [supported, MR "VA 3 f0 c1\r\nfoo\r\n"]) $ \server -> do           let spec = (mockServerSpec server) { ssAuth = Auth.Auth "user" "pass" }           client <- Client.newClient [spec]-            Client.def { Client.optsServerRetries = 0, Client.optsServerTimeout = 3000 }+            (oneConnection Client.def { Client.optsServerRetries = 0, Client.optsTimeout = 3 })           first <- async $ Client.get client "key"           waitForRequests server 1 `shouldReturn` ["version\r\n"]           second <- async $ Client.get client "key"@@ -1917,7 +2035,7 @@         ([Noop] ++ authExchange ++ [supported, MR "VA 3 f0 c1\r\nfoo\r\n"]) $ \server -> do           let spec = (mockServerSpec server) { ssAuth = Auth.Auth "user" "pass" }           client <- Client.newClient [spec]-            Client.def { Client.optsServerRetries = 0, Client.optsServerTimeout = 3000 }+            (oneConnection Client.def { Client.optsServerRetries = 0, Client.optsTimeout = 3 })           first <- async $ Client.get client "key"           waitForRequests server 1 `shouldReturn` ["version\r\n"]           second <- async $ Client.get client "key"@@ -1942,7 +2060,7 @@         , authExchange ++ [supported, MR "VA 3 f0 c1\r\nfoo\r\n"] ] $ \server -> do           let spec = (mockServerSpec server) { ssAuth = Auth.Auth "user" "pass" }           client <- Client.newClient [spec] Client.def-            { Client.optsServerRetries = 0, Client.optsServerTimeout = 3000+            { Client.optsServerRetries = 0, Client.optsTimeout = 3             , Client.optsServerOptions = Client.defaultServerOptions { Client.soNumResources = 2 } }           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar@@ -1969,7 +2087,7 @@         , MR "CLIENT_ERROR unauthenticated\r\n", MR "CLIENT_ERROR authentication failure\r\n" ] $ \server -> do           let spec = (mockServerSpec server) { ssAuth = Auth.Auth "user" "pass" }           client <- Client.newClient [spec]-            Client.def { Client.optsServerRetries = 0, Client.optsServerTimeout = 3000 }+            (oneConnection Client.def { Client.optsServerRetries = 0, Client.optsTimeout = 3 })           first <- async $ Client.get client "key"           waitForRequests server 1 `shouldReturn` ["version\r\n"]           second <- async $ Client.get client "key"@@ -2017,7 +2135,7 @@     -- matched. Sent once, it throws the failure instead.     it "doesn't report an append with a version that may have been carried out as a mismatch" $       withServerAndClientOpts fastStaysDead [Noop, MR "EX c0\r\n"] $ \server client -> do-        Client.append client "key" "v" 9 `shouldThrow` (== ClientError Timeout)+        Client.append client "key" "v" (Just 9) `shouldThrow` (== ClientError Timeout)         mockRequests server `shouldReturn` ["version\r\n", "ms key 1 MA C9 c\r\nv\r\n"]      -- A reply that can't be read, such as one whose value length is@@ -2027,7 +2145,7 @@       it ("doesn't send " <> name <> " again after a reply with a malformed value length") $         withServerAndClientOpts fastStaysDead [MR "VA (1) c5\r\n6\r\n", MR "VA 1 c5\r\n6\r\n"] $ \server client -> do           [s] <- toList <$> Cluster.getServers client-          arith client "key" 0 1 0 0 `shouldThrow` isBadLength+          arith client "key" 1 (Just (0, 0)) Nothing `shouldThrow` isBadLength           map (== "version\r\n") <$> mockRequests server `shouldReturn` [True, False]           readIORef (Server.failed s) >>= (`shouldNotBe` 0) @@ -2057,7 +2175,7 @@               N.sendAll connection ("VERSION " <> supportedVersion <> "\r\n")         bracket (forkIO takeAll) killThread $ \_ -> flip finally (readIORef accepted >>= mapM_ N.close) $ do           client <- Client.newClient [ServerSpec "127.0.0.1" (show port) Auth.NoAuth] fastStaysDead-          Client.append client "key" (C.replicate (32 * 1024 * 1024) 'x') 0+          Client.append client "key" (C.replicate (32 * 1024 * 1024) 'x') Nothing             `shouldThrow` (== ClientError Timeout)           [s] <- toList <$> Cluster.getServers client           readIORef (Server.failed s) >>= (`shouldNotBe` 0)@@ -2084,7 +2202,7 @@       it ("retries " <> name <> " whose connection was refused") $         withBoundSocketReuseAddr loopbackAddress $ \port -> do           let spec = ServerSpec "127.0.0.1" (show port) Auth.NoAuth-          client <- Client.newClient [spec] fastStaysDead { Client.optsFailRetryDelay = 500 }+          client <- Client.newClient [spec] fastStaysDead { Client.optsRetryDelay = 0.5 }           running <- async $ run client           threadDelay 100000           withMockMemcachedAt supportedVersion (atPort port loopbackAddress) [MR reply] $ \server -> do@@ -2097,7 +2215,7 @@       -- attempt runs out of its 300 ms waiting for it, and the retry, 10 ms       -- later, gets it.       it ("retries " <> name <> " that ran out of time waiting for its connection") $-        withServerAndClientOpts fastStaysDead [MR reply] $ \server client -> do+        withServerAndClientOpts (oneConnection fastStaysDead) [MR reply] $ \server client -> do           [s] <- toList <$> Cluster.getServers client           held <- newEmptyMVar           holder <- async $ Server.withSocket s $ \_ -> putMVar held () >> threadDelay 450000@@ -2152,7 +2270,7 @@           [CloseConnection, CloseConnection, CloseConnection, MR "VA 1 c5\r\n6\r\n"] $ \server client -> do             [s] <- toList <$> Cluster.getServers client             leaveThree s-            Client.increment client "key" 0 1 0 0 `shouldReturn` Just (6, 5)+            Client.increment client "key" 1 (Just (0, 0)) Nothing `shouldReturn` Just (6, 5)             readIORef (Server.failed s) `shouldReturn` 0             mockRequests server `shouldReturn`               replicate 3 "version\r\n" ++ replicate 3 "mn\r\n" ++ ["version\r\n", "ma key D1 MI v c N0 J0\r\n"]@@ -2169,7 +2287,7 @@         [s] <- toList <$> Cluster.getServers client         Server.withSocket s $ \c -> sendRaw c "mn\r\n" >> void (recvResponse c)         timeout 5000000 (takeMVar reset) `shouldReturn` Just ()-        Client.increment client "key" 0 1 0 0 `shouldReturn` Just (6, 5)+        Client.increment client "key" 1 (Just (0, 0)) Nothing `shouldReturn` Just (6, 5)         readIORef (Server.failed s) `shouldReturn` 0         mockRequests server `shouldReturn`           ["version\r\n", "mn\r\n", "version\r\n", "ma key D1 MI v c N0 J0\r\n"]@@ -2186,7 +2304,7 @@         waitForRequests server 2 `shouldReturn` ["version\r\n", "mn\r\n"]         -- The mock sends MN once it has recorded the request.         threadDelay 100000-        Client.increment client "key" 0 1 0 0 `shouldReturn` Just (6, 5)+        Client.increment client "key" 1 (Just (0, 0)) Nothing `shouldReturn` Just (6, 5)         readIORef (Server.failed s) `shouldReturn` 0         mockRequests server `shouldReturn`           ["version\r\n", "mn\r\n", "version\r\n", "ma key D1 MI v c N0 J0\r\n"]@@ -2200,7 +2318,7 @@       withServerAndClientOpts fast [MR "MN\r\nMN\r\n", MR "VA 1 c5\r\n6\r\n"] $ \server client -> do         [s] <- toList <$> Cluster.getServers client         Server.withSocket s $ \c -> sendRaw c "mn\r\n" >> void (recvResponse c)-        Client.increment client "key" 0 1 0 0 `shouldReturn` Just (6, 5)+        Client.increment client "key" 1 (Just (0, 0)) Nothing `shouldReturn` Just (6, 5)         readIORef (Server.failed s) `shouldReturn` 0         mockClosed server `shouldReturn` 1         mockRequests server `shouldReturn`@@ -2214,7 +2332,7 @@       withServerAndClientOpts (threeConnections dropping)         [DelayMS 300 CloseConnection, Noop] $ \server client -> do           [s] <- toList <$> Cluster.getServers client-          failing <- async $ Client.increment client "key" 0 1 0 0+          failing <- async $ Client.increment client "key" 1 (Just (0, 0)) Nothing           waitForRequests server 2 `shouldReturn` ["version\r\n", "ma key D1 MI v c N0 J0\r\n"]           idle <- Server.withSocket s return           wait failing `shouldThrow` isUnexpectedEOF@@ -2229,7 +2347,7 @@       withServerAndClientOpts (threeConnections dropping)         [DelayMS 300 (MR "SERVER_ERROR backend failure\r\n"), Noop] $ \server client -> do           [s] <- toList <$> Cluster.getServers client-          failing <- async $ Client.increment client "key" 0 1 0 0+          failing <- async $ Client.increment client "key" 1 (Just (0, 0)) Nothing           waitForRequests server 2 `shouldReturn` ["version\r\n", "ma key D1 MI v c N0 J0\r\n"]           idle <- Server.withSocket s return           wait failing `shouldThrow` (== ProtocolError (E.ServerError "backend failure"))@@ -2279,7 +2397,7 @@      it "closeAll closes a connection in use instead of handing it to a waiting thread" $       withMockMemcached supportedVersion [Noop, Noop] $ \server -> do-        s <- Server.newServerDefault Server.defaultServerOptions (mockServerSpec server)+        s <- Server.newServerDefault (Client.optsServerOptions (oneConnection Client.def)) (mockServerSpec server)         held <- newEmptyMVar         release <- newEmptyMVar         first <- async $ Server.withSocket s $ \c -> putMVar held c >> takeMVar release@@ -2324,6 +2442,22 @@         cancel interrupted         Client.get client "key" `shouldReturn` Just ("foo", 2, 7) +    -- soKeepAlive is in seconds: the pool closes a connection once it has+    -- been idle that long, up to a second later.+    it "closes a connection that has been idle for soKeepAlive" $+      withSilentListener $ \port idleClosed firstClosed -> do+        let opts = Client.def+              { Client.optsServerOptions = Client.defaultServerOptions { Client.soKeepAlive = 0.5 } }+        client <- Client.newClient [ServerSpec "127.0.0.1" (show port) Auth.NoAuth] opts+        [s] <- toList <$> Cluster.getServers client+        start <- getMonotonicTime+        Server.withSocket s (const (return ()))+        timeout 5000000 (takeMVar firstClosed) `shouldReturn` Just ()+        end <- getMonotonicTime+        (end - start) `shouldSatisfy` (>= 0.5)+        idleClosed `shouldReturn` 1+        keepReachable client+     -- A failed attempt closes the server's idle connections. A cancel that     -- arrives meanwhile must end the operation, not be lost so that it     -- retries, and must not leave any of them open. Here a listener takes@@ -2341,8 +2475,8 @@       withOpenFiles 1100 $ replicateM_ 3 $ withSilentListener $ \port idleClosed firstClosed -> do         let idle = 500             opts = Client.def-              { Client.optsServerTimeout = 200-              , Client.optsFailRetryDelay = 3000+              { Client.optsTimeout = 0.2+              , Client.optsRetryDelay = 3               , Client.optsServerOptions = Client.defaultServerOptions { Client.soNumResources = idle + 1 } }         client <- Client.newClient [ServerSpec "127.0.0.1" (show port) Auth.NoAuth] opts         [s] <- toList <$> Cluster.getServers client@@ -2496,17 +2630,17 @@         Auth.authenticate connection Auth.NoAuth `shouldReturn` ()      it "validates credential delimiters" $ do-      Auth.validateCredentials "user" "pass" `shouldBe` Right ()+      validateCredentials "user" "pass" `shouldBe` Right ()       -- memcached's auth file splits each line at its first ':'.-      Auth.validateCredentials "user" "pa:ss" `shouldBe` Right ()+      validateCredentials "user" "pa:ss" `shouldBe` Right ()       -- memcached splits the credentials it is sent at spaces only, and its       -- auth file ends a password only at CR, LF or NUL, so a tab is part of       -- either.-      Auth.validateCredentials "us\ter" "pass" `shouldBe` Right ()-      Auth.validateCredentials "user" "pa\tss" `shouldBe` Right ()-      mapM_ (\c -> Auth.validateCredentials ("us" <> c <> "er") "pass" `shouldSatisfy` isLeft)+      validateCredentials "us\ter" "pass" `shouldBe` Right ()+      validateCredentials "user" "pa\tss" `shouldBe` Right ()+      mapM_ (\c -> validateCredentials ("us" <> c <> "er") "pass" `shouldSatisfy` isLeft)         [" ", "\r", "\n", "\0", ":"]-      mapM_ (\c -> Auth.validateCredentials "user" ("pa" <> c <> "ss") `shouldSatisfy` isLeft)+      mapM_ (\c -> validateCredentials "user" ("pa" <> c <> "ss") `shouldSatisfy` isLeft)         [" ", "\r", "\n", "\0"]      it "authenticates each new client connection" $@@ -2762,12 +2896,12 @@   describe "credentials in output" $ do     it "shows credentials without the password" $ do       let auth = Auth.Auth "user" "secret"-      show auth `shouldBe` "Auth {username = \"user\", password = <redacted>}"-      showsPrec 11 auth "" `shouldBe` "(Auth {username = \"user\", password = <redacted>})"+      show auth `shouldBe` "Auth \"user\" <redacted>"+      showsPrec 11 auth "" `shouldBe` "(Auth \"user\" <redacted>)"       showsPrec 11 Auth.NoAuth "" `shouldBe` "NoAuth"       show (Just (ServerSpec "cache.example" "1234" auth)) `shouldBe`         "Just (ServerSpec {ssHost = \"cache.example\", ssPort = \"1234\", \-        \ssAuth = Auth {username = \"user\", password = <redacted>}})"+        \ssAuth = Auth \"user\" <redacted>})"      prop "never shows the password" $       forAll ((,) <$> keyGen <*> keyGen) $ \(user, pass) ->@@ -2794,8 +2928,8 @@           config = "CONFIG cluster 0 " <> C.pack (show (B.length body)) <> "\r\n"             <> body <> "\r\nEND\r\n"       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config, Noop] $ \cfg ->-        EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-          \(StringException message _) -> message == "Not a valid URI: memcached://bad{host:11211"+        EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+          (== DiscoveryError "Not a valid URI: memcached://bad{host:11211")      prop "never echoes the password of an invalid URI" $       forAll keyGen $ \pass ->@@ -2909,7 +3043,7 @@         let uri = "memcached://" <> percentEncode user <> ":" <> percentEncode pass <> "@cache.example"         in fmap specFields (parseServerSpec uri) === Right ("cache.example", "11211", Just (user, pass)) -  describe "Database.Memcache.Client alone" $+  describe "Database.Memcache.Client alone" $ do     -- Every name is qualified by Client, so this stops compiling if the module     -- stops exporting a type its own signatures use.     it "names the types its signatures use" $@@ -2924,30 +3058,64 @@         cas <- Client.set client ("count" :: Client.Key) ("2" :: Client.Value)           (0 :: Client.Flags) (60 :: Client.Expiration)         cas `shouldBe` (9 :: Client.Version)-        Client.increment client "count" (0 :: Client.Initial) (1 :: Client.Delta) 60 cas+        Client.increment client "count" (1 :: Client.Delta) (Just (0 :: Client.Initial, 60)) (Just cas)           `shouldReturn` Just (3, 10)         results <- Client.stats client Nothing         map snd (results :: [(Client.Server, Client.StatResults)]) `shouldBe` [[("pid", "1")]] +    -- A custom router, with every name qualified by Client too: keys that+    -- begin "local:" go to a live server on 127.0.0.1, and the rest as the+    -- default router sends them.+    it "has what a custom router needs" $+      withMockMemcached supportedVersion [MR "SERVER_ERROR down\r\n"] $ \server -> do+        let local :: Client.Client -> Client.Key -> IO (Maybe Client.Server)+            local c key+              | "local:" `B.isPrefixOf` key = do+                  live <- filterM (Client.isAlive c) . toList =<< Client.getServers c+                  return $ find ((== "127.0.0.1") . Client.serverHost) live+              | otherwise = Client.ketamaServerForKey c key+        client <- Client.newClient+          [Client.ServerSpec "cache.example" "11211" Client.NoAuth, mockServerSpec server]+          Client.def+            { Client.optsGetServerForKey = local+            , Client.optsServerRetries = 0+            , Client.optsDeadTimeout = 3600+            }+        fmap Client.serverPort <$> local client "local:key"+          `shouldReturn` Just (show (mockPort server))+        -- The failure marks the mock's server failed, so the router skips it,+        -- as ketamaServerForKey does for other keys.+        Client.get client "local:key"+          `shouldThrow` (== Client.ProtocolError (Client.ServerError "down"))+        Client.get client "local:key" `shouldThrow` (== Client.ClientError Client.NoServersReady)+        fmap Client.serverHost <$> local client "key" `shouldReturn` Just "cache.example"+   describe "named defaults" $ do     -- Options and ServerOptions have no Eq instance (Options holds functions),     -- so these compare the fields that can be compared.     let serverFields so = (Client.soNumResources so, Client.soNumStripes so, Client.soKeepAlive so)         optionFields o =-          ( Client.optsServerRetries o, Client.optsFailRetryDelay o-          , Client.optsDeadRetryDelay o, Client.optsServerTimeout o+          ( Client.optsServerRetries o, Client.optsRetryDelay o+          , Client.optsDeadTimeout o, Client.optsTimeout o           , serverFields (Client.optsServerOptions o) )      it "have the documented values" $ do       Client.defaultServerSpec `shouldBe` Client.ServerSpec "127.0.0.1" "11211" Client.NoAuth-      serverFields Client.defaultServerOptions `shouldBe` (1, 1, 300)-      optionFields Client.defaultOptions `shouldBe` (1, 200, 1500, 750, (1, 1, 300))+      serverFields Client.defaultServerOptions `shouldBe` (4, 1, 300)+      optionFields Client.defaultOptions `shouldBe` (1, 0.2, 1.5, 0.75, (4, 1, 300))      it "are the values def gives" $ do       Client.defaultServerSpec `shouldBe` Client.def       serverFields Client.defaultServerOptions `shouldBe` serverFields Client.def       optionFields Client.defaultOptions `shouldBe` optionFields Client.def +    it "let a client use four connections to a server at once" $+      withServerAndClient [Noop] $ \server client -> do+        [s] <- toList <$> Cluster.getServers client+        fillPool s 4+        -- Each connection checked the version as it opened.+        mockRequests server `shouldReturn` replicate 4 "version\r\n"+   describe "clusters" $ do     -- A server's sid hashes its host and port, so two servers can have the     -- same sid, as a record update gives them here. They are still different@@ -3077,7 +3245,7 @@       withMockMemcached supportedVersion [DelayMS 5000 (MR "OK\r\n")] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b -> do         client <- Client.newClient [mockServerSpec a, mockServerSpec b]-          Client.def { Client.optsServerTimeout = 10000 }+          Client.def { Client.optsTimeout = 10 }         flushing <- async $ Client.flush client Nothing         waitForRequests a 2 `shouldReturn` ["version\r\n", "flush_all\r\n"]         cancel flushing@@ -3142,7 +3310,7 @@       withLocalhostAddresses $ \first later ->       withBoundSocket first $ \port -> do         let spec = ServerSpec "localhost" (show port) Auth.NoAuth-        refused <- Client.newClient [spec] oneAttempt { Client.optsServerTimeout = 10000 }+        refused <- Client.newClient [spec] oneAttempt { Client.optsTimeout = 10 }         withBoundSocketReuseAddr (atPort port later) $ \_ ->           Client.get refused "key" `shouldThrow` isDoesNotExistError         withMockMemcachedAt supportedVersion (atPort port later) [MR "VA 3 f2 c7\r\nfoo\r\n"] $ \_ -> do@@ -3197,7 +3365,7 @@       withFullListener first $ \port stopListening ->       withMockMemcachedAt supportedVersion (atPort port later) [MR "VA 3 f2 c7\r\nfoo\r\n"] $ \server -> do         impatient <- Client.newClient [localhostSpec server Auth.NoAuth]-          oneAttempt { Client.optsServerTimeout = 300 }+          oneAttempt { Client.optsTimeout = 0.3 }         Client.get impatient "key" `shouldThrow` (== ClientError Timeout)         mockRequests server `shouldReturn` []         stopListening@@ -3266,14 +3434,14 @@           ] $ \(problem, bytes) ->       it ("gives up on a config reply " <> problem) $         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", Repeat bytes] $ \cfg ->-          EC.newClient Client.def { Client.optsServerTimeout = 10000 } hour (endpoint cfg)+          EC.newClient Client.def { Client.optsTimeout = 10 } (endpoint cfg) hour             `shouldThrow` isBadLength      it "discovers nodes with the config command" $       withMockMemcached supportedVersion [MR "VA 3 f0 c1\r\nfoo\r\n"] $ \node -> do         let config = "CONFIG cluster 0 " <> nodeList "1" [node] <> "END\r\n"         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config] $ \cfg -> do-          client <- EC.newClient Client.def hour (endpoint cfg)+          client <- EC.newClient Client.def (endpoint cfg) hour           Client.get client "key" `shouldReturn` Just ("foo", 0, 1)           -- The connection's own version check, then discovery's.           waitForRequests cfg 3 `shouldReturn`@@ -3289,7 +3457,7 @@       withMockServer [MR "VA 3 f0 c1\r\nfoo\r\n"] $ \node -> do         let value = "VALUE AmazonElastiCache:cluster 0 " <> nodeList "1" [node] <> "END\r\n"         withMockServer [MR "VERSION 1.4.5\r\n", MR value, Noop] $ \cfg -> do-          timeout 5000000 (EC.newClient Client.def hour (endpoint cfg))+          timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour)             `shouldThrow` versionRefused "VERSION 1.4.5"           mockRequests cfg `shouldReturn` ["version\r\n"]           mockRequests node `shouldReturn` []@@ -3299,7 +3467,7 @@       withMockServer [MR "VERSION 1.6.9\r\n", MR "HD c1\r\n"] $ \node -> do         let config = "CONFIG cluster 0 " <> nodeList "1" [node] <> "END\r\n"         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config] $ \cfg -> do-          client <- EC.newClient Client.def hour (endpoint cfg)+          client <- EC.newClient Client.def (endpoint cfg) hour           Client.set client "key" injection 0 0 `shouldThrow` versionRefused "VERSION 1.6.9"           mockRequests node `shouldReturn` ["version\r\n"] @@ -3311,7 +3479,7 @@       withMockMemcached supportedVersion [MR "VA 3 f0 c1\r\nfoo\r\n"] $ \node -> do         let value = "VALUE AmazonElastiCache:cluster 0 " <> nodeList "1" [node] <> "END\r\n"         withMockMemcached supportedVersion [MR "VERSION 1.4.5\r\n", MR value] $ \cfg -> do-          client <- EC.newClient Client.def hour (endpoint cfg)+          client <- EC.newClient Client.def (endpoint cfg) hour           Client.get client "key" `shouldReturn` Just ("foo", 0, 1)           waitForRequests cfg 3 `shouldReturn`             ["version\r\n", "version\r\n", "get AmazonElastiCache:cluster\r\n"]@@ -3328,8 +3496,8 @@       ] $ \(version, request) ->       it ("asks an endpoint at version " <> version <> " with " <> request) $         withMockMemcached supportedVersion [MR ("VERSION " <> C.pack version <> "\r\n"), MR "ERROR\r\n", Noop] $ \cfg -> do-          timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-            \(StringException message _) -> message == "Configuration endpoint replied: ERROR"+          timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+            (== DiscoveryError "Configuration endpoint replied: ERROR")           mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n", C.pack request <> "\r\n"]      -- The version is read leniently: discovery skips the line's first 8@@ -3341,8 +3509,8 @@       ] $ \(line, request) ->       it ("reads the version reply " <> show line) $         withMockMemcached supportedVersion [MR (C.pack line <> "\r\n"), MR "ERROR\r\n", Noop] $ \cfg -> do-          timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-            \(StringException message _) -> message == "Configuration endpoint replied: ERROR"+          timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+            (== DiscoveryError "Configuration endpoint replied: ERROR")           mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n", C.pack request <> "\r\n"]      -- A version reply discovery can't read is an error, as another reply it@@ -3351,24 +3519,24 @@       ["ERROR", "VERSION 1.6.", "VERSION 1.6.12 extra", "VERSION 1.6.12-"] $ \line ->       it ("rejects the version reply " <> show line) $         withMockMemcached supportedVersion [MR (C.pack line <> "\r\n"), Noop] $ \cfg -> do-          timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-            \(StringException message _) -> message == "Unrecognized version reply: " <> line+          timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+            (== DiscoveryError ("Unrecognized version reply: " <> line))           mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n"]      it "reads a version of up to 64 bytes" $ do       let versionOf n = "VERSION 1.6.12-" <> C.replicate (n - 7) 'a'       withMockMemcached supportedVersion [MR (versionOf 64 <> "\r\n"), MR "ERROR\r\n", Noop] $ \cfg -> do-        timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-          \(StringException message _) -> message == "Configuration endpoint replied: ERROR"+        timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+          (== DiscoveryError "Configuration endpoint replied: ERROR")         mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n", "config get cluster\r\n"]       withMockMemcached supportedVersion [MR (versionOf 65 <> "\r\n"), Noop] $ \cfg -> do-        timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-          \(StringException message _) -> message == "Unrecognized version reply: " <> C.unpack (versionOf 65)+        timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+          (== DiscoveryError ("Unrecognized version reply: " <> C.unpack (versionOf 65)))         mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n"]      -- Reading a version of 32,000 numbers took seconds, which the time limit     -- can't interrupt where asynchronous exceptions are masked, as in a-    -- bracket's acquire: there newClient overran optsServerTimeout, and with+    -- bracket's acquire: there newClient overran optsTimeout, and with     -- the configuration sent along with the version, it returned a client.     -- Now discovery reads no version longer than 64 bytes, so it fails at once.     forM_@@ -3381,8 +3549,9 @@       it ("fails at once on a long version reply" <> how) $         withMockMemcached supportedVersion [reply, Noop, Noop] $ \cfg -> do           begin <- getMonotonicTime-          run (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-            \(StringException message _) -> "Unrecognized version reply: VERSION 1.1.1." `isPrefixOf` message+          run (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow` \err ->+            "ElastiCache discovery failed: Unrecognized version reply: VERSION 1.1.1."+              `isPrefixOf` displayException (err :: MemcacheError)           elapsed <- subtract begin <$> getMonotonicTime           elapsed `shouldSatisfy` (< 2)           mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n"]@@ -3404,8 +3573,8 @@             config = "CONFIG cluster 0 " <> C.pack (show (B.length body)) <> "\r\n"               <> body <> "\r\nEND\r\n"         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config, Noop] $ \cfg ->-          EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-            \(StringException message _) -> message == expected+          EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+            (== DiscoveryError expected)      -- Other hosts change the node in other ways. "/" or "?" ends the host,     -- so the port is lost. The host is what follows "@", and what comes@@ -3423,8 +3592,8 @@         let node = host <> "|10.0.0.1|" <> port         it ("won't take the node " <> show node) $           withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing "1" [node]), Noop] $ \cfg ->-            EC.newClient Client.def hour (endpoint cfg) `shouldThrow` \(StringException message _) ->-              message == "Node is not a plain host and port: memcached://" <> C.unpack host <> ":" <> C.unpack port+            EC.newClient Client.def (endpoint cfg) hour `shouldThrow` (== DiscoveryError+              ("Node is not a plain host and port: memcached://" <> C.unpack host <> ":" <> C.unpack port))      -- An error reply is one line with no END line after it, and memcached     -- keeps the connection open, as the Noop does: discovery must not wait@@ -3434,8 +3603,8 @@       forM_ ["ERROR", "CLIENT_ERROR bad command line format", "SERVER_ERROR out of memory"] $ \reply ->         it ("throws at once when " <> C.unpack request <> " gets " <> reply) $           withMockMemcached supportedVersion [MR ("VERSION " <> version <> "\r\n"), MR (C.pack reply <> "\r\n"), Noop] $ \cfg -> do-            timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-              \(StringException message _) -> message == "Configuration endpoint replied: " <> reply+            timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+              (== DiscoveryError ("Configuration endpoint replied: " <> reply))             mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n", request <> "\r\n"]      -- With no Noop the mock closes the connection after the error line, as@@ -3443,18 +3612,23 @@     -- error line is reported, not the closed connection.     it "reports an error reply even when the endpoint then closes the connection" $       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR "ERROR\r\n"] $ \cfg ->-        timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-          \(StringException message _) -> message == "Configuration endpoint replied: ERROR"+        timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+          (== DiscoveryError "Configuration endpoint replied: ERROR")      -- A miss is END alone, so the reply's first line is also its last.     it "reports a missing cluster key when discovery's version request gets a version before 1.4.14" $       withMockMemcached supportedVersion [MR "VERSION 1.4.5\r\n", MR "END\r\n", Noop] $ \cfg ->-        timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-          \(StringException message _) -> message == "Unrecognized number of lines: 1"+        timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow`+          (== DiscoveryError "Unrecognized number of lines: 1") +    it "fails when the options make no server for the endpoint" $+      withMockMemcached "1.6.12" [] $ \cfg -> do+        let opts = Client.def { Client.optsServerSpecsToServers = \_ _ -> pure [] }+        EC.newClient opts (endpoint cfg) hour `shouldThrow` (== DiscoveryError "No servers were found")+     -- The endpoint's text goes into these errors escaped, and cut to its-    -- first 200 characters, as displayException does for a MemcacheError, so-    -- that it can't break the lines of a log.+    -- first 200 characters, so that it can't break the lines of a log, and+    -- displayException doesn't escape it again.     forM_       [ ("an error reply", MR "SERVER_ERROR x\ESC[2J\nforged log line\r\n",           "Configuration endpoint replied: SERVER_ERROR x\\ESC[2J\\nforged log line")@@ -3467,8 +3641,9 @@       ] $ \(what, reply, expected) ->       it ("escapes and shortens the endpoint's text in the error for " <> what) $         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", reply, Noop] $ \cfg ->-          timeout 5000000 (EC.newClient Client.def hour (endpoint cfg)) `shouldThrow`-            \(StringException message _) -> message == expected+          timeout 5000000 (EC.newClient Client.def (endpoint cfg) hour) `shouldThrow` \err ->+            err == DiscoveryError expected+              && displayException err == "ElastiCache discovery failed: " <> expected      -- A config whose node line is empty, or only spaces, lists no nodes. The     -- error says so, rather than that the line, taken as one empty entry,@@ -3476,8 +3651,8 @@     forM_ [("empty", []), ("only spaces", ["  "])] $ \(what, entries) ->       it ("rejects a config whose node line is " <> what) $         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing "1" entries), Noop] $ \cfg ->-          EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-            \(StringException message _) -> message == "Configuration lists no nodes"+          EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+            (== DiscoveryError "Configuration lists no nodes")      -- Two spaces between nodes make an empty entry, as the line is split at     -- each space. The error says that the config lists an empty node, rather@@ -3485,8 +3660,8 @@     it "rejects a config that lists an empty node" $ do       let config = configListing "1" ["a|10.0.0.1|1", "", "b|10.0.0.2|2"]       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config, Noop] $ \cfg ->-        EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-          \(StringException message _) -> message == "Configuration lists an empty node"+        EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+          (== DiscoveryError "Configuration lists an empty node")      -- ElastiCache allows far fewer nodes in a cluster. A config reply of     -- 300 KB can list 10,000, and discovery would make a server for each,@@ -3495,7 +3670,7 @@     it "takes a config listing 1,000 nodes, but not 1,001" $ do       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing "1" (manyNodes 1000))] $ \cfg ->         withDiscovery Client.def $ \opts _ made -> do-          client <- EC.newClient opts hour (endpoint cfg)+          client <- EC.newClient opts (endpoint cfg) hour           length <$> Cluster.getServers client `shouldReturn` 1000           -- newClient called the server constructor for the endpoint and for           -- each node. As start is never run, the refresh thread is held at@@ -3508,8 +3683,8 @@           waitFor 1002 (length <$> made) `shouldReturn` 1002       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing "1" (manyNodes 1001)), Noop] $ \cfg ->         withDiscovery Client.def $ \opts _ made -> do-          EC.newClient opts hour (endpoint cfg) `shouldThrow`-            \(StringException message _) -> message == "Configuration lists 1001 nodes, over the limit of 1000"+          EC.newClient opts (endpoint cfg) hour `shouldThrow`+            (== DiscoveryError "Configuration lists 1001 nodes, over the limit of 1000")           filter (/= [mockServerSpec cfg]) <$> made `shouldReturn` []      -- Discovery counts the nodes before it parses any of them, so that a@@ -3517,8 +3692,8 @@     -- be parsed, and the count fails first.     it "counts the nodes before parsing any of them" $       withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing "1" ("bad" : manyNodes 1000)), Noop] $ \cfg ->-        EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-          \(StringException message _) -> message == "Configuration lists 1001 nodes, over the limit of 1000"+        EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+          (== DiscoveryError "Configuration lists 1001 nodes, over the limit of 1000")      -- A node listed twice would get a second server, which its keys would     -- fall back to when the first is marked failed. Nodes are told apart by@@ -3530,8 +3705,8 @@             config = configListing "1" [node a "127.0.0.1", node b "127.0.0.1", node a "10.0.0.2"]         withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR config, Noop] $ \cfg ->           withDiscovery Client.def $ \opts _ made -> do-            EC.newClient opts hour (endpoint cfg) `shouldThrow`-              \(StringException message _) -> message == "Node listed twice: 127.0.0.1:" <> show (mockPort a)+            EC.newClient opts (endpoint cfg) hour `shouldThrow`+              (== DiscoveryError ("Node listed twice: 127.0.0.1:" <> show (mockPort a)))             filter (/= [mockServerSpec cfg]) <$> made `shouldReturn` []      -- A configuration's version is the line before its nodes. Discovery@@ -3542,7 +3717,7 @@       it ("reads the configuration version " <> show version) $         withMockMemcached "1.6.12"             [MR "VERSION 1.6.12\r\n", MR (configListing version ["127.0.0.1|127.0.0.1|11211"])] $ \cfg -> do-          client <- EC.newClient Client.def hour (endpoint cfg)+          client <- EC.newClient Client.def (endpoint cfg) hour           length <$> Cluster.getServers client `shouldReturn` 1      -- A version with anything else in it, such as a sign, a second number, a@@ -3564,11 +3739,11 @@       it ("rejects the configuration version " <> show version) $         withMockMemcached "1.6.12"             [MR "VERSION 1.6.12\r\n", MR (configListing version ["127.0.0.1|127.0.0.1|11211"]), Noop] $ \cfg ->-          EC.newClient Client.def hour (endpoint cfg) `shouldThrow`-            \(StringException message _) -> message == expected+          EC.newClient Client.def (endpoint cfg) hour `shouldThrow`+            (== DiscoveryError expected)      -- When a request is never answered, discovery gives up once-    -- optsServerTimeout has passed. The limit is above the 750 ms default, so+    -- optsTimeout has passed. The limit is above the 750 ms default, so     -- giving up no sooner than 1 s shows that the default was not used. The     -- extra Noop keeps the mock reading, as an endpoint that has stopped     -- answering would, rather than closing the connection. The first request@@ -3579,16 +3754,33 @@           , ("config get cluster", withMockMemcached "1.6.12", [MR "VERSION 1.6.12\r\n"]             , ["version\r\n", "version\r\n", "config get cluster\r\n"])           ] $ \(request, withMock, replies, requests) ->-      it ("gives up after optsServerTimeout when the endpoint never answers " <> request) $+      it ("gives up after optsTimeout when the endpoint never answers " <> request) $         withMock (replies ++ [Noop, Noop]) $ \cfg -> do           start <- getMonotonicTime-          timeout 5000000 (EC.newClient Client.def { Client.optsServerTimeout = 1000 } hour (endpoint cfg))+          timeout 5000000 (EC.newClient Client.def { Client.optsTimeout = 1 } (endpoint cfg) hour)             `shouldThrow` (== ClientError Timeout)           elapsed <- subtract start <$> getMonotonicTime           elapsed `shouldSatisfy` (>= 1)           -- Nothing answers the last request, so wait for the mock to record it.           waitForRequests cfg (length requests) `shouldReturn` requests +    -- The interval is in seconds. The refresh thread waits it out once the+    -- test lets it go on, then refreshes on a new connection, whose version+    -- check is the endpoint's fourth request.+    it "waits the interval, in seconds, before refreshing" $+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->+      withMockMemcached "1.6.12" (refreshTo "1" [a] ++ noReplies) $ \cfg ->+      withDiscovery patient $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) 0.5+        begin <- getMonotonicTime+        start+        waitFor True ((>= 4) . length <$> mockRequests cfg) `shouldReturn` True+        elapsed <- subtract begin <$> getMonotonicTime+        elapsed `shouldSatisfy` (>= 0.5)+        take 4 <$> mockRequests cfg `shouldReturn`+          ["version\r\n", "version\r\n", "config get cluster\r\n", "version\r\n"]+        keepReachable client+     -- Each refresh opens its own connection to the endpoint, which is     -- checked like any other. Here the endpoint reports 1.6.9 to the     -- connections of the first two refreshes, so those refreshes fail,@@ -3599,8 +3791,8 @@       withMockServer ([supported] ++ refreshTo "1" [a]           ++ [MR "VERSION 1.6.9\r\n", MR "VERSION 1.6.9\r\n"]           ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         waitFor 6 (length <$> mockRequests cfg) `shouldReturn` 6         mockRequests cfg `shouldReturn` ["version\r\n", "version\r\n", "config get cluster\r\n"]@@ -3623,8 +3815,8 @@           ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The first discovery and each refresh connect to the endpoint         -- afresh, and each new connection first checks its version.@@ -3653,8 +3845,8 @@           ++ refreshTo "2" [a, b]           ++ [MR "VERSION 1.6.12\r\n", MR "SERVER_ERROR out of memory\r\n"]           ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The first discovery and each refresh connect to the endpoint         -- afresh, and each new connection first checks its version.@@ -3673,7 +3865,7 @@     -- gets its reply, which lists b alone at a higher version, only after the     -- limit. Had the client waited for it, it would have dropped a, and the     -- next refresh, which connects again, would have made a's server again.-    it "abandons a refresh slower than optsServerTimeout and runs the next one" $+    it "abandons a refresh slower than optsTimeout and runs the next one" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withConcurrentMockMemcached "1.6.12"@@ -3683,8 +3875,8 @@             : noReplies )           : refreshTo "3" [a, b]           : repeat noReplies ) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 1000 } $ \opts start made -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 1 } $ \opts start made -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         begin <- getMonotonicTime         start         waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2@@ -3704,8 +3896,8 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ [Noop] ++ refreshTo "2" [a, b] ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 300 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 0.3 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2         -- The refresh after the one that found b gets no reply either. Once@@ -3726,8 +3918,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a]           ++ [MR "VERSION 1.6.12\r\n", Repeat ("CONFIG cluster 0 9\r\n" <> C.replicate 4096 'x' <> "\r\n")]           ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The refresh after the one whose reply never ends has sent its         -- request, so that one has ended, and it may not drop the server.@@ -3761,8 +3953,8 @@             ++ noReplies) $ \cfg ->         -- With this time limit no refresh runs out of time on a slow machine,         -- which would shift the replies.-        withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start made -> do-          client <- EC.newClient opts tenMs (endpoint cfg)+        withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start made -> do+          client <- EC.newClient opts (endpoint cfg) tenMs           start           waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2           -- Servers were made for a when the client was created and for b at@@ -3790,8 +3982,8 @@           withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \a ->           withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \b ->           withMockMemcached supportedVersion (discoveryTo "9" [a, b] ++ discoveryTo version [a] ++ noReplies) $ \cfg ->-          withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start made -> do-            client <- EC.newClient opts tenMs (endpoint cfg)+          withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start made -> do+            client <- EC.newClient opts (endpoint cfg) tenMs             Client.flush client Nothing             start             -- The refresh after the one that lists a alone has sent its@@ -3821,8 +4013,8 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withMockMemcached "1.6.12" (refreshTo "5" [a] ++ refreshTo "3" [a, b] ++ refreshTo "4" [a, b] ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start made -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start made -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The refresh after the one at version 4 has sent its request, so         -- that one has been handled.@@ -3839,8 +4031,8 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "3" [a, b] ++ refreshTo "2" [a] ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The refresh after the one at version 2 has sent its request, so         -- that one has been handled.@@ -3857,7 +4049,7 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "2" [a, b] ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do         me <- myThreadId         states <- newIORef []         let recording serverOptions specs = do@@ -3867,7 +4059,7 @@                 atomicModifyIORef' states (\earlier -> (state : earlier, ()))               Client.optsServerSpecsToServers opts serverOptions specs         client <- mask_ $-          EC.newClient opts { Client.optsServerSpecsToServers = recording } tenMs (endpoint cfg)+          EC.newClient opts { Client.optsServerSpecsToServers = recording } (endpoint cfg) tenMs         start         waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2         readIORef states `shouldReturn` [Unmasked, Unmasked]@@ -3879,9 +4071,9 @@     it "stops refreshing when the client is quit" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "2" [a] ++ noReplies) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do         (recording, refreshThreads) <- recordingThreads opts-        client <- EC.newClient recording tenMs (endpoint cfg)+        client <- EC.newClient recording (endpoint cfg) tenMs         start         -- The second refresh has asked for the version. Each refresh         -- connects to the endpoint afresh, and each new connection first@@ -3914,9 +4106,9 @@               atomicModifyIORef' kept (\earlier -> (servers ++ earlier, ()))               return servers             holding = Client.def-              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = holdB }+              { Client.optsTimeout = 10, Client.optsServerSpecsToServers = holdB }         withDiscovery holding $ \opts start made -> do-          client <- EC.newClient opts tenMs (endpoint cfg)+          client <- EC.newClient opts (endpoint cfg) tenMs           start           waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True           Client.quit client@@ -3946,10 +4138,10 @@                 void (try (readMVar held) :: IO (Either SomeException ()))               Client.optsServerSpecsToServers Client.def serverOptions specs             catching = Client.def-              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = catchB }+              { Client.optsTimeout = 10, Client.optsServerSpecsToServers = catchB }         withDiscovery catching $ \opts start made -> do           (recording, refreshThreads) <- recordingThreads opts-          client <- EC.newClient recording tenMs (endpoint cfg)+          client <- EC.newClient recording (endpoint cfg) tenMs           start           waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True           [thread] <- refreshThreads@@ -3961,12 +4153,12 @@           length <$> Cluster.getServers client `shouldReturn` 1      -- Making b's server waits with asynchronous exceptions masked-    -- uninterruptibly, so that the refresh thread can't be interrupted, as-    -- while it looks the endpoint's name up, and the client is quit-    -- meanwhile. quit returns at once all the same, and the kill lands once-    -- the wait is over. If the thread that sends the kill runs late, the-    -- refresh reaches the swap first, and the flag stops the swap. Either-    -- way, the refresh replaces no servers, and its connection is closed.+    -- uninterruptibly, so that the refresh thread can't be interrupted, and+    -- the client is quit meanwhile. quit returns at once all the same, and+    -- the kill lands once the wait is over. If the thread that sends the kill+    -- runs late, the refresh reaches the swap first, and the flag stops the+    -- swap. Either way, the refresh replaces no servers, and its connection+    -- is closed.     it "returns from quit at once while the refresh thread can't be interrupted" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->@@ -3976,10 +4168,10 @@               when (specs == [mockServerSpec b]) $ uninterruptibleMask_ (readMVar held)               Client.optsServerSpecsToServers Client.def serverOptions specs             holding = Client.def-              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = holdB }+              { Client.optsTimeout = 10, Client.optsServerSpecsToServers = holdB }         withDiscovery holding $ \opts start made -> do           (recording, refreshThreads) <- recordingThreads opts-          client <- EC.newClient recording tenMs (endpoint cfg)+          client <- EC.newClient recording (endpoint cfg) tenMs           start           waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True           [thread] <- refreshThreads@@ -4002,8 +4194,8 @@     it "keeps refreshing when a cluster made from the client by setServers is quit" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached "1.6.12" (concatMap (\n -> refreshTo (C.pack (show n)) [a]) [1 :: Int ..]) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         other <- Cluster.setServers client . Right <$> Cluster.getServers client         start         waitFor True ((>= 6) . length <$> mockRequests cfg) `shouldReturn` True@@ -4021,9 +4213,9 @@     it "stops refreshing once the client is garbage collected" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached "1.6.12" (concatMap (\n -> refreshTo (C.pack (show n)) [a]) [1 :: Int ..]) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do         (recording, refreshThreads) <- recordingThreads opts-        client <- EC.newClient recording tenMs (endpoint cfg)+        client <- EC.newClient recording (endpoint cfg) tenMs         start         waitFor True ((>= 9) . length <$> mockRequests cfg) `shouldReturn` True         keepReachable client@@ -4043,9 +4235,9 @@     it "stops refreshing once the client is garbage collected, when every refresh is ignored" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached "1.6.12" (cycle (refreshTo "1" [a])) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do         (recording, refreshThreads) <- recordingThreads opts-        client <- EC.newClient recording tenMs (endpoint cfg)+        client <- EC.newClient recording (endpoint cfg) tenMs         start         waitFor True ((>= 9) . length <$> mockRequests cfg) `shouldReturn` True         keepReachable client@@ -4061,8 +4253,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "2" [b, a] ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         Client.flush client Nothing         start         waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2@@ -4081,8 +4273,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshToAt "2" "10.0.0.2" [a] ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         [original] <- toList <$> Cluster.getServers client         Client.flush client Nothing         start@@ -4103,8 +4295,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshToAt "2" "10.0.0.2" [a] ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         flushing <- async $ Client.flush client Nothing         waitForRequests a 2 `shouldReturn` ["version\r\n", "flush_all\r\n"]         start@@ -4136,8 +4328,8 @@           : (refreshTo "1" [a] ++ noReplies)           : (refreshToAt "2" "10.0.0.2" [a] ++ noReplies)           : repeat noReplies ) $ \cfg ->-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         Client.flush client Nothing         start         waitFor 1 (mockClosed a) `shouldReturn` 1@@ -4165,9 +4357,9 @@               | specs == [mockServerSpec b] = ioError (userError "no server for b")               | otherwise = Client.optsServerSpecsToServers Client.def serverOptions specs             failing = Client.def-              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = failForB }+              { Client.optsTimeout = 10, Client.optsServerSpecsToServers = failForB }         withDiscovery failing $ \opts start made -> do-          client <- EC.newClient opts tenMs (endpoint cfg)+          client <- EC.newClient opts (endpoint cfg) tenMs           start           waitFor 1 (mockClosed cfg) `shouldReturn` 1           -- The refresh failed at b's server, and kept a's.@@ -4197,9 +4389,9 @@                 then ioError (userError "no server for b")                 else Client.optsServerSpecsToServers Client.def serverOptions specs             failing = Client.def-              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = failForBOnce }+              { Client.optsTimeout = 10, Client.optsServerSpecsToServers = failForBOnce }         withDiscovery failing $ \opts start made -> do-          client <- EC.newClient opts tenMs (endpoint cfg)+          client <- EC.newClient opts (endpoint cfg) tenMs           start           waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2           -- b's server was made at both refreshes, as the first failed.@@ -4223,8 +4415,8 @@         withMockMemcached "1.6.12" (refreshTo "1" [hi, lo] ++ refreshTo "2" [hi, lo, c] ++ noReplies) $ \cfg ->           -- With this time limit no refresh runs out of time on a slow           -- machine, which would shift the replies.-          withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-            client <- EC.newClient opts tenMs (endpoint cfg)+          withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+            client <- EC.newClient opts (endpoint cfg) tenMs             let ports = map Server.serverPort . toList <$> Cluster.getServers client                 portsOf = map (show . mockPort)             ports `shouldReturn` portsOf [hi, lo]@@ -4244,8 +4436,8 @@           ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start made -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start made -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         start         -- The refresh after the third has sent its request, so the third has         -- been handled. Each refresh connects to the endpoint afresh, and@@ -4272,8 +4464,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a, b] ++ refreshTo "2" [a] ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start made -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start made -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         Client.flush client Nothing         initial <- Cluster.getServers client         start@@ -4301,8 +4493,8 @@       withMockMemcached "1.6.12" (refreshTo "1" [a, b] ++ refreshTo "2" [a] ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.-      withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do-        client <- EC.newClient opts tenMs (endpoint cfg)+      withDiscovery Client.def { Client.optsTimeout = 10 } $ \opts start _ -> do+        client <- EC.newClient opts (endpoint cfg) tenMs         initial <- Cluster.getServers client         flushing <- async $ Client.flush client Nothing         waitForRequests b 2 `shouldReturn` ["version\r\n", "flush_all\r\n"]@@ -4325,8 +4517,10 @@       _ <- forkIO $ N.sendAll right bytes       recvResponse connection     wire key = either (error . show) id (encodeKey key)-    isKeyTooLong (ClientError (KeyTooLong _)) = True-    isKeyTooLong _ = False+    isInvalidKey (ClientError (InvalidKey _)) = True+    isInvalidKey _ = False+    isInvalidArgument (ClientError (InvalidArgument _)) = True+    isInvalidArgument _ = False     isInvalidAuthentication (ClientError (InvalidAuthentication _)) = True     isInvalidAuthentication _ = False     isServerError (ProtocolError (E.ServerError _)) = True@@ -4391,10 +4585,10 @@     valueOps =       [ ("set",     \c -> void $ Client.set c "key" injection 0 0)       , ("add",     \c -> void $ Client.add c "key" injection 0 0)-      , ("replace", \c -> void $ Client.replace c "key" injection 0 0 0)+      , ("replace", \c -> void $ Client.replace c "key" injection 0 0 Nothing)       , ("cas",     \c -> void $ Client.cas c "key" injection 0 0 1)-      , ("append",  \c -> void $ Client.append c "key" injection 0)-      , ("prepend", \c -> void $ Client.prepend c "key" injection 0)+      , ("append",  \c -> void $ Client.append c "key" injection Nothing)+      , ("prepend", \c -> void $ Client.prepend c "key" injection Nothing)       ]     -- The batch operations, which pipeline their requests.     batchOps :: [(String, Client.Client -> IO ())]@@ -4405,9 +4599,13 @@       ]     injection :: B.ByteString     injection = "set injected 0 0 3\r\nbad"-    fastFailover = Client.def { Client.optsFailRetryDelay = 10, Client.optsDeadRetryDelay = 60000 }+    fastFailover = Client.def { Client.optsRetryDelay = 0.01, Client.optsDeadTimeout = 60 }     -- One attempt per operation, and a server it marks dead is used again at once.-    oneAttempt = Client.def { Client.optsServerRetries = 0, Client.optsDeadRetryDelay = 0 }+    oneAttempt = Client.def { Client.optsServerRetries = 0, Client.optsDeadTimeout = 0 }+    -- A pool of one connection to each server, for tests in which a request+    -- waits for the connection another holds.+    oneConnection opts =+      opts { Client.optsServerOptions = Client.defaultServerOptions { Client.soNumResources = 1 } }     -- 300 keys, more than a batch holds: a batch of 256, then one of 44.     batchKeys = [C.pack ("key" <> show i) | i <- [0 .. 299 :: Int]]     -- Where each batch ended among the requests the mock received: the@@ -4417,16 +4615,18 @@     -- successful reply the mock would give a retry.     sentOnce :: [(String, B.ByteString, Client.Client -> IO ())]     sentOnce =-      [ ("an increment", "VA 1 c5\r\n6\r\n", \c -> void (Client.increment c "key" 0 1 0 0))-      , ("a decrement", "VA 1 c5\r\n4\r\n", \c -> void (Client.decrement c "key" 0 1 0 0))-      , ("an append", "HD c5\r\n", \c -> void (Client.append c "key" "v" 0))-      , ("a prepend", "HD c5\r\n", \c -> void (Client.prepend c "key" "v" 0))-      , ("an append with a version", "HD c5\r\n", \c -> void (Client.append c "key" "v" 9))-      , ("a prepend with a version", "HD c5\r\n", \c -> void (Client.prepend c "key" "v" 9))+      [ ("an increment", "VA 1 c5\r\n6\r\n", \c -> void (Client.increment c "key" 1 (Just (0, 0)) Nothing))+      , ("a decrement", "VA 1 c5\r\n4\r\n", \c -> void (Client.decrement c "key" 1 (Just (0, 0)) Nothing))+      , ("an append", "HD c5\r\n", \c -> void (Client.append c "key" "v" Nothing))+      , ("a prepend", "HD c5\r\n", \c -> void (Client.prepend c "key" "v" Nothing))+      , ("an append with a version", "HD c5\r\n", \c -> void (Client.append c "key" "v" (Just 9)))+      , ("a prepend with a version", "HD c5\r\n", \c -> void (Client.prepend c "key" "v" (Just 9)))       , ("an add", "HD c5\r\n", \c -> void (Client.add c "key" "v" 0 0))-      , ("a delete", "HD\r\n", \c -> void (Client.delete c "key" 0))-      , ("a cas with a version", "HD c5\r\n", \c -> void (Client.cas c "key" "v" 0 0 9))-      , ("a replace with a version", "HD c5\r\n", \c -> void (Client.replace c "key" "v" 0 0 9))+      , ("a delete", "HD\r\n", \c -> void (Client.delete c "key" Nothing))+      , ("a cas", "HD c5\r\n", \c -> void (Client.cas c "key" "v" 0 0 9))+      , ("a cas with version 0", "HD c5\r\n", \c -> void (Client.cas c "key" "v" 0 0 0))+      , ("a replace with a version", "HD c5\r\n", \c -> void (Client.replace c "key" "v" 0 0 (Just 9)))+      , ("a replace with version 0", "HD c5\r\n", \c -> void (Client.replace c "key" "v" 0 0 (Just 0)))       ]     -- The operations whose request can be sent again, each with a reply the     -- mock gives the retry, and a check of the result.@@ -4436,8 +4636,7 @@       , ("a get-and-touch", "VA 1 c5\r\nv\r\n", \c -> Client.gat c "key" 0 `shouldReturn` Just ("v", 0, 5))       , ("a touch", "HD c5\r\n", \c -> Client.touch c "key" 0 `shouldReturn` Just 5)       , ("a set", "HD c5\r\n", \c -> Client.set c "key" "v" 0 0 `shouldReturn` 5)-      , ("a cas with version 0", "HD c5\r\n", \c -> Client.cas c "key" "v" 0 0 0 `shouldReturn` Just 5)-      , ("a replace with version 0", "HD c5\r\n", \c -> Client.replace c "key" "v" 0 0 0 `shouldReturn` Just 5)+      , ("a replace without a version", "HD c5\r\n", \c -> Client.replace c "key" "v" 0 0 Nothing `shouldReturn` Just 5)       , ("a getMany batch", "VA 1 c5 O0\r\nv\r\nMN\r\n", \c -> Client.getMany c ["key"] `shouldReturn` [("key", ("v", 0, 5))])       , ("a setMany batch", "HD c5 O0\r\nMN\r\n", \c -> Client.setMany c [("key", "v", 0, 0)] `shouldReturn` [("key", 5)])       , ("a deleteMany batch", "HD O0\r\nMN\r\n", \c -> Client.deleteMany c ["key"])@@ -4447,7 +4646,7 @@       ]     -- A get and an increment, each with the mock's reply to it.     getOnce = (\c -> Client.get c "key" `shouldReturn` Just ("v", 0, 5), "VA 1 c5\r\nv\r\n")-    incrementOnce = (\c -> Client.increment c "key" 0 1 0 0 `shouldReturn` Just (6, 5), "VA 1 c5\r\n6\r\n")+    incrementOnce = (\c -> Client.increment c "key" 1 (Just (0, 0)) Nothing `shouldReturn` Just (6, 5), "VA 1 c5\r\n6\r\n")     loopbackAddress = N.SockAddrInet 0 (N.tupleToHostAddress (127, 0, 0, 1))     -- Run a test with a fresh path for a Unix socket, or mark it pending     -- where there are no Unix sockets.@@ -4455,7 +4654,7 @@       | N.isUnixDomainSocketAvailable = withSocketPath test       | otherwise = pendingWith "Unix sockets are unavailable"     -- Long enough to read a stats reply of hundreds of thousands of lines.-    slowStats opts = opts { Client.optsServerTimeout = 10000 }+    slowStats opts = opts { Client.optsTimeout = 10 }     -- What @stats conns@ reports for one client connection at its longest,     -- 240 bytes: a five-digit descriptor, a server listening on a Unix socket     -- at a 107-byte path (the longest memcached takes), the longest state name@@ -4466,9 +4665,9 @@     localhostSpec server = ServerSpec "localhost" (show (mockPort server))     -- Each attempt has 10 s, so that even on a slow machine one is unlikely     -- to run out of time after using up a mock's reply.-    patient = Client.def { Client.optsServerTimeout = 10000 }-    hour = 3600 * 1000000-    tenMs = 10 * 1000+    patient = Client.def { Client.optsTimeout = 10 }+    hour = 3600+    tenMs = 0.01     -- The endpoint check only looks for ".cfg" somewhere in the URI, so put it     -- in the path and keep the host a plain loopback address.     endpoint cfg = either error id $