packages feed

cicero-api (empty) → 0.1.1.3

raw patch · 14 files changed

+1057/−0 lines, 14 filesdep +aesondep +attoparsecdep +base

Dependencies added: aeson, attoparsec, base, binary, bytestring, cicero-api, containers, haskeline, http-client, http-client-tls, optparse-applicative, servant, servant-client, servant-client-core, text, time, unix, uuid

Files

+ LICENSE view
@@ -0,0 +1,53 @@+Apache License++Version 2.0, January 2004++http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.++"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:++You must give any other recipients of the Work or Derivative Works a copy of this License; and+You must cause any modified files to carry prominent notices stating that You changed the files; and+You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and+If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. ++You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS
+ NOTICE view
@@ -0,0 +1,14 @@+Copyright 2022 Input Output (Hong Kong) Ltd.++   Licensed under the Apache License, Version 2.0 (the "License");+   you may not use this file except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS,+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+   See the License for the specific language governing permissions and+   limitations under the License.+
+ cicero-api.cabal view
@@ -0,0 +1,63 @@+cabal-version: 3.0+name:          cicero-api+version:       0.1.1.3+license:       Apache-2.0+license-files:+  LICENSE+  NOTICE+maintainer:  shea.levy@iohk.io+author:      Shea Levy+homepage:    https://github.com/input-output-hk/cicero-api#readme+bug-reports: https://github.com/input-output-hk/cicero-api/issues+synopsis: API bindings to IOHK's Cicero job scheduler+description:+  API bindings to IOHK's Cicero job scheduler. Also includes a simple CLI client.++  See github.com/input-output-hk/cicero+build-type: Simple+category: API++source-repository head+    type: git+    location: https://github.com/input-output-hk/cicero-pipe++library+  exposed-modules:+    IOHK.Cicero.API+    IOHK.Cicero.API.Action+    IOHK.Cicero.API.Fact+    IOHK.Cicero.API.Invocation+    IOHK.Cicero.API.Run+  build-depends:+    base ^>= 4.16.0.0,+    bytestring ^>= 0.11.1.0,+    binary ^>= 0.8.9.0,+    text ^>= 1.2.5.0,+    aeson ^>= 2.0.3.0,+    containers ^>= 0.6.5.1,+    time ^>= 1.11.1.1,+    uuid ^>= 1.3.15,+    servant ^>=0.19+  hs-source-dirs:   src+  default-language: Haskell2010++executable cicero-cli+  main-is: Main.hs+  other-modules: Action, Fact, Invocation, Run+  hs-source-dirs: cli+  build-depends:+    base ^>= 4.16.0.0,+    bytestring ^>= 0.11.1.0,+    attoparsec ^>= 0.14.4,+    servant-client-core ^>= 0.19,+    servant-client ^>= 0.19,+    optparse-applicative ^>= 0.17.0.0,+    http-client-tls ^>= 0.3.6.1,+    aeson ^>= 2.0.3.0,+    http-client ^>= 0.7.11,+    uuid ^>= 1.3.15,+    haskeline ^>= 0.8.2,+    servant ^>=0.19,+    unix ^>= 2.7.2.2,+    cicero-api+  default-language: Haskell2010
+ cli/Action.hs view
@@ -0,0 +1,70 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedRecordDot #-}+module Action where++import IOHK.Cicero.API.Action+import Options.Applicative+import Servant.Client+import Data.Aeson+import System.IO (stdout)+import Data.ByteString.Lazy.Char8+import Control.Exception++namesParser :: Parser ActionNamesV1+namesParser+  =  Only <$> strOption+       ( long "name"+      <> metavar "NAME"+      <> help "the specific action to create from SOURCE (all if omitted)"+       )+ <|> pure AllNames++createActionParser :: Parser CreateActionV1+createActionParser = CreateAction+  <$> namesParser+  <*> argument str+        ( metavar "SOURCE"+       <> help "the action source as a go-getter URL"+        )++createActionInfo :: ParserInfo CreateActionV1+createActionInfo = info createActionParser+  ( fullDesc+ <> header "cicero-cli action create — Create a new action"+  )++getActionParser :: Parser ActionID+getActionParser = argument (maybeReader actionIdFromString)+  ( metavar "ACTION_ID"+ <> help "the ID of the action to get"+  )++getActionInfo :: ParserInfo ActionID+getActionInfo = info getActionParser+  ( fullDesc+ <> header "cicero-cli action get — Get information about an action"+  )++data ActionCommand+  = CmdCreateAction !CreateActionV1+  | CmdGetAction !ActionID++actionCommandParser :: Parser ActionCommand+actionCommandParser = hsubparser+  ( command "create" (CmdCreateAction <$> createActionInfo)+ <> command "get" (CmdGetAction <$> getActionInfo)+  )++actionCommandInfo :: ParserInfo ActionCommand+actionCommandInfo = info actionCommandParser+  ( fullDesc+ <> header "cicero-cli action — Manage Cicero actions"+  )++handler :: ActionCommand -> Client ClientM API -> ClientEnv -> IO ()+handler (CmdCreateAction ca) actionClient cEnv = runClientM (actionClient.create ca) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res+handler (CmdGetAction id) actionClient cEnv = runClientM (actionClient.get id) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res
+ cli/Fact.hs view
@@ -0,0 +1,145 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RecordWildCards #-}+module Fact where++import IOHK.Cicero.API.Fact+import IOHK.Cicero.API.Run hiding (API)+import Servant.Client+import Options.Applicative+import Control.Exception+import Data.Aeson+import Data.Aeson.Parser.Internal hiding (value)+import System.Posix.Types+import System.Posix.IO+import System.IO (stdout)+import Data.ByteString.Lazy as LBS+import Data.ByteString.Lazy.Char8+import Data.Attoparsec.ByteString (feed, eitherResult, parse, IResult(Partial))+import Data.UUID++data Readable+  = File !FilePath+  | Cap !Fd++consume :: Readable -> IO ByteString+consume (File f) = LBS.readFile f+consume (Cap fd) = fdToHandle fd >>= hGetContents++readableOption :: Mod OptionFields FilePath -> Mod OptionFields Fd -> Parser Readable+readableOption fileFields capFields+  =  File <$> strOption fileFields+ <|> Cap <$> option auto capFields++data FactSource+  = LiteralFact !Value+  | ReadableFact !Readable++data CreateFactArgs = CreateFactArgs+  { factSource :: !FactSource+  , artifactSource :: !(Maybe Readable)+  }++valueReader :: ReadM Value+valueReader = do+  bytes <- str+  case eitherDecodeStrict' bytes of+    Left e -> readerError $ "error parsing " ++ show bytes ++ ": " ++ e+    Right v -> pure v++factSourceParser :: Parser FactSource+factSourceParser+  =  LiteralFact <$> option valueReader+       ( long "fact"+      <> metavar "FACT"+      <> help "the fact value"+       )+ <|> ReadableFact <$> readableOption+       ( long "fact-file"+      <> metavar "FACT_FILE"+      <> help "the path to a file containing the fact value"+       )+       ( long "fact-fd"+      <> metavar "FACT_FD"+      <> help "a file descriptor containing the fact value"+       )++createFactArgsParser :: Parser CreateFactArgs+createFactArgsParser = CreateFactArgs+  <$> factSourceParser+  <*> (optional $ readableOption+        ( long "artifact-file"+       <> metavar "ARTIFACT_FILE"+       <> help "the file containing the artifact to attach"+        )+        ( long "artifact-fd"+       <> metavar "ARTIFACT_FD"+       <> help "a file descriptor containing the artifact to attach"+        ))++createFactArgsInfo :: ParserInfo CreateFactArgs+createFactArgsInfo = info createFactArgsParser+  ( fullDesc+ <> header "cicero-cli fact create — Create a new fact"+  )++getFactsParser :: Parser RunID+getFactsParser = option (maybeReader runIdFromString)+  ( long "run-id"+ <> metavar "RUN_ID"+ <> help "the ID of the run which produced the facts"+  )++getFactsInfo :: ParserInfo RunID+getFactsInfo = info getFactsParser+  ( fullDesc+ <> header "cicero-cli fact get-all — Get information about facts"+  )++data FactCommand+  = CmdCreateFact !CreateFactArgs+  | CmdGetFacts !RunID++factCommandParser :: Parser FactCommand+factCommandParser = hsubparser+  ( command "create" (CmdCreateFact <$> createFactArgsInfo)+ <> command "get-all" (CmdGetFacts <$> getFactsInfo)+  )++factCommandInfo :: ParserInfo FactCommand+factCommandInfo = info factCommandParser+  ( fullDesc+ <> header "cicero-cli fact — Manage Cicero facts"+  )++data FactParseException = FactParseException+  { parseError :: !String+  } deriving Show++instance Exception FactParseException++createFactHandler :: CreateFactArgs -> (CreateFactV1 -> ClientM FactV1) -> ClientEnv -> IO ()+createFactHandler createArgs call cEnv = do+  fact <- case createArgs.factSource of+    LiteralFact v -> pure v+    ReadableFact f -> do+      factBytes <- consume f+      let parsedBytes = foldlChunks feed (Partial (parse jsonEOF')) factBytes+          res = feed parsedBytes ""+      case eitherResult res of+        Left e -> throw $ FactParseException e+        Right v -> pure v+  artifact <- case createArgs.artifactSource of+    Nothing -> pure Nothing+    Just f -> Just <$> consume f+  runClientM (call (CreateFact { .. })) cEnv >>= \case+    Left e -> throw e+    Right res -> hPutStrLn stdout $ encode res++handler :: FactCommand -> Client ClientM API -> ClientEnv -> IO ()+handler (CmdCreateFact createArgs) factClient cEnv =+  createFactHandler createArgs factClient.create cEnv+handler (CmdGetFacts rid) factClient cEnv = runClientM (factClient.getAll rid) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res
+ cli/Invocation.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedRecordDot #-}+module Invocation where++import IOHK.Cicero.API.Invocation+import Options.Applicative+import Servant.Client+import Data.Aeson+import System.IO (stdout)+import Data.ByteString.Lazy.Char8+import Control.Exception++getInvocationParser :: Parser InvocationID+getInvocationParser = argument (maybeReader invocationIdFromString)+  ( metavar "INVOCATION_ID"+ <> help "the ID of the invocation to get"+  )++getInvocationInfo :: ParserInfo InvocationID+getInvocationInfo = info getInvocationParser+  ( fullDesc+ <> header "cicero-cli invocation get — Get information about an invocation"+  )++data InvocationCommand+  = CmdGetInvocation !InvocationID++invocationCommandParser :: Parser InvocationCommand+invocationCommandParser = hsubparser+  ( command "get" (CmdGetInvocation <$> getInvocationInfo)+  )++invocationCommandInfo :: ParserInfo InvocationCommand+invocationCommandInfo = info invocationCommandParser+  ( fullDesc+ <> header "cicero-cli invocation — Manage Cicero invocations"+  )++handler :: InvocationCommand -> Client ClientM API -> ClientEnv -> IO ()+handler (CmdGetInvocation id) invocationClient cEnv = runClientM (invocationClient.get id) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res
+ cli/Main.hs view
@@ -0,0 +1,100 @@+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE LambdaCase #-}+module Main where++import IOHK.Cicero.API+import Servant.Client+import Servant.Client.Core.BaseUrl+import Data.Proxy+import Network.HTTP.Client hiding (Proxy)+import Network.HTTP.Client.TLS+import Data.ByteString.Char8 as BS+import Options.Applicative+import Control.Exception+import System.Console.Haskeline+import Servant.API.BasicAuth+import Servant.Client.Core.BasicAuth++import Action+import Fact+import Invocation+import Run++data Command+  = CmdFact !FactCommand+  | CmdAction !ActionCommand+  | CmdInvocation !InvocationCommand+  | CmdRun !RunCommand++commandParser :: Parser Command+commandParser = hsubparser+  ( command "fact" (CmdFact <$> factCommandInfo)+ <> command "action" (CmdAction <$> actionCommandInfo)+ <> command "invocation" (CmdInvocation <$> invocationCommandInfo)+ <> command "run" (CmdRun <$> runCommandInfo)+  )++data Args = Args+  { ciceroURL :: !BaseUrl+  , ciceroUser :: !(Maybe ByteString)+  , cmd :: !Command+  }++baseUrlReader :: ReadM BaseUrl+baseUrlReader = do+  urlStr <- str+  case parseBaseUrl urlStr of+    Left e -> case fromException e of+      Just (InvalidBaseUrlException s) -> readerError $ "invalid URL '" ++ urlStr ++ "': " ++ s+      Nothing -> readerError $ "exception parsing '" ++ urlStr ++ "' as a URL: " ++ displayException e+    Right b -> pure b++argsParser :: Parser Args+argsParser = Args+  <$> option baseUrlReader+        ( long "cicero-url"+       <> metavar "CICERO_URL"+       <> help "URL of the cicero server"+       <> showDefaultWith showBaseUrl+       <> (value $ BaseUrl Http "localhost" 8080 "")+        )+  <*> (optional $ option str+        ( long "user"+       <> metavar "USER"+       <> help "User name for BASIC authentication with the cicero server"+        ))+  <*> commandParser++argsInfo :: ParserInfo Args+argsInfo = info (argsParser <**> helper)+  ( fullDesc+ <> header "cicero-cli — A tool for interacting with the Cicero API"+  )++getHandler :: Command -> Client ClientM API -> ClientEnv -> IO ()+getHandler (CmdAction acmd) apiClient = Action.handler acmd apiClient.action+getHandler (CmdFact fcmd) apiClient = Fact.handler fcmd apiClient.fact+getHandler (CmdInvocation icmd) apiClient = Invocation.handler icmd apiClient.invocation+getHandler (CmdRun rcmd) apiClient = Run.handler rcmd apiClient.run++main :: IO ()+main = do+  args <- execParser argsInfo+  auth <- case args.ciceroUser of+    Nothing -> pure Nothing+    Just u -> runInputT defaultSettings (getPassword Nothing ("password for " ++ (BS.unpack u) ++ ":")) >>= \case+      Just s -> pure . Just . BasicAuthData u $ BS.pack s+      Nothing -> fail "no password provided"+  manager <- newTlsManagerWith $+        tlsManagerSettings { managerResponseTimeout = responseTimeoutNone }+  let+    cEnv = mkClientEnv manager args.ciceroURL+    cEnv' = case auth of+      Nothing -> cEnv+      Just ba -> cEnv+        { makeClientRequest = \u -> defaultMakeClientRequest u . basicAuthReq ba+        }+  getHandler args.cmd+    (client $ Proxy @API)+    cEnv'
+ cli/Run.hs view
@@ -0,0 +1,108 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE LambdaCase #-}+module Run where++import IOHK.Cicero.API.Fact hiding (API)+import IOHK.Cicero.API.Run+import Data.UUID+import Numeric.Natural+import Servant.Client+import Data.Aeson+import System.IO (stdout)+import Data.ByteString.Lazy.Char8+import Control.Exception+import Options.Applicative++import qualified Fact++data GetRunsArgs = GetRunsArgs+  { recursive :: !Bool+  , inputs :: ![ FactID ]+  , offset :: !(Maybe Natural)+  , limit :: !(Maybe Natural)+  }++getRunsArgsParser :: Parser GetRunsArgs+getRunsArgsParser = GetRunsArgs+  <$> switch+        ( long "recursive"+       <> help "get the transitive closure of runs started by facts at FACT_IDs"+        )+  <*> many (option (maybeReader factIdFromString)+             ( long "fact-id"+            <> metavar "FACT_ID"+            <> help "only get runs started by this fact (multiple instances are ANDed together)"+             ))+  <*> optional (option auto+        ( long "offset"+       <> metavar "OFFSET"+       <> help "offset into result list to start query (for pagination)"+        ))+  <*> optional (option auto+        ( long "limit"+       <> metavar "OFFSET"+       <> help "offset into result list to start query (for pagination)"+        ))++getRunsInfo :: ParserInfo GetRunsArgs+getRunsInfo = info getRunsArgsParser+  ( fullDesc+ <> header "cicero-cli run get-all — Get information about runs"+  )++data CreateFactArgs = CreateFactArgs+  { run :: !RunID+  , factArgs :: !Fact.CreateFactArgs+  }++runIdArgsParser :: Parser RunID+runIdArgsParser = option (maybeReader runIdFromString)+  ( long "run-id"+ <> metavar "RUN_ID"+ <> help "the ID of the run to associate the fact with"+  )++createFactArgsParser :: Parser CreateFactArgs+createFactArgsParser = CreateFactArgs+  <$> runIdArgsParser+  <*> Fact.createFactArgsParser++createFactInfo :: ParserInfo CreateFactArgs+createFactInfo = info createFactArgsParser+  ( fullDesc+ <> header "cicero-cli run create-fact — Create a new fact associated with a run"+  )++getLogsInfo :: ParserInfo RunID+getLogsInfo = info runIdArgsParser+  ( fullDesc+ <> header "cicero-cli run get-logs — Get logs for a run"+  )++data RunCommand+  = CmdGetRuns !GetRunsArgs+  | CmdCreateFact !CreateFactArgs+  | CmdGetLogs !RunID++runCommandParser :: Parser RunCommand+runCommandParser = hsubparser+  ( command "get-all" (CmdGetRuns <$> getRunsInfo)+ <> command "create-fact" (CmdCreateFact <$> createFactInfo)+ <> command "get-logs" (CmdGetLogs <$> getLogsInfo)+  )++runCommandInfo :: ParserInfo RunCommand+runCommandInfo = info runCommandParser+  ( fullDesc+ <> header "cicero-cli run — Manage Cicero runs"+  )++handler :: RunCommand -> Client ClientM API -> ClientEnv -> IO ()+handler (CmdGetRuns gra) runClient cEnv = runClientM (runClient.getAll gra.recursive gra.inputs gra.offset gra.limit) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res+handler (CmdCreateFact createArgs) runClient cEnv =+  Fact.createFactHandler createArgs.factArgs (runClient.createFact createArgs.run) cEnv+handler (CmdGetLogs rid) runClient cEnv = runClientM (runClient.getLogs rid) cEnv >>= \case+  Left e -> throw e+  Right res -> hPutStrLn stdout $ encode res
+ src/IOHK/Cicero/API.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+module IOHK.Cicero.API where++import Servant.API+import Servant.API.NamedRoutes+import Servant.API.Generic++import IOHK.Cicero.API.Action as Action+import IOHK.Cicero.API.Fact as Fact+import IOHK.Cicero.API.Invocation as Invocation+import IOHK.Cicero.API.Run as Run++-- | The Cicero API+type API = "api" :> NamedRoutes APIRoutes++-- | The routes for the Cicero API+data APIRoutes mode = APIRoutes+  { action :: mode :- "action" :> Action.API+  , fact :: mode :- "fact" :> Fact.API+  , invocation :: mode :- "invocation" :> Invocation.API+  , run :: mode :- "run" :> Run.API+  } deriving stock Generic
+ src/IOHK/Cicero/API/Action.hs view
@@ -0,0 +1,156 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE BlockArguments #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE DeriveGeneric #-}+module IOHK.Cicero.API.Action where++import Data.Coerce+import Data.Text+import Data.Aeson+import Data.Aeson.Encoding+import Data.Aeson.Types+import Data.Map+import Data.Time.LocalTime+import Data.UUID as UUID+import Data.String+import Servant.API+import Servant.API.Generic+import Servant.API.NamedRoutes++type API = NamedRoutes ActionRoutes++newtype ActionID = ActionID { uuid :: UUID } deriving newtype (ToHttpApiData, FromJSON, ToJSON, Eq, Ord)++actionIdFromString :: String -> Maybe ActionID+actionIdFromString = coerce . UUID.fromString++-- | Action routes in the Cicero API+data ActionRoutes mode = ActionRoutes+  { create :: mode :- ReqBody '[JSON] CreateActionV1 :> Post '[JSON] CreateActionResponseV2+  , get :: mode :- Capture "id" ActionID :> Get '[JSON] ActionV2+  } deriving stock Generic++data CreateActionV1 = CreateAction+  { names :: !ActionNamesV1+  , source :: !ActionSourceV1+  }++instance ToJSON CreateActionV1 where+  toJSON ca = object $ "source" .= ca.source : case ca.names of+    Only n -> [ "name" .= n ]+    AllNames -> []+  toEncoding ca = pairs $ "source" .= ca.source <> case ca.names of+    Only n -> "name" .= n+    AllNames -> mempty++data CreateActionResponseV2+  = -- | The specific action created+    --+    -- Returned if an 'Only' was set in 'names'+    CreateActionOnly !ActionV2+  | -- | All actions created+    --+    -- Returned if 'AllNames' was set in 'names'+    CreateActionAll !([ ActionV2 ])++instance FromJSON CreateActionResponseV2 where+  parseJSON v = prependFailure "parsing CreateActionResponseV2 failed, " $ case v of+    Object _ -> CreateActionOnly <$> parseJSON v+    Array _ -> CreateActionAll <$> parseJSON v+    _ -> typeMismatch "Object or Array" v++instance ToJSON CreateActionResponseV2 where+  toJSON (CreateActionOnly act) = toJSON act+  toJSON (CreateActionAll acts) = toJSON acts++  toEncoding (CreateActionOnly act) = toEncoding act+  toEncoding (CreateActionAll acts) = toEncoding acts++-- | The source of an action, as a [go-getter URL](https://github.com/hashicorp/go-getter#url-format)+newtype ActionSourceV1 = ActionSource { unActionSource :: Text } deriving newtype (IsString, FromJSON, ToJSON)++-- | The action names to add from a given 'ActionSourceV1'+data ActionNamesV1+  = -- | Just add the action with the given name+    Only !Text+  | -- | Add all names exported by the source+    AllNames++-- | A [CUE lang](https://cuelang.org/) value+--+-- For now just a wrapper around 'Text' that we hope parses+newtype CUE = CUE { expr :: Text } deriving newtype (FromJSON, ToJSON)++-- | An input to a job+data InputV2 = Input+  { -- | Negate the matching condition?+    not :: !Bool+  , -- | Can this input be missing?+    optional :: !Bool+  , -- | Which facts to match+    match :: !CUE+  }++instance FromJSON InputV2 where+  parseJSON = withObject "InputV2" \o -> Input+    <$> o .: "not"+    <*> o .: "optional"+    <*> o .: "match"++instance ToJSON InputV2 where+  toJSON i = object+    [ "not" .= i.not+    , "optional" .= i.optional+    , "match" .= i.match+    ]+  toEncoding i = pairs+    ( "not" .= i.not+   <> "optional" .= i.optional+   <> "match" .= i.match+    )++-- | An action+data ActionV2 = Action+  { id :: !ActionID+  , name :: !Text+  , source :: !ActionSourceV1+  , createdAt :: !ZonedTime+  , active :: !Bool+  , meta :: !(Maybe (Map Text Value))+  , inputs :: !(Map Text InputV2)+  }++instance FromJSON ActionV2 where+  parseJSON = withObject "ActionV2" \o -> Action+    <$> o .: "id"+    <*> o .: "name"+    <*> o .: "source"+    <*> o .: "created_at"+    <*> o .: "active"+    <*> o .: "meta"+    <*> o .: "inputs"++instance ToJSON ActionV2 where+  toJSON a = object+    [ "id" .= a.id+    , "name" .= a.name+    , "source" .= a.source+    , "created_at" .= a.createdAt+    , "active" .= a.active+    , "meta" .= a.meta+    , "inputs" .= a.inputs+    ]+  toEncoding a = pairs+    ( "id" .= a.id+   <> "name" .= a.name+   <> "source" .= a.source+   <> "created_at" .= a.createdAt+   <> "active" .= a.active+   <> "meta" .= a.meta+   <> "inputs" .= a.inputs+    )
+ src/IOHK/Cicero/API/Fact.hs view
@@ -0,0 +1,98 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE BlockArguments #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE MultiParamTypeClasses #-}+module IOHK.Cicero.API.Fact where++import Data.Coerce+import Data.Text+import Data.Aeson+import Data.Time.LocalTime+import Data.UUID+import Data.ByteString.Lazy+import Data.Binary.Builder+import Servant.API+import Servant.API.Generic+import Servant.API.NamedRoutes++import {-# SOURCE #-} IOHK.Cicero.API.Run (RunID)++newtype FactID = FactID { uuid :: UUID } deriving newtype (ToJSON, FromJSON, ToHttpApiData, Eq, Ord)++factIdFromString :: String -> Maybe FactID+factIdFromString = coerce . fromString++type API = NamedRoutes FactRoutes++-- | Fact routes in the Cicero API+data FactRoutes mode = FactRoutes+  { create :: mode :- ReqBody '[OctetStream] CreateFactV1 :> Post '[JSON] FactV1+  , getAll :: mode :- QueryParam' '[Required, Strict] "run" RunID :> Get '[JSON] [FactV1]+  } deriving stock Generic++data CreateFactV1 = CreateFact+  { -- | The data of the fact+    fact :: !Value+  , -- | Binary blob attached to the fact+    artifact :: !(Maybe ByteString)+  }++-- | This instance assumes that @'toEncoding' \@'Value'@ has no trailing whitespace!+instance MimeRender OctetStream CreateFactV1 where+  mimeRender _ cf = toLazyByteString $ factBuilt <> artifactBuilt+    where+      factBuilt = fromEncoding $ toEncoding cf.fact+      artifactBuilt = case cf.artifact of+        Just a -> fromLazyByteString a+        Nothing -> mempty++-- | A Cicero fact+data FactV1 = Fact+  { id :: !FactID+  , runId :: !(Maybe RunID)+  , createdAt :: !ZonedTime+  , value :: !Value+  , -- | The hash of the artifact, if any+    --+    -- This should be a proper hash type+    binaryHash :: !(Maybe Text)+  }++instance FromJSON FactV1 where+  parseJSON = withObject "FactV1" \o -> Fact+    <$> o .: "id"+    <*> o .:? "run_id"+    <*> o .: "created_at"+    <*> o .: "value"+    <*> o .:? "binary_hash"++instance ToJSON FactV1 where+  toJSON f = object $+      [ "id" .= f.id+      , "created_at" .= f.createdAt+      , "value" .= f.value+      ] ++ runIdFields ++ binaryHashFields+    where+      runIdFields = case f.runId of+        Just rid -> [ "run_id" .= rid ]+        Nothing -> []+      binaryHashFields = case f.binaryHash of+        Just hash -> [ "binary_hash" .= hash ]+        Nothing -> []+  toEncoding f = pairs $+      ( "id" .= f.id+     <> "created_at" .= f.createdAt+     <> "value" .= f.value+      ) <> runIdFields <> binaryHashFields+    where+      runIdFields = case f.runId of+        Just rid -> "run_id" .= rid+        Nothing -> mempty+      binaryHashFields = case f.binaryHash of+        Just hash -> "binary_hash" .= hash+        Nothing -> mempty
+ src/IOHK/Cicero/API/Invocation.hs view
@@ -0,0 +1,58 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralisedNewtypeDeriving #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE BlockArguments #-}+{-# LANGUAGE OverloadedStrings #-}+module IOHK.Cicero.API.Invocation where++import Data.Aeson+import Data.UUID as UUID+import Data.Coerce+import Data.Time.LocalTime+import Servant.API+import Servant.API.Generic+import Servant.API.NamedRoutes++import IOHK.Cicero.API.Action++newtype InvocationID = InvocationID { uuid :: UUID } deriving newtype (ToJSON, FromJSON, ToHttpApiData, Eq, Ord)++invocationIdFromString :: String -> Maybe InvocationID+invocationIdFromString = coerce . UUID.fromString++type API = NamedRoutes InvocationRoutes++data InvocationRoutes mode = InvocationRoutes+  { get :: mode :- Capture "id" InvocationID :> Get '[JSON] InvocationV1+  } deriving stock Generic++data InvocationV1 = Invocation+  { id :: !InvocationID+  , actionId :: !ActionID+  , createdAt :: !ZonedTime+  , finishedAt :: !(Maybe ZonedTime)+  }++instance FromJSON InvocationV1 where+  parseJSON = withObject "InvocationV1" \o -> Invocation+    <$> o .: "id"+    <*> o .: "action_id"+    <*> o .: "created_at"+    <*> o .:? "finished_at"++instance ToJSON InvocationV1 where+  toJSON i = object+    [ "id" .= i.id+    , "action_id" .= i.actionId+    , "created_at" .= i.createdAt+    , "finished_at" .= i.finishedAt+    ]+  toEncoding i = pairs+    ( "id" .= i.id+   <> "action_id" .= i.actionId+   <> "created_at" .= i.createdAt+   <> "finished_at" .= i.finishedAt+    )
+ src/IOHK/Cicero/API/Run.hs view
@@ -0,0 +1,115 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE BlockArguments #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralisedNewtypeDeriving #-}+{-# LANGUAGE DerivingStrategies #-}+module IOHK.Cicero.API.Run where++import Data.Aeson+import Data.Coerce+import Data.Text+import Data.Time.LocalTime+import Data.UUID+import Numeric.Natural+import Servant.API+import Servant.API.Generic+import Servant.API.NamedRoutes++import IOHK.Cicero.API.Fact+import IOHK.Cicero.API.Invocation++newtype RunID = RunID { uuid :: UUID } deriving newtype (ToJSON, FromJSON, ToHttpApiData, Eq, Ord)++runIdFromString :: String -> Maybe RunID+runIdFromString = coerce . fromString+++type API = NamedRoutes RunRoutes++-- | Run routes in the Cicero API+data RunRoutes mode = RunRoutes+  { getAll :: mode+           :- QueryFlag "recursive"+           :> QueryParams "input" FactID+           :> QueryParam "offset" Natural+           :> QueryParam "limit" Natural+           :> Get '[JSON] [RunV2]+  , createFact :: mode+               :- Capture "id" RunID+               :> "fact"+               :> ReqBody '[OctetStream] CreateFactV1+               :> Post '[JSON] FactV1+  , getLogs :: mode+            :- Capture "id" RunID+            :> "logs"+            :> Get '[JSON] RunLogsV1+  } deriving stock Generic++data RunV2 = Run+  { nomadJobId :: !RunID+  , invocationId :: !InvocationID+  , createdAt :: !ZonedTime+  , finishedAt :: !(Maybe ZonedTime)+  }++instance FromJSON RunV2 where+  parseJSON = withObject "RunV2" \o -> Run+    <$> o .: "nomad_job_id"+    <*> o .: "invocation_id"+    <*> o .: "created_at"+    <*> o .: "finished_at"++instance ToJSON RunV2 where+  toJSON r = object+    [ "nomad_job_id" .= r.nomadJobId+    , "invocation_id" .= r.invocationId+    , "created_at" .= r.createdAt+    , "finished_at" .= r.finishedAt+    ]+  toEncoding r = pairs+    ( "nomad_job_id" .= r.nomadJobId+   <> "invocation_id" .= r.invocationId+   <> "created_at" .= r.createdAt+   <> "finished_at" .= r.finishedAt+    )++newtype RunLogsV1 = RunLogs [RunLog]++instance FromJSON RunLogsV1 where+  parseJSON = withObject "RunLogsV1" \o ->+    RunLogs <$> o .: "logs"++instance ToJSON RunLogsV1 where+  toJSON (RunLogs logs) = object+    [ "logs" .= logs+    ]+  toEncoding (RunLogs logs) = pairs+    ( "logs" .= logs+    )++data RunLog = RunLog+  { time :: !ZonedTime+  , source :: !Text+  , text :: !Text+  }++instance FromJSON RunLog where+  parseJSON = withObject "RunLog" \o -> RunLog+    <$> o .: "Time"+    <*> o .: "Source"+    <*> o .: "Text"++instance ToJSON RunLog where+  toJSON r = object+    [ "Time" .= r.time+    , "Source" .= r.source+    , "Text" .= r.text+    ]+  toEncoding r = pairs+    ( "Time" .= r.time+   <> "Source" .= r.source+   <> "Text" .= r.text+    )
+ src/IOHK/Cicero/API/Run.hs-boot view
@@ -0,0 +1,9 @@+module IOHK.Cicero.API.Run where++import Data.Aeson+import Data.UUID (UUID)++newtype RunID = RunID { uuid :: UUID }++instance ToJSON RunID+instance FromJSON RunID