module Hasql.Comms.Recv ( Recv, singleResult, allResults, toHandler, Error (..), )whereimport Data.ByteString qualified as ByteStringimport Hasql.Comms.ResultDecoder qualified as ResultDecoderimport Hasql.Platform.Preludeimport Pqi qualified as Pq-- | An action that receives and decodes results from a connection.---- The @tag@ type parameter is a value attached at construction,-- which the error carries if receiving or decoding fails.newtype Recv tag a = Recv (Pq.Connection -> IO (Either (Error tag) a)) deriving stock (Functor)instance Applicative (Recv tag) where {-# INLINE pure #-} pure x = Recv \_ -> pure (Right x) {-# INLINE (<*>) #-} Recv recv1 <*> Recv recv2 = Recv \cs -> do ef <- recv1 cs eg <- recv2 cs pure case (ef, eg) of -- A lost connection explains every other error in the same round -- trip: whatever else failed, it failed because the connection died. -- It must not be hidden behind an earlier statement's ordinary error. (Left e@ConnectionLostError {}, _) -> Left e -- In the pipeline mode the server's last words, e.g. a FATAL with -- 57P01, can arrive as an earlier result error while the connection -- still looks fine, and only a later receive finds it bad. That -- diagnostic is first in operation order, so it wins. (Left earlier, Left lost@ConnectionLostError {}) -> Left (absorbDiagnostic earlier lost) (_, Left e@ConnectionLostError {}) -> Left e _ -> ef <*> eginstance Bifunctor Recv where {-# INLINE bimap #-} bimap f g (Recv recv) = Recv (fmap (bimap (fmap f) g) . recv)toHandler :: Recv tag a -> Pq.Connection -> IO (Either (Error tag) a)toHandler (Recv recv) = recv-- | Exactly one result.---- After the results have been consumed the connection status is checked.-- If the connection is bad, the outcome is 'ConnectionLostError' regardless-- of what the results contained. See 'ConnectionLostError' for the reason.singleResult :: tag -> ResultDecoder.ResultDecoder a -> Recv tag asingleResult tag handler = Recv \connection -> do firstResult <- Pq.getResult connection -- Only look for a second result when there was a first one: -- in the pipeline mode a 'Nothing' separates the results of consecutive -- queries, so asking again would consume the next query's result. secondResult <- case firstResult of Nothing -> pure Nothing Just _ -> Pq.getResult connection connectionStatus <- Pq.status connection case connectionStatus of Pq.ConnectionBad -> connectionLostError tag connection (catMaybes [firstResult, secondResult]) _ -> case (firstResult, secondResult) of (Nothing, _) -> do errorMessage <- Pq.errorMessage connection pure (Left (NoResultsError tag errorMessage)) (Just _, Just _) -> do -- Unreachable today: 'singleResult' backs 'queryParams' and -- 'queryPrepared', which go through the extended protocol where -- Postgres rejects multi-statement SQL outright. Draining anyway -- keeps this branch correct on its own terms rather than relying on -- that non-local argument to hold forever. drainRemaining connection pure (Left (TooManyResultsError tag 1)) (Just result, Nothing) -> do decoded <- ResultDecoder.toHandler handler result pure (first (ResultError tag 0) decoded) where drainRemaining connection = Pq.getResult connection >>= \case Nothing -> pure () Just _ -> drainRemaining connection-- | Consume all results from a multi-statement query (e.g., scripts).-- Each result is decoded using the provided handler.-- This is useful for scripts that may contain multiple statements,-- where each statement produces a result that needs to be validated.-- All results are consumed even if an error occurs, to leave the connection-- in a clean state.---- The first error is the one reported: it is the cause, and whatever fails-- after it is a consequence. The server stops a script at its first error,-- so a later one can only come from the driver itself, e.g. the result it-- makes up when the connection is lost.---- Like 'singleResult', a bad connection status after the results have been-- consumed makes the outcome 'ConnectionLostError' regardless of what the-- results contained.allResults :: tag -> ResultDecoder.ResultDecoder a -> Recv tag ()allResults tag handler = Recv \connection -> do let loop resultIndex maybeError maybeDiagnostic maybeDetails = do result <- Pq.getResult connection case result of Nothing -> pure (maybeError, maybeDiagnostic, maybeDetails) Just result -> do decodedResult <- ResultDecoder.toHandler handler result case decodedResult of Left err -> do -- Continue consuming results even after error to clean up connection diagnostic <- ResultDecoder.serverDiagnostic result details <- Pq.resultErrorMessage result loop (resultIndex + 1) (maybeError <|> Just (ResultError tag resultIndex err)) (maybeDiagnostic <|> diagnostic) (maybeDetails <|> (details >>= nonEmpty)) Right _ -> loop (resultIndex + 1) maybeError maybeDiagnostic maybeDetails (maybeError, maybeDiagnostic, maybeDetails) <- loop 0 Nothing Nothing Nothing connectionStatus <- Pq.status connection case connectionStatus of Pq.ConnectionBad -> do details <- lostConnectionDetails connection maybeDetails pure (Left (ConnectionLostError tag maybeDiagnostic details)) _ -> pure (maybe (Right ()) Left maybeError)-- | The outcome when the connection is found bad after its results have-- been consumed: 'ConnectionLostError' carrying the first genuine server-- diagnostic among the results, if any, and the most useful local details.connectionLostError :: tag -> Pq.Connection -> [Pq.Result] -> IO (Either (Error tag) a)connectionLostError tag connection results = do diagnostics <- traverse ResultDecoder.serverDiagnostic results messages <- traverse Pq.resultErrorMessage results details <- lostConnectionDetails connection (listToMaybe (catMaybes (fmap (>>= nonEmpty) messages))) pure (Left (ConnectionLostError tag (listToMaybe (catMaybes diagnostics)) details))-- | The local details of a lost connection: the first non-empty error-- message among its results, or else the connection's own error message.lostConnectionDetails :: Pq.Connection -> Maybe ByteString -> IO (Maybe ByteString)lostConnectionDetails connection resultDetails = case resultDetails of Just details -> pure (Just details) Nothing -> Pq.errorMessage connectionnonEmpty :: ByteString -> Maybe ByteStringnonEmpty bytes = if ByteString.null bytes then Nothing else Just bytes-- | Retain the earlier error's server diagnostic, if it carries a genuine-- one, in place of the one the loss itself produced: it comes first in-- operation order.absorbDiagnostic :: Error tag -> Error tag -> Error tagabsorbDiagnostic earlier (ConnectionLostError tag diagnostic details) = ConnectionLostError tag (earlierDiagnostic <|> diagnostic) details where earlierDiagnostic = case earlier of ResultError _ _ resultError@(ResultDecoder.ServerError code _ _ _ _) | not (ByteString.null code) -> Just resultError _ -> NothingabsorbDiagnostic _ lost = lost-- * Errors-- | Error of receiving results, carrying the tag of the action that caused it.data Error tag = ResultError tag -- | Offset of the result in the series. Int -- | Underlying error. ResultDecoder.Error | NoResultsError tag -- | Details about the error. Possibly empty. (Maybe ByteString) | TooManyResultsError tag -- | Expected count. Int | -- | The connection was bad by the time the results had been consumed. -- -- Decided by the connection status alone, not by the content of the results. -- That is the only reliable signal, because what the driver reports about a -- dead connection varies: -- -- * When the socket closes silently, the driver makes up a fatal result with -- no SQLSTATE, indistinguishable from a server error by its shape. -- * When the server announces its termination (@57P01@, @57P02@), the genuine -- fatal result comes first and the connection is only marked bad when the -- EOF that follows it is read, i.e. after that result has been returned. -- -- Takes precedence over every other error in the same receive. See -- [#341](https://github.com/nikita-volkov/hasql/issues/341). ConnectionLostError tag -- | The first genuine server diagnostic among the results, if any: a -- result error carrying a nonempty SQLSTATE. Locally manufactured -- results never qualify - see 'ResultDecoder.serverDiagnostic'. (Maybe ResultDecoder.Error) -- | Local details about the loss: the first non-empty error message -- among the results, or the connection's error message. (Maybe ByteString) deriving stock (Show, Eq, Functor)instance Comonad Error where {-# INLINE extract #-} extract = \case ResultError tag _ _ -> tag NoResultsError tag _ -> tag TooManyResultsError tag _ -> tag ConnectionLostError tag _ _ -> tag {-# INLINE duplicate #-} duplicate e = case e of ResultError _ resultIndex resultError -> ResultError e resultIndex resultError NoResultsError _ details -> NoResultsError e details TooManyResultsError _ expectedCount -> TooManyResultsError e expectedCount ConnectionLostError _ diagnostic details -> ConnectionLostError e diagnostic details