statsd-rupp 0.5.0.2 → 0.6.0
raw patch · 7 files changed
+201/−84 lines, 7 filesdep +asyncdep +stmdep −unliftiosetup-changedPVP ok
version bump matches the API change (PVP)
Dependencies added: async, stm
Dependencies removed: unliftio
API changes (from Hackage documentation)
- System.Metrics.StatsD: addTiming :: MonadIO m => StatTiming -> Int -> m ()
+ System.Metrics.StatsD: addTiming :: StatTiming -> Int -> IO ()
- System.Metrics.StatsD: decrementGauge :: MonadIO m => StatGauge -> Int -> m ()
+ System.Metrics.StatsD: decrementGauge :: StatGauge -> Int -> IO ()
- System.Metrics.StatsD: incrementCounter :: MonadIO m => StatCounter -> Int -> m ()
+ System.Metrics.StatsD: incrementCounter :: StatCounter -> Int -> IO ()
- System.Metrics.StatsD: incrementGauge :: MonadIO m => StatGauge -> Int -> m ()
+ System.Metrics.StatsD: incrementGauge :: StatGauge -> Int -> IO ()
- System.Metrics.StatsD: newSetElement :: MonadIO m => StatSet -> String -> m ()
+ System.Metrics.StatsD: newSetElement :: StatSet -> String -> IO ()
- System.Metrics.StatsD: newStatCounter :: MonadIO m => Stats -> Key -> Int -> m StatCounter
+ System.Metrics.StatsD: newStatCounter :: Stats -> Key -> Int -> IO StatCounter
- System.Metrics.StatsD: newStatGauge :: MonadIO m => Stats -> Key -> Int -> m StatGauge
+ System.Metrics.StatsD: newStatGauge :: Stats -> Key -> Int -> IO StatGauge
- System.Metrics.StatsD: newStatSet :: MonadIO m => Stats -> Key -> m StatSet
+ System.Metrics.StatsD: newStatSet :: Stats -> Key -> IO StatSet
- System.Metrics.StatsD: newStatTiming :: MonadIO m => Stats -> Key -> Int -> m StatTiming
+ System.Metrics.StatsD: newStatTiming :: Stats -> Key -> Int -> IO StatTiming
- System.Metrics.StatsD: setGauge :: MonadIO m => StatGauge -> Int -> m ()
+ System.Metrics.StatsD: setGauge :: StatGauge -> Int -> IO ()
- System.Metrics.StatsD: withStats :: MonadUnliftIO m => StatConfig -> (Stats -> m a) -> m a
+ System.Metrics.StatsD: withStats :: StatConfig -> (Stats -> IO a) -> IO a
- System.Metrics.StatsD.Internal: connectStatsD :: MonadIO m => String -> Int -> m Socket
+ System.Metrics.StatsD.Internal: connectStatsD :: String -> Int -> IO Socket
- System.Metrics.StatsD.Internal: newMetric :: MonadIO m => Stats -> ByteString -> MetricData -> m ()
+ System.Metrics.StatsD.Internal: newMetric :: Stats -> ByteString -> MetricData -> IO ()
- System.Metrics.StatsD.Internal: newMetrics :: MonadIO m => m (TVar Metrics)
+ System.Metrics.StatsD.Internal: newMetrics :: IO (TVar Metrics)
- System.Metrics.StatsD.Internal: processSample :: MonadIO m => Stats -> Int -> ByteString -> Value -> m ()
+ System.Metrics.StatsD.Internal: processSample :: Stats -> Int -> ByteString -> Value -> IO ()
- System.Metrics.StatsD.Internal: statsFlush :: MonadIO m => Stats -> m ()
+ System.Metrics.StatsD.Internal: statsFlush :: Stats -> IO ()
- System.Metrics.StatsD.Internal: statsLoop :: MonadIO m => Stats -> m ()
+ System.Metrics.StatsD.Internal: statsLoop :: Stats -> IO ()
- System.Metrics.StatsD.Internal: submit :: MonadIO m => Stats -> Sample -> m ()
+ System.Metrics.StatsD.Internal: submit :: Stats -> Sample -> IO ()
Files
- CHANGELOG.md +29/−0
- README.md +15/−3
- Setup.hs +1/−0
- src/System/Metrics/StatsD.hs +41/−21
- src/System/Metrics/StatsD/Internal.hs +38/−31
- statsd-rupp.cabal +6/−4
- test/Spec.hs +71/−25
CHANGELOG.md view
@@ -6,6 +6,35 @@ and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## 0.6.0 - 2026-11-15++- Every function runs in plain `IO` instead of any `MonadIO` or+ `MonadUnliftIO` monad. This breaks backwards compatibility. Names and+ argument orders are the same.+- Remove the dependency on `unliftio`. The library now depends on `async` and+ `stm` directly.+- `withStats` closes its UDP socket when it returns. It was left open, so a+ program that opened clients again and again lost a file descriptor each+ time. A handle that outlives the scope still counts and sends nothing.+- Test `withStats` over UDP, and the errors for bad keys and sampling rates.++### Migrating++- Code that already runs in `IO` needs no change.+- Code in another monad has to lift each call: `liftIO (incrementCounter c 1)`.+- `withStats` takes a function in `IO`. To use it from a monad transformer+ stack, run the stack inside that function. With `ReaderT env IO`, for+ example:++ ```haskell+ env <- ask+ liftIO $ withStats cfg $ \stats -> runReaderT (app stats) env+ ```++- Behaviour is unchanged: the same errors are thrown as `IOError`, network+ errors are ignored when sending, and the flushing thread is linked to the+ caller of `withStats`.+ ## 0.5.0.2 - 2026-11-07 - Lots of documentation.
README.md view
@@ -71,6 +71,8 @@ updating it is one short STM transaction and at most one UDP packet. - **Sampling saves traffic, not accuracy.** Sampling thins out the samples you send. Aggregated statistics always count every reading.+- **Plain `IO`.** Every action is an ordinary `IO` action, built on `base`,+ `stm` and `async`. From a monad transformer stack, call them with `liftIO`. - **Familiar names.** Aggregated metrics follow the naming of the StatsD daemon (`stats.counters.x.count`, `stats.timers.x.mean_90`), so existing dashboards and alerts keep working.@@ -84,7 +86,7 @@ | Aggregation | Counts and rates; gauge values; distinct set sizes; timing count, rate, mean, median, standard deviation, minimum, maximum, sum, sum of squares and percentiles | | Naming | Configurable namespace and prefixes; key validation | | Transport | UDP to any host and port, with an optional newline after each line |-| Monads | Works in any `MonadIO`; `withStats` needs `MonadUnliftIO` |+| Monads | Plain `IO`; from another monad, call it with `liftIO` | ### What is not included @@ -135,7 +137,7 @@ ```yaml extra-deps:- - statsd-rupp-0.5.0.1+ - statsd-rupp-0.6.0 ``` ## Quick start@@ -190,9 +192,9 @@ {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE ScopedTypeVariables #-} +import Control.Exception (SomeException, throwIO, try) import GHC.Clock (getMonotonicTimeNSec) import System.Metrics.StatsD-import UnliftIO (SomeException, throwIO, try) data Metrics = Metrics { requests :: StatCounter,@@ -232,6 +234,12 @@ Use a monotonic clock (`GHC.Clock.getMonotonicTimeNSec`) for durations, so that clock adjustments do not produce negative or huge timings. +`try` from `Control.Exception` also catches asynchronous exceptions, such as+the one a timeout sends to a request that takes too long. That is wanted here:+the request is timed and counted as an error, and `throwIO` then lets the+exception carry on. Never swallow such an exception, or the thread cannot be+stopped.+ ### 4. Choose the mode - If a real StatsD daemon aggregates for you, turn aggregation off with@@ -255,6 +263,10 @@ `Stats` handle to your function. If aggregation is on, it also runs a thread that flushes statistics. Everything stops when the function returns. A `Stats` can be shared between threads.++Everything runs in `IO`. In a `ReaderT` or similar stack, record metrics with+`liftIO (incrementCounter c 1)`, and run your stack inside the function that+you give to `withStats`. ### Registering metrics
Setup.hs view
@@ -1,2 +1,3 @@ import Distribution.Simple+ main = defaultMain
src/System/Metrics/StatsD.hs view
@@ -63,6 +63,13 @@ -- individual samples sent. The aggregated statistics always count every -- reading. --+-- * __Plain 'IO'.__ Every action is an ordinary 'IO' action. Versions before+-- 0.6.0 accepted any monad that can run 'IO', at the price of a class+-- constraint on every signature and one more dependency. A concrete type is+-- easier to read, and lifting is easy to do where it is needed: code in+-- another monad calls these functions with @liftIO@, and runs its own monad+-- inside the function it gives to 'withStats'.+-- -- = Example -- -- @@@ -104,23 +111,28 @@ ( -- * Configuration StatConfig (..), defStatConfig,+ -- * Running Stats, withStats,+ -- * Counters StatCounter, newStatCounter, incrementCounter,+ -- * Gauges StatGauge, newStatGauge, setGauge, incrementGauge, decrementGauge,+ -- * Timings StatTiming, newStatTiming, addTiming,+ -- * Sets StatSet, newStatSet,@@ -128,9 +140,12 @@ ) where +import Control.Concurrent.Async (link, withAsync)+import Control.Exception (bracket, throwIO) import Control.Monad (when) import Data.ByteString.Char8 qualified as C import Data.HashSet qualified as HashSet+import Network.Socket qualified as Net import System.Metrics.StatsD.Internal ( MetricData (..), StatConfig (..),@@ -147,8 +162,6 @@ processSample, statsLoop, )-import UnliftIO (MonadIO, MonadUnliftIO, throwIO)-import UnliftIO.Async (link, withAsync) -- | Name of a metric. Only ASCII letters, digits, @.@, @_@ and @-@ are allowed. type Key = String@@ -194,8 +207,7 @@ -- Sampling is per metric because traffic is: a counter incremented on every -- request needs a low rate, while one incremented on every error can afford to -- send everything.-newStatCounter ::- (MonadIO m) => Stats -> Key -> Int -> m StatCounter+newStatCounter :: Stats -> Key -> Int -> IO StatCounter newStatCounter stats key sampling = do when (sampling < 0) $ throwIO $@@ -207,8 +219,7 @@ -- -- Throws an 'IOError' if the key is invalid or a metric with the same key -- already exists.-newStatGauge ::- (MonadIO m) => Stats -> Key -> Int -> m StatGauge+newStatGauge :: Stats -> Key -> Int -> IO StatGauge newStatGauge stats key ini = do newMetric stats (C.pack key) (GaugeData ini) return $ StatGauge stats (C.pack key)@@ -218,7 +229,7 @@ -- -- Throws an 'IOError' if the sampling rate is negative, if the key is invalid, -- or if a metric with the same key already exists.-newStatTiming :: (MonadIO m) => Stats -> Key -> Int -> m StatTiming+newStatTiming :: Stats -> Key -> Int -> IO StatTiming newStatTiming stats key sampling = do when (sampling < 0) $ throwIO $@@ -231,14 +242,14 @@ -- -- Throws an 'IOError' if the key is invalid or a metric with the same key -- already exists.-newStatSet :: (MonadIO m) => Stats -> Key -> m StatSet+newStatSet :: Stats -> Key -> IO StatSet newStatSet stats key = do newMetric stats (C.pack key) (SetData HashSet.empty) return $ StatSet stats (C.pack key) -- | Add a number to a counter. The aggregated count is reset to zero after each -- flush.-incrementCounter :: (MonadIO m) => StatCounter -> Int -> m ()+incrementCounter :: StatCounter -> Int -> IO () incrementCounter StatCounter {..} = processSample stats sampling key . Counter @@ -247,29 +258,29 @@ -- Note that in the StatsD protocol a negative value is interpreted as a -- decrement, so StatsD servers receiving samples will not set the gauge to a -- negative value.-setGauge :: (MonadIO m) => StatGauge -> Int -> m ()+setGauge :: StatGauge -> Int -> IO () setGauge StatGauge {..} i = processSample stats 1 key (Gauge i False) -- | Add a number to a gauge, which may be negative. The aggregated value never -- goes below zero and saturates at 'maxBound'.-incrementGauge :: (MonadIO m) => StatGauge -> Int -> m ()+incrementGauge :: StatGauge -> Int -> IO () incrementGauge StatGauge {..} i = processSample stats 1 key (Gauge i True) -- | Subtract a number from a gauge. The aggregated value never goes below zero.-decrementGauge :: (MonadIO m) => StatGauge -> Int -> m ()+decrementGauge :: StatGauge -> Int -> IO () decrementGauge x i = incrementGauge x (negate i) -- | Record a timing, normally a duration in milliseconds. The timings collected -- during a flush interval are summarised and then discarded.-addTiming :: (MonadIO m) => StatTiming -> Int -> m ()+addTiming :: StatTiming -> Int -> IO () addTiming StatTiming {..} = processSample stats sampling key . Timing -- | Record that an element was seen in a set. Elements should follow the same -- character rules as keys, or StatsD servers may reject the sample.-newSetElement :: (MonadIO m) => StatSet -> String -> m ()+newSetElement :: StatSet -> String -> IO () newSetElement StatSet {..} = processSample stats 1 key . Set . C.pack @@ -277,7 +288,9 @@ -- -- If 'reportStats' is on, a background thread is started that flushes -- aggregated statistics every 'flushInterval' milliseconds. It is stopped when--- the function returns.+-- the function returns, and it is linked to the calling thread: should it ever+-- fail, the exception is re-thrown there instead of the statistics silently+-- going quiet. -- -- Calls 'error' if the configuration is invalid: if a prefix or the namespace is -- not a valid key, if 'flushInterval' is not positive, or if a percentile is not@@ -287,11 +300,18 @@ -- A scope rather than a global client keeps the background flusher's lifetime -- explicit, and makes it possible to run several independent clients in one -- program, for example in tests.-withStats :: (MonadUnliftIO m) => StatConfig -> (Stats -> m a) -> m a+--+-- The UDP socket is closed when the function returns, however it returns,+-- after the background thread has stopped. Before 0.6.0 it was left open: a+-- program that opened clients again and again, as a test suite does, lost a+-- file descriptor each time. A 'Stats' handle, or a metric made from it, that+-- outlives the scope still counts what it is given and sends nothing: sending+-- on the closed socket fails, and failures to send are ignored.+withStats :: StatConfig -> (Stats -> IO a) -> IO a withStats cfg go = do metrics <- newMetrics- socket <- connectStatsD cfg.statsdServer cfg.statsdPort- let stats = newStats cfg metrics socket- if cfg.reportStats- then withAsync (statsLoop stats) (\a -> link a >> go stats)- else go stats+ bracket (connectStatsD cfg.statsdServer cfg.statsdPort) Net.close $ \socket -> do+ let stats = newStats cfg metrics socket+ if cfg.reportStats+ then withAsync (statsLoop stats) (\a -> link a >> go stats)+ else go stats
src/System/Metrics/StatsD/Internal.hs view
@@ -80,6 +80,17 @@ ) where +import Control.Concurrent (threadDelay)+import Control.Concurrent.STM+ ( STM,+ TVar,+ atomically,+ modifyTVar,+ newTVarIO,+ readTVar,+ stateTVar,+ )+import Control.Exception (IOException, bracketOnError, handle, throwIO) import Control.Monad (MonadPlus (..), forM_, forever, guard, unless, void, when) import Data.Bool (bool) import Data.ByteString (ByteString)@@ -100,17 +111,6 @@ import Network.Socket.ByteString qualified as Net import Text.Printf (printf) import Text.Read (readMaybe)-import UnliftIO (MonadIO, handleIO, liftIO, throwIO)-import UnliftIO.Concurrent (threadDelay)-import UnliftIO.STM- ( STM,- TVar,- atomically,- modifyTVar,- newTVarIO,- readTVar,- stateTVar,- ) -- | Handle to a StatsD client. Create one with -- 'System.Metrics.StatsD.withStats'. It can be shared between threads.@@ -288,7 +288,7 @@ -- | Register a metric. Throws an 'IOError' if the key is invalid or already -- registered.-newMetric :: (MonadIO m) => Stats -> ByteString -> MetricData -> m ()+newMetric :: Stats -> ByteString -> MetricData -> IO () newMetric stats key store = do unless (validateKey key) $ do throwIO $ userError "Metric key is invalid"@@ -345,8 +345,7 @@ -- | Record a reading and, if samples are reported, send it subject to the -- sampling rate.-processSample ::- (MonadIO m) => Stats -> Int -> ByteString -> Value -> m ()+processSample :: Stats -> Int -> ByteString -> Value -> IO () processSample stats sampling key val = do idx <- atomically $ newReading stats key val when stats.params.samples $@@ -354,7 +353,7 @@ Sample key val sampling idx -- | Create an empty set of metrics.-newMetrics :: (MonadIO m) => m (TVar Metrics)+newMetrics :: IO (TVar Metrics) newMetrics = newTVarIO HashMap.empty -- | Validate a configuration and derive its parameters. Calls 'error' if the@@ -403,13 +402,13 @@ } -- | Flush statistics every flush interval, forever.-statsLoop :: (MonadIO m) => Stats -> m ()+statsLoop :: Stats -> IO () statsLoop stats = forever $ do threadDelay (stats.params.flush * 1000) statsFlush stats -- | Send the statistics of all metrics and reset them.-statsFlush :: (MonadIO m) => Stats -> m ()+statsFlush :: Stats -> IO () statsFlush stats = do mapM_ (send stats) =<< atomically@@ -614,7 +613,7 @@ byteString e <> "|s" -- | Send a sample if the sampling rate selects it.-submit :: (MonadIO m) => Stats -> Sample -> m ()+submit :: Stats -> Sample -> IO () submit stats sample = forM_ (toReport stats.params sample) (send stats) @@ -622,19 +621,27 @@ -- -- Errors are ignored on purpose: the alternative, failing the code that recorded -- a metric because the network is down, is never what a program wants.-send :: (MonadIO m) => Stats -> Report -> m ()+--+-- Only 'IOException' is ignored, which is what the network raises. Anything+-- else, and in particular an asynchronous exception such as the one that+-- cancels the calling thread, passes through, so that recording a metric can+-- never make a thread impossible to stop.+send :: Stats -> Report -> IO () send stats report =- liftIO $- handleIO (const (return ())) $- void $- Net.send- stats.socket- (formatReport report <> bool "" "\n" stats.params.newline)+ handle ignore $+ void $+ Net.send+ stats.socket+ (formatReport report <> bool "" "\n" stats.params.newline)+ where+ ignore :: IOException -> IO ()+ ignore _ = return () -- | Resolve a host and port and create a UDP socket connected to it. Calls--- 'error' if the host cannot be resolved.-connectStatsD :: (MonadIO m) => String -> Int -> m Socket-connectStatsD host port = liftIO $ do+-- 'error' if the host cannot be resolved. The caller closes the socket; if+-- connecting it fails, it is closed here.+connectStatsD :: String -> Int -> IO Socket+connectStatsD host port = do as <- Net.getAddrInfo Nothing@@ -643,9 +650,9 @@ a <- case as of a : _ -> return a [] -> error $ "Cannot resolve: " <> host <> ":" <> show port- sock <- Net.socket (Net.addrFamily a) Net.Datagram Net.defaultProtocol- Net.connect sock (Net.addrAddress a)- return sock+ bracketOnError (Net.socket (Net.addrFamily a) Net.Datagram Net.defaultProtocol) Net.close $ \sock -> do+ Net.connect sock (Net.addrAddress a)+ return sock -- | Parse a line in the StatsD protocol. The inverse of 'formatReport'. parseReport :: (MonadPlus m) => ByteString -> m Report
statsd-rupp.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: statsd-rupp-version: 0.5.0.2+version: 0.6.0 synopsis: Simple StatsD Client description: Please see the README on GitHub at <https://github.com/jprupp/statsd-rupp#readme> category: System@@ -34,10 +34,11 @@ src ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints build-depends:- base >=4.7 && <5+ async >=2.2.4 && <3+ , base >=4.7 && <5 , bytestring >=0.11.5.1 && <2 , network >=3.1.4.0 && <4- , unliftio >=0.2.25 && <2+ , stm >=2.5.1.0 && <3 , unordered-containers >=0.2.19.1 && <2 , vector >=0.13.0 && <2 default-language: Haskell2010@@ -52,12 +53,13 @@ ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N build-depends: QuickCheck+ , async >=2.2.4 && <3 , base >=4.7 && <5 , bytestring >=0.11.5.1 && <2 , hspec , network >=3.1.4.0 && <4 , statsd-rupp- , unliftio >=0.2.25 && <2+ , stm >=2.5.1.0 && <3 , unordered-containers >=0.2.19.1 && <2 , vector >=0.13.0 && <2 default-language: Haskell2010
test/Spec.hs view
@@ -5,6 +5,17 @@ {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wno-orphans #-} +import Control.Concurrent.Async (link, withAsync)+import Control.Concurrent.STM+ ( atomically,+ newTQueueIO,+ newTVarIO,+ readTQueue,+ readTVarIO,+ writeTQueue,+ writeTVar,+ )+import Control.Exception (bracket) import Control.Monad import Data.ByteString (ByteString) import Data.ByteString.Char8 qualified as C@@ -17,21 +28,10 @@ import Network.Socket.ByteString import System.Metrics.StatsD import System.Metrics.StatsD.Internal+import System.Timeout (timeout) import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck-import UnliftIO- ( MonadIO (liftIO),- MonadUnliftIO,- atomically,- bracket,- link,- newTQueueIO,- newTVarIO,- readTQueue,- withAsync,- writeTQueue,- ) main :: IO () main = hspec $ do@@ -86,12 +86,53 @@ let ts = makeTimingStats ps V.last (trimPercentile 95 ts).cumsquares `shouldBe` sumsq (percent 95 ps) V.last (trimPercentile 75 ts).cumsquares `shouldBe` sumsq (percent 75 ps)+ describe "client" $ do+ it "sends samples and statistics over UDP" $ do+ withUdpServer $ \(port, receive) -> do+ let cfg = testConfig {statsdServer = "127.0.0.1", statsdPort = port}+ sent = Report "comets" (Counter 7) 1.0+ flushed = Report "stats.counters.comets.count" (Counter 7) 1.0+ -- A flush may come before the increment and report a count of+ -- zero, so wait for the reports wanted instead of the first ones.+ wait [] = return ()+ wait rs = receive >>= \r -> wait (filter ((/= r) . Just) rs)+ withStats cfg $ \stats -> do+ c <- newStatCounter stats "comets" 1+ incrementCounter c 7+ timeout (5 * 1000 * 1000) (wait [sent, flushed])+ `shouldReturn` Just ()+ it "closes its socket when it is done, and sends nothing after" $ do+ withUdpServer $ \(port, _) -> do+ let cfg = testConfig {statsdServer = "127.0.0.1", statsdPort = port}+ (stats, c) <- withStats cfg $ \stats -> do+ c <- newStatCounter stats "comets" 1+ -- open while the function runs+ void (getPeerName stats.socket)+ return (stats, c)+ getPeerName stats.socket `shouldThrow` anyIOException+ -- a metric that outlives the scope is harmless+ incrementCounter c 1 `shouldReturn` ()+ it "closes its socket when the function fails" $ do+ withUdpServer $ \(port, _) -> do+ let cfg = testConfig {statsdServer = "127.0.0.1", statsdPort = port}+ kept <- newTVarIO Nothing+ withStats cfg (\stats -> atomically (writeTVar kept (Just stats)) >> ioError (userError "stop"))+ `shouldThrow` anyIOException+ Just stats <- readTVarIO kept+ getPeerName stats.socket `shouldThrow` anyIOException around (withMockStats testConfig) $ do describe "counter" $ do it "creates two counters" $ \(stats, _) -> do _ <- newStatCounter stats "planets" 1 _ <- newStatCounter stats "moons" 1 return () :: Expectation+ it "refuses an invalid key" $ \(stats, _) ->+ newStatCounter stats "dwarf planets" 1 `shouldThrow` anyIOException+ it "refuses a key that is taken" $ \(stats, _) -> do+ _ <- newStatCounter stats "planets" 1+ newStatGauge stats "planets" 0 `shouldThrow` anyIOException+ it "refuses a negative sampling rate" $ \(stats, _) ->+ newStatCounter stats "planets" (-1) `shouldThrow` anyIOException it "reports on two counters" $ \(stats, report) -> do planets <- newStatCounter stats "planets" 1 moons <- newStatCounter stats "moons" 1@@ -110,8 +151,8 @@ rs <- replicateM 5 report let rs' = [ Report "moons" (Counter x) 0.25- | (i, x) <- zip [(1 :: Int) ..] counts,- i `mod` 4 == 0+ | (i, x) <- zip [(1 :: Int) ..] counts,+ i `mod` 4 == 0 ] rs `shouldMatchList` rs' r <- report@@ -160,8 +201,8 @@ rs <- replicateM 10 report let rs' = [ Report "cats" (Timing x) 0.01- | (i, x) <- zip [(1 :: Int) ..] timings,- i `mod` 100 == 0+ | (i, x) <- zip [(1 :: Int) ..] timings,+ i `mod` 100 == 0 ] rs `shouldMatchList` rs' it "reports stats" $ \(stats, report) -> do@@ -277,11 +318,7 @@ rs <- replicateM (length set + length rs') report rs `shouldEndWith` rs' -withMockStats ::- (MonadUnliftIO m) =>- StatConfig ->- ((Stats, m Report) -> m a) ->- m a+withMockStats :: StatConfig -> ((Stats, IO Report) -> IO a) -> IO a withMockStats cfg go = withMockSockets $ \(s1, s2) -> do q <- newTQueueIO@@ -294,15 +331,24 @@ go (s, atomically (readTQueue q)) where fwd s2 q = forever $ do- bs <- liftIO $ C.lines <$> recv s2 (2 ^ (20 :: Int))+ bs <- C.lines <$> recv s2 (2 ^ (20 :: Int)) let rs = map (fromJust . parseReport) bs mapM_ (atomically . writeTQueue q) rs -withMockSockets :: (MonadUnliftIO m) => ((Socket, Socket) -> m a) -> m a+withMockSockets :: ((Socket, Socket) -> IO a) -> IO a withMockSockets = bracket- (liftIO (socketPair AF_UNIX Stream 0))- (\(s1, s2) -> liftIO (close s1 >> close s2))+ (socketPair AF_UNIX Stream 0)+ (\(s1, s2) -> close s1 >> close s2)++-- | Listen for UDP on a free local port. Passes the port and an action that+-- waits for a packet and parses it as a report.+withUdpServer :: ((Int, IO (Maybe Report)) -> IO a) -> IO a+withUdpServer go =+ bracket (socket AF_INET Datagram defaultProtocol) close $ \sock -> do+ bind sock (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ port <- socketPort sock+ go (fromIntegral port, parseReport <$> recv sock 4096) testConfig :: StatConfig testConfig = defStatConfig {flushInterval = 50}