packages feed

minici-0.1.10: src/Command/Run.hs

module Command.Run (
    RunCommand,
) where

import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class

import Data.Char
import Data.Containers.ListUtils
import Data.Either
import Data.List
import Data.Maybe
import Data.Text (Text)
import Data.Text qualified as T

import System.Console.GetOpt
import System.FilePath.Glob

import Command
import Config
import Eval
import Job
import Job.Types
import Output
import Range
import Repo
import Terminal


data RunCommand = RunCommand RunOptions [ Text ]

data RunOptions = RunOptions
    { roRerun :: RerunOption
    , roRanges :: [ Text ]
    , roSinceUpstream :: [ Text ]
    , roNewCommitsOn :: [ Text ]
    , roNewTags :: [ Pattern ]
    }

data RerunOption
    = RerunExplicit
    | RerunFailed
    | RerunAll
    | RerunNone

instance Command RunCommand where
    commandName _ = "run"
    commandDescription _ = "Execude jobs per minici.yaml for given commits"

    type CommandArguments RunCommand = [ Text ]

    commandUsage _ = T.pack $ unlines $
        [ "Usage: minici run"
        , "         run jobs for commits on current branch not yet in upstream branch"
        , "   or: minici run <job>..."
        , "         run jobs specified on the command line"
        , "   or: minici run [--range=]<commit>..<commit>"
        , "         run jobs for commits in given range"
        , "   or: minici run <option>..."
        , "         run jobs based on given options (see below)"
        ]

    type CommandOptions RunCommand = RunOptions
    defaultCommandOptions _ = RunOptions
        { roRerun = RerunExplicit
        , roRanges = []
        , roSinceUpstream = []
        , roNewCommitsOn = []
        , roNewTags = []
        }

    commandOptions _ =
        [ Option [] [ "rerun-explicit" ]
            (NoArg (\opts -> opts { roRerun = RerunExplicit }))
            "rerun jobs given explicitly on command line and their failed dependencies (default)"
        , Option [] [ "rerun-failed" ]
            (NoArg (\opts -> opts { roRerun = RerunFailed }))
            "rerun failed jobs only"
        , Option [] [ "rerun-all" ]
            (NoArg (\opts -> opts { roRerun = RerunAll }))
            "rerun all jobs"
        , Option [] [ "rerun-none" ]
            (NoArg (\opts -> opts { roRerun = RerunNone }))
            "do not rerun any job"
        , Option [] [ "range" ]
            (ReqArg (\val opts -> opts { roRanges = T.pack val : roRanges opts }) "<range>")
            "run jobs for commits in given range"
        , Option [] [ "since-upstream" ]
            (ReqArg (\val opts -> opts { roSinceUpstream = T.pack val : roSinceUpstream opts }) "<ref>")
            "run jobs for commits on <ref> not yet in its upstream ref"
        , Option [] [ "new-commits-on" ]
            (ReqArg (\val opts -> opts { roNewCommitsOn = T.pack val : roNewCommitsOn opts }) "<branch>")
            "run jobs for new commits on given branch"
        , Option [] [ "new-tags" ]
            (ReqArg (\val opts -> opts { roNewTags = compile val : roNewTags opts }) "<pattern>")
            "run jobs for new annotated tags matching pattern"
        ]

    commandInit _ = RunCommand
    commandExec = cmdRun


data JobSource = JobSource (TMVar (Maybe ( [ JobSourceItem ], JobSource )))

data JobSourceItem = JobSourceItem
    { jsiJobSet :: JobSet
    , jsiCancelAction :: Maybe (MVar (IO ()))
    }

emptyJobSource :: MonadIO m => m JobSource
emptyJobSource = JobSource <$> liftIO (newTMVarIO Nothing)

oneshotJobSource :: MonadIO m => [ JobSet ] -> m JobSource
oneshotJobSource jobsets = do
    next <- emptyJobSource
    JobSource <$> liftIO (newTMVarIO (Just ( map (`JobSourceItem` Nothing) jobsets, next )))

takeJobSource :: JobSource -> STM (Maybe ( [ JobSourceItem ], JobSource ))
takeJobSource (JobSource tmvar) = takeTMVar tmvar

mergeSources :: [ JobSource ] -> IO JobSource
mergeSources sources = do
    let go tmvar [] = do
            atomically (putTMVar tmvar Nothing)
        go tmvar cur = do
            ( jobsets, next ) <- atomically (select cur)
            if null next
              then do
                go tmvar next
              else do
                nextvar <- newEmptyTMVarIO
                atomically $ putTMVar tmvar (Just ( jobsets, JobSource nextvar ))
                go nextvar next

    tmvar <- newEmptyTMVarIO
    void $ forkIO $ go tmvar sources
    return $ JobSource tmvar

  where
    select :: [ JobSource ] -> STM ( [ JobSourceItem ], [ JobSource ] )
    select [] = retry
    select (x@(JobSource tmvar) : xs) = do
        tryTakeTMVar tmvar >>= \case
            Nothing -> fmap (x :) <$> select xs
            Just Nothing -> return ( [], xs )
            Just (Just ( jobsets, x' )) -> return ( jobsets, x' : xs )


argumentJobSource :: [ JobName ] -> CommandExec JobSource
argumentJobSource [] = emptyJobSource
argumentJobSource names = do
    jobRoot <- getJobRoot
    ( config, jcommit ) <- case jobRoot of
        JobRootConfig config -> do
            commit <- sequence . fmap createWipCommit =<< tryGetDefaultRepo
            return ( config, commit )
        JobRootRepo repo -> do
            commit <- createWipCommit repo
            config <- either fail return =<< loadConfigForCommit =<< getCommitTree commit
            return ( config, Just commit )

    jobtree <- case jcommit of
        Just commit -> (: []) <$> getCommitTree commit
        Nothing -> return []
    let cidPart = case jobRoot of
            JobRootConfig {} -> []
            JobRootRepo {} -> map (JobIdRepo Nothing . JobIdTree "" . treeId) jobtree
    forM_ names $ \name ->
        case find ((name ==) . jobName) (configJobs config) of
            Just _  -> return ()
            Nothing -> tfail $ "job ‘" <> textJobName name <> "’ not found"

    jset <- cmdEvalWith (\ei -> ei { eiCurrentIdRev = cidPart ++ eiCurrentIdRev ei }) $ do
        evalJobSetSelected names (map (( Nothing , ) . RepoRefCommit) $ maybeToList jcommit) JobSet
            { jobsetId = ()
            , jobsetConfig = Just config
            , jobsetCommit = jcommit
            , jobsetExplicitlyRequested = names
            , jobsetJobsEither = Right (configJobs config)
            }
    oneshotJobSource [ jset ]

refJobSource :: [ JobRef ] -> CommandExec JobSource
refJobSource [] = emptyJobSource
refJobSource refs = do
    sets <- foldl' addJobToList [] <$> cmdEvalWith id (mapM evalJobReferenceToSet refs)
    oneshotJobSource sets
  where
    addJobToList :: [ JobSet ] -> JobSet -> [ JobSet ]
    addJobToList (cur : rest) jset
        | jobsetId cur == jobsetId jset = cur { jobsetJobsEither = fmap (nubOrdOn jobId) $ (++) <$> (jobsetJobsEither cur) <*> (jobsetJobsEither jset)
                                              , jobsetExplicitlyRequested = nubOrd $ jobsetExplicitlyRequested cur ++ jobsetExplicitlyRequested jset
                                              } : rest
        | otherwise                     = cur : addJobToList rest jset
    addJobToList [] jset                = [ jset ]

loadJobSetFromRoot :: (MonadIO m, MonadFail m) => JobRoot -> Commit -> m DeclaredJobSet
loadJobSetFromRoot root commit = case root of
    JobRootRepo _ -> loadJobSetForCommit commit
    JobRootConfig config -> return JobSet
        { jobsetId = ()
        , jobsetConfig = Just config
        , jobsetCommit = Just commit
        , jobsetExplicitlyRequested = []
        , jobsetJobsEither = Right $ configJobs config
        }


watchExpressionSource :: RangeExpression -> CommandExec JobSource
watchExpressionSource expr = do
    root <- getJobRoot
    repo <- getDefaultRepo
    einputBase <- getEvalInput
    let loop = isRangeExpressionDynamic expr
    let go running prev tmvar = do
            cur <- atomically $ do
                cur <- evaluateRange expr
                when (cur == prev) retry
                return cur

            commits <- getAddedRangeCommits repo prev cur
            jobsets <- forM commits $ \commit -> do
                tree <- getCommitTree commit
                let einput = einputBase
                        { eiCurrentIdRev = JobIdRepo Nothing (JobIdTree (treeSubdir tree) (treeId tree)) : eiCurrentIdRev einputBase
                        }
                dset <- loadJobSetFromRoot root commit
                let fset err = JobSet
                        { jobsetId = JobSetId $ reverse $
                            JobIdRepo Nothing (JobIdCommit (commitId commit)) : eiCurrentIdRev einputBase
                        , jobsetConfig = Nothing
                        , jobsetCommit = Just commit
                        , jobsetExplicitlyRequested = []
                        , jobsetJobsEither = Left $ T.unpack $ textEvalError err
                        }
                jsiJobSet <- fmap (either fset id) $ flip runEval einput $
                    evalJobSet [ ( Nothing, RepoRefCommit commit ) ] dset
                jsiCancelAction <- Just <$> newEmptyMVar
                return JobSourceItem {..}

            obsolete <- getAddedRangeCommits repo cur prev
            let ( cancel, keep ) = partition (maybe False (`elem` obsolete) . jobsetCommit . jsiJobSet) running
            mapM_ (mapM_ (join . readMVar) . jsiCancelAction) cancel

            nextvar <- newEmptyTMVarIO
            atomically $ putTMVar tmvar $ Just ( jobsets, JobSource nextvar )
            if loop
              then do
                go (reverse jobsets ++ keep) cur nextvar
              else do
                atomically $ putTMVar nextvar Nothing

    liftIO $ do
        tmvar <- newEmptyTMVarIO
        void $ forkIO $ go [] EmptyCommitRange tmvar
        return $ JobSource tmvar

watchBranchSource :: Text -> CommandExec JobSource
watchBranchSource branch = do
    repo <- getDefaultRepo
    expr <- evaluateDeclaredRange repo $ RangeExpression (WatchedRef (TextRef branch)) (StaticRef (TextRef branch))
    watchExpressionSource expr

watchTagSource :: Pattern -> CommandExec JobSource
watchTagSource pat = do
    repo <- getDefaultRepo
    expr <- evaluateDeclaredRange repo $ WatchedTagsExpression (TagPattern pat True)
    watchExpressionSource expr

cmdRun :: RunCommand -> CommandExec ()
cmdRun (RunCommand RunOptions {..} args) = do
    CommonOptions {..} <- getCommonOptions
    output <- getOutput
    storageDir <- getStorageDir

    rangeOptions <- concat <$> sequence
        [ forM roRanges $ \range -> case T.splitOn ".." range of
            [ base, tip ]
                | not (T.null base) && not (T.null tip)
                -> return ( Just base, tip )
            _ -> tfail $ "invalid range: " <> range
        , forM roSinceUpstream $ return . ( Nothing, )
        ]

    let ( nameOptions, jobOptions ) = partition (T.all $ \c -> isAlphaNum c || c == '_') args
        ( refOptions, exprOptions ) = partitionEithers $ map splitRefs jobOptions
        splitRefs t = case parseJobRef t of
            JobRef [ e ] -> Right e
            JobRef [ e, "" ] -> Right e
            ref -> Left ref

    argumentJobs <- argumentJobSource $ map JobName nameOptions
    refJobs <- refJobSource refOptions

    exprJobs <- forM exprOptions $ \trange ->
        case parseRangeExpression trange of
            Left err -> fail err
            Right expr -> do
                repo <- getDefaultRepo
                range <- evaluateDeclaredRange repo expr
                watchExpressionSource range

    defaultSource <- getJobRoot >>= \case
        _ | not (null rangeOptions && null roNewCommitsOn && null roNewTags && null args) -> do
            emptyJobSource

        JobRootRepo repo -> do
            watchExpressionSource =<< evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef "HEAD")) (StaticRef (UpstreamRef "HEAD")))

        JobRootConfig config -> do
            argumentJobSource (jobName <$> configJobs config)

    ranges <- forM rangeOptions $ \( mbBase, tip ) -> do
        repo <- getDefaultRepo
        range <- case mbBase of
            Just base ->
                evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef tip)) (StaticRef (TextRef base)))
            Nothing -> do
                evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef tip)) (StaticRef (UpstreamRef tip)))
        watchExpressionSource range

    branches <- mapM watchBranchSource roNewCommitsOn
    tags <- mapM watchTagSource roNewTags

    liftIO $ do
        mngr <- newJobManager storageDir optJobs

        source <- mergeSources $ concat [ [ defaultSource, argumentJobs, refJobs ], exprJobs, ranges, branches, tags ]
        mbHeaderLine <- mapM (flip newLine "") (outputTerminal output)

        threadCount <- newTVarIO (0 :: Int)
        let changeCount f = atomically $ do
                writeTVar threadCount . f =<< readTVar threadCount
        let waitForJobs = do
                atomically $ do
                    flip when retry . (0 <) =<< readTVar threadCount
                waitForRemainingTasks mngr

        let loop _ Nothing = return ()
            loop names (Just ( [], next )) = do
                loop names =<< atomically (takeJobSource next)

            loop pnames (Just ( JobSourceItem {..} : rest, next )) = do
                let names = nub $ (pnames ++) $ map jobName $ jobsetJobs jsiJobSet
                when (names /= pnames) $ do
                    forM_ mbHeaderLine $ \headerLine -> do
                        redrawLine headerLine $ T.concat $
                            T.replicate (8 + 50) " " :
                            map ((" " <>) . fitToLength 7 . textJobName) names

                let commit = jobsetCommit jsiJobSet
                    shortCid = T.pack $ take 7 $ maybe (repeat ' ') (showCommitId . commitId) commit
                shortDesc <- fitToLength 50 <$> maybe (return "") getCommitTitle commit

                case jobsetJobsEither jsiJobSet of
                    Right jobs -> do
                        tasks <- runJobs mngr output jobs $ case roRerun of
                            RerunExplicit -> \jid status -> jid `elem` jobsetExplicitlyRequested jsiJobSet || jobStatusFailed status
                            RerunFailed -> \_ status -> jobStatusFailed status
                            RerunAll -> \_ _ -> True
                            RerunNone -> \_ _ -> False
                        let findJob name = taskStatus <$> find ((name ==) . jobName . taskJob) tasks
                            statuses = map findJob names
                        forM_ (outputTerminal output) $ \tout -> do
                            line <- newLine tout ""
                            void $ forkIO $ do
                                displayStatusLine tout line shortCid (" " <> shortDesc) statuses
                        mask $ \restore -> do
                            changeCount (+ 1)
                            void $ forkIO $ do
                                void $ try @SomeException $ restore $ waitForJobStatuses statuses
                                changeCount (subtract 1)
                        case jsiCancelAction of
                            Just var -> putMVar var $ mapM_ cancelTask tasks
                            Nothing -> return ()
                    Left err -> do
                        case jsiCancelAction of
                            Just var -> putMVar var $ return ()
                            Nothing -> return ()
                        forM_ (outputTerminal output) $ flip newLine $
                            "\ESC[91m" <> shortCid <> "\ESC[0m" <> " " <> shortDesc <> " \ESC[91m" <> T.pack err <> "\ESC[0m"
                        outputEvent output $ TestMessage $ "jobset-fail " <> T.pack err
                        outputEvent output $ LogMessage $ "Jobset failed: " <> shortCid <> " " <> T.pack err
                loop names (Just ( rest, next ))

        handle @SomeException
            (\e -> do
                if | Just UserInterrupt <- fromException e
                   -> outputEvent output RunInterruptedByUser
                   | otherwise
                   -> outputMessage output $ "exception in run loop: " <> T.pack (show e)
                cancelAllJobs mngr
            ) $ do
            loop [] =<< atomically (takeJobSource source)
            waitForJobs
        waitForJobs
    outputEvent output $ TestMessage "run-finish"


fitToLength :: Int -> Text -> Text
fitToLength maxlen str | len <= maxlen = str <> T.replicate (maxlen - len) " "
                       | otherwise     = T.take (maxlen - 1) str <> "…"
    where len = T.length str

showStatus :: Int -> Bool -> AnnotatedStatus -> Text
showStatus width blink ( status, fnotes ) = case status of
    JobQueued       -> " \ESC[94m…\ESC[0m" <> showNotes (width - 2)
    JobWaiting uses -> "\ESC[94m~" <> fitToLength (width - 1) (T.intercalate "," (map textJobName uses) <> showNotes (width - 1)) <> "\ESC[0m"
    JobSkipped      ->  " \ESC[0m-\ESC[0m" <> showNotes (width - 2)
    JobRunning      -> " \ESC[96m" <> (if blink then "*" else "•") <> "\ESC[0m" <> showNotes 5
    JobError _      -> "\ESC[91m!!\ESC[0m" <> showNotes (width - 2)
    JobFailed       -> " \ESC[91m✗\ESC[0m" <> showNotes (width - 2)
    JobCancelled    ->  " \ESC[0mC\ESC[0m" <> showNotes (width - 2)
    JobDone _       -> " \ESC[92m✓\ESC[0m" <> showNotes (width - 2)

    JobDuplicate _ s -> case s of
        JobQueued    -> " \ESC[94m^\ESC[0m" <> showNotes (width - 2)
        JobWaiting _ -> " \ESC[94m^\ESC[0m" <> showNotes (width - 2)
        JobSkipped   ->  " \ESC[0m-\ESC[0m" <> showNotes (width - 2)
        JobRunning   -> " \ESC[96m" <> (if blink then "*" else "^") <> "\ESC[0m" <> showNotes (width - 2)
        _            -> showStatus width blink ( s, fnotes )

    JobPreviousStatus (JobDone _) -> "\ESC[90m«\ESC[32m✓\ESC[0m" <> showNotes (width - 2)
    JobPreviousStatus (JobFailed) -> "\ESC[90m«\ESC[31m✗\ESC[0m" <> showNotes (width - 2)
    JobPreviousStatus s           -> "\ESC[90m«\ESC[0m" <> showStatus (width - 1) blink ( s, fnotes )
  where
    showNotes w = fitToLength w $ T.concat $ " " : map showNote fnotes
    showNote fnote = "[" <> T.pack (maybe "?" (show . tfNumber) (footnoteTerminal fnote)) <> "]"

displayStatusLine :: TerminalOutput -> TerminalLine -> Text -> Text -> [ Maybe (STM AnnotatedStatus) ] -> IO ()
displayStatusLine tout line prefix1 prefix2 statuses = do
    go "\0"
  where
    go prev = do
        ( ss, cur ) <- atomically $ do
            sns <- mapM sequence statuses
            blink <- terminalBlinkStatus tout
            let cur = T.concat $ map (maybe "        " ((" " <>) . showStatus 7 blink)) sns
            when (cur == prev) retry
            return ( map (fmap fst) sns, cur )

        let prefix1' = if any (maybe False jobStatusFailed) ss
                         then "\ESC[91m" <> prefix1 <> "\ESC[0m"
                         else prefix1
        redrawLine line $ prefix1' <> prefix2 <> cur

        if all (maybe True jobStatusFinished) ss
           then return ()
           else go cur

waitForJobStatuses :: [ Maybe (STM AnnotatedStatus) ] -> IO ()
waitForJobStatuses mbstatuses = do
    let statuses = catMaybes mbstatuses
    atomically $ do
        ss <- sequence statuses
        when (any (not . jobStatusFinished . fst) ss) retry