packages feed

unkai-0.1.0.1: test/Test/Unkai/Streaming.hs

module Test.Unkai.Streaming (streamingTests) where

import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)
import Control.Exception (AsyncException (ThreadKilled), Exception, bracket, fromException, throwIO, try)
import Control.Lens ((&), (?~), (^.))
import Control.Monad (void, zipWithM_)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Resource (ResourceT)
import Data.Aeson (eitherDecodeStrict)
import Data.ByteString qualified as BS
import Data.ByteString.Builder (byteString)
import Data.ByteString.Char8 qualified as BS8
import Data.ByteString.Lazy qualified as LBS
import Data.Generics.Labels ()
import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Client.Internal qualified as HTTPInternal
import Network.HTTP.Types (hContentLength, hContentType, methodPost, status200, status204, status500)
import Network.Wai qualified as Wai
import Streamly.Data.Stream qualified as Stream
import System.FilePath ((</>))
import System.Timeout (timeout)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))
import Test.Unkai.MockServer
import Unkai (Credentials (FromTokenFile), Env, Stream, download, newEnvWith, runResourceT, send, sinkLBS, sourceBody, upload)
import Unkai.Storage qualified as Storage

streamingTests :: TestTree
streamingTests =
  testGroup
    "scoped streaming"
    [ testCase "generated GET yields the prefix before the server writes the suffix" $ bounded delayedDownload,
      testCase "an empty download releases at EOF" $ bounded emptyDownload,
      testCase "a short read closes the unfinished response at scope exit" $
        bounded $
          withUnfinishedBody runResourceT,
      testCase "a consumer exception closes the unfinished response" $
        bounded $
          withUnfinishedBody $ \readBody -> do
            result <- try @ConsumerFailure @() (runResourceT (readBody >> liftIO (throwIO ConsumerFailure)))
            result @?= Left ConsumerFailure,
      testCase "cancellation closes the unfinished response" $ bounded cancelledDownload,
      testCase "a JSON response decodes object metadata" $ bounded decodedBody,
      testCase "a unit response drains its body reader through EOF" $ bounded discardedBody,
      testCase "multipart sends empty and reusable file bodies with their exact lengths" $ bounded multipartFiles
    ]

bounded :: Assertion -> Assertion
bounded action =
  timeout 10000000 action >>= \case
    Just () -> pure ()
    Nothing -> assertFailure "timed out waiting for the streaming response or its cleanup"

type StorageEnv = Env '[Storage.Devstorage'ReadWrite]

objectRequest :: Storage.StorageObjectsGet
objectRequest = Storage.newStorageObjectsGet "bucket" "reports/q1.csv"

prefix :: BS.ByteString
prefix = "first bytes"

consumePrefix :: Stream -> ResourceT IO Stream
consumePrefix = go prefix
  where
    go remaining stream
      | BS.null remaining = pure stream
      | otherwise =
          Stream.uncons stream >>= \case
            Nothing -> liftIO (assertFailure "body ended before the prefix")
            Just (chunk, rest) ->
              case BS.stripPrefix chunk remaining of
                Nothing -> liftIO (assertFailure ("unexpected prefix chunk: " <> show chunk))
                Just remaining' -> go remaining' rest

withStorageServer ::
  HTTP.ManagerSettings ->
  Wai.Response ->
  (StorageEnv -> IO [RecordedRequest] -> IO a) ->
  IO a
withStorageServer settings response run = withTokenFile $ \file ->
  withServerSettings settings (const (pure response)) $ \manager requests -> do
    env <- newEnvWith (FromTokenFile file) (\_ _ -> pure ()) manager
    run env requests

withCloseCount ::
  Wai.Response ->
  (StorageEnv -> IO [RecordedRequest] -> IO Int -> IO a) ->
  IO a
withCloseCount response run = do
  closed <- newIORef 0
  -- Count the adapter's release action independently of HTTP connection pooling.
  let instrument rs =
        pure rs {HTTPInternal.responseClose' = HTTPInternal.ResponseClose close}
        where
          close = modifyIORef' closed (+ 1) >> HTTP.responseClose rs
      settings = HTTP.defaultManagerSettings {HTTP.managerModifyResponse = instrument}
  withStorageServer settings response $ \env requests -> run env requests (readIORef closed)

delayedDownload :: Assertion
delayedDownload = do
  sendSuffix <- newEmptyMVar
  let suffix = "last bytes"
      response = Wai.responseStream status200 [] $ \write flush -> do
        write (byteString prefix)
        flush
        takeMVar sendSuffix
        write (byteString suffix)
  withCloseCount response $ \env requests closed -> do
    runResourceT $ do
      stream <- download env objectRequest
      rest <- consumePrefix stream
      liftIO $ do
        map path <$> requests >>= (@?= ["/storage/v1/b/bucket/o/reports%2Fq1.csv"])
        closed >>= (@?= 0)
        putMVar sendSuffix ()
      sinkLBS rest >>= liftIO . (@?= LBS.fromStrict suffix)
      liftIO (closed >>= (@?= 1))
    closed >>= (@?= 1)

emptyDownload :: Assertion
emptyDownload = withCloseCount (Wai.responseLBS status200 [] "") $ \env _ closed -> do
  runResourceT $ do
    download env objectRequest >>= sinkLBS >>= liftIO . (@?= "")
    liftIO (closed >>= (@?= 1))
  closed >>= (@?= 1)

withUnfinishedBody :: (ResourceT IO () -> Assertion) -> Assertion
withUnfinishedBody run = do
  disconnected <- newEmptyMVar
  let response = Wai.responseRaw raw (jsonResponse status500 "")
      raw receive write = do
        write ("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n" <> prefix)
        receive >>= putMVar disconnected
  withCloseCount response $ \env _ closed -> do
    let readBody = do
          _ <- download env objectRequest >>= consumePrefix
          liftIO (closed >>= (@?= 0))
    run readBody
    closed >>= (@?= 1)
    takeMVar disconnected >>= (@?= BS.empty)

data ConsumerFailure = ConsumerFailure
  deriving stock (Eq, Show)

instance Exception ConsumerFailure

cancelledDownload :: Assertion
cancelledDownload = withUnfinishedBody $ \readBody -> do
  ready <- newEmptyMVar
  block <- newEmptyMVar
  finished <- newEmptyMVar
  let consume = runResourceT $ do
        readBody
        liftIO (putMVar ready () >> takeMVar block)
  bracket (forkFinally consume (putMVar finished)) killThread $ \consumer -> do
    takeMVar ready
    killThread consumer
    takeMVar finished >>= \case
      Left cause -> fromException cause @?= Just ThreadKilled
      Right () -> assertFailure "expected cancellation to escape"

decodedBody :: Assertion
decodedBody = withStorageServer HTTP.defaultManagerSettings response $ \env _ -> do
  metadata <- runResourceT (send env objectRequest)
  (metadata ^. #name) @?= Just "reports/q1.csv"
  where
    response = jsonResponse status200 "{\"name\":\"reports/q1.csv\"}"

discardedBody :: Assertion
discardedBody = do
  calls <- newIORef (0 :: Int)
  -- A real 204 has no body. Supply chunks at the HTTP reader boundary to test
  -- that the generated unit-response decoder drains rather than returning early.
  let reader = do
        n <- readIORef calls
        writeIORef calls (n + 1)
        pure $ case n of
          0 -> "first"
          1 -> "second"
          _ -> ""
      instrument rs = pure rs {HTTPInternal.responseBody = reader}
      settings = HTTP.defaultManagerSettings {HTTP.managerModifyResponse = instrument}
  withStorageServer settings (Wai.responseLBS status204 [] "") $ \env _ -> do
    runResourceT (send env (Storage.newStorageObjectsDelete "bucket" "unused"))
    readIORef calls >>= (@?= 3)

multipartFiles :: Assertion
multipartFiles = withDirectory $ \dir ->
  withStorageServer HTTP.defaultManagerSettings (jsonResponse status200 "{}") $ \env requests -> do
    let empty = dir </> "empty.bin"
        nonempty = dir </> "sample.bin"
        bytes = BS.pack [0, 13, 10, 128, 255] <> BS.replicate 70000 42
        metadata = Storage.newObject & #name ?~ "reports/q1.csv"
        request = Storage.newStorageObjectsInsert "bucket" metadata
    BS.writeFile empty BS.empty
    BS.writeFile nonempty bytes
    emptyBody <- sourceBody empty
    fileBody <- sourceBody nonempty
    runResourceT $ do
      void (upload env request emptyBody)
      void (upload env request fileBody)
      void (upload env request fileBody)
    captured <- requests
    length captured @?= 3
    zipWithM_ (checkMultipart metadata) [BS.empty, bytes, bytes] captured

checkMultipart :: Storage.Object -> BS.ByteString -> RecordedRequest -> Assertion
checkMultipart metadata bytes captured = do
  method captured @?= methodPost
  path captured @?= "/upload/storage/v1/b/bucket/o"
  filter ((== "uploadType") . fst) (query captured) @?= [("uploadType", Just "multipart")]
  lookup hContentLength (headers captured) @?= Just (BS8.pack (show (LBS.length (body captured))))
  case lookup hContentType (headers captured) >>= BS.stripPrefix "multipart/related; boundary=" of
    Just boundary | not (BS.null boundary) -> do
      let marker = "--" <> boundary
          wire = LBS.toStrict (body captured)
          (metadataPart, mediaPart) = BS.breakSubstring ("\r\n" <> marker <> "\r\n") wire
      case BS.stripPrefix (marker <> "\r\nContent-Type: ") metadataPart of
        Nothing -> assertFailure "missing JSON metadata part"
        Just payload -> do
          let (contentType, framedJSON) = BS.breakSubstring "\r\n\r\n" payload
          BS8.takeWhile (/= ';') contentType @?= "application/json"
          eitherDecodeStrict (BS.drop 4 framedJSON) @?= Right metadata
      mediaPart
        @?= "\r\n"
          <> marker
          <> "\r\nContent-Type: application/octet-stream\r\n\r\n"
          <> bytes
          <> "\r\n"
          <> marker
          <> "--\r\n"
    contentType -> assertFailure ("invalid multipart boundary: " <> show contentType)