sandwich-contexts 0.3.0.4 → 0.3.1.0
raw patch · 7 files changed
+331/−13 lines, 7 files
Files
- CHANGELOG.md +8/−0
- LICENSE +30/−0
- lib/Test/Sandwich/Contexts/MySQL.hs +265/−0
- lib/Test/Sandwich/Contexts/Nix.hs +6/−3
- lib/Test/Sandwich/Contexts/PostgreSQL.hs +9/−4
- lib/Test/Sandwich/Contexts/ReverseProxy/TCP.hs +7/−3
- sandwich-contexts.cabal +6/−3
CHANGELOG.md view
@@ -1,5 +1,13 @@ # Changelog for sandwich-contexts +## 0.3.1.0++* Export `renderDerivationWithPkgs` from `Test.Sandwich.Contexts.Nix`.+* Add `Test.Sandwich.Contexts.MySQL`, for MySQL/MariaDB via Nix (`introduceMysqlViaNix`), with an option to choose the auth plugin (e.g. `caching_sha2_password`).+* The TCP-to-Unix-socket proxy now closes the connection when either side closes.+* Postgres contexts now report `127.0.0.1` instead of `localhost` in `postgresAddress` and `postgresConnString`, so clients don't try IPv6 `::1` first and fail to connect. The TCP-to-Unix-socket proxy now listens on loopback only.+* Bump `nixpkgsMaster` to a commit from 10/22/2026.+ ## 0.3.0.4 * Use the latest process file logging and managed asyncs from `sandwich`.
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright Tom McLaughlin (c) 2026++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of Tom McLaughlin nor the names of other+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ lib/Test/Sandwich/Contexts/MySQL.hs view
@@ -0,0 +1,265 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeOperators #-}++{-|+Provides a MySQL/MariaDB database, using a suitable package from Nix. The server+is started listening on a Unix socket (short path) and exposed to the test as a+TCP address via a reverse proxy, matching "Test.Sandwich.Contexts.PostgreSQL".++Both MariaDB and Oracle MySQL are supported: the flavor is detected from the Nix+package's binaries (MariaDB ships @mariadb-install-db@; MySQL does not), and the+appropriate init/start commands are used for each.+-}+module Test.Sandwich.Contexts.MySQL (+ -- * Nix+ introduceMysqlViaNix+ , withMysqlViaNix+ , withMysqlViaNix'++ -- * Options+ , MysqlNixOptions(..)+ , defaultMysqlNixOptions+ , MysqlAuthPlugin(..)++ -- * Types+ , mysql+ , MysqlContext(..)+ , MysqlVariant(..)++ , NetworkAddress(..)+ ) where++import Control.Monad+import Control.Monad.Catch (MonadMask)+import Control.Monad.IO.Unlift+import Control.Monad.Logger+import Data.String.Interpolate+import qualified Data.Text as T+import Relude+import System.Exit+import System.FilePath+import System.IO.Temp+import Test.Sandwich+import Test.Sandwich.Contexts.Nix+import Test.Sandwich.Contexts.ReverseProxy.TCP+import Test.Sandwich.Contexts.Types.Network+import Test.Sandwich.Contexts.UnixSocketPath+import UnliftIO.Async+import UnliftIO.Concurrent (threadDelay)+import UnliftIO.Directory+import UnliftIO.Exception+import UnliftIO.Process+++-- * Labels++mysql :: Label "mysql" MysqlContext+mysql = Label++-- * Types++data MysqlNixOptions = MysqlNixOptions {+ -- | MariaDB or Oracle MySQL package to use within the Nixpkgs snapshot of your+ -- 'NixContext'. Defaults to @mariadb@; @mysql80@ (etc.) selects Oracle MySQL.+ mysqlNixPackage :: Text+ -- | Username to create. Default @test@.+ , mysqlNixUsername :: Text+ -- | Password for the created user. Default @test@.+ , mysqlNixPassword :: Text+ -- | Database to create. Default @test@.+ , mysqlNixDatabase :: Text+ -- | Auth plugin for the created user, on the Oracle MySQL flavor only (MariaDB+ -- always uses native password). Default 'NativePassword'.+ , mysqlNixAuthPlugin :: MysqlAuthPlugin+ }+defaultMysqlNixOptions :: MysqlNixOptions+defaultMysqlNixOptions = MysqlNixOptions {+ mysqlNixPackage = "mariadb"+ , mysqlNixUsername = "test"+ , mysqlNixPassword = "test"+ , mysqlNixDatabase = "test"+ , mysqlNixAuthPlugin = NativePassword+ }++-- | MySQL authentication plugin for the created user. MySQL 8 defaults new users+-- to @caching_sha2_password@; 'NativePassword' forces the simpler+-- @mysql_native_password@ (what most lightweight clients and credential-forwarding+-- proxies speak).+data MysqlAuthPlugin = NativePassword | CachingSha2Password+ deriving (Show, Eq)++-- | Which flavor of server a Nix package provides.+data MysqlVariant = MariaDB | MySQL+ deriving (Show, Eq)++data MysqlContext = MysqlContext {+ mysqlUsername :: Text+ , mysqlPassword :: Text+ , mysqlDatabase :: Text+ , mysqlVariant :: MysqlVariant+ , mysqlAddress :: NetworkAddress+ , mysqlConnString :: Text+ } deriving (Show)+++-- | Introduce a MySQL/MariaDB instance, using a suitable package from Nix.+introduceMysqlViaNix :: (+ HasBaseContext context, HasNixContext context+ , MonadUnliftIO m, MonadMask m+ )+ -- | Options+ => MysqlNixOptions+ -> SpecFree (LabelValue "mysql" MysqlContext :> context) m ()+ -> SpecFree context m ()+introduceMysqlViaNix opts = introduceWith "MySQL via Nix" mysql $ \action ->+ withMysqlViaNix opts (void . action)++-- | Bracket-style variant of 'introduceMysqlViaNix'.+withMysqlViaNix :: (+ HasBaseContextMonad context m, HasNixContext context+ , MonadUnliftIO m, MonadMask m, MonadFail m, MonadLoggerIO m+ )+ -- | Options+ => MysqlNixOptions+ -> (MysqlContext -> m a)+ -> m a+withMysqlViaNix opts action = do+ nc <- getContext nixContext+ withMysqlViaNix' nc opts action++-- | Lower-level variant of 'withMysqlViaNix'.+withMysqlViaNix' :: (+ HasBaseContextMonad context m+ , MonadUnliftIO m, MonadMask m, MonadFail m, MonadLoggerIO m+ )+ -- | Nix context+ => NixContext+ -- | Options+ -> MysqlNixOptions+ -> (MysqlContext -> m a)+ -> m a+withMysqlViaNix' nc (MysqlNixOptions {..}) action = do+ binDir <- (</> "bin") <$> buildNixPackage' nc mysqlNixPackage+ variant <- detectVariant binDir+ Just dir <- getCurrentFolder+ baseDir <- liftIO $ createTempDirectory dir "mysql-nix"+ let dataDir = baseDir </> "data"++ -- The Unix socket path has a short length limit (~107 bytes), so keep it out of+ -- the (potentially long) sandwich test tree.+ withUnixSocketDirectory "mysql-sock" 20 $ \sockDir -> do+ let sock = sockDir </> "mysqld.sock"+ bracket+ (do+ -- Initialize the data directory (root authenticates over the socket).+ case variant of+ MariaDB ->+ runProc dir binDir "mariadb-install-db" [+ "--no-defaults"+ , "--datadir=" <> dataDir+ , "--auth-root-authentication-method=normal"+ ]+ MySQL -> do+ createDirectoryIfMissing True dataDir+ runProc dir binDir "mysqld" [+ "--no-defaults"+ , "--initialize-insecure"+ , "--datadir=" <> dataDir+ ]++ -- Start the server on the Unix socket only (TCP comes from the proxy).+ (_, serverAsy) <- createProcessWithLogging ((proc (binDir </> serverBin variant) (+ [ "--no-defaults"+ , "--datadir=" <> dataDir+ , "--socket=" <> sock+ , "--skip-networking"+ , "--pid-file=" <> (baseDir </> "mysqld.pid")+ ] <> serverExtraArgs variant)) { cwd = Just dir })++ waitForReady binDir sock++ -- Create the user + database.+ runProc dir binDir "mysql" [+ "--no-defaults", "--socket=" <> sock+ , "-u", "root"+ , "-e", toString (setupSql variant)+ ]++ pure serverAsy+ )+ (\serverAsy -> do+ void $ tryAny $ readProcessWithExitCode (binDir </> "mysqladmin") [+ "--no-defaults", "--socket=" <> sock+ , "-u", "root"+ , "shutdown"+ ] ""+ cancel serverAsy)+ (\_ ->+ withProxyToUnixSocket sock $ \port ->+ action MysqlContext {+ mysqlUsername = mysqlNixUsername+ , mysqlPassword = mysqlNixPassword+ , mysqlDatabase = mysqlNixDatabase+ , mysqlVariant = variant+ -- 127.0.0.1 rather than "localhost"; same reason as Postgres. The+ -- setup SQL grants to '%' as well as 'localhost', so this still matches.+ , mysqlAddress = NetworkAddressTCP "127.0.0.1" (fromIntegral port)+ , mysqlConnString = [i|mysql://#{mysqlNixUsername}:#{mysqlNixPassword}@127.0.0.1:#{port}/#{mysqlNixDatabase}|]+ })+ where+ -- MariaDB always uses native password auth. On MySQL, the auth plugin is chosen+ -- by 'mysqlNixAuthPlugin' (default native, so lightweight clients and+ -- credential-forwarding proxies can authenticate; caching_sha2 is opt-in).+ setupSql variant = T.concat+ [ "CREATE DATABASE IF NOT EXISTS ", mysqlNixDatabase, "; "+ , "CREATE USER '", mysqlNixUsername, "'@'%' ", authClause variant, "; "+ , "CREATE USER '", mysqlNixUsername, "'@'localhost' ", authClause variant, "; "+ , "GRANT ALL PRIVILEGES ON ", mysqlNixDatabase, ".* TO '", mysqlNixUsername, "'@'%'; "+ , "GRANT ALL PRIVILEGES ON ", mysqlNixDatabase, ".* TO '", mysqlNixUsername, "'@'localhost'; "+ , "FLUSH PRIVILEGES;"+ ]+ authClause MariaDB = "IDENTIFIED BY '" <> mysqlNixPassword <> "'"+ authClause MySQL = "IDENTIFIED WITH " <> pluginName mysqlNixAuthPlugin <> " BY '" <> mysqlNixPassword <> "'"+ pluginName NativePassword = "mysql_native_password"+ pluginName CachingSha2Password = "caching_sha2_password"++-- | Detect the server flavor from the package's binaries: only MariaDB ships+-- @mariadb-install-db@.+detectVariant :: MonadIO m => FilePath -> m MysqlVariant+detectVariant binDir = do+ isMaria <- doesFileExist (binDir </> "mariadb-install-db")+ pure $ if isMaria then MariaDB else MySQL++serverBin :: MysqlVariant -> FilePath+serverBin MariaDB = "mariadbd"+serverBin MySQL = "mysqld"++-- | Disable MySQL's X plugin so it doesn't try to open its own network port.+serverExtraArgs :: MysqlVariant -> [String]+serverExtraArgs MariaDB = []+serverExtraArgs MySQL = ["--mysqlx=0"]++-- | Poll @mysqladmin ping@ until the server accepts connections.+waitForReady :: (MonadUnliftIO m, MonadLoggerIO m) => FilePath -> FilePath -> m ()+waitForReady binDir sock = go (150 :: Int)+ where+ go 0 = expectationFailure "MySQL server did not become ready in time"+ go n = do+ (code, _, _) <- liftIO $ readProcessWithExitCode (binDir </> "mysqladmin") [+ "--no-defaults", "--socket=" <> sock, "-u", "root", "ping"+ ] ""+ case code of+ ExitSuccess -> pure ()+ _ -> threadDelay 200_000 >> go (n - 1)++runProc :: (HasBaseContextMonad context m, MonadUnliftIO m, MonadLoggerIO m) => FilePath -> FilePath -> FilePath -> [String] -> m ()+runProc dir binDir binName args = do+ (ps, asy) <- createProcessWithLogging ((proc (binDir </> binName) args) { cwd = Just dir })+ finally (waitForProcess ps >>= (`shouldBe` ExitSuccess)) (cancel asy)
lib/Test/Sandwich/Contexts/Nix.hs view
@@ -54,6 +54,9 @@ , nixpkgsRelease2405 , nixpkgsRelease2311 + -- * Lower-level+ , renderDerivationWithPkgs+ -- * Types , nixContext , NixContext(..)@@ -125,15 +128,15 @@ , nixpkgsDerivationAllowUnfree :: Bool } deriving (Show, Eq) --- | Nixpkgs master, accessed 6\/28\/2025.+-- | Nixpkgs master, accessed 10\/22\/2026. -- You can compute updated values for this release (or others) by running -- nix-prefetch-github NixOS nixpkgs --rev master nixpkgsMaster :: NixpkgsDerivation nixpkgsMaster = NixpkgsDerivationFetchFromGitHub { nixpkgsDerivationOwner = "NixOS" , nixpkgsDerivationRepo = "nixpkgs"- , nixpkgsDerivationRev = "40a8fd31ccc6d87eff8e8aae833d213b10bb9f50"- , nixpkgsDerivationSha256 = "sha256-HXlk/16dnoQqy2wjizF1uA7b1gNS8iYFq7vSAG2P8dk="+ , nixpkgsDerivationRev = "02c087f3fe673c9e317f206a627cb6b910336dbe"+ , nixpkgsDerivationSha256 = "sha256-IoNisKcGbUjdd45qCqywGMCYmZ5EnkxezvLII0FWwNA=" , nixpkgsDerivationAllowUnfree = False }
lib/Test/Sandwich/Contexts/PostgreSQL.hs view
@@ -171,8 +171,12 @@ postgresUsername = postgresNixUsername , postgresPassword = postgresNixPassword , postgresDatabase = postgresNixDatabase- , postgresAddress = NetworkAddressTCP "localhost" port- , postgresConnString = [i|postgresql://#{postgresNixUsername}:#{postgresNixPassword}@localhost:#{port}/#{postgresNixDatabase}|]+ -- 127.0.0.1, not "localhost": the proxy binds IPv4 loopback, and+ -- "localhost" resolves to ::1 first wherever IPv6 is up (e.g. a k8s pod,+ -- whose /etc/hosts maps both), which strands clients that try only the+ -- first resolved address.+ , postgresAddress = NetworkAddressTCP "127.0.0.1" port+ , postgresConnString = [i|postgresql://#{postgresNixUsername}:#{postgresNixPassword}@127.0.0.1:#{port}/#{postgresNixDatabase}|] , postgresContainerAddress = Nothing } @@ -413,8 +417,9 @@ postgresUsername = postgresContainerUser , postgresPassword = postgresContainerPassword , postgresDatabase = postgresContainerUser- , postgresAddress = NetworkAddressTCP "localhost" localPort- , postgresConnString = [i|postgresql://#{postgresContainerUser}:#{postgresContainerPassword}@localhost:#{localPort}/#{postgresContainerUser}|]+ -- 127.0.0.1 rather than "localhost"; see the note in withPostgresViaNix'.+ , postgresAddress = NetworkAddressTCP "127.0.0.1" localPort+ , postgresConnString = [i|postgresql://#{postgresContainerUser}:#{postgresContainerPassword}@127.0.0.1:#{localPort}/#{postgresContainerUser}|] , postgresContainerAddress = Just $ NetworkAddressTCP (toString containerName) 5432 }
lib/Test/Sandwich/Contexts/ReverseProxy/TCP.hs view
@@ -15,7 +15,7 @@ import Network.Socket import Relude import Test.Sandwich (expectationFailure, HasBaseContextMonad, managedWithAsync_)-import UnliftIO.Async (concurrently_)+import UnliftIO.Async (race_) import UnliftIO.Exception import UnliftIO.Timeout @@ -23,7 +23,9 @@ withProxyToUnixSocket :: (MonadUnliftIO m, HasBaseContextMonad context m) => FilePath -> (PortNumber -> m a) -> m a withProxyToUnixSocket socketPath f = do portVar <- newEmptyMVar- let ss = DCN.serverSettings 0 "*"+ -- Loopback only: this fronts a test database, so there's no reason to accept+ -- connections from the network.+ let ss = DCN.serverSettings 0 "127.0.0.1" & setAfterBind (\sock -> do getSocketName sock >>= \case SockAddrInet port _ -> putMVar portVar port@@ -37,7 +39,9 @@ Just port -> f port where+ -- Use race_ (not concurrently_) so that when either direction closes, the+ -- other is torn down and the peer socket is closed. app appdata = DCNU.runUnixClient (DCNU.clientSettings socketPath) $ \appdataServer ->- concurrently_+ race_ (runConduit $ DCN.appSource appdata .| DCN.appSink appdataServer) (runConduit $ DCN.appSource appdataServer .| DCN.appSink appdata)
sandwich-contexts.cabal view
@@ -1,17 +1,19 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.38.1.+-- This file has been generated from package.yaml by hpack version 0.39.1. -- -- see: https://github.com/sol/hpack name: sandwich-contexts-version: 0.3.0.4+version: 0.3.1.0 synopsis: Contexts for the Sandwich test library description: Please see the <https://codedownio.github.io/sandwich documentation>.+category: Testing author: Tom McLaughlin maintainer: tom@codedown.io-copyright: 2025 Tom McLaughlin+copyright: 2026 Tom McLaughlin license: BSD3+license-file: LICENSE build-type: Simple extra-source-files: CHANGELOG.md@@ -23,6 +25,7 @@ Test.Sandwich.Contexts.Files Test.Sandwich.Contexts.HttpWaits Test.Sandwich.Contexts.Nix+ Test.Sandwich.Contexts.MySQL Test.Sandwich.Contexts.PostgreSQL Test.Sandwich.Contexts.Types.Network Test.Sandwich.Contexts.Types.S3