packages feed

hasql-pool 1.3.0.6 → 1.7.0.0

raw patch · API changes only · 46 files changed · show whitespace changes · browse hasql-pool-1.7.0.0

API changes (from Hackage documentation)

0 removed, 8 added, 8 changed

version bump matches the API change (PVP)

+ Hasql.Pool.Config: FIFO :: ReuseOrder
+ Hasql.Pool.Config: LIFO :: ReuseOrder
+ Hasql.Pool.Config: data ReuseOrder
+ Hasql.Pool.Config: reuseOrder :: ReuseOrder -> Setting
+ Hasql.Pool.Config.Defaults: reuseOrder :: ReuseOrder
+ Hasql.Pool.Observation: AcquireErrorConnectionTerminationReason :: AcquireError -> ConnectionTerminationReason
+ Hasql.Pool.Observation: ExceptionConnectionTerminationReason :: Text -> ConnectionTerminationReason
+ Hasql.Pool.Observation: SessionErrorConnectionTerminationReason :: SessionError -> ConnectionTerminationReason
- Hasql.Pool: ConnectionUsageError :: ConnectionError -> UsageError
+ Hasql.Pool: ConnectionUsageError :: AcquireError -> UsageError
- Hasql.Pool: SessionUsageError :: SessionError -> UsageError
+ Hasql.Pool: SessionUsageError :: UseError -> UsageError
- Hasql.Pool: acquire :: Config -> IO Pool
+ Hasql.Pool: acquire :: Adapter -> Config -> IO Pool
- Hasql.Pool.Config: dynamicConnectionSettings :: IO [Setting] -> Setting
+ Hasql.Pool.Config: dynamicConnectionSettings :: IO Settings -> Setting
- Hasql.Pool.Config: staticConnectionSettings :: [Setting] -> Setting
+ Hasql.Pool.Config: staticConnectionSettings :: Settings -> Setting
- Hasql.Pool.Config.Defaults: dynamicConnectionSettings :: IO [Setting]
+ Hasql.Pool.Config.Defaults: dynamicConnectionSettings :: IO Settings
- Hasql.Pool.Config.Defaults: staticConnectionSettings :: [Setting]
+ Hasql.Pool.Config.Defaults: staticConnectionSettings :: Settings
- Hasql.Pool.Observation: NetworkErrorConnectionTerminationReason :: Maybe Text -> ConnectionTerminationReason
+ Hasql.Pool.Observation: NetworkErrorConnectionTerminationReason :: ConnectionError -> ConnectionTerminationReason

Files

CHANGELOG.md view
@@ -1,7 +1,59 @@-# v1.3.0.6+# v1.7.0.0 +## Breaking++- Migrate to `hasql-2.2`. `Errors.ConnectionUseError` now carries a structured `Errors.ConnectionError` instead of `Text`, and the pool's dependency bound moves to `hasql ^>=2.2` accordingly.+- `NetworkErrorConnectionTerminationReason` now carries `Errors.ConnectionError` instead of `Maybe Text`. Other termination diagnostics are also represented by their structured Hasql error type where available; exception details remain text.+ ## Fixes +- Connection termination observations now preserve structured acquisition, connection-use and fatal session errors, so callers can inspect SQLSTATE and diagnostic fields instead of parsing text. A `pg_terminate_backend` FATAL (`57P01`) is available through `Errors.toSqlState`.++- A connection lost before or during a receive is now classified as connection-fatal by hasql on every operation shape, where it previously could surface as a catchable session error. The pool's existing reactive disposal handles it: the entry is evicted and a later use establishes a replacement.++# v1.6.0.0++## Breaking++- Migrate to `hasql-2.1`. `UsageError`'s `ConnectionUsageError` now wraps `Errors.AcquireError` (was `Errors.ConnectionError`), and `SessionUsageError` now wraps `Errors.UseError` (was `Errors.SessionError`), matching hasql's merge of its connection-fatal error constructors into a single `UseError` type. Code pattern-matching into the wrapped error needs an extra step through `SessionUseError`/`ConnectionUseError` to reach what used to be there directly.++## Fixes++- A session that fails with `MissingTypesSessionError` no longer causes the connection to be discarded. The type lookup behind that error is a live catalog query which leaves no residue on the connection - nothing is negatively cached and the connection state comes back untouched - so a fresh connection would ask the same catalog and get the same answer. Referencing a type that does not exist used to cost a full teardown and reconnect per attempt.++- A session that fails with `UnexpectedColumnTypeStatementError` no longer causes the connection to be discarded. That rule was there for decoders built against an OID the catalog had since reassigned, but that case never reaches this error: the server notices the retired type first and raises `XX000`. What does reach it is the ordinary decoder mismatch - asking for `int4` where the column is `text` - which is a caller-side bug that a fresh connection reproduces identically.++- Connections are now discarded on `26000` (`invalid_sql_statement_name`) and `42P05` (`duplicate_prepared_statement`). Both mean hasql's per-connection statement cache and the server disagree about what is prepared, and since nothing evicts from that cache, the disagreement is permanent - every subsequent execution of the affected statement fails for the rest of the connection's life.++- Connections are now discarded on `25P02` (`in_failed_sql_transaction`), which means the connection is parked inside an aborted transaction where every statement fails until a rollback the pool has no opportunity to issue.++- Connections are now discarded on class `08` (`connection_exception`, including `08P01` `protocol_violation`), on `40003` (`statement_completion_unknown`), and on class `57P` (`admin_shutdown`, `crash_shutdown`, `database_dropped`, the idle-session timeouts, and the rest). Note that `57014` (`query_canceled`) is deliberately excluded - a cancelled query leaves a perfectly healthy connection.++  Codes deliberately left retaining, with the reasoning recorded in `Hasql.Pool.ConnectionDiscards`, include class `53` (`insufficient_resources` - a server-side shortage that a reconnect cannot cure, and where discarding would turn a resource crunch into a reconnect storm), `40001`/`40P01` (the canonical same-connection retry cases), `55P03`/`55006`, `58030`, and `XX001`/`XX002`.++- A session interrupted by an asynchronous exception (a caller-side `timeout`, `race`, or `killThread`) is now discarded instead of returned to the pool. Hasql finishes the connection on that path itself, so re-queuing it as before handed the next caller a spent handle - a plausible root cause of "connection pointer is NULL" reports (#38).++  As a consequence, `initSession` no longer survives such an exception - it now only survives ordinary session errors (a bad query, a constraint violation), since those are the only case that leaves the old connection in play.+# v1.5.1.1++## Fixes++- After the server closes an idle pooled connection (a Postgres restart,+  `pg_terminate_backend`, a server-side idle timeout), the first session on+  it can fail with `UnexpectedRowCountStatementError` instead of a connection+  error. Hasql maps the extra result that reports the closed connection to+  that error, and a `singleRow` statement that returns two rows fails the+  same way on a healthy connection, so the error alone cannot justify a+  discard: the dead connection got returned to the pool and failed one more+  session before it was discarded, so after a database restart every pooled+  connection failed two sessions. Now, when a session fails with an error+  that does not require a discard, `use` also checks the status that the+  adapter reports for the connection and discards it when it is marked bad.++# v1.5.1.0++## Fixes+ - Fix pool capacity leak when `use` gets interrupted during connection   establishment, connection refresh, or an observation (#60) - Fix pool state corruption from throwing observation handlers; handlers@@ -9,13 +61,57 @@ - Fix background reaper dying permanently from a failed connection   release or observation - Fix `release` leaking flushed entries on failure+- Fix waiters waiting forever on a garbage-collected pool -# v1.3.0.5+## Added +- `reuseOrder` setting (#59): LIFO reuse lets the pool shrink to the+  connections the load needs and keeps caches warm; FIFO stays the default+- One background timer for acquisition timeouts instead of one+  uncancelable timer per waiting request (#58)++## Changed++- Connections are handed to waiting requests in arrival order; a request+  no longer takes a connection while others wait (#58)+# v1.5.0.1++- Allow newer pqi.++# v1.5.0.0++## Breaking++- Migrate to `hasql-2`, replacing `postgresql-libpq` with the `pqi` connection-adapter interface. `acquire` now takes a `Pqi.Adapter` as its first argument; pick one from an adapter package such as `pqi-ffi` or `pqi-native`.++# v1.4.2.3+ ## Fixes +- Fix publishing.++# v1.4.2.2++## Fixes+ - Fix pool capacity leak when `initSession` fails (#56) - Fix background reaper never passively evicting idle connections: it used the connection-lifetime timeout instead of the idleness timeout when checking for idle connections++# v1.4.2.1++## Fixes++- Discard pooled connections after driver errors (#55)++# v1.4++- Migrated to `hasql-1.10`+- Updated connection settings API to use monoid-based `Settings` instead of list-based `[Setting]`+- Updated error types to use `Hasql.Errors` module instead of `Hasql.Session` and `Hasql.Connection`+- Changed session execution API from `Session.run session connection` to `Connection.use connection session`+- Error handling now uses `ConnectionSessionError` for connection-level issues instead of `ClientError`+- Updated statement construction to use `Statement.preparable` and `Statement.unpreparable` instead of direct constructor+- Hid the `Defaults` module from the public API  # v1.3 
hasql-pool.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: hasql-pool-version: 1.3.0.6+version: 1.7.0.0 category: Hasql, Database, PostgreSQL synopsis: Pool of connections for Hasql homepage: https://github.com/nikita-volkov/hasql-pool@@ -68,27 +68,26 @@ library   import: base-settings   hs-source-dirs:-    src/library/exposed-    src/library/other+    src/library/ -  -- cabal-gild: discover src/library/exposed   exposed-modules:     Hasql.Pool     Hasql.Pool.Config     Hasql.Pool.Config.Defaults     Hasql.Pool.Observation -  -- cabal-gild: discover src/library/other   other-modules:     Hasql.Pool.Config.Config+    Hasql.Pool.Config.ReuseOrder     Hasql.Pool.Config.Setting+    Hasql.Pool.ConnectionDiscards     Hasql.Pool.Prelude-    Hasql.Pool.SessionErrorDestructors    build-depends:     base >=4.11 && <5,     bytestring >=0.10 && <0.14,-    hasql >=1.9 && <1.10,+    hasql ^>=2.2,+    pqi >=1.0 && <1.2,     stm >=2.5 && <3,     text >=1.2 && <3,     time >=1.9 && <2,@@ -100,19 +99,22 @@   hs-source-dirs: src/integration-tests   main-is: Main.hs   other-modules:+    Helpers.Adapters     Helpers.Hooks     Helpers.Scripts     Helpers.Sessions-    Specs.BySubject.Config.AgingTimeoutSpec-    Specs.BySubject.Config.IdlenessTimeoutSpec-    Specs.BySubject.Config.InitSessionSpec-    Specs.BySubject.Helpers.Sessions.CountConnectionsSpec-    Specs.BySubject.Helpers.Sessions.GetSettingSpec-    Specs.BySubject.ReleaseSpec-    Specs.BySubject.SpecHook-    Specs.BySubject.UsageError.AcquisitionTimeoutSpec-    Specs.BySubject.UsageError.SessionSpec-    Specs.BySubject.UseSpec+    Specs.Config.AgingTimeoutSpec+    Specs.Config.IdlenessTimeoutSpec+    Specs.Config.InitSessionSpec+    Specs.ConnectionDiscardsSpec+    Specs.Helpers.Sessions.CountConnectionsSpec+    Specs.Helpers.Sessions.GetSettingSpec+    Specs.InterruptionSpec+    Specs.ReleaseSpec+    Specs.SpecHook+    Specs.UsageError.AcquisitionTimeoutSpec+    Specs.UsageError.SessionSpec+    Specs.UseSpec    ghc-options: -threaded   build-tool-depends:@@ -123,8 +125,34 @@     hasql,     hasql-pool,     hspec >=2.6 && <3,+    pqi >=1.0 && <1.2,+    pqi-ffi ^>=1.0,+    pqi-native ^>=1.0,     random >=1.2 && <2,     rerebase >=1.15 && <2,-    testcontainers-postgresql >=0.0.2 && <0.1,+    testcontainers-postgresql >=0.2 && <0.3,     text-builder >=1 && <1.1,     tuple ^>=0.3.0.2,++test-suite unit-tests+  import: base-settings+  type: exitcode-stdio-1.0+  hs-source-dirs:+    src/unit-tests+    src/library++  main-is: Main.hs+  other-modules:+    Hasql.Pool.ConnectionDiscards+    Hasql.Pool.Prelude++  build-depends:+    base >=4.11 && <5,+    bytestring >=0.10 && <0.14,+    hasql ^>=2.2,+    hspec >=2.6 && <3,+    pqi >=1.0 && <1.2,+    stm >=2.5 && <3,+    text >=1.2 && <3,+    time >=1.9 && <2,+    uuid >=1.3 && <2,
+ src/integration-tests/Helpers/Adapters.hs view
@@ -0,0 +1,30 @@+module Helpers.Adapters+  ( adapters,+    byAdapter,+    hook,+  )+where++import Pqi qualified+import Pqi.Ffi qualified+import Pqi.Native qualified+import Prelude+import Test.Hspec++adapters :: [Pqi.Adapter]+adapters =+  [ Pqi.Ffi.adapter,+    Pqi.Native.adapter+  ]++-- | Run the given spec-building function once per available Pqi adapter,+-- nesting each run under a @describe@ named after the adapter.+byAdapter :: (Pqi.Adapter -> Spec) -> Spec+byAdapter f =+  for_ adapters \adapter ->+    describe (toList (Pqi.name adapter)) (f adapter)++hook :: SpecWith Pqi.Adapter -> Spec+hook hookedSpec =+  byAdapter \adapter ->+    mapSubject (const adapter) hookedSpec
src/integration-tests/Helpers/Hooks.hs view
@@ -13,7 +13,7 @@   TestcontainersPostgresql.run     TestcontainersPostgresql.Config       { forwardLogs = False,-        distro = TestcontainersPostgresql.Distro17,+        tagName = "postgres:17",         auth = TestcontainersPostgresql.TrustAuth       }     (\(host, portInt) -> handler (host, fromIntegral portInt))
src/integration-tests/Helpers/Scripts.hs view
@@ -1,56 +1,85 @@ module Helpers.Scripts where -import Hasql.Connection.Setting qualified as Connection.Setting-import Hasql.Connection.Setting.Connection qualified as Connection.Setting.Connection-import Hasql.Connection.Setting.Connection.Param qualified as Connection.Setting.Connection.Param+import Hasql.Connection.Settings qualified as Connection.Settings import Hasql.Pool qualified as Pool import Hasql.Pool.Config qualified as Config+import Hasql.Pool.Observation (Observation) import Hasql.Session qualified as Session+import Pqi qualified import Prelude import System.Random.Stateful qualified as Random import TextBuilder qualified  -- | -- Parameters provided by the scope.--- Host and port of a running isolated postgres server.-type ScopeParams = (Text, Word16)+-- Adapter, host and port of a running isolated postgres server.+type ScopeParams = (Pqi.Adapter, Text, Word16)  onTaggedPool :: Int -> DiffTime -> DiffTime -> DiffTime -> Text -> ScopeParams -> (Pool.Pool -> IO ()) -> IO ()-onTaggedPool poolSize acqTimeout maxLifetime maxIdletime appName (host, port) =+onTaggedPool poolSize acqTimeout maxLifetime maxIdletime appName (adapter, host, port) =   bracket     ( Pool.acquire+        adapter         ( Config.settings             [ Config.size poolSize,               Config.acquisitionTimeout acqTimeout,               Config.agingTimeout maxLifetime,               Config.idlenessTimeout maxIdletime,               Config.staticConnectionSettings-                [ Connection.Setting.connection-                    ( Connection.Setting.Connection.params-                        [ Connection.Setting.Connection.Param.host host,-                          Connection.Setting.Connection.Param.port (fromIntegral port),-                          Connection.Setting.Connection.Param.user "postgres",-                          Connection.Setting.Connection.Param.password "",-                          Connection.Setting.Connection.Param.dbname "postgres",-                          Connection.Setting.Connection.Param.other "application_name" appName+                ( mconcat+                    [ Connection.Settings.hostAndPort host (fromIntegral port),+                      Connection.Settings.user "postgres",+                      Connection.Settings.password "",+                      Connection.Settings.dbname "postgres",+                      Connection.Settings.applicationName appName                     ]                 )             ]-            ]         )     )     Pool.release  onAutotaggedPool :: Int -> DiffTime -> DiffTime -> DiffTime -> ScopeParams -> (Text -> Pool.Pool -> IO ()) -> IO ()-onAutotaggedPool poolSize acqTimeout maxLifetime maxIdletime (host, port) cont = do+onAutotaggedPool poolSize acqTimeout maxLifetime maxIdletime scopeParams cont = do   -- Generate app name   appName <- generateName "hasql-pool-test-"-  onTaggedPool poolSize acqTimeout maxLifetime maxIdletime appName (host, port) (cont appName)+  onTaggedPool poolSize acqTimeout maxLifetime maxIdletime appName scopeParams (cont appName) +onTaggedPoolWithObservationHandler :: Int -> DiffTime -> DiffTime -> DiffTime -> (Observation -> IO ()) -> Text -> ScopeParams -> (Pool.Pool -> IO ()) -> IO ()+onTaggedPoolWithObservationHandler poolSize acqTimeout maxLifetime maxIdletime observationHandler appName (adapter, host, port) =+  bracket+    ( Pool.acquire+        adapter+        ( Config.settings+            [ Config.size poolSize,+              Config.acquisitionTimeout acqTimeout,+              Config.agingTimeout maxLifetime,+              Config.idlenessTimeout maxIdletime,+              Config.observationHandler observationHandler,+              Config.staticConnectionSettings+                ( mconcat+                    [ Connection.Settings.hostAndPort host (fromIntegral port),+                      Connection.Settings.user "postgres",+                      Connection.Settings.password "",+                      Connection.Settings.dbname "postgres",+                      Connection.Settings.applicationName appName+                    ]+                )+            ]+        )+    )+    Pool.release++onAutotaggedPoolWithObservationHandler :: Int -> DiffTime -> DiffTime -> DiffTime -> (Observation -> IO ()) -> ScopeParams -> (Text -> Pool.Pool -> IO ()) -> IO ()+onAutotaggedPoolWithObservationHandler poolSize acqTimeout maxLifetime maxIdletime observationHandler scopeParams cont = do+  appName <- generateName "hasql-pool-test-"+  onTaggedPoolWithObservationHandler poolSize acqTimeout maxLifetime maxIdletime observationHandler appName scopeParams (cont appName)+ onTaggedPoolWithInitSession :: Int -> DiffTime -> DiffTime -> DiffTime -> Session.Session () -> Text -> ScopeParams -> (Pool.Pool -> IO ()) -> IO ()-onTaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession appName (host, port) =+onTaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession appName (adapter, host, port) =   bracket     ( Pool.acquire+        adapter         ( Config.settings             [ Config.size poolSize,               Config.acquisitionTimeout acqTimeout,@@ -58,27 +87,54 @@               Config.idlenessTimeout maxIdletime,               Config.initSession initSession,               Config.staticConnectionSettings-                [ Connection.Setting.connection-                    ( Connection.Setting.Connection.params-                        [ Connection.Setting.Connection.Param.host host,-                          Connection.Setting.Connection.Param.port (fromIntegral port),-                          Connection.Setting.Connection.Param.user "postgres",-                          Connection.Setting.Connection.Param.password "",-                          Connection.Setting.Connection.Param.dbname "postgres",-                          Connection.Setting.Connection.Param.other "application_name" appName+                ( mconcat+                    [ Connection.Settings.hostAndPort host (fromIntegral port),+                      Connection.Settings.user "postgres",+                      Connection.Settings.password "",+                      Connection.Settings.dbname "postgres",+                      Connection.Settings.applicationName appName                     ]                 )             ]-            ]         )     )     Pool.release  onAutotaggedPoolWithInitSession :: Int -> DiffTime -> DiffTime -> DiffTime -> Session.Session () -> ScopeParams -> (Text -> Pool.Pool -> IO ()) -> IO ()-onAutotaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession (host, port) cont = do+onAutotaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession (adapter, host, port) cont = do   appName <- generateName "hasql-pool-test-"-  onTaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession appName (host, port) (cont appName)+  onTaggedPoolWithInitSession poolSize acqTimeout maxLifetime maxIdletime initSession appName (adapter, host, port) (cont appName) +onTaggedPoolWithReuseOrder :: Int -> DiffTime -> DiffTime -> DiffTime -> Config.ReuseOrder -> Text -> ScopeParams -> (Pool.Pool -> IO ()) -> IO ()+onTaggedPoolWithReuseOrder poolSize acqTimeout maxLifetime maxIdletime reuseOrder appName (adapter, host, port) =+  bracket+    ( Pool.acquire+        adapter+        ( Config.settings+            [ Config.size poolSize,+              Config.acquisitionTimeout acqTimeout,+              Config.agingTimeout maxLifetime,+              Config.idlenessTimeout maxIdletime,+              Config.reuseOrder reuseOrder,+              Config.staticConnectionSettings+                ( mconcat+                    [ Connection.Settings.hostAndPort host (fromIntegral port),+                      Connection.Settings.user "postgres",+                      Connection.Settings.password "",+                      Connection.Settings.dbname "postgres",+                      Connection.Settings.applicationName appName+                    ]+                )+            ]+        )+    )+    Pool.release++onAutotaggedPoolWithReuseOrder :: Int -> DiffTime -> DiffTime -> DiffTime -> Config.ReuseOrder -> ScopeParams -> (Text -> Pool.Pool -> IO ()) -> IO ()+onAutotaggedPoolWithReuseOrder poolSize acqTimeout maxLifetime maxIdletime reuseOrder scopeParams cont = do+  appName <- generateName "hasql-pool-test-"+  onTaggedPoolWithReuseOrder poolSize acqTimeout maxLifetime maxIdletime reuseOrder appName scopeParams (cont appName)+ onDefaultTaggedPool :: ScopeParams -> (Text -> Pool.Pool -> IO ()) -> IO () onDefaultTaggedPool =   onAutotaggedPool 3 10 1_800 1_800@@ -92,6 +148,7 @@     $ mconcat     $ [ TextBuilder.text prefix,         TextBuilder.decimal uniqueNum1,+        "-",         TextBuilder.decimal uniqueNum2       ] 
src/integration-tests/Helpers/Sessions.hs view
@@ -5,22 +5,24 @@     setSetting,     getSetting,     countConnections,+    sleep,+    backendPid,   ) where  import Data.Tuple.All-import Hasql.Connection qualified as Connection import Hasql.Decoders qualified as Decoders import Hasql.Encoders qualified as Encoders import Hasql.Session qualified as Session import Hasql.Statement qualified as Statement+import Pqi qualified import Prelude  selectOne :: Session.Session Int64 selectOne =   Session.statement () statement   where-    statement = Statement.Statement "SELECT 1" Encoders.noParams decoder True+    statement = Statement.preparable "SELECT 1::int8" Encoders.noParams decoder     decoder = Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8))  badQuery :: Session.Session ()@@ -28,19 +30,20 @@   Session.statement () statement   where     statement =-      Statement.Statement "zzz" Encoders.noParams Decoders.noResult True+      Statement.preparable "zzz" Encoders.noParams Decoders.noResult  closeConn :: Session.Session ()-closeConn = do-  conn <- ask-  liftIO $ Connection.release conn+closeConn =+  Session.onLibpqConnection \conn -> do+    Pqi.finish conn+    pure (Right (), conn)  setSetting :: Text -> Text -> Session.Session () setSetting name value = do   Session.statement (name, value) statement   where     statement =-      Statement.Statement "SELECT set_config($1, $2, false)" encoder Decoders.noResult True+      Statement.preparable "SELECT set_config($1, $2, false)" encoder Decoders.noResult     encoder =       mconcat         [ sel1 >$< Encoders.param (Encoders.nonNullable Encoders.text),@@ -51,7 +54,7 @@ getSetting name = do   Session.statement name statement   where-    statement = Statement.Statement "SELECT current_setting($1, true)" encoder decoder True+    statement = Statement.preparable "SELECT current_setting($1, true)" encoder decoder     encoder = Encoders.param (Encoders.nonNullable Encoders.text)     decoder = Decoders.singleRow (Decoders.column (Decoders.nullable Decoders.text)) @@ -59,6 +62,20 @@ countConnections appName = do   Session.statement appName statement   where-    statement = Statement.Statement "SELECT count(*) FROM pg_stat_activity WHERE application_name = $1" encoder decoder True+    statement = Statement.preparable "SELECT count(*) FROM pg_stat_activity WHERE application_name = $1" encoder decoder     encoder = Encoders.param (Encoders.nonNullable Encoders.text)     decoder = Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8))++sleep :: Double -> Session.Session ()+sleep seconds =+  Session.statement seconds statement+  where+    statement = Statement.preparable "SELECT pg_sleep($1)" encoder Decoders.noResult+    encoder = Encoders.param (Encoders.nonNullable Encoders.float8)++backendPid :: Session.Session Int32+backendPid =+  Session.statement () statement+  where+    statement = Statement.preparable "SELECT pg_backend_pid()" Encoders.noParams decoder+    decoder = Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4))
− src/integration-tests/Specs/BySubject/Config/AgingTimeoutSpec.hs
@@ -1,32 +0,0 @@-module Specs.BySubject.Config.AgingTimeoutSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Actively times out old connections" \scopeParams -> do-    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \_appName1 pool1 -> do-      Scripts.onAutotaggedPool 3 10 0.5 1_800 scopeParams \appName2 pool2 -> do-        res <- use pool2 $ Sessions.selectOne-        res `shouldBe` Right 1-        res2 <- use pool1 $ Sessions.countConnections appName2-        res2 `shouldBe` Right 1-        threadDelay 1_000_000 -- 1s-        res3 <- use pool1 $ Sessions.countConnections appName2-        res3 `shouldBe` Right 0--  it "Passively times out old connections" \scopeParams -> do-    -- 0.5s connection lifetime-    Scripts.onAutotaggedPool 1 10 0.5 1_800 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname-      res <- use pool $ Sessions.setSetting varName "hello world"-      res `shouldBe` Right ()-      res2 <- use pool $ Sessions.getSetting varName-      res2 `shouldBe` Right (Just "hello world")-      threadDelay 1_000_000 -- 1s-      res3 <- use pool $ Sessions.getSetting varName-      res3 `shouldBe` Right Nothing
− src/integration-tests/Specs/BySubject/Config/IdlenessTimeoutSpec.hs
@@ -1,44 +0,0 @@-module Specs.BySubject.Config.IdlenessTimeoutSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Times out old connections (maxIdletime)" \scopeParams -> do-    -- 0.5s connection idle time-    Scripts.onAutotaggedPool 1 10 1_800 0.5 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname-      res <- use pool $ Sessions.setSetting varName "hello world"-      res `shouldBe` Right ()-      res2 <- use pool $ Sessions.getSetting varName-      res2 `shouldBe` Right (Just "hello world")-      -- busy sleep, to keep connection alive-      forM_ [1 :: Int .. 10] $ \_ -> do-        r <- use pool $ Sessions.selectOne-        r `shouldBe` Right 1-        threadDelay 100_000 -- 0.1s-      res3 <- use pool $ Sessions.getSetting varName-      res3 `shouldBe` Right (Just "hello world")-      -- idle sleep, connection times out-      threadDelay 1_000_000 -- 1s-      res4 <- use pool $ Sessions.getSetting varName-      res4 `shouldBe` Right Nothing--  it "Passively times out idle connections" \scopeParams -> do-    -- 0.5s connection idle time, large lifetime, so only idleness can explain a passive close.-    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \_appName1 pool1 -> do-      Scripts.onAutotaggedPool 3 10 1_800 0.5 scopeParams \appName2 pool2 -> do-        res <- use pool2 $ Sessions.selectOne-        res `shouldBe` Right 1-        res2 <- use pool1 $ Sessions.countConnections appName2-        res2 `shouldBe` Right 1-        -- Give the background reaper (1s tick) a chance to passively evict-        -- the now-idle connection, without ever calling `use pool2` again-        -- (which would trigger the separate active idleness check).-        threadDelay 1_500_000 -- 1.5s-        res3 <- use pool1 $ Sessions.countConnections appName2-        res3 `shouldBe` Right 0
− src/integration-tests/Specs/BySubject/Config/InitSessionSpec.hs
@@ -1,59 +0,0 @@-module Specs.BySubject.Config.InitSessionSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Persists after exceptions thrown in session" \scopeParams -> do-    Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname--      res <- use pool do-        Sessions.setSetting varName "1"-        Sessions.getSetting varName-      shouldBe res (Right (Just "1"))--      try @SomeException do-        use pool do-          liftIO do-            throwIO (userError "Intentional error for testing")--      res <- use pool do-        Sessions.getSetting varName-      shouldBe res (Right (Just "1"))--  it "Persists after bad query" \scopeParams -> do-    Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname--      res <- use pool do-        Sessions.setSetting varName "1"-        Sessions.getSetting varName-      shouldBe res (Right (Just "1"))--      use pool do-        Sessions.badQuery--      res <- use pool do-        Sessions.getSetting varName-      shouldBe res (Right (Just "1"))--  -- https://github.com/nikita-volkov/hasql-pool/issues/56-  it "Does not exhaust the pool capacity when it fails" \scopeParams -> do-    -- Pool of size 1 whose init session always fails, with a short-    -- acquisition timeout so that a leaked capacity slot shows up as-    -- an AcquisitionTimeoutUsageError instead of hanging the test.-    Scripts.onAutotaggedPoolWithInitSession 1 1 60 60 Sessions.badQuery scopeParams \_ pool -> do-      res1 <- use pool Sessions.selectOne-      res1 `shouldSatisfy` \case-        Left (SessionUsageError _) -> True-        _ -> False--      res2 <- use pool Sessions.selectOne-      res2 `shouldSatisfy` \case-        Left (SessionUsageError _) -> True-        _ -> False
− src/integration-tests/Specs/BySubject/Helpers/Sessions/CountConnectionsSpec.hs
@@ -1,14 +0,0 @@-module Specs.BySubject.Helpers.Sessions.CountConnectionsSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Counts active connections" \scopeParams -> do-    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \appName pool -> do-      res <- use pool $ Sessions.countConnections appName-      res `shouldBe` Right 1
− src/integration-tests/Specs/BySubject/Helpers/Sessions/GetSettingSpec.hs
@@ -1,36 +0,0 @@-module Specs.BySubject.Helpers.Sessions.GetSettingSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Getting and setting session variables works" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname-      res <- use pool $ Sessions.getSetting varName-      res `shouldBe` Right Nothing-      res <- use pool $ do-        Sessions.setSetting varName "hello world"-        Sessions.getSetting varName-      res `shouldBe` Right (Just "hello world")--  it "Session variables stay set when a connection gets reused" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      varName <- Scripts.generateVarname-      res <- use pool $ Sessions.setSetting varName "hello world"-      res `shouldBe` Right ()-      res2 <- use pool $ Sessions.getSetting varName-      res2 `shouldBe` Right (Just "hello world")--  it "Releasing the pool resets session variables" \scopeParams -> do-    varName <- Scripts.generateVarname-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      res <- use pool $ Sessions.setSetting varName "hello world"-      res `shouldBe` Right ()-      release pool-      res <- use pool $ Sessions.getSetting varName-      res `shouldBe` Right Nothing
− src/integration-tests/Specs/BySubject/ReleaseSpec.hs
@@ -1,16 +0,0 @@-module Specs.BySubject.ReleaseSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "The pool remains usable after release" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      _ <- use pool $ Sessions.selectOne-      release pool-      res <- use pool $ Sessions.selectOne-      shouldSatisfy res $ isRight
− src/integration-tests/Specs/BySubject/SpecHook.hs
@@ -1,11 +0,0 @@--- Docs: https://hspec.github.io/hspec-discover.html-module Specs.BySubject.SpecHook where--import Helpers.Hooks qualified as Hooks-import Helpers.Scripts qualified as Scripts-import Prelude-import Test.Hspec--hook :: SpecWith Scripts.ScopeParams -> Spec-hook =-  aroundAll Hooks.postgres17 . parallel
− src/integration-tests/Specs/BySubject/UsageError/AcquisitionTimeoutSpec.hs
@@ -1,33 +0,0 @@-module Specs.BySubject.UsageError.AcquisitionTimeoutSpec where--import Control.Concurrent.Async (race)-import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Gets produced on timeout" \scopeParams ->-    -- 1ms timeout-    Scripts.onAutotaggedPool 1 0.001 1_800 1_800 scopeParams \_ pool -> do-      sleeping <- newEmptyMVar-      t0 <- getCurrentTime-      res <--        race-          ( use pool-              $ liftIO-              $ do-                putMVar sleeping ()-                -- 1s-                threadDelay 1_000_000-          )-          ( do-              takeMVar sleeping-              use pool $ Sessions.selectOne-          )-      t1 <- getCurrentTime-      res `shouldBe` Right (Left AcquisitionTimeoutUsageError)-      -- 0.5s-      diffUTCTime t1 t0 `shouldSatisfy` (< 0.5)
− src/integration-tests/Specs/BySubject/UsageError/SessionSpec.hs
@@ -1,17 +0,0 @@-module Specs.BySubject.UsageError.SessionSpec where--import Hasql.Pool-import Hasql.Session qualified as Session-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Simulation of connection error works" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      res <- use pool $ Sessions.closeConn >> Sessions.selectOne-      shouldSatisfy res $ \case-        Left (SessionUsageError (Session.QueryError _ _ (Session.ClientError _))) -> True-        _ -> False
− src/integration-tests/Specs/BySubject/UseSpec.hs
@@ -1,40 +0,0 @@-module Specs.BySubject.UseSpec where--import Hasql.Pool-import Helpers.Scripts qualified as Scripts-import Helpers.Sessions qualified as Sessions-import Prelude-import Test.Hspec--spec :: SpecWith Scripts.ScopeParams-spec = do-  it "Releases a spot in the pool when there is a query error" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      use pool Sessions.badQuery `shouldNotReturn` (Right ())-      use pool Sessions.selectOne `shouldReturn` (Right 1)--  it "Connection errors cause eviction of connection" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne-      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne-      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne-      res <- use pool $ Sessions.selectOne-      shouldSatisfy res $ isRight--  it "Connection gets returned to the pool after normal use" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      _ <- use pool $ Sessions.selectOne-      _ <- use pool $ Sessions.selectOne-      _ <- use pool $ Sessions.selectOne-      _ <- use pool $ Sessions.selectOne-      res <- use pool $ Sessions.selectOne-      shouldSatisfy res $ isRight--  it "Connection gets returned to the pool after non-connection error" \scopeParams ->-    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do-      _ <- use pool $ Sessions.badQuery-      _ <- use pool $ Sessions.badQuery-      _ <- use pool $ Sessions.badQuery-      _ <- use pool $ Sessions.badQuery-      res <- use pool $ Sessions.selectOne-      shouldSatisfy res $ isRight
+ src/integration-tests/Specs/Config/AgingTimeoutSpec.hs view
@@ -0,0 +1,32 @@+module Specs.Config.AgingTimeoutSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Actively times out old connections" \scopeParams -> do+    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \_appName1 pool1 -> do+      Scripts.onAutotaggedPool 3 10 0.5 1_800 scopeParams \appName2 pool2 -> do+        res <- use pool2 $ Sessions.selectOne+        res `shouldBe` Right 1+        res2 <- use pool1 $ Sessions.countConnections appName2+        res2 `shouldBe` Right 1+        threadDelay 1_000_000 -- 1s+        res3 <- use pool1 $ Sessions.countConnections appName2+        res3 `shouldBe` Right 0++  it "Passively times out old connections" \scopeParams -> do+    -- 0.5s connection lifetime+    Scripts.onAutotaggedPool 1 10 0.5 1_800 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname+      res <- use pool $ Sessions.setSetting varName "hello world"+      res `shouldBe` Right ()+      res2 <- use pool $ Sessions.getSetting varName+      res2 `shouldBe` Right (Just "hello world")+      threadDelay 1_000_000 -- 1s+      res3 <- use pool $ Sessions.getSetting varName+      res3 `shouldBe` Right Nothing
+ src/integration-tests/Specs/Config/IdlenessTimeoutSpec.hs view
@@ -0,0 +1,62 @@+module Specs.Config.IdlenessTimeoutSpec where++import Hasql.Pool+import Hasql.Pool.Config qualified as Config+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Times out old connections (maxIdletime)" \scopeParams -> do+    -- 0.5s connection idle time+    Scripts.onAutotaggedPool 1 10 1_800 0.5 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname+      res <- use pool $ Sessions.setSetting varName "hello world"+      res `shouldBe` Right ()+      res2 <- use pool $ Sessions.getSetting varName+      res2 `shouldBe` Right (Just "hello world")+      -- busy sleep, to keep connection alive+      forM_ [1 :: Int .. 10] $ \_ -> do+        r <- use pool $ Sessions.selectOne+        r `shouldBe` Right 1+        threadDelay 100_000 -- 0.1s+      res3 <- use pool $ Sessions.getSetting varName+      res3 `shouldBe` Right (Just "hello world")+      -- idle sleep, connection times out+      threadDelay 1_000_000 -- 1s+      res4 <- use pool $ Sessions.getSetting varName+      res4 `shouldBe` Right Nothing++  it "Passively times out idle connections" \scopeParams -> do+    -- 0.5s connection idle time, large lifetime, so only idleness can explain a passive close.+    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \_appName1 pool1 -> do+      Scripts.onAutotaggedPool 3 10 1_800 0.5 scopeParams \appName2 pool2 -> do+        res <- use pool2 $ Sessions.selectOne+        res `shouldBe` Right 1+        res2 <- use pool1 $ Sessions.countConnections appName2+        res2 `shouldBe` Right 1+        -- Give the background reaper (1s tick) a chance to passively evict+        -- the now-idle connection, without ever calling `use pool2` again+        -- (which would trigger the separate active idleness check).+        threadDelay 1_500_000 -- 1.5s+        res3 <- use pool1 $ Sessions.countConnections appName2+        res3 `shouldBe` Right 0++  it "Times out the connections that aren't needed with LIFO" \scopeParams -> do+    -- 0.5s connection idle time+    Scripts.onAutotaggedPoolWithReuseOrder 2 10 1_800 0.5 Config.LIFO scopeParams \appName pool -> do+      held <- newEmptyMVar+      done <- newEmptyMVar+      -- Establish two connections.+      _ <- forkIO (void (use pool (liftIO (putMVar held () *> takeMVar done))))+      takeMVar held+      use pool Sessions.selectOne `shouldReturn` Right 1+      putMVar done ()+      -- Keep using the pool one pool request at a time, which needs only one+      -- connection, for longer than the idle time and the reaper's 1s tick.+      forM_ [1 :: Int .. 15] \_ -> do+        use pool Sessions.selectOne `shouldReturn` Right 1+        threadDelay 100_000 -- 0.1s+      use pool (Sessions.countConnections appName) `shouldReturn` Right 1
+ src/integration-tests/Specs/Config/InitSessionSpec.hs view
@@ -0,0 +1,62 @@+module Specs.Config.InitSessionSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Does not persist after exceptions thrown in session" \scopeParams -> do+    Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname++      res <- use pool do+        Sessions.setSetting varName "1"+        Sessions.getSetting varName+      shouldBe res (Right (Just "1"))++      try @SomeException do+        use pool do+          liftIO do+            throwIO (userError "Intentional error for testing")++      -- An asynchronous exception out of a session always spends the+      -- connection, so the pool hands out a fresh one here and the+      -- setting from before the exception is gone.+      res <- use pool do+        Sessions.getSetting varName+      shouldBe res (Right Nothing)++  it "Persists after bad query" \scopeParams -> do+    Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname++      res <- use pool do+        Sessions.setSetting varName "1"+        Sessions.getSetting varName+      shouldBe res (Right (Just "1"))++      use pool do+        Sessions.badQuery++      res <- use pool do+        Sessions.getSetting varName+      shouldBe res (Right (Just "1"))++  -- https://github.com/nikita-volkov/hasql-pool/issues/56+  it "Does not exhaust the pool capacity when it fails" \scopeParams -> do+    -- Pool of size 1 whose init session always fails, with a short+    -- acquisition timeout so that a leaked capacity slot shows up as+    -- an AcquisitionTimeoutUsageError instead of hanging the test.+    Scripts.onAutotaggedPoolWithInitSession 1 1 60 60 Sessions.badQuery scopeParams \_ pool -> do+      res1 <- use pool Sessions.selectOne+      res1 `shouldSatisfy` \case+        Left (SessionUsageError _) -> True+        _ -> False++      res2 <- use pool Sessions.selectOne+      res2 `shouldSatisfy` \case+        Left (SessionUsageError _) -> True+        _ -> False
+ src/integration-tests/Specs/ConnectionDiscardsSpec.hs view
@@ -0,0 +1,183 @@+-- | Reachability and recovery coverage for+-- 'Hasql.Pool.ConnectionDiscards'.+--+-- The verdicts themselves are pure functions of a SQLSTATE and are pinned by+-- the @unit-tests@ suite, which needs no server. What only a live server can+-- establish is the two things asserted here:+--+-- * that the code in question actually reaches the predicate as a+--   'Errors.SessionUseError', rather than arriving as a+--   'Errors.ConnectionUseError' the pool discards without consulting the+--   module at all, and+--+-- * that the discard restores service - the residue really was+--   connection-local, and a fresh connection runs the same statement+--   successfully.+--+-- Every test therefore runs against a pool of size 1, so "the next use" is+-- guaranteed to be either the same connection or its replacement.+module Specs.ConnectionDiscardsSpec where++import Data.IORef qualified as IORef+import Data.Text qualified as Text+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Errors qualified as Errors+import Hasql.Pool+import Hasql.Pool.Observation qualified as Observation+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  -- XX000. The server notices the retired type OID while replanning the+  -- prepared statement and raises @cache lookup failed for type NNNN@, which+  -- repeats on every subsequent execution over that connection.+  it "Discards a connection whose prepared statement references a recreated type" \scopeParams -> do+    typeName <- Text.replace "-" "_" <$> Scripts.generateName "cached_type_"+    onSingleConnectionPool scopeParams \pool -> do+      use pool (Session.script (createTypeSql typeName)) `shouldReturn` Right ()+      use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"+      use pool (Session.script (recreateTypeSql typeName)) `shouldReturn` Right ()+      shouldFailWithSessionError (use pool (roundtripEnum typeName "ok"))+      use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"++  -- 0A000, @cached plan must not change result type@. The prepared plan for+  -- @select *@ was built against one column; adding a second one invalidates+  -- it permanently for this connection.+  it "Discards a connection whose prepared plan outlived the shape of its result" \scopeParams -> do+    tableName <- Text.replace "-" "_" <$> Scripts.generateName "cached_plan_"+    onSingleConnectionPool scopeParams \pool -> do+      use pool (Session.script ("create table " <> quoteIdentifier tableName <> " (a int8)"))+        `shouldReturn` Right ()+      use pool (selectStar tableName) `shouldReturn` Right ()+      use pool (Session.script ("alter table " <> quoteIdentifier tableName <> " add column b int8"))+        `shouldReturn` Right ()+      shouldFailWithSessionError (use pool (selectStar tableName))+      -- The replacement connection replans against the new shape, so the+      -- one-column decoder now genuinely mismatches. That it fails+      -- \*differently* is the point: the plan-cache residue is gone.+      use pool (selectTwoColumns tableName) `shouldReturn` Right ()++  -- 26000, @prepared statement "..." does not exist@. Hasql's statement+  -- cache still lists the name; the server no longer does, and nothing+  -- evicts the stale entry.+  it "Discards a connection whose statement cache outlived the server's prepared statements" \scopeParams ->+    onSingleConnectionPool scopeParams \pool -> do+      use pool Sessions.selectOne `shouldReturn` Right 1+      use pool (Session.script "deallocate all") `shouldReturn` Right ()+      shouldFailWithSessionError (use pool Sessions.selectOne)+      use pool Sessions.selectOne `shouldReturn` Right 1++  -- 25P02. Note the sequencing: the statement that aborts the transaction+  -- fails with a syntax error, which is correctly *retained* - the residue+  -- only becomes visible on the following use, which is the one that+  -- triggers the discard.+  it "Discards a connection left parked in an aborted transaction" \scopeParams ->+    onSingleConnectionPool scopeParams \pool -> do+      shouldFailWithSessionError (use pool (Session.script "begin" >> Sessions.badQuery))+      shouldFailWithSessionError (use pool Sessions.selectOne)+      use pool Sessions.selectOne `shouldReturn` Right 1++  -- 57P01. Terminating the backend underneath a session is announced with a+  -- genuine FATAL error result, so hasql reports it as a+  -- 'Errors.ConnectionUseError' carrying an 'Errors.ServerConnectionError'+  -- with the SQLSTATE intact - never as a server error reaching+  -- 'ConnectionDiscards.serverError'. The @57P@ rule is therefore dead for+  -- this code, and is kept only because the rest of the class has not been+  -- shown to behave the same way. The pool must discard the connection and+  -- establish a replacement, which the size-1 pool makes observable. Its+  -- termination observation must preserve the structured server error too.+  it "Recovers from a backend terminated underneath it and observes its error" \scopeParams -> do+    observations <- IORef.newIORef []+    let observe observation =+          IORef.atomicModifyIORef' observations \recorded ->+            (observation : recorded, ())+    Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 1_800 observe scopeParams \_ pool -> do+      use pool Sessions.selectOne `shouldReturn` Right 1+      terminated <- use pool terminateSelf+      terminated `shouldSatisfy` \case+        Left (SessionUsageError (Errors.ConnectionUseError connectionError)) ->+          Errors.toSqlState connectionError == Just "57P01"+        _ -> False+      use pool Sessions.selectOne `shouldReturn` Right 1+    recorded <- IORef.readIORef observations+    recorded `shouldSatisfy` any hasStructuredTerminationError++hasStructuredTerminationError :: Observation.Observation -> Bool+hasStructuredTerminationError = \case+  Observation.ConnectionObservation _ (Observation.TerminatedConnectionStatus (Observation.NetworkErrorConnectionTerminationReason (Errors.ServerConnectionError serverError))) ->+    Errors.toSqlState serverError == Just "57P01"+  _ ->+    False++onSingleConnectionPool :: Scripts.ScopeParams -> (Pool -> IO ()) -> IO ()+onSingleConnectionPool scopeParams cont =+  Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams (const cont)++shouldFailWithSessionError :: (Show a) => IO (Either UsageError a) -> Expectation+shouldFailWithSessionError action = do+  res <- action+  shouldSatisfy res \case+    Left (SessionUsageError _) -> True+    _ -> False++quoteIdentifier :: Text -> Text+quoteIdentifier identifier =+  "\"" <> Text.replace "\"" "\"\"" identifier <> "\""++createTypeSql :: Text -> Text+createTypeSql typeName =+  "create type " <> quoteIdentifier typeName <> " as enum ('sad', 'ok', 'happy')"++recreateTypeSql :: Text -> Text+recreateTypeSql typeName =+  "drop type "+    <> quoteIdentifier typeName+    <> "; create type "+    <> quoteIdentifier typeName+    <> " as enum ('sad', 'ok', 'happy')"++roundtripEnum :: Text -> Text -> Session.Session Text+roundtripEnum typeName value =+  Session.statement value statement+  where+    statement =+      Statement.preparable+        ("select $1 :: " <> quoteIdentifier typeName)+        (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing typeName id)))+        (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing typeName Just))))++selectStar :: Text -> Session.Session ()+selectStar tableName =+  Session.statement () statement+  where+    statement =+      Statement.preparable+        ("select * from " <> quoteIdentifier tableName)+        Encoders.noParams+        (Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.int8)) $> ())++selectTwoColumns :: Text -> Session.Session ()+selectTwoColumns tableName =+  Session.statement () statement+  where+    statement =+      Statement.preparable+        ("select * from " <> quoteIdentifier tableName)+        Encoders.noParams+        ( Decoders.rowList+            ( (,)+                <$> Decoders.column (Decoders.nonNullable Decoders.int8)+                <*> Decoders.column (Decoders.nonNullable Decoders.int8)+            )+            $> ()+        )++terminateSelf :: Session.Session ()+terminateSelf =+  Session.script "select pg_terminate_backend(pg_backend_pid())"
+ src/integration-tests/Specs/Helpers/Sessions/CountConnectionsSpec.hs view
@@ -0,0 +1,14 @@+module Specs.Helpers.Sessions.CountConnectionsSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Counts active connections" \scopeParams -> do+    Scripts.onAutotaggedPool 3 10 1_800 1_800 scopeParams \appName pool -> do+      res <- use pool $ Sessions.countConnections appName+      res `shouldBe` Right 1
+ src/integration-tests/Specs/Helpers/Sessions/GetSettingSpec.hs view
@@ -0,0 +1,36 @@+module Specs.Helpers.Sessions.GetSettingSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Getting and setting session variables works" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname+      res <- use pool $ Sessions.getSetting varName+      res `shouldBe` Right Nothing+      res <- use pool $ do+        Sessions.setSetting varName "hello world"+        Sessions.getSetting varName+      res `shouldBe` Right (Just "hello world")++  it "Session variables stay set when a connection gets reused" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      varName <- Scripts.generateVarname+      res <- use pool $ Sessions.setSetting varName "hello world"+      res `shouldBe` Right ()+      res2 <- use pool $ Sessions.getSetting varName+      res2 `shouldBe` Right (Just "hello world")++  it "Releasing the pool resets session variables" \scopeParams -> do+    varName <- Scripts.generateVarname+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      res <- use pool $ Sessions.setSetting varName "hello world"+      res `shouldBe` Right ()+      release pool+      res <- use pool $ Sessions.getSetting varName+      res `shouldBe` Right Nothing
+ src/integration-tests/Specs/InterruptionSpec.hs view
@@ -0,0 +1,163 @@+module Specs.InterruptionSpec where++import Control.Exception (SomeException, try)+import Hasql.Pool+import Hasql.Pool qualified as Pool+import Hasql.Pool.Config qualified as Config+import Hasql.Pool.Observation+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++-- | Regression tests for the pool capacity getting lost when a pool request+-- gets interrupted anywhere between the enrollment and the session+-- (https://github.com/nikita-volkov/hasql-pool/issues/60), and for the pool+-- surviving failing observation handlers.+spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Restores the pool capacity when the pool request is interrupted while observing the connection attempt" \scopeParams ->+    onGatedPool connectingObs 1 10 1_800 1_800 scopeParams \gate pool -> do+      interruptAt gate (\pool -> void (use pool Sessions.selectOne)) pool+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Restores the pool capacity when the pool request is interrupted while observing the idle-eviction" \scopeParams ->+    onGatedPool idleEvictionObs 1 10 1_800 0.3 scopeParams \gate pool -> do+      -- Establish a connection and let it go idle.+      _ <- use pool Sessions.selectOne+      threadDelay 600_000 -- 0.6s+      interruptAt gate (\pool -> void (use pool Sessions.selectOne)) pool+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Preserves the dequeued connection when the pool request is interrupted while observing its use" \scopeParams ->+    onGatedPool inUseObs 1 10 1_800 1_800 scopeParams \gate pool -> do+      -- Establish a connection and return it to the pool.+      _ <- use pool Sessions.selectOne+      interruptAt gate (\pool -> void (use pool Sessions.selectOne)) pool+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Succeeds the session when the observation handler throws synchronously during the connection attempt" \scopeParams ->+    Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 1_800 (throwAt connectingObs) scopeParams \_ pool -> do+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Succeeds the session when the observation handler throws synchronously during the idle-eviction" \scopeParams ->+    Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 0.3 (throwAt idleEvictionObs) scopeParams \_ pool -> do+      _ <- use pool Sessions.selectOne+      threadDelay 600_000 -- 0.6s+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Succeeds the session when the observation handler throws synchronously while observing the use" \scopeParams ->+    Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 1_800 (throwAt inUseObs) scopeParams \_ pool -> do+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "The reaper survives a throwing observation handler and keeps reaping on later ticks" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ counterPool ->+      Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 0.3 (throwAt idleEvictionObs) scopeParams \appName pool -> do+        -- Establish a connection and let it go idle past the reaper's tick.+        _ <- use pool Sessions.selectOne+        threadDelay 1_600_000 -- 1.6s+        -- The connection got reaped and the reaper is still alive.+        use counterPool (Sessions.countConnections appName) `shouldReturn` Right 0+        use pool Sessions.selectOne `shouldReturn` Right 1+        -- It keeps reaping on the later ticks.+        threadDelay 1_600_000 -- 1.6s+        use counterPool (Sessions.countConnections appName) `shouldReturn` Right 0++  it "The pool remains usable after the release with a throwing observation handler" \scopeParams ->+    Scripts.onAutotaggedPoolWithObservationHandler 1 10 1_800 1_800 (throwAt releaseObs) scopeParams \_ pool -> do+      _ <- use pool Sessions.selectOne+      release pool+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Resolves the pool requests waiting on a garbage-collected pool" \scopeParams -> do+    (adapter, host, port) <- pure scopeParams+    result <- newEmptyMVar+    -- Inside this block the pool is only reachable from the waiting pool+    -- request. Once collected, the finalizer resolves it, and if it is not+    -- collectible, the acquisition timeout does. Either way it does not wait+    -- forever.+    do+      pool <-+        Pool.acquire+          adapter+          ( Config.settings+              [ -- No capacity: every pool request waits.+                Config.size 0,+                Config.acquisitionTimeout 0.5+              ]+          )+      _ <- forkIO (putMVar result =<< use pool Sessions.selectOne)+      threadDelay 100_000 -- 0.1s, to let the pool request start waiting+      pure ()+    performGC+    performGC+    res <- takeMVar result+    res `shouldBe` Left AcquisitionTimeoutUsageError++-- | Runs the action in a pool request interrupted at the gated observation.+-- The pool request is expected to die with the interruption.+interruptAt :: Gate -> (Pool.Pool -> IO ()) -> Pool.Pool -> IO ()+interruptAt gate action pool = do+  armGate gate+  done <- newEmptyMVar+  thread <- forkIO do+    _ <- try @SomeException (action pool)+    putMVar done ()+  takeMVar (gateEntered gate)+  killThread thread+  disarmGate gate+  takeMVar done++-- | Runs the continuation in a pool with a gated observation handler.+onGatedPool :: (Observation -> Bool) -> Int -> DiffTime -> DiffTime -> DiffTime -> Scripts.ScopeParams -> (Gate -> Pool.Pool -> IO ()) -> IO ()+onGatedPool matches poolSize acqTimeout maxLifetime maxIdletime scopeParams cont = do+  gate <- newGate matches+  Scripts.onAutotaggedPoolWithObservationHandler poolSize acqTimeout maxLifetime maxIdletime (gateHandler gate) scopeParams \appName pool -> cont gate pool++-- | A gate for stopping a pool request at a chosen observation and letting the+-- test interrupt it there. While the gate is armed, the pool request stops at+-- the first matching observation, waiting to be released or interrupted.+data Gate = Gate+  { gateMatches :: Observation -> Bool,+    gateEntered :: MVar (),+    gateProceed :: MVar (),+    gateArmed :: IORef Bool+  }++newGate :: (Observation -> Bool) -> IO Gate+newGate matches = Gate matches <$> newEmptyMVar <*> newEmptyMVar <*> newIORef False++armGate, disarmGate :: Gate -> IO ()+armGate gate = writeIORef (gateArmed gate) True+disarmGate gate = writeIORef (gateArmed gate) False++-- | The observation handler stopping at the gate.+gateHandler :: Gate -> Observation -> IO ()+gateHandler gate observation =+  when (gateMatches gate observation) do+    armed <- readIORef (gateArmed gate)+    when armed do+      putMVar (gateEntered gate) ()+      takeMVar (gateProceed gate)++-- | The observations the tests stop or throw at.+connectingObs, idleEvictionObs, inUseObs, releaseObs :: Observation -> Bool+connectingObs = \case+  ConnectionObservation _ ConnectingConnectionStatus -> True+  _ -> False+idleEvictionObs = \case+  ConnectionObservation _ (TerminatedConnectionStatus IdlenessConnectionTerminationReason) -> True+  _ -> False+inUseObs = \case+  ConnectionObservation _ InUseConnectionStatus -> True+  _ -> False+releaseObs = \case+  ConnectionObservation _ (TerminatedConnectionStatus ReleaseConnectionTerminationReason) -> True+  _ -> False++-- | An observation handler that throws synchronously at the matching+-- observations, and passes all the other observations through.+throwAt :: (Observation -> Bool) -> Observation -> IO ()+throwAt matches observation =+  when (matches observation) do+    error "Synchronous exception from the observation handler"
+ src/integration-tests/Specs/ReleaseSpec.hs view
@@ -0,0 +1,16 @@+module Specs.ReleaseSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "The pool remains usable after release" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      _ <- use pool $ Sessions.selectOne+      release pool+      res <- use pool $ Sessions.selectOne+      shouldSatisfy res $ isRight
+ src/integration-tests/Specs/SpecHook.hs view
@@ -0,0 +1,15 @@+-- Docs: https://hspec.github.io/hspec-discover.html+module Specs.SpecHook where++import Helpers.Adapters qualified as Adapters+import Helpers.Hooks qualified as Hooks+import Helpers.Scripts qualified as Scripts+import Test.Hspec++hook :: SpecWith Scripts.ScopeParams -> Spec+hook hookedSpec =+  Adapters.hook+    ( aroundAllWith+        (\action adapter -> Hooks.postgres17 \(host, port) -> action (adapter, host, port))+        (parallel hookedSpec)+    )
+ src/integration-tests/Specs/UsageError/AcquisitionTimeoutSpec.hs view
@@ -0,0 +1,45 @@+module Specs.UsageError.AcquisitionTimeoutSpec where++import Control.Concurrent.Async (forConcurrently, race)+import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Gets produced on timeout" \scopeParams ->+    -- 1ms timeout+    Scripts.onAutotaggedPool 1 0.001 1_800 1_800 scopeParams \_ pool -> do+      sleeping <- newEmptyMVar+      t0 <- getCurrentTime+      res <-+        race+          ( use pool+              $ liftIO+              $ do+                putMVar sleeping ()+                -- 1s+                threadDelay 1_000_000+          )+          ( do+              takeMVar sleeping+              use pool $ Sessions.selectOne+          )+      t1 <- getCurrentTime+      res `shouldBe` Right (Left AcquisitionTimeoutUsageError)+      -- 0.5s+      diffUTCTime t1 t0 `shouldSatisfy` (< 0.5)++  it "Gets produced for every waiting pool request, and the pool remains usable" \scopeParams ->+    -- 100ms timeout+    Scripts.onAutotaggedPool 1 0.1 1_800 1_800 scopeParams \_ pool -> do+      held <- newEmptyMVar+      done <- newEmptyMVar+      _ <- forkIO (void (use pool (liftIO (putMVar held () *> takeMVar done))))+      takeMVar held+      results <- forConcurrently [1 .. 3 :: Int] \_ -> use pool Sessions.selectOne+      results `shouldBe` replicate 3 (Left AcquisitionTimeoutUsageError)+      putMVar done ()+      use pool Sessions.selectOne `shouldReturn` Right 1
+ src/integration-tests/Specs/UsageError/SessionSpec.hs view
@@ -0,0 +1,16 @@+module Specs.UsageError.SessionSpec where++import Hasql.Pool+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Bad SQL query triggers error" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      res <- use pool Sessions.badQuery+      shouldSatisfy res $ \case+        Left (SessionUsageError _) -> True+        _ -> False
+ src/integration-tests/Specs/UseSpec.hs view
@@ -0,0 +1,254 @@+module Specs.UseSpec where++import Control.Concurrent.Async (race)+import Data.Text qualified as Text+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Errors qualified as Errors+import Hasql.Pool+import Hasql.Pool.Config qualified as Config+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  it "Releases a spot in the pool when there is a query error" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      use pool Sessions.badQuery `shouldNotReturn` (Right ())+      use pool Sessions.selectOne `shouldReturn` (Right 1)++  it "Connection errors cause eviction of connection" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne+      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne+      _ <- use pool $ Sessions.closeConn >> Sessions.selectOne+      res <- use pool $ Sessions.selectOne+      shouldSatisfy res $ isRight++  it "Driver errors cause eviction of connection" \scopeParams -> do+    settingName <- Scripts.generateVarname+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      use pool (Sessions.setSetting settingName "present") `shouldReturn` Right ()+      result <- use pool driverError+      result `shouldSatisfy` \case+        Left (SessionUsageError (Errors.ConnectionUseError _)) -> True+        _ -> False+      use pool (Sessions.getSetting settingName) `shouldReturn` Right Nothing++  -- After a server restart or @pg_terminate_backend@ the first statement on+  -- the closed connection used to fail with a catchable+  -- 'Errors.UnexpectedRowCountStatementError' or server error instead of a+  -- 'Errors.ConnectionUseError'; hasql now classifies the loss as+  -- connection-fatal on every receive. Either way the pool must not hand+  -- the connection out again.+  it "Connections closed by the server cause eviction of connection" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \appName pool -> do+      use pool Sessions.selectOne `shouldReturn` Right 1+      Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ adminPool ->+        use adminPool (terminateBackends appName) `shouldReturn` Right [True]+      _ <- use pool Sessions.selectOne+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Unexpected row counts on a healthy connection don't cause eviction of connection" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      Right pid <- use pool backendPid+      result <- use pool selectTwoRowsAsSingleRow+      result `shouldSatisfy` \case+        Left (SessionUsageError (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ Errors.UnexpectedRowCountStatementError {}))) -> True+        _ -> False+      use pool backendPid `shouldReturn` Right pid++  it "Connection gets returned to the pool after normal use" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      _ <- use pool $ Sessions.selectOne+      _ <- use pool $ Sessions.selectOne+      _ <- use pool $ Sessions.selectOne+      _ <- use pool $ Sessions.selectOne+      res <- use pool $ Sessions.selectOne+      shouldSatisfy res $ isRight++  it "Connection gets returned to the pool after non-connection error" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      _ <- use pool $ Sessions.badQuery+      _ <- use pool $ Sessions.badQuery+      _ <- use pool $ Sessions.badQuery+      _ <- use pool $ Sessions.badQuery+      res <- use pool $ Sessions.selectOne+      shouldSatisfy res $ isRight++  -- https://github.com/nikita-volkov/hasql-pool/issues/38+  --+  -- When a session is interrupted by an asynchronous exception (e.g., a+  -- caller-side timeout racing the query, as simulated here via `race`)+  -- while it is genuinely blocked waiting on the server's response, the+  -- underlying libpq connection is left mid-command: the query was sent,+  -- but its result was never read. `onLiveConn` in Hasql.Pool.use still+  -- unconditionally returns such a connection to the pool (the `Left exc`+  -- branch calls `returnConn` for all exceptions, not just synchronous+  -- ones), so the next `use` call hands out a connection whose protocol+  -- state is desynced from libpq's expectations. This is a plausible root+  -- cause of the "connection pointer is NULL" reports: two independent+  -- consumers of hasql-pool end up driving the same libpq connection state+  -- machine without coordination.+  it "Does not return a connection to the pool when the session is interrupted by an asynchronous exception" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      started <- newEmptyMVar+      _ <-+        race+          ( use pool do+              liftIO $ putMVar started ()+              Sessions.sleep 2+          )+          ( do+              takeMVar started+              -- Give the query time to actually reach the server and for+              -- the client to start blocking on the socket read, as+              -- opposed to being cancelled while still sending.+              threadDelay 200_000+          )+      res <- use pool Sessions.selectOne+      res `shouldSatisfy` isRight++  it "Gives a freed connection to a pool request waiting for it rather than to a later one" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      order <- newIORef []+      held <- newEmptyMVar+      done <- newEmptyMVar+      finished <- newEmptyMVar+      let record name = use pool (liftIO (atomicModifyIORef' order \names -> (names <> [name], ())))+      -- Requests a connection again as soon as it returns one, before the+      -- waiting pool request gets to run.+      _ <- forkIO do+        _ <- use pool (liftIO (putMVar held () *> takeMVar done))+        _ <- record "later"+        putMVar finished ()+      takeMVar held+      _ <- forkIO (record "waiting" *> putMVar finished ())+      -- Give the waiting pool request time to start waiting.+      threadDelay 100_000+      putMVar done ()+      replicateM_ 2 (takeMVar finished)+      readIORef order `shouldReturn` ["waiting", "later"]++  it "Loses no capacity when a pool request waiting for a connection is interrupted" \scopeParams ->+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      held <- newEmptyMVar+      done <- newEmptyMVar+      _ <- forkIO (void (use pool (liftIO (putMVar held () *> takeMVar done))))+      takeMVar held+      waiting <- forkIO (void (use pool Sessions.selectOne))+      -- Give the pool request time to start waiting.+      threadDelay 100_000+      killThread waiting+      putMVar done ()+      use pool Sessions.selectOne `shouldReturn` Right 1++  it "Reuses the most recently returned connection with LIFO" \scopeParams ->+    Scripts.onAutotaggedPoolWithReuseOrder 2 10 1_800 1_800 Config.LIFO scopeParams \_ pool -> do+      (first, second) <- returnTwoConnections pool+      first `shouldNotBe` second+      use pool Sessions.backendPid `shouldReturn` Right second++  it "Reuses the least recently returned connection by default" \scopeParams ->+    Scripts.onAutotaggedPool 2 10 1_800 1_800 scopeParams \_ pool -> do+      (first, second) <- returnTwoConnections pool+      first `shouldNotBe` second+      use pool Sessions.backendPid `shouldReturn` Right first++  it "Cached type errors cause eviction of connection" \scopeParams -> do+    typeName <- Text.replace "-" "_" <$> Scripts.generateName "cached_type_"+    Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams \_ pool -> do+      use pool (Session.script (createTypeSql typeName)) `shouldReturn` Right ()+      use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"+      use pool (Session.script (recreateTypeSql typeName)) `shouldReturn` Right ()+      res <- use pool (roundtripEnum typeName "ok")+      shouldSatisfy res \case+        Left (SessionUsageError _) -> True+        _ -> False+      use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"++quoteIdentifier :: Text -> Text+quoteIdentifier identifier =+  "\"" <> Text.replace "\"" "\"\"" identifier <> "\""++createTypeSql :: Text -> Text+createTypeSql typeName =+  "create type " <> quotedTypeName <> " as enum ('sad', 'ok', 'happy')"+  where+    quotedTypeName = quoteIdentifier typeName++recreateTypeSql :: Text -> Text+recreateTypeSql typeName =+  "drop type " <> quotedTypeName <> "; create type " <> quotedTypeName <> " as enum ('sad', 'ok', 'happy')"+  where+    quotedTypeName = quoteIdentifier typeName++roundtripEnum :: Text -> Text -> Session.Session Text+roundtripEnum typeName value =+  Session.statement value statement+  where+    statement =+      Statement.preparable+        ("select $1 :: " <> quoteIdentifier typeName)+        (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing typeName id)))+        (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing typeName Just))))++terminateBackends :: Text -> Session.Session [Bool]+terminateBackends appName =+  Session.statement appName statement+  where+    statement =+      Statement.unpreparable+        "select pg_terminate_backend(pid, 10000) from pg_stat_activity where application_name = $1"+        (Encoders.param (Encoders.nonNullable Encoders.text))+        (Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.bool)))++backendPid :: Session.Session Int32+backendPid =+  Session.statement () statement+  where+    statement =+      Statement.preparable+        "select pg_backend_pid()"+        Encoders.noParams+        (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++selectTwoRowsAsSingleRow :: Session.Session Int64+selectTwoRowsAsSingleRow =+  Session.statement () statement+  where+    statement =+      Statement.preparable+        "select * from (values (1 :: int8), (2 :: int8)) as t"+        Encoders.noParams+        (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))++driverError :: Session.Session ()+driverError =+  Session.onLibpqConnection \connection ->+    pure (Left (Errors.ConnectionUseError (Errors.LocalConnectionError "synthetic driver error")), connection)++-- | Establish two connections, return the first before the second, and give+-- their backend PIDs.+returnTwoConnections :: Pool -> IO (Int32, Int32)+returnTwoConnections pool = do+  held <- newEmptyMVar+  done <- newEmptyMVar+  returned <- newEmptyMVar+  _ <- forkIO do+    res <- use pool (Sessions.backendPid <* liftIO (putMVar held () *> takeMVar done))+    putMVar returned res+  takeMVar held+  res <- use pool do+    second <- Sessions.backendPid+    first <- liftIO do+      putMVar done ()+      takeMVar returned+    pure (first, second)+  case res of+    Right (Right first, second) -> pure (first, second)+    _ -> fail ("Unexpected result: " <> show res)
+ src/library/Hasql/Pool.hs view
@@ -0,0 +1,523 @@+module Hasql.Pool+  ( -- * Pool+    Pool,+    acquire,+    use,+    release,++    -- * Errors+    UsageError (..),+  )+where++import Data.Text qualified as Text+import Data.UUID.V4 qualified as Uuid+import Hasql.Connection (Connection)+import Hasql.Connection qualified as Connection+import Hasql.Connection.Settings qualified as Connection.Settings+import Hasql.Errors qualified as Errors+import Hasql.Pool.Config.Config qualified as Config+import Hasql.Pool.Config.ReuseOrder (ReuseOrder (..))+import Hasql.Pool.ConnectionDiscards qualified as ConnectionDiscards+import Hasql.Pool.Observation+import Hasql.Pool.Prelude+import Hasql.Session qualified as Session+import Pqi qualified++-- | A connection tagged with metadata.+data Entry = Entry+  { entryConnection :: Connection,+    entryCreationTimeNSec :: Word64,+    entryUseTimeNSec :: Word64,+    entryId :: UUID+  }++entryIsAged :: Word64 -> Word64 -> Entry -> Bool+entryIsAged maxLifetime now Entry {..} =+  now > entryCreationTimeNSec + maxLifetime++entryIsIdle :: Word64 -> Word64 -> Entry -> Bool+entryIsIdle maxIdletime now Entry {..} =+  now > entryUseTimeNSec + maxIdletime++-- | A pool request waiting for a connection.+data Waiter = Waiter+  { -- | When the pool request times out, in nanoseconds of the monotonic clock.+    waiterDeadline :: Word64,+    -- | What the pool request gets.+    waiterGiven :: TMVar Given,+    -- | Whether the pool request stopped waiting, so that it gets passed over.+    waiterGone :: TVar Bool+  }++-- | What a waiting pool request gets: an idle connection, or the slot of a+-- closed one to establish a connection in, with the reuse flag at the time,+-- or a timeout.+data Given+  = Given (TVar Bool) (Maybe Entry)+  | TimedOut++-- | What a pool request holds after the enrollment transaction commits and+-- has to give back on any failure.+data Holding+  = -- | An entry dequeued from the idle connections.+    EntryHolding (TVar Bool) Entry+  | -- | A capacity unit taken from the pool.+    SlotHolding (TVar Bool)+  | -- | A spot in the waiting queue.+    WaitingHolding Waiter++-- | Pool of connections to DB.+data Pool = Pool+  { -- | Pool size.+    poolSize :: Int,+    -- | Adapter used to establish connections.+    poolAdapter :: Pqi.Adapter,+    -- | Connection settings.+    poolFetchConnectionSettings :: IO Connection.Settings.Settings,+    -- | Acquisition timeout, in nanoseconds.+    poolAcquisitionTimeout :: Word64,+    -- | Maximal connection lifetime, in nanoseconds.+    poolMaxLifetime :: Word64,+    -- | Maximal connection idle time, in nanoseconds.+    poolMaxIdletime :: Word64,+    -- | Avail connections, in the order they get reused.+    poolConnectionQueue :: TQueue Entry,+    -- | Which end of the queue returned connections go to.+    poolReuseOrder :: ReuseOrder,+    -- | Remaining capacity.+    -- The pool size limits the sum of poolCapacity, the length+    -- of poolConnectionQueue and the number of in-flight+    -- connections.+    poolCapacity :: TVar Int,+    -- | Pool requests waiting for a connection, the longest waiting first.+    -- Freed connections and slots go to them before anyone else,+    -- so that only the pool request given one wakes up.+    poolWaiting :: TQueue Waiter,+    -- | Whether to return a connection to the pool.+    poolReuseVar :: TVar (TVar Bool),+    -- | To stop the manager and expirer threads via garbage collection.+    poolReaperRef :: IORef (),+    -- | Action for reporting the observations.+    poolObserver :: Observation -> IO (),+    -- | Initial session to execute upon every established connection.+    poolInitSession :: Session.Session ()+  }++-- | Contain the failures of the user-supplied observation handler. Synchronous+-- exceptions from it are discarded, asynchronous ones are honored, so that+-- neither affects the pool's state or the session result, and the pool's+-- threads stay killable.+containObserver :: (Observation -> IO ()) -> Observation -> IO ()+containObserver observer observation =+  catch @SomeException (observer observation) \exc ->+    case fromException exc of+      Just SomeAsyncException {} -> throwIO exc+      Nothing -> return ()++-- | Create a connection-pool.+--+-- No connections actually get established by this function. It is delegated+-- to 'use'.+--+-- If you want to ensure that the pool connects fine at the initialization phase, just run 'use' with an empty session (@pure ()@) and check for errors.+--+-- The 'Pqi.Adapter' determines which connection implementation the pool uses, e.g. an FFI adapter backed by @postgresql-libpq@, or a pure Haskell one. Pick one from an adapter package such as @pqi-ffi@ or @pqi-native@.+acquire :: Pqi.Adapter -> Config.Config -> IO Pool+acquire adapter config = do+  connectionQueue <- newTQueueIO+  capVar <- newTVarIO (Config.size config)+  reuseVar <- newTVarIO =<< newTVarIO True+  waiting <- newTQueueIO+  reaperRef <- newIORef ()+  let observer = containObserver (Config.observationHandler config)++  managerTid <- forkIOWithUnmask $ \unmask -> unmask $ forever $ do+    threadDelay 1000000+    now <- getMonotonicTimeNSec+    join . atomically $ do+      entries <- flushTQueue connectionQueue+      let (agedEntries, unagedEntries) = partition (entryIsAged agingTimeoutNanos now) entries+          (idleEntries, liveEntries) = partition (entryIsIdle maxIdletimeNanos now) unagedEntries+      traverse_ (writeTQueue connectionQueue) liveEntries+      return $ do+        forM_ agedEntries $ reap observer reuseVar waiting capVar AgingConnectionTerminationReason+        forM_ idleEntries $ reap observer reuseVar waiting capVar IdlenessConnectionTerminationReason++  expirerTid <- forkIOWithUnmask $ \unmask -> unmask $ expire waiting++  void . mkWeakIORef reaperRef $ do+    -- When the pool goes out of scope, resolve the pool requests still+    -- waiting, and stop the manager and the expirer.+    atomically $ drainWaiting waiting+    killThread managerTid+    killThread expirerTid++  return $ Pool (Config.size config) adapter (Config.connectionSettingsProvider config) acqTimeoutNanos agingTimeoutNanos maxIdletimeNanos connectionQueue (Config.reuseOrder config) capVar waiting reuseVar reaperRef observer (Config.initSession config)+  where+    acqTimeoutNanos =+      div (fromIntegral (diffTimeToPicoseconds (Config.acquisitionTimeout config))) 1_000+    agingTimeoutNanos =+      div (fromIntegral (diffTimeToPicoseconds (Config.agingTimeout config))) 1_000+    maxIdletimeNanos =+      div (fromIntegral (diffTimeToPicoseconds (Config.idlenessTimeout config))) 1_000++-- | Release all the idle connections in the pool, and mark the in-use connections+-- to be released after use. Any connections acquired after the call will be+-- freshly established.+--+-- The pool remains usable after this action.+-- So you can use this function to reset the connections in the pool.+-- Naturally, you can also use it to release the resources.+release :: Pool -> IO ()+release Pool {..} =+  join . atomically $ do+    prevReuse <- readTVar poolReuseVar+    writeTVar prevReuse False+    newReuse <- newTVar True+    writeTVar poolReuseVar newReuse+    entries <- flushTQueue poolConnectionQueue+    return $ forM_ entries $ \entry ->+      mask \restore ->+        catch @SomeException+          ( do+              restore $ Connection.release (entryConnection entry)+              restore $ poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus ReleaseConnectionTerminationReason))+              atomically $ freeSlot poolReuseVar poolWaiting poolCapacity+          )+          \exc -> do+            atomically $ freeSlot poolReuseVar poolWaiting poolCapacity+            case fromException exc of+              Just SomeAsyncException {} -> throwIO exc+              Nothing -> return ()++-- | Use a connection from the pool to run a session and return the connection+-- to the pool, when finished.+--+-- A connection error, a session error that leaves connection-specific+-- state, or a session error on a connection the adapter marks as+-- 'Pqi.ConnectionBad' gets interpreted as a loss of connection. The+-- connection is not returned to the pool and a slot is freed for a new one.+--+-- __Warning:__ Due to the mechanism mentioned above you should avoid intercepting this error type from within sessions.+--+-- When no connection is available, the pool requests wait for one in the+-- order they came, and a later pool request doesn't take a connection while+-- others wait.+use :: forall a. Pool -> Session.Session a -> IO (Either UsageError a)+use Pool {..} sess = do+  now <- getMonotonicTimeNSec+  mask \unmask -> do+    holding <- atomically $ do+      reuseVar <- readTVar poolReuseVar+      waited <- someoneWaiting poolWaiting+      -- Behind the pool requests already waiting, which get what's freed first.+      if waited+        then enqueue now <&> WaitingHolding+        else+          asum+            [ readTQueue poolConnectionQueue <&> EntryHolding reuseVar,+              do+                capVal <- readTVar poolCapacity+                if capVal > 0+                  then do+                    writeTVar poolCapacity $! pred capVal+                    return $ SlotHolding reuseVar+                  else retry,+              enqueue now <&> WaitingHolding+            ]+    case holding of+      EntryHolding reuseVar entry -> onEntry unmask reuseVar entry+      SlotHolding reuseVar -> onSlot unmask reuseVar+      WaitingHolding waiter -> do+        given <- atomically (takeTMVar (waiterGiven waiter)) `onException` abandon waiter+        case given of+          TimedOut -> return $ Left AcquisitionTimeoutUsageError+          Given reuseVar Nothing -> onSlot unmask reuseVar+          Given reuseVar (Just entry) -> onEntry unmask reuseVar entry+  where+    enqueue :: Word64 -> STM Waiter+    enqueue now = do+      waiter <- Waiter (now + poolAcquisitionTimeout) <$> newEmptyTMVar <*> newTVar False+      writeTQueue poolWaiting waiter+      return waiter++    abandon :: Waiter -> IO ()+    abandon waiter = do+      given <- atomically $ do+        writeTVar (waiterGone waiter) True+        tryTakeTMVar (waiterGiven waiter)+      forM_ given \case+        Given _ Nothing -> atomically returnSlot+        Given reuseVar (Just entry) -> returnConn reuseVar entry+        TimedOut -> return ()++    returnSlot :: STM ()+    returnSlot = freeSlot poolReuseVar poolWaiting poolCapacity++    -- \| Holding one entry dequeued from the idle connections. If it is still+    -- good, run the session on it; if it expired, replace it with a fresh+    -- connection on the same slot. All the way, the holding is given back on+    -- interruption.+    onEntry :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> IO (Either UsageError a)+    onEntry unmask reuseVar entry = do+      now <- getMonotonicTimeNSec+      if entryIsAged poolMaxLifetime now entry+        then renewEntry unmask reuseVar entry AgingConnectionTerminationReason+        else+          if entryIsIdle poolMaxIdletime now entry+            then renewEntry unmask reuseVar entry IdlenessConnectionTerminationReason+            else onLiveConn unmask reuseVar entry {entryUseTimeNSec = now}++    -- \| Holding an expired entry. Release its connection and establish a+    -- fresh one on the same slot. On interruption the slot gets given back:+    -- the released connection cannot return to the pool.+    renewEntry :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> ConnectionTerminationReason -> IO (Either UsageError a)+    renewEntry unmask reuseVar entry reason = do+      outcome <-+        onException+          ( do+              Connection.release (entryConnection entry)+              unmask $ poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus reason))+              establish unmask+          )+          (atomically returnSlot)+      case outcome of+        Left err -> return $ Left err+        Right newEntry -> onLiveConn unmask reuseVar newEntry++    -- \| Holding one capacity unit. Establish a connection on it and run the+    -- session. On interruption the slot gets given back.+    onSlot :: (forall x. IO x -> IO x) -> TVar Bool -> IO (Either UsageError a)+    onSlot unmask reuseVar = do+      outcome <- onException (establish unmask) (atomically returnSlot)+      case outcome of+        Left err -> return $ Left err+        Right entry -> onLiveConn unmask reuseVar entry++    -- Run with one capacity unit held: establish the connection and run the+    -- init session on it. On any failure the slot gets given back and the+    -- error gets returned. On interruption the slot gets given back and the+    -- exception gets rethrown.+    establish :: (forall x. IO x -> IO x) -> IO (Either UsageError Entry)+    establish unmask = do+      settings <- unmask poolFetchConnectionSettings+      now <- getMonotonicTimeNSec+      id <- Uuid.nextRandom+      unmask $ poolObserver (ConnectionObservation id ConnectingConnectionStatus)+      unmask (Connection.acquire poolAdapter settings) >>= \case+        Left connErr -> do+          unmask $ poolObserver (ConnectionObservation id (TerminatedConnectionStatus (AcquireErrorConnectionTerminationReason connErr)))+          atomically returnSlot+          return $ Left $ ConnectionUsageError connErr+        Right connection ->+          unmask (Connection.use connection poolInitSession) >>= \case+            Left err -> do+              Connection.release connection+              unmask+                $ case err of+                  Errors.ConnectionUseError connectionError ->+                    poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason connectionError)))+                  Errors.SessionUseError sessionErr ->+                    poolObserver (ConnectionObservation id (TerminatedConnectionStatus (InitializationErrorTerminationReason sessionErr)))+              atomically returnSlot+              return $ Left $ SessionUsageError err+            Right () -> do+              unmask $ poolObserver (ConnectionObservation id (ReadyForUseConnectionStatus EstablishedConnectionReadyForUseReason))+              return $ Right (Entry connection now now id)++    -- \| Holding one entry ready for use. Run the session on it, return the+    -- entry to the pool, and return the session result. Interrupted, the+    -- session exception gets rethrown after the entry is back in the pool.+    onLiveConn :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> IO (Either UsageError a)+    onLiveConn unmask reuseVar entry = do+      sessRes <-+        onException+          ( unmask $ do+              poolObserver (ConnectionObservation (entryId entry) InUseConnectionStatus)+              try @SomeException (Connection.use (entryConnection entry) sess)+          )+          (returnConn reuseVar entry)++      case sessRes of+        Left exc -> do+          Connection.release (entryConnection entry)+          atomically returnSlot+          unmask+            $ poolObserver+              ( ConnectionObservation+                  (entryId entry)+                  (TerminatedConnectionStatus (ExceptionConnectionTerminationReason (Text.pack (displayException exc))))+              )+          throwIO exc+        Right (Left err) ->+          case err of+            Errors.ConnectionUseError connectionError -> do+              Connection.release (entryConnection entry)+              atomically returnSlot+              unmask+                $ poolObserver+                  ( ConnectionObservation+                      (entryId entry)+                      (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason connectionError))+                  )+              return $ Left $ SessionUsageError err+            Errors.SessionUseError sessionErr -> do+              discard <- (||) (ConnectionDiscards.sessionError sessionErr) <$> connectionIsLost (entryConnection entry)+              if discard+                then do+                  Connection.release (entryConnection entry)+                  atomically returnSlot+                  unmask+                    $ poolObserver+                      ( ConnectionObservation+                          (entryId entry)+                          (TerminatedConnectionStatus (SessionErrorConnectionTerminationReason sessionErr))+                      )+                  return $ Left $ SessionUsageError err+                else do+                  returnConn reuseVar entry+                  unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus (SessionFailedConnectionReadyForUseReason sessionErr)))+                  return $ Left $ SessionUsageError err+        Right (Right res) -> do+          returnConn reuseVar entry+          unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus SessionSucceededConnectionReadyForUseReason))+          return $ Right res++    -- Back to the pool request waiting longest or to the idle connections,+    -- unless the pool was released meanwhile.+    returnConn reuseVar entry =+      join . atomically $ do+        reuse <- readTVar reuseVar+        if reuse+          then do+            nextWaiter poolWaiting >>= \case+              Just waiter -> do+                currentReuseVar <- readTVar poolReuseVar+                putTMVar (waiterGiven waiter) (Given currentReuseVar (Just entry))+              Nothing ->+                case poolReuseOrder of+                  LIFO -> unGetTQueue poolConnectionQueue entry+                  FIFO -> writeTQueue poolConnectionQueue entry+            return $ return ()+          else return $ do+            Connection.release (entryConnection entry)+            atomically returnSlot+            poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus ReleaseConnectionTerminationReason))++-- | Whether the adapter has marked the connection as lost.+--+-- When the server closes an idle connection, e.g. on restart or with+-- @pg_terminate_backend@, the next statement on it can fail with an error+-- that doesn't say so: 'Errors.UnexpectedRowCountStatementError', for the+-- extra result that reports the closed connection. A statement returning more+-- rows than its decoder expects fails the same way on a healthy connection, so+-- the error can't tell the two apart. The connection status can: the adapter+-- has set it to 'Pqi.ConnectionBad' by then.+connectionIsLost :: Connection -> IO Bool+connectionIsLost connection =+  Connection.use connection checkStatus <&> \case+    Left _ -> True+    Right lost -> lost+  where+    checkStatus =+      Session.onLibpqConnection \pqConnection -> do+        status <- Pqi.status pqConnection+        return (Right (status == Pqi.ConnectionBad), pqConnection)++-- | Whether a pool request is waiting. The ones that stopped waiting get+-- dropped.+someoneWaiting :: TQueue Waiter -> STM Bool+someoneWaiting waiting =+  tryPeekTQueue waiting >>= \case+    Nothing -> return False+    Just waiter ->+      readTVar (waiterGone waiter) >>= \case+        True -> readTQueue waiting *> someoneWaiting waiting+        False -> return True++-- | Take the pool request waiting longest, passing over the ones that stopped+-- waiting.+nextWaiter :: TQueue Waiter -> STM (Maybe Waiter)+nextWaiter waiting =+  tryReadTQueue waiting >>= \case+    Nothing -> return Nothing+    Just waiter ->+      readTVar (waiterGone waiter) >>= \case+        True -> nextWaiter waiting+        False -> return (Just waiter)++-- | Give the slot of a closed connection to the pool request waiting longest,+-- or back to the pool if no pool request waits.+freeSlot :: TVar (TVar Bool) -> TQueue Waiter -> TVar Int -> STM ()+freeSlot reuseVarVar waiting capVar =+  nextWaiter waiting >>= \case+    Just waiter -> do+      reuseVar <- readTVar reuseVarVar+      putTMVar (waiterGiven waiter) (Given reuseVar Nothing)+    Nothing -> modifyTVar' capVar succ++-- | Time out the pool requests waiting too long. All wait as long, so the pool+-- request waiting longest times out first: one thread sleeps until its+-- deadline, rather than every waiting pool request registering a timer, which+-- GHC can't cancel.+expire :: TQueue Waiter -> IO ()+expire waiting = forever $ do+  deadline <- atomically $ do+    waited <- someoneWaiting waiting+    if waited then waiterDeadline <$> peekTQueue waiting else retry+  now <- getMonotonicTimeNSec+  -- In microseconds, at most an hour at a time.+  when (deadline > now) $ threadDelay (fromIntegral (min 3_600_000_000 (div (deadline - now) 1_000 + 1)))+  atomically . timeOut =<< getMonotonicTimeNSec+  where+    timeOut now =+      tryPeekTQueue waiting >>= \case+        Just waiter | waiterDeadline waiter <= now -> do+          _ <- readTQueue waiting+          gone <- readTVar (waiterGone waiter)+          unless gone $ putTMVar (waiterGiven waiter) TimedOut+          timeOut now+        _ -> return ()++-- | Resolve the pool requests still waiting: with the pool gone, nothing will+-- ever be given to them.+drainWaiting :: TQueue Waiter -> STM ()+drainWaiting waiting =+  tryReadTQueue waiting >>= \case+    Nothing -> return ()+    Just waiter -> do+      gone <- readTVar (waiterGone waiter)+      unless gone $ void $ tryPutTMVar (waiterGiven waiter) TimedOut+      drainWaiting waiting++-- | Terminate one expired connection on the reaper's tick: release it, report+-- the termination, and give its slot back. The slot gets given back even when+-- the release or the observation fails, so no capacity is lost, and a failing+-- entry neither skips the other entries of the tick nor kills the reaper.+reap :: (Observation -> IO ()) -> TVar (TVar Bool) -> TQueue Waiter -> TVar Int -> ConnectionTerminationReason -> Entry -> IO ()+reap observer reuseVar waiting capVar reason entry =+  mask \restore ->+    catch @SomeException+      ( do+          restore $ Connection.release (entryConnection entry)+          restore $ observer (ConnectionObservation (entryId entry) (TerminatedConnectionStatus reason))+          atomically $ freeSlot reuseVar waiting capVar+      )+      \exc -> do+        atomically $ freeSlot reuseVar waiting capVar+        case fromException exc of+          Just SomeAsyncException {} -> throwIO exc+          Nothing -> return ()++-- | Union over all errors that 'use' can result in.+data UsageError+  = -- | Attempt to establish a connection failed.+    ConnectionUsageError Errors.AcquireError+  | -- | Session execution failed.+    SessionUsageError Errors.UseError+  | -- | Timeout acquiring a connection.+    AcquisitionTimeoutUsageError+  deriving (Show, Eq)++instance Exception UsageError
+ src/library/Hasql/Pool/Config.hs view
@@ -0,0 +1,28 @@+-- | DSL for construction of configs.+module Hasql.Pool.Config+  ( Config.Config,+    settings,+    Setting.Setting,+    Setting.size,+    Setting.acquisitionTimeout,+    Setting.agingTimeout,+    Setting.idlenessTimeout,+    Setting.staticConnectionSettings,+    Setting.dynamicConnectionSettings,+    Setting.observationHandler,+    Setting.initSession,+    Setting.reuseOrder,+    ReuseOrder.ReuseOrder (..),+  )+where++import Hasql.Pool.Config.Config qualified as Config+import Hasql.Pool.Config.ReuseOrder qualified as ReuseOrder+import Hasql.Pool.Config.Setting qualified as Setting+import Hasql.Pool.Prelude++-- | Compile config from a list of settings.+-- Latter settings override the preceding in cases of conflicts.+settings :: [Setting.Setting] -> Config.Config+settings =+  foldr ($) Config.defaults . fmap Setting.apply
+ src/library/Hasql/Pool/Config/Config.hs view
@@ -0,0 +1,34 @@+module Hasql.Pool.Config.Config where++import Hasql.Connection.Settings qualified as Connection.Settings+import Hasql.Pool.Config.Defaults qualified as Defaults+import Hasql.Pool.Config.ReuseOrder (ReuseOrder)+import Hasql.Pool.Observation (Observation)+import Hasql.Pool.Prelude+import Hasql.Session qualified as Session++-- | Configuration for Hasql connection pool.+data Config = Config+  { size :: Int,+    acquisitionTimeout :: DiffTime,+    agingTimeout :: DiffTime,+    idlenessTimeout :: DiffTime,+    connectionSettingsProvider :: IO Connection.Settings.Settings,+    observationHandler :: Observation -> IO (),+    initSession :: Session.Session (),+    reuseOrder :: ReuseOrder+  }++-- | Reasonable defaults, which can be built upon.+defaults :: Config+defaults =+  Config+    { size = Defaults.size,+      acquisitionTimeout = Defaults.acquisitionTimeout,+      agingTimeout = Defaults.agingTimeout,+      idlenessTimeout = Defaults.idlenessTimeout,+      connectionSettingsProvider = Defaults.dynamicConnectionSettings,+      observationHandler = Defaults.observationHandler,+      initSession = Defaults.initSession,+      reuseOrder = Defaults.reuseOrder+    }
+ src/library/Hasql/Pool/Config/Defaults.hs view
@@ -0,0 +1,53 @@+module Hasql.Pool.Config.Defaults where++import Hasql.Connection.Settings qualified as Connection.Settings+import Hasql.Pool.Config.ReuseOrder (ReuseOrder (..))+import Hasql.Pool.Observation (Observation)+import Hasql.Pool.Prelude+import Hasql.Session qualified as Session++-- |+-- 3 connections.+size :: Int+size = 3++-- |+-- 10 seconds.+acquisitionTimeout :: DiffTime+acquisitionTimeout = 10++-- |+-- 1 day.+agingTimeout :: DiffTime+agingTimeout = 60 * 60 * 24++-- |+-- 10 minutes.+idlenessTimeout :: DiffTime+idlenessTimeout = 60 * 10++-- |+-- > "postgresql://postgres:postgres@localhost:5432/postgres"+staticConnectionSettings :: Connection.Settings.Settings+staticConnectionSettings =+  "postgresql://postgres:postgres@localhost:5432/postgres"++-- |+-- > pure "postgresql://postgres:postgres@localhost:5432/postgres"+dynamicConnectionSettings :: IO Connection.Settings.Settings+dynamicConnectionSettings = pure staticConnectionSettings++-- |+-- > const (pure ())+observationHandler :: Observation -> IO ()+observationHandler = const (pure ())++-- |+-- > pure ()+initSession :: Session.Session ()+initSession = pure ()++-- |+-- The idle connection returned longest ago first.+reuseOrder :: ReuseOrder+reuseOrder = FIFO
+ src/library/Hasql/Pool/Config/ReuseOrder.hs view
@@ -0,0 +1,17 @@+module Hasql.Pool.Config.ReuseOrder where++import Hasql.Pool.Prelude++-- | Which of the idle connections a pool request gets.+data ReuseOrder+  = -- | Last in, first out: the one returned most recently.+    --+    -- The pool keeps reusing the few connections the load needs, so the rest+    -- time out as idle, and the ones in use keep their caches warm.+    LIFO+  | -- | First in, first out: the one returned longest ago.+    --+    -- Pool requests cycle through all the connections, so steady load keeps+    -- every connection open.+    FIFO+  deriving (Show, Eq)
+ src/library/Hasql/Pool/Config/Setting.hs view
@@ -0,0 +1,117 @@+module Hasql.Pool.Config.Setting where++import Hasql.Connection.Settings qualified as Connection.Settings+import Hasql.Pool.Config.Config (Config)+import Hasql.Pool.Config.Config qualified as Config+import Hasql.Pool.Config.ReuseOrder (ReuseOrder (..))+import Hasql.Pool.Observation (Observation)+import Hasql.Pool.Prelude+import Hasql.Session qualified as Session++apply :: Setting -> Config -> Config+apply (Setting run) = run++-- | A single setting of a config.+newtype Setting+  = Setting (Config -> Config)++-- | Pool size.+--+-- 3 by default.+size :: Int -> Setting+size x =+  Setting (\config -> config {Config.size = x})++-- | Connection acquisition timeout.+--+-- 10 seconds by default.+acquisitionTimeout :: DiffTime -> Setting+acquisitionTimeout x =+  Setting (\config -> config {Config.acquisitionTimeout = x})++-- | Maximal connection lifetime.+--+-- Determines how long is available for reuse.+-- After the timeout passes and an active session is finished the connection will be closed releasing a slot in the pool for a fresh connection to be established.+--+-- This is useful as a healthy measure for resetting the server-side caches.+--+-- 1 day by default.+agingTimeout :: DiffTime -> Setting+agingTimeout x =+  Setting (\config -> config {Config.agingTimeout = x})++-- | Maximal connection idle time.+--+-- How long to keep a connection open when it's not being used.+--+-- 10 minutes by default.+idlenessTimeout :: DiffTime -> Setting+idlenessTimeout x =+  Setting (\config -> config {Config.idlenessTimeout = x})++-- | Connection string.+--+-- By default it is:+--+-- > "postgresql://postgres:postgres@localhost:5432/postgres"+staticConnectionSettings :: Connection.Settings.Settings -> Setting+staticConnectionSettings x =+  Setting (\config -> config {Config.connectionSettingsProvider = pure x})++-- | Action providing connection settings.+--+-- Gets used each time a connection gets established by the pool.+-- This may be useful for some authorization models.+--+-- By default it is:+--+-- > pure "postgresql://postgres:postgres@localhost:5432/postgres"+dynamicConnectionSettings :: IO Connection.Settings.Settings -> Setting+dynamicConnectionSettings x =+  Setting (\config -> config {Config.connectionSettingsProvider = x})++-- | Observation handler.+--+-- Typically it's used for monitoring the state of the pool via metrics and logging.+--+-- An observation handler must not throw. Synchronous exceptions from it are discarded; asynchronous exceptions are honored. Its failure never affects the session result or the pool's state.+--+-- If the provided action is not lightweight, it's recommended to use intermediate bufferring via channels like TBQueue to avoid occupying the pool management thread for too long.+-- E.g., if the action is @'atomically' . 'writeTBQueue' yourQueue@, then reading from it and processing can be done on a separate thread.+--+-- By default it is:+--+-- > const (pure ())+observationHandler :: (Observation -> IO ()) -> Setting+observationHandler x =+  Setting (\config -> config {Config.observationHandler = x})++-- | Initial session.+--+-- Gets executed on every connection upon acquisition.+-- Lets you specify the connection-wide settings.+--+-- E.g., you can set the search path for all the sessions executed by the pool by executing the following:+--+-- > initSession (Session.sql "SET search_path TO schema1, schema2, public;")+--+-- The state it establishes survives an ordinary session error (a bad query, a+-- constraint violation), since those leave the connection reusable. It does+-- not survive an asynchronous exception escaping the session: any such+-- exception spends the connection, so the next use runs 'initSession' again+-- on a fresh one.+initSession :: Session.Session () -> Setting+initSession x =+  Setting (\config -> config {Config.initSession = x})++-- | Which of the idle connections a pool request gets.+--+-- With 'LIFO', the pool shrinks to the connections the load needs: the rest+-- time out as idle (see 'idlenessTimeout'). With 'FIFO', steady load keeps+-- every connection open.+--+-- 'FIFO' by default.+reuseOrder :: ReuseOrder -> Setting+reuseOrder x =+  Setting (\config -> config {Config.reuseOrder = x})
+ src/library/Hasql/Pool/ConnectionDiscards.hs view
@@ -0,0 +1,206 @@+-- | Classification of 'Errors.SessionError' along the axis the pool cares+-- about: whether the connection it came back on is still fit to reuse.+--+-- Hasql's own verdict - 'Errors.SessionUseError' - only promises the+-- connection is still usable in the sense that 'Hasql.Connection.use' will+-- run another session on it without throwing. It does not promise the+-- statement that just failed can ever succeed on the same connection: a+-- stale catalog cache or a plan built against a type that no longer exists+-- leaves the connection alive but unable to replan that statement. Hasql+-- declined to own this call - see the removal of+-- 'Hasql.Errors.IsError.isTransient' - so the pool keeps making it itself,+-- the same way it always did.+--+-- 'Errors.ConnectionUseError' needs no classification here: it always means+-- the connection is gone, and hasql has already finished it.+--+-- == The standard a rule has to meet+--+-- A rule belongs here only if it can name the /residue/: state left behind+-- on this particular connection that a fresh connection would not have, and+-- that no subsequent session can clear. A rule that cannot name the residue+-- is a rule to delete.+--+-- The two errors are not symmetric. A wrong discard costs one reconnect,+-- paid once. A wrong retain hands back a connection whose client-side+-- caches - 'Hasql.ConnectionState.oidCache' and+-- 'Hasql.ConnectionState.statementCache' - disagree with the server, and+-- since nothing ever evicts from either, that connection fails the same+-- statement for the whole of its remaining lifetime. That asymmetry is the+-- reason a discard is the default cure below, not a reason to discard on+-- suspicion: the bar is still a nameable residue.+module Hasql.Pool.ConnectionDiscards where++import Data.Text qualified as Text+import Hasql.Errors qualified as Errors+import Hasql.Pool.Prelude++sessionError :: Errors.SessionError -> Bool+sessionError = \case+  -- Missing types leave no residue on the connection: the lookup is a live+  -- catalog query, nothing gets negatively cached, and the connection state+  -- comes back untouched. A fresh connection would ask the same catalog and+  -- get the same answer, so discarding buys nothing but a reconnect.+  Errors.MissingTypesSessionError {} -> False+  Errors.ScriptSessionError _ serverErr -> serverError serverErr+  Errors.StatementSessionError _ _ _ _ _ statementErr -> statementError statementErr++statementError :: Errors.StatementError -> Bool+statementError = \case+  Errors.ServerStatementError serverErr -> serverError serverErr+  -- The remaining constructors all describe a disagreement between the+  -- decoder the caller supplied and the result the server actually sent.+  -- The server raised no error, no cache was consulted or written, and the+  -- connection is in exactly the state it was in before the statement ran.+  -- A fresh connection re-runs the statement and fails identically, so a+  -- discard would cost a reconnect and change nothing.+  --+  -- 'UnexpectedColumnTypeStatementError' is worth singling out, because it+  -- used to discard. The reasoning was that a decoder built against an OID+  -- the catalog has since reassigned cannot succeed while the connection+  -- holds the old cache. That case is real, but it does not surface here:+  -- the server notices the dropped type first and raises @XX000@ (see+  -- 'serverError'), which arrives as a 'ServerStatementError'. What reaches+  -- this constructor instead is the ordinary mismatch - a decoder asking+  -- for @int4@ where the column is @text@ - which is a bug in the caller's+  -- code, not residue on the connection.+  --+  -- The match is deliberately exhaustive rather than a wildcard: when hasql+  -- adds a constructor, this module should fail to compile and force a+  -- verdict, instead of silently inheriting @False@.+  Errors.UnexpectedRowCountStatementError {} -> False+  Errors.UnexpectedColumnCountStatementError {} -> False+  Errors.UnexpectedColumnTypeStatementError {} -> False+  Errors.RowStatementError {} -> False+  Errors.UnexpectedResultStatementError {} -> False++-- | Verdict on a server error, keyed on its SQLSTATE.+--+-- The codes below are matched exactly unless a comment says otherwise.+-- Exactness is load-bearing in two places: @XX000@ discards while @XX001@+-- and @XX002@ do not, and @42P05@ discards while the rest of class @42@+-- does not.+serverError :: Errors.ServerError -> Bool+serverError (Errors.ServerError code _ _ _ _)+  -- @internal_error@. The target is @cache lookup failed for type NNNN@,+  -- raised when a prepared statement's plan references a type OID that a+  -- @drop type@ / @create type@ has since retired. Verified against a live+  -- server: every subsequent execution on that connection raises it again,+  -- forever. The residue is the server-side prepared statement bound to a+  -- dead OID, together with hasql's 'statementCache' entry that keeps+  -- pointing at it; both are session-scoped, so a fresh connection replans+  -- cleanly.+  --+  -- The code is broader than that: @XX000@ is also PostgreSQL's catch-all+  -- for internal faults that say nothing about the connection. Those get+  -- discarded too. That is a known over-reach, accepted because the code+  -- alone carries no way to tell the cases apart - the distinguishing+  -- signal is the message text, which the server localises under+  -- @lc_messages@ and which the pool therefore cannot rely on.+  | code == "XX000" = True+  -- @feature_not_supported@. The target is @cached plan must not change+  -- result type@, raised when a schema change alters the columns or+  -- parameter types a prepared statement was planned against. Verified+  -- against a live server: it too repeats on every subsequent execution.+  -- Same residue as @XX000@, same cure.+  --+  -- Same over-reach, too: plenty of statements asking for something+  -- PostgreSQL simply does not do raise @0A000@ on a perfectly healthy+  -- connection, and are discarded for nothing.+  | code == "0A000" = True+  -- @invalid_sql_statement_name@. Hasql's 'statementCache' is a+  -- client-side ledger of what it believes is prepared on this connection.+  -- This code means the ledger and the server disagree - the name hasql+  -- intends to execute is not there - and since nothing ever evicts from+  -- that ledger, the disagreement is permanent. Reproducible by+  -- deallocating a prepared statement and executing it afterwards.+  | code == "26000" = True+  -- @duplicate_prepared_statement@: the same ledger desynced the other way,+  -- with the server holding a name hasql thinks is free. Reachable when+  -- something outside hasql prepared a colliding name, or after a reset+  -- hasql did not observe. Same residue, same permanence.+  | code == "42P05" = True+  -- @in_failed_sql_transaction@. The connection is parked inside an aborted+  -- transaction, and every statement on it fails until a rollback. The pool+  -- does no I/O on the return path, so it cannot issue that rollback, which+  -- leaves a discard as the only cure available.+  | code == "25P02" = True+  -- Class @08@, @connection_exception@ - prefix match. Most of the class+  -- describes a connection that is already gone. @08P01@+  -- (@protocol_violation@) is the one that earns its place on residue+  -- grounds rather than liveness: client and server disagree about where+  -- they are in the wire protocol, and nothing on the connection can+  -- resynchronise them.+  --+  -- Expect most of this class to be unreachable in practice: when the+  -- socket dies hasql reports 'Errors.ConnectionUseError', which the pool+  -- discards without consulting this module at all. @08P01@ is the member+  -- worth keeping regardless, since a protocol desync need not come with a+  -- dead socket.+  | Text.isPrefixOf "08" code = True+  -- @statement_completion_unknown@. The one code in class @40@ that+  -- qualifies: the client does not know whether the statement committed, so+  -- the connection's transactional state is genuinely unknown rather than+  -- merely failed.+  | code == "40003" = True+  -- Class @57P@ - prefix match. @57P01@ (@admin_shutdown@), @57P02@+  -- (@crash_shutdown@), @57P03@ (@cannot_connect_now@), @57P04@+  -- (@database_dropped@), @57P05@ (@idle_session_timeout@), @57P06@+  -- (@idle_in_transaction_session_timeout@). All are FATAL: the server+  -- emits the error and closes the socket, so a connection that saw one is+  -- gone or going.+  --+  -- The prefix is @57P@ rather than @57@ on purpose. @57014@+  -- (@query_canceled@) must not match: a cancelled query leaves a perfectly+  -- healthy connection, and discarding on it would punish every caller-side+  -- timeout with a reconnect.+  --+  -- As with class @08@, some of these only ever arrive as+  -- 'Errors.ConnectionUseError', which the pool discards without consulting+  -- this module. @57P01@ was tested directly: terminating the backend+  -- underneath a session surfaces as a 'Errors.ConnectionUseError' carrying+  -- an 'Errors.ServerConnectionError' with the SQLSTATE intact - never as a+  -- 'Errors.ServerError' reaching this function.+  -- The rule is kept anyway: it costs nothing, and the remaining codes in+  -- the class have not been shown to behave the same way.+  | Text.isPrefixOf "57P" code = True+  | otherwise = False++-- $rejected+--+-- Codes deliberately /not/ discarded, recorded here so they are not+-- reintroduced on the strength of sounding alarming. Each fails the+-- standard in the module header: the error is real, but the residue is not+-- on this connection.+--+-- * Class @53@, @insufficient_resources@ - @53000@, @53100@ (@disk_full@),+--   @53200@ (@out_of_memory@), @53400@. These describe a shortage on the+--   /server/. The connection that received the error is structurally+--   untouched, and a reconnect does not cure a full disk. Worse, under load+--   the condition fires on many connections at once, so a discard rule+--   turns a resource shortage into a reconnect storm against a server that+--   is already short of resources. @53300@ (@too_many_connections@) is+--   additionally unreachable here: it arrives at acquisition time as an+--   'Errors.AcquireError' and never reaches this module.+--+-- * @25001@, @active_sql_transaction@. Raised when a command that cannot+--   run inside a transaction block is issued inside one. A caller bug, on a+--   healthy connection, reproduced identically by a fresh one. Listed only+--   so nobody groups it with @25P02@ by prefix.+--+-- * @40001@ (@serialization_failure@) and @40P01@ (@deadlock_detected@).+--   The canonical retry-on-the-same-connection cases. Discarding these+--   would make every serialisation retry pay for a reconnect.+--+-- * @57014@, @query_canceled@. See the @57P@ rule above.+--+-- * @55P03@ (@lock_not_available@) and @55006@ (@object_in_use@). Pure+--   contention between sessions; nothing is left behind on either.+--+-- * @58030@ (@io_error@), @XX001@ (@data_corrupted@), @XX002@+--   (@index_corrupted@). Genuinely alarming, but the damage is on disk. A+--   fresh connection reads the same corrupt page.+--+-- * Class @54@ (@program_limit_exceeded@), class @22@ (data exceptions),+--   and class @42@ other than @42P05@ (syntax and access rule violations).+--   Statement bugs, not connection state.
+ src/library/Hasql/Pool/Observation.hs view
@@ -0,0 +1,77 @@+-- | Interface for processing observations of the status of the pool.+--+-- Provides a flexible mechanism for monitoring the healthiness of the pool via logs and metrics without any opinionated choices on the actual monitoring technologies.+-- Specific interpreters are encouraged to be created as extension libraries.+module Hasql.Pool.Observation+  ( Observation (..),+    ConnectionStatus (..),+    ConnectionReadyForUseReason (..),+    ConnectionTerminationReason (..),+  )+where++import Hasql.Errors qualified as Errors+import Hasql.Pool.Prelude++-- | An observation of a change of the state of a pool.+data Observation+  = -- | Status of one of the pool's connections has changed.+    ConnectionObservation+      -- | Generated connection ID.+      -- For grouping the observations by one connection.+      UUID+      -- | Status that the connection has entered.+      ConnectionStatus+  deriving (Show, Eq)++-- | Status of a connection.+--+-- <<diagrams-output/connection-status-model.png>>+data ConnectionStatus+  = -- | Connection is being established.+    --+    -- This is the initial status of every connection.+    ConnectingConnectionStatus+  | -- | Connection is established and not occupied.+    ReadyForUseConnectionStatus ConnectionReadyForUseReason+  | -- | Is being used by some session.+    --+    -- After it's done the status will transition to 'ReadyForUseConnectionStatus' or 'TerminatedConnectionStatus'.+    InUseConnectionStatus+  | -- | Connection terminated.+    TerminatedConnectionStatus ConnectionTerminationReason+  deriving (Show, Eq)++data ConnectionReadyForUseReason+  = -- | Connection just got established.+    EstablishedConnectionReadyForUseReason+  | -- | Session execution ended with a failure that does not require a connection reset.+    SessionFailedConnectionReadyForUseReason Errors.SessionError+  | -- | Session execution ended with success.+    SessionSucceededConnectionReadyForUseReason+  deriving (Show, Eq)++-- | Explanation of why a connection was terminated.+data ConnectionTerminationReason+  = -- | The age timeout of the connection has passed.+    AgingConnectionTerminationReason+  | -- | The timeout of how long a connection may remain idle in the pool has passed.+    IdlenessConnectionTerminationReason+  | -- | The connection became unusable and had to be discarded.+    --+    -- This includes connectivity issues with the server as well as fatal+    -- session errors that invalidate the connection's prepared statement or+    -- type caches. The underlying error stays structured so callers can+    -- inspect a server-reported SQLSTATE with 'Errors.toSqlState'.+    NetworkErrorConnectionTerminationReason Errors.ConnectionError+  | -- | Connection acquisition failed before the connection became usable.+    AcquireErrorConnectionTerminationReason Errors.AcquireError+  | -- | A fatal session error required the connection to be discarded.+    SessionErrorConnectionTerminationReason Errors.SessionError+  | -- | An exception caused the connection to be discarded.+    ExceptionConnectionTerminationReason Text+  | -- | User has invoked the 'Hasql.Pool.release' procedure.+    ReleaseConnectionTerminationReason+  | -- | Initialization session failure.+    InitializationErrorTerminationReason Errors.SessionError+  deriving (Show, Eq)
+ src/library/Hasql/Pool/Prelude.hs view
@@ -0,0 +1,75 @@+module Hasql.Pool.Prelude+  ( module Exports,+  )+where++import Control.Applicative as Exports hiding (WrappedArrow (..))+import Control.Arrow as Exports hiding (first, second)+import Control.Category as Exports+import Control.Concurrent as Exports+import Control.Concurrent.STM as Exports hiding (orElse)+import Control.Exception as Exports+import Control.Monad as Exports hiding (fail, forM, forM_, mapM, mapM_, msum, sequence, sequence_)+import Control.Monad.Fail as Exports+import Control.Monad.Fix as Exports hiding (fix)+import Control.Monad.IO.Class as Exports+import Control.Monad.ST as Exports+import Data.Bifunctor as Exports+import Data.Bits as Exports+import Data.Bool as Exports+import Data.ByteString as Exports (ByteString)+import Data.Char as Exports+import Data.Coerce as Exports+import Data.Complex as Exports+import Data.Data as Exports+import Data.Dynamic as Exports+import Data.Either as Exports+import Data.Fixed as Exports+import Data.Foldable as Exports hiding (toList)+import Data.Function as Exports hiding (id, (.))+import Data.Functor as Exports hiding (unzip)+import Data.Functor.Compose as Exports+import Data.IORef as Exports+import Data.Int as Exports+import Data.Ix as Exports+import Data.List as Exports hiding (all, and, any, concat, concatMap, elem, find, foldl, foldl', foldl1, foldr, foldr1, isSubsequenceOf, mapAccumL, mapAccumR, maximum, maximumBy, minimum, minimumBy, notElem, or, product, sortOn, sum, uncons)+import Data.List.NonEmpty as Exports (NonEmpty (..))+import Data.Maybe as Exports+import Data.Monoid as Exports hiding (Alt)+import Data.Ord as Exports+import Data.Proxy as Exports+import Data.Ratio as Exports+import Data.STRef as Exports+import Data.String as Exports+import Data.Text as Exports (Text)+import Data.Time as Exports+import Data.Traversable as Exports+import Data.Tuple as Exports+import Data.UUID as Exports (UUID)+import Data.Unique as Exports+import Data.Version as Exports+import Data.Void as Exports+import Data.Word as Exports+import Debug.Trace as Exports+import Foreign.ForeignPtr as Exports+import Foreign.Ptr as Exports+import Foreign.StablePtr as Exports+import Foreign.Storable as Exports+import GHC.Clock as Exports (getMonotonicTimeNSec)+import GHC.Conc as Exports hiding (orElse, threadWaitRead, threadWaitReadSTM, threadWaitWrite, threadWaitWriteSTM, withMVar)+import GHC.Exts as Exports (IsList (..), groupWith, inline, lazy, sortWith)+import GHC.Generics as Exports (Generic)+import GHC.IO.Exception as Exports+import Numeric as Exports+import Prelude as Exports hiding (all, and, any, concat, concatMap, elem, fail, foldl, foldl1, foldr, foldr1, id, mapM, mapM_, maximum, minimum, notElem, or, product, sequence, sequence_, sum, (.))+import System.Environment as Exports+import System.Exit as Exports+import System.IO as Exports (Handle, hClose)+import System.IO.Error as Exports+import System.IO.Unsafe as Exports+import System.Mem as Exports+import System.Mem.StableName as Exports+import System.Timeout as Exports+import Text.Printf as Exports (hPrintf, printf)+import Text.Read as Exports (Read (..), readEither, readMaybe)+import Unsafe.Coerce as Exports
− src/library/exposed/Hasql/Pool.hs
@@ -1,348 +0,0 @@-module Hasql.Pool-  ( -- * Pool-    Pool,-    acquire,-    use,-    release,--    -- * Errors-    UsageError (..),-  )-where--import Data.Text.Encoding qualified as Text-import Data.Text.Encoding.Error qualified as Text-import Data.UUID.V4 qualified as Uuid-import Hasql.Connection (Connection)-import Hasql.Connection qualified as Connection-import Hasql.Connection.Setting qualified as Connection.Setting-import Hasql.Pool.Config.Config qualified as Config-import Hasql.Pool.Observation-import Hasql.Pool.Prelude-import Hasql.Pool.SessionErrorDestructors qualified as ErrorsDestruction-import Hasql.Session qualified as Session---- | A connection tagged with metadata.-data Entry = Entry-  { entryConnection :: Connection,-    entryCreationTimeNSec :: Word64,-    entryUseTimeNSec :: Word64,-    entryId :: UUID-  }--entryIsAged :: Word64 -> Word64 -> Entry -> Bool-entryIsAged maxLifetime now Entry {..} =-  now > entryCreationTimeNSec + maxLifetime--entryIsIdle :: Word64 -> Word64 -> Entry -> Bool-entryIsIdle maxIdletime now Entry {..} =-  now > entryUseTimeNSec + maxIdletime---- | Contain the failures of the user-supplied observation handler. Synchronous--- exceptions from it are discarded, asynchronous ones are honored, so that--- neither affects the pool's state or the session result, and the pool's--- threads stay killable.-containObserver :: (Observation -> IO ()) -> Observation -> IO ()-containObserver observer observation =-  catch @SomeException (observer observation) \exc ->-    case fromException exc of-      Just SomeAsyncException {} -> throwIO exc-      Nothing -> return ()---- | Pool of connections to DB.-data Pool = Pool-  { -- | Pool size.-    poolSize :: Int,-    -- | Connection settings.-    poolFetchConnectionSettings :: IO [Connection.Setting.Setting],-    -- | Acquisition timeout, in microseconds.-    poolAcquisitionTimeout :: Int,-    -- | Maximal connection lifetime, in nanoseconds.-    poolMaxLifetime :: Word64,-    -- | Maximal connection idle time, in nanoseconds.-    poolMaxIdletime :: Word64,-    -- | Avail connections.-    poolConnectionQueue :: TQueue Entry,-    -- | Remaining capacity.-    -- The pool size limits the sum of poolCapacity, the length-    -- of poolConnectionQueue and the number of in-flight-    -- connections.-    poolCapacity :: TVar Int,-    -- | Whether to return a connection to the pool.-    poolReuseVar :: TVar (TVar Bool),-    -- | To stop the manager thread via garbage collection.-    poolReaperRef :: IORef (),-    -- | Action for reporting the observations.-    poolObserver :: Observation -> IO (),-    -- | Initial session to execute upon every established connection.-    poolInitSession :: Session.Session ()-  }---- | Create a connection-pool.------ No connections actually get established by this function. It is delegated--- to 'use'.------ If you want to ensure that the pool connects fine at the initialization phase, just run 'use' with an empty session (@pure ()@) and check for errors.-acquire :: Config.Config -> IO Pool-acquire config = do-  connectionQueue <- newTQueueIO-  capVar <- newTVarIO (Config.size config)-  reuseVar <- newTVarIO =<< newTVarIO True-  reaperRef <- newIORef ()-  let observer = containObserver (Config.observationHandler config)--  managerTid <- forkIOWithUnmask $ \unmask -> unmask $ forever $ do-    threadDelay 1000000-    now <- getMonotonicTimeNSec-    join . atomically $ do-      entries <- flushTQueue connectionQueue-      let (agedEntries, unagedEntries) = partition (entryIsAged agingTimeoutNanos now) entries-          (idleEntries, liveEntries) = partition (entryIsIdle maxIdletimeNanos now) unagedEntries-      traverse_ (writeTQueue connectionQueue) liveEntries-      return $ do-        forM_ agedEntries $ reap observer capVar AgingConnectionTerminationReason-        forM_ idleEntries $ reap observer capVar IdlenessConnectionTerminationReason--  void . mkWeakIORef reaperRef $ do-    -- When the pool goes out of scope, stop the manager.-    killThread managerTid--  return $ Pool (Config.size config) (Config.connectionSettingsProvider config) acqTimeoutMicros agingTimeoutNanos maxIdletimeNanos connectionQueue capVar reuseVar reaperRef observer (Config.initSession config)-  where-    acqTimeoutMicros =-      div (fromIntegral (diffTimeToPicoseconds (Config.acquisitionTimeout config))) 1_000_000-    agingTimeoutNanos =-      div (fromIntegral (diffTimeToPicoseconds (Config.agingTimeout config))) 1_000-    maxIdletimeNanos =-      div (fromIntegral (diffTimeToPicoseconds (Config.idlenessTimeout config))) 1_000---- | Release all the idle connections in the pool, and mark the in-use connections--- to be released after use. Any connections acquired after the call will be--- freshly established.------ The pool remains usable after this action.--- So you can use this function to reset the connections in the pool.--- Naturally, you can also use it to release the resources.-release :: Pool -> IO ()-release Pool {..} =-  join . atomically $ do-    prevReuse <- readTVar poolReuseVar-    writeTVar prevReuse False-    newReuse <- newTVar True-    writeTVar poolReuseVar newReuse-    entries <- flushTQueue poolConnectionQueue-    return $ forM_ entries $ \entry ->-      mask \restore ->-        catch @SomeException-          ( do-              restore $ Connection.release (entryConnection entry)-              restore $ poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus ReleaseConnectionTerminationReason))-              atomically $ modifyTVar' poolCapacity succ-          )-          \exc -> do-            atomically $ modifyTVar' poolCapacity succ-            case fromException exc of-              Just SomeAsyncException {} -> throwIO exc-              Nothing -> return ()---- | Terminate one expired connection on the reaper's tick: release it, report--- the termination, and give its slot back. The slot gets given back even when--- the release or the observation fails, so no capacity is lost, and a failing--- entry neither skips the other entries of the tick nor kills the reaper.-reap :: (Observation -> IO ()) -> TVar Int -> ConnectionTerminationReason -> Entry -> IO ()-reap observer capVar reason entry =-  mask \restore ->-    catch @SomeException-      ( do-          restore $ Connection.release (entryConnection entry)-          restore $ observer (ConnectionObservation (entryId entry) (TerminatedConnectionStatus reason))-          atomically $ modifyTVar' capVar succ-      )-      \exc -> do-        atomically $ modifyTVar' capVar succ-        case fromException exc of-          Just SomeAsyncException {} -> throwIO exc-          Nothing -> return ()---- | Use a connection from the pool to run a session and return the connection--- to the pool, when finished.------ Session failing with a 'Session.ClientError' gets interpreted as a loss of--- connection. In such case the connection does not get returned to the pool--- and a slot gets freed up for a new connection to be established the next--- time one is needed. The error still gets returned from this function.------ __Warning:__ Due to the mechanism mentioned above you should avoid intercepting this error type from within sessions.-use :: forall a. Pool -> Session.Session a -> IO (Either UsageError a)-use Pool {..} sess =-  mask \unmask -> do-    timeout <- do-      delay <- registerDelay poolAcquisitionTimeout-      return $ readTVar delay-    holding <- atomically $ do-      reuseVar <- readTVar poolReuseVar-      asum-        [ readTQueue poolConnectionQueue <&> EntryHolding reuseVar,-          do-            capVal <- readTVar poolCapacity-            if capVal > 0-              then do-                writeTVar poolCapacity $! pred capVal-                return $ SlotHolding reuseVar-              else retry,-          do-            timedOut <- timeout-            if timedOut-              then return TimedOutHolding-              else retry-        ]-    case holding of-      TimedOutHolding -> return $ Left AcquisitionTimeoutUsageError-      EntryHolding reuseVar entry -> onEntry unmask reuseVar entry-      SlotHolding reuseVar -> onSlot unmask reuseVar-  where-    returnSlot :: STM ()-    returnSlot = modifyTVar' poolCapacity succ--    -- \| Holding one entry dequeued from the idle connections. If it is still-    -- good, run the session on it; if it expired, replace it with a fresh-    -- connection on the same slot. All the way, the holding is given back on-    -- interruption.-    onEntry :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> IO (Either UsageError a)-    onEntry unmask reuseVar entry = do-      now <- getMonotonicTimeNSec-      if entryIsAged poolMaxLifetime now entry-        then renewEntry unmask reuseVar entry AgingConnectionTerminationReason-        else-          if entryIsIdle poolMaxIdletime now entry-            then renewEntry unmask reuseVar entry IdlenessConnectionTerminationReason-            else onLiveConn unmask reuseVar entry {entryUseTimeNSec = now}--    -- \| Holding an expired entry. Release its connection and establish a-    -- fresh one on the same slot. On interruption the slot gets given back:-    -- the released connection cannot return to the pool.-    renewEntry :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> ConnectionTerminationReason -> IO (Either UsageError a)-    renewEntry unmask reuseVar entry reason = do-      outcome <--        onException-          ( do-              Connection.release (entryConnection entry)-              unmask $ poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus reason))-              establish unmask-          )-          (atomically returnSlot)-      case outcome of-        Left err -> return $ Left err-        Right newEntry -> onLiveConn unmask reuseVar newEntry--    -- \| Holding one capacity unit. Establish a connection on it and run the-    -- session. On interruption the slot gets given back.-    onSlot :: (forall x. IO x -> IO x) -> TVar Bool -> IO (Either UsageError a)-    onSlot unmask reuseVar = do-      outcome <- onException (establish unmask) (atomically returnSlot)-      case outcome of-        Left err -> return $ Left err-        Right entry -> onLiveConn unmask reuseVar entry--    -- Run with one capacity unit held: establish the connection and run the-    -- init session on it. On any failure the slot gets given back and the-    -- error gets returned. On interruption the slot gets given back and the-    -- exception gets rethrown.-    establish :: (forall x. IO x -> IO x) -> IO (Either UsageError Entry)-    establish unmask = do-      settings <- unmask poolFetchConnectionSettings-      now <- getMonotonicTimeNSec-      id <- Uuid.nextRandom-      unmask $ poolObserver (ConnectionObservation id ConnectingConnectionStatus)-      unmask (Connection.acquire settings) >>= \case-        Left connErr -> do-          unmask $ poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (fmap (Text.decodeUtf8With Text.lenientDecode) connErr))))-          atomically returnSlot-          return $ Left $ ConnectionUsageError connErr-        Right connection ->-          unmask (Session.run poolInitSession connection) >>= \case-            Left err -> do-              Connection.release connection-              unmask-                $ ErrorsDestruction.reset-                  ( \details ->-                      poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (fmap (Text.decodeUtf8With Text.lenientDecode) details))))-                  )-                  (poolObserver (ConnectionObservation id (TerminatedConnectionStatus (InitializationErrorTerminationReason err))))-                  err-              atomically returnSlot-              return $ Left $ SessionUsageError err-            Right () -> do-              unmask $ poolObserver (ConnectionObservation id (ReadyForUseConnectionStatus EstablishedConnectionReadyForUseReason))-              return $ Right (Entry connection now now id)--    -- \| Holding one entry ready for use. Run the session on it, return the-    -- entry to the pool, and return the session result. Interrupted, the-    -- session exception gets rethrown after the entry is back in the pool.-    onLiveConn :: (forall x. IO x -> IO x) -> TVar Bool -> Entry -> IO (Either UsageError a)-    onLiveConn unmask reuseVar entry = do-      sessRes <--        onException-          ( unmask $ do-              poolObserver (ConnectionObservation (entryId entry) InUseConnectionStatus)-              try @SomeException (Session.run sess (entryConnection entry))-          )-          (returnConn reuseVar entry)--      case sessRes of-        Left exc -> do-          returnConn reuseVar entry-          throwIO exc-        Right (Left err) ->-          ErrorsDestruction.reset-            ( \details -> do-                Connection.release (entryConnection entry)-                atomically returnSlot-                unmask $ poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (fmap (Text.decodeUtf8With Text.lenientDecode) details))))-                return $ Left $ SessionUsageError err-            )-            ( do-                returnConn reuseVar entry-                unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus (SessionFailedConnectionReadyForUseReason err)))-                return $ Left $ SessionUsageError err-            )-            err-        Right (Right res) -> do-          returnConn reuseVar entry-          unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus SessionSucceededConnectionReadyForUseReason))-          return $ Right res--    -- Back to the idle connections, unless the pool was released meanwhile.-    returnConn :: TVar Bool -> Entry -> IO ()-    returnConn reuseVar entry =-      join . atomically $ do-        reuse <- readTVar reuseVar-        if reuse-          then writeTQueue poolConnectionQueue entry $> return ()-          else return $ do-            Connection.release (entryConnection entry)-            atomically returnSlot-            poolObserver (ConnectionObservation (entryId entry) (TerminatedConnectionStatus ReleaseConnectionTerminationReason))---- | What a pool request holds after the enrollment transaction commits and--- has to give back on any failure.-data Holding-  = -- | An entry dequeued from the idle connections.-    EntryHolding (TVar Bool) Entry-  | -- | A capacity unit taken from the pool.-    SlotHolding (TVar Bool)-  | -- | The acquisition timed out.-    TimedOutHolding---- | Union over all errors that 'use' can result in.-data UsageError-  = -- | Attempt to establish a connection failed.-    ConnectionUsageError Connection.ConnectionError-  | -- | Session execution failed.-    SessionUsageError Session.SessionError-  | -- | Timeout acquiring a connection.-    AcquisitionTimeoutUsageError-  deriving (Show, Eq)--instance Exception UsageError
− src/library/exposed/Hasql/Pool/Config.hs
@@ -1,25 +0,0 @@--- | DSL for construction of configs.-module Hasql.Pool.Config-  ( Config.Config,-    settings,-    Setting.Setting,-    Setting.size,-    Setting.acquisitionTimeout,-    Setting.agingTimeout,-    Setting.idlenessTimeout,-    Setting.staticConnectionSettings,-    Setting.dynamicConnectionSettings,-    Setting.observationHandler,-    Setting.initSession,-  )-where--import Hasql.Pool.Config.Config qualified as Config-import Hasql.Pool.Config.Setting qualified as Setting-import Hasql.Pool.Prelude---- | Compile config from a list of settings.--- Latter settings override the preceding in cases of conflicts.-settings :: [Setting.Setting] -> Config.Config-settings =-  foldr ($) Config.defaults . fmap Setting.apply
− src/library/exposed/Hasql/Pool/Config/Defaults.hs
@@ -1,49 +0,0 @@-module Hasql.Pool.Config.Defaults where--import Hasql.Connection.Setting qualified as Connection.Setting-import Hasql.Connection.Setting.Connection qualified as Connection.Setting.Connection-import Hasql.Pool.Observation (Observation)-import Hasql.Pool.Prelude-import Hasql.Session qualified as Session---- |--- 3 connections.-size :: Int-size = 3---- |--- 10 seconds.-acquisitionTimeout :: DiffTime-acquisitionTimeout = 10---- |--- 1 day.-agingTimeout :: DiffTime-agingTimeout = 60 * 60 * 24---- |--- 10 minutes.-idlenessTimeout :: DiffTime-idlenessTimeout = 60 * 10---- |--- > "postgresql://postgres:postgres@localhost:5432/postgres"-staticConnectionSettings :: [Connection.Setting.Setting]-staticConnectionSettings =-  [ Connection.Setting.connection (Connection.Setting.Connection.string "postgresql://postgres:postgres@localhost:5432/postgres")-  ]---- |--- > pure "postgresql://postgres:postgres@localhost:5432/postgres"-dynamicConnectionSettings :: IO [Connection.Setting.Setting]-dynamicConnectionSettings = pure staticConnectionSettings---- |--- > const (pure ())-observationHandler :: Observation -> IO ()-observationHandler = const (pure ())---- |--- > pure ()-initSession :: Session.Session ()-initSession = pure ()
− src/library/exposed/Hasql/Pool/Observation.hs
@@ -1,60 +0,0 @@--- | Interface for processing observations of the status of the pool.------ Provides a flexible mechanism for monitoring the healthiness of the pool via logs and metrics without any opinionated choices on the actual monitoring technologies.--- Specific interpreters are encouraged to be created as extension libraries.-module Hasql.Pool.Observation where--import Hasql.Pool.Prelude-import Hasql.Session qualified as Session---- | An observation of a change of the state of a pool.-data Observation-  = -- | Status of one of the pool's connections has changed.-    ConnectionObservation-      -- | Generated connection ID.-      -- For grouping the observations by one connection.-      UUID-      -- | Status that the connection has entered.-      ConnectionStatus-  deriving (Show, Eq)---- | Status of a connection.------ <<diagrams-output/connection-status-model.png>>-data ConnectionStatus-  = -- | Connection is being established.-    ---    -- This is the initial status of every connection.-    ConnectingConnectionStatus-  | -- | Connection is established and not occupied.-    ReadyForUseConnectionStatus ConnectionReadyForUseReason-  | -- | Is being used by some session.-    ---    -- After it's done the status will transition to 'ReadyForUseConnectionStatus' or 'TerminatedConnectionStatus'.-    InUseConnectionStatus-  | -- | Connection terminated.-    TerminatedConnectionStatus ConnectionTerminationReason-  deriving (Show, Eq)--data ConnectionReadyForUseReason-  = -- | Connection just got established.-    EstablishedConnectionReadyForUseReason-  | -- | Session execution ended with a failure that does not require a connection reset.-    SessionFailedConnectionReadyForUseReason Session.SessionError-  | -- | Session execution ended with success.-    SessionSucceededConnectionReadyForUseReason-  deriving (Show, Eq)---- | Explanation of why a connection was terminated.-data ConnectionTerminationReason-  = -- | The age timeout of the connection has passed.-    AgingConnectionTerminationReason-  | -- | The timeout of how long a connection may remain idle in the pool has passed.-    IdlenessConnectionTerminationReason-  | -- | Connectivity issues with the server.-    NetworkErrorConnectionTerminationReason (Maybe Text)-  | -- | User has invoked the 'Hasql.Pool.release' procedure.-    ReleaseConnectionTerminationReason-  | -- | Initialization session failure.-    InitializationErrorTerminationReason Session.SessionError-  deriving (Show, Eq)
− src/library/other/Hasql/Pool/Config/Config.hs
@@ -1,31 +0,0 @@-module Hasql.Pool.Config.Config where--import Hasql.Connection.Setting qualified as Connection.Setting-import Hasql.Pool.Config.Defaults qualified as Defaults-import Hasql.Pool.Observation (Observation)-import Hasql.Pool.Prelude-import Hasql.Session qualified as Session---- | Configuration for Hasql connection pool.-data Config = Config-  { size :: Int,-    acquisitionTimeout :: DiffTime,-    agingTimeout :: DiffTime,-    idlenessTimeout :: DiffTime,-    connectionSettingsProvider :: IO [Connection.Setting.Setting],-    observationHandler :: Observation -> IO (),-    initSession :: Session.Session ()-  }---- | Reasonable defaults, which can be built upon.-defaults :: Config-defaults =-  Config-    { size = Defaults.size,-      acquisitionTimeout = Defaults.acquisitionTimeout,-      agingTimeout = Defaults.agingTimeout,-      idlenessTimeout = Defaults.idlenessTimeout,-      connectionSettingsProvider = Defaults.dynamicConnectionSettings,-      observationHandler = Defaults.observationHandler,-      initSession = Defaults.initSession-    }
− src/library/other/Hasql/Pool/Config/Setting.hs
@@ -1,95 +0,0 @@-module Hasql.Pool.Config.Setting where--import Hasql.Connection.Setting qualified as Connection.Setting-import Hasql.Pool.Config.Config (Config)-import Hasql.Pool.Config.Config qualified as Config-import Hasql.Pool.Observation (Observation)-import Hasql.Pool.Prelude-import Hasql.Session qualified as Session--apply :: Setting -> Config -> Config-apply (Setting run) = run---- | A single setting of a config.-newtype Setting-  = Setting (Config -> Config)---- | Pool size.------ 3 by default.-size :: Int -> Setting-size x =-  Setting (\config -> config {Config.size = x})---- | Connection acquisition timeout.------ 10 seconds by default.-acquisitionTimeout :: DiffTime -> Setting-acquisitionTimeout x =-  Setting (\config -> config {Config.acquisitionTimeout = x})---- | Maximal connection lifetime.------ Determines how long is available for reuse.--- After the timeout passes and an active session is finished the connection will be closed releasing a slot in the pool for a fresh connection to be established.------ This is useful as a healthy measure for resetting the server-side caches.------ 1 day by default.-agingTimeout :: DiffTime -> Setting-agingTimeout x =-  Setting (\config -> config {Config.agingTimeout = x})---- | Maximal connection idle time.------ How long to keep a connection open when it's not being used.------ 10 minutes by default.-idlenessTimeout :: DiffTime -> Setting-idlenessTimeout x =-  Setting (\config -> config {Config.idlenessTimeout = x})---- | Connection string.------ By default it is:------ > "postgresql://postgres:postgres@localhost:5432/postgres"-staticConnectionSettings :: [Connection.Setting.Setting] -> Setting-staticConnectionSettings x =-  Setting (\config -> config {Config.connectionSettingsProvider = pure x})---- | Action providing connection settings.------ Gets used each time a connection gets established by the pool.--- This may be useful for some authorization models.------ By default it is:------ > pure "postgresql://postgres:postgres@localhost:5432/postgres"-dynamicConnectionSettings :: IO [Connection.Setting.Setting] -> Setting-dynamicConnectionSettings x =-  Setting (\config -> config {Config.connectionSettingsProvider = x})---- | Observation handler.------ An observation handler must not throw. Synchronous exceptions from it are discarded; asynchronous exceptions are honored. Its failure never affects the session result or the pool's state.------ Typically it's used for monitoring the state of the pool via metrics and logging.------ If the provided action is not lightweight, it's recommended to use intermediate bufferring via channels like TBQueue to avoid occupying the pool management thread for too long.--- E.g., if the action is @'atomically' . 'writeTBQueue' yourQueue@, then reading from it and processing can be done on a separate thread.------ By default it is:------ > const (pure ())-observationHandler :: (Observation -> IO ()) -> Setting-observationHandler x =-  Setting (\config -> config {Config.observationHandler = x})---- | Initial session.------ Gets executed on every connection upon acquisition.--- Lets you specify the connection-wide settings.-initSession :: Session.Session () -> Setting-initSession x =-  Setting (\config -> config {Config.initSession = x})
− src/library/other/Hasql/Pool/Prelude.hs
@@ -1,75 +0,0 @@-module Hasql.Pool.Prelude-  ( module Exports,-  )-where--import Control.Applicative as Exports hiding (WrappedArrow (..))-import Control.Arrow as Exports hiding (first, second)-import Control.Category as Exports-import Control.Concurrent as Exports-import Control.Concurrent.STM as Exports hiding (orElse)-import Control.Exception as Exports-import Control.Monad as Exports hiding (fail, forM, forM_, mapM, mapM_, msum, sequence, sequence_)-import Control.Monad.Fail as Exports-import Control.Monad.Fix as Exports hiding (fix)-import Control.Monad.IO.Class as Exports-import Control.Monad.ST as Exports-import Data.Bifunctor as Exports-import Data.Bits as Exports-import Data.Bool as Exports-import Data.ByteString as Exports (ByteString)-import Data.Char as Exports-import Data.Coerce as Exports-import Data.Complex as Exports-import Data.Data as Exports-import Data.Dynamic as Exports-import Data.Either as Exports-import Data.Fixed as Exports-import Data.Foldable as Exports hiding (toList)-import Data.Function as Exports hiding (id, (.))-import Data.Functor as Exports hiding (unzip)-import Data.Functor.Compose as Exports-import Data.IORef as Exports-import Data.Int as Exports-import Data.Ix as Exports-import Data.List as Exports hiding (all, and, any, concat, concatMap, elem, find, foldl, foldl', foldl1, foldr, foldr1, isSubsequenceOf, mapAccumL, mapAccumR, maximum, maximumBy, minimum, minimumBy, notElem, or, product, sortOn, sum, uncons)-import Data.List.NonEmpty as Exports (NonEmpty (..))-import Data.Maybe as Exports-import Data.Monoid as Exports hiding (Alt)-import Data.Ord as Exports-import Data.Proxy as Exports-import Data.Ratio as Exports-import Data.STRef as Exports-import Data.String as Exports-import Data.Text as Exports (Text)-import Data.Time as Exports-import Data.Traversable as Exports-import Data.Tuple as Exports-import Data.UUID as Exports (UUID)-import Data.Unique as Exports-import Data.Version as Exports-import Data.Void as Exports-import Data.Word as Exports-import Debug.Trace as Exports-import Foreign.ForeignPtr as Exports-import Foreign.Ptr as Exports-import Foreign.StablePtr as Exports-import Foreign.Storable as Exports-import GHC.Clock as Exports (getMonotonicTimeNSec)-import GHC.Conc as Exports hiding (orElse, threadWaitRead, threadWaitReadSTM, threadWaitWrite, threadWaitWriteSTM, withMVar)-import GHC.Exts as Exports (IsList (..), groupWith, inline, lazy, sortWith)-import GHC.Generics as Exports (Generic)-import GHC.IO.Exception as Exports-import Numeric as Exports-import Prelude as Exports hiding (all, and, any, concat, concatMap, elem, fail, foldl, foldl1, foldr, foldr1, id, mapM, mapM_, maximum, minimum, notElem, or, product, sequence, sequence_, sum, (.))-import System.Environment as Exports-import System.Exit as Exports-import System.IO as Exports (Handle, hClose)-import System.IO.Error as Exports-import System.IO.Unsafe as Exports-import System.Mem as Exports-import System.Mem.StableName as Exports-import System.Timeout as Exports-import Text.Printf as Exports (hPrintf, printf)-import Text.Read as Exports (Read (..), readEither, readMaybe)-import Unsafe.Coerce as Exports
− src/library/other/Hasql/Pool/SessionErrorDestructors.hs
@@ -1,10 +0,0 @@-module Hasql.Pool.SessionErrorDestructors where--import Hasql.Pool.Prelude-import Hasql.Session qualified as Session--reset :: (Maybe ByteString -> x) -> x -> Session.SessionError -> x-reset onReset onNoReset = \case-  Session.QueryError _ _ (Session.ClientError details) -> onReset details-  Session.PipelineError (Session.ClientError details) -> onReset details-  _ -> onNoReset
+ src/unit-tests/Main.hs view
@@ -0,0 +1,109 @@+module Main (main) where++import Data.Foldable (traverse_)+import Data.Text (Text)+import Data.Text qualified as Text+import Hasql.Errors qualified as Errors+import Hasql.Pool.ConnectionDiscards qualified as ConnectionDiscards+import Prelude+import Test.Hspec++main :: IO ()+main = hspec spec++spec :: Spec+spec = do+  describe "serverError" do+    describe "Discards" do+      traverse_+        discards+        [ ("XX000", "internal_error: stale plan against a retired type OID"),+          ("0A000", "feature_not_supported: cached plan must not change result type"),+          ("26000", "invalid_sql_statement_name: statement cache ledger desync"),+          ("42P05", "duplicate_prepared_statement: the same desync inverted"),+          ("25P02", "in_failed_sql_transaction: parked in an aborted transaction"),+          ("40003", "statement_completion_unknown: commit status unknown"),+          ("08000", "connection_exception"),+          ("08001", "sqlclient_unable_to_establish_sqlconnection"),+          ("08003", "connection_does_not_exist"),+          ("08004", "sqlserver_rejected_establishment_of_sqlconnection"),+          ("08006", "connection_failure"),+          ("08007", "transaction_resolution_unknown"),+          ("08P01", "protocol_violation: client and server disagree on wire state"),+          ("57P01", "admin_shutdown"),+          ("57P02", "crash_shutdown"),+          ("57P03", "cannot_connect_now"),+          ("57P04", "database_dropped"),+          ("57P05", "idle_session_timeout"),+          ("57P06", "idle_in_transaction_session_timeout")+        ]++    -- The rejections matter more than the acceptances: they are the rules+    -- most likely to be reintroduced on the strength of sounding alarming.+    describe "Retains" do+      traverse_+        retains+        [ ("53000", "insufficient_resources: a server-side shortage, not residue"),+          ("53100", "disk_full: a reconnect does not empty the disk"),+          ("53200", "out_of_memory: discarding turns a crunch into a reconnect storm"),+          ("53300", "too_many_connections: an acquisition-time error to begin with"),+          ("53400", "configuration_limit_exceeded"),+          ("25001", "active_sql_transaction: a caller bug on a healthy connection"),+          ("40001", "serialization_failure: the canonical same-connection retry"),+          ("40P01", "deadlock_detected: likewise"),+          ("57014", "query_canceled: must not be swept up by the 57P rule"),+          ("55P03", "lock_not_available: contention, not residue"),+          ("55006", "object_in_use: likewise"),+          ("58030", "io_error: the damage is on disk"),+          ("XX001", "data_corrupted: must not be swept up by the XX000 rule"),+          ("XX002", "index_corrupted: likewise"),+          ("54000", "program_limit_exceeded"),+          ("22012", "division_by_zero"),+          ("23505", "unique_violation"),+          ("42601", "syntax_error: must not be swept up by the 42P05 rule"),+          ("42P01", "undefined_table: likewise"),+          ("0A001", "a neighbour of 0A000, which is matched exactly")+        ]++  describe "statementError" do+    it "Retains on an unexpected column type, which is a decoder bug rather than residue" do+      ConnectionDiscards.statementError (Errors.UnexpectedColumnTypeStatementError 0 23 25)+        `shouldBe` False+    it "Retains on an unexpected row count" do+      ConnectionDiscards.statementError (Errors.UnexpectedRowCountStatementError 1 1 2)+        `shouldBe` False+    it "Retains on an unexpected column count" do+      ConnectionDiscards.statementError (Errors.UnexpectedColumnCountStatementError 2 3)+        `shouldBe` False+    it "Retains on an unexpected result" do+      ConnectionDiscards.statementError (Errors.UnexpectedResultStatementError "whatever")+        `shouldBe` False+    it "Defers to the server error it wraps" do+      ConnectionDiscards.statementError (Errors.ServerStatementError (serverErrorWithCode "XX000"))+        `shouldBe` True++  describe "sessionError" do+    it "Retains on missing types, whose lookup leaves the connection untouched" do+      ConnectionDiscards.sessionError (Errors.MissingTypesSessionError mempty)+        `shouldBe` False+    it "Defers to the server error a failed script carries" do+      ConnectionDiscards.sessionError (Errors.ScriptSessionError "select 1" (serverErrorWithCode "26000"))+        `shouldBe` True+    it "Defers to the statement error a failed statement carries" do+      ConnectionDiscards.sessionError+        (Errors.StatementSessionError 1 0 "select 1" [] False (Errors.UnexpectedRowCountStatementError 1 1 0))+        `shouldBe` False++discards :: (Text, String) -> Spec+discards (code, why) =+  it ("Discards on " <> Text.unpack code <> " - " <> why) do+    ConnectionDiscards.serverError (serverErrorWithCode code) `shouldBe` True++retains :: (Text, String) -> Spec+retains (code, why) =+  it ("Retains on " <> Text.unpack code <> " - " <> why) do+    ConnectionDiscards.serverError (serverErrorWithCode code) `shouldBe` False++serverErrorWithCode :: Text -> Errors.ServerError+serverErrorWithCode code =+  Errors.ServerError code "synthetic" Nothing Nothing Nothing