-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT
{-# LANGUAGE TypeFamilies #-}

{- | Conditional S3 writes, the listing that tells a missing key from a refused read, and a byte
bound on the responses to both.

amazonka's generated @PutObject@ has no @If-Match@ or @If-None-Match@ field, so 'ConditionalPut'
adds the header before signing and the signature covers it. A store that ignores the header would
overwrite unconditionally, so a writer that relies on it needs a store that enforces it.
-}
module Ecluse.Runtime.Aws.S3.Conditional (
    WritePrecondition (..),
    ConditionalPut (..),
    isWriteConflict,
    absenceListing,
    listingProvesAbsence,

    -- * Bounded responses
    Capped (..),
    ResponseTooLarge (..),
    maxCappedResponseBytes,
) where

import Amazonka qualified as AWS
import Amazonka.S3 qualified as S3
import Amazonka.S3.Lens qualified as S3L
import Amazonka.Types qualified as Types
import Conduit ((.|))
import Lens.Micro ((%~), (?~), (^.))
import Network.HTTP.Types (Header)
import UnliftIO.Exception (throwIO)

import Ecluse.Core.Stream (boundBytes)
import Ecluse.Runtime.Aws.Fault (serviceStatus)

-- | What a conditional write requires of the object the key holds.
data WritePrecondition
    = -- | No object holds the key: @If-None-Match: *@.
      IfAbsent
    | -- | The object holds exactly this ETag: @If-Match@.
      IfRevision ByteString
    deriving stock (WritePrecondition -> WritePrecondition -> Bool
(WritePrecondition -> WritePrecondition -> Bool)
-> (WritePrecondition -> WritePrecondition -> Bool)
-> Eq WritePrecondition
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: WritePrecondition -> WritePrecondition -> Bool
== :: WritePrecondition -> WritePrecondition -> Bool
$c/= :: WritePrecondition -> WritePrecondition -> Bool
/= :: WritePrecondition -> WritePrecondition -> Bool
Eq, Int -> WritePrecondition -> ShowS
[WritePrecondition] -> ShowS
WritePrecondition -> String
(Int -> WritePrecondition -> ShowS)
-> (WritePrecondition -> String)
-> ([WritePrecondition] -> ShowS)
-> Show WritePrecondition
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> WritePrecondition -> ShowS
showsPrec :: Int -> WritePrecondition -> ShowS
$cshow :: WritePrecondition -> String
show :: WritePrecondition -> String
$cshowList :: [WritePrecondition] -> ShowS
showList :: [WritePrecondition] -> ShowS
Show)

-- | A @PutObject@ the store applies only while its precondition holds.
data ConditionalPut = ConditionalPut WritePrecondition S3.PutObject

instance AWS.AWSRequest ConditionalPut where
    type AWSResponse ConditionalPut = S3.PutObjectResponse
    request :: (Service -> Service) -> ConditionalPut -> Request ConditionalPut
request Service -> Service
overrides (ConditionalPut WritePrecondition
precondition PutObject
native) =
        Request PutObject -> Request ConditionalPut
forall a b. Coercible a b => a -> b
coerce ((Service -> Service) -> PutObject -> Request PutObject
forall a. AWSRequest a => (Service -> Service) -> a -> Request a
AWS.request Service -> Service
overrides PutObject
native Request PutObject
-> (Request PutObject -> Request PutObject) -> Request PutObject
forall a b. a -> (a -> b) -> b
& ([Header] -> Identity [Header])
-> Request PutObject -> Identity (Request PutObject)
forall a (f :: * -> *).
Functor f =>
([Header] -> f [Header]) -> Request a -> f (Request a)
Types.request_headers (([Header] -> Identity [Header])
 -> Request PutObject -> Identity (Request PutObject))
-> ([Header] -> [Header]) -> Request PutObject -> Request PutObject
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
%~ WritePrecondition -> [Header] -> [Header]
withPrecondition WritePrecondition
precondition)
    response :: forall (m :: * -> *).
MonadResource m =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy ConditionalPut
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse ConditionalPut)))
response ByteStringLazy -> IO ByteStringLazy
decode Service
service Proxy ConditionalPut
_ = (ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy PutObject
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse PutObject)))
forall a (m :: * -> *).
(AWSRequest a, MonadResource m) =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy a
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse a)))
forall (m :: * -> *).
MonadResource m =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy PutObject
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse PutObject)))
AWS.response ByteStringLazy -> IO ByteStringLazy
decode Service
service (Proxy PutObject
forall {k} (t :: k). Proxy t
Proxy :: Proxy S3.PutObject)

-- Any precondition the generated request already carries is replaced, so exactly one is signed.
withPrecondition :: WritePrecondition -> [Header] -> [Header]
withPrecondition :: WritePrecondition -> [Header] -> [Header]
withPrecondition WritePrecondition
precondition [Header]
headers =
    Header
condition Header -> [Header] -> [Header]
forall a. a -> [a] -> [a]
: (Header -> Bool) -> [Header] -> [Header]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(HeaderName
name, ByteString
_) -> HeaderName
name HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
/= HeaderName
"If-Match" Bool -> Bool -> Bool
&& HeaderName
name HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
/= HeaderName
"If-None-Match") [Header]
headers
  where
    condition :: Header
condition = case WritePrecondition
precondition of
        WritePrecondition
IfAbsent -> (HeaderName
"If-None-Match", ByteString
"*")
        IfRevision ByteString
etag -> (HeaderName
"If-Match", ByteString
etag)

-- | Whether the store refused a conditional write because its precondition no longer held.
isWriteConflict :: AWS.Error -> Bool
isWriteConflict :: Error -> Bool
isWriteConflict Error
err = Error -> Maybe Int
serviceStatus Error
err Maybe Int -> [Maybe Int] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [Int -> Maybe Int
forall a. a -> Maybe a
Just Int
409, Int -> Maybe Int
forall a. a -> Maybe a
Just Int
412]

-- | The one-key listing a refused read falls back on, which needs only prefix-scoped @s3:ListBucket@.
absenceListing :: Text -> Text -> S3.ListObjectsV2
absenceListing :: Text -> Text -> ListObjectsV2
absenceListing Text
bucket Text
key =
    BucketName -> ListObjectsV2
S3.newListObjectsV2 (Text -> BucketName
S3.BucketName Text
bucket)
        ListObjectsV2 -> (ListObjectsV2 -> ListObjectsV2) -> ListObjectsV2
forall a b. a -> (a -> b) -> b
& (Maybe Text -> Identity (Maybe Text))
-> ListObjectsV2 -> Identity ListObjectsV2
Lens' ListObjectsV2 (Maybe Text)
S3L.listObjectsV2_prefix
        ((Maybe Text -> Identity (Maybe Text))
 -> ListObjectsV2 -> Identity ListObjectsV2)
-> Text -> ListObjectsV2 -> ListObjectsV2
forall s t a b. ASetter s t a (Maybe b) -> b -> s -> t
?~ Text
key
            ListObjectsV2 -> (ListObjectsV2 -> ListObjectsV2) -> ListObjectsV2
forall a b. a -> (a -> b) -> b
& (Maybe Int -> Identity (Maybe Int))
-> ListObjectsV2 -> Identity ListObjectsV2
Lens' ListObjectsV2 (Maybe Int)
S3L.listObjectsV2_maxKeys
        ((Maybe Int -> Identity (Maybe Int))
 -> ListObjectsV2 -> Identity ListObjectsV2)
-> Int -> ListObjectsV2 -> ListObjectsV2
forall s t a b. ASetter s t a (Maybe b) -> b -> s -> t
?~ Int
1

-- | Only a complete, empty listing proves absence. A truncated or populated one proves nothing.
listingProvesAbsence :: S3.ListObjectsV2Response -> Bool
listingProvesAbsence :: ListObjectsV2Response -> Bool
listingProvesAbsence ListObjectsV2Response
response =
    ListObjectsV2Response
response ListObjectsV2Response
-> Getting (Maybe Bool) ListObjectsV2Response (Maybe Bool)
-> Maybe Bool
forall s a. s -> Getting a s a -> a
^. Getting (Maybe Bool) ListObjectsV2Response (Maybe Bool)
Lens' ListObjectsV2Response (Maybe Bool)
S3L.listObjectsV2Response_isTruncated Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False
        Bool -> Bool -> Bool
&& [Object] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([Object] -> Maybe [Object] -> [Object]
forall a. a -> Maybe a -> a
fromMaybe [] (ListObjectsV2Response
response ListObjectsV2Response
-> Getting (Maybe [Object]) ListObjectsV2Response (Maybe [Object])
-> Maybe [Object]
forall s a. s -> Getting a s a -> a
^. Getting (Maybe [Object]) ListObjectsV2Response (Maybe [Object])
Lens' ListObjectsV2Response (Maybe [Object])
S3L.listObjectsV2Response_contents))

-- | A request whose response body, success or error, is bounded before the generated decoder reads it. A longer one throws 'ResponseTooLarge'.
newtype Capped a = Capped a

instance (AWS.AWSRequest a) => AWS.AWSRequest (Capped a) where
    type AWSResponse (Capped a) = AWS.AWSResponse a
    request :: (Service -> Service) -> Capped a -> Request (Capped a)
request Service -> Service
overrides (Capped a
native) = Request a -> Request (Capped a)
forall a b. Coercible a b => a -> b
coerce ((Service -> Service) -> a -> Request a
forall a. AWSRequest a => (Service -> Service) -> a -> Request a
AWS.request Service -> Service
overrides a
native)
    response :: forall (m :: * -> *).
MonadResource m =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy (Capped a)
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse (Capped a))))
response ByteStringLazy -> IO ByteStringLazy
decode Service
service Proxy (Capped a)
_ = (ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy a
-> ClientResponse ClientBody
-> m (Either Error (Response (AWSResponse a)))
forall a (m :: * -> *).
(AWSRequest a, MonadResource m) =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy a
-> ClientResponse ClientBody
-> m (Either Error (ClientResponse (AWSResponse a)))
forall (m :: * -> *).
MonadResource m =>
(ByteStringLazy -> IO ByteStringLazy)
-> Service
-> Proxy a
-> ClientResponse ClientBody
-> m (Either Error (Response (AWSResponse a)))
AWS.response ByteStringLazy -> IO ByteStringLazy
decode Service
service (Proxy a
forall {k} (t :: k). Proxy t
Proxy :: Proxy a) (ClientResponse ClientBody
 -> m (Either Error (Response (AWSResponse a))))
-> (ClientResponse ClientBody -> ClientResponse ClientBody)
-> ClientResponse ClientBody
-> m (Either Error (Response (AWSResponse a)))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ClientBody -> ClientBody)
-> ClientResponse ClientBody -> ClientResponse ClientBody
forall a b. (a -> b) -> Response a -> Response b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (ClientBody
-> ConduitT ByteString ByteString (ResourceT IO) () -> ClientBody
forall (m :: * -> *) a b c r.
Monad m =>
ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r
.| Int
-> (Int -> ResourceT IO ())
-> ConduitT ByteString ByteString (ResourceT IO) ()
forall (m :: * -> *).
Monad m =>
Int -> (Int -> m ()) -> ConduitT ByteString ByteString m ()
boundBytes Int
maxCappedResponseBytes (ResourceT IO () -> Int -> ResourceT IO ()
forall a b. a -> b -> a
const (ResponseTooLarge -> ResourceT IO ()
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO (Int -> ResponseTooLarge
ResponseTooLarge Int
maxCappedResponseBytes))))

-- | A capped response passed its bound, in bytes.
newtype ResponseTooLarge = ResponseTooLarge Int
    deriving stock (ResponseTooLarge -> ResponseTooLarge -> Bool
(ResponseTooLarge -> ResponseTooLarge -> Bool)
-> (ResponseTooLarge -> ResponseTooLarge -> Bool)
-> Eq ResponseTooLarge
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResponseTooLarge -> ResponseTooLarge -> Bool
== :: ResponseTooLarge -> ResponseTooLarge -> Bool
$c/= :: ResponseTooLarge -> ResponseTooLarge -> Bool
/= :: ResponseTooLarge -> ResponseTooLarge -> Bool
Eq, Int -> ResponseTooLarge -> ShowS
[ResponseTooLarge] -> ShowS
ResponseTooLarge -> String
(Int -> ResponseTooLarge -> ShowS)
-> (ResponseTooLarge -> String)
-> ([ResponseTooLarge] -> ShowS)
-> Show ResponseTooLarge
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ResponseTooLarge -> ShowS
showsPrec :: Int -> ResponseTooLarge -> ShowS
$cshow :: ResponseTooLarge -> String
show :: ResponseTooLarge -> String
$cshowList :: [ResponseTooLarge] -> ShowS
showList :: [ResponseTooLarge] -> ShowS
Show)

instance Exception ResponseTooLarge

-- | 64 KiB: a one-key listing or an S3 error document is a few hundred bytes.
maxCappedResponseBytes :: Int
maxCappedResponseBytes :: Int
maxCappedResponseBytes = Int
64 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1024