packages feed

hasql 2.1.0.0 → 2.2.0.0

raw patch · API changes only · 13 files changed · show whitespace changes · browse hasql-2.2.0.0

+939/−141 lines, 13 filesdep +networkdep ~pqi-nativePVP ok

Dependencies added: network

Dependency ranges changed: pqi-native

API changes (from Hackage documentation)

0 removed, 4 added, 1 changed

version bump matches the API change (PVP)

+ Hasql.Errors: LocalConnectionError :: Text -> ConnectionError
+ Hasql.Errors: ServerConnectionError :: ServerError -> ConnectionError
+ Hasql.Errors: data ConnectionError
+ Hasql.Errors: instance Hasql.Errors.IsError Hasql.Engine.Errors.ConnectionError
- Hasql.Errors: ConnectionUseError :: Text -> UseError
+ Hasql.Errors: ConnectionUseError :: ConnectionError -> UseError

Files

CHANGELOG.md view
@@ -1,3 +1,22 @@+# v2.2.0.0++## Breaking++- `ConnectionUseError` now carries a structured `ConnectionError` instead of a plain `Text`:++  - `LocalConnectionError` - the driver observed the connection's death locally: a dropped socket, a bare EOF, a request `libpq` refused to send. Carries human-readable details; `toSqlState` reports `Nothing`.+  - `ServerConnectionError` - the server announced the failure with a genuine error report before the connection died (e.g. a `FATAL` with SQLSTATE `57P01` in response to `pg_terminate_backend`). Carries the full `ServerError`; `toSqlState` delegates to it.++  Both constructors mean the same thing operationally - the connection is gone and the handle is spent - so the split carries no retryability or catchability verdict; it exists so that a SQLSTATE the server actually reported survives into `toSqlState` instead of being flattened into prose.++  Pattern matches, constructions and `Session.onLibpqConnection` callbacks that build the error themselves need updating. Part of the fix for [#341](https://github.com/nikita-volkov/hasql/issues/341).++## Fixes++- A connection lost before or during a receive is now reported as `ConnectionUseError` across every operation shape: statements (unprepared, prepared, cached), pipelines, scripts and the type-info lookup behind named types. It used to surface as a catchable `SessionUseError` whenever the driver returned an error result for the loss, which made connection pools keep handing out the dead connection. When the server announced the termination with a genuine diagnostic (`57P01` from `pg_terminate_backend`), that diagnostic is preserved as `ServerConnectionError` and `toSqlState` returns its code; silent closes and notice-only announcements (AWS Aurora's crash-shutdown `57P02`) are `LocalConnectionError` with `toSqlState = Nothing`. A use that decoded results successfully but ends with the connection gone is still conservatively reported as `ConnectionUseError`, with the results discarded. Fixes [#341](https://github.com/nikita-volkov/hasql/issues/341).++  Applications using the `pqi-native` adapter need `pqi-native >= 1.0.1.14`, which is the first release that reports connection loss through libpq-shaped results and connection status instead of an internal exception.+ # v2.1.0.0  ## Breaking
README.md view
@@ -111,10 +111,12 @@   -- The session failed, the connection is still live and reusable.   Left (Errors.SessionUseError err) -> ...   -- The connection is gone. Hasql has already closed it.-  Left (Errors.ConnectionUseError reason) -> ...+  Left (Errors.ConnectionUseError err) -> ... ```  A `ConnectionUseError` means the handle is spent. Hasql finished the connection before returning, so every later `use` on it reports the same error and `release` is a no-op. Pools must discard it rather than return it. A `SessionUseError` carries a `SessionError` and leaves the connection untouched.++The `ConnectionError` payload of a `ConnectionUseError` says where the diagnostic came from. A `ServerConnectionError` carries the full `ServerError` the server announced before dying - a `FATAL` with SQLSTATE `57P01` in response to `pg_terminate_backend`, say - and `toSqlState` reports its code. A `LocalConnectionError` means the driver observed the death itself, with no server diagnostic to report: a dropped socket, a bare EOF, a refused send. Both mean the same thing operationally; the split carries no retryability verdict.  All three types implement `IsError`, which renders a message and details for logging and exposes the server's SQLSTATE through `toSqlState` where one was reported. 
hasql.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: hasql-version: 2.1.0.0+version: 2.2.0.0 category: Hasql, Database, PostgreSQL synopsis: Fast PostgreSQL driver with a flexible mapping API description:@@ -265,7 +265,7 @@     criterion >=1.6 && <2,     hasql,     pqi-ffi ^>=1.0,-    pqi-native ^>=1.0.1.0,+    pqi-native ^>=1.0.1.14,     rerebase <2,  test-suite profiling@@ -328,6 +328,7 @@     Helpers.Statements.TooManyParams     Helpers.Statements.WrongDecoder     Integration.Isolated.Connection.AcquireSpec+    Integration.Isolated.Connection.Use.LostConnectionSpec     Integration.Sharing.Connection.Use.InterruptionSpec     Integration.Sharing.Connection.UseSpec     Integration.Sharing.Decoders.CitextSpec@@ -380,9 +381,10 @@     hasql,     hspec ^>=2.11.12,     iproute,+    network >=3.2 && <3.3,     pqi >=1.0 && <1.2,     pqi-ffi ^>=1.0,-    pqi-native ^>=1.0.1.0,+    pqi-native ^>=1.0.1.14,     QuickCheck,     quickcheck-instances >=0.3.11 && <0.4,     random >=1.3 && <1.4,
src/comms/Hasql/Comms/Recv.hs view
@@ -7,6 +7,7 @@   ) where +import Data.ByteString qualified as ByteString import Hasql.Comms.ResultDecoder qualified as ResultDecoder import Hasql.Platform.Prelude import Pqi qualified as Pq@@ -27,7 +28,19 @@     Recv \cs -> do       ef <- recv1 cs       eg <- recv2 cs-      pure (ef <*> eg)+      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 <*> eg  instance Bifunctor Recv where   {-# INLINE bimap #-}@@ -37,27 +50,28 @@ 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 a-singleResult tag handler = Recv \connection -> runExceptT do-  result <- ExceptT do-    result <- Pq.getResult connection-    case result of-      Nothing -> do-        errorMessage <- Pq.errorMessage connection-        status <- Pq.status connection-        pure (Left (NoResultsError tag (status == Pq.ConnectionBad) errorMessage))-      Just result -> pure (Right result)-  ExceptT do-    result <- Pq.getResult connection-    case result of-      Nothing -> do-        status <- Pq.status connection-        if status == Pq.ConnectionBad-          then do+singleResult 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 True errorMessage))-          else pure (Right result)-      Just _ -> do+        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@@ -65,10 +79,9 @@         -- that non-local argument to hold forever.         drainRemaining connection         pure (Left (TooManyResultsError tag 1))-  result <- ExceptT do-    result <- ResultDecoder.toHandler handler result-    pure (first (ResultError tag 0) result)-  pure result+      (Just result, Nothing) -> do+        decoded <- ResultDecoder.toHandler handler result+        pure (first (ResultError tag 0) decoded)   where     drainRemaining connection =       Pq.getResult connection >>= \case@@ -81,29 +94,83 @@ -- 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 = do+  let loop resultIndex maybeError maybeDiagnostic maybeDetails = do         result <- Pq.getResult connection         case result of-          Nothing -> do-            status <- Pq.status connection-            if status == Pq.ConnectionBad-              then do-                errorMessage <- Pq.errorMessage connection-                pure (Just (NoResultsError tag True errorMessage))-              else pure maybeError+          Nothing -> pure (maybeError, maybeDiagnostic, maybeDetails)           Just result -> do             decodedResult <- ResultDecoder.toHandler handler result             case decodedResult of-              Left err ->+              Left err -> do                 -- Continue consuming results even after error to clean up connection-                loop (resultIndex + 1) (Just (ResultError tag resultIndex err))+                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-  errorOrUnit <- loop 0 Nothing-  pure (maybe (Right ()) Left errorOrUnit)+                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 connection++nonEmpty :: ByteString -> Maybe ByteString+nonEmpty 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 tag+absorbDiagnostic 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+      _ -> Nothing+absorbDiagnostic _ lost = lost+ -- * Errors  -- | Error of receiving results, carrying the tag of the action that caused it.@@ -116,35 +183,48 @@       ResultDecoder.Error   | NoResultsError       tag-      -- | Whether @PQstatus@ reported the connection as bad when the results-      -- failed to arrive.-      ---      -- 'True' means the socket is gone: the results are not late, they are-      -- never coming, and the connection has to be replaced. 'False' means-      -- the connection is intact and the server genuinely produced nothing-      -- where a result was expected.-      ---      -- The send side reports the same distinction (see-      -- 'Hasql.Comms.Roundtrip.ClientError'); without it here a dropped-      -- socket is indistinguishable from a statement that returned no rows.-      Bool       -- | 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+    NoResultsError tag _ -> tag     TooManyResultsError tag _ -> tag+    ConnectionLostError tag _ _ -> tag    {-# INLINE duplicate #-}   duplicate e = case e of     ResultError _ resultIndex resultError -> ResultError e resultIndex resultError-    NoResultsError _ connectionLost details -> NoResultsError e connectionLost details+    NoResultsError _ details -> NoResultsError e details     TooManyResultsError _ expectedCount -> TooManyResultsError e expectedCount+    ConnectionLostError _ diagnostic details -> ConnectionLostError e diagnostic details
src/comms/Hasql/Comms/ResultDecoder.hs view
@@ -8,6 +8,7 @@      -- * Extractors     columnOids,+    serverDiagnostic,      -- * Constructors @@ -135,7 +136,31 @@     position <-       parsePosition <$> Pq.resultErrorField result Pq.DiagStatementPosition     pure $ Left $ ServerError code message detail hint position-  where++-- | The genuine server error report a result carries, if any.+--+-- A result qualifies only when it carries a nonempty SQLSTATE. Both libpq+-- and the native adapter manufacture fatal-looking results with no+-- diagnostic fields when a connection dies locally, and those must not pass+-- for the server's word: provenance is decided by the SQLSTATE, not by the+-- result's status or its message text.+serverDiagnostic :: Pq.Result -> IO (Maybe Error)+serverDiagnostic result = do+  code <- Pq.resultErrorField result Pq.DiagSqlstate+  case code of+    Just code | not (ByteString.null code) -> do+      message <-+        fold <$> Pq.resultErrorField result Pq.DiagMessagePrimary+      detail <-+        Pq.resultErrorField result Pq.DiagMessageDetail+      hint <-+        Pq.resultErrorField result Pq.DiagMessageHint+      position <-+        parsePosition <$> Pq.resultErrorField result Pq.DiagStatementPosition+      pure (Just (ServerError code message detail hint position))+    _ -> pure Nothing++parsePosition :: Maybe ByteString -> Maybe Int parsePosition = \case   Nothing -> Nothing   Just pos ->
src/library-tests/Helpers/Scripts.hs view
@@ -19,12 +19,18 @@ onUnpreparableConnection = onConnection True  onConnection :: Bool -> ScopeParams -> (Connection.Connection -> IO a) -> IO a-onConnection unpreparable (adapter, host, port) =-  bracket-    ( do+onConnection unpreparable scope =+  bracket (acquire unpreparable scope) Connection.release++-- | Acquire a connection, failing the test if that is not possible.+--+-- The caller is responsible for releasing it. Prefer 'onConnection', which+-- does so, unless the test needs to control the release itself.+acquire :: Bool -> ScopeParams -> IO Connection.Connection+acquire unpreparable (adapter, host, port) = do   let settings =         mconcat-                [ Settings.hostAndPort host (fromIntegral port),+          [ Settings.hostAndPort host port,             Settings.user "postgres",             Settings.password "postgres",             Settings.dbname "postgres",@@ -34,8 +40,6 @@   case res of     Left err -> fail ("Connection failed: " <> show err)     Right conn -> pure conn-    )-    Connection.release  -- | Generate a unique name of the following pattern: --
+ src/library-tests/Integration/Isolated/Connection/Use/LostConnectionSpec.hs view
@@ -0,0 +1,537 @@+-- |+-- Contract of 'Hasql.Connection.use' when the connection is gone by the time+-- an operation receives its results:+--+-- > Connection.use returns Left (ConnectionUseError _)+--+-- It applies whatever the server sent before closing, including a genuine+-- @FATAL@ diagnostic, and to every operation that receives results:+-- statements (unpreparable, preparable on first use and from the statement+-- cache), pipelines, scripts and the type-info lookup that precedes a+-- statement with named types.+--+-- A dead connection must not be reported as a catchable+-- 'Errors.SessionUseError', because pools discard a connection only on+-- 'Errors.ConnectionUseError' and otherwise keep handing out the dead one.+--+-- The payload records where the diagnostic came from. A genuine server+-- @FATAL@ - the @57P01@ announcing @pg_terminate_backend@ - surfaces as+-- 'Errors.ServerConnectionError' with its SQLSTATE intact. A silent close+-- and the crash shutdown's notice-only @57P02@ (a notice never reaches the+-- receive) surface as 'Errors.LocalConnectionError' with no SQLSTATE. A+-- further use of the spent handle reports a generic local-only error rather+-- than replaying the original diagnostic.+--+-- The connection dies *between* two sessions, so the next session's send+-- still succeeds (the bytes land in the kernel buffer) and the failure only+-- shows up on receive. A reset (RST) would instead make the send fail, which+-- is a different, already correctly handled path, so the silent-close fixture+-- closes gracefully (FIN).+--+-- Isolated, because the crash-shutdown fixture makes the server terminate+-- every connection it has, so the spec needs a server of its own and runs its+-- cells one at a time.+--+-- Reproduces <https://github.com/nikita-volkov/hasql/issues/341>.+module Integration.Isolated.Connection.Use.LostConnectionSpec (spec) where++import Data.ByteString qualified as ByteString+import Data.Text qualified as Text+import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Errors qualified as Errors+import Hasql.Pipeline qualified as Pipeline+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.PostgresContainer qualified as PostgresContainer+import Helpers.Scripts qualified as Scripts+import Network.Socket qualified as Socket+import Network.Socket.ByteString qualified as Socket.ByteString+import Pqi qualified+import Prelude+import Test.Hspec+import TestcontainersPostgresql qualified++-- | The connection-loss contract, exercised per adapter (via the surrounding+-- hook), per Postgres distro, per way of dying and per operation shape.+spec :: SpecWith Pqi.Adapter+spec =+  for_ ["postgres:9", "postgres:18"] \tagName ->+    describe (toList tagName)+      $ aroundAllWith+        ( \action adapter ->+            PostgresContainer.run+              TestcontainersPostgresql.Config+                { tagName,+                  auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",+                  forwardLogs = False+                }+              (\(host, port) -> action (adapter, host, port))+        )+        do+          byWay+          midOperation++-- * Ways of dying between two sessions++byWay :: SpecWith Scripts.ScopeParams+byWay =+  for_ ways \Way {name, withKillableConnection, announcedSqlState} ->+    describe name do+      for_ operations \Operation {name, warmUp, session} ->+        it name \config ->+          withKillableConnection config \connection kill -> do+            warmUpResult <- Connection.use connection warmUp+            warmUpResult `shouldBe` Right ()+            kill+            outcome <- useWithinBounds connection session+            shouldBeConnectionFatal announcedSqlState outcome++      -- The first use has received whatever the server announced, so the+      -- further one reports the spent handle generically, replaying no+      -- diagnostic.+      it "Reports a further use of the same handle as a lost connection too" \config ->+        withKillableConnection config \connection kill -> do+          kill+          _ <- useWithinBounds connection (void (Session.statement () selectOne))+          outcome <- useWithinBounds connection (void (Session.statement () selectOne))+          shouldBeConnectionFatal Nothing outcome++-- | A way for the connection to die between two sessions.+data Way = Way+  { name :: String,+    -- | Provides a healthy connection together with an action that kills it+    -- and returns only after the kill has landed.+    withKillableConnection ::+      Scripts.ScopeParams ->+      (Connection.Connection -> IO () -> IO ()) ->+      IO (),+    -- | The SQLSTATE the server announces the termination with in an error+    -- result, if it does.+    announcedSqlState :: Maybe Text+  }++ways :: [Way]+ways =+  [ Way+      { name = "Silent close",+        withKillableConnection = \(adapter, host, port) action ->+          withSeveringProxy host port \proxyPort sever _ ->+            withVictimConnection (adapter, "127.0.0.1", proxyPort) \connection ->+              action connection sever,+        announcedSqlState = Nothing+      },+    Way+      { name = "Server-announced termination",+        withKillableConnection = \config@(adapter, host, port) action ->+          -- The victim goes through the proxy, which here is merely a buffer.+          -- Postgres closes its socket for good when it terminates the+          -- backend, so the victim's next write would be answered with a+          -- reset, which races with the read of the FATAL message and fails+          -- the send of a multi-write operation. The proxy keeps its client+          -- side open, so the victim deterministically gets the FATAL message+          -- followed by a plain FIN.+          withSeveringProxy host port \proxyPort _ _ ->+            withVictimConnection (adapter, "127.0.0.1", proxyPort) \victim -> do+              pid <- run victim (Session.statement () selectBackendPid)+              action victim (terminateBackend config pid),+        -- admin_shutdown, which pg_terminate_backend makes the backend send.+        announcedSqlState = Just "57P01"+      },+    Way+      { name = "Crash shutdown",+        -- The shape the issue was reported with, from an AWS Aurora failover:+        -- the server sends a warning with crash_shutdown (57P02) and closes.+        -- Stock Postgres does exactly that to every backend when another one+        -- crashes. A warning is a notice, not a result, so it never reaches+        -- the receive, and the client is left with a plain EOF.+        --+        -- Goes through the proxy for the same reason as the termination.+        withKillableConnection = \config@(adapter, host, port) action ->+          finally+            ( withSeveringProxy host port \proxyPort _ awaitUpstreamClosed ->+                withVictimConnection (adapter, "127.0.0.1", proxyPort) \victim ->+                  action victim do+                    crashAnotherBackend config+                    awaitUpstreamClosed+            )+            (awaitRecovery config),+        announcedSqlState = Nothing+      }+  ]+  where+    selectBackendPid :: Statement.Statement () Int32+    selectBackendPid =+      Statement.preparable+        "select pg_backend_pid()"+        mempty+        (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++    -- Terminates the backend from a second connection and waits until it+    -- has vanished from @pg_stat_activity@, so that the kill has landed+    -- before the victim runs anything.+    --+    -- Uses the one-argument @pg_terminate_backend@, because the two-argument+    -- one does not exist on the Postgres 9 the shared hook also runs.+    terminateBackend :: Scripts.ScopeParams -> Int32 -> IO ()+    terminateBackend config pid =+      Scripts.onPreparableConnection config \killer -> do+        terminated <- run killer (Session.statement pid terminate)+        unless terminated do+          fail ("pg_terminate_backend returned false for pid " <> show pid)+        waitUntilGone killer (200 :: Int)+      where+        terminate =+          Statement.preparable+            "select pg_terminate_backend($1)"+            (Encoders.param (Encoders.nonNullable Encoders.int4))+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))+        countActive =+          Statement.preparable+            "select count(*) :: int8 from pg_stat_activity where pid = $1"+            (Encoders.param (Encoders.nonNullable Encoders.int4))+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))+        waitUntilGone killer attemptsLeft = do+          count <- run killer (Session.statement pid countActive)+          if count == 0+            then pure ()+            else+              if attemptsLeft <= 0+                then fail ("Backend " <> show pid <> " is still in pg_stat_activity after it was terminated")+                else do+                  threadDelay 25_000+                  waitUntilGone killer (attemptsLeft - 1)++    -- Makes the server go through a crash restart, by killing a backend of+    -- a second connection with SIGKILL.+    --+    -- The postmaster then terminates every other backend with SIGQUIT, and+    -- each of them sends its client a warning with crash_shutdown (57P02)+    -- before it exits. The killed backend is the one running the @COPY@,+    -- which is the parent of the shell the program runs in.+    crashAnotherBackend :: Scripts.ScopeParams -> IO ()+    crashAnotherBackend config =+      bracket (Scripts.acquire False config) Connection.release \crasher ->+        -- Fails, as the backend running it dies.+        void (Connection.use crasher (Session.script "copy (select 1) to program 'kill -KILL $PPID'"))++    -- Waits until the server accepts connections again after a crash+    -- restart, so that the next test finds it usable.+    awaitRecovery :: Scripts.ScopeParams -> IO ()+    awaitRecovery config =+      loop (300 :: Int)+      where+        loop attemptsLeft =+          try @IOException (Scripts.acquire False config) >>= \case+            Right connection -> Connection.release connection+            Left err ->+              if attemptsLeft <= 0+                then throwIO err+                else do+                  threadDelay 100_000+                  loop (attemptsLeft - 1)++-- * Operations run after the connection died++-- | A session that is run as the victim's next one after the connection died.+data Operation = Operation+  { name :: String,+    -- | Runs while the connection is still healthy, before it is killed.+    warmUp :: Session.Session (),+    -- | The session under test.+    session :: Session.Session ()+  }++operations :: [Operation]+operations =+  [ Operation+      { name = "Unpreparable statement",+        warmUp = pure (),+        session = void (Session.statement () selectOneUnpreparable)+      },+    Operation+      { name = "Preparable statement, first use",+        warmUp = pure (),+        session = void (Session.statement () selectOne)+      },+    Operation+      { name = "Preparable statement, already in the statement cache",+        warmUp = void (Session.statement () selectOne),+        session = void (Session.statement () selectOne)+      },+    Operation+      { name = "Pipeline of two statements",+        warmUp = pure (),+        session =+          void+            ( Session.pipeline+                ( (,)+                    <$> Pipeline.statement () selectOne+                    <*> Pipeline.statement () selectOne+                )+            )+      },+    Operation+      { name = "Script",+        warmUp = pure (),+        session = Session.script "select 1"+      },+    Operation+      { name = "Statement with a named type, whose OID is looked up first",+        warmUp = pure (),+        -- The type needs not to exist: the lookup roundtrip fails before+        -- anything checks for it.+        session = void (Session.statement "lost_connection_spec_enum" selectNamedType)+      }+  ]++selectOne :: Statement.Statement () Int32+selectOne =+  Statement.preparable+    "select 1"+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++selectOneUnpreparable :: Statement.Statement () Int32+selectOneUnpreparable =+  Statement.unpreparable+    "select 1"+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++selectNamedType :: Statement.Statement Text Text+selectNamedType =+  Statement.preparable+    "select $1 :: lost_connection_spec_enum"+    (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing "lost_connection_spec_enum" id)))+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing "lost_connection_spec_enum" Just))))++-- * Dying in the middle of an operation++-- | The connection dies while the operation is receiving its results, so a+-- single round trip mixes what the server managed to send with the loss+-- itself.+midOperation :: SpecWith Scripts.ScopeParams+midOperation =+  describe "Mid-operation" do+    it "Statement whose backend terminates itself" \config ->+      withVictimConnection config \connection -> do+        outcome <- useWithinBounds connection (void (Session.statement () terminateOwnBackend))+        shouldBeConnectionFatal (Just "57P01") outcome++    it "Script with a successful statement before the backend terminates itself" \config ->+      -- The first statement's result is decoded successfully and the loss is+      -- only observed after it. The whole use is still reported as+      -- connection-fatal and the decoded results are discarded: a session+      -- that cannot vouch for the connection cannot vouch for what a pool+      -- would hand out next.+      withVictimConnection config \connection -> do+        outcome <-+          useWithinBounds+            connection+            (Session.script "select 1; select pg_terminate_backend(pg_backend_pid())")+        shouldBeConnectionFatal (Just "57P01") outcome++    it "Pipeline whose first statement terminates the backend" \config ->+      -- The termination is announced with a genuine FATAL result, while the+      -- results of the statements behind it are manufactured locally by the+      -- driver once the connection is found lost. The manufactured ones must+      -- not shadow the genuine diagnostic.+      withVictimConnection config \connection -> do+        outcome <-+          useWithinBounds+            connection+            ( void+                ( Session.pipeline+                    ( (,)+                        <$> Pipeline.statement () terminateOwnBackend+                        <*> Pipeline.statement () selectOne+                    )+                )+            )+        shouldBeConnectionFatal (Just "57P01") outcome++terminateOwnBackend :: Statement.Statement () Bool+terminateOwnBackend =+  Statement.preparable+    "select pg_terminate_backend(pg_backend_pid())"+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))++-- * Expectation++-- | What a call to 'Connection.use' did.+--+-- Besides returning, it can break its contract of never throwing and never+-- blocking, which a lost connection has been seen to provoke. Those are+-- recorded as outcomes, so that they fail the test with a message instead of+-- escaping it or hanging the run.+data Outcome+  = -- | It returned.+    ReturnedOutcome (Either Errors.UseError ())+  | -- | It threw, which the public API promises never to do.+    ThrewOutcome SomeException+  | -- | It did not return within the bounds of the test.+    HungOutcome+  deriving stock (Show)++-- | Runs 'Connection.use' and captures whatever it does.+useWithinBounds :: Connection.Connection -> Session.Session () -> IO Outcome+useWithinBounds connection session =+  fmap+    (either ThrewOutcome (maybe HungOutcome ReturnedOutcome))+    (try @SomeException (timeout 5_000_000 (Connection.use connection session)))++-- | Fails with the full actual outcome, so that a red run records the+-- misclassification it observed.+--+-- The expected SQLSTATE also decides the expected payload variant: a+-- genuinely announced diagnostic must arrive as+-- 'Errors.ServerConnectionError', everything else as+-- 'Errors.LocalConnectionError'.+shouldBeConnectionFatal :: Maybe Text -> Outcome -> Expectation+shouldBeConnectionFatal expectedSqlState = \case+  ReturnedOutcome (Left (Errors.ConnectionUseError connectionError)) -> do+    Errors.toSqlState connectionError `shouldBe` expectedSqlState+    case (expectedSqlState, connectionError) of+      (Just _, Errors.ServerConnectionError _) -> pure ()+      (Nothing, Errors.LocalConnectionError _) -> pure ()+      _ ->+        expectationFailure+          ( mconcat+              [ "Expected the payload variant matching SQLSTATE ",+                show expectedSqlState,+                ", got: ",+                show connectionError+              ]+          )+  actual ->+    expectationFailure+      ( mconcat+          [ "Expected: ReturnedOutcome (Left (ConnectionUseError _)) with SQLSTATE ",+            show expectedSqlState,+            "\n     Got: ",+            show actual+          ]+      )++-- * Fixtures++-- | Acquires the connection that is going to be killed.+--+-- Does not use 'Scripts.onPreparableConnection', because its release+-- would block forever if a lost connection makes 'Connection.use' leave the+-- handle unusable. The release is bounded instead, and the dead connection is+-- left for the garbage collector.+withVictimConnection :: Scripts.ScopeParams -> (Connection.Connection -> IO a) -> IO a+withVictimConnection config =+  bracket (Scripts.acquire False config) \connection ->+    void (timeout 1_000_000 (Connection.release connection))++-- | Runs a session that the fixture depends on, failing the test on any+-- error: an error here is a broken fixture, not the behaviour under test.+run :: Connection.Connection -> Session.Session a -> IO a+run connection session =+  Connection.use connection session >>= \case+    Left err -> fail ("Unexpected session error in fixture: " <> show err)+    Right result -> pure result++-- | A TCP proxy that sits between the connection under test and the database.+--+-- It accepts exactly one client and forwards bytes in both directions.+--+-- Its client-facing socket stays open until the scope ends, so whatever the+-- client sends after the database side has gone is swallowed by the kernel+-- buffer instead of being answered with a reset, and the client reads the+-- database's last words followed by a plain FIN.+--+-- The provided @sever@ action closes the database side without the database+-- saying anything: the forwarder passes the EOF on to the client as a FIN,+-- and @sever@ returns once the forwarders have stopped.+--+-- The provided @awaitUpstreamClosed@ action returns once the database has+-- closed its side and everything it sent before that has been passed on to+-- the client.+withSeveringProxy ::+  -- | Database host.+  Text ->+  -- | Database port.+  Word16 ->+  -- | Receives the proxy's port, the @sever@ action and the+  -- @awaitUpstreamClosed@ action.+  (Word16 -> IO () -> IO () -> IO a) ->+  IO a+withSeveringProxy upstreamHost upstreamPort action = do+  upstreamAddress <- do+    addresses <-+      Socket.getAddrInfo+        (Just Socket.defaultHints {Socket.addrSocketType = Socket.Stream})+        (Just (Text.unpack upstreamHost))+        (Just (show upstreamPort))+    case addresses of+      address : _ -> pure address+      [] -> fail ("Cannot resolve " <> Text.unpack upstreamHost)+  opened <- newIORef []+  forwarders <- newIORef []+  severance <- newEmptyMVar+  downstreamStopped <- newEmptyMVar+  let open socketAction = do+        socket <- socketAction+        atomicModifyIORef' opened \sockets -> (socket : sockets, ())+        pure socket+      -- Registers the thread before an exception can interrupt the forking+      -- one, so that the teardown never misses a forwarder.+      fork io = mask_ do+        thread <- forkIOWithUnmask \unmask -> unmask io+        atomicModifyIORef' forwarders \threads -> (thread : threads, ())+        pure thread+  listener <- open (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol)+  Socket.bind listener (Socket.SockAddrInet 0 (Socket.tupleToHostAddress (127, 0, 0, 1)))+  Socket.listen listener 1+  proxyPort <- Socket.socketPort listener+  acceptor <- forkIO do+    (client, _) <- Socket.accept listener+    atomicModifyIORef' opened \sockets -> (client : sockets, ())+    upstream <-+      open+        ( Socket.socket+            (Socket.addrFamily upstreamAddress)+            Socket.Stream+            Socket.defaultProtocol+        )+    Socket.connect upstream (Socket.addrAddress upstreamAddress)+    clientToUpstream <- fork (forward client upstream)+    _ <- fork (forward upstream client `finally` putMVar downstreamStopped ())+    putMVar severance do+      Socket.shutdown upstream Socket.ShutdownBoth+      readMVar downstreamStopped+      killThread clientToUpstream+  let sever = join (readMVar severance)+      awaitUpstreamClosed = readMVar downstreamStopped+      -- Stops every thread before closing any socket. A closed descriptor is+      -- reused by the next socket any concurrent test opens, and a forwarder+      -- still holding it would read from or shut down that socket instead.+      teardown = do+        killThread acceptor+        traverse_ killThread =<< readIORef forwarders+        sockets <- readIORef opened+        for_ sockets \socket -> Socket.close socket `catch` \(_ :: IOException) -> pure ()+  action (fromIntegral proxyPort) sever awaitUpstreamClosed `finally` teardown+  where+    -- Copies bytes until the source reaches EOF or fails, then passes that on+    -- as a FIN, so that the peer never waits for bytes that cannot come.+    forward :: Socket.Socket -> Socket.Socket -> IO ()+    forward source destination =+      loop `catch` \(_ :: IOException) -> finish+      where+        finish =+          Socket.shutdown destination Socket.ShutdownSend+            `catch` \(_ :: IOException) -> pure ()+        loop = do+          chunk <- Socket.ByteString.recv source 16_384+          if ByteString.null chunk+            then finish+            else do+              Socket.ByteString.sendAll destination chunk+              loop
src/library-tests/Integration/Sharing/Session/OnLibpqConnection/DirtyReturnCleanupSpec.hs view
@@ -37,7 +37,7 @@     describe "Reporting a connection error" do       it "Gets the connection finished rather than repaired" \config -> do         Scripts.onPreparableConnection config \connection -> do-          result <- Connection.use connection (dirtyReturn (Errors.ConnectionUseError "Simulated failure"))+          result <- Connection.use connection (dirtyReturn (Errors.ConnectionUseError (Errors.LocalConnectionError "Simulated failure")))           case result of             Left (Errors.ConnectionUseError _) -> pure ()             _ -> expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/Session/StatementSpec.hs view
@@ -65,8 +65,10 @@      it "reports a statement that genuinely returned no rows as a row-count mismatch, not a lost connection" \config -> do       -- The server answering with zero rows and the socket going away both-      -- reach `use` through the same absence of a result, and only an-      -- internal flag tells them apart (see `Hasql.Comms.Recv.NoResultsError`).+      -- reach `use` through the same absence of a result, and only the+      -- connection status observed after the receive tells them apart: a bad+      -- status is a `Hasql.Comms.Recv.ConnectionLostError`, an intact+      -- connection with no result is a `Hasql.Comms.Recv.NoResultsError`.       -- Getting this wrong either way is a real hazard: reporting a genuine       -- empty result as `ConnectionUseError` would have pools discard a       -- perfectly good connection, and reporting a dropped socket as this
src/library-tests/Pure/ErrorsSpec.hs view
@@ -263,29 +263,81 @@                      \  expectedMax: 1\n\                      \  actual: 10" +  describe "ConnectionError" do+    describe "toMessage" do+      it "renders LocalConnectionError" do+        (Errors.toMessage (Errors.LocalConnectionError "connection lost"))+          `shouldBe` "Connection error"++      it "renders ServerConnectionError with the wrapped message" do+        (Errors.toMessage (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing)))+          `shouldBe` "Server error"++    describe "toDetails" do+      it "includes reason for LocalConnectionError" do+        (Errors.toDetails (Errors.LocalConnectionError "connection lost"))+          `shouldBe` [("reason", "connection lost")]++      it "includes the wrapped server error's details for ServerConnectionError" do+        (Errors.toDetails (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing)))+          `shouldBe` [("code", "57P01"), ("message", "terminating connection due to administrator command")]++    describe "toSqlState" do+      it "is Nothing for LocalConnectionError" do+        (Errors.toSqlState (Errors.LocalConnectionError "connection lost"))+          `shouldBe` Nothing++      it "delegates to the wrapped server error for ServerConnectionError" do+        (Errors.toSqlState (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing)))+          `shouldBe` Just "57P01"++    describe "toDetailedText" do+      it "renders LocalConnectionError with details" do+        (Errors.toDetailedText (Errors.LocalConnectionError "connection lost"))+          `shouldBe` "Connection error\n\+                     \  reason: connection lost"++      it "renders ServerConnectionError without duplicating the wrapped message" do+        (Errors.toDetailedText (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing)))+          `shouldBe` "Server error\n\+                     \  code: 57P01\n\+                     \  message: terminating connection due to administrator command"+   describe "UseError" do     describe "toMessage" do       it "renders SessionUseError with the wrapped message" do         (Errors.toMessage (Errors.SessionUseError (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0))))           `shouldBe` "Unexpected number of rows" -      it "renders ConnectionUseError" do-        (Errors.toMessage (Errors.ConnectionUseError "connection lost"))+      it "renders ConnectionUseError with the local payload's message" do+        (Errors.toMessage (Errors.ConnectionUseError (Errors.LocalConnectionError "connection lost")))           `shouldBe` "Connection error" +      it "renders ConnectionUseError with the server payload's message" do+        (Errors.toMessage (Errors.ConnectionUseError (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing))))+          `shouldBe` "Server error"+     describe "toDetails" do-      it "includes reason for ConnectionUseError" do-        (Errors.toDetails (Errors.ConnectionUseError "connection lost"))+      it "includes reason for a locally observed ConnectionUseError" do+        (Errors.toDetails (Errors.ConnectionUseError (Errors.LocalConnectionError "connection lost")))           `shouldBe` [("reason", "connection lost")] +      it "includes the server diagnostic for a server-announced ConnectionUseError" do+        (Errors.toDetails (Errors.ConnectionUseError (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing))))+          `shouldBe` [("code", "57P01"), ("message", "terminating connection due to administrator command")]+     describe "toSqlState" do       it "digs the code out of a wrapped SessionUseError" do         (Errors.toSqlState (Errors.SessionUseError (Errors.ScriptSessionError "DROP TABLE users" (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing))))           `shouldBe` Just "42P01" -      it "is Nothing for ConnectionUseError" do-        (Errors.toSqlState (Errors.ConnectionUseError "connection lost"))+      it "is Nothing for a locally observed ConnectionUseError" do+        (Errors.toSqlState (Errors.ConnectionUseError (Errors.LocalConnectionError "connection lost")))           `shouldBe` Nothing++      it "digs the code out of a server-announced ConnectionUseError" do+        (Errors.toSqlState (Errors.ConnectionUseError (Errors.ServerConnectionError (Errors.ServerError "57P01" "terminating connection due to administrator command" Nothing Nothing Nothing))))+          `shouldBe` Just "57P01"    describe "toDetailedText with multiline values" do     it "indents multiline detail values correctly" do
src/library/Hasql/Connection.hs view
@@ -188,7 +188,7 @@     takeMVar var >>= \case       Nothing -> do         putMVar var Nothing-        pure (Left (ConnectionUseError "The connection is no longer available"))+        pure (Left (ConnectionUseError (LocalConnectionError "The connection is no longer available")))       Just connectionState -> do         (result, !newState) <-           onException (unmask (Session.run session connectionState)) do
src/library/Hasql/Engine/Errors.hs view
@@ -167,7 +167,9 @@     -- This covers every way 'Hasql.Connection.use' can lose the connection:     -- a dropped socket, a request @libpq@ refused to send outright (e.g.     -- more than 65535 parameters in one statement), an unexpected response-    -- from the server, or a bug in Hasql. The reason text says which.+    -- from the server, or a bug in Hasql. The 'ConnectionError' payload says+    -- whether the server announced the failure or the driver observed it+    -- locally.     --     -- 'Hasql.Connection.use' has finished the connection before returning     -- this, so the 'Hasql.Connection.Connection' the session ran on is@@ -180,11 +182,40 @@     -- than replacing it: the repair would have to push a Sync, which     -- flushes and commits the very commands the failed session never got to     -- complete. So this is reported uniformly rather than split by cause --    -- retry policy belongs to the caller, informed by the reason text and,-    -- for server errors, 'Hasql.Errors.toSqlState'.+    -- retry policy belongs to the caller, informed by the payload and,+    -- where the server announced the failure, 'Hasql.Errors.toSqlState'.     ConnectionUseError+      ConnectionError+  deriving stock (Show, Eq)++-- |+-- Details of a connection-fatal failure: the payload of+-- 'ConnectionUseError'.+--+-- The two constructors record where the diagnostic came from, not how the+-- failure should be treated. Both mean the same thing operationally - the+-- connection is gone and the handle is spent - so the split carries no+-- retryability or catchability verdict. It exists because a SQLSTATE is+-- worth keeping when the server actually reported one, and inventing one+-- when it did not would be a lie.+data ConnectionError+  = -- | The driver observed the connection's death locally: a dropped+    -- socket, a request @libpq@ refused to send, an EOF with no server+    -- diagnostic before it, a driver bug. Carries human-readable details+    -- for logging.+    --+    -- 'Hasql.Errors.toSqlState' is always 'Nothing' for this constructor:+    -- no server diagnostic was observed, so there is no SQLSTATE to report.+    LocalConnectionError       -- | Human-readable details about what went wrong.       Text+  | -- | The server announced the failure with a genuine error report before+    -- the connection died - e.g. a @FATAL@ with SQLSTATE @57P01@ in+    -- response to @pg_terminate_backend@.+    --+    -- 'Hasql.Errors.toSqlState' delegates to the carried 'ServerError'.+    ServerConnectionError+      ServerError   deriving stock (Show, Eq)  -- |@@ -376,8 +407,12 @@ -- repair would have to push a Sync, which flushes and commits the very -- commands the failed session never got to complete - so the connection is -- finished instead.+--+-- The failure is observed locally, on the way out, so the payload is always+-- a 'LocalConnectionError': whatever the server thought of the request never+-- made it back as a diagnostic. fromSendError :: Text -> UseError-fromSendError = ConnectionUseError+fromSendError = ConnectionUseError . LocalConnectionError  fromRoundtripError :: Hasql.Comms.Roundtrip.Error tag -> UseError fromRoundtripError = \case@@ -391,7 +426,7 @@   Hasql.Comms.Recv.ResultError tag _resultOffset resultError ->     case tag of       Nothing ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpected error in an operation not associated with any statement. ",             "This indicates a bug in Hasql or the server misbehaving. ",             "Error: ",@@ -406,16 +441,10 @@             parameters             prepared             (fromStatementResultError resultError)-  Hasql.Comms.Recv.NoResultsError tag connectionLost details ->-    if connectionLost-      then -- The results are not late, they are never coming: the socket is-      -- gone. Reporting this as a row-count mismatch would describe a-      -- dropped connection as a statement that returned nothing, and-      -- leave pools reusing a connection that no longer exists.-        ConnectionUseError (maybe "" decodeUtf8Lenient details)-      else case tag of+  Hasql.Comms.Recv.NoResultsError tag details ->+    case tag of       Nothing ->-          (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpectedly got no results in an operation not associated with any statement. ",             "This indicates a bug in Hasql or the server misbehaving. ",             "Details: ",@@ -430,10 +459,16 @@             parameters             prepared             (UnexpectedRowCountStatementError 1 1 0)+  -- The connection died before or while the results arrived, so nothing+  -- earlier in the same receive stays a recoverable error: pools discard+  -- the connection only on 'ConnectionUseError', and reporting the loss as+  -- anything else keeps the dead connection in circulation.+  Hasql.Comms.Recv.ConnectionLostError _ diagnostic details ->+    ConnectionUseError (toConnectionError diagnostic details)   Hasql.Comms.Recv.TooManyResultsError tag actual ->     case tag of       Nothing ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpectedly got too many results in an operation not associated with any statement. ",             "This indicates a bug in Hasql or the server misbehaving. ",             "Amount: ",@@ -505,24 +540,24 @@                 position             )       Hasql.Comms.ResultDecoder.UnexpectedResult msg ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpected result in script: ",             TextBuilder.text msg           ]       Hasql.Comms.ResultDecoder.UnexpectedRowCount actual ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpected amount of rows in script: ",             TextBuilder.decimal actual           ]       Hasql.Comms.ResultDecoder.UnexpectedColumnCount expected actual ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Unexpected amount of columns in script: expected ",             TextBuilder.decimal expected,             ", got ",             TextBuilder.decimal actual           ]       Hasql.Comms.ResultDecoder.DecoderTypeMismatch colIdx expectedOid actualOid ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Decoder type mismatch in script: expected OID ",             TextBuilder.string (show expectedOid),             " at column ",@@ -531,27 +566,49 @@             TextBuilder.string (show actualOid)           ]       Hasql.Comms.ResultDecoder.RowError rowIndex rowError ->-        (ConnectionUseError . TextBuilder.toText . mconcat)+        (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)           [ "Row error in script at row ",             TextBuilder.decimal rowIndex,             ": ",             TextBuilder.string (show rowError)           ]-  Hasql.Comms.Recv.NoResultsError _ connectionLost details ->-    if connectionLost-      then ConnectionUseError (maybe "" decodeUtf8Lenient details)-      else-        (ConnectionUseError . TextBuilder.toText . mconcat)+  Hasql.Comms.Recv.NoResultsError _ details ->+    (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)       [ "Got no results in script.",         " This indicates a bug in Hasql or the server misbehaving.",         details           & filter (/= "")           & foldMap (mappend " Details: " . TextBuilder.text . decodeUtf8Lenient)       ]+  -- The connection died before or while the results arrived, so nothing+  -- earlier in the same receive stays a recoverable error: pools discard+  -- the connection only on 'ConnectionUseError', and reporting the loss as+  -- anything else keeps the dead connection in circulation.+  Hasql.Comms.Recv.ConnectionLostError _ diagnostic details ->+    ConnectionUseError (toConnectionError diagnostic details)   Hasql.Comms.Recv.TooManyResultsError _ actual ->-    (ConnectionUseError . TextBuilder.toText . mconcat)+    (ConnectionUseError . LocalConnectionError . TextBuilder.toText . mconcat)       [ "Got too many results in script. ",         "This indicates a bug in Hasql or the server misbehaving. ",         "Amount: ",         TextBuilder.decimal actual       ]++-- | Classify a connection loss onto the public payload: a genuine server+-- diagnostic becomes 'ServerConnectionError', anything else - a synthetic+-- result the driver manufactured for the loss, a bare EOF, a refused send -+-- is 'LocalConnectionError' with the most useful local text available.+toConnectionError :: Maybe Hasql.Comms.ResultDecoder.Error -> Maybe ByteString -> ConnectionError+toConnectionError diagnostic details =+  case diagnostic of+    Just (Hasql.Comms.ResultDecoder.ServerError code message detail hint position) ->+      ServerConnectionError+        ( ServerError+            (decodeUtf8Lenient code)+            (decodeUtf8Lenient message)+            (fmap decodeUtf8Lenient detail)+            (fmap decodeUtf8Lenient hint)+            position+        )+    _ ->+      LocalConnectionError (maybe "" decodeUtf8Lenient details)
src/library/Hasql/Errors.hs view
@@ -19,6 +19,7 @@      -- * Use errors     UseError (..),+    ConnectionError (..),      -- * Session errors     SessionError (..),@@ -248,19 +249,36 @@     ScriptSessionError _ serverError -> toSqlState serverError     MissingTypesSessionError {} -> Nothing +instance IsError ConnectionError where+  toMessage = \case+    LocalConnectionError {} ->+      "Connection error"+    ServerConnectionError err ->+      toMessage err++  toDetails = \case+    LocalConnectionError reason ->+      [("reason", reason)]+    ServerConnectionError err ->+      toDetails err++  toSqlState = \case+    LocalConnectionError {} -> Nothing+    ServerConnectionError err -> toSqlState err+ instance IsError UseError where   toMessage = \case     SessionUseError err ->       toMessage err-    ConnectionUseError {} ->-      "Connection error"+    ConnectionUseError err ->+      toMessage err    toDetails = \case     SessionUseError err ->       toDetails err-    ConnectionUseError reason ->-      [("reason", reason)]+    ConnectionUseError err ->+      toDetails err    toSqlState = \case     SessionUseError err -> toSqlState err-    ConnectionUseError {} -> Nothing+    ConnectionUseError err -> toSqlState err