on ffe9aed help sign in
16 files changed+98−350
since splitsnapshots
unifiedsplit
README.md−64 app/Main.hs+6−23 package.yaml−4 src/Control/HasGithubStatus.hs−14 src/Control/Task/Scheduler.hs+4−5 src/Control/Task/Scheduler/Query.hs+1−21 src/Data/Submission.hs−1 src/Data/Tasks/Build.hs+40−33 src/Data/Tasks/StatusUpdate.hs+1 src/Server.hs+31−116 src/Server/Config.hs+7−7 src/Server/Html.hs+6−10 src/Server/Schema.hs+1−3 src/Server/Schema/V2.hs−46 stack.yaml+1−2 tasks.yaml−1
README.mddeleted−64
@@ -1,64 +0,0 @@
1−# sc-build
2−
3−Need both manual weebohook and app.
4−
5−Installation id needs to be configured manually.
6−
7−## Usage
8−
9−You want to have some predefined docker container with maximum dependencies cached.
10−
11−
12−Exmaple:
13−
14−```dockerfile
15−FROM fpco/stack-build:lts-14.27
16−
17−RUN stack update
18−RUN stack build tasty tasty-hspec aeson containers bytestring
19−
20−WORKDIR /
21−```
22−
23−You need to build that container and git it a name:
24−
25−```bash
26−docker build -t fast-lts-14.27 - < FastDockerFile
27−```
28−
29−After that you can use it in your `tasks.yaml`:
30−
31−```yaml
32−test-task:
33− prebuild: |
34− cp -f ../../test-task/package.yaml .
35− cp -f ../../test-task/stack.yaml .
36− cp -f -R ../../test-task/test .
37− dockerfile: |
38− FROM fast-lts-14.27
39− COPY . src
40− WORKDIR /src
41− ENTRYPOINT stack test --fast
42− timeoutMinutes: 10
43−```
44−
45−The docker container is expected to write json to stdout, conating test results:
46−
47−```json
48−{
49− "test1": true,
50− "test2": false
51−}
52−```
53−
54−For macos docker API:
55−
56−```bash
57−socat TCP-LISTEN:1234,range=127.0.0.1/32,reuseaddr,fork UNIX-CLIENT:/var/run/docker.sock
58−```
59−
60−or this (didn't work for me):
61−
62−```bash
63−docker run -d -v /var/run/docker.sock:/var/run/docker.sock -p 127.0.0.1:2357:1234 bobrik/socat TCP-LISTEN:1234,fork UNIX-CONNECT:/var/run/docker.sock
64−```
app/Main.hs+6−23
@@ -1,30 +1,13 @@
11module Main (main) where
22
33import qualified Data.ByteString.Char8 as BS
4−import Data.Yaml (encode)
5−import Options.Applicative
4+import Data.Yaml
65import Server
76import Server.Config
7+import System.Environment
88
99main :: IO ()
10−main =
11− execParser (info (getOptions <**> helper) fullDesc) >>= \case
12− PrintDefaultConfig -> putStrLn . BS.unpack . encode $ defaultConfig
13− RunServer config -> runServer config
14−
15−data Run
16− = PrintDefaultConfig
17− | RunServer FilePath
18−
19−getOptions :: Parser Run
20−getOptions =
21− subparser
22− ( command "default" (info (pure PrintDefaultConfig <**> helper) fullDesc)
23− )
24− <|> ( RunServer
25− <$> strOption
26− ( long "config"
27− <> help "Path to yaml config file."
28− <> value "config.yaml"
29− )
30− )
10+main = getArgs >>= \case
11+ [] -> runServer
12+ ["default"] -> putStrLn . BS.unpack . encode $ defaultConfig
13+ xs -> error . show $ xs
package.yaml−4
@@ -52,7 +52,6 @@ library:
5252 - transformers
5353 - cassava
5454 - http-media
55− - utf8-string
5655
5756executables:
5857 sc-build-exe:
@@ -64,9 +63,6 @@ executables:
6463 - -with-rtsopts=-N
6564 dependencies:
6665 - sc-build
67− - bytestring
68− - yaml
69− - optparse-applicative
7066 sc-build-migrations:
7167 main: Main.hs
7268 source-dirs: migrations
src/Control/HasGithubStatus.hsdeleted−14
@@ -1,14 +0,0 @@
1−module Control.HasGithubStatus
2− ( HasGithubStatus (..),
3− )
4−where
5−
6−import Colog
7−import Data.Submission
8−import GitHub.Data
9−
10−class HasGithubStatus m where
11− schedulePendingStatus :: WithLog env Message m => Name Owner -> Name Repo -> Name Commit -> m ()
12− scheduleTestedStatus :: WithLog env Message m => TestResult -> Name Owner -> Name Repo -> Name Commit -> m ()
13− scheduleFailedStatus :: WithLog env Message m => String -> Name Owner -> Name Repo -> Name Commit -> m ()
14− deadlineHasPassedStatus :: WithLog env Message m => Name Owner -> Name Repo -> Name Commit -> m ()
src/Control/Task/Scheduler.hs+4−5
@@ -3,7 +3,6 @@
33module Control.Task.Scheduler
44 ( scheduleTask,
55 runTasks,
6− makeAllRunnable,
76 )
87where
98
@@ -21,7 +20,6 @@ import Data.Word
2120import GHC.TypeLits
2221import Server.Schema
2322import Squeal.PostgreSQL
24−import UnliftIO.Exception
2523
2624scheduleTask ::
2725 (StaticPQ m, WithLog env Message m, Task t s, MonadUnliftIO m) =>
@@ -47,6 +45,7 @@ rescheduleTaskTime ::
4745rescheduleTaskTime = rescheduleTaskQuery
4846
4947class RunTasks (ts :: [*]) m where
48+
5049 runTask :: WithLog env Message m => PickedTask -> m ()
5150
5251 taskNames :: [String]
@@ -56,6 +55,7 @@ instance
5655 (Task t ts, TaskMonad t m, StaticPQ m, RunTasks tt m, MonadUnliftIO m) =>
5756 RunTasks (t ': tt) m
5857 where
58+
5959 runTask (PickedTask s (Jsonb v) initialStartTime) | symbolVal @ts Proxy == s =
6060 case fromJSON @t v of
6161 A.Error e ->
@@ -67,9 +67,7 @@ instance
6767 <> e
6868 A.Success t -> do
6969 logInfo . T.pack $ "running task " <> task <> " with " <> show t <> " created at " <> show initialStartTime
70− r <- performTask @t @ts @m t `catchAny` \e -> do
71− logError . T.pack . displayException $ e
72− return Failure
70+ r <- performTask @t @ts @m t
7371 when (r == Failure) $ logWarning . T.pack $ "Task " <> task <> " failed"
7472 case r of
7573 Success -> completeTaskQuery t
@@ -81,6 +79,7 @@ instance
8179 taskNames = symbolVal @ts Proxy : taskNames @tt @m
8280
8381instance RunTasks '[] m where
82+
8483 runTask (PickedTask s (Jsonb v) _) =
8584 logError . T.pack $ "Unknown task " <> s <> " with payload " <> show v
8685
src/Control/Task/Scheduler/Query.hs+1−21
@@ -5,7 +5,6 @@ module Control.Task.Scheduler.Query
55 completeTaskQuery,
66 rescheduleTaskQuery,
77 pickTasksQuery,
8− makeAllRunnable,
98 PickedTask (..),
109 )
1110where
@@ -41,7 +40,6 @@ scheduleTaskQuery task = do
4140 :* Set (param @2) `as` #payload
4241 :* Default `as` #creation_time
4342 :* Default `as` #started
44− :* Default `as` #failures
4543 )
4644 ( OnConflict
4745 (OnConstraint #pk_task_payload)
@@ -88,7 +86,6 @@ rescheduleTaskQuery payload = do
8886 #tasks
8987 ( Default `as` #creation_time
9088 :* Default `as` #started
91− :* Set (#failures + 1) `as` #failures
9289 )
9390 (param @1 .== #task .&& param @2 .== #payload)
9491 dbWrite (const $ return ()) $
@@ -103,7 +100,7 @@ pickTasksQuery ::
103100 Word64 ->
104101 m [PickedTask]
105102pickTasksQuery tasks limitCount = do
106− logDebug $ "reading tasks " <> T.unwords (T.pack <$> tasks)
103+ logDebug "reading tasks"
107104 let query :: Query_ Schema () PickedTask
108105 query =
109106 select_
@@ -114,10 +111,7 @@ pickTasksQuery tasks limitCount = do
114111 ( from (table #tasks)
115112 & where_ (#task `in_` (literal <$> tasks))
116113 & where_ (not_ . notNull $ #started)
117− & where_ (#failures .< 20)
118− & orderBy [#creation_time & Asc]
119114 & limit limitCount
120− & orderBy [#creation_time & Desc]
121115 )
122116 startedMan :: Manipulation_ Schema (String, Jsonb Value) ()
123117 startedMan =
@@ -138,17 +132,3 @@ data PickedTask
138132 creationTime :: UTCTime
139133 }
140134 deriving (Eq, Show, Generic, SOP.Generic, SOP.HasDatatypeInfo)
141−
142−makeAllRunnable ::
143− (StaticPQ m, WithLog env Message m, MonadUnliftIO m) =>
144− m ()
145−makeAllRunnable = do
146− let startAll :: Manipulation_ Schema () ()
147− startAll =
148− update_
149− #tasks
150− ( Set false `as` #started
151− )
152− (notNull #started)
153− dbWrite (const $ return ()) $
154− manipulate_ startAll
src/Data/Submission.hs−1
@@ -29,7 +29,6 @@ data SubmissionStatus
2929 = SubmissionRun TestResult
3030 | SubmissionFailed String
3131 | BuildScheduled
32− | PastDeadline
3332 deriving (Generic, FromJSON, ToJSON, Eq, Show)
3433
3534newtype TestResult
src/Data/Tasks/Build.hs+40−33
@@ -10,16 +10,17 @@ where
1010import Colog
1111import Control.Concurrent
1212import Control.GithubCloner
13−import Control.HasGithubStatus
1413import Control.Monad.Except
1514import Control.Monad.IO.Unlift
1615import Control.Task
16+import Control.Task.Scheduler
1717import Data.Aeson hiding (Success)
1818import qualified Data.ByteString.Lazy.Char8 as BS
19−import qualified Data.ByteString.Lazy.UTF8 as BS
19+import qualified Data.Map as M
2020import Data.String
2121import Data.Submission
2222import Data.Submission.Query
23+import Data.Tasks.StatusUpdate
2324import qualified Data.Text as T
2425import Data.Time.Clock.POSIX
2526import qualified Docker.Client as D
@@ -45,9 +46,7 @@ data Build
4546 deriving (Eq, Show, Generic, FromJSON, ToJSON)
4647
4748instance Task Build "build-repo" where
48− type
49− TaskMonad Build m =
50− (MonadUnliftIO m, StaticPQ m, HasDockerInfo m, GithubCloner m, HasGithubStatus m)
49+ type TaskMonad Build m = (MonadUnliftIO m, StaticPQ m, HasDockerInfo m, GithubCloner m)
5150
5251 performTask Build {..} =
5352 bracket createDir (liftIO . removePathForcibly) $ \dir -> flip catchAny (const $ return Failure) $ do
@@ -55,7 +54,7 @@ instance Task Build "build-repo" where
5554 (shellCode, _, shellErr) <- readProcess . setWorkingDir dir $ shell preProcessShell
5655 case shellCode of
5756 ExitFailure n -> do
58− let err = BS.toString shellErr
57+ let err = BS.unpack shellErr
5958 logError . T.pack $
6059 "preprocessing command for repo " <> show fullRepoName <> " at sha "
6160 <> show sha
@@ -63,7 +62,7 @@ instance Task Build "build-repo" where
6362 <> show n
6463 <> " and error "
6564 <> err
66− scheduleFailedStatus err owner repoName sha
65+ scheduleTask erroredTask
6766 updateSubmissionStatus fullRepoName sha' (SubmissionFailed err)
6867 ExitSuccess -> do
6968 h <- liftIO D.defaultHttpHandler
@@ -74,8 +73,7 @@ instance Task Build "build-repo" where
7473 Exception err,
7574 WithLog env Message m,
7675 StaticPQ m,
77− MonadUnliftIO m,
78− HasGithubStatus m
76+ MonadUnliftIO m
7977 ) =>
8078 D.DockerT IO (Either err a) ->
8179 m a
@@ -91,7 +89,7 @@ instance Task Build "build-repo" where
9189 ExceptT $ D.buildImageFromDockerfile (D.defaultBuildOpts imageName) absDir
9290 ExceptT $ D.createContainer opts Nothing
9391 dockerRes <- fmap (either id id)
94− . race (liftIO (threadDelay (timeoutMinutes * 60000000)) >> return (ExitFailure 1, "Time out", "Time out"))
92+ . race (liftIO (threadDelay (timeoutMinutes * 60000000)) >> return (ExitFailure 1, "Time out"))
9593 $ flip
9694 finally
9795 ( runDocker $
@@ -115,21 +113,10 @@ instance Task Build "build-repo" where
115113 tail = D.All
116114 }
117115 cid
118− buildErr <-
119− ExceptT $
120− D.getContainerLogs
121− D.LogOpts
122− { stdout = True,
123− stderr = True,
124− since = Nothing,
125− timestamps = False,
126− tail = D.All
127− }
128− cid
129− return (buildCode, buildOut, buildErr)
116+ return (buildCode, buildOut)
130117 case dockerRes of
131− (ExitFailure n, _, buildErr) -> do
132− let err = BS.toString buildErr
118+ (ExitFailure n, buildOut) -> do
119+ let err = BS.unpack buildOut
133120 logError . T.pack $
134121 "test command for repo " <> show fullRepoName <> " at sha "
135122 <> show sha
@@ -137,40 +124,60 @@ instance Task Build "build-repo" where
137124 <> show n
138125 <> " and error "
139126 <> err
140− scheduleFailedStatus err owner repoName sha
127+ scheduleTask erroredTask
141128 updateSubmissionStatus fullRepoName sha' (SubmissionFailed err)
142− (ExitSuccess, buildOut, _) ->
129+ (ExitSuccess, buildOut) ->
143130 case eitherDecode' (BS.dropWhile (/= '{') buildOut) of
144131 Left err' -> do
145− let err = err' <> " " <> BS.toString buildOut
132+ let err = err' <> " " <> BS.unpack buildOut
146133 logError . T.pack $
147134 "could not decode test result from repo " <> show fullRepoName
148135 <> " at sha "
149136 <> show sha
150137 <> ": "
151138 <> err
152− scheduleFailedStatus err owner repoName sha
153− updateSubmissionStatus fullRepoName sha' (SubmissionFailed (err <> BS.toString buildOut))
139+ scheduleTask erroredTask
140+ updateSubmissionStatus fullRepoName sha' (SubmissionFailed err)
154141 Right testResult@TestResult {..} -> do
155− scheduleTestedStatus testResult owner repoName sha
142+ let total = M.size tests
143+ passed = M.size . M.filter id $ tests
144+ description = T.pack $ show passed <> "/" <> show total
145+ status =
146+ statusTask
147+ NewStatus
148+ { newStatusState =
149+ if total == passed then StatusSuccess else StatusFailure,
150+ newStatusTargetUrl = Nothing,
151+ newStatusDescription = Just description,
152+ newStatusContext = Nothing
153+ }
154+ scheduleTask status
156155 updateSubmissionStatus fullRepoName sha' (SubmissionRun testResult)
157156 return Success
158157 where
158+ statusTask = StatusUpdate owner repoName sha
159+ erroredTask =
160+ statusTask $
161+ NewStatus
162+ { newStatusState = StatusError,
163+ newStatusTargetUrl = Nothing,
164+ newStatusDescription = Just "Build failed",
165+ newStatusContext = Nothing
166+ }
159167 fullRepoName = T.unpack $ untagName owner <> "/" <> untagName repoName
160168 sha' = T.unpack $ untagName sha
161169 runEither ::
162170 ( Exception err,
163171 WithLog env Message m,
164172 StaticPQ m,
165− MonadUnliftIO m,
166− HasGithubStatus m
173+ MonadUnliftIO m
167174 ) =>
168175 Either err b ->
169176 m b
170177 runEither (Left err) = do
171178 let err' = show err
172179 logError $ T.pack err'
173− scheduleFailedStatus err' owner repoName sha
180+ scheduleTask erroredTask
174181 updateSubmissionStatus fullRepoName sha' (SubmissionFailed err')
175182 throwIO err
176183 runEither (Right a) = return a
src/Data/Tasks/StatusUpdate.hs+1
@@ -31,6 +31,7 @@ instance FromJSON NewStatus where
3131 <*> v .:? "context"
3232
3333instance Task StatusUpdate "update-commit-ci-status" where
34+
3435 type TaskMonad StatusUpdate m = (AppRequestable m)
3536
3637 performTask StatusUpdate {..} = do
src/Server.hs+31−116
@@ -10,7 +10,6 @@ import Colog
1010import Control.AppRequestable
1111import Control.Concurrent
1212import Control.GithubCloner
13−import Control.HasGithubStatus
1413import Control.Monad.Except
1514import Control.Monad.IO.Unlift
1615import Control.Monad.Reader
@@ -30,7 +29,6 @@ import Data.Submission.Query
3029import Data.Tasks.Build
3130import Data.Tasks.StatusUpdate
3231import qualified Data.Text as T
33−import Data.Time.Clock
3432import Data.Yaml
3533import GHC.Generics
3634import GitHub hiding (Accept)
@@ -39,7 +37,7 @@ import GitHub.App.Request
3937import GitHub.Auth (Auth (OAuth))
4038import GitHub.Data.Name
4139import GitHub.Data.Webhooks.Events
42−import GitHub.Data.Webhooks.Payload hiding (URL (..))
40+import GitHub.Data.Webhooks.Payload
4341import Network.HTTP.Client.TLS (newTlsManager)
4442import Network.HTTP.Media.MediaType
4543import Network.Wai.Handler.Warp
@@ -50,6 +48,7 @@ import Server.Config
5048import Server.Html
5149import Server.Schema
5250import Squeal.PostgreSQL
51+import System.IO
5352import Text.Blaze.Html
5453import UnliftIO.Exception (catch, displayException, handleAny, throwIO, try)
5554
@@ -75,18 +74,17 @@ type API =
7574 :> Post '[HTML] Markup
7675 :<|> "results" :> Capture "task name" String :> Get '[CSV, HTML] [Score]
7776
78−webhookInstallation :: WithLog env Message m => RepoWebhookEvent -> ((), InstallationEvent) -> m ()
77+webhookInstallation :: MonadIO m => RepoWebhookEvent -> ((), InstallationEvent) -> m ()
7978webhookInstallation _ ((), ev) =
80− logInfo . T.pack . show $ ev
79+ liftIO $ do
80+ print ev
81+ hFlush stdout
82+
83+pendingStatus :: NewStatus
84+pendingStatus = NewStatus StatusPending Nothing Nothing Nothing
8185
8286webhookPushEvent ::
83− ( StaticPQ m,
84− MonadReader (ServerData m) m,
85− MonadUnliftIO m,
86− HasTasks m,
87− MonadError ServerError m,
88− WithLog env Message m
89− ) =>
87+ (StaticPQ m, WithLog env Message m, MonadUnliftIO m, HasTasks m, MonadError ServerError m) =>
9088 RepoWebhookEvent ->
9189 ((), PushEvent) ->
9290 m ()
@@ -104,32 +102,22 @@ webhookPushEvent _ ((), ev) = do
104102 M.takeWhileAntitone (repoName >) tasks
105103 case task of
106104 Just (name, TaskConfig {..}) | T.take (T.length name) repoName == name -> do
107− nowTime <- liftIO getCurrentTime
108− if nowTime > deadline
109− then do
110− deadlineHasPassedStatus (N owner) (N repoName) (N sha)
111− createSubmission $
112− Submission
113− user
114− (T.unpack fullRepoName)
115− (T.unpack name)
116− (T.unpack sha)
117− (Jsonb PastDeadline)
118− else do
119− schedulePendingStatus (N owner) (N repoName) (N sha)
120− createSubmission $
121− Submission
122− user
123− (T.unpack fullRepoName)
124− (T.unpack name)
125− (T.unpack sha)
126− (Jsonb BuildScheduled)
127− scheduleTask $ Build prebuild dockerfile (N owner) (N repoName) (N sha) timeoutMinutes
128− logInfo . T.pack . show $ ev
105+ scheduleTask $ StatusUpdate (N owner) (N repoName) (N sha) pendingStatus
106+ createSubmission $
107+ Submission
108+ user
109+ (T.unpack fullRepoName)
110+ (T.unpack name)
111+ (T.unpack sha)
112+ (Jsonb BuildScheduled)
113+ scheduleTask $ Build prebuild dockerfile (N owner) (N repoName) (N sha) timeoutMinutes
114+ liftIO $ do
115+ print ev
116+ hFlush stdout
129117 _ -> return ()
130118
131119retestSubmission ::
132− (StaticPQ m, MonadReader (ServerData m) m, MonadUnliftIO m, HasTasks m, MonadHasBaseUrl m) =>
120+ (StaticPQ m, WithLog env Message m, MonadUnliftIO m, HasTasks m, MonadHasBaseUrl m) =>
133121 String ->
134122 String ->
135123 String ->
@@ -148,7 +136,7 @@ retestSubmission owner repoName sha = do
148136 M.takeWhileAntitone (repoName' >) tasks
149137 case task of
150138 Just (name, TaskConfig {..}) | T.take (T.length name) repoName' == name -> do
151− schedulePendingStatus (N owner') (N repoName') (N sha')
139+ scheduleTask $ StatusUpdate (N owner') (N repoName') (N sha') pendingStatus
152140 updateSubmissionStatus fullRepoName sha BuildScheduled
153141 scheduleTask $ Build prebuild dockerfile (N owner') (N repoName') (N sha') timeoutMinutes
154142 _ -> return ()
@@ -175,9 +163,9 @@ instance MonadError ServerError (ServerM schema) where
175163server :: ServerT API (ServerM Schema)
176164server = (webhookInstallation :<|> webhookPushEvent) :<|> getSubmissionR :<|> retestSubmission :<|> getResults
177165
178−runServer :: FilePath -> IO ()
179−runServer config = do
180− c@Config {..} <- getConfig config
166+runServer :: IO ()
167+runServer = do
168+ c@Config {..} <- getConfig
181169 print c
182170 pem <- BS.readFile appPkPemPath
183171 appPkPem <- case readRsaPem pem of
@@ -198,19 +186,13 @@ runServer config = do
198186 tasks = ts,
199187 logger = cfilter ((logSeverity <=) . msgSeverity) richMessageAction,
200188 baseUrl = baseSiteUrl,
201− dockerUrl = T.pack cfgDockerUrl,
202− context = githubContext
189+ dockerUrl = T.pack cfgDockerUrl
203190 }
204191 repeatIfNotEmpty n f = f >>= \m -> do
205192 when (m == 0) $ liftIO $ threadDelay n
206193 repeatIfNotEmpty n f
207194 printingErrors =
208195 handleAny (logError . T.pack . displayException >=> const (return 0))
209− usingConnectionPool pool
210− . (`runReaderT` serverData)
211− . unApp
212− . handleAny (error . displayException)
213− $ makeAllRunnable
214196 replicateM_ builderCount
215197 $ forkIO . repeatIfNotEmpty (10 ^ (6 :: Int))
216198 . usingConnectionPool pool
@@ -243,9 +225,8 @@ data ServerData m
243225 { githubAppAuth :: !InstallationAuth,
244226 tasks :: IORef TasksConfig,
245227 logger :: LogAction m Message,
246− baseUrl :: T.Text,
247− dockerUrl :: T.Text,
248− context :: T.Text
228+ baseUrl :: String,
229+ dockerUrl :: T.Text
249230 }
250231
251232newtype PolyGitHubKey = PolyGitHubKey (forall result. GitHubKey result)
@@ -280,71 +261,6 @@ instance MonadReader (ServerData n) m => MonadHasBaseUrl m where
280261instance (MonadIO m, MonadReader (ServerData n) m) => HasTasks m where
281262 getTasks = asks tasks >>= liftIO . readIORef
282263
283−instance (MonadReader (ServerData m) m, StaticPQ m, MonadUnliftIO m) => HasGithubStatus m where
284− schedulePendingStatus nOwner@(N owner) nRepo@(N repo) nCommit@(N sha) = do
285− h <- asks baseUrl
286− c <- asks context
287− scheduleTask $
288− StatusUpdate
289− nOwner
290− nRepo
291− nCommit
292− ( NewStatus
293− StatusPending
294− (Just . URL $ h <> "/submission/" <> owner <> "/" <> repo <> "/" <> sha)
295− (Just "⌛")
296− (Just c)
297− )
298− scheduleTestedStatus TestResult {..} nOwner@(N owner) nRepo@(N repo) nCommit@(N sha) = do
299− h <- asks baseUrl
300− c <- asks context
301− let total = M.size tests
302− passed = M.size . M.filter id $ tests
303− description = T.pack $ show passed <> "/" <> show total <> if passed == total then " ✅" else " ❌"
304− status =
305− StatusUpdate
306− nOwner
307− nRepo
308− nCommit
309− NewStatus
310− { newStatusState =
311− if total == passed then StatusSuccess else StatusFailure,
312− newStatusTargetUrl = Just . URL $ h <> "/submission/" <> owner <> "/" <> repo <> "/" <> sha,
313− newStatusDescription = Just description,
314− newStatusContext = Just c
315− }
316− scheduleTask status
317− scheduleFailedStatus _ nOwner@(N owner) nRepo@(N repo) nCommit@(N sha) = do
318− h <- asks baseUrl
319− c <- asks context
320− let status =
321− StatusUpdate
322− nOwner
323− nRepo
324− nCommit
325− NewStatus
326− { newStatusState = StatusError,
327− newStatusTargetUrl = Just . URL $ h <> "/submission/" <> owner <> "/" <> repo <> "/" <> sha,
328− newStatusDescription = Just "Build failed ☠️",
329− newStatusContext = Just c
330− }
331− scheduleTask status
332− deadlineHasPassedStatus nOwner@(N owner) nRepo@(N repo) nCommit@(N sha) = do
333− h <- asks baseUrl
334− c <- asks context
335− let status =
336− StatusUpdate
337− nOwner
338− nRepo
339− nCommit
340− NewStatus
341− { newStatusState = StatusError,
342− newStatusTargetUrl = Just . URL $ h <> "/submission/" <> owner <> "/" <> repo <> "/" <> sha,
343− newStatusDescription = Just "The deadline has passed ⏰",
344− newStatusContext = Just c
345− }
346− scheduleTask status
347−
348264instance (MonadReader (ServerData n) m) => HasDockerInfo m where
349265 getDockerUrl = asks dockerUrl
350266
@@ -354,8 +270,7 @@ data TaskConfig
354270 = TaskConfig
355271 { prebuild :: String,
356272 dockerfile :: String,
357− timeoutMinutes :: Int,
358− deadline :: UTCTime
273+ timeoutMinutes :: Int
359274 }
360275 deriving stock (Show, Eq, Generic)
361276 deriving anyclass (FromJSON, ToJSON)
src/Server/Config.hs+7−7
@@ -28,11 +28,11 @@ data Config
2828 installationId :: !(Id Installation),
2929 tasksPath :: !FilePath,
3030 databseUrl :: !ByteString,
31− baseSiteUrl :: !Text,
31+ baseSiteUrl :: !String,
3232 cfgDockerUrl :: !String,
33+ cfgDockerFile :: !FilePath,
3334 logSeverity :: !Severity,
34− builderCount :: !Int,
35− githubContext :: !Text
35+ builderCount :: !Int
3636 }
3737 deriving (Show, Generic)
3838
@@ -66,13 +66,13 @@ defaultConfig =
6666 databseUrl = "host=localhost port=5432 dbname=sc-build connect_timeout=10",
6767 baseSiteUrl = "http://localhost:8080",
6868 cfgDockerUrl = "http://localhost:1234",
69+ cfgDockerFile = "TmpDockerfile",
6970 logSeverity = Info,
70− builderCount = 2,
71− githubContext = "MY CI NAME"
71+ builderCount = 2
7272 }
7373
74−getConfig :: FilePath -> IO Config
75−getConfig = decodeFileThrow
74+getConfig :: IO Config
75+getConfig = decodeThrow "config.yaml"
7676
7777-- getConfig :: IO Config
7878-- getConfig =
src/Server/Html.hs+6−10
@@ -16,7 +16,6 @@ import qualified Data.Map as M
1616import Data.String
1717import Data.Submission
1818import Data.Submission.Query
19−import qualified Data.Text as T
2019import Server.Schema
2120import Squeal.PostgreSQL (Jsonb (..))
2221import Text.Blaze
@@ -39,16 +38,15 @@ getSubmissionR user repo sha' = do
3938 Nothing ->
4039 return . ("Not found",) $
4140 H.h1 "404. not found. go away."
42− Just Submission {..} -> return . (problem,) $ do
41+ Just Submission {..} -> return . (repo,) $ do
4342 H.h1 $ toHtml problem
4443 H.h2 $ toHtml userName
45− H.h3 . H.code . toHtml . take 7 $ sha
4644 case status of
4745 Jsonb BuildScheduled -> do
48− H.h3 "Waiting to build ⌛"
46+ H.h3 "Waiting to build"
4947 restartBuild
5048 Jsonb (SubmissionFailed err) -> do
51− H.h3 "Failed to build ☠️"
49+ H.h3 "Failed to build"
5250 restartBuild
5351 H.code . H.pre $ toHtml err
5452 Jsonb (SubmissionRun (TestResult tests)) -> do
@@ -56,13 +54,11 @@ getSubmissionR user repo sha' = do
5654 passed = M.size . M.filter Prelude.id $ tests
5755 H.h3 . toHtml $
5856 "Tests have run: " <> show passed <> "/" <> show total
59− <> if passed == total then " 🎉" else " 🍌"
57+ <> if passed == total then " ✅" else ""
6058 restartBuild
6159 H.table $ flip M.foldMapWithKey tests $ \testName testPassed -> H.tr $ do
6260 (H.td H.! A.align "right") . H.p $ toHtml testName
6361 H.td $ if testPassed then "✅" else "❌"
64− Jsonb PastDeadline ->
65− H.h3 "This was submitted after the deadline ⏰"
6662 return . docTypeHtml $ do
6763 H.head $ do
6864 H.title $ toHtml titleText
@@ -95,12 +91,12 @@ getSubmissionR user repo sha' = do
9591 H.body inner
9692
9793class MonadHasBaseUrl m where
98− getBaseUrl :: m T.Text
94+ getBaseUrl :: m String
9995
10096getUrl :: (MonadHasBaseUrl m, Monad m) => String -> String -> m String
10197getUrl fullName sha = do
10298 siteBase <- getBaseUrl
103− return $ T.unpack siteBase <> "/submission/" <> fullName <> "/" <> sha
99+ return $ siteBase <> "/submission/" <> fullName <> "/" <> sha
104100
105101redirectToSubmission ::
106102 (MonadHasBaseUrl m, Monad m) =>
src/Server/Schema.hs+1−3
@@ -6,15 +6,13 @@ module Server.Schema
66where
77
88import Server.Schema.V1
9−import Server.Schema.V2
109import Squeal.PostgreSQL
1110
1211type StaticPQ m = MonadPQ Schema m
1312
14−type Schema = SchemaV2
13+type Schema = SchemaV1
1514
1615migration :: AlignedList (Migration (Terminally PQ IO)) (Public '[]) Schema
1716migration =
1817 pureMigration schemaMigrationV1
19− :>> pureMigration schemaMigrationV2
2018 :>> Done
src/Server/Schema/V2.hsdeleted−46
@@ -1,46 +0,0 @@
1−module Server.Schema.V2
2− ( SchemaV2,
3− schemaMigrationV2,
4− )
5−where
6−
7−import Data.Aeson
8−import Data.Int
9−import Data.Submission
10−import Data.Text (Text)
11−import Data.Time
12−import Server.Schema.V1
13−import Squeal.PostgreSQL
14−
15−type SchemaV2 =
16− Public
17− '[ "tasks"
18− ::: 'Table
19− ( '[ "pk_task_payload" :=> 'PrimaryKey '["task", "payload"]
20− ]
21− :=> '[ "task" ::: 'NoDef :=> 'NotNull (PG Text),
22− "payload" ::: 'NoDef :=> 'NotNull (PG (Jsonb Value)),
23− "creation_time" ::: 'Def :=> 'NotNull (PG UTCTime),
24− "started" ::: 'Def :=> 'NotNull (PG Bool),
25− "failures" ::: 'Def :=> 'NotNull (PG Int32)
26− ]
27− ),
28− "submissions"
29− ::: 'Table
30− ( '["pk_submission_repo_full_name_sha" :=> 'PrimaryKey '["repo_full_name", "sha"]]
31− :=> '[ "user_name" ::: 'NoDef :=> 'NotNull (PG String),
32− "repo_full_name" ::: 'NoDef :=> 'NotNull (PG String),
33− "problem" ::: 'NoDef :=> 'NotNull (PG String),
34− "sha" ::: 'NoDef :=> 'NotNull (PG String),
35− "status" ::: 'NoDef :=> 'NotNull (PG (Jsonb SubmissionStatus))
36− ]
37− )
38− ]
39−
40−schemaMigrationV2 :: Migration Definition SchemaV1 SchemaV2
41−schemaMigrationV2 =
42− Migration
43− { name = "v2",
44− up = alterTable #tasks (addColumn #failures (default_ 0 $ notNullable int)),
45− down = alterTable #tasks (dropColumn #failures)
46− }
stack.yaml+1−2
@@ -46,9 +46,8 @@ extra-deps:
4646- git: https://github.com/ilyakooo0/github-app
4747 commit: 0bede85ab53eb8f953cf6f4e58a756a205e88e0b
4848- servant-github-webhook-0.4.2.0
49+- docker-0.6.0.3
4950- http-client-0.5.14
50−- git: https://github.com/ilyakooo0/docker-hs
51− commit: 5cfdc4d7facd7043f530bce4ce0f0c57c923b029
5251
5352# Override default flag values for local packages and extra-deps
5453# flags: {}
tasks.yaml−1
@@ -8,4 +8,3 @@ test-task:
88 COPY . src
99 WORKDIR /src
1010 ENTRYPOINT stack test --fast
11− timeoutMinutes: 10