packages feed

memcache 0.5.0.0 → 0.5.1.0

raw patch · 21 files changed

+1964/−362 lines, 21 filesdep ~resource-poolPVP ok

version bump matches the API change (PVP)

Dependency ranges changed: resource-pool

API changes (from Hackage documentation)

+ Database.Memcache.Cluster: serverOpExpecting :: Cluster -> String -> [ByteString] -> Server -> ByteString -> IO Response

Files

CHANGELOG.md view
@@ -1,3 +1,46 @@+# 0.5.1.0 - November 29th, 2026++Fixes found after 0.5.0.0 (#46), with one new function. Some change+behaviour that callers can notice, listed first.++## Behaviour changes++- `flush` sends `flush_all` to every server, including servers marked dead,+  carries on past a server that fails, and throws the first failure at the+  end. A server that is down now slows every flush (#105).+- A server at its connection limit is now retried and failed over, and+  throws `ProtocolError (ServerError "Too many open connections")` instead of+  `UnknownOp "ERROR"` or, with credentials, `InvalidAuthentication`. Other+  `ERROR` replies keep their text in `UnknownOp` (#111).+- `getMany`, `setMany` and `deleteMany` give each reply in a batch its own+  `optsServerTimeout`, instead of one for the whole batch (#112).+- `parseServerSpec` and `parseConfigurationEndpoint` reject a `memcached:`+  URI without `//`, which used to mean the default server (#115).+- An ElastiCache refresh applies a configuration only if its version is+  higher than that of the one applied last, and a version that can't be read+  fails discovery (#109).+- `quit` stops an ElastiCache client's refresh thread, which also stops once+  the client has been garbage collected (#108).++## New++- `serverOpExpecting` in `Database.Memcache.Cluster` runs a request against+  one server, marked dead or not (#105).++## Fixes++- Values over 128 MiB, up to the 1 GiB that stores allow, can be read;+  reading one used to mark the server dead (#110).+- Servers whose `sid` hashes collide are no longer treated as one server, so+  batch operations send each its own keys (#107).+- Credentials may contain tabs, as memcached allows (#116).+- The bounds exclude resource-pool 0.3, which no CI job built (#113).++## Documentation++- What memcached does with expirations of 2^31 or more (#106).+- The `StringException` and `ErrorCall` a client can throw (#114).+ # 0.5.0.0 - November 18th, 2026  This release changes how a cluster routes keys to its servers, so upgrading
Database/Memcache/Auth.hs view
@@ -24,15 +24,28 @@ import Database.Memcache.Types import Database.Memcache.Types.Authentication (validateCredentials) -import Control.Monad (unless)+import Control.Monad (void, when) import qualified Data.ByteString.Char8 as B8 import UnliftIO.Exception (catch, throwIO) --- | Authenticate a connection using text-protocol credentials. Throws--- 'InvalidAuthentication' when the credentials can't be sent safely,--- @'OpError' 'TextAuthFail'@ when the server rejects them, and another--- 'MemcacheError', such as 'UnexpectedResponse', for any other reply but--- @STORED@.+-- | 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@@ -44,8 +57,20 @@   -- never send them to a server that isn't gating on auth-file mode.   sendRaw socket versionRequest   probe <- recvResponse socket-  unless (responseCode probe == "CLIENT_ERROR") $ throwIO $ ClientError-    (InvalidAuthentication "server is not in auth-file mode; refusing to send credentials")+  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
Database/Memcache/Client.hs view
@@ -33,17 +33,29 @@  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.+'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.  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-                free connection to the server, and consider it failed.+                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. -* __Retry__: on operation failure (a timeout, a network error, or a+* __Retry__: on operation failure (a timeout, a network error, a              @SERVER_ERROR@ reply whose text names no status, such as-             memcached's proxy sends when a backend fails) we close the+             memcached's proxy sends when a backend fails, or the+             @ERROR Too many open connections@ that memcached sends to a new+             connection when it is at its connection limit) we close the              connection, if any, and retry the operation, doing this up to              'optsServerRetries' times. Unless the attempt only ran out of time              waiting for a free connection, we also close the server's idle@@ -85,7 +97,10 @@                 configurable period of time has passed, we consider the server                 alive again and try to use it. This can lead to consistency                 issues (stale data), but is usually fine for caching purposes-                and is the common approach in Memcached clients.+                and is the common approach in Memcached clients. 'flush' is+                the exception: it goes to every server, including those marked+                dead, so that none serves values from before the flush once it+                is used again.  Some of this behavior can be configured through the 'Options' data type. We also have the following concepts exposed by Memcached:@@ -97,7 +112,7 @@               version matches it, except that a 'Version' of @0@ skips the               check. -  [@expiration@] Each value pair has an 'Expiration' associated with it. Once a+  [@expiration@] Each value pair has an 'Expiration' associated with it. Once                  a value expires, it will no longer be returned from the cache                  until a new value for that key is set. Expirations come in two                  forms, the first form interprets the expiration value as the@@ -107,11 +122,49 @@                  is greater than 30 days however (@2592000@), the expiration                  field is instead interpreted as a UNIX timestamp (the number                  of seconds since epoch). The timestamp specifies the date at-                 which the value should expire.+                 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.    [@flags@] Each value can have a small amount of fixed metadata associated             with it beyond the value itself, these are the 'Flags'. +  [@value size@] A value can be up to 1 GiB long. The operations that store+                 one throw 'OpError' 'ErrValueTooLarge' for a longer value+                 before sending anything, and a reply that claims a longer+                 value throws v'ProtocolError' 'BadLength'. memcached stores+                 values only up to its item size limit (@-I@, 1 MiB by+                 default and 1 GiB at most), and answers a longer one with+                 'ErrValueTooLarge' too. The limit is on the whole item,+                 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+                 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.+ Usage is roughly as follows:  > {-# LANGUAGE OverloadedStrings #-}@@ -174,6 +227,8 @@ import           Database.Memcache.Server import           Database.Memcache.Socket import           Database.Memcache.Types+import           Database.Memcache.Types.Cluster (Cluster (cStopRefresh))+import           Database.Memcache.Util    (maxValueLength)  import           Control.Exception         (uninterruptibleMask_) import           Control.Monad             (foldM, forM_, when)@@ -183,7 +238,7 @@ import           Data.Default import           Data.Maybe                (fromMaybe, listToMaybe) import           Data.Word-import           UnliftIO.Exception        (Exception, bracket, handle, throwIO)+import           UnliftIO.Exception        (Exception, SomeException, bracket, handle, throwIO, try)  -- | A Memcached cluster client. type Client = Cluster@@ -198,12 +253,12 @@ -- 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--- (with resource-pool 0.3, one for each capability), so concurrent requests to--- a server beyond that wait for a free connection. The wait counts towards--- each attempt's 'optsServerTimeout'. 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.+-- connections as 'soNumResources' and 'soNumStripes' allow, one 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+-- 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. -- -- Nothing is sent until an operation needs a connection to a server. Each new -- connection then checks the server's version, and refuses a server older than@@ -228,8 +283,18 @@ -- Like 'closeAll', it can't be cut short by an asynchronous exception: one -- that arrives while it closes connections is delivered once every server's -- idle connections are closed.+--+-- For a client made by "Database.Memcache.ElastiCacheClient"'s @newClient@,+-- '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+-- used after 'quit', it keeps the servers it had. quit :: Client -> IO ()-quit c = getServers c >>= uninterruptibleMask_ . mapM_ closeAll+quit c = do+  cStopRefresh c+  getServers c >>= uninterruptibleMask_ . mapM_ closeAll  -- | Create a client with 'newClient', run an action with it, and close the -- client's connections with 'quit' when the action returns or throws.@@ -266,6 +331,14 @@     _ -> failResponse response "GET"  -- | Fetch many keys. 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:+-- 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/ keys for about /n/ + 1 timeouts per attempt, as /n/ calls to 'get'+-- would. getMany :: Client -> [Key] -> IO [(Key, (Value, Flags, Version))] getMany c keys = do   replies <- keyedBatchOp c [(key, getManyRequest) | key <- keys]@@ -306,9 +379,9 @@ -- | Store a new (or overwrite existing) key-value pair, returning its @Version@ -- identifier. Use an expiration value of @0@ to store forever. ----- A value larger than 1 GiB, the largest item any memcached server can store,--- throws 'OpError' 'ErrValueTooLarge' before anything is sent, as it does in--- every operation that stores a value.+-- A value larger than 1 GiB, more than any memcached server can store, throws+-- '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" @@ -323,11 +396,15 @@ -- 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 -- 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), and each batch, like a--- 'set', must finish within 'optsServerTimeout'. When a server fails--- part-way through, the requests it was handling are sent again, storing the--- same values; the versions returned are from the retry. If this throws,--- some of the pairs may have been stored.+-- 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+-- 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+-- /n/ + 1 timeouts per attempt, as /n/ calls to 'set' would. When a server+-- fails part-way through, the requests it was handling are sent again,+-- storing the same values; the versions returned are from the retry. If this+-- 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@@ -399,11 +476,6 @@     NoError -> return $ responseCas response     _ -> failResponse response operation --- | 1 GiB, memcached's @ITEM_SIZE_MAX_UPPER_LIMIT@. No memcached server can--- store a larger item, so none can store a longer value.-maxValueLength :: Int-maxValueLength = 1073741824- -- | Reject a value longer than @maxValueLength@ before anything is sent. -- memcached can't store it, and one longer than 2147483645 bytes would make -- it run the rest of the value's bytes as commands. This evaluates the value@@ -504,6 +576,12 @@ -- | Delete many keys, pipelining the requests to each server as 'getMany' -- does. The deletes are unconditional, like 'delete' with a version of @0@. --+-- 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+-- 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.+-- -- This returns once each key has been deleted or found missing, without -- saying which: when a server fails part-way through, the requests it was -- handling are sent again, and the retry finds the keys the first attempt@@ -525,15 +603,47 @@  -- | Remove (delete) all currently stored key-value pairs from the cluster. The -- expiration value can be used to cause this flush to occur in the future--- rather than immediately. The servers are flushed in turn, and one that--- fails, or gives a reply other than @OK@, throws and leaves the servers--- after it unflushed.+-- 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.+--+-- @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+-- a server that is down delays every flush, even while it is marked dead: by+-- 'optsFailRetryDelay' before each retry, and by 'optsServerTimeout' for each+-- attempt it doesn't answer.+--+-- A server that fails, or gives a reply other than @OK@, doesn't stop the+-- servers after it from being flushed. Once every server has been tried, the+-- first such failure is thrown, and every server that didn't fail has been+-- flushed. 'NoServersReady' is thrown only when the client has no servers. flush :: Client -> Maybe Expiration -> IO () flush c e = do-  results <- allOpExpecting c "FLUSH" ["OK"] (flushRequest e)-  forM_ results $ \(_, response) -> do-    status <- responseStatus response-    when (status /= NoError) $ failResponse response "FLUSH"+  servers <- getServers c+  when (null servers) $ throwIO (ClientError NoServersReady)+  outcomes <- mapM flushServer servers+  mapM_ (either throwIO return) outcomes+  where+    -- A server's failure is kept until every server has been tried. 'try'+    -- lets asynchronous exceptions through, so the caller can still+    -- interrupt the flush.+    flushServer :: Server -> IO (Either SomeException ())+    flushServer s = try $ do+      response <- serverOpExpecting c "FLUSH" ["OK"] s (flushRequest e)+      status <- responseStatus response+      when (status /= NoError) $ failResponse response "FLUSH"  -- | Return statistics on the stored key-value pairs at every available server -- in the cluster. The optional key can be used to select a different set of
Database/Memcache/Cluster.hs view
@@ -65,6 +65,11 @@ 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@@ -136,13 +141,15 @@          -- * Operations         Retries, keyedOp, keyedOpExpecting, keyedOpExpectingOnce, keyedBatchOp,-        anyOp, anyOpExpecting, allOp, allOpExpecting, allOp'+        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)@@ -186,10 +193,14 @@         -- 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. Other-        -- error replies are answers, thrown at once without counting against-        -- the server: @ERROR@, @CLIENT_ERROR@, and a @SERVER_ERROR@ whose text-        -- names a status, such as running out of memory.+        -- 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@@ -229,19 +240,33 @@         -- Default is 200ms.         optsFailRetryDelay       :: Milli,         -- | How long to wait after a server has been marked down, before-        -- trying to use it again.+        -- 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. @getMany@, @setMany@ and @deleteMany@ make their-        -- attempts for each batch, and @stats@ and @flush@ 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.+        -- 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@@ -250,6 +275,11 @@         -- 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.@@ -293,24 +323,6 @@ instance Default Options where   def = defaultOptions --- | Memcached cluster.-data Cluster = Cluster {-        -- | Either servers that discovery replaces, or a fixed set of servers-        -- and their ketama ring, built on first use.-        cServers         :: Either (MVar (V.Vector Server)) (V.Vector Server, Ketama.Ring),-        -- | For servers in an 'MVar': the ketama ring last built and the-        -- servers it was built for.-        cRingCache       :: IORef (V.Vector Server, Ketama.Ring),--        -- See @Options@ for description of these values.--        cRetries         :: {-# UNPACK #-} !Int,-        cFailDelay       :: {-# UNPACK #-} !Int, -- ^ microseconds-        cDeadDelay       :: !NominalDiffTime,-        cTimeout         :: {-# UNPACK #-} !Int, -- ^ microseconds-        cGetServerForKey :: Cluster -> Key -> IO (Maybe Server)-    }- -- | Get the currently configured servers. getServers :: Cluster -> IO (V.Vector Server) getServers = either readMVar (pure . fst) . cServers@@ -323,8 +335,13 @@ -- 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 }+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@@ -341,7 +358,8 @@             cFailDelay = toMicroseconds optsFailRetryDelay,             cDeadDelay = fromRational $ toRational optsDeadRetryDelay / 1000,             cTimeout   = toMicroseconds optsServerTimeout,-            cGetServerForKey = optsGetServerForKey+            cGetServerForKey = optsGetServerForKey,+            cStopRefresh = pure ()         }  -- | Convert a duration in milliseconds to the microseconds that 'threadDelay'@@ -494,7 +512,7 @@ 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 $ \sent s' -> withSocket s' $ \connection -> do+  retryOp c s PerAttempt $ \sent s' _ -> withSocket s' $ \connection -> do     when (resend == SendOnce) $ do       checkIdle connection       writeIORef sent True@@ -535,9 +553,10 @@ -- '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. 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.+-- 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@@ -611,6 +630,15 @@ -- 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@@ -649,9 +677,12 @@     -- 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.-    runBatch server items = retryOp c server $ \_ server' -> withSocket server' $ \connection -> do-      sendRaw connection (B.concat (map request items ++ [noOpRequest]))-      recvUntilMN connection items []+    -- 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@@ -667,14 +698,14 @@     -- 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 connection pending acc = do-      response <- recvResponse connection+    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 connection rest acc+        ("EN", Nothing) | _ : rest <- pending -> recvUntilMN restartTimeout connection rest acc         (_, opaque) -> case dropWhile (\(_, opaque', _) -> Just opaque' /= opaque) pending of-          (key, _, _) : rest -> recvUntilMN connection rest ((key, response) : acc)+          (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)) }@@ -683,10 +714,12 @@      batchSize = 256 :: Int -    -- Each batch must be sent and answered within the server timeout, so a-    -- batch also closes once its requests reach 1 MiB, memcached's default-    -- item size limit. A batch is then no larger than a single large store;-    -- a request over the limit goes in a batch of its own.+    -- 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 [] = []@@ -725,26 +758,42 @@         Nothing     -> throwIO $ ClientError NoServersReady         Just (s, _) -> serverOp c s Resend check req --- | Run a Memcached operation against all servers 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;--- '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.+-- | 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.+-- 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 Memcached operation against all servers in the cluster, handling any--- failures that occur, retrying the specified number of times. Similar to+-- | 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@@ -760,7 +809,7 @@ -- 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 (const op)+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.@@ -774,23 +823,35 @@             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 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'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 -> (IORef Bool -> Server -> IO a) -> IO a+retryOp :: forall a. Cluster -> Server -> Timing -> (IORef Bool -> Server -> IO () -> IO a) -> IO a {-# INLINE retryOp #-}-retryOp Cluster{..} s op = go cRetries+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,@@ -804,11 +865,15 @@         sent <- newIORef False         try (attempt sent) >>= either (handleErrs n sent) return -    -- One attempt at the operation, with its own timeout and @slotTaken@.+    -- One attempt at the operation, with its own timeout or timeouts and+    -- @slotTaken@.     attempt :: IORef Bool -> IO a     attempt sent = do         taken <- newIORef False-        mr <- timeout cTimeout (op sent s { slotTaken = Just taken })+        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@@ -860,8 +925,10 @@ -- 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. Nor is a reply out of step retried or counted: the server has the--- request, and may have carried it out.+-- 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
Database/Memcache/ElastiCacheClient.hs view
@@ -18,20 +18,24 @@   ) where -import Control.Concurrent (forkIOWithUnmask, threadDelay)-import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar)-import Control.Monad (guard, when)+import Control.Concurrent (forkIO, forkIOWithUnmask, killThread, threadDelay)+import Control.Concurrent.MVar (MVar, mkWeakMVar, modifyMVar, newMVar)+import Control.Monad (guard, void, when) import Data.Bifunctor (first) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as C+import Data.Char (isAscii, isSpace)+import Data.IORef (IORef, atomicWriteIORef, newIORef, readIORef) import Data.List (sort) import qualified Data.List.NonEmpty as NE+import Data.Maybe (isJust) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T 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 qualified Database.Memcache.Client as Client import Database.Memcache.Cluster (Options, getServers, setServers)@@ -39,12 +43,14 @@ import Database.Memcache.Server (Server, closeAll, withSocket) import Database.Memcache.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, withDetail)+import Database.Memcache.Util (note, readDecimal, 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, throwIO, throwString, tryAny, uninterruptibleMask_)+import UnliftIO.Exception (bracket, finally, mask_, throwIO, throwString, tryAny, uninterruptibleMask_)  -- | Parse an ElastiCache configuration endpoint. --@@ -52,6 +58,9 @@ -- -- https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/AutoDiscovery.Using.html --+-- The rest is read as 'parseServerSpec' reads a server, so the endpoint must+-- begin @memcached:\/\/@, as in+-- @memcached:\/\/mycluster.abc123.cfg.use1.cache.amazonaws.com:11211@. parseConfigurationEndpoint :: String -> Either String ConfigurationEndpoint parseConfigurationEndpoint url = do   note "URI does not contain '.cfg'" $ guard $ ".cfg" `T.isInfixOf` T.pack url@@ -108,28 +117,46 @@ -- 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 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+-- 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'. --+-- A configuration begins with its version, a number that, as AWS documents+-- it, goes up by one each time a node is added to the cluster or removed from+-- it. Discovery reads the version as a number in decimal digits, ignoring+-- ASCII whitespace around it, and can't read one with anything else in it,+-- such as a sign or a decimal point, or one too large for 64 bits. The first+-- discovery takes its configuration whatever the version. After that, a+-- refresh applies a configuration only if its version is higher than that of+-- the configuration applied last, the first discovery's included, and+-- otherwise leaves the servers as they are, whatever nodes and IP addresses+-- it lists. So a reply from an endpoint that hasn't caught up with a change+-- yet doesn't roll the servers back. But a version that goes backwards is+-- ignored until the client is made again, or until it passes the version+-- applied last. AWS's own cluster client does the same, except that its+-- refreshes don't count the configuration it was made with, so the first of+-- them to read a configuration applies it even at a lower or the same+-- version.+-- -- Servers are made by calling 'optsServerSpecsToServers' with one node at a--- time. A refresh keeps the 'Server', and so the failure state, of every node--- still listed with the same host and port, and its connections too unless the--- node is listed with another IP address. It makes servers only for new nodes,--- and closes the connections of nodes no longer listed: idle ones at once, and--- one in use as soon as its request finishes. It closes the connections of a--- node listed with another IP address the same way, as ElastiCache lists a--- node it has replaced, so that its requests connect again, looking its name--- up afresh. If the name still resolves to the replaced node's address then,--- they connect to it, and later refreshes don't close those connections, as--- the listed address no longer changes.+-- time. A refresh that applies a configuration keeps the 'Server', and so the+-- failure state, of every node still listed with the same host and port, and+-- its connections too unless the node is listed with another IP address. It+-- makes servers only for new nodes, and closes the connections of nodes no+-- longer listed: idle ones at once, and one in use as soon as its request+-- finishes. It closes the connections of a node listed with another IP+-- address the same way, as ElastiCache lists a node it has replaced, so that+-- its requests connect again, looking its name up afresh. If the name still+-- resolves to the replaced node's address then, they connect to it, and later+-- refreshes don't close those connections, as the listed address no longer+-- changes. -- -- Each refresh connects to the endpoint afresh, looking its name up again, and -- closes that connection when it is done, whether it worked or not: the name@@ -137,11 +164,21 @@ -- could lead to a node that ElastiCache has since replaced, and get no reply. -- Each refresh has the same time and length limits as the first discovery. A -- refresh that fails, for example because it runs out of time or the reply is--- an error, is too long, can't be parsed, lists no nodes, more than 1,000, an--- empty node or one twice, or lists a node that isn't a plain host and port,--- leaves the servers as they are, and discovery tries again after the next+-- an error, is too long, can't be parsed, has a version that can't be read,+-- lists no nodes, more than 1,000, an empty node or one twice, or lists a node+-- that isn't a plain host and port, leaves the servers as they are, and with+-- them the version applied last, and discovery tries again after the next -- interval. --+-- The thread stops for good when the client is closed with+-- 'Database.Memcache.Client.quit'. No refresh replaces the servers once their+-- connections are closed, and a refresh in progress is abandoned, closing its+-- connection to the endpoint. The thread also stops once the client has been+-- garbage collected, as it doesn't keep the client reachable: at the end of+-- the interval it is waiting out, or, if a refresh is in progress, without+-- replacing the servers: when that refresh would replace them, or else at the+-- end of the next interval.+-- -- Discovery connects to the configuration endpoint like any other server, so -- it fails for a cluster running a memcached older than 1.6.10, having sent -- only the authentication exchange, when the endpoint has credentials, and@@ -155,35 +192,78 @@ newClient options interval cfgEndpoint = bracket acquireCfgClient releaseCfgClient resolveCluster'   where     acquireCfgClient = Client.newClient [unConfigurationEndpoint cfgEndpoint] options+    -- This quits the first discovery's client, not the client returned, so+    -- it doesn't stop the refresh thread.     releaseCfgClient = Client.quit     resolveCluster' cfgClient = do-      serverSpecs <- resolveClusterWithin options cfgClient+      -- The first discovery applies its configuration whatever the version.+      (version, serverSpecs) <- resolveClusterWithin options cfgClient       (nodes, _, _) <- reuseServers options [] serverSpecs        -- Prepare MVar       serversMVar <- newMVar $ nodeServers nodes+      -- The refresh thread gets the MVar only through a weak pointer, so+      -- that it doesn't keep the client reachable, and can stop once the+      -- client has been garbage collected.+      servers <- mkWeakMVar serversMVar (pure ())+      stopped <- newIORef False       -- Refresh with asynchronous exceptions unmasked, whatever the caller's       -- masking state. A thread forked inside mask_, as in a bracket's       -- acquire, would otherwise refresh masked for good, and each refresh's       -- time limit could interrupt it only where it waits.-      _ <- forkIOWithUnmask $ \unmask ->-        unmask $ repeatAutoDiscover options interval cfgEndpoint serversMVar nodes+      thread <- forkIOWithUnmask $ \unmask ->+        unmask $ repeatAutoDiscover options interval cfgEndpoint servers stopped version nodes+      -- What 'Client.quit' runs before it closes the servers' connections.+      -- Once the flag is set, no refresh replaces the servers. Killing the+      -- thread abandons a refresh in progress, but the kill alone can't stop+      -- 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.+      let stop = mask_ $ do+            atomicWriteIORef stopped True+            void $ forkIO $ killThread thread        -- The configuration client was made with the same options, so it only       -- needs its servers replacing: cServers = Left <MVar <Vector Server>>-      pure $ setServers cfgClient $ Left serversMVar+      pure (setServers cfgClient $ Left serversMVar) { cStopRefresh = stop } -repeatAutoDiscover :: Options -> Int -> ConfigurationEndpoint -> MVar (V.Vector Server) -> Nodes -> IO ()-repeatAutoDiscover opts interval cfgEndpoint mVar initialNodes = do+-- | Refresh the servers in the 'MVar' every interval, starting from the+-- configuration version and the nodes of the first discovery, until the flag+-- is set or the 'MVar' has been garbage collected. AWS's own cluster client+-- starts its refreshes from version -1 instead, whatever the version of the+-- configuration it was made with, so the first of them to read a+-- configuration applies it even at a lower or the same version. Starting from+-- 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+  -> ConfigVersion -> Nodes -> IO ()+repeatAutoDiscover opts interval cfgEndpoint servers stopped initialVersion initialNodes = do   cfgClient <- Client.newClient [unConfigurationEndpoint cfgEndpoint] opts-  let refresh nodes = do+  -- Wait out the interval, then refresh, unless the client has been quit or+  -- 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+        quitting <- readIORef stopped+        reachable <- isJust <$> deRefWeak servers+        when (reachable && not quitting) $ refresh version nodes+      refresh version nodes = do         -- A refresh that fails or does not finish in time keeps the current         -- servers. 'tryAny' lets asynchronous exceptions, such as         -- 'killThread', through.         result <- tryAny $ do-          serverSpecs <- resolveClusterWithin opts cfgClient-          reuseServers opts nodes serverSpecs+          (version', serverSpecs) <- resolveClusterWithin opts cfgClient+          -- Apply only a configuration newer than the one applied last, so+          -- that one from an endpoint that hasn't caught up with a change yet+          -- can't roll the servers back. Make no servers for any other.+          if version' > version+            then do+              (nodes', gone, moved) <- reuseServers opts nodes serverSpecs+              pure $ Just (version', nodes', gone, moved)+            else pure Nothing         -- Close the connection to the endpoint, whether the refresh worked or         -- not, so that the next refresh connects again, looking the         -- endpoint's name up afresh. The name leads to one of the nodes, and@@ -191,8 +271,10 @@         -- may get no reply, so the next refresh would run out of time on it.         Client.quit cfgClient         case result of-          Left _ -> refresh nodes-          Right (nodes', gone, moved) -> do+          -- The refresh failed, or its configuration is no newer.+          Left _ -> next version nodes+          Right Nothing -> next version nodes+          Right (Just (version', nodes', gone, moved)) -> do             -- Swap in the new servers, then close the connections of nodes             -- that have gone, or whose IP address has changed. A request             -- still using one of them finishes normally, and its connection@@ -200,12 +282,24 @@             -- and the loop together, so that an asynchronous exception can't             -- arrive between them, or stop the loop part way, and leave some             -- of those connections open. Neither waits long: only this thread-            -- takes the 'MVar', and 'closeAll' only ever waits briefly.-            uninterruptibleMask_ $ do-              modifyMVar_ mVar $ \_curServers -> pure $ nodeServers nodes'-              mapM_ closeAll (gone ++ moved)-            refresh nodes'-  refresh initialNodes+            -- takes the 'MVar', and 'closeAll' only ever waits briefly. Once+            -- the client has been quit or garbage collected, swap nothing in,+            -- and stop.+            swapped <- uninterruptibleMask_ $ do+              target <- deRefWeak servers+              replaced <- maybe (pure False) (swapTo nodes') target+              when replaced $ mapM_ closeAll (gone ++ moved)+              pure replaced+            when swapped $ next version' nodes'+      -- 'Client.quit' sets the flag before it reads the servers to close+      -- their connections, so checking the flag while holding the 'MVar'+      -- means that no refresh swaps in servers that quit doesn't close.+      swapTo nodes' mVar = modifyMVar mVar $ \current -> do+        quitting <- readIORef stopped+        pure $ if quitting then (current, False) else (nodeServers nodes', True)+  -- Close the connection to the endpoint too when the thread is killed, as+  -- 'Client.quit' does to a refresh in progress.+  next initialVersion initialNodes `finally` Client.quit cfgClient  -- | The nodes found by discovery, by host and port, with the IP address listed -- for each and the servers made for each.@@ -231,7 +325,9 @@   (nodes, gone, moved') <- reuseServers opts rest specs   pure ((node, (ip, servers)) : nodes, gone, if moved then servers ++ moved' else moved') -resolveCluster :: Client -> IO [(ServerSpec, Text)]+-- | Ask the endpoint for the cluster's configuration, and return its version+-- and nodes.+resolveCluster :: Client -> IO (ConfigVersion, [(ServerSpec, Text)]) resolveCluster cfgClient = do   servers <- getServers cfgClient @@ -252,14 +348,15 @@         then resolveViaConfigCmd socket         else resolveViaAutoDiscoveryKey socket -    rawNodeInfo <- unTry $ handleConfigGetClusterResponse rawResponse+    (cfgVersion, rawNodeInfo) <- unTry $ handleConfigGetClusterResponse rawResponse -    unTry $ handleRawNodeInfo rawNodeInfo+    nodes <- unTry $ handleRawNodeInfo rawNodeInfo+    pure (cfgVersion, nodes)  -- Run 'resolveCluster', throwing 'ClientError' 'Timeout' unless it finishes, -- connecting and both requests included, within the options' -- 'optsServerTimeout'.-resolveClusterWithin :: Options -> Client -> IO [(ServerSpec, Text)]+resolveClusterWithin :: Options -> Client -> IO (ConfigVersion, [(ServerSpec, Text)]) resolveClusterWithin opts cfgClient = do   found <- timeout serverTimeout $ resolveCluster cfgClient   maybe (throwIO $ ClientError Timeout) pure found@@ -267,16 +364,43 @@     -- 'optsServerTimeout' is in milliseconds; 'timeout' takes microseconds.     serverTimeout = truncate (optsServerTimeout opts * 1000) --- Handle the raw response from /memcached/.+-- Handle the raw response from /memcached/, returning the configuration's+-- version and its line of nodes. Both requests get the configuration in the+-- same form: after the line that starts the reply, a line with the version and+-- one listing the nodes. -- -- See: https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/AutoDiscovery.AddingToYourClientLibrary.html#AutoDiscovery.AddingToYourClientLibrary.OutputFormat-handleConfigGetClusterResponse :: ByteString -> Either String Text+handleConfigGetClusterResponse :: ByteString -> Either String (ConfigVersion, Text) handleConfigGetClusterResponse bs = do   text <- first show $ T.decodeUtf8' bs    case T.lines text of-    [_, _, nodeInfo, _, _] -> pure $ T.strip nodeInfo+    [_, version, nodeInfo, _, _] -> do+      cfgVersion <- parseConfigVersion version+      pure (cfgVersion, T.strip nodeInfo)     xs -> Left $ "Unrecognized number of lines: " <> show (length xs)++-- | A configuration's version, which ElastiCache raises each time a node is+-- added to the cluster or removed from it.+type ConfigVersion = Word64++-- | Read a configuration's version. Drop the ASCII whitespace around it+-- first: AWS documents the line as ending in LF alone, and one that ends in+-- CR LF reads the same. What is left must be a number in decimal digits alone+-- that fits in 64 bits. AWS's own cluster client for Java reads the version+-- with Java's @trim@ and @Long.parseLong@, so it also drops the control+-- characters around it, and takes a sign and digits outside ASCII, such as+-- Arabic-Indic ones, but stops at 2^63 - 1, the largest Java @long@. A+-- version comes from a counter, so this takes only ASCII digits, but any+-- number that fits in 64 bits.+parseConfigVersion :: Text -> Either String ConfigVersion+parseConfigVersion line =+  note ("Unrecognized configuration version" `withDetail` T.unpack line) $+    readDecimal (T.encodeUtf8 (T.dropAround isAsciiSpace line))+  where+    -- Not 'T.strip', which would also drop whitespace outside ASCII, such as+    -- a no-break space.+    isAsciiSpace c = isAscii c && isSpace c  -- Handle node information --
Database/Memcache/Errors.hs view
@@ -25,7 +25,15 @@  import           UnliftIO.Exception --- | All exceptions that a Memcached client may throw.+-- | 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,+-- when a client is created, and a Unix socket path too long for the system,+-- when an operation connects to it. -- -- 'displayException' gives a one-line message for logs and users, such as -- @memcached operation failed: key not found@. Any detail, such as text the@@ -67,7 +75,8 @@     -- also throws it when its first discovery takes longer than the timeout.     | Timeout     -- | Credentials were rejected before being sent: they contain a-    -- forbidden delimiter, or the server is not in auth-file mode.+    -- 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.@@ -78,9 +87,12 @@ data ProtocolError     -- | Received an unknown response line.     = UnknownPkt    { protocolError :: String }-    -- | Unknown Memcached operation. Also thrown when a new connection asks-    -- the server for its version and the reply is a version below 1.6.10, or-    -- any other reply that is neither an error nor a readable version; the+    -- | Unknown Memcached operation: the server replied @ERROR@, as memcached+    -- does to a command it doesn't know. The message is the reply's line,+    -- such as @\"ERROR\"@. memcached's @ERROR Too many open connections@ is+    -- a 'ServerError' instead. Also thrown when a new connection asks the+    -- server for its version and the reply is a version below 1.6.10, or any+    -- other reply that is neither an error nor a readable version; the     -- message quotes the reply. The connection is then closed, having sent     -- only the authentication exchange, when credentials are set, and     -- @version@.@@ -91,7 +103,13 @@     | BadLength     { protocolError :: String }     -- | Response is for a different operation than expected.     | UnexpectedResponse { protocolError :: String }-    -- | Memcached reported a server failure.+    -- | Memcached reported a server failure: a @SERVER_ERROR@ reply whose+    -- text names no status, with that text as the message, or 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@), 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').     | ServerError   { protocolError :: String }     -- | Memcached rejected the command.     | BadCommand    { protocolError :: String }
Database/Memcache/Server.hs view
@@ -69,21 +69,25 @@ -- -- 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.3,-  -- see 'soNumStripes'. With 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'.+  -- | 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.3, a pool has a stripe for-  -- each capability instead, and each stripe holds up to 'soNumResources'-  -- times 'soNumStripes' connections divided by the number of capabilities,-  -- rounded up. A thread then takes connections from its own capability's-  -- stripe, so a request can wait for one while other stripes have room. With-  -- 0.4 and 0.5.0.0, stripes beyond the number of capabilities are never used.+  -- | 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.@@ -100,8 +104,8 @@ -- * 'soNumStripes': 1 -- * 'soKeepAlive': 300 seconds ----- That is, at most one connection to each server (with resource-pool 0.3, one--- for each capability), closed once it has been idle for 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@@ -267,11 +271,16 @@ -- -- 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. 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.+-- 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
Database/Memcache/Socket.hs view
@@ -36,6 +36,7 @@  import           Database.Memcache.Errors import           Database.Memcache.Types+import           Database.Memcache.Util    (maxValueLength, readDecimal)  import           Control.Monad             (unless) import           Data.ByteString           (ByteString)@@ -149,6 +150,12 @@ 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@@ -164,8 +171,11 @@       [] | 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 <= 128 * 1024 * 1024 -> return n+      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@@ -175,7 +185,18 @@     splitTokens line =       filter (not . B.null) (C.split ' ' (fromMaybe line (B.stripSuffix "\r" line))) --- | Convert a response code and tokens to the corresponding status.+-- | 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@@ -193,11 +214,19 @@   "MN"           -> return NoError   "SERVER_ERROR" -> serverFailure   "CLIENT_ERROR" -> clientFailure-  "ERROR"        -> throwIO $ ProtocolError UnknownOp { protocolError = "ERROR" }+  "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@@ -229,24 +258,6 @@   token <- find (B.isPrefixOf prefix) xs   readDecimal (B.drop (B.length prefix) token) --- | Read a number from a reply. Memcached writes value lengths, CAS values,--- flags and counter values as plain decimal digits, so accept exactly that: at--- least one digit and nothing else, not even a sign or a space. A number too--- large for the type is rejected rather than wrapped around.-readDecimal :: (Integral a, Bounded a) => ByteString -> Maybe a-readDecimal input-  | B.null input = Nothing-  | otherwise = go 0 input-  where-    go !n rest = case B.uncons rest of-      Nothing -> Just n-      Just (byte, rest')-        | byte < 0x30 || byte > 0x39 -> Nothing-        | n > limit || (n == limit && digit > lastDigit) -> Nothing-        | otherwise -> go (n * 10 + digit) rest'-        where digit = fromIntegral (byte - 0x30)-    (limit, lastDigit) = maxBound `quotRem` 10- -- | Longest response line accepted before assuming the stream is desynchronised. maxLineLength :: Int maxLineLength = 8 * 1024@@ -465,10 +476,11 @@ -- 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, the largest item memcached 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.+-- 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)@@ -485,10 +497,11 @@ -- 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, the largest item memcached 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.+-- 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)@@ -515,10 +528,11 @@ -- 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, the largest item memcached 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.+-- 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)
+ Database/Memcache/Timeout.hs view
@@ -0,0 +1,116 @@+{-# LANGUAGE CPP #-}++{-|+Module      : Database.Memcache.Timeout+Description : A timeout that its action can start again+Copyright   : (c) David Terei, 2026+License     : BSD+Maintainer  : code@davidterei.com+Stability   : internal+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.++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.+-}+module Database.Memcache.Timeout (+        timeoutRestartable+    ) where++import           Control.Concurrent       (forkIOWithUnmask, killThread, myThreadId, threadDelay, throwTo)+#if !defined(mingw32_HOST_OS)+import qualified Control.Concurrent       as Concurrent+#endif+import           Control.Concurrent.MVar  (newEmptyMVar, takeMVar, tryPutMVar)+import qualified Control.Exception        as E+import           Control.Monad            (unless, void, when)+import           Data.IORef               (atomicWriteIORef, newIORef, readIORef)+import           Data.Unique              (Unique, newUnique)+import           GHC.Clock                (getMonotonicTimeNSec)+#if !defined(mingw32_HOST_OS)+import qualified GHC.Event                as Event+#endif++-- | Like 'System.Timeout.timeout', but the action is given an action that+-- starts its time again, from the moment it is run, by moving its deadline.+-- Once the time first runs out, a watchdog thread reads the deadline: if it+-- has passed, the watchdog throws the action an exception of its own, and+-- otherwise it sleeps until the deadline and reads it again. The watchdog is+-- stopped once the action has finished, so the exception never reaches the+-- caller (see 'withWatchdog'). As with 'System.Timeout.timeout', a time below+-- zero means none, and zero gives 'Nothing' without running the action.+timeoutRestartable :: Int -> (IO () -> IO a) -> IO (Maybe a)+timeoutRestartable usecs action+    | usecs < 0 = Just <$> action (return ())+    | usecs == 0 = return Nothing+    | otherwise = do+        worker <- myThreadId+        expired <- TimedOut <$> newUnique+        deadline <- newIORef =<< later+        let restart = later >>= atomicWriteIORef deadline+            -- Sleep at most 1,000 s at a time, which threadDelay takes on+            -- any platform, and check again.+            watch = do+                now <- nanoseconds+                end <- readIORef deadline+                if now < end+                    then threadDelay (fromInteger (min 1000000000 ((end - now) `div` 1000 + 1))) >> watch+                    else throwTo worker expired+        E.handleJust (\e -> if e == expired then Just () else Nothing) (const (return Nothing)) $+            withWatchdog usecs watch (Just <$> action restart)+  where+    nanoseconds = toInteger <$> getMonotonicTimeNSec+    later = (+ toInteger usecs * 1000) <$> nanoseconds++-- | Run an action with a watchdog thread, started once the given time has+-- passed, and stopped once the action has finished. The watchdog claims a+-- lock before it does anything else, and the cleanup either takes the lock+-- first, so that the watchdog, if it starts, does nothing, or kills the+-- watchdog that holds it, as 'System.Timeout.timeout' does. On the threaded+-- runtime, as in 'System.Timeout.timeout', the system's timer manager starts+-- the watchdog, so an action that finishes in time starts no thread.+-- Elsewhere there is no timer manager, and the watchdog starts at once, as the+-- thread of 'System.Timeout.timeout' does: the watch begins by sleeping until+-- the deadline.+withWatchdog :: Int -> IO () -> IO a -> IO a+withWatchdog usecs watch run = do+    lock <- newEmptyMVar+    let start = void $ forkIOWithUnmask $ \unmask -> unmask $ do+            claimed <- tryPutMVar lock . Just =<< myThreadId+            when claimed watch+        -- True if the watchdog never claimed the lock.+        stop = do+            first <- tryPutMVar lock Nothing+            unless first $ takeMVar lock >>= mapM_ killThread+            return first+    startAfter usecs start stop+  where+#if !defined(mingw32_HOST_OS)+    startAfter time start stop+        | Concurrent.rtsSupportsBoundThreads = do+            manager <- Event.getSystemTimerManager+            E.bracket (Event.registerTimeout manager time start)+                (\key -> E.uninterruptibleMask_ $ do+                    first <- stop+                    when first $ Event.unregisterTimeout manager key)+                (const run)+#endif+    startAfter _ start stop = E.bracket_ start (E.uninterruptibleMask_ stop) run++-- | Thrown by 'timeoutRestartable' to the action it runs, once the action's+-- time has run out. Each call makes its own, and catches only that one. Like+-- the exception of 'System.Timeout.timeout', it is asynchronous, so that+-- handlers for synchronous exceptions let it through.+newtype TimedOut = TimedOut Unique+  deriving Eq++instance Show TimedOut where+  show _ = "<<timeout>>"++instance E.Exception TimedOut where+  toException = E.asyncExceptionToException+  fromException = E.asyncExceptionFromException
Database/Memcache/Types.hs view
@@ -33,7 +33,24 @@ type Initial    = Word64 -- | Arithmetic increment or decrement amount. type Delta      = Word64--- | Expiration in protocol time units.+-- | When a value expires, in seconds: @0@ for never, up to 30 days+-- (@2592000@) a number of seconds from now, and above that a Unix time, so+-- 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. type Expiration = Word32 -- | Application-defined value flags. type Flags      = Word32@@ -50,8 +67,8 @@     -- | The key already exists.     | ErrKeyExists     -- | The value exceeds the server limit. The client also throws this-    -- itself, before sending anything, for a value larger than 1 GiB, the-    -- largest item any memcached server can store.+    -- itself, before sending anything, for a value larger than 1 GiB, more+    -- than any memcached server can store.     | ErrValueTooLarge     -- | The item was not stored.     | ErrItemNotStored
Database/Memcache/Types/Authentication.hs view
@@ -44,9 +44,11 @@ type Password = ByteString  -- | Check credentials before they are sent: neither part may contain a--- space, tab, CR, LF or NUL, and the username may not contain @:@. The+-- space, CR, LF or NUL, and the username may not contain @:@. The -- password may contain @:@, as memcached's auth file splits each line at--- its first @:@.+-- its first @:@. Either part may contain a tab: memcached splits the+-- credentials it is sent at spaces only, and its auth file ends a password+-- only at CR, LF or NUL. validateCredentials :: Username -> Password -> Either String () validateCredentials user pass     | B8.elem ':' user || B8.any forbidden user =@@ -54,4 +56,4 @@     | B8.any forbidden pass = Left "password contains a forbidden delimiter"     | otherwise = Right ()   where-    forbidden c = c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\0'+    forbidden c = c == ' ' || c == '\r' || c == '\n' || c == '\0'
+ Database/Memcache/Types/Cluster.hs view
@@ -0,0 +1,50 @@+{-|+Module      : Database.Memcache.Types.Cluster+Description : The Cluster type+Copyright   : (c) David Terei, 2016+License     : BSD+Maintainer  : code@davidterei.com+Stability   : stable+Portability : GHC++The 'Cluster' type, with all its fields. "Database.Memcache.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           Database.Memcache.Types        (Key)+import           Database.Memcache.Types.Server (Server)++import           Control.Concurrent.MVar        (MVar)+import           Data.IORef                     (IORef)+import           Data.Time.Clock                (NominalDiffTime)+import qualified Data.Vector                    as V++-- | Memcached cluster.+data Cluster = Cluster {+        -- | Either servers that discovery replaces, or a fixed set of servers+        -- and their ketama ring, built on first use.+        cServers         :: Either (MVar (V.Vector Server)) (V.Vector Server, Ketama.Ring),+        -- | For servers in an 'MVar': the ketama ring last built and the+        -- servers it was built for.+        cRingCache       :: IORef (V.Vector Server, Ketama.Ring),++        -- See @Options@ for description of these values.++        cRetries         :: {-# UNPACK #-} !Int,+        cFailDelay       :: {-# UNPACK #-} !Int, -- ^ microseconds+        cDeadDelay       :: !NominalDiffTime,+        cTimeout         :: {-# UNPACK #-} !Int, -- ^ microseconds+        cGetServerForKey :: Cluster -> Key -> IO (Maybe Server),+        -- | Stop the thread that replaces the servers in 'cServers', as+        -- ElastiCache discovery's refresh thread does, so that it can't+        -- replace them once @quit@ has closed their connections: @quit@ runs+        -- this first. It returns at once and doesn't throw. @pure ()@ for+        -- every other cluster, including one made by @setServers@ from an+        -- ElastiCache client, as no thread replaces the servers it is given.+        cStopRefresh     :: IO ()+    }
Database/Memcache/Types/Server.hs view
@@ -21,15 +21,18 @@ import           Database.Memcache.Types        (Authentication)  import           Data.IORef+import           Data.Ord                       (comparing) import           Data.Pool                      (Pool) import           Data.Time.Clock.POSIX          (POSIXTime) import           Network.Socket                 (HostName, ServiceName)  -- | Memcached server connection. data Server = Server {-        -- | Hash of the server's host and port, which the 'Eq' and 'Ord'-        -- instances compare. Only the deprecated @legacyServerForKey@ routes-        -- keys by this value; see "Database.Memcache.Cluster".+        -- | 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".         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@@ -63,8 +66,20 @@   show Server{..} =     "Server [" ++ show sid ++ "] " ++ addr ++ ":" ++ show port +-- | Servers are equal when they have the same host, port and @sid@, whatever+-- their pools, credentials and failure state. @newServerDefault@ sets @sid@+-- to a hash of the host and port, so the servers it makes for the same host+-- and port are equal, even for different clients; a custom+-- @optsServerSpecsToServers@ can set it to anything. instance Eq Server where-    (==) x y = sid x == sid y+    x == y = comparedFields x == comparedFields y +-- | Servers are ordered by @sid@, then by host, then by port. instance Ord Server where-    compare x y = compare (sid x) (sid y)+    compare = comparing comparedFields++-- | What the 'Eq' and 'Ord' instances compare. The 'sid' comes first, so+-- servers whose hashes differ keep the order they had when the instances+-- compared nothing else.+comparedFields :: Server -> (Int, HostName, ServiceName)+comparedFields s = (sid s, addr s, port s)
Database/Memcache/Types/ServerSpec.hs view
@@ -65,6 +65,12 @@  -- | Parse a @memcached://@ URI into a @ServerSpec@. --+-- The URI must have the @\/\/@ that begins its authority, even an empty one,+-- as in @memcached:\/\/@. Without it there is no host, port or credentials to+-- read, so @memcached:cache.example:11211@, @memcached:\/run\/memcached.sock@+-- and @memcached:user:secret\@cache.example@ are errors, not the default+-- server. So is a URI with another scheme.+-- -- The username and password are percent-decoded, so -- @memcached:\/\/user:p%40ss\@cache.example@ has the password @p\@ss@, and -- must pass 'validateCredentials'; one given without the other is ignored.@@ -90,16 +96,20 @@ parseServerSpec :: String -> Either String ServerSpec parseServerSpec s = do   uri <- note "Not a valid URI" $ parseAbsoluteURI s-  note "Must begin memcached://" $ guard $ uriScheme uri == "memcached:"+  -- Without the "//", a URI has no authority, and so no host, port or+  -- credentials: "memcached:cache.example:11211" would be the default server,+  -- with its host and port dropped.+  authority <- note "Must begin memcached://" $ do+    guard $ uriScheme uri == "memcached:"+    uriAuthority uri -  let mAuth = uriAuthority uri-  auth <- maybe (pure Nothing) (readAuthentication . uriUserInfo) mAuth+  auth <- readAuthentication (uriUserInfo authority)   socketPath <- readSocketPath uri    pure     . maybe id setSocketPath socketPath-    . maybe id setHost mAuth-    . maybe id setPort mAuth+    . setHost authority+    . setPort authority     . maybe id setAuth auth     $ defaultServerSpec 
Database/Memcache/Util.hs view
@@ -10,16 +10,39 @@ Small helpers shared by the library's modules. Not exposed. -} module Database.Memcache.Util (+        maxValueLength,         note,+        readDecimal,         withDetail     ) where +import Data.ByteString (ByteString)+import qualified Data.ByteString as B import Data.Char (isAscii, isPrint, showLitChar)  -- | Turn a 'Nothing' into an error. note :: e -> Maybe a -> Either e a note e = maybe (Left e) Right +-- | Read a number that a server sent. Memcached writes value lengths, CAS+-- values, flags and counter values as plain decimal digits, and ElastiCache+-- writes its configuration's version that way, so accept exactly that: at+-- least one digit and nothing else, not even a sign or a space. A number too+-- large for the type is rejected rather than wrapped around.+readDecimal :: (Integral a, Bounded a) => ByteString -> Maybe a+readDecimal input+  | B.null input = Nothing+  | otherwise = go 0 input+  where+    go !n rest = case B.uncons rest of+      Nothing -> Just n+      Just (byte, rest')+        | byte < 0x30 || byte > 0x39 -> Nothing+        | n > limit || (n == limit && digit > lastDigit) -> Nothing+        | otherwise -> go (n * 10 + digit) rest'+        where digit = fromIntegral (byte - 0x30)+    (limit, lastDigit) = maxBound `quotRem` 10+ -- | 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@@ -34,3 +57,14 @@     escapeChar c         | isAscii c && isPrint c && c /= '\\' = (c :)         | otherwise                          = showLitChar c++-- | The longest value the client stores or reads: 1 GiB, memcached's+-- @ITEM_SIZE_MAX_UPPER_LIMIT@, the largest item size limit (@-I@) it allows.+-- 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.+maxValueLength :: Int+maxValueLength = 1024 * 1024 * 1024
README.md view
@@ -81,8 +81,17 @@  Keys and values are strict `ByteString`s. Misses are returned as `Nothing`, while unexpected failures are thrown as a `MemcacheError` or a network-`IOException`. Operations that take a CAS `Version` skip the check when it is-`0`. `increment` and `decrement` create a missing key with the given initial+`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.+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 [`Database.Memcache.Client`](https://hackage.haskell.org/package/memcache/docs/Database-Memcache-Client.html) documentation covers every operation, along with the timeouts, retries and@@ -94,15 +103,15 @@ 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 (with resource-pool 0.3,-one for each capability), so concurrent requests to the same server wait for-each other; see [Architecture Notes](#architecture-notes) to allow more. The-wait counts towards each attempt's `optsServerTimeout`. An attempt that runs-out of time while still waiting is retried like any failed attempt, but if it-was the last attempt, the operation fails with `Timeout` and the server isn't-marked dead. An attempt that runs out of time afterwards, while opening,-authenticating or using its connection, counts as a server failure, however-long it waited first.+Each server's pool holds one connection by default, so concurrent requests to+the same server wait for each other; see+[Architecture Notes](#architecture-notes) to allow more. The wait counts+towards each attempt's `optsServerTimeout`. An attempt that runs out of time+while still waiting is retried like any failed attempt, but if it was the last+attempt, the operation fails with `Timeout` and the server isn't marked dead.+An attempt that runs out of time afterwards, while opening, authenticating or+using its connection, counts as a server failure, however long it waited+first.  A failed operation is retried, except that a request that mustn't be sent twice (`increment`, `decrement`, `append`, `prepend`, `add`, `delete`, and@@ -119,6 +128,15 @@ whole proxy dead: at once if the request mustn't be sent twice, and otherwise once its retries get the same reply. +memcached at its connection limit (`-c`, 1024 by default) answers a new+connection with `ERROR Too many open connections` and closes it. That is a+failure too, as a refused connection is. Nothing has been sent yet, so the+operation is retried, even one that mustn't be sent twice. Once every attempt+has got that reply, it fails with `ServerError` and the server is marked dead,+so in a cluster its keys go to other servers until `optsDeadRetryDelay` has+passed. Other `ERROR` replies, which memcached sends for a command it doesn't+know, fail at once with `UnknownOp`.+ ### Servers and authentication  `newClient` takes one `ServerSpec` per server, and routes each key to one of@@ -143,6 +161,10 @@   mc <- M.newClient [spec] M.def ``` +The `//` is required. Without it, as in `memcached:cache.example:11211` or+`memcached:/run/memcached.sock`, a URI has no host, port or credentials, so+`parseServerSpec` returns an error rather than the default server.+ The server must be started with `-Y <authfile>`, where the auth file holds one `username:password` line per user. This library connects without TLS, so credentials and all data are sent unencrypted; only rely on them within a@@ -193,9 +215,23 @@   mc <- EC.newClient M.def (60 * 1000000) endpoint ``` +`M.quit` stops the thread, so that no refresh replaces the servers once their+connections are closed. The thread also stops once the client has been garbage+collected.+ Discovery connects to the configuration endpoint like any other server, so it fails for a cluster running a memcached older than 1.6.10. +Each configuration has a version, which goes up as nodes are added or+removed. A refresh applies a configuration only if its version is higher than+that of the one applied last, the first discovery's included, so that a reply+from an endpoint that hasn't caught up yet can't roll the node list back. A+version that goes backwards is then ignored until it passes the one applied+last, or the client is made again. AWS's own cluster client does the same,+except that its refreshes don't count the configuration it was made with, so+the first of them to read a configuration applies it even at a lower or the+same version.+ ### Upgrading from 0.4  Version 0.5 requires memcached 1.6.10 or newer and refuses an older server, so@@ -263,15 +299,27 @@ 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, each batch over one pooled connection.+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+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. -By default each server's pool holds a single connection (`soNumResources = 1`;-with resource-pool 0.3, one for each capability), 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 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.  Either way, a pool is fine for now.++The package's bounds leave out resource-pool 0.3, whose pools have a stripe+for each capability, whatever `soNumStripes` is: a thread could then wait for+a connection while other stripes had room, or for one it held itself.  ## Other clients 
memcache.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name:          memcache-version:       0.5.0.0+version:       0.5.1.0 synopsis:      A memcached client library. description:   A client library for a Memcached cluster. Memcached is an in-memory key-value@@ -96,7 +96,9 @@     Database.Memcache.Types    other-modules:+    Database.Memcache.Timeout     Database.Memcache.Types.Authentication+    Database.Memcache.Types.Cluster     Database.Memcache.Types.Server     Database.Memcache.Types.ServerSpec     Database.Memcache.Util@@ -118,7 +120,9 @@     , hashable           >=1.4.2.0     , network            >=3.1.4.0     , network-uri        >=2.6.4.2-    , resource-pool      >=0.2.3.2+    -- 0.3 gives a pool a stripe for each capability, and no CI job builds+    -- with it; see ServerOptions in Database.Memcache.Server.+    , resource-pool      >=0.2.3.2 && (<0.3 || >=0.4)     , text               >=1.2.5.0     , time               >=1.11.1.1     , unliftio           >=0.2.25.0
test-integration/Integration.hs view
@@ -8,7 +8,7 @@ import qualified Data.ByteString.Char8    as B import           Data.Char                (isAscii) import           Data.Foldable            (toList)-import           Data.IORef               (readIORef)+import           Data.IORef               (readIORef, writeIORef) import           Data.Maybe               (isJust) import           Data.Time.Clock.POSIX    (getPOSIXTime) import qualified Database.Memcache.Client as M@@ -58,8 +58,10 @@           describe "three-server cluster" $ clusterSpecs clusterPorts           describe "restarted server" $ restartSpecs path           describe "paused server" $ pausedSpecs path+          describe "server at its connection limit" $ connectionLimitSpecs path authfile           describe "Unix socket" $ unixSocketSpecs path           describe "server out of memory" $ outOfMemorySpecs fullPort+          describe "server with a 256 MiB item size limit" $ largeItemSpecs path           describe "ElastiCache discovery" $ elastiCacheSpecs port  integrationSpecs :: Int -> Spec@@ -307,6 +309,13 @@     client <- M.newClient [server (M.Auth "colon" "se:cr:et")] M.def     _ <- M.set client "integration-auth-colon" "value" 0 0     fmap first <$> M.get client "integration-auth-colon" `shouldReturn` Just "value"++  -- memcached splits the credentials it is sent at spaces only, and its auth+  -- file ends a password only at CR, LF or NUL.+  it "accepts a username and a password containing a tab" $ do+    client <- M.newClient [server (M.Auth "tab\tuser" "tab\tsecret")] M.def+    _ <- M.set client "integration-auth-tab" "value" 0 0+    fmap first <$> M.get client "integration-auth-tab" `shouldReturn` Just "value"  where   server = ServerSpec "127.0.0.1" (show port)   isBadCommand (M.ProtocolError (M.BadCommand _)) = True@@ -358,6 +367,22 @@     M.flush client Nothing     flushCounts client `shouldReturn` map (+ 1) counts     M.getMany client keys `shouldReturn` []++  -- Skipped, a server marked dead would keep its keys, and serve them once it+  -- is used again. The test's client has every server alive, so it can count+  -- the flushes and read every server's keys.+  it "flushes a server marked dead" $ \client -> do+    storeKeys client+    counts <- flushCounts client+    other <- M.newClient [ServerSpec "127.0.0.1" (show port) M.NoAuth | port <- ports] M.def+    dead : _ <- toList <$> Cluster.getServers other+    -- A failure time in the future keeps the server marked dead.+    writeIORef (Server.failed dead) 1e10+    M.flush other Nothing+    flushCounts client `shouldReturn` map (+ 1) counts+    M.getMany client keys `shouldReturn` []+    readIORef (Server.failed dead) `shouldReturn` 1e10+    M.quit other  where   -- Keys with spaces are sent in base64.   keys =@@ -466,6 +491,42 @@       fmap first <$> M.get other key `shouldReturn` expected       counted `shouldReturn` earlier + 1 +-- | Tests against a memcached at its connection limit, which answers a new+-- connection with ERROR Too many open connections and closes it. Each test+-- starts a memcached that takes few connections, and holds connections to it+-- until it turns one away.+connectionLimitSpecs :: FilePath -> FilePath -> Spec+connectionLimitSpecs executable authfile = do+  it "counts a server at its connection limit against it, and uses it again once it has room" $+    atLimit [] M.NoAuth++  -- With credentials, the request sent before them, to check that the+  -- server is in auth-file mode, gets the line.+  it "does the same when the client has credentials" $+    atLimit ["-Y", authfile] (M.Auth "user" "secret")+ where+  atLimit args auth =+    withMemcached executable (["-c", "64"] ++ args) $ \port -> do+      -- 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 }+      [server] <- toList <$> Cluster.getServers client+      withConnectionsHeld port $ do+        M.get client "integration-limit"+          `shouldThrow` (== M.ProtocolError (M.ServerError "Too many open connections"))+        readIORef (Server.failed server) >>= (`shouldNotBe` 0)+      -- memcached notices the closed connections asynchronously. A try that+      -- it turns away takes about 20 ms, wait included, so this gives it+      -- about 5 s.+      let untilRoom attempts = do+            result <- try (M.get client "integration-limit")+            case result of+              Left (M.ProtocolError (M.ServerError _)) | attempts > (0 :: Int) ->+                threadDelay 10000 >> untilRoom (attempts - 1)+              _ -> result `shouldBe` Right Nothing+      untilRoom 250+ -- | Tests against a memcached that listens on a Unix socket. unixSocketSpecs :: FilePath -> Spec unixSocketSpecs executable =@@ -511,6 +572,25 @@     M.increment client "integration-counter" 0 1 0 0 `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+-- 128 MiB. It needs -m of at least twice that, but takes memory only as it+-- stores items.+largeItemSpecs :: FilePath -> Spec+largeItemSpecs executable =+  it "stores a value over 128 MiB and reads it back" $+    withMemcached executable ["-I", "256m", "-m", "1024"] $ \port -> do+      -- 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 }+      let key = "integration-over-128-mib"+          value = B.replicate (128 * 1024 * 1024 + 1) 'v'+      version <- M.set client key value 5 0+      M.get client key `shouldReturn` Just (value, 5, version)+      M.gat client key 0 `shouldReturn` Just (value, 5, version)+      M.getMany client [key] `shouldReturn` [(key, (value, 5, version))]+      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.@@ -564,6 +644,36 @@       value:_ -> read (B.unpack value)       []      -> 0 +-- | Hold connections to memcached until it turns one away with ERROR Too many+-- open connections, as it does at its connection limit, then run the action,+-- and close the connections held once it is done. Each connection sends a+-- version request: memcached answers it on a connection it has taken, with+-- its version, or CLIENT_ERROR in auth-file mode, and sends the line to one+-- it turns away whatever that sent. Fails if memcached takes 1,000+-- connections, or closes one without a reply, or doesn't answer one within+-- 5 s.+withConnectionsHeld :: Int -> IO a -> IO a+withConnectionsHeld port action = hold (1000 :: Int)+ where+  -- Each connection is held open until the action, run once memcached has+  -- turned one away, is done.+  hold attempts = bracket (socket AF_INET Stream defaultProtocol) close $ \sock -> do+    N.connect sock (N.SockAddrInet (fromIntegral port) (tupleToHostAddress (127, 0, 0, 1)))+    NB.sendAll sock "version\r\n"+    reply <- timeout 5000000 (recvReply sock "")+    case reply of+      Just "ERROR Too many open connections\r\n" -> action+      Just "" -> fail "memcached closed a connection without answering its version request"+      Just _ | attempts > 1 -> hold (attempts - 1)+      Just _ -> fail "memcached took 1,000 connections without turning one away"+      Nothing -> fail "memcached didn't answer a version request within 5 s"+  -- Read up to the end of the first line, or until memcached closes the+  -- connection.+  recvReply sock acc = do+    chunk <- NB.recv sock 1024+    let reply = acc <> chunk+    if B.null chunk || "\n" `B.isSuffixOf` reply then return reply else recvReply sock reply+ -- | Run an action against a memcached started with the given extra -- arguments on a free port. withMemcached@@ -648,15 +758,15 @@   withMemcached executable [] $ \port ->     withMemcacheds executable (n - 1) $ \ports -> action (port : ports) --- | Run an action with an auth file allowing @user@ / @secret@ and--- @colon@ / @se:cr:et@.+-- | Run an action with an auth file allowing @user@ / @secret@,+-- @colon@ / @se:cr:et@, and "tab\tuser" / "tab\tsecret", which hold tabs. withAuthfile :: (FilePath -> IO a) -> IO a withAuthfile action = do   tmp <- getTemporaryDirectory   -- Default permissions, so a memcached that drops privileges (e.g. when   -- started as root with -u) can still read it.   bracket (openTempFileWithDefaultPermissions tmp "memcached-auth") (removeFile . fst) $ \(path, handle) -> do-    hPutStr handle "user:secret\ncolon:se:cr:et\n"+    hPutStr handle "user:secret\ncolon:se:cr:et\ntab\tuser:tab\tsecret\n"     hClose handle     action path 
test/MockServer.hs view
@@ -43,6 +43,9 @@     = MR B.ByteString     -- | Close the client connection instead of replying.     | CloseConnection+    -- | Reply with these bytes, then close the connection, as memcached does+    -- to a new connection when it is at its connection limit.+    | ReplyThenClose B.ByteString     -- | Wait this many milliseconds, then take the given action.     | DelayMS Int MockResponse     -- | Read the request but send nothing back.@@ -330,6 +333,7 @@       MR bytes      -> N.sendAll client bytes >> return True       DelayMS ms r' -> threadDelay (ms * 1000) >> respond r'       CloseConnection -> return False+      ReplyThenClose bytes -> N.sendAll client bytes >> return False       Repeat bytes  -> forever (N.sendAll client bytes)       -- The connection is closed here, so that the MVar is filled only once       -- it is closed. Closing it again, as serveConnection does, does
test/RoutingSpec.hs view
@@ -13,7 +13,7 @@ import           Data.Foldable             (for_, toList) import qualified Data.Hashable             as Hashable import           Data.IORef                (readIORef, writeIORef)-import           Data.List                 (find, findIndex, group, nub, sort)+import           Data.List                 (find, findIndex, group, nub, sort, sortOn) import           Data.Maybe                (fromMaybe, listToMaybe, maybeToList) import           Data.Time.Clock.POSIX     (getPOSIXTime) import           Data.Word                 (Word32)@@ -396,7 +396,9 @@ router04 live k =   let hashedKey = Hashable.hash k       searchF s = sid s < hashedKey-      servers' = sort live+      -- 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')
test/Spec.hs view
@@ -24,11 +24,12 @@ import           Data.Char                 (isAscii, isPrint) import qualified Network.Socket            as N import qualified Network.Socket.ByteString as N-import           Control.Concurrent        (MVar, forkIO, getNumCapabilities, killThread,-                                            myThreadId, newEmptyMVar, putMVar, readMVar,-                                            takeMVar, threadDelay, tryPutMVar, yield)-import           Control.Exception         (MaskingState (..), bracket, displayException, finally,-                                            getMaskingState, mask_, try)+import           Control.Concurrent        (MVar, ThreadId, forkIO, getNumCapabilities,+                                            killThread, myThreadId, newEmptyMVar, putMVar,+                                            readMVar, takeMVar, threadDelay, tryPutMVar, yield)+import           Control.Exception         (MaskingState (..), SomeException, bracket,+                                            displayException, finally, getMaskingState, mask_,+                                            try, uninterruptibleMask_) import           Control.Monad             (forM_, forever, replicateM_, unless, void, when,                                             (>=>)) import           Data.Either               (isLeft, isRight)@@ -38,8 +39,9 @@ import           Data.List                 (find, isInfixOf, isPrefixOf, nub) import           Foreign.Marshal.Alloc     (mallocBytes) import           GHC.Clock                 (getMonotonicTime)-import           GHC.Conc                  (ThreadStatus (..), threadStatus)+import           GHC.Conc                  (ThreadStatus (..), getAllocationCounter, threadStatus) import           System.IO.Error           (isDoesNotExistError)+import           System.Mem                (performMajorGC) import           System.Timeout            (timeout) import           UnliftIO.Async            (Async, AsyncCancelled (..), async, asyncOn,                                             asyncThreadId, cancel, mapConcurrently, wait)@@ -267,6 +269,19 @@       (recvResponseFrom "XX\r\n" >>= responseStatus) `shouldThrow` isUnknownStatus       recvResponseFrom "\r\n" `shouldThrow` isUnknownPkt +    -- memcached sends this line to a new connection, and then closes it, when+    -- it is at its connection limit. Only that exact text is a server failure:+    -- another server may send text after ERROR for a command it doesn't know,+    -- which stays a rejected command, with the line kept.+    it "maps memcached's ERROR at its connection limit to a server error, and keeps other ERROR lines" $ do+      (recvResponseFrom "ERROR Too many open connections\r\n" >>= responseStatus)+        `shouldThrow` (== ProtocolError (E.ServerError "Too many open connections"))+      forM_+        [ "ERROR", "ERROR unknown command", "ERROR too many open connections"+        , "ERROR Too many open connections now", "ERROR Too many" ] $ \line ->+        (recvResponseFrom (line <> "\r\n") >>= responseStatus)+          `shouldThrow` (== ProtocolError (UnknownOp (C.unpack line)))+     -- Byte 0xa0 is part of many UTF-8 characters, such as the Cyrillic Er     -- (D0 A0) here.     it "splits response lines on spaces only" $ do@@ -401,9 +416,37 @@         _ <- forkIO $ N.sendAll right "VA 5\r\nhe" >> N.close right         recvResponse connection `shouldThrow` isUnexpectedEOF -    it "rejects unreasonably large value lengths" $-      recvResponseFrom "VA 134217729\r\n" `shouldThrow` isBadLength+    -- Receive a reply that claims a value of the given length, sends the+    -- first three bytes of it, and closes the connection. So a length that+    -- is accepted ends in UnexpectedEOF, rather than waiting for the rest.+    let recvClaimingValue n =+          bracket (N.socketPair N.AF_UNIX N.Stream 0) closePair $ \(left, right) -> do+            connection <- newConnection left+            _ <- forkIO $ N.sendAll right ("VA " <> n <> "\r\nabc") >> N.close right+            recvResponse connection +    -- 1 GiB is the longest value the client sends, and more than any+    -- memcached server can store.+    it "rejects a value length over 1 GiB" $+      forM_ ["1073741825", "2147483648", "9223372036854775807"] $ \n ->+        recvClaimingValue n `shouldThrow` isBadLength++    -- A length of up to 1 GiB is accepted. A length over 128 MiB used to be+    -- rejected, so a value memcached had stored couldn't be read.+    it "accepts a value length of up to 1 GiB" $+      forM_ ["134217729", "1073741824"] $ \n ->+        recvClaimingValue n `shouldThrow` isUnexpectedEOF++    -- The value is read as it arrives, not allocated whole first, so a reply+    -- of a few bytes that claims 1 GiB doesn't make the client allocate+    -- 1 GiB. The allocation counter counts down, and counts only this+    -- thread, which is the one that reads.+    it "reads a value claimed to be 1 GiB as it arrives, without allocating it first" $ do+      start <- getAllocationCounter+      recvClaimingValue "1073741824" `shouldThrow` isUnexpectedEOF+      end <- getAllocationCounter+      (start - end) `shouldSatisfy` (< 16 * 1024 * 1024)+     it "rejects an unterminated response line" $       recvResponseFrom (C.replicate (16 * 1024) 'x') `shouldThrow` isBadLength @@ -466,6 +509,12 @@         Client.get client "key" `shouldThrow` displays           "memcached protocol error: command rejected by server: \\ESC]0;owned\\a bad data chunk" +    it "describes ERROR replies with their text" $ do+      (recvResponseFrom "ERROR Too many open connections\r\n" >>= responseStatus)+        `shouldThrow` displays "memcached protocol error: server error: Too many open connections"+      (recvResponseFrom "ERROR unknown command\r\n" >>= responseStatus)+        `shouldThrow` displays "memcached protocol error: command not recognized by server: ERROR unknown command"+     it "escapes bytes outside ASCII" $       displayException (ProtocolError (E.ServerError "caf\233 \195\169"))         `shouldBe` "memcached protocol error: server error: caf\\233 \\195\\169"@@ -532,6 +581,18 @@       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))] +    -- 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+    -- keys go to one server.+    it "sends each server its own keys when their sids are equal" $+      withSameSidClient [MR "VA 1 f0 c1 O0\r\nx\r\n", MR "MN\r\n"] [MR "VA 1 f0 c2 O1\r\ny\r\n", MR "MN\r\n"] $+        \a b client -> do+          result <- tryIO (Client.getMany client ["a1", "b1"])+          mockRequests a `shouldReturn` ["version\r\n", "mg a1 v f c q O0\r\n", "mn\r\n"]+          mockRequests b `shouldReturn` ["version\r\n", "mg b1 v f c q O1\r\n", "mn\r\n"]+          result `shouldBe` Right [("a1", ("x", 0, 1)), ("b1", ("y", 0, 2))]+     -- A batch is written whole before its replies are read, so it must be     -- small enough that the replies can't fill the socket buffers first,     -- which would leave both ends blocked until the attempt runs out of@@ -732,6 +793,14 @@             , "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" ]           mockRequests b `shouldReturn` ["version\r\n", "ms b1 1 F0 T0 MS c O1\r\ny\r\n", "mn\r\n"] +    -- As for getMany, two servers with the same sid each get their own pairs.+    it "sends each server its own pairs when their sids are equal" $+      withSameSidClient [MR "HD c1 O0\r\n", MR "MN\r\n"] [MR "HD c2 O1\r\n", MR "MN\r\n"] $ \a b client -> do+        result <- tryIO (Client.setMany client [("a1", "x", 0, 0), ("b1", "y", 0, 0)])+        mockRequests a `shouldReturn` ["version\r\n", "ms a1 1 F0 T0 MS c O0\r\nx\r\n", "mn\r\n"]+        mockRequests b `shouldReturn` ["version\r\n", "ms b1 1 F0 T0 MS c O1\r\ny\r\n", "mn\r\n"]+        result `shouldBe` Right [("a1", 1), ("b1", 2)]+     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)]@@ -804,6 +873,14 @@         mockRequests a `shouldReturn` ["version\r\n", "md a1 O0\r\n", "mn\r\n"]         mockRequests b `shouldReturn` ["version\r\n", "md b1 O1\r\n", "mn\r\n"] +    -- As for getMany, two servers with the same sid each get their own keys.+    it "sends each server its own keys when their sids are equal" $+      withSameSidClient [MR "HD O0\r\n", MR "MN\r\n"] [MR "HD O1\r\n", MR "MN\r\n"] $ \a b client -> do+        result <- tryIO (Client.deleteMany client ["a1", "b1"])+        mockRequests a `shouldReturn` ["version\r\n", "md a1 O0\r\n", "mn\r\n"]+        mockRequests b `shouldReturn` ["version\r\n", "md b1 O1\r\n", "mn\r\n"]+        result `shouldBe` Right ()+     -- As for getMany, a batch holds at most 256 requests.     it "closes a batch once it holds 256 requests" $ do       let deleted i = MR ("HD O" <> asDecimal i <> "\r\n")@@ -866,6 +943,17 @@       withClient [MR "VA (3) f2 c7\r\nfoo\r\n", MR "VA (3) f2 c7\r\nfoo\r\n"] $ \client ->         Client.get client "key" `shouldThrow` isBadLength +    -- memcached started with -I over 128m stores such a value. The client+    -- used to refuse to read one, and to mark the server dead for it. One+    -- attempt, of 10 s, as reading the value can take longer than the+    -- default 750 ms on a busy machine.+    it "gets a value over 128 MiB without marking the server dead" $ do+      let value = C.replicate (128 * 1024 * 1024 + 1) 'v'+      withServerAndClientOpts patient { Client.optsServerRetries = 0 }+        [MR ("VA " <> asDecimal (B.length value) <> " f2 c7\r\n" <> value <> "\r\n")] $ \_ client -> do+          Client.get client "key" `shouldReturn` Just (value, 2, 7)+          Cluster.getServers client >>= mapM_ (\s -> readIORef (Server.failed s) `shouldReturn` 0)+     it "gets and touches a value" $       withServerAndClient [MR "VA 3 f2 c7\r\nfoo\r\n", MR "EN\r\n"] $ \server client -> do         Client.gat client "key" 60 `shouldReturn` Just ("foo", 2, 7)@@ -1662,6 +1750,88 @@           waitForRequests server 2 `shouldReturn` ["version\r\n", "md key\r\n"]           readIORef (Server.failed s) >>= (`shouldNotBe` 0) +    -- A batch's first reply's timeout covers the wait for the connection too,+    -- as a single request's does. As above, the getMany waits 500 ms for the+    -- only connection, and the mock takes 800 ms over the first reply, so the+    -- getMany runs out of its 1 s using the connection, and its only attempt+    -- 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 }+        [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+          release <- newEmptyMVar+          holder <- async $ Server.withSocket s $ \_ -> putMVar held () >> takeMVar release+          takeMVar held+          getting <- async $ Client.getMany client ["one"]+          waitUntilBlocked getting+          threadDelay 500000+          putMVar release ()+          wait holder+          wait getting `shouldThrow` (== ClientError Timeout)+          take 2 <$> waitForRequests server 2 `shouldReturn` ["version\r\n", "mg one v f c q O0\r\n"]+          readIORef (Server.failed s) >>= (`shouldNotBe` 0)++    -- In a batch, each reply has a timeout of its own, as the single+    -- requests the batch stands for would. Here the mock takes 200 ms over+    -- each of the four replies to a batch of three requests and its mn: each+    -- comes well within its 500 ms, though the batch takes 800 ms. Its only+    -- attempt must succeed, having sent the batch once.+    forM_+      [ ("getMany",+          \c -> Client.getMany c ["one", "two", "three"]+            `shouldReturn` [("one", ("a", 0, 1)), ("two", ("b", 0, 2)), ("three", ("c", 0, 3))],+          ["VA 1 c1 O0\r\na\r\n", "VA 1 c2 O1\r\nb\r\n", "VA 1 c3 O2\r\nc\r\n"],+          ["mg one v f c q O0\r\n", "mg two v f c q O1\r\n", "mg three v f c q O2\r\n"])+      , ("setMany",+          \c -> Client.setMany c [("one", "a", 0, 0), ("two", "b", 0, 0), ("three", "c", 0, 0)]+            `shouldReturn` [("one", 1), ("two", 2), ("three", 3)],+          ["HD c1 O0\r\n", "HD c2 O1\r\n", "HD c3 O2\r\n"],+          ["ms one 1 F0 T0 MS c O0\r\na\r\n", "ms two 1 F0 T0 MS c O1\r\nb\r\n", "ms three 1 F0 T0 MS c O2\r\nc\r\n"])+      , ("deleteMany",+          \c -> Client.deleteMany c ["one", "two", "three"],+          ["HD O0\r\n", "NF O1\r\n", "HD O2\r\n"],+          ["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 }+          (map (DelayMS 200 . MR) (replies ++ ["MN\r\n"])) $ \server client -> do+            [s] <- toList <$> Cluster.getServers client+            run client+            mockRequests server `shouldReturn` "version\r\n" : requests ++ ["mn\r\n"]+            readIORef (Server.failed s) `shouldReturn` 0++    -- A reply that never comes still times out, a timeout after the reply+    -- before it was read. Here the mock answers the first request after+    -- 200 ms and never answers the second, so the only attempt runs out of+    -- time 700 ms in at the earliest, where one timeout for the whole batch+    -- ran out after 500 ms, and marks the server dead. The extra Noop keeps+    -- 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 }+        [DelayMS 200 (MR "VA 1 c1 O0\r\na\r\n"), Noop, Noop, Noop] $ \server client -> do+          [s] <- toList <$> Cluster.getServers client+          start <- getMonotonicTime+          timeout 5000000 (Client.getMany client ["one", "two"]) `shouldThrow` (== ClientError Timeout)+          end <- getMonotonicTime+          (end - start) `shouldSatisfy` (>= 0.65)+          readIORef (Server.failed s) >>= (`shouldNotBe` 0)+          mockRequests server `shouldReturn`+            ["version\r\n", "mg one v f c q O0\r\n", "mg two v f c q O1\r\n", "mn\r\n"]++    -- A reply's timeout doesn't start again while the reply comes in+    -- pieces. Here the first reply's line comes at once, but its value comes+    -- 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 }+        (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"])+            `shouldThrow` (== ClientError Timeout)+     -- The last attempt decides whether the server is marked dead. Here the     -- first attempt times out waiting for the connection, which another     -- thread holds for 800 ms. The second attempt starts 1 s later, gets the@@ -2294,6 +2464,27 @@         _ <- forkIO $ N.sendAll right "VERSION 1.6\r\n"         Auth.authenticate connection (Auth.Auth "user" "pass") `shouldThrow` isInvalidAuthentication +    -- Only VERSION shows that the server isn't in auth-file mode. memcached+    -- at its connection limit answers the probe with its ERROR line, and that+    -- must stay a server failure. An error reply throws as it would for any+    -- request, and any other reply, even with a code that responseStatus+    -- doesn't know, throws UnknownOp quoting it, as in the version check.+    -- None sends the credentials.+    forM_+      [ ("ERROR Too many open connections", ProtocolError (E.ServerError "Too many open connections"))+      , ("ERROR", ProtocolError (UnknownOp "ERROR"))+      , ("SERVER_ERROR backend failure", ProtocolError (E.ServerError "backend failure"))+      , ("HD", ProtocolError (UnknownOp "Expected VERSION or CLIENT_ERROR, got: \"HD\""))+      , ("XX 1", ProtocolError (UnknownOp "Expected VERSION or CLIENT_ERROR, got: \"XX 1\"")) ] $+      \(reply, err) ->+        it ("throws for the probe's reply " <> show reply <> ", without sending the credentials") $+          bracket (N.socketPair N.AF_UNIX N.Stream 0) closePair $ \(left, right) -> do+            connection <- newConnection left+            _ <- forkIO $ N.sendAll right (reply <> "\r\n")+            Auth.authenticate connection (Auth.Auth "user" "pass") `shouldThrow` (== err)+            N.shutdown left N.ShutdownSend+            recvExactly right 1024 `shouldReturn` "version\r\n"+     it "rejects credentials containing delimiters before contacting the server" $       bracket (N.socketPair N.AF_UNIX N.Stream 0) closePair $ \(left, _) -> do         connection <- newConnection left@@ -2308,10 +2499,15 @@       Auth.validateCredentials "user" "pass" `shouldBe` Right ()       -- memcached's auth file splits each line at its first ':'.       Auth.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)-        [" ", "\t", "\r", "\n", "\0", ":"]+        [" ", "\r", "\n", "\0", ":"]       mapM_ (\c -> Auth.validateCredentials "user" ("pa" <> c <> "ss") `shouldSatisfy` isLeft)-        [" ", "\t", "\r", "\n", "\0"]+        [" ", "\r", "\n", "\0"]      it "authenticates each new client connection" $       withMockServer (authExchange ++ [supported, MR "VA 3 f2 c7\r\nfoo\r\n"]) $ \server -> do@@ -2333,6 +2529,48 @@         mockRequests server `shouldReturn`           authRequests ++ authRequests ++ ["version\r\n", "mg key v f c\r\n"] +    -- memcached at its connection limit answers every new connection with+    -- its ERROR line, and closes it, so with credentials the probe gets the+    -- line. That is a server failure, not a server outside auth-file mode:+    -- the get is retried on a new connection, which authenticates as usual.+    it "retries when memcached at its connection limit answers the probe" $+      withMockServer ([atLimit] ++ authExchange ++ [supported, MR "VA 3 f2 c7\r\nfoo\r\n"]) $ \server -> do+        client <- Client.newClient [withCredentials server] fastFailover+        Client.get client "key" `shouldReturn` Just ("foo", 2, 7)+        mockRequests server `shouldReturn` ["version\r\n"] ++ authRequests ++ ["version\r\n", "mg key v f c\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) `shouldReturn` 0++    -- The reply left over is for credentials that must never be sent.+    it "marks the server dead once memcached at its connection limit answers every probe" $+      withMockServer [atLimit, atLimit, MR "STORED\r\n"] $ \server -> do+        client <- Client.newClient [withCredentials server] fastFailover+        Client.get client "key" `shouldThrow` (== ProtocolError (E.ServerError "Too many open connections"))+        mockRequests server `shouldReturn` ["version\r\n", "version\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) >>= (`shouldNotBe` 0)++    -- A server that doesn't know version would refuse it once authenticated,+    -- too: a rejected command, not a server failure.+    it "throws an ERROR reply to the probe as it would for any request" $+      withMockServer [MR "ERROR\r\n", MR "STORED\r\n"] $ \server -> do+        client <- Client.newClient [withCredentials server] fastFailover+        Client.get client "key" `shouldThrow` (== ProtocolError (UnknownOp "ERROR"))+        mockRequests server `shouldReturn` ["version\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) `shouldReturn` 0++    -- Without credentials, the version check refuses the same reply, and+    -- neither retries nor marks the server dead: a retry would get it again.+    it "refuses a server that answers the probe with neither an error nor VERSION, as the version check does" $+      withMockServer [MR "HD\r\n", MR "STORED\r\n"] $ \server -> do+        client <- Client.newClient [withCredentials server] fastFailover+        Client.get client "key"+          `shouldThrow` (== ProtocolError (UnknownOp "Expected VERSION or CLIENT_ERROR, got: \"HD\""))+        mockRequests server `shouldReturn` ["version\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) `shouldReturn` 0+   -- Older servers don't read the data block of the meta set this client   -- sends, so they run the value's bytes as commands. The client must not   -- send them anything but its version check (and, with credentials, the@@ -2393,6 +2631,15 @@         Client.set client "key" "value" 0 0 `shouldThrow` (== ProtocolError (UnknownOp "ERROR"))         mockRequests server `shouldReturn` ["version\r\n"] +    it "keeps the text of an ERROR reply to version, and neither retries it nor marks the server dead" $+      withMockServer [MR "ERROR unknown command\r\n", MR "HD c1\r\n"] $ \server -> do+        client <- Client.newClient [mockServerSpec server] Client.def+        Client.set client "key" "value" 0 0+          `shouldThrow` (== ProtocolError (UnknownOp "ERROR unknown command"))+        mockRequests server `shouldReturn` ["version\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) `shouldReturn` 0+     -- A SERVER_ERROR whose text names no status is a server failure, as for     -- any request: the operation is retried, on a new connection that asks     -- for the version again, and once every attempt has failed, the server@@ -2407,6 +2654,29 @@           [s] <- toList <$> Cluster.getServers client           readIORef (Server.failed s) >>= (`shouldNotBe` 0) +    -- memcached at its connection limit answers a new connection with its+    -- ERROR line and closes it. That is a server failure, as a refused+    -- connection is, and nothing has been sent yet, so the operation is+    -- retried, even an increment, which is sent once.+    forM_ [("a get", getOnce, "mg key v f c\r\n"), ("an increment", incrementOnce, "ma key D1 MI v c N0 J0\r\n")] $+      \(name, (run, reply), request) ->+        it ("retries " <> name <> " when memcached at its connection limit answers version") $+          withMockServer [atLimit, supported, MR reply] $ \server -> do+            client <- Client.newClient [mockServerSpec server] fastFailover+            run client+            mockRequests server `shouldReturn` ["version\r\n", "version\r\n", request]+            [s] <- toList <$> Cluster.getServers client+            readIORef (Server.failed s) `shouldReturn` 0++    it "marks the server dead once memcached at its connection limit answers every attempt" $+      withMockServer [atLimit, atLimit, MR "HD c1\r\n"] $ \server -> do+        client <- Client.newClient [mockServerSpec server] fastFailover+        Client.set client "key" "value" 0 0+          `shouldThrow` (== ProtocolError (E.ServerError "Too many open connections"))+        mockRequests server `shouldReturn` ["version\r\n", "version\r\n"]+        [s] <- toList <$> Cluster.getServers client+        readIORef (Server.failed s) >>= (`shouldNotBe` 0)+     -- stats closes the connection it reads a reply from, so each stats opens     -- a new connection, which checks the version like any other. Here the     -- server reports 1.6.9 to the second.@@ -2583,6 +2853,15 @@      mapM_ rejects       [ ("http://cache.example", "Must begin memcached://")+      -- Without the "//", a URI has no authority, and so no host, port or+      -- credentials. Each of these used to give the default server, so the+      -- last two lost their credentials.+      , ("memcached:", "Must begin memcached://")+      , ("memcached:cache.example:11211", "Must begin memcached://")+      , ("memcached:/host", "Must begin memcached://")+      , ("memcached:/run/memcached.sock", "Must begin memcached://")+      , ("memcached:user:pass@host", "Must begin memcached://")+      , ("memcached:/user:secret@cache.example", "Must begin memcached://")       , ("not a uri", "Not a valid URI")       -- The URI parser rejects malformed escapes.       , ("memcached://user:p%zzss@cache.example", "Not a valid URI")@@ -2608,12 +2887,16 @@       , ("memcached:///run/a@b.sock", rawAtMessage)       ] -    -- Without the "//", the URI has no host, not even an empty one, so its-    -- path is no socket. Were it one, the password of the second URI, which-    -- is missing a slash, would be in ssHost, which show prints.-    it "takes no Unix socket path from a URI without //" $-      forM_ ["memcached:/run/memcached.sock", "memcached:/user:secret@cache.example"] $ \uri ->-        fmap ssHost (parseServerSpec uri) `shouldSatisfy` either (const True) (not . isPrefixOf "/")+    -- Whatever follows "memcached:", a URI without "//" has no host, not even+    -- an empty one, so its path is no Unix socket either: were it one, the+    -- password of "memcached:/user:secret@cache.example", which is missing a+    -- slash, would be in ssHost, which show prints. The errors don't quote+    -- the URI.+    prop "rejects any URI without //" $+      forAll (listOf (elements "ab1.-_~:@/?#!$&'()*+,;=") `suchThat` (not . isPrefixOf "//")) $ \rest ->+        let result = parseServerSpec ("memcached:" <> rest)+        in counterexample (show (fmap specFields result)) $+             result `elem` map Left ["Must begin memcached://", "Not a valid URI"]      it "gives getAddrInfo an IPv6 address it accepts" $ do       spec <- either fail return $ parseServerSpec "memcached://[::1]:11211"@@ -2666,6 +2949,27 @@       optionFields Client.defaultOptions `shouldBe` optionFields Client.def    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+    -- servers, ordered by host and then port.+    it "tells servers apart by host and port when their sids are equal" $ do+      let server host port = Server.newServerDefault Server.defaultServerOptions (ServerSpec host port Auth.NoAuth)+          withSid n s = s { Server.sid = n }+      a <- withSid 2 <$> server "cache1.example" "11211"+      b <- withSid 2 <$> server "cache2.example" "11211"+      c <- withSid 2 <$> server "cache1.example" "11212"+      d <- withSid 1 <$> server "cache9.example" "11211"+      [a == b, a == c, b == c] `shouldBe` [False, False, False]+      [compare a b, compare a c, compare c b] `shouldBe` [LT, LT, LT]+      -- A lower sid still comes first, whatever the host, and another sid+      -- makes another server, even with the same host and port.+      compare d a `shouldBe` LT+      (withSid 1 a == a, compare (withSid 1 a) a) `shouldBe` (False, LT)+      -- Servers made for the same host and port are equal.+      e <- server "cache1.example" "11211"+      e' <- server "cache1.example" "11211"+      (e == e', compare e e') `shouldBe` (True, EQ)+     it "fails over to another server once one is marked dead" $       withMockMemcached supportedVersion [MR "VA 1 f0 c1\r\nA\r\n", CloseConnection, CloseConnection] $ \a ->       withMockMemcached supportedVersion [MR "VA 1 f0 c1\r\nB\r\n", CloseConnection, CloseConnection] $ \b -> do@@ -2678,14 +2982,34 @@         second <- Client.get client "key"         map (fmap fst3) [first, second] `shouldSatisfy` (`elem` [[Just "A", Just "B"], [Just "B", Just "A"]]) +    -- Each server serves one get, then answers new connections as memcached+    -- does once it is at its connection limit.+    it "fails over from a server at its connection limit" $+      withMockServer [supported, MR "VA 1 f0 c1\r\nA\r\n", atLimit, atLimit] $ \a ->+      withMockServer [supported, MR "VA 1 f0 c1\r\nB\r\n", atLimit, atLimit] $ \b -> do+        client <- Client.newClient [mockServerSpec a, mockServerSpec b] fastFailover+        first <- Client.get client "key"+        -- Close the connection the get left in the pool, so that the next+        -- get to that server opens a new one.+        Client.quit client+        Client.get client "key" `shouldThrow` (== ProtocolError (E.ServerError "Too many open connections"))+        second <- Client.get client "key"+        map (fmap fst3) [first, second] `shouldSatisfy` (`elem` [[Just "A", Just "B"], [Just "B", Just "A"]])+     it "throws NoServersReady once every server is dead" $       withMockMemcached supportedVersion [CloseConnection, CloseConnection] $ \a -> do         client <- Client.newClient [mockServerSpec a] fastFailover         Client.get client "key" `shouldThrow` isUnexpectedEOF         Client.get client "key" `shouldThrow` (== ClientError NoServersReady)-        Client.flush client Nothing `shouldThrow` (== ClientError NoServersReady)         Client.version client `shouldThrow` (== ClientError NoServersReady) +    -- flush goes to servers marked dead too, so it throws NoServersReady only+    -- when there are no servers at all.+    it "throws NoServersReady from flush when there are no servers" $ do+      client <- Client.newClient [] Client.def+      Client.flush (Cluster.setServers client (Right mempty)) Nothing+        `shouldThrow` (== ClientError NoServersReady)+     it "flushes every server" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b -> do@@ -2694,11 +3018,78 @@         mockRequests a `shouldReturn` ["version\r\n", "flush_all\r\n"]         mockRequests b `shouldReturn` ["version\r\n", "flush_all\r\n"] -    it "stops flushing at a server whose reply is rejected" $+    -- Skipped, a server marked dead would keep its values, and serve them once+    -- it is used again. Answering the flush doesn't clear its mark.+    it "flushes a server marked dead, which stays marked dead" $+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \b -> do+        client <- Client.newClient [mockServerSpec a, mockServerSpec b] Client.def+        [dead, _] <- toList <$> Cluster.getServers client+        -- A failure time in the future keeps the server marked dead.+        writeIORef (Server.failed dead) 1e10+        Client.flush client Nothing+        mockRequests a `shouldReturn` ["version\r\n", "flush_all\r\n"]+        mockRequests b `shouldReturn` ["version\r\n", "flush_all\r\n"]+        readIORef (Server.failed dead) `shouldReturn` 1e10++    -- A server marked dead gets the usual retries, and if they all fail, it+    -- is marked dead again from the new failure: neither 0 nor its old mark.+    it "retries flushing a server marked dead, and marks it again if it fails" $+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->+      withMockMemcached supportedVersion [CloseConnection, CloseConnection] $ \b -> do+        client <- Client.newClient [mockServerSpec a, mockServerSpec b] fastFailover+        [_, dead] <- toList <$> Cluster.getServers client+        writeIORef (Server.failed dead) 1e10+        Client.flush client Nothing `shouldThrow` isUnexpectedEOF+        mockRequests a `shouldReturn` ["version\r\n", "flush_all\r\n"]+        mockRequests b `shouldReturn` concat (replicate 2 ["version\r\n", "flush_all\r\n"])+        readIORef (Server.failed dead) >>= (`shouldSatisfy` (\t -> t /= 0 && t < 1e10))++    -- b drops both of its connections, so both its attempts fail, and it is+    -- marked dead. c is flushed all the same, and only then is b's failure+    -- thrown.+    it "flushes the servers after one that fails, then throws its failure" $+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->+      withMockMemcached supportedVersion [CloseConnection, CloseConnection] $ \b ->+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \c -> do+        client <- Client.newClient (map mockServerSpec [a, b, c]) fastFailover+        Client.flush client Nothing `shouldThrow` isUnexpectedEOF+        mockRequests a `shouldReturn` ["version\r\n", "flush_all\r\n"]+        mockRequests b `shouldReturn` concat (replicate 2 ["version\r\n", "flush_all\r\n"])+        mockRequests c `shouldReturn` ["version\r\n", "flush_all\r\n"]+        servers <- toList <$> Cluster.getServers client+        map (/= 0) <$> mapM (readIORef . Server.failed) servers `shouldReturn` [False, True, False]++    -- a's reply is rejected, and c's is an error reply. b and c are flushed+    -- all the same, and a's failure, the first, is thrown.+    it "throws the first server's failure once every server has been tried" $       withMockMemcached supportedVersion [MR "HD\r\n"] $ \a ->+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->+      withMockMemcached supportedVersion [MR "CLIENT_ERROR bad command line format\r\n"] $ \c -> do+        client <- Client.newClient (map mockServerSpec [a, b, c]) Client.def+        Client.flush client Nothing+          `shouldThrow` (== ProtocolError (UnexpectedResponse "Expected FLUSH, got: \"HD\""))+        forM_ [a, b, c] $ \server -> mockRequests server `shouldReturn` ["version\r\n", "flush_all\r\n"]++    -- A cancel isn't kept like a server's failure: it ends the flush at once,+    -- while the flush waits for a's reply, so b is never sent anything.+    it "stops flushing at once when cancelled" $+      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 }+        flushing <- async $ Client.flush client Nothing+        waitForRequests a 2 `shouldReturn` ["version\r\n", "flush_all\r\n"]+        cancel flushing+        mockRequests b `shouldReturn` []++    -- flush used allOpExpecting, which still stops at a server whose reply+    -- it rejects.+    it "stops allOpExpecting at a server whose reply is rejected" $+      withMockMemcached supportedVersion [MR "HD\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "HD\r\n"] $ \b -> do         client <- Client.newClient [mockServerSpec a, mockServerSpec b] Client.def-        Client.flush client Nothing+        Cluster.allOpExpecting client "FLUSH" ["OK"] (flushRequest Nothing)           `shouldThrow` (== ProtocolError (UnexpectedResponse "Expected FLUSH, got: \"HD\""))         requests <- (++) <$> mockRequests a <*> mockRequests b         requests `shouldBe` ["version\r\n", "flush_all\r\n"]@@ -2862,6 +3253,12 @@     it "rejects an endpoint that is not a configuration endpoint" $       isLeft (EC.parseConfigurationEndpoint "memcached://cache.example:11211") `shouldBe` True +    -- Without the "//", it used to be the default server, so discovery ran+    -- against whatever listened on 127.0.0.1:11211.+    it "rejects a configuration endpoint without //" $+      either Just (const Nothing) (EC.parseConfigurationEndpoint "memcached:mycluster.cfg.example:11211")+        `shouldBe` Just "Must begin memcached://"+     -- With this time limit, the reply reaches the length limit long before     -- discovery could run out of time.     forM_ [ ("whose first line never ends", C.replicate 4096 'x')@@ -2874,7 +3271,7 @@      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 [node] <> "END\r\n"+        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.get client "key" `shouldReturn` Just ("foo", 0, 1)@@ -2890,7 +3287,7 @@     -- reply left over for a request that should never come.     it "refuses a configuration endpoint older than memcached 1.6.10" $       withMockServer [MR "VA 3 f0 c1\r\nfoo\r\n"] $ \node -> do-        let value = "VALUE AmazonElastiCache:cluster 0 " <> nodeList [node] <> "END\r\n"+        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))             `shouldThrow` versionRefused "VERSION 1.4.5"@@ -2900,7 +3297,7 @@     -- The client's connections to the nodes it discovers are checked too.     it "refuses a discovered node older than memcached 1.6.10" $       withMockServer [MR "VERSION 1.6.9\r\n", MR "HD c1\r\n"] $ \node -> do-        let config = "CONFIG cluster 0 " <> nodeList [node] <> "END\r\n"+        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.set client "key" injection 0 0 `shouldThrow` versionRefused "VERSION 1.6.9"@@ -2912,7 +3309,7 @@     -- later then, as these mocks do.     it "discovers nodes from the cluster key when discovery's version request gets one before 1.4.14" $       withMockMemcached supportedVersion [MR "VA 3 f0 c1\r\nfoo\r\n"] $ \node -> do-        let value = "VALUE AmazonElastiCache:cluster 0 " <> nodeList [node] <> "END\r\n"+        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.get client "key" `shouldReturn` Just ("foo", 0, 1)@@ -2979,7 +3376,7 @@       , (" inside mask_", mask_, MR longVersion)       , (" as a bracket's acquire", \make -> bracket make Client.quit pure, MR longVersion)       , ( " inside mask_ with the configuration sent along", mask_-        , MR (longVersion <> configListing ["127.0.0.1|127.0.0.1|11211"]) )+        , MR (longVersion <> configListing "1" ["127.0.0.1|127.0.0.1|11211"]) )       ] $ \(how, run, reply) ->       it ("fails at once on a long version reply" <> how) $         withMockMemcached supportedVersion [reply, Noop, Noop] $ \cfg -> do@@ -3025,7 +3422,7 @@       \(host, port) -> do         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 [node]), Noop] $ \cfg ->+          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 @@ -3063,9 +3460,9 @@           "Configuration endpoint replied: SERVER_ERROR x\\ESC[2J\\nforged log line")       , ("a long error reply", MR ("SERVER_ERROR " <> C.replicate 1000 'x' <> "\r\n"),           "Configuration endpoint replied: SERVER_ERROR " <> replicate 187 'x' <> "...")-      , ("a malformed node", MR (configListing ["a\ESCb|127.0.0.1|11211"]),+      , ("a malformed node", MR (configListing "1" ["a\ESCb|127.0.0.1|11211"]),           "Not a valid URI: memcached://a\\ESCb:11211")-      , ("node info it can't split", MR (configListing ["a|\tb"]),+      , ("node info it can't split", MR (configListing "1" ["a|\tb"]),           "Unrecognized components in node info: a|\\tb")       ] $ \(what, reply, expected) ->       it ("escapes and shortens the endpoint's text in the error for " <> what) $@@ -3078,7 +3475,7 @@     -- isn't a host, an IP address and a port.     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 entries), Noop] $ \cfg ->+        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" @@ -3086,7 +3483,7 @@     -- each space. The error says that the config lists an empty node, rather     -- than that the entry isn't a host, an IP address and a port.     it "rejects a config that lists an empty node" $ do-      let config = configListing ["a|10.0.0.1|1", "", "b|10.0.0.2|2"]+      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"@@ -3096,7 +3493,7 @@     -- and then the first request would wait seconds for the ring that routes     -- keys. Discovery counts the nodes before it makes any server.     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 (manyNodes 1000))] $ \cfg ->+      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)           length <$> Cluster.getServers client `shouldReturn` 1000@@ -3109,7 +3506,7 @@           -- wakes every second, until a major GC ended it, or would fail           -- withDiscovery's check that it has ended.           waitFor 1002 (length <$> made) `shouldReturn` 1002-      withMockMemcached "1.6.12" [MR "VERSION 1.6.12\r\n", MR (configListing (manyNodes 1001)), Noop] $ \cfg ->+      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"@@ -3119,7 +3516,7 @@     -- reply listing too many costs no parsing: the first entry here can't     -- 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 ("bad" : manyNodes 1000)), Noop] $ \cfg ->+      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" @@ -3130,13 +3527,46 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b -> do         let node m ip = "127.0.0.1|" <> ip <> "|" <> C.pack (show (mockPort m))-            config = configListing [node a "127.0.0.1", node b "127.0.0.1", node a "10.0.0.2"]+            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)             filter (/= [mockServerSpec cfg]) <$> made `shouldReturn` [] +    -- A configuration's version is the line before its nodes. Discovery+    -- reads it without the ASCII whitespace around it, so that a line ending+    -- in CR LF, where AWS documents LF alone, reads the same, and then as+    -- decimal digits alone, of any number that fits in 64 bits.+    forM_ ["0", "007", " 12 ", "\t12\t", "12\r", "18446744073709551615"] $ \version ->+      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)+          length <$> Cluster.getServers client `shouldReturn` 1++    -- A version with anything else in it, such as a sign, a second number, a+    -- digit outside ASCII or whitespace outside ASCII, here a no-break space+    -- in UTF-8, or one too large for 64 bits, can't be read, and the first+    -- discovery fails, as it does for a reply it can't parse. The error+    -- quotes the line, escaped.+    forM_+      [ ("", "Unrecognized configuration version")+      , ("-1", "Unrecognized configuration version: -1")+      , ("+1", "Unrecognized configuration version: +1")+      , ("1.5", "Unrecognized configuration version: 1.5")+      , ("1 2", "Unrecognized configuration version: 1 2")+      , ("0x1f", "Unrecognized configuration version: 0x1f")+      , ("\217\161", "Unrecognized configuration version: \\1633")+      , ("\194\160\&12", "Unrecognized configuration version: \\160\\&12")+      , ("18446744073709551616", "Unrecognized configuration version: 18446744073709551616")+      ] $ \(version, expected) ->+      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+     -- When a request is never answered, discovery gives up once     -- optsServerTimeout 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@@ -3166,7 +3596,7 @@     -- endpoint then stops answering.     it "keeps the servers when a refresh's connection is refused" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->-      withMockServer ([supported] ++ refreshTo [a]+      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@@ -3182,14 +3612,14 @@     it "keeps discovering after a refresh fails" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a]+      withMockMemcached "1.6.12" (refreshTo "1" [a]           -- The endpoint drops the connection and replies with garbage-          -- before a refresh succeeds. Then it lists no nodes, and then it-          -- stops answering.+          -- before a refresh succeeds. Then it lists no nodes, at a higher+          -- version, and then it stops answering.           ++ [CloseConnection]           ++ [MR "VERSION 1.6.12\r\n", MR "garbage\r\nEND\r\n"]-          ++ refreshTo [a, b]-          ++ refreshTo []+          ++ refreshTo "2" [a, b]+          ++ refreshTo "3" []           ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.@@ -3218,9 +3648,9 @@     it "keeps discovering after a refresh gets an error reply" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a]+      withMockMemcached "1.6.12" (refreshTo "1" [a]           ++ [MR "VERSION 1.6.12\r\n", MR "ERROR\r\n"]-          ++ refreshTo [a, b]+          ++ 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@@ -3240,18 +3670,18 @@         mockRequests b `shouldReturn` ["version\r\n", "flush_all\r\n"]      -- Each connection to the endpoint gets its own replies. The first refresh-    -- gets its reply, which lists b alone, 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.+    -- 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" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withConcurrentMockMemcached "1.6.12"-          ( refreshTo [a]+          ( refreshTo "1" [a]           : ( MR "VERSION 1.6.12\r\n"-            : DelayMS 2000 (MR ("CONFIG cluster 0 " <> nodeList [b] <> "END\r\n"))+            : DelayMS 2000 (MR ("CONFIG cluster 0 " <> nodeList "2" [b] <> "END\r\n"))             : noReplies )-          : refreshTo [a, b]+          : refreshTo "3" [a, b]           : repeat noReplies ) $ \cfg ->       withDiscovery Client.def { Client.optsServerTimeout = 1000 } $ \opts start made -> do         client <- EC.newClient opts tenMs (endpoint cfg)@@ -3273,7 +3703,7 @@     it "keeps discovering after a refresh gets no reply" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a] ++ [Noop] ++ refreshTo [a, b] ++ noReplies) $ \cfg ->+      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)         start@@ -3293,7 +3723,7 @@     -- must end the refresh.     it "keeps the servers when a refresh gets a config reply that never ends" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->-      withMockMemcached "1.6.12" (refreshTo [a]+      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@@ -3313,7 +3743,9 @@     -- A refresh whose reply lists no nodes fails, rather than dropping every     -- server, and one whose reply lists too many nodes, an empty node or a     -- node twice, fails before making a server for any of them. Each keeps-    -- the servers.+    -- the servers, and the version they were applied at: the failed+    -- refresh's version is higher than the next refresh's, which still+    -- applies.     forM_       [ ("no nodes", [])       , ("more than 1,000 nodes", manyNodes 1001)@@ -3323,9 +3755,9 @@       it ("keeps the servers when a refresh lists " <> problem) $         withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->         withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-        withMockMemcached "1.6.12" (refreshTo [a]-            ++ [MR "VERSION 1.6.12\r\n", MR (configListing nodes)]-            ++ refreshTo [a, b]+        withMockMemcached "1.6.12" (refreshTo "1" [a]+            ++ [MR "VERSION 1.6.12\r\n", MR (configListing "3" nodes)]+            ++ refreshTo "2" [a, b]             ++ noReplies) $ \cfg ->         -- With this time limit no refresh runs out of time on a slow machine,         -- which would shift the replies.@@ -3338,6 +3770,83 @@           filter (/= [mockServerSpec cfg]) <$> made             `shouldReturn` [[mockServerSpec a], [mockServerSpec b]] +    -- A configuration's version goes up as nodes are added or removed, and a+    -- refresh applies a configuration only if its version is higher than+    -- that of the one applied last, so that a reply with an older version, as+    -- from an endpoint node that hasn't caught up yet, can't roll the servers+    -- back. A refresh whose version can't be read fails, and keeps the+    -- servers too. Here the client starts at version 9 with a and b, and the+    -- refresh lists a alone. 10 is higher than 9, though it sorts before it+    -- as text. Both ways of asking for the configuration get the check. With+    -- a reply left, b's mock waits on its connection until it closes.+    forM_ [("config get cluster", refreshTo), ("get AmazonElastiCache:cluster", keyRefreshTo)] $+      \(request, discoveryTo) ->+      forM_+        [ ("lower", "8", False), ("the same", "9", False), ("unreadable", "10x", False)+        , ("higher", "10", True) ] $ \(what, version, applies) ->+        it ((if applies then "applies a refresh whose configuration version is "+               else "keeps the servers when a refresh's configuration version is ")+             <> what <> ", asking with " <> C.unpack request) $+          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)+            Client.flush client Nothing+            start+            -- The refresh after the one that lists a alone has sent its+            -- request, so that one has been handled. Each refresh connects to+            -- the endpoint afresh, and each new connection first checks its+            -- version.+            waitFor 8 (length <$> mockRequests cfg) `shouldReturn` 8+            mockRequests cfg `shouldReturn`+              concat (replicate 2 ["version\r\n", "version\r\n", request <> "\r\n"])+              ++ ["version\r\n", "version\r\n"]+            length <$> Cluster.getServers client `shouldReturn` (if applies then 1 else 2)+            Client.flush client Nothing+            mockRequests a `shouldReturn` ["version\r\n", "flush_all\r\n", "flush_all\r\n"]+            if applies+              then waitFor 1 (mockClosed b) `shouldReturn` 1+              -- b's server is kept, with its connection.+              else mockRequests b `shouldReturn` ["version\r\n", "flush_all\r\n", "flush_all\r\n"]+            -- The refresh made no server.+            filter (/= [mockServerSpec cfg]) <$> made+              `shouldReturn` [[mockServerSpec a], [mockServerSpec b]]++    -- A refresh compares its version with that of the configuration applied+    -- last, not with that of the last one it got. The client starts at+    -- version 5, and the refreshes at 3 and then 4 are both lower: had the+    -- client kept version 3, it would have applied 4.+    it "compares a refresh's configuration version with that of the one applied last" $+      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)+        start+        -- The refresh after the one at version 4 has sent its request, so+        -- that one has been handled.+        waitFor 11 (length <$> mockRequests cfg) `shouldReturn` 11+        length <$> Cluster.getServers client `shouldReturn` 1+        filter (/= [mockServerSpec cfg]) <$> made `shouldReturn` [[mockServerSpec a]]++    -- The version applied last can be a refresh's as well as the first+    -- discovery's. The refresh at version 3 applies a and b, so the one at+    -- version 2 after it is older, though newer than the first discovery's:+    -- had the thread kept version 1 after applying 3, it would have rolled+    -- the servers back to a alone.+    it "compares a refresh's configuration version with that of one a refresh applied" $+      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)+        start+        -- The refresh after the one at version 2 has sent its request, so+        -- that one has been handled.+        waitFor 11 (length <$> mockRequests cfg) `shouldReturn` 11+        length <$> Cluster.getServers client `shouldReturn` 2+     -- A refresh runs with asynchronous exceptions unmasked even when the     -- client is made inside mask_, as in a bracket's acquire, so that its     -- time limit can interrupt it while it computes, not only where it@@ -3347,7 +3856,7 @@     it "refreshes unmasked when the client is made inside mask_" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a] ++ refreshTo [a, b] ++ noReplies) $ \cfg ->+      withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "2" [a, b] ++ noReplies) $ \cfg ->       withDiscovery Client.def { Client.optsServerTimeout = 10000 } $ \opts start _ -> do         me <- myThreadId         states <- newIORef []@@ -3363,11 +3872,193 @@         waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2         readIORef states `shouldReturn` [Unmasked, Unmasked] +    -- After the first refresh, the endpoint stops answering, so the second+    -- refresh waits for a reply, for up to 10 s. quit stops the refresh+    -- thread: that refresh is abandoned, closing its connection, and no+    -- refresh follows it.+    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+        (recording, refreshThreads) <- recordingThreads opts+        client <- EC.newClient recording tenMs (endpoint cfg)+        start+        -- The second refresh has asked for the version. Each refresh+        -- connects to the endpoint afresh, and each new connection first+        -- checks its version.+        waitFor 8 (length <$> mockRequests cfg) `shouldReturn` 8+        Client.quit client+        [thread] <- refreshThreads+        waitFor True (threadEnded thread) `shouldReturn` True+        -- The first discovery's connection, the first refresh's, and the+        -- waiting refresh's.+        waitFor 3 (mockClosed cfg) `shouldReturn` 3+        -- Ten intervals later, no refresh has followed.+        threadDelay 100000+        length <$> mockRequests cfg `shouldReturn` 8++    -- The first refresh lists b, and making b's server waits until the test+    -- lets it go on, with the refresh's connection to the endpoint back in+    -- its pool. The client is quit meanwhile. The refresh is abandoned,+    -- closing that connection, and the servers stay as they were: no refresh+    -- may replace them once quit has closed their connections.+    it "abandons a refresh in progress when the client is quit" $+      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 -> do+        held <- newEmptyMVar+        kept <- newIORef []+        let holdB serverOptions specs = do+              when (specs == [mockServerSpec b]) $ readMVar held+              servers <- Client.optsServerSpecsToServers Client.def serverOptions specs+              atomicModifyIORef' kept (\earlier -> (servers ++ earlier, ()))+              return servers+            holding = Client.def+              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = holdB }+        withDiscovery holding $ \opts start made -> do+          client <- EC.newClient opts tenMs (endpoint cfg)+          start+          waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True+          Client.quit client+          -- The first discovery's connection, and the refresh's.+          waitFor 2 (mockClosed cfg) `shouldReturn` 2+          putMVar held ()+          threadDelay 100000+          length <$> Cluster.getServers client `shouldReturn` 1+          -- Checked last, so that every server made, the refresh thread's+          -- server for the endpoint among them, stays reachable until now,+          -- and the garbage collector can't close the refresh's connection in+          -- place of the client.+          length <$> readIORef kept `shouldReturn` 3++    -- The first refresh lists b, and making b's server waits, catching every+    -- exception, as code that catches SomeException does. So it swallows the+    -- kill that quit sends, and the refresh goes on to the swap. The flag+    -- that quit sets keeps the refresh from replacing the servers, and the+    -- thread ends.+    it "replaces no servers after quit when the server constructor catches the kill" $+      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 -> do+        held <- newEmptyMVar+        let catchB serverOptions specs = do+              when (specs == [mockServerSpec b]) $+                void (try (readMVar held) :: IO (Either SomeException ()))+              Client.optsServerSpecsToServers Client.def serverOptions specs+            catching = Client.def+              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = catchB }+        withDiscovery catching $ \opts start made -> do+          (recording, refreshThreads) <- recordingThreads opts+          client <- EC.newClient recording tenMs (endpoint cfg)+          start+          waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True+          [thread] <- refreshThreads+          -- Quit once the refresh waits to make b's server, so that the kill+          -- reaches it there.+          waitUntilThreadBlocked thread+          Client.quit client+          waitFor True (threadEnded thread) `shouldReturn` True+          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.+    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 ->+      withMockMemcached "1.6.12" (refreshTo "1" [a] ++ refreshTo "2" [a, b] ++ noReplies) $ \cfg -> do+        held <- newEmptyMVar+        let holdB serverOptions specs = do+              when (specs == [mockServerSpec b]) $ uninterruptibleMask_ (readMVar held)+              Client.optsServerSpecsToServers Client.def serverOptions specs+            holding = Client.def+              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = holdB }+        withDiscovery holding $ \opts start made -> do+          (recording, refreshThreads) <- recordingThreads opts+          client <- EC.newClient recording tenMs (endpoint cfg)+          start+          waitFor True (elem [mockServerSpec b] <$> made) `shouldReturn` True+          [thread] <- refreshThreads+          waitUntilThreadBlocked thread+          -- A quit that waited for the thread would wait until b's server+          -- could be made: let that happen after 3 s, so that such a quit+          -- fails the test rather than hangs it.+          release <- forkIO $ threadDelay 3000000 >> void (tryPutMVar held ())+          timeout 1000000 (Client.quit client) `shouldReturn` Just ()+          void (tryPutMVar held ())+          killThread release+          waitFor True (threadEnded thread) `shouldReturn` True+          -- The first discovery's connection, and the refresh's.+          waitFor 2 (mockClosed cfg) `shouldReturn` 2+          length <$> Cluster.getServers client `shouldReturn` 1++    -- A cluster made from the client by setServers has servers of its own,+    -- which the refresh thread doesn't replace, so quitting it leaves the+    -- thread refreshing the client's servers.+    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)+        other <- Cluster.setServers client . Right <$> Cluster.getServers client+        start+        waitFor True ((>= 6) . length <$> mockRequests cfg) `shouldReturn` True+        Client.quit other+        -- Two more refreshes, each with three requests on a connection of its+        -- own.+        requests <- length <$> mockRequests cfg+        waitFor True ((>= requests + 6) . length <$> mockRequests cfg) `shouldReturn` True+        keepReachable client++    -- The refresh thread doesn't keep the client reachable, so it stops once+    -- the client has been garbage collected, leaving no connection to the+    -- endpoint open. Every refresh here works, and the client is used until+    -- the thread has refreshed twice.+    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+        (recording, refreshThreads) <- recordingThreads opts+        client <- EC.newClient recording tenMs (endpoint cfg)+        start+        waitFor True ((>= 9) . length <$> mockRequests cfg) `shouldReturn` True+        keepReachable client+        [thread] <- refreshThreads+        -- A collection while the thread swaps in servers finds the client+        -- reachable, so collect until the thread has ended.+        waitFor True (performMajorGC >> threadDelay 10000 >> threadEnded thread) `shouldReturn` True+        -- Each connection to the endpoint got three requests, and the client+        -- closed every one.+        connections <- (`div` 3) . length <$> mockRequests cfg+        waitFor connections (mockClosed cfg) `shouldReturn` connections++    -- The same when every refresh is ignored, as for a cluster that doesn't+    -- change: after a refresh that applies nothing, the thread still waits+    -- out the interval and checks that the client is reachable before the+    -- next, rather than refreshing again at once.+    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+        (recording, refreshThreads) <- recordingThreads opts+        client <- EC.newClient recording tenMs (endpoint cfg)+        start+        waitFor True ((>= 9) . length <$> mockRequests cfg) `shouldReturn` True+        keepReachable client+        [thread] <- refreshThreads+        waitFor True (performMajorGC >> threadDelay 10000 >> threadEnded thread) `shouldReturn` True+        connections <- (`div` 3) . length <$> mockRequests cfg+        waitFor connections (mockClosed cfg) `shouldReturn` connections+     it "keeps the connections of nodes still listed" $       withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       -- Listing b first checks that servers are matched by host and port.-      withMockMemcached "1.6.12" (refreshTo [a] ++ refreshTo [b, a] ++ noReplies) $ \cfg ->+      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@@ -3387,7 +4078,7 @@     -- replaced, so they must be closed, though the node keeps its server.     it "closes the connections of a node whose IP address changes" $       withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \a ->-      withMockMemcached "1.6.12" (refreshTo [a] ++ refreshToAt "10.0.0.2" [a] ++ noReplies) $ \cfg ->+      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@@ -3409,7 +4100,7 @@     -- reply left, a's mock then waits on that connection until it closes.     it "closes a connection in use by a node whose IP address changes once its request finishes" $       withMockMemcached supportedVersion [DelayMS 300 (MR "OK\r\n"), MR "OK\r\n"] $ \a ->-      withMockMemcached "1.6.12" (refreshTo [a] ++ refreshToAt "10.0.0.2" [a] ++ noReplies) $ \cfg ->+      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@@ -3425,20 +4116,25 @@         -- The flush isn't interrupted: it gets a's reply.         wait flushing         waitFor 1 (mockClosed a) `shouldReturn` 1+        -- The refresh thread stops once the client has been garbage+        -- collected, so keep the client reachable until the refreshes are+        -- done.+        keepReachable client      -- The endpoint's name leads to one of the nodes, so once ElastiCache     -- replaces that node, a connection to the endpoint made before then may     -- get no reply. Each connection to the endpoint gets its own replies: the-    -- first refresh's connection stops answering once that refresh is done,-    -- and the next connection lists a with a new IP address. The time limit-    -- is longer than waitFor waits, so a refresh that took the first-    -- refresh's connection again would close a's connection too late.+    -- first refresh's connection, which gets the same configuration again,+    -- stops answering once that refresh is done, and the next connection+    -- lists a with a new IP address, at a higher version. The time limit is+    -- longer than waitFor waits, so a refresh that took the first refresh's+    -- connection again would close a's connection too late.     it "connects to the endpoint afresh for each refresh" $       withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \a ->       withConcurrentMockMemcached "1.6.12"-          ( refreshTo [a]-          : (refreshTo [a] ++ noReplies)-          : (refreshToAt "10.0.0.2" [a] ++ noReplies)+          ( refreshTo "1" [a]+          : (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)@@ -3448,6 +4144,10 @@         -- The client closed the connections of both refreshes once they were         -- done, rather than leave them open.         waitFor 2 (mockClosed cfg) `shouldReturn` 2+        -- The refresh thread stops once the client has been garbage+        -- collected, so keep the client reachable until the refreshes are+        -- done.+        keepReachable client      -- Making b's server fails, so the first refresh fails after it has read     -- the endpoint's reply, with the connection back in the pool. The@@ -3458,8 +4158,8 @@       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->       withConcurrentMockMemcached "1.6.12"-          ( refreshTo [a]-          : (refreshTo [a, b] ++ noReplies)+          ( refreshTo "1" [a]+          : (refreshTo "2" [a, b] ++ noReplies)           : repeat noReplies ) $ \cfg -> do         let failForB serverOptions specs               | specs == [mockServerSpec b] = ioError (userError "no server for b")@@ -3475,6 +4175,37 @@             `shouldReturn` [[mockServerSpec a], [mockServerSpec b]]           length <$> Cluster.getServers client `shouldReturn` 1 +    -- A configuration that fails to apply, as making b's server fails here+    -- the first time, doesn't count as applied: the version applied last+    -- stays 1, so the next refresh, which gets the same configuration at the+    -- same version, 2, applies it. Each connection to the endpoint gets its+    -- own replies.+    it "tries a configuration again at the same version after making a server fails" $+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->+      withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->+      withConcurrentMockMemcached "1.6.12"+          ( refreshTo "1" [a]+          : (refreshTo "2" [a, b] ++ noReplies)+          : (refreshTo "2" [a, b] ++ noReplies)+          : repeat noReplies ) $ \cfg -> do+        failedOnce <- newIORef False+        let failForBOnce serverOptions specs = do+              failNow <- if specs == [mockServerSpec b]+                then atomicModifyIORef' failedOnce (\failed -> (True, not failed))+                else pure False+              if failNow+                then ioError (userError "no server for b")+                else Client.optsServerSpecsToServers Client.def serverOptions specs+            failing = Client.def+              { Client.optsServerTimeout = 10000, Client.optsServerSpecsToServers = failForBOnce }+        withDiscovery failing $ \opts start made -> do+          client <- EC.newClient opts tenMs (endpoint cfg)+          start+          waitFor 2 (length <$> Cluster.getServers client) `shouldReturn` 2+          -- b's server was made at both refreshes, as the first failed.+          filter (/= [mockServerSpec cfg]) <$> made+            `shouldReturn` [[mockServerSpec a], [mockServerSpec b], [mockServerSpec b]]+     -- The order breaks ties on the ketama ring. Discovery used to sort the     -- servers by sid, so both the first discovery and the refresh list the     -- node with the higher sid first.@@ -3489,7 +4220,7 @@         [sidA] <- sidOf a         [sidB] <- sidOf b         let (hi, lo) = if sidA > sidB then (a, b) else (b, a)-        withMockMemcached "1.6.12" (refreshTo [hi, lo] ++ refreshTo [hi, lo, c] ++ noReplies) $ \cfg ->+        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@@ -3502,14 +4233,14 @@             ports `shouldReturn` portsOf [hi, lo, c]      -- The first refresh adds b, the second fails, and the third lists a and b-    -- again.+    -- again, at a higher version, so that it is applied.     it "reuses the servers of known nodes after a refresh fails" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a]-          ++ refreshTo [a, b]+      withMockMemcached "1.6.12" (refreshTo "1" [a]+          ++ refreshTo "2" [a, b]           ++ [CloseConnection]-          ++ refreshTo [a, b]+          ++ refreshTo "3" [a, b]           ++ noReplies) $ \cfg ->       -- With this time limit no refresh runs out of time on a slow machine,       -- which would shift the replies.@@ -3538,7 +4269,7 @@       withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \a ->       -- With a reply left, b's mock waits on its connection until it closes.       withMockMemcached supportedVersion [MR "OK\r\n", MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a, b] ++ refreshTo [a] ++ noReplies) $ \cfg ->+      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@@ -3567,7 +4298,7 @@     it "closes a connection in use by a node no longer listed once its request finishes" $       withMockMemcached supportedVersion [MR "OK\r\n"] $ \a ->       withMockMemcached supportedVersion [DelayMS 300 (MR "OK\r\n"), MR "OK\r\n"] $ \b ->-      withMockMemcached "1.6.12" (refreshTo [a, b] ++ refreshTo [a] ++ noReplies) $ \cfg ->+      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@@ -3639,6 +4370,12 @@     authRequests = ["version\r\n", "set auth 0 0 9\r\nuser pass\r\n"]     withCredentials server = (mockServerSpec server) { ssAuth = Auth.Auth "user" "pass" }     supported = MR ("VERSION " <> supportedVersion <> "\r\n")+    -- memcached at its connection limit sends a new connection this line and+    -- closes it, without waiting for a request. The mock waits for the+    -- client's first request, the version check or the auth probe, so that+    -- the client never writes to a connection already closed, which can fail+    -- the write instead.+    atLimit = ReplyThenClose "ERROR Too many open connections\r\n"     -- Versions as memcached reports them, with Ubuntu's suffix and a     -- release candidate's; 1.10.0 and 1.6.9 catch comparing them as text.     oldVersions =@@ -3736,34 +4473,52 @@     -- in the path and keep the host a plain loopback address.     endpoint cfg = either error id $       EC.parseConfigurationEndpoint ("memcached://127.0.0.1:" <> show (mockPort cfg) <> "/x.cfg")-    -- A config reply body listing the given nodes, from its length line-    -- onwards.-    nodeList = nodeListAt "127.0.0.1"+    -- A config reply body with the given version line, listing the given+    -- nodes, from its length line onwards.+    nodeList version = nodeListAt version "127.0.0.1"     -- The same, giving each node the IP address @ip@.-    nodeListAt ip nodes =+    nodeListAt version ip nodes =       let node n = "127.0.0.1|" <> ip <> "|" <> C.pack (show (mockPort n))-          body = "1\n" <> C.unwords (map node nodes) <> "\n"+          body = version <> "\n" <> C.unwords (map node nodes) <> "\n"       in C.pack (show (B.length body)) <> "\r\n" <> body <> "\r\n"     -- A version reply of 32,000 numbers, 64,009 bytes long.     longVersion = "VERSION " <> C.intercalate "." (replicate 32000 "1") <> "\r\n"     -- Node entries for n nodes, each with a name of its own.     manyNodes n = ["node" <> C.pack (show i) <> ".example|10.0.0.1|11211" | i <- [1 .. n :: Int]]-    -- A config reply listing the given node entries, each host|IP|port.-    configListing entries =-      let body = "1\n" <> C.unwords entries <> "\n"+    -- A config reply with the given version line, listing the given node+    -- entries, each host|IP|port.+    configListing version entries =+      let body = version <> "\n" <> C.unwords entries <> "\n"       in "CONFIG cluster 0 " <> C.pack (show (B.length body)) <> "\r\n" <> body <> "\r\nEND\r\n"-    -- The config endpoint's replies to one discovery of the given nodes,-    -- whether it creates a client or refreshes one.-    refreshTo = refreshToAt "127.0.0.1"-    refreshToAt ip nodes =-      [MR "VERSION 1.6.12\r\n", MR ("CONFIG cluster 0 " <> nodeListAt ip nodes <> "END\r\n")]+    -- The config endpoint's replies to one discovery of the given nodes, with+    -- the given version line, whether it creates a client or refreshes one.+    refreshTo version = refreshToAt version "127.0.0.1"+    refreshToAt version ip nodes =+      [MR "VERSION 1.6.12\r\n", MR ("CONFIG cluster 0 " <> nodeListAt version ip nodes <> "END\r\n")]+    -- The same from an endpoint that reports a version before 1.4.14 to+    -- discovery's version request, so that discovery reads the cluster key.+    keyRefreshTo version nodes =+      [ MR "VERSION 1.4.5\r\n"+      , MR ("VALUE AmazonElastiCache:cluster 0 " <> nodeList version nodes <> "END\r\n") ]     -- What the endpoint does once a test's script is done: it reads requests     -- and never answers. A mock that stopped listening instead would give-    -- its port back while the refresh thread, which runs until the test+    -- its port back while the refresh thread, which can run until the test     -- ends, still connects to it every interval. Another process running     -- the tests could then get that port for a mock of its own, and the     -- thread would take that mock's replies.     noReplies = repeat Noop+    -- Options whose server constructor records each thread but the caller's+    -- that calls it, as the refresh thread does when it starts, and an+    -- action that lists those threads.+    recordingThreads opts = do+      me <- myThreadId+      threads <- newIORef []+      let recording serverOptions specs = do+            thread <- myThreadId+            when (thread /= me) $ atomicModifyIORef' threads (\earlier -> (thread : earlier, ()))+            Client.optsServerSpecsToServers opts serverOptions specs+      return (opts { Client.optsServerSpecsToServers = recording }, nub <$> readIORef threads)+    threadEnded thread = (`elem` [ThreadFinished, ThreadDied]) <$> threadStatus thread  -- | Run an action with a client connected to a fresh mock server, which -- reports 'supportedVersion' to each connection's version check.@@ -3793,7 +4548,8 @@  -- | Use the client, so it stays reachable until this point: otherwise the -- pool's finalizers could close its connections while a test is checking that--- 'Client.quit' closed them.+-- 'Client.quit' closed them, and an ElastiCache client's refresh thread could+-- stop before the refreshes a test waits for. keepReachable :: Client.Client -> IO () keepReachable = Cluster.getServers >=> mapM_ (readIORef . Server.failed) @@ -3823,6 +4579,23 @@     -- Servers compare equal when they are for the same host and port.     serversFor specs = toList <$> (Cluster.getServers =<< Client.newClient specs Client.def) +-- | Like 'withTwoServerClient', but the client gives both servers the same+-- sid, as two servers whose hosts and ports hash alike would have. The router+-- tells the servers apart by their ports.+withSameSidClient+  :: [MockResponse] -> [MockResponse]+  -> (MockServer -> MockServer -> Client.Client -> IO a) -> IO a+withSameSidClient as bs action =+  withMockMemcached supportedVersion as $ \a ->+  withMockMemcached supportedVersion bs $ \b -> do+    let sameSid opts specs = map (\s -> s { Server.sid = 0 }) <$> mapM (Server.newServerDefault opts) specs+        route cluster key =+          let port = show (mockPort (if "a" `B.isPrefixOf` key then a else b))+          in find ((== port) . Server.serverPort) <$> Cluster.getServers cluster+    client <- Client.newClient [mockServerSpec a, mockServerSpec b]+      Client.def { Client.optsServerSpecsToServers = sameSid, Client.optsGetServerForKey = route }+    action a b client+ -- | Run an action with a client, made with the given options, whose only -- server is at a port that is bound but never listened on, so that every -- attempt to connect to it is refused.@@ -3831,8 +4604,8 @@   withBoundSocket (N.SockAddrInet 0 (N.tupleToHostAddress (127, 0, 0, 1))) $ \port ->     Client.withClient [ServerSpec "127.0.0.1" (show port) Auth.NoAuth] opts action --- | The longest value the client sends: 1 GiB, the largest item memcached can--- store.+-- | The longest value the client sends: 1 GiB, more than any memcached server+-- can store. valueLimit :: Int valueLimit = 1073741824 @@ -3872,9 +4645,12 @@ -- discovery thread back, when that thread starts and whenever it adds a node, -- until the test runs the action it is passed. The test is also passed an -- action that lists the specs given to each call of the constructor, oldest--- first. The thread is killed when the test ends, as nothing else stops it,--- if it has called the constructor by then, and a test that passed then--- checks that the thread has ended.+-- first. The thread is killed when the test ends, if it has called the+-- constructor by then, and a test that passed then checks that the thread+-- has ended. 'Client.quit' stops the thread too, and so does a garbage+-- collection once the client is unreachable, so a test that waits for+-- refreshes must keep its client reachable until they are done, as with+-- 'keepReachable'. withDiscovery   :: Client.Options -> (Client.Options -> IO () -> IO [[ServerSpec]] -> IO a) -> IO a withDiscovery opts test = do@@ -3971,10 +4747,14 @@ -- | Wait until the thread is blocked, as when it waits for the pool. A thread -- that ends instead fails the test rather than hanging it. waitUntilBlocked :: Async a -> IO ()-waitUntilBlocked thread = do-  status <- threadStatus (asyncThreadId thread)+waitUntilBlocked = waitUntilThreadBlocked . asyncThreadId++-- | 'waitUntilBlocked' for a thread given by its 'ThreadId'.+waitUntilThreadBlocked :: ThreadId -> IO ()+waitUntilThreadBlocked thread = do+  status <- threadStatus thread   case status of-    ThreadRunning -> threadDelay 1000 >> waitUntilBlocked thread+    ThreadRunning -> threadDelay 1000 >> waitUntilThreadBlocked thread     ThreadBlocked _ -> return ()     _ -> expectationFailure "the thread ended without blocking" @@ -4032,10 +4812,10 @@   vectorOf len (frequency [(8, choose (0x21, 0x7e)), (1, arbitrary)])  -- | Non-empty credentials of arbitrary bytes, biased towards ones a URI--- must escape, without the bytes 'validateCredentials' rejects (space, tab,--- CR, LF, NUL) or any in @extra@.+-- must escape, without the bytes 'validateCredentials' rejects (space, CR,+-- LF, NUL) or any in @extra@. credentialGen :: String -> Gen B.ByteString-credentialGen extra = C.pack <$> listOf1 (byte `suchThat` (`notElem` (" \t\r\n\0" <> extra)))+credentialGen extra = C.pack <$> listOf1 (byte `suchThat` (`notElem` (" \r\n\0" <> extra)))   where     byte = frequency [(4, choose ('\0', '\xff')), (1, elements ":@%/?#[]")]