1 {-# LANGUAGE DeriveGeneric #-}
2 {-# LANGUAGE ScopedTypeVariables #-}
3 {-# LANGUAGE TypeApplications #-}
4 {-# LANGUAGE TypeFamilies #-}
5 {-# LANGUAGE NumericUnderscores #-}
6 module Utils.Jobs (test) where
8 import Control.Concurrent
9 import qualified Control.Concurrent.Async as Async
10 import Control.Concurrent.STM
11 import Control.Exception
13 import Control.Monad.Reader
14 import Control.Monad.Except
18 import Data.Sequence (Seq, (|>), fromList)
21 import System.IO.Unsafe
22 import Network.HTTP.Client.TLS (newTlsManager)
23 import Network.HTTP.Client (Manager)
25 import qualified Servant.Job.Types as SJ
26 import qualified Servant.Job.Core as SJ
28 import Gargantext.Utils.Jobs.Internal (newJob)
29 import Gargantext.Utils.Jobs.Map
30 import Gargantext.Utils.Jobs.Monad hiding (withJob)
31 import Gargantext.Utils.Jobs.Queue (applyPrios, defaultPrios)
32 import Gargantext.Utils.Jobs.State
33 import Gargantext.API.Prelude
34 import Gargantext.API.Admin.EnvTypes as EnvTypes
35 import Gargantext.API.Admin.Orchestrator.Types
42 deriving (Eq, Ord, Show, Enum, Bounded)
44 -- | This type models the schedule picked up by the orchestrator.
45 newtype JobSchedule = JobSchedule { _JobSchedule :: Seq JobT } deriving (Eq, Show)
47 addJobToSchedule :: JobT -> MVar JobSchedule -> IO ()
48 addJobToSchedule jobt mvar = do
49 modifyMVar_ mvar $ \js -> do
50 let js' = js { _JobSchedule = _JobSchedule js |> jobt }
53 data Counts = Counts { countAs :: Int, countBs :: Int }
56 jobDuration, initialDelay :: Int
60 testMaxRunners :: IO ()
62 -- max runners = 2 with default settings
64 let settings = defaultJobSettings 2 k
65 st :: JobsState JobT [String] () <- newJobsState settings defaultPrios
66 runningJs <- newTVarIO []
67 let j num _jHandle _inp _l = do
68 atomically $ modifyTVar runningJs (\xs -> ("Job #" ++ show num) : xs)
69 threadDelay jobDuration
70 atomically $ modifyTVar runningJs (\xs -> filter (/=("Job #" ++ show num)) xs)
71 jobs = [ j n | n <- [1..4::Int] ]
72 _jids <- forM jobs $ \f -> pushJob A () f settings st
73 threadDelay initialDelay
74 r1 <- readTVarIO runningJs
75 sort r1 `shouldBe` ["Job #1", "Job #2"]
76 threadDelay jobDuration
77 r2 <- readTVarIO runningJs
78 sort r2 `shouldBe` ["Job #3", "Job #4"]
79 threadDelay jobDuration
80 r3 <- readTVarIO runningJs
86 -- Use a single runner, so that we can check the order of execution
87 -- without worrying about the runners competing with each other.
88 let settings = defaultJobSettings 1 k
89 prios = [(B, 10), (C, 1), (D, 5)]
90 st :: JobsState JobT [String] () <- newJobsState settings $
91 applyPrios prios defaultPrios -- B has the highest priority
92 pickedSchedule <- newMVar (JobSchedule mempty)
93 let j jobt _jHandle _inp _l = addJobToSchedule jobt pickedSchedule
100 -- Push all the jobs in the same STM transaction, so that they are all stored in the queue by
101 -- the time 'popQueue' gets called.
102 now <- getCurrentTime
103 atomically $ forM_ jobs $ \(t, f) -> void $ pushJobWithTime now t () f settings st
105 -- wait for the jobs to finish, waiting for more than the total duration,
106 -- so that we are sure that all jobs have finished, then check the schedule.
107 threadDelay jobDuration
108 finalSchedule <- readMVar pickedSchedule
109 finalSchedule `shouldBe` JobSchedule (fromList [B, D, C, A])
111 testExceptions :: IO ()
114 let settings = defaultJobSettings 2 k
115 st :: JobsState JobT [String] () <- newJobsState settings defaultPrios
117 (\_jHandle _inp _log -> readFile "/doesntexist.txt" >>= putStrLn)
119 threadDelay initialDelay
120 mjob <- lookupJob jid (jobsData st)
122 Nothing -> error "boo"
123 Just je -> case jTask je of
124 DoneJ _ r -> isLeft r `shouldBe` True
128 testFairness :: IO ()
131 let settings = defaultJobSettings 1 k
132 st :: JobsState JobT [String] () <- newJobsState settings defaultPrios
133 pickedSchedule <- newMVar (JobSchedule mempty)
134 let j jobt _jHandle _inp _l = addJobToSchedule jobt pickedSchedule
141 time <- getCurrentTime
142 -- in this scenario we simulate two types of jobs all with
143 -- all the same level of priority: our queue implementation
144 -- will behave as a classic FIFO, keeping into account the
146 atomically $ forM_ (zip [0,2 ..] jobs) $ \(timeDelta, (t, f)) -> void $
147 pushJobWithTime (addUTCTime (fromInteger timeDelta) time) t () f settings st
149 threadDelay jobDuration
150 finalSchedule <- readMVar pickedSchedule
151 finalSchedule `shouldBe` JobSchedule (fromList [A, A, B, A, A])
154 newtype MyDummyMonad a =
155 MyDummyMonad { _MyDummyMonad :: GargM Env GargError a }
156 deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env)
158 instance MonadJob MyDummyMonad GargJob (Seq JobLog) JobLog where
159 getJobEnv = MyDummyMonad getJobEnv
161 instance MonadJobStatus MyDummyMonad where
162 type JobHandle MyDummyMonad = EnvTypes.ConcreteJobHandle GargError
163 type JobType MyDummyMonad = GargJob
164 type JobOutputType MyDummyMonad = JobLog
165 type JobEventType MyDummyMonad = JobLog
167 getLatestJobStatus jId = MyDummyMonad (getLatestJobStatus jId)
168 withTracer _ jh n = n jh
169 markStarted n jh = MyDummyMonad (markStarted n jh)
170 markProgress steps jh = MyDummyMonad (markProgress steps jh)
171 markFailure steps mb_msg jh = MyDummyMonad (markFailure steps mb_msg jh)
172 markComplete jh = MyDummyMonad (markComplete jh)
173 markFailed mb_msg jh = MyDummyMonad (markFailed mb_msg jh)
175 runMyDummyMonad :: Env -> MyDummyMonad a -> IO a
176 runMyDummyMonad env m = do
177 res <- runExceptT . flip runReaderT env $ _MyDummyMonad m
182 testTlsManager :: Manager
183 testTlsManager = unsafePerformIO newTlsManager
184 {-# NOINLINE testTlsManager #-}
187 -> (JobHandle MyDummyMonad -> () -> MyDummyMonad ())
188 -> IO (SJ.JobStatus 'SJ.Safe JobLog)
189 withJob env f = runMyDummyMonad env $ MyDummyMonad $
190 -- the job type doesn't matter in our tests, we use a random one, as long as it's of type 'GargJob'.
191 newJob @_ @GargError mkJobHandle (pure env) RecomputeGraphJob (\_ hdl input ->
192 runMyDummyMonad env $ (Right <$> (f hdl input >> getLatestJobStatus hdl))) (SJ.JobInput () Nothing)
195 -> (JobHandle MyDummyMonad -> () -> MyDummyMonad ())
197 withJob_ env f = void (withJob env f)
202 let settings = defaultJobSettings 1 k
203 myEnv <- newJobEnv settings defaultPrios testTlsManager
205 { _env_settings = error "env_settings not needed, but forced somewhere (check StrictData)"
206 , _env_logger = error "env_logger not needed, but forced somewhere (check StrictData)"
207 , _env_pool = error "env_pool not needed, but forced somewhere (check StrictData)"
208 , _env_nodeStory = error "env_nodeStory not needed, but forced somewhere (check StrictData)"
209 , _env_manager = testTlsManager
210 , _env_self_url = error "self_url not needed, but forced somewhere (check StrictData)"
211 , _env_scrapers = error "scrapers not needed, but forced somewhere (check StrictData)"
213 , _env_config = error "config not needed, but forced somewhere (check StrictData)"
214 , _env_mail = error "mail not needed, but forced somewhere (check StrictData)"
215 , _env_nlp = error "nlp not needed, but forced somewhere (check StrictData)"
218 testFetchJobStatus :: IO ()
219 testFetchJobStatus = do
223 withJob_ myEnv $ \hdl _input -> do
224 mb_status <- getLatestJobStatus hdl
226 -- now let's log something
228 mb_status' <- getLatestJobStatus hdl
230 mb_status'' <- getLatestJobStatus hdl
232 liftIO $ modifyMVar_ evts (\xs -> pure $ mb_status : mb_status' : mb_status'' : xs)
237 readMVar evts >>= \expected -> map _scst_remaining expected `shouldBe` [Nothing, Just 10, Just 5]
239 testFetchJobStatusNoContention :: IO ()
240 testFetchJobStatusNoContention = do
246 let job1 = \() -> withJob_ myEnv $ \hdl _input -> do
248 mb_status <- getLatestJobStatus hdl
249 liftIO $ modifyMVar_ evts1 (\xs -> pure $ mb_status : xs)
252 let job2 = \() -> withJob_ myEnv $ \hdl _input -> do
254 mb_status <- getLatestJobStatus hdl
255 liftIO $ modifyMVar_ evts2 (\xs -> pure $ mb_status : xs)
258 Async.forConcurrently_ [job1, job2] ($ ())
261 readMVar evts1 >>= \expected -> map _scst_remaining expected `shouldBe` [Just 100]
262 readMVar evts2 >>= \expected -> map _scst_remaining expected `shouldBe` [Just 50]
264 testMarkProgress :: IO ()
265 testMarkProgress = do
267 evts <- newTBQueueIO 7
268 let getStatus hdl = do
269 liftIO $ threadDelay 100_000
270 st <- getLatestJobStatus hdl
271 liftIO $ atomically $ writeTBQueue evts st
273 allEventsArrived <- isFullTBQueue evts
274 if allEventsArrived then flushTBQueue evts else retry
276 withJob_ myEnv $ \hdl _input -> do
283 markFailure 1 Nothing hdl
286 markFailure 1 (Just "boom") hdl
296 markFailed (Just "kaboom") hdl
300 [jl0, jl1, jl2, jl3, jl4, jl5, jl6] <- atomically readAllEvents
302 -- Check the events are what we expect
303 jl0 `shouldBe` JobLog { _scst_succeeded = Just 0
304 , _scst_failed = Just 0
305 , _scst_remaining = Just 10
306 , _scst_events = Just []
308 jl1 `shouldBe` JobLog { _scst_succeeded = Just 1
309 , _scst_failed = Just 0
310 , _scst_remaining = Just 9
311 , _scst_events = Just []
313 jl2 `shouldBe` JobLog { _scst_succeeded = Just 1
314 , _scst_failed = Just 1
315 , _scst_remaining = Just 8
316 , _scst_events = Just []
318 jl3 `shouldBe` JobLog { _scst_succeeded = Just 1
319 , _scst_failed = Just 2
320 , _scst_remaining = Just 7
321 , _scst_events = Just [
322 ScraperEvent { _scev_message = Just "boom"
323 , _scev_level = Just "ERROR"
324 , _scev_date = Nothing }
327 jl4 `shouldBe` JobLog { _scst_succeeded = Just 8
328 , _scst_failed = Just 2
329 , _scst_remaining = Just 0
330 , _scst_events = Just [
331 ScraperEvent { _scev_message = Just "boom"
332 , _scev_level = Just "ERROR"
333 , _scev_date = Nothing }
336 jl5 `shouldBe` JobLog { _scst_succeeded = Just 1
337 , _scst_failed = Just 0
338 , _scst_remaining = Just 4
339 , _scst_events = Just []
341 jl6 `shouldBe` JobLog { _scst_succeeded = Just 1
342 , _scst_failed = Just 4
343 , _scst_remaining = Just 0
344 , _scst_events = Just [
345 ScraperEvent { _scev_message = Just "kaboom"
346 , _scev_level = Just "ERROR"
347 , _scev_date = Nothing }
353 describe "job queue" $ do
354 it "respects max runners limit" $
356 it "respects priorities" $
358 it "can handle exceptions" $
360 it "fairly picks equal-priority-but-different-kind jobs" $
362 describe "job status update and tracking" $ do
363 it "can fetch the latest job status" $
365 it "can spin two separate jobs and track their status separately" $
366 testFetchJobStatusNoContention
367 it "marking stuff behaves as expected" $