launchdarkly-server-sdk 4.6.2 → 4.6.3
raw patch · 13 files changed
+334/−29 lines, 13 files
Files
- CHANGELOG.md +11/−0
- launchdarkly-server-sdk.cabal +2/−1
- src/LaunchDarkly/Server/Client/Internal.hs +1/−1
- src/LaunchDarkly/Server/Evaluate.hs +17/−5
- src/LaunchDarkly/Server/Features.hs +24/−11
- src/LaunchDarkly/Server/Network/Eventing.hs +6/−7
- src/LaunchDarkly/Server/Network/Polling.hs +10/−2
- src/LaunchDarkly/Server/Network/Streaming.hs +1/−1
- test/Spec.hs +2/−0
- test/Spec/Client.hs +51/−0
- test/Spec/Features.hs +74/−0
- test/Spec/Polling.hs +110/−0
- test/Spec/Streaming.hs +25/−1
CHANGELOG.md view
@@ -2,6 +2,17 @@ All notable changes to the LaunchDarkly Haskell Server-side SDK will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org). +## [4.6.3](https://github.com/launchdarkly/haskell-server-sdk/compare/4.6.2...4.6.3) (2026-11-20)+++### Bug Fixes++* Accept flag and segment data that omits optional properties or sets them to null ([#134](https://github.com/launchdarkly/haskell-server-sdk/issues/134)) ([73b32f1](https://github.com/launchdarkly/haskell-server-sdk/commit/73b32f15d5f115fb324bb1309ffbe4409859cca2))+* Ignore a stream delete event with an unknown path kind instead of reconnecting ([#135](https://github.com/launchdarkly/haskell-server-sdk/issues/135)) ([07ae248](https://github.com/launchdarkly/haskell-server-sdk/commit/07ae24826472f4bda70bfebc18137e8ed975d5ac))+* Keep polling after a connection reset while reading a poll response ([#137](https://github.com/launchdarkly/haskell-server-sdk/issues/137)) ([013fe8b](https://github.com/launchdarkly/haskell-server-sdk/commit/013fe8be18bef3266744da9d9f8b412c2abad01f))+* Record the default value in analytics events when a typed evaluation has the wrong type ([#131](https://github.com/launchdarkly/haskell-server-sdk/issues/131)) ([6cd202a](https://github.com/launchdarkly/haskell-server-sdk/commit/6cd202a7bc95770046cb37a2b4a003546e238170))+* Stop logging the server time as a warning on every event delivery ([#139](https://github.com/launchdarkly/haskell-server-sdk/issues/139)) ([b3171cd](https://github.com/launchdarkly/haskell-server-sdk/commit/b3171cd76b8828be0ddf67e9e367c644aacd9f61))+ ## [4.6.2](https://github.com/launchdarkly/haskell-server-sdk/compare/4.6.1...4.6.2) (2026-11-16)
launchdarkly-server-sdk.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: launchdarkly-server-sdk-version: 4.6.2+version: 4.6.3 synopsis: Server-side SDK for integrating with LaunchDarkly description: Please see the README on GitHub at <https://github.com/launchdarkly/haskell-server-sdk#readme> category: Web@@ -146,6 +146,7 @@ Spec.Integrations.TestData Spec.Operators Spec.PersistentDataStore+ Spec.Polling Spec.Reference Spec.Segment Spec.Store
src/LaunchDarkly/Server/Client/Internal.hs view
@@ -31,7 +31,7 @@ -- | The version string for this library. clientVersion :: Text-clientVersion = "4.6.2" -- x-release-please-version+clientVersion = "4.6.3" -- x-release-please-version -- | -- Client is the LaunchDarkly client. Client instances are thread-safe.
src/LaunchDarkly/Server/Evaluate.hs view
@@ -56,16 +56,22 @@ if status /= Initialized then pure $ EvaluationDetail fallback Nothing $ EvaluationReasonError EvalErrorClientNotReady else- evaluateInternalClient client key context (wrap fallback) includeReason >>= \(detail, _) ->+ evaluateInternalClient client key context (wrap fallback) includeReason (isJust . convert) >>= \(detail, _) -> pure $ maybe (EvaluationDetail fallback Nothing $ if isError (getField @"reason" detail) then (getField @"reason" detail) else EvaluationReasonError EvalErrorWrongType) (setValue detail) (convert $ getField @"value" detail) -evaluateInternalClient :: Client -> Text -> Context -> Value -> Bool -> IO (EvaluationDetail Value, Maybe [Text])-evaluateInternalClient _ _ (Invalid _) fallback _ = pure $ (errorDefault EvalErrorInvalidContext fallback, Nothing)-evaluateInternalClient client key context fallback includeReason = do+-- | Evaluates a flag and records the analytics events for the evaluation.+--+-- The last argument tells if a value has the type that the caller requested.+-- The check occurs before the SDK makes the event. If the value has the wrong+-- type, the event and the result contain the default value, no variation index,+-- and a WRONG_TYPE reason.+evaluateInternalClient :: Client -> Text -> Context -> Value -> Bool -> (Value -> Bool) -> IO (EvaluationDetail Value, Maybe [Text])+evaluateInternalClient _ _ (Invalid _) fallback _ _ = pure $ (errorDefault EvalErrorInvalidContext fallback, Nothing)+evaluateInternalClient client key context fallback includeReason hasExpectedType = do (detail, unknown, events, prereqs) <- getFlagC (getField @"store" client) key >>= \case Left err -> do@@ -76,7 +82,7 @@ pure (errorDefault EvalErrorFlagNotFound fallback, True, pure event, Nothing) Right (Just flag) -> do (detail, events, prereqs) <- evaluateDetail flag context HS.empty $ getField @"store" client- let detail' = setFallback detail fallback+ let detail' = checkType $ setFallback detail fallback pure ( detail' , False@@ -93,6 +99,12 @@ ) processEvalEvents (getField @"config" client) (getField @"events" client) context includeReason events unknown pure (detail, prereqs)+ where+ -- A result without a variation index already contains the default value.+ checkType detail+ | isJust (getField @"variationIndex" detail) && not (hasExpectedType $ getField @"value" detail) =+ EvaluationDetail fallback Nothing $ EvaluationReasonError EvalErrorWrongType+ | otherwise = detail getOffValue :: Flag -> EvaluationReason -> EvaluationDetail Value getOffValue flag reason = case getField @"offVariation" flag of
src/LaunchDarkly/Server/Features.hs view
@@ -43,7 +43,7 @@ clauses <- o .: "clauses" variation <- o .:? "variation" rollout <- o .:? "rollout"- trackEvents <- o .: "trackEvents"+ trackEvents <- o .:? "trackEvents" .!= False pure Rule { id = fromMaybe "" id@@ -185,14 +185,14 @@ key <- obj .: "key" version <- obj .: "version" on <- obj .: "on"- trackEvents <- obj .: "trackEvents"- trackEventsFallthrough <- obj .: "trackEventsFallthrough"- deleted <- obj .: "deleted"- prerequisites <- obj .: "prerequisites"- salt <- obj .: "salt"- targets <- obj .: "targets"+ trackEvents <- obj .:? "trackEvents" .!= False+ trackEventsFallthrough <- obj .:? "trackEventsFallthrough" .!= False+ deleted <- obj .:? "deleted" .!= False+ prerequisites <- obj .:? "prerequisites" .!= mempty+ salt <- obj .:? "salt" .!= ""+ targets <- obj .:? "targets" .!= mempty contextTargets <- obj .:? "contextTargets" .!= mempty- rules <- obj .: "rules"+ rules <- obj .:? "rules" .!= mempty fallthrough <- obj .: "fallthrough" offVariation <- obj .:? "offVariation" variations <- obj .: "variations"@@ -236,7 +236,7 @@ instance FromJSON SegmentRule where parseJSON = withObject "SegmentRule" $ \o -> do- id <- o .: "id"+ id <- o .:? "id" .!= "" clauses <- o .: "clauses" weight <- o .:? "weight" bucketBy <- o .:? "bucketBy"@@ -254,8 +254,21 @@ , version :: !Natural , deleted :: !Bool }- deriving (Generic, FromJSON, ToJSON, Show, Eq)+ deriving (Generic, ToJSON, Show, Eq) +instance FromJSON Segment where+ parseJSON = withObject "Segment" $ \o -> do+ key <- o .: "key"+ included <- o .:? "included" .!= mempty+ includedContexts <- o .:? "includedContexts" .!= mempty+ excluded <- o .:? "excluded" .!= mempty+ excludedContexts <- o .:? "excludedContexts" .!= mempty+ salt <- o .:? "salt" .!= ""+ rules <- o .:? "rules" .!= mempty+ version <- o .: "version"+ deleted <- o .:? "deleted" .!= False+ pure Segment {..}+ data SegmentTarget = SegmentTarget { values :: !(HashSet Text) , contextKind :: !Text@@ -275,7 +288,7 @@ parseJSON = withObject "Clause" $ \o -> do attr <- o .: "attribute" kind <- o .:? "contextKind"- negate <- o .: "negate"+ negate <- o .:? "negate" .!= False op <- o .: "op" values <- o .: "values"
src/LaunchDarkly/Server/Network/Eventing.hs view
@@ -36,13 +36,12 @@ checkAuthorization response let code = responseStatus response serverTime = getServerTime response- in $(logWarn) (T.append "@@@ server time from LD was determined to be: " $ T.pack $ show serverTime)- >> if code < status400- then pure (True, serverTime)- else- if isHttpUnrecoverable $ statusCode $ code- then $(logWarn) (T.append "got non recoverable event post response dropping payload: " $ T.pack $ show code) >> pure (True, serverTime)- else pure (False, serverTime)+ if code < status400+ then pure (True, serverTime)+ else+ if isHttpUnrecoverable $ statusCode $ code+ then $(logWarn) (T.append "got non recoverable event post response dropping payload: " $ T.pack $ show code) >> pure (True, serverTime)+ else pure (False, serverTime) setEventHeaders :: Request -> Request setEventHeaders request =
src/LaunchDarkly/Server/Network/Polling.hs view
@@ -1,11 +1,13 @@ module LaunchDarkly.Server.Network.Polling (pollingThread) where import Control.Concurrent (threadDelay)+import Control.Exception (SomeAsyncException, SomeException, fromException, tryJust) import Control.Monad.Catch (MonadMask, MonadThrow) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (MonadLogger, logDebug, logError) import Data.Aeson (FromJSON (..), eitherDecode) import Data.Generics.Product (getField)+import Data.Maybe (isJust) import Data.Text (Text) import qualified Data.Text as T import GHC.Generics (Generic)@@ -14,7 +16,7 @@ import LaunchDarkly.AesonCompat (KeyMap) import LaunchDarkly.Server.Features (Flag, Segment)-import LaunchDarkly.Server.Network.Common (checkAuthorization, handleUnauthorized, isHttpUnrecoverable, tryHTTP)+import LaunchDarkly.Server.Network.Common (checkAuthorization, handleUnauthorized, isHttpUnrecoverable) import Data.ByteString.Lazy (ByteString) import GHC.Natural (Natural)@@ -29,9 +31,15 @@ } deriving (Generic, FromJSON, Show) +-- `httpLbs` can throw exceptions that are not an `HttpException`, such as a socket reset while it reads the body.+-- This catches all of them, so that a failed poll does not stop the polling thread.+-- Async exceptions stay uncaught so `close` can stop the thread.+tryPoll :: IO a -> IO (Either SomeException a)+tryPoll = tryJust $ \e -> if isJust (fromException @SomeAsyncException e) then Nothing else Just e+ processPoll :: (MonadIO m, MonadLogger m, MonadMask m, MonadThrow m) => Manager -> DataSourceUpdates -> Request -> m Bool processPoll manager dataSourceUpdates request =- liftIO (tryHTTP $ httpLbs request manager) >>= \case+ liftIO (tryPoll $ httpLbs request manager) >>= \case (Left err) -> do $(logError) (T.pack $ show err) pure True
src/LaunchDarkly/Server/Network/Streaming.hs view
@@ -159,7 +159,7 @@ | T.isPrefixOf "/segments/" path -> logDelete "segment" path (dataSourceUpdatesDeleteSegment dataSourceUpdates (T.drop 10 path) version) | otherwise -> do $(logError) "unknown delete path"- pure False+ pure True Left err -> do $(logError) $ T.append "failed to parse delete" (T.pack err) pure False
test/Spec.hs view
@@ -16,6 +16,7 @@ import qualified Spec.Integrations.TestData import qualified Spec.Operators import qualified Spec.PersistentDataStore+import qualified Spec.Polling import qualified Spec.Reference import qualified Spec.Segment import qualified Spec.Store@@ -41,6 +42,7 @@ , Spec.Segment.allTests , Spec.Store.allTests , Spec.PersistentDataStore.allTests+ , Spec.Polling.allTests , Spec.Streaming.allTests , TestLabel "Integration.FileData" Spec.Integrations.FileData.allTests , TestLabel "Integration.TestData" Spec.Integrations.TestData.allTests
test/Spec/Client.hs view
@@ -1,16 +1,25 @@ module Spec.Client (allTests) where +import Control.Concurrent (killThread)+import Control.Concurrent.MVar (readMVar)+import Control.Monad (forM_)+import Data.Aeson (Value (..)) import Data.Function ((&)) import Data.Generics.Product (getField) import System.Timeout (timeout) import Test.HUnit +import LaunchDarkly.AesonCompat (objectValues, singleton) import LaunchDarkly.Server.Client+import LaunchDarkly.Server.Client.Internal (Status (Initialized), setStatus) import LaunchDarkly.Server.Config import LaunchDarkly.Server.Context+import LaunchDarkly.Server.Events (EventType (..), processSummary)+import LaunchDarkly.Server.Features (Flag (..), VariationOrRollout (..)) import LaunchDarkly.Server.Store.Internal import Data.Text (Text)+import Util.Features (makeTestFlag) makeEmptyStore :: IO (StoreHandle IO) makeEmptyStore = do@@ -34,6 +43,47 @@ result <- timeout (5 * 1000000) $ flushEvents client >> flushEvents client assertEqual "flushEvents returned" (Just ()) result +-- Test that a typed evaluation of the wrong type records the default value in the events.+-- The feature event and the summary counter must not record the value or variation of the flag.+testWrongTypeEventRecordsDefaultValue :: Test+testWrongTypeEventRecordsDefaultValue = TestCase $ do+ let config =+ makeConfig "secret"+ & configSetUseLdd True+ & configSetFlushIntervalSeconds 3600+ & configSetEventsURI "http://127.0.0.1:1"+ flag =+ (makeTestFlag "flag" 5)+ { trackEvents = True+ , variations = [Bool True]+ , fallthrough = VariationOrRollout {variation = Just 0, rollout = Nothing}+ }+ client <- makeClient config+ -- Stop the event thread before the evaluation. The thread flushes the event queue when it starts,+ -- and that flush can remove the events that this test reads.+ forM_ (getField @"eventThreadPair" client) $ \(thread, sync) -> killThread thread >> readMVar sync+ initializeStore (getField @"store" client) (singleton "flag" flag) mempty+ setStatus client Initialized++ detail <- stringVariationDetail client "flag" (makeContext "user-key" "user") "default"+ assertEqual "returned detail" (EvaluationDetail "default" Nothing (EvaluationReasonError EvalErrorWrongType)) detail++ let state = getField @"events" client+ processSummary config state+ events <- readMVar $ getField @"events" state+ case [getField @"event" e | EventTypeFeature e <- events] of+ [feature] -> do+ assertEqual "feature event value" (String "default") (getField @"value" feature)+ assertEqual "feature event variation" Nothing (getField @"variation" feature)+ assertEqual "feature event reason" (Just $ EvaluationReasonError EvalErrorWrongType) (getField @"reason" feature)+ other -> assertFailure $ "expected one feature event, got " ++ show (length other)+ case [counter | EventTypeSummary summary <- events, flagSummary <- objectValues (getField @"features" summary), counter <- objectValues (getField @"counters" flagSummary)] of+ [counter] -> do+ assertEqual "counter value" (String "default") (getField @"value" counter)+ assertEqual "counter variation" Nothing (getField @"variation" counter)+ assertEqual "counter version" (Just 5) (getField @"version" counter)+ other -> assertFailure $ "expected one summary counter, got " ++ show (length other)+ makeTestClient :: Text -> IO Client makeTestClient sdkKey = do client <- makeClient $ (makeConfig sdkKey) & configSetOffline True@@ -45,4 +95,5 @@ TestList [ testSecureModeHashIsGeneratedCorrectly , testFlushEventsDoesNotBlock+ , testWrongTypeEventRecordsDefaultValue ]
test/Spec/Features.hs view
@@ -2,6 +2,7 @@ import Data.Aeson import Data.ByteString.Lazy+import Data.Generics.Product (getField) import Data.Text as T import LaunchDarkly.Server.Features import Test.HUnit@@ -76,9 +77,82 @@ assertBool "Re-encoding sets usingEnvironmentId correctly" ("usingEnvironmentId\": false" `T.isInfixOf` json) Nothing -> assertFailure "Failed to decode into flag" +decodeOrFail :: FromJSON a => ByteString -> IO a+decodeOrFail json = case eitherDecode json of+ Right value -> pure value+ Left err -> assertFailure $ "Failed to decode: " ++ err++testOmittedOrNullFlagPropertiesTakeTheirDefaults :: Test+testOmittedOrNullFlagPropertiesTakeTheirDefaults = TestCase $ do+ withDefaults <-+ decodeOrFail+ "{\"key\":\"flag-key\",\"version\":1,\"on\":true,\"fallthrough\":{\"variation\":0},\"variations\":[true,false],\+ \\"trackEvents\":false,\"trackEventsFallthrough\":false,\"deleted\":false,\"clientSide\":false,\+ \\"prerequisites\":[],\"salt\":\"\",\"targets\":[],\"contextTargets\":[],\"rules\":[]}"+ omitted <-+ decodeOrFail+ "{\"key\":\"flag-key\",\"version\":1,\"on\":true,\"fallthrough\":{\"variation\":0},\"variations\":[true,false]}"+ nulls <-+ decodeOrFail+ "{\"key\":\"flag-key\",\"version\":1,\"on\":true,\"fallthrough\":{\"variation\":0,\"rollout\":null},\"variations\":[true,false],\+ \\"trackEvents\":null,\"trackEventsFallthrough\":null,\"deleted\":null,\"clientSide\":null,\"clientSideAvailability\":null,\+ \\"prerequisites\":null,\"salt\":null,\"targets\":null,\"contextTargets\":null,\"rules\":null,\+ \\"offVariation\":null,\"debugEventsUntilDate\":null}"+ -- A flag without its optional properties, or with them set to null, equals a flag with the default values.+ assertEqual "omitted properties" (withDefaults :: Flag) omitted+ assertEqual "null properties" withDefaults nulls++testOmittedOrNullRuleAndClausePropertiesTakeTheirDefaults :: Test+testOmittedOrNullRuleAndClausePropertiesTakeTheirDefaults = TestCase $ do+ let flagWithRule rule =+ "{\"key\":\"flag-key\",\"version\":1,\"on\":true,\"fallthrough\":{\"variation\":0},\"variations\":[true,false],\"rules\":["+ <> rule+ <> "]}"+ withDefaults <-+ decodeOrFail $+ flagWithRule+ "{\"id\":\"rule-id\",\"variation\":1,\"trackEvents\":false,\+ \\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"],\"negate\":false}]}"+ omitted <-+ decodeOrFail $+ flagWithRule "{\"id\":\"rule-id\",\"variation\":1,\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"]}]}"+ nulls <-+ decodeOrFail $+ flagWithRule+ "{\"id\":\"rule-id\",\"variation\":1,\"rollout\":null,\"trackEvents\":null,\+ \\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"],\"negate\":null,\"contextKind\":null}]}"+ -- A rule or clause without its optional properties, or with them set to null, equals one with the default values.+ assertEqual "omitted properties" (withDefaults :: Flag) omitted+ assertEqual "null properties" withDefaults nulls++testOmittedOrNullSegmentPropertiesTakeTheirDefaults :: Test+testOmittedOrNullSegmentPropertiesTakeTheirDefaults = TestCase $ do+ withDefaults <-+ decodeOrFail+ "{\"key\":\"segment-key\",\"version\":1,\"included\":[],\"includedContexts\":[],\"excluded\":[],\"excludedContexts\":[],\+ \\"salt\":\"\",\"deleted\":false,\+ \\"rules\":[{\"id\":\"\",\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"]}]}]}"+ omitted <-+ decodeOrFail+ "{\"key\":\"segment-key\",\"version\":1,\"rules\":[{\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"]}]}]}"+ nulls <-+ decodeOrFail+ "{\"key\":\"segment-key\",\"version\":1,\"included\":null,\"includedContexts\":null,\"excluded\":null,\"excludedContexts\":null,\+ \\"salt\":null,\"deleted\":null,\+ \\"rules\":[{\"id\":null,\"weight\":null,\"bucketBy\":null,\"rolloutContextKind\":null,\+ \\"clauses\":[{\"attribute\":\"key\",\"op\":\"in\",\"values\":[\"a\"]}]}]}"+ onlyRequired <- decodeOrFail "{\"key\":\"segment-key\",\"version\":1}"+ -- A segment without its optional properties, or with them set to null, equals one with the default values.+ assertEqual "omitted properties" (withDefaults :: Segment) omitted+ assertEqual "null properties" withDefaults nulls+ assertEqual "only required properties" [] (getField @"rules" (onlyRequired :: Segment))+ allTests :: Test allTests = TestList [ testCanDecodeNewSchema , testCanDecodeOldSchema+ , testOmittedOrNullFlagPropertiesTakeTheirDefaults+ , testOmittedOrNullRuleAndClausePropertiesTakeTheirDefaults+ , testOmittedOrNullSegmentPropertiesTakeTheirDefaults ]
+ test/Spec/Polling.hs view
@@ -0,0 +1,110 @@+{-# LANGUAGE NumericUnderscores #-}++module Spec.Polling (allTests) where++import Control.Concurrent (forkIO, killThread, threadDelay)+import Control.Concurrent.MVar (newEmptyMVar, readMVar, tryPutMVar)+import Control.Exception (SomeException, throwIO, toException)+import Control.Monad (forever, void)+import Control.Monad.Logger (LogLevel (..), fromLogStr, runLoggingT)+import Data.Aeson (encode, object, (.=))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as B8+import qualified Data.ByteString.Lazy as L+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import qualified Data.Text as T+import Data.Text.Encoding (decodeUtf8With)+import Data.Text.Encoding.Error (lenientDecode)+import Network.HTTP.Client (Manager, defaultManagerSettings, managerRawConnection, newManager, responseTimeoutNone)+import Network.HTTP.Client.Internal (makeConnection)+import System.Timeout (timeout)+import Test.HUnit++import LaunchDarkly.AesonCompat (KeyMap, objectKeys)+import LaunchDarkly.Server.Config.ClientContext (ClientContext (..))+import LaunchDarkly.Server.Config.HttpConfiguration (HttpConfiguration (..))+import LaunchDarkly.Server.DataSource.Internal (DataSourceUpdates (..))+import LaunchDarkly.Server.Features (Flag)+import LaunchDarkly.Server.Network.Polling (pollingThread)+import Util.Features (makeTestFlag)++allTests :: Test+allTests =+ TestList+ [ TestLabel "polls again after a connection reset during the response body" testPollsAgainAfterBodyReset+ ]++-- | One socket read. 'Fail' throws from inside the read, the way a reset socket does.+data ReadStep = Send ByteString | Fail SomeException++-- | Serves each new connection from the next list of reads. Once the lists run out, opening a connection blocks.+-- Once the reads of a connection run out, reads block.+scriptedManager :: IORef [[ReadStep]] -> IO Manager+scriptedManager pending =+ newManager defaultManagerSettings {managerRawConnection = pure $ \_ _ _ -> openNext}+ where+ openNext =+ pop pending >>= \case+ Nothing -> blockForever+ Just script -> do+ steps <- newIORef script+ makeConnection (readStep steps) (const $ pure ()) (pure ())+ readStep steps =+ pop steps >>= \case+ Nothing -> blockForever+ Just (Send bytes) -> pure bytes+ Just (Fail e) -> throwIO e++pop :: IORef [a] -> IO (Maybe a)+pop ref = atomicModifyIORef' ref $ \case+ [] -> ([], Nothing)+ x : rest -> (rest, Just x)++blockForever :: IO a+blockForever = forever $ threadDelay 1_000_000_000++-- | A poll response with one flag.+pollBody :: ByteString+pollBody = L.toStrict $ encode $ object ["flags" .= object ["flag" .= makeTestFlag "flag" 1], "segments" .= object []]++responseHead :: ByteString+responseHead = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " <> B8.pack (show $ B.length pollBody) <> "\r\n\r\n"++-- The first poll gets half the body and then a socket reset. The second poll gets the full body.+-- The poll interval is 0 s, so the second poll starts as soon as the first one fails.+testPollsAgainAfterBodyReset :: Test+testPollsAgainAfterBodyReset = TestCase $ do+ pending <- newIORef [[Send responseHead, Send (B.take (B.length pollBody `div` 2) pollBody), Fail reset], [Send responseHead, Send pollBody]]+ manager <- scriptedManager pending+ logRef <- newIORef []+ initVar <- newEmptyMVar+ let logTo _ _ level msg = atomicModifyIORef' logRef (\xs -> (xs ++ [(level, decodeUtf8With lenientDecode $ fromLogStr msg)], ()))+ context =+ ClientContext+ { runLogger = (`runLoggingT` logTo)+ , httpConfiguration =+ HttpConfiguration+ { defaultRequestHeaders = []+ , defaultRequestTimeout = responseTimeoutNone+ , tlsManager = manager+ }+ }+ updates =+ DataSourceUpdates+ { dataSourceUpdatesInit = \flags _ -> void (tryPutMVar initVar flags) >> pure (Right ())+ , dataSourceUpdatesInsertFlag = const $ pure (Right ())+ , dataSourceUpdatesInsertSegment = const $ pure (Right ())+ , dataSourceUpdatesDeleteFlag = \_ _ -> pure (Right ())+ , dataSourceUpdatesDeleteSegment = \_ _ -> pure (Right ())+ , dataSourceUpdatesSetStatus = const $ pure ()+ }+ thread <- forkIO $ runLogger context $ pollingThread "http://localhost" 0 context updates+ initialized <- timeout 5_000_000 (readMVar initVar :: IO (KeyMap Flag))+ killThread thread+ logs <- readIORef logRef+ assertEqual "flags from the second poll" (Just ["flag"]) (objectKeys <$> initialized)+ assertBool ("logs the reset, got: " ++ show logs) $+ any (\(level, msg) -> level == LevelError && T.isInfixOf "Connection reset by peer" msg) logs+ where+ reset = toException $ userError "Connection reset by peer"
test/Spec/Streaming.hs view
@@ -13,8 +13,9 @@ import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L+import Data.Generics.Product (getField) import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)-import Data.Maybe (isJust)+import Data.Maybe (fromMaybe, isJust) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With)@@ -52,6 +53,7 @@ , TestLabel "does not retry an unauthorized SDK key" testUnauthorizedDoesNotRetry , TestLabel "logs an invalid stream URI and stops" testLogsInvalidUri , TestLabel "decodes UTF-8 split across reads" testUtf8SplitAcrossReads+ , TestLabel "ignores a delete with an unknown path kind and keeps reading" testIgnoresDeleteWithUnknownPath , TestLabel "backoff stays at the cap after many attempts" testBackoffCeiling , TestLabel "a connection open for 60 s resets the backoff" testRetryAttempt ]@@ -318,6 +320,28 @@ run <- runStream [[responseHead, chunk beforeAccent, chunk (B.take 1 fromAccent), chunk (B.drop 1 fromAccent)]] assertInitialized run assertEqual "connections" 1 (connections run)++-- The patch after the delete must be applied, so the stream must keep reading after the delete.+testIgnoresDeleteWithUnknownPath :: Test+testIgnoresDeleteWithUnknownPath = TestCase $ do+ patched <- newIORef []+ bodyReads <- newIORef [deleteEvent, patchEvent]+ let body = fromMaybe B.empty <$> pop bodyReads+ updates =+ DataSourceUpdates+ { dataSourceUpdatesInit = \_ _ -> pure (Right ())+ , dataSourceUpdatesInsertFlag = \flag -> atomicModifyIORef' patched (\keys -> (keys ++ [getField @"key" flag], Right ()))+ , dataSourceUpdatesInsertSegment = const $ pure (Right ())+ , dataSourceUpdatesDeleteFlag = \_ _ -> pure (Right ())+ , dataSourceUpdatesDeleteSegment = \_ _ -> pure (Right ())+ , dataSourceUpdatesSetStatus = const $ pure ()+ }+ void $ timeout 5_000_000 $ runLoggingT (readStream 1_000_000 body updates) (\_ _ _ _ -> pure ())+ keys <- readIORef patched+ assertEqual "flags patched after the delete" ["flag"] keys+ where+ deleteEvent = "event: delete\ndata: {\"path\":\"/cats/Jack\",\"version\":1}\n\n"+ patchEvent = "event: patch\ndata: " <> L.toStrict (encode $ object ["path" .= ("/flags/flag" :: Text), "data" .= makeTestFlag "flag" 2]) <> "\n\n" testKillThreadStopsStream :: Test testKillThreadStopsStream = TestCase $ do