packages feed

dag-migrations-0.1.0.0 / src / Database / DagMigrations / Graph.hs

-- | Validation of a registry of migrations, and the dependency graph that-- it produces. A project imports "Database.DagMigrations", which re-exports-- t'MigrationGraph', 'validate', 'registeredIdentifiers', and 'linearOrder'-- from this module.module Database.DagMigrations.Graph  ( MigrationGraph,    validate,    registeredIdentifiers,    lookupMigration,    linearOrder,    inLinearOrder,    downSet,    upSet,  )whereimport Data.Graph (SCC (..), stronglyConnComp)import Data.Graph qualified as Graphimport Data.List qualified as Listimport Data.List.NonEmpty (NonEmpty (..))import Data.List.NonEmpty qualified as NonEmptyimport Data.Map.Strict (Map)import Data.Map.Strict qualified as Mapimport Data.Maybe (fromMaybe)import Data.Set (Set)import Data.Set qualified as Setimport Database.DagMigrations.Error (ValidationError (..))import Database.DagMigrations.Migration (Migration (..))-- | A registry of migrations that has passed validation: identifiers are-- unique, every dependency is registered, and the dependencies are-- acyclic. Only 'validate' builds one.data MigrationGraph i m = MigrationGraph  { graphMigrations :: Map i (Migration i m),    -- | The lexicographically least linear extension of the dependency    -- order, by @Ord i@.    graphOrder :: [i],    graphDependencies :: Graph.Graph,    graphVertexKey :: Graph.Vertex -> i,    graphKeyVertex :: i -> Maybe Graph.Vertex  }-- | Checks a registry, and returns either every problem that it finds, in-- ascending order, or the validated graph. It is pure.validate :: (Ord i) => [Migration i m] -> Either (NonEmpty (ValidationError i)) (MigrationGraph i m)validate migrations =  case NonEmpty.nonEmpty (Set.toAscList problems) of    Just errors -> Left errors    Nothing -> Right (buildGraph migrations knownDependencies order)  where    occurrences = Map.fromListWith (+) [(migrationId m, 1 :: Int) | m <- migrations]    isRegistered i = Map.member i occurrences    knownDependencies =      Map.fromListWith        Set.union        [(migrationId m, Set.filter isRegistered (migrationDependencies m)) | m <- migrations]    order = leastLinearExtension knownDependencies    unplaced = Map.keysSet knownDependencies `Set.difference` Set.fromList order    duplicates = [DuplicateIdentifier i | (i, n) <- Map.toList occurrences, n > 1]    unknowns =      [ UnknownDependency (migrationId m) d      | m <- migrations,        d <- Set.toList (migrationDependencies m),        not (isRegistered d)      ]    cycles =      [ cycleError knownDependencies component      | CyclicSCC members <- stronglyConnComp (unplacedEdges knownDependencies unplaced),        Just component <- [NonEmpty.nonEmpty members]      ]    problems = Set.fromList (duplicates <> unknowns <> cycles)-- | The edges among the nodes that Kahn's algorithm could not place, in the-- form that 'stronglyConnComp' takes.unplacedEdges :: (Ord i) => Map i (Set i) -> Set i -> [(i, i, [i])]unplacedEdges dependencies unplaced =  [ (n, n, Set.toList (Set.intersection unplaced ds))  | (n, ds) <- Map.toList (Map.restrictKeys dependencies unplaced)  ]-- | The error for one cyclic strongly connected component: a cycle through-- its least member. Every member of a cyclic component lies on a cycle, so-- the fallback to the whole component is unreachable.cycleError :: (Ord i) => Map i (Set i) -> NonEmpty i -> ValidationError icycleError dependencies component =  DependencyCycle (fromMaybe sorted (cycleThrough dependencies (Set.fromList (NonEmpty.toList component)) start))  where    sorted = NonEmpty.sort component    start = NonEmpty.head sorted-- | A shortest cycle through @start@ that stays inside @component@. Each-- element of the result depends on the next, and the last depends on-- @start@, which comes first. 'Nothing' when no such cycle exists.cycleThrough :: (Ord i) => Map i (Set i) -> Set i -> i -> Maybe (NonEmpty i)cycleThrough dependencies component start =  fmap (\closer -> start :| pathFrom closer) (List.find closesCycle finalFrontier)  where    successors x = Set.intersection component (Map.findWithDefault Set.empty x dependencies)    closesCycle x = Set.member start (successors x)    (finalFrontier, parents) = until finished expand ([start], Map.singleton start start)    finished (frontier, _) = null frontier || any closesCycle frontier    expand (frontier, visited) =      let fresh =            -- 'Map.fromListWith' passes the new value first; keep the old one,            -- the parent that the search reached first.            Map.fromListWith              (\_ first -> first)              [ (y, x)              | x <- frontier,                y <- Set.toAscList (successors x),                not (Map.member y visited)              ]       in (Map.keys fresh, Map.union visited fresh)    -- The nodes from the child of start down to the given node.    pathFrom closer =      reverse        ( List.unfoldr            (\y -> if y == start then Nothing else fmap (\p -> (y, p)) (Map.lookup y parents))            closer        )-- | Kahn's algorithm with a min-priority queue. Returns the-- lexicographically least linear extension of the order generated by the-- map's dependency relation, restricted to the nodes that it can place. A-- node on a cycle, or above one, is never placed. Every dependency must-- be a key of the map.leastLinearExtension :: (Ord i) => Map i (Set i) -> [i]leastLinearExtension dependencies = List.unfoldr step (initialReady, initialCounts)  where    dependents =      Map.fromListWith        Set.union        [(d, Set.singleton n) | (n, ds) <- Map.toList dependencies, d <- Set.toList ds]    initialCounts = Map.map Set.size dependencies    initialReady = Map.keysSet (Map.filter (== 0) initialCounts)    step (ready, counts) = do      (next, rest) <- Set.minView ready      let released = Map.findWithDefault Set.empty next dependents          counts' = foldr (Map.adjust (subtract 1)) counts (Set.toList released)          newlyReady = Set.filter (\d -> Map.lookup d counts' == Just 0) released      pure (next, (Set.union rest newlyReady, counts'))-- | Builds the validated graph. The dependencies must be acyclic, and every-- dependency must be a key of the map.buildGraph :: (Ord i) => [Migration i m] -> Map i (Set i) -> [i] -> MigrationGraph i mbuildGraph migrations dependencies order =  MigrationGraph    { graphMigrations = Map.fromList [(migrationId m, m) | m <- migrations],      graphOrder = order,      graphDependencies = graph,      -- 'nodeFromVertex' fails on a vertex outside the graph. The graph's      -- functions apply it only to vertices that 'Graph.reachable' returns      -- for the same graph.      graphVertexKey = \v -> let (_, key, _) = nodeFromVertex v in key,      graphKeyVertex = vertexFromKey    }  where    (graph, nodeFromVertex, vertexFromKey) =      Graph.graphFromEdges [((), n, Set.toList ds) | (n, ds) <- Map.toList dependencies]-- | The identifiers of every registered migration.registeredIdentifiers :: MigrationGraph i m -> Set iregisteredIdentifiers = Map.keysSet . graphMigrations-- | The registered migration with this identifier.lookupMigration :: (Ord i) => i -> MigrationGraph i m -> Maybe (Migration i m)lookupMigration i = Map.lookup i . graphMigrations-- | Every registered identifier, in the lexicographically least linear-- extension of the dependency order.linearOrder :: MigrationGraph i m -> [i]linearOrder = graphOrder-- | The given identifiers that are registered, in the order of-- 'linearOrder'.inLinearOrder :: (Ord i) => MigrationGraph i m -> Set i -> [i]inLinearOrder graph ids = filter (`Set.member` ids) (graphOrder graph)-- | The identifier and everything that it depends on, directly or-- indirectly. Empty when the identifier is not registered.downSet :: (Ord i) => MigrationGraph i m -> i -> Set idownSet graph = reachableFrom graph (graphDependencies graph)-- | The identifier and everything that depends on it, directly or-- indirectly. Empty when the identifier is not registered.upSet :: (Ord i) => MigrationGraph i m -> i -> Set iupSet graph = reachableFrom graph (Graph.transposeG (graphDependencies graph))-- | The identifiers reachable from this one along the given edges,-- including itself. Empty when the identifier is not registered.reachableFrom :: (Ord i) => MigrationGraph i m -> Graph.Graph -> i -> Set ireachableFrom graph edges i =  maybe    Set.empty    (Set.fromList . map (graphVertexKey graph) . Graph.reachable edges)    (graphKeyVertex graph i)