packages feed

dag-migrations-conformance-0.1.0.0 / src / Database / DagMigrations / Conformance.hs

-- | A test suite that every adapter runs against its database, to show that-- it satisfies the adapter contract of "Database.DagMigrations.Adapter".-- An adapter's test suite builds a t'Fixture' for its database, and runs-- 'adapterConformance' on it with hspec.module Database.DagMigrations.Conformance  ( Fixture (..),    adapterConformance,  )whereimport Control.Concurrent (forkFinally, threadDelay)import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, readMVar, tryPutMVar, tryReadMVar)import Control.Exception (ErrorCall (..), SomeException, finally, throwIO)import Control.Monad.IO.Class (liftIO)import Control.Monad.Trans.Class (lift)import Control.Monad.Trans.Except (ExceptT (..), runExceptT, throwE)import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)import Data.Either (isLeft)import Data.Foldable (traverse_)import Data.IORef (IORef, modifyIORef', newIORef, readIORef)import Data.List.NonEmpty (NonEmpty (..))import Data.Map.Strict (Map)import Data.Map.Strict qualified as Mapimport Data.Maybe (fromMaybe)import Data.Set qualified as Setimport Data.Text (Text)import Data.Void (Void, absurd)import Database.DagMigrationsimport Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..), BootstrapOutcome (..))import System.Timeout (timeout)import Test.Hspec-- | The operations that the suite needs from the database under test. @db@-- is a handle to one database, @tx@ is the adapter's transaction value, and-- @ae@ is the adapter's error type. The suite names its markers with short-- lowercase ASCII words, such as @a@.data Fixture db tx ae = Fixture  { -- | Creates an empty database, passes it to the action, and removes the    -- database when the action returns or throws.    withEmptyDatabase :: forall a. (db -> IO a) -> IO a,    -- | Opens a session on the database, passes the adapter over it to the    -- action, and closes the session when the action returns or throws.    -- The suite uses sessions from separate calls at the same time, on    -- separate threads, to test the run lock. A session sets no limit on    -- the wait for the run lock, such as PostgreSQL's @lock_timeout@, that    -- is shorter than the suite's waits of five seconds.    withAdapter :: forall a. db -> (Adapter tx ae -> IO a) -> IO a,    -- | Creates the marker with this name inside the transaction. For an    -- SQL database, a marker is a table. When the marker exists, the call    -- throws the exception of the adapter's database library.    createMarker :: tx -> Text -> IO (),    -- | Drops the marker with this name inside the transaction. When the    -- marker does not exist, the call throws the exception of the    -- adapter's database library.    dropMarker :: tx -> Text -> IO (),    -- | Returns whether the database holds the marker with this name in    -- committed state, as another session sees it.    markerExists :: db -> Text -> IO Bool,    -- | Throws the exception of the adapter's database library inside the    -- transaction, as the library does when the database rejects a    -- statement.    failInLibrary :: tx -> IO (),    -- | Commits a @dbmigrations@ tracking table that holds these rows, in a    -- database that has no tracking table. 'Nothing' means that the    -- adapter does not recognize that table, and the suite skips its    -- version 0 cases.    seedVersion0 :: Maybe (db -> [Text] -> IO ())  }-- | The monad of the suite's test migrations: they read the transaction,-- and fail with text.type ConformanceM tx = ReaderT tx (ExceptT Text IO)-- | The specification that every adapter must pass. Each case calls-- 'withEmptyDatabase' once. Run the cases one at a time, not in hspec's-- parallel mode. The lock cases need the adapter's blocking calls to let-- other Haskell threads run, so build the test suite with @-threaded@. The-- suite waits at most five seconds for any session.adapterConformance :: (Eq ae, Show ae) => Fixture db tx ae -> SpecadapterConformance fixture = describe "adapter conformance" $ do  describe "bootstrap" $ do    it "creates the tracking table, and then does nothing" $      session fixture $ \_ adapter -> do        created <- bootstrap adapter        created `shouldSatisfy` isCreated        bootstrap adapter `shouldReturn` Right AlreadyCurrent    it "reads nothing, and creates nothing, before the table exists" $      session fixture $ \_ adapter -> do        readApplied adapter `shouldReturn` Right Map.empty        run <- newRun adapter defaultRunSettings (abc fixture)        fmap appliedSet <$> inspect (runMigrator run) `shouldReturn` Right Set.empty        -- 'Created' shows that neither call created the table.        created <- bootstrap adapter        created `shouldSatisfy` isCreated  describe "migrate" $ do    it "applies every migration, and records a row for each" $      session fixture $ \db adapter -> do        run <- newRun adapter defaultRunSettings (abc fixture)        migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()        Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a", "b", "c"]        traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [True, True, True]    it "reverts what depends on the target, and keeps the target" $      session fixture $ \db adapter -> do        run <- newRun adapter defaultRunSettings (abc fixture)        migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()        migrate (runMigrator run) Down (TargetMigration "a") `shouldReturn` Right ()        Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]        traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [True, False, False]  describe "atomicity" $ do    it "rolls back a migration that fails, and keeps the steps before it" $      session fixture $ \db adapter -> do        let failing = (markerMigration fixture "b" ["a"]) {migrationUp = mark fixture "b" >> lift (throwE "boom")}        run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], failing]        migrate (runMigrator run) Up AllMigrations          `shouldReturn` Left (MigrationFailed "b" Up (Right "boom"))        commitNothing adapter        Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]        traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]    it "rolls back a failure of the database library, and reports the adapter's error" $      session fixture $ \db adapter -> do        let failing =              (markerMigration fixture "b" ["a"])                { migrationUp = mark fixture "b" >> (ask >>= liftIO . failInLibrary fixture)                }        run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], failing]        result <- migrate (runMigrator run) Up AllMigrations        result `shouldSatisfy` isAdapterFailureOf "b"        commitNothing adapter        Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]        traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]    it "rolls back and rethrows any other exception, and releases the lock" $      session fixture $ \db adapter -> do        let throwing =              (markerMigration fixture "b" ["a"])                { migrationUp = mark fixture "b" >> liftIO (throwIO (ErrorCall "thrown"))                }        run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], throwing]        migrate (runMigrator run) Up AllMigrations `shouldThrow` (== ErrorCall "thrown")        commitNothing adapter        Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]        traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]        released <- timeout lockWait (withAdapter fixture db (\other -> withRunLock other (pure ())))        released `shouldBe` Just (Right ())  describe "the run lock" $ do    it "keeps a second session waiting until the first releases the lock" $      withEmptyDatabase fixture $ \db -> do        entered <- newEmptyMVar        attempting <- newEmptyMVar        release <- newEmptyMVar        firstDone <- newEmptyMVar        secondDone <- newEmptyMVar        let holder = withAdapter fixture db $ \first ->              withRunLock first (putMVar entered () >> readMVar release)            contender = withAdapter fixture db $ \second ->              putMVar attempting () >> withRunLock second (pure ())            -- Lets the first session finish, and waits for both sessions            -- to close, so that the database can be removed.            finish = do              _ <- tryPutMVar release ()              traverse_ (timeout lockWait . readMVar) [firstDone, secondDone]        flip finally finish $ do          _ <- forkFinally holder (putMVar firstDone)          timeout lockWait (readMVar entered) `shouldReturn` Just ()          _ <- forkFinally contender (putMVar secondDone)          timeout lockWait (readMVar attempting) `shouldReturn` Just ()          threadDelay contentionDelay          early <- tryReadMVar secondDone          traverse_ (expectationFailure . contentionFailure) early          _ <- tryPutMVar release ()          awaitSession firstDone          awaitSession secondDone    it "frees the lock after an interrupted wait, once that session closes" $      withEmptyDatabase fixture $ \db -> do        entered <- newEmptyMVar        release <- newEmptyMVar        firstDone <- newEmptyMVar        interruptedDone <- newEmptyMVar        let holder = withAdapter fixture db $ \first ->              withRunLock first (putMVar entered () >> readMVar release)            interrupted = withAdapter fixture db $ \second ->              timeout contentionDelay (withRunLock second (pure ()))            -- Lets the first session finish, and waits for both sessions            -- to close, so that the database can be removed.            finish = do              _ <- tryPutMVar release ()              _ <- timeout lockWait (readMVar firstDone)              timeout lockWait (readMVar interruptedDone)        flip finally finish $ do          _ <- forkFinally holder (putMVar firstDone)          timeout lockWait (readMVar entered) `shouldReturn` Just ()          _ <- forkFinally interrupted (putMVar interruptedDone)          outcome <- timeout lockWait (readMVar interruptedDone)          traverse_ expectationFailure (interruptionFailure outcome)          _ <- tryPutMVar release ()          awaitSession firstDone          third <- timeout lockWait (withAdapter fixture db (\other -> withRunLock other (pure ())))          third `shouldBe` Just (Right ())  describe "rows" $ do    it "fails to record a row that exists, and changes nothing" $      session fixture $ \_ adapter -> do        _ <- bootstrap adapter        recordRow adapter (markerRow "a" Nothing) `shouldReturn` Right ()        again <- recordRow adapter (markerRow "a" (Just (Fingerprint "other")))        again `shouldSatisfy` isLeft        applied adapter `shouldReturn` Map.fromList [("a", Nothing)]    it "fails to remove a row that does not exist, and changes nothing" $      session fixture $ \_ adapter -> do        _ <- bootstrap adapter        recordRow adapter (markerRow "b" Nothing) `shouldReturn` Right ()        removed <- committing adapter (\tx -> removeApplied adapter tx "a")        removed `shouldSatisfy` isLeft        applied adapter `shouldReturn` Map.fromList [("b", Nothing)]    it "undoes the row changes of a transaction that rolls back" $      session fixture $ \_ adapter -> do        _ <- bootstrap adapter        recordRow adapter (markerRow "a" Nothing) `shouldReturn` Right ()        rollingBack          adapter          ( \tx -> runExceptT $ do              ExceptT (recordApplied adapter tx (markerRow "b" Nothing))              ExceptT (recordFingerprints adapter tx (Map.fromList [("a", Just (Fingerprint "v1"))]))              ExceptT (removeApplied adapter tx "a")          )          `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Nothing)]  describe "fingerprints" $    it "records fingerprints, rejects a mismatch, and accepts a change" $      session fixture $ \_ adapter -> do        let v1 = Fingerprint "v1"            v2 = Fingerprint "v2"            vb = Fingerprint "vb"            -- Migration a has the given fingerprint, and b always has vb.            runWith fingerprintA =              newRun                adapter                defaultRunSettings                [ (markerMigration fixture "a" []) {migrationFingerprint = fingerprintA},                  (markerMigration fixture "b" []) {migrationFingerprint = Just vb}                ]        plain <- runWith Nothing        migrate (runMigrator plain) Up AllMigrations `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]        first <- runWith (Just v1)        migrate (runMigrator first) Up AllMigrations `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Just v1), ("b", Just vb)]        second <- runWith (Just v2)        migrate (runMigrator second) Up AllMigrations          `shouldReturn` Left (FingerprintsMismatched (FingerprintMismatch "a" (Just v1) (Just v2) :| []))        applied adapter `shouldReturn` Map.fromList [("a", Just v1), ("b", Just vb)]        acceptFingerprints (runMigrator second) (Set.fromList ["a"]) `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Just v2), ("b", Just vb)]        cleared <- runWith Nothing        acceptFingerprints (runMigrator cleared) (Set.fromList ["a"]) `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]        committing adapter (\tx -> recordFingerprints adapter tx (Map.fromList [("z", Just v1)]))          `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]  traverse_ (version0 fixture) (seedVersion0 fixture)-- | The cases for an adapter that recognizes the @dbmigrations@ table. They-- read the table only through the adapter, which leaves out the row-- @root@, so they cannot show that a failed upgrade kept that row. The-- adapter's own tests check it.version0 :: (Eq ae, Show ae) => Fixture db tx ae -> (db -> [Text] -> IO ()) -> Specversion0 fixture seed = describe "version 0" $ do  it "reads a version 0 table without its root row" $    withEmptyDatabase fixture $ \db -> do      seed db ["root", "a"]      withAdapter fixture db $ \adapter ->        applied adapter `shouldReturn` Map.fromList [("a", Nothing)]  it "upgrades a version 0 table to the current version, and keeps its rows without root" $    withEmptyDatabase fixture $ \db -> do      seed db ["root", "a", "b"]      withAdapter fixture db $ \adapter -> do        run <- newRun adapter defaultRunSettings (abc fixture)        migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()        firstEvent <- take 1 <$> readEvents run        map isUpgradeFromVersion0 firstEvent `shouldBe` [True]        applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]        traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [False, False, True]        bootstrap adapter `shouldReturn` Right AlreadyCurrent        again <- recordRow adapter (markerRow "a" Nothing)        again `shouldSatisfy` isLeft        committing adapter (\tx -> recordFingerprints adapter tx (Map.fromList [("a", Just (Fingerprint "v1"))]))          `shouldReturn` Right ()        applied adapter          `shouldReturn` Map.fromList [("a", Just (Fingerprint "v1")), ("b", Nothing), ("c", Nothing)]  it "upgrades a version 0 table that holds identifiers in several rows, and keeps one row for each identifier" $    withEmptyDatabase fixture $ \db -> do      seed db ["root", "a", "b", "a", "root"]      withAdapter fixture db $ \adapter -> do        run <- newRun adapter defaultRunSettings (abc fixture)        migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]        traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [False, False, True]        again <- recordRow adapter (markerRow "a" Nothing)        again `shouldSatisfy` isLeft        committing adapter (\tx -> removeApplied adapter tx "a") `shouldReturn` Right ()        applied adapter `shouldReturn` Map.fromList [("b", Nothing), ("c", Nothing)]-- | A migrator over an adapter, and the events that its runs report, in-- the order of reporting.data Run tx ae = Run  { runMigrator :: Migrator Text (ConformanceM tx) tx Text ae,    runEvents :: IORef [ProgressEvent Text]  }-- | Validates the registry, and builds a migrator over the adapter that-- records its events. Throws an 'IOError', which fails the test, when the-- registry is not valid.newRun ::  Adapter tx ae ->  RunSettings ->  [Migration Text (ConformanceM tx)] ->  IO (Run tx ae)newRun adapter settings registry = do  events <- newIORef []  graph <- either (ioError . userError . show) pure (validate registry)  pure    Run      { runMigrator =          Migrator            { migratorAdapter = adapter,              migratorCodec = textIdentifiers,              migratorInterpreter = Interpreter (\tx action -> runExceptT (runReaderT action tx)),              migratorProgress = Progress (\event -> modifyIORef' events (event :)),              migratorSettings = settings,              migratorGraph = graph            },        runEvents = events      }-- | The events of a run's migrator, in the order of reporting.readEvents :: Run tx ae -> IO [ProgressEvent Text]readEvents run = reverse <$> readIORef (runEvents run)-- | Opens a session on a new empty database.session :: Fixture db tx ae -> (db -> Adapter tx ae -> IO a) -> IO asession fixture use = withEmptyDatabase fixture $ \db -> withAdapter fixture db (use db)-- | The applied rows, or a test failure that shows the adapter's error.applied :: (Show ae) => Adapter tx ae -> IO (Map Text (Maybe Fingerprint))applied adapter =  readApplied adapter >>= either (\err -> expectationFailure (show err) >> pure Map.empty) pure-- | Runs the operation in a transaction that commits whatever the-- operation returns, and gives back the operation's result.committing :: Adapter tx ae -> (tx -> IO (Either ae a)) -> IO (Either ae a)committing adapter operation = do  result <- withTransaction adapter (fmap (Right @Void) . operation)  pure $ case result of    Left (Left err) -> Left err    Left (Right impossible) -> absurd impossible    Right outcome -> outcome-- | Runs the operation in a transaction that rolls back whatever the-- operation returns, and gives back the operation's result.rollingBack :: Adapter tx ae -> (tx -> IO (Either ae a)) -> IO (Either ae a)rollingBack adapter operation = do  result <- withTransaction adapter (fmap (Left @_ @Void) . operation)  pure $ case result of    Left (Left err) -> Left err    Left (Right outcome) -> outcome    Right impossible -> absurd impossible-- | Commits an empty transaction in the session, and fails the test when-- the adapter reports an error. When the adapter left an earlier-- transaction open instead of rolling it back, this commit makes that-- transaction's writes visible to the checks that follow.commitNothing :: (Eq ae, Show ae) => Adapter tx ae -> ExpectationcommitNothing adapter = committing adapter (\_ -> pure (Right ())) `shouldReturn` Right ()-- | Records the row in a transaction of its own.recordRow :: Adapter tx ae -> AppliedRow -> IO (Either ae ())recordRow adapter row = committing adapter (\tx -> recordApplied adapter tx row)-- | The row of the marker migration with this name.markerRow :: Text -> Maybe Fingerprint -> AppliedRowmarkerRow name = AppliedRow name ("marker " <> name)-- | Waits for a session of the lock test to finish. Fails the test when the-- session does not finish in time, when it threw, or when the run lock-- returned the adapter's error.awaitSession :: (Show ae) => MVar (Either SomeException (Either ae ())) -> ExpectationawaitSession done = do  outcome <- timeout lockWait (readMVar done)  case outcome of    Nothing -> expectationFailure "the session did not finish in time"    Just finished -> traverse_ expectationFailure (sessionFailure finished)-- | Describes a session of the lock test that threw, or whose run lock-- returned the adapter's error. Returns 'Nothing' for a session that took-- and released the lock.sessionFailure :: (Show ae) => Either SomeException (Either ae ()) -> Maybe StringsessionFailure (Left err) = Just ("the session threw " <> show err)sessionFailure (Right (Left err)) = Just ("the run lock failed with " <> show err)sessionFailure (Right (Right ())) = Nothing-- | Describes a session whose wait for the lock should have been-- interrupted. Returns 'Nothing' when the wait was interrupted, and the-- session closed, in time.interruptionFailure :: (Show ae) => Maybe (Either SomeException (Maybe (Either ae ()))) -> Maybe StringinterruptionFailure Nothing = Just "the interrupted session did not finish in time"interruptionFailure (Just (Left err)) = Just ("the interrupted session threw " <> show err)interruptionFailure (Just (Right (Just taken))) =  Just ("the wait for the lock returned " <> show taken <> " while another session held it")interruptionFailure (Just (Right Nothing)) = Nothing-- | Describes a second session that finished while the first session held-- the lock.contentionFailure :: (Show ae) => Either SomeException (Either ae ()) -> StringcontentionFailure finished =  fromMaybe "the second session took the lock while the first held it" (sessionFailure finished)-- | Migrations @a@, @b@ and @c@, where @b@ and @c@ depend on @a@.abc :: Fixture db tx ae -> [Migration Text (ConformanceM tx)]abc fixture =  [markerMigration fixture "a" [], markerMigration fixture "b" ["a"], markerMigration fixture "c" ["a"]]-- | A migration that creates the marker with its own name, and drops it-- when reverted.markerMigration :: Fixture db tx ae -> Text -> [Text] -> Migration Text (ConformanceM tx)markerMigration fixture name dependencies =  Migration    { migrationId = name,      migrationDependencies = Set.fromList dependencies,      migrationDescription = "marker " <> name,      migrationFingerprint = Nothing,      migrationUp = mark fixture name,      migrationDown = Just (ask >>= \tx -> liftIO (dropMarker fixture tx name))    }-- | Creates the marker with this name in the migration's transaction.mark :: Fixture db tx ae -> Text -> ConformanceM tx ()mark fixture name = ask >>= \tx -> liftIO (createMarker fixture tx name)-- | Returns whether 'bootstrap' created the tracking table.isCreated :: Either ae BootstrapOutcome -> BoolisCreated (Right (Created _)) = TrueisCreated _ = False-- | Returns whether the event reports an upgrade of a version 0 table.isUpgradeFromVersion0 :: ProgressEvent Text -> BoolisUpgradeFromVersion0 (TrackingTableUpgraded (TrackingVersion 0) _) = TrueisUpgradeFromVersion0 _ = False-- | Returns whether the run failed in the given migration's @Up@ step with-- the adapter's error.isAdapterFailureOf :: Text -> Either (RunError Text Text ae) () -> BoolisAdapterFailureOf identifier (Left (MigrationFailed failed Up (Left _))) = failed == identifierisAdapterFailureOf _ _ = False-- | How long the lock tests wait for a thread, in microseconds.lockWait :: IntlockWait = 5000000-- | How long the lock test lets the second session wait, in microseconds.contentionDelay :: IntcontentionDelay = 200000