packages feed

shibuya-redis-adapter-0.1.0.0: test/Main.hs

module Main (main) where

import Control.Concurrent
import Control.Concurrent.Async (wait, withAsync)
import Control.Exception (bracket, try)
import Control.Monad (unless, void)
import Data.ByteString qualified as BS
import Data.HashMap.Strict qualified as HashMap
import Data.IORef
import Data.Text qualified as T
import Database.Redis qualified as R
import Effectful (IOE, liftIO, runEff)
import Effectful.Exception qualified as E
import Fixture
import OpenTelemetry.Attributes (toAttribute)
import Shibuya
import Shibuya.Adapter.Redis
import Shibuya.Adapter.Redis qualified as ReaderFields (ReaderConfig (telemetry))
import Shibuya.Adapter.Redis.Internal
import Streamly.Data.Stream qualified as Stream
import System.Timeout (timeout)

check :: String -> Bool -> IO ()
check label ok = unless ok (fail label)

main :: IO ()
main = do
  completed <- timeout 15000000 $ withRedis $ \info ->
    bracket (R.connect info) R.disconnect $ \borrowed -> do
      let pools = BorrowCommands info borrowed
      bad <- try @AdapterError (withRedisRuntime pools (defaultRuntimeOptions {pollMillis = 0}) (const (pure ())))
      check "invalid poll limit" (case bad of Left InvalidOptions -> True; _ -> False)
      -- Fail the second PING after acquiring the dedicated read pool.
      let countClients =
            R.runRedis borrowed (R.sendRequest ["CLIENT", "LIST"])
              >>= either (fail . show) (pure . length . BS.split 10)
      before <- countClients
      bracket (R.connect (info {R.connectDatabase = -1})) R.disconnect $ \unusable -> do
        failed <- try @R.ConnectError (withRedisRuntime (BorrowCommands info unusable) defaultRuntimeOptions (const (pure ())))
        check "second pool failed to acquire" (either (const True) (const False) failed)
      after <- countClients
      check "partial acquisition released read connection" (before == after)
      check "reader rejects concurrent handlers" (either (const True) (const False) (validateDeliveryPolicy IndependentReader StrictInOrder (Async 2)))
      withRedisRuntime pools defaultRuntimeOptions roundTrip
      withRedisRuntime pools defaultRuntimeOptions checkTelemetryDefaults
      withRedisRuntime pools defaultRuntimeOptions checkGroupTelemetryDefault
      withRedisRuntime pools defaultRuntimeOptions checkSingleAttachment
      withRedisRuntime pools defaultRuntimeOptions $ \runtime ->
        withAsync (pollStream runtime (R.xreadOpts [("idle", "0-0")] (R.XReadOpts (Just 1200) (Just 1)))) $ \reader -> do
          -- Wait for Redis to confirm that the dedicated connection is blocked.
          let awaitRead = do
                clients <- runCommand runtime (R.sendRequest ["INFO", "clients"])
                unless ("blocked_clients:1" `BS.isInfixOf` clients) (threadDelay 1000 >> awaitRead)
          awaitRead
          stopIntake runtime
          stopIntake runtime
          wait reader >>= check "poll cancelled on shutdown" . (== Nothing)
      R.runRedis borrowed R.ping >>= check "borrowed pool still usable" . (== Right R.Pong)
  check "runner fixture deadline" (completed == Just ())
  putStrLn "PONG; binary delivery, rejection replay, cancelled poll and finalizer drain passed"

roundTrip :: RedisRuntime -> IO ()
roundTrip runtime = do
  let key = "orders"
      identity = SourceIdentity "demo" Nothing key
      pairs = [("item", "a"), ("item", BS.pack [0, 255])]
      expected = RedisEntry identity (EntryId 7 2) pairs
      expectedId = (entryEnvelope expected).messageId
      alternate = RedisEntry (SourceIdentity "dem" Nothing "oorders") (EntryId 7 2) pairs
      reason = InvalidPayload (T.replicate 600 "x")
      owner = LogicalReader "index"
  let headers = [("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"), ("tracestate", "acme=opaque")]
      traced = expected {fields = pairs <> headers}
      convert = decodeEnvelope Right (const Nothing)
  check "default extractor reads both W3C fields" (((.traceContext) <$> convert defaultTraceContext traced) == Right (Just headers))
  check "tracestate by itself does not propagate" (defaultTraceContext (traced {fields = drop 1 headers}) == Nothing)
  check "untraced entries have no context" (((.traceContext) <$> convert defaultTraceContext expected) == Right Nothing)
  check "custom extractor overrides W3C fields" (((.traceContext) <$> convert (const Nothing) traced) == Right Nothing)
  check
    "Redis attributes omit the stream key"
    ((entryEnvelope traced).attributes == HashMap.fromList [("messaging.system", toAttribute ("redis" :: T.Text)), ("messaging.message.id", toAttribute ("7-2" :: T.Text)), ("shibuya.redis.entry_id", toAttribute ("7-2" :: T.Text))])
  check "length-framed message ID" (expectedId /= (entryEnvelope alternate).messageId)
  check "missing generation distinct from empty" (expectedId /= (entryEnvelope (expected {sourceIdentity = identity {generation = Just ""}})).messageId)
  check "reject invalid stream ID" (parseEntryId "18446744073709551616-1" == Nothing)
  check "decoder failure retains identity" (decodeEnvelope (const (Left reason)) (const Nothing) defaultTraceContext expected == Left @DecodeFailure @(Envelope ()) (DecodeFailure expected reason))
  void $ runCommand runtime (R.xadd key "7-2" pairs)
  started <- newEmptyMVar
  intakeClosed <- newEmptyMVar
  finalized <- newEmptyMVar
  firstReply <- newIORef True
  let sourceAction = do
        rows <- liftIO $ pollStream runtime (R.xreadOpts [(key, "0-0")] (readBatchOptions runtime))
        entry <- liftIO $ case rows of
          Just (Just [R.XReadResponse k [R.StreamsRecord rawId fs]])
            | k == key,
              Just i <- parseEntryId rawId ->
                pure (RedisEntry identity i fs)
          _ -> fail "expected one stream record"
        let finish decision = liftIO $ do
              check "runner decision" (decision == AckDeadLetter reason)
              readMVar intakeClosed
              inserted <- runCommand runtime (storeRejection "failures" owner entry reason Nothing)
              loseReply <- atomicModifyIORef' firstReply (\first -> (False, first))
              if loseReply && inserted then fail "fixture hid successful Redis reply" else pure ()
              count <- runCommand runtime (R.hlen "failures")
              check "one logical rejection" (not loseReply && not inserted && count == 1)
              putMVar finalized ()
        pure $ mkIngested (entryEnvelope entry) (AckHandle finish)
      baseAdapter = mkRedisAdapter runtime "redis-fixture" (defaultAdapterTelemetry {traceCorrelation = LinkOnly}) (Stream.fromEffect sourceAction)
      adapter = baseAdapter {shutdown = baseAdapter.shutdown >> liftIO (void (tryPutMVar intakeClosed ()))}
      handler message = liftIO $ do
        check "wire fidelity and stable ID" (message.envelope.payload == expected && message.envelope.messageId == expectedId)
        check "producer time and attempt absent" (message.envelope.enqueuedAt == Nothing && message.envelope.attempt == Nothing)
        putMVar started ()
        pure (AckDeadLetter reason)
  check "configured telemetry" (adapter.telemetry.traceCorrelation == LinkOnly)
  runEff $ runTracingNoop $ do
    result <- runApp defaultAppConfig [(ProcessorId "fixture", mkProcessor adapter handler)]
    app <- either (liftIO . fail . show) pure result
    flip E.finally (stopApp app) $ do
      liftIO $ takeMVar started
      drained <- stopAppGracefully (ShutdownConfig 2 4) app
      liftIO $ check "graceful app drain" drained
  takeMVar finalized

checkTelemetryDefaults :: RedisRuntime -> IO ()
checkTelemetryDefaults runtime = do
  let config = rawReaderConfig "reader" "index" (SourceIdentity "test" Nothing "defaults") Earliest
  check "reader defaults to linked roots" (config.telemetry.traceCorrelation == LinkOnly)
  reader <- newReader @'[Tracing, IOE] runtime (config {ReaderFields.telemetry = defaultAdapterTelemetry})
  check "reader applies telemetry override" (reader.readerAdapter.telemetry.traceCorrelation == ParentAndLink)

checkGroupTelemetryDefault :: RedisRuntime -> IO ()
checkGroupTelemetryDefault runtime = do
  let config = rawGroupConfig "worker" (SourceIdentity "test" Nothing "defaults") "jobs" "solo" (CreateIfAbsent (EntryId 0 0))
  worker <- newGroupWorker @'[Tracing, IOE] runtime config
  check "group defaults to parent and link" (worker.groupAdapter.telemetry.traceCorrelation == ParentAndLink)

checkSingleAttachment :: RedisRuntime -> IO ()
checkSingleAttachment runtime = do
  let source = SourceIdentity "test" Nothing "attach-once"
      readerConfig = rawReaderConfig "reader" "index" source Earliest
      groupConfig = rawGroupConfig "worker" source "missing" "solo" AttachExisting
      newProjection = void (newReader @'[Tracing, IOE] runtime readerConfig)
      newWorker = void (newGroupWorker @'[Tracing, IOE] runtime groupConfig)
      assertAttached label action = do
        result <- try @AdapterError action
        check label (case result of Left RuntimeAlreadyAttached -> True; _ -> False)
  missing <- try @GroupError newWorker
  check "failed group initialization is reported" (case missing of Left GroupUnavailable -> True; _ -> False)
  newProjection
  assertAttached "runtime rejects a second independent reader" newProjection
  assertAttached "runtime rejects a group worker after a reader" newWorker