A peer-to-peer stack for code collaboration
Move http storge primfns to lib
Thomas Scholtescd19b9e1c191
diff --git a/exe/API.hs b/exe/API.hsdeleted file mode 100644index f44dba2..0000000--- a/exe/API.hs+++ /dev/null@@ -1,55 +0,0 @@-{-# OPTIONS_GHC -fno-warn-orphans #-}-module API where--import qualified Data.ByteString.Lazy as LBS-import qualified Data.Text as T-import GHC.Exts (IsList(..))-import Protolude-import Radicle-import Radicle.Internal.Annotation (thisPos)-import Servant.API--instance MimeRender PlainText Value where- mimeRender _ x = LBS.fromStrict $ encodeUtf8 $ renderCompactPretty x--instance MimeUnrender PlainText Value where- mimeUnrender _ x =- let src = decodeUtf8 $ LBS.toStrict x- in first T.unpack $ parse "[request body]" src--newtype Values = Values { getValues :: [Value] }- deriving (Eq, Show, Ord)--instance IsList Values where- type Item Values = Value- fromList = Values- toList = getValues--instance MimeRender PlainText Values where- mimeRender _ (Values xs)- = LBS.intercalate "\n" $ mimeRender p <$> xs- where- p = Proxy :: Proxy PlainText--instance MimeUnrender PlainText Values where- mimeUnrender _ x =- let src = decodeUtf8 $ LBS.toStrict x- in case parseValues "[request body]" src of- Right vs -> Right $ Values vs- Left err -> Left . toS $ renderPrettyDef err'- where err' :: LangError Value- err' = LangError [thisPos] (ParseError err)---- | Endpoint to submit an expression to a chain. Responds with @:ok@ if the--- expression has been submitted sucessfully.-type ChainSubmitEndpoint = "submit" :> ReqBody '[PlainText] Values :> Post '[PlainText] Value--chainSubmitEndpoint :: Proxy ChainSubmitEndpoint-chainSubmitEndpoint = Proxy---- | Endpoint to obtain all entries in a chain starting from the given--- index. Responds with a Radicle vector of the expressions.-type ChainSinceEndpoint = "since" :> Capture "index" Int :> Get '[PlainText] Value--chainSinceEndpoint :: Proxy ChainSinceEndpoint-chainSinceEndpoint = Proxydiff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hsindex c5a4e67..54c9f47 100644--- a/exe/RadicleExe.hs+++ b/exe/RadicleExe.hs@@ -1,20 +1,12 @@module RadicleExe (main) where-import API-import Control.Monad.Catch (MonadThrow)-import qualified Data.Text as T-import GHC.Exts (fromList)-import Network.HTTP.Client (defaultManagerSettings, newManager)-import qualified Network.HTTP.Client as HttpClientimport Options.Applicativeimport Prelude (String)import Protolude hiding (TypeError, option, sourceFile)import Radicle-import Servant.Clientimport System.Directory (doesFileExist)-import qualified Radicle.Internal.Number as Num-import qualified Radicle.Internal.PrimFns as PrimFns+import Radicle.Internal.HttpStoragemain :: IO ()main = do@@ -22,9 +14,9 @@ main = doif sourceFile opts' == "-"then dosrc <- getContents- mgr <- newManager defaultManagerSettingslet prog = interpretMany (toS $ sourceFile opts') src- (result, _state) <- runLang (bindings mgr) prog+ bindings <- createBindings+ (result, _state) <- runLang bindings progcase result ofLeft (LangError _ Exit) -> pure ()Left e -> do putStrLn $ renderPrettyDef e@@ -35,8 +27,8 @@ main = dohist <- case histFile opts' ofNothing -> getHistoryFileJust h -> pure h- mgr <- newManager defaultManagerSettings- repl (Just hist) (toS $ sourceFile opts') src (bindings mgr)+ bindings <- createBindings+ repl (Just hist) (toS $ sourceFile opts') src bindingswhereallOpts = info (opts <**> helper)( fullDesc@@ -84,55 +76,7 @@ opts = Opts)))--- * Primops--bindings :: (MonadIO m, ReplM m) => HttpClient.Manager -> Bindings (PrimFns m)-bindings mgr = addPrimFns (replPrimFns <> clientPrimFns mgr) pureEnv--clientPrimFns :: MonadIO m => HttpClient.Manager -> PrimFns m-clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]- where- sendPrimop =- ( "send!"- , "Given a URL (string) and a value, sends the value `v` to the remote\- \ chain located at the URL for evaluation."- , PrimFns.twoArg "send!" $ \case- (String url, Vec v) -> do- res <- liftIO $ runClientM' url mgr (submit $ toList v)- case res of- Left e -> throwErrorHere . OtherError- $ "send!: failed:" <> show e- Right r -> pure r- (String _, v) -> throwErrorHere $ TypeError "send!" 1 TVec v- (v, _) -> throwErrorHere $ TypeError "send!" 0 TString v- )- receivePrimop =- ( "receive!"- , "Given a URL (string) and a integral number `n`, queries the remote chain\- \ for the last `n` inputs that have been evaluated."- , PrimFns.twoArg "receive!" $ \case- (String url, Number n) -> do- case Num.isInt n of- Left _ -> throwErrorHere . OtherError- $ "receive!: expecting int argument"- Right r -> do- liftIO (runClientM' url mgr (since r)) >>= \case- Left err -> throwErrorHere . OtherError- $ "receive!: request failed:" <> show err- Right v' -> pure v'- (String _, v) -> throwErrorHere $ TypeError "receive!" 1 TNumber v- (v, _) -> throwErrorHere $ TypeError "receive!" 0 TString v- )---- * Client functions--submit :: [Value] -> ClientM Value-submit = client chainSubmitEndpoint . Values--since :: Int -> ClientM Value-since = client chainSinceEndpoint--runClientM' :: (MonadThrow m, MonadIO m) => Text -> HttpClient.Manager -> ClientM a -> m (Either ServantError a)-runClientM' baseUrl manager endpoint = do- url <- parseBaseUrl $ T.unpack baseUrl- liftIO $ runClientM endpoint $ mkClientEnv manager url+createBindings :: (MonadIO m, ReplM m) => IO (Bindings (PrimFns m))+createBindings = do+ storage <- createHttpStoragePrimFns+ pure $ addPrimFns (replPrimFns <> storage) pureEnvdiff --git a/exe/Server.hs b/exe/Server.hsindex 7bacbf1..8e962d2 100644--- a/exe/Server.hs+++ b/exe/Server.hs@@ -46,8 +46,8 @@ import Servant, serveDirectoryFileServer)-import APIimport Radicle+import Radicle.Internal.HttpStorageimport Server.DB-- * Typesdiff --git a/package.yaml b/package.yamlindex 522efd6..3a94220 100644--- a/package.yaml+++ b/package.yaml@@ -11,28 +11,7 @@ extra-source-files:dependencies:- base >=4 && <5- protolude-- aeson-- containers-- cryptonite-- data-default-- deriving-compat-- directory-- filepath-- generics-eot-- haskeline-- megaparsec-- mtl-- pointed-- prettyprinter-- prettyprinter-ansi-terminal-- recursion-schemes-- scientific-- serialise-- template-haskell-- text-- time-- unordered-containers-- uuid+when:- condition: impl(ghcjs)dependencies: ghcjs-dom@@ -44,6 +23,34 @@ data-files:library:source-dirs: src+ dependencies:+ - aeson+ - bytestring+ - containers+ - cryptonite+ - data-default+ - deriving-compat+ - directory+ - filepath+ - generics-eot+ - haskeline+ - http-client+ - http-media+ - megaparsec+ - mtl+ - pointed+ - prettyprinter+ - prettyprinter-ansi-terminal+ - recursion-schemes+ - servant+ - servant-client+ - scientific+ - serialise+ - template-haskell+ - text+ - time+ - unordered-containers+ - uuidtests:spec:@@ -53,17 +60,24 @@ tests:ghc-options: -threadeddependencies:- radicle+ - containers+ - cryptonite- directory- filemanip- interpolate+ - megaparsec- QuickCheck- quickcheck-instances- safe+ - scientific+ - serialise- string-qq- tasty- tasty-discover- tasty-hunit- tasty-quickcheck+ - text+ - timedoctest:main: Main.hssource-dirs:@@ -81,16 +95,12 @@ executables:radicle:main: RadicleExe.hssource-dirs: exe- other-modules: API+ other-modules: []dependencies:- radicle- - bytestring+ - directory- exceptions- - http-client- - http-media- optparse-applicative- - servant- - servant-clientwhen:- condition: impl(ghcjs)buildable: false@@ -99,12 +109,14 @@ executables:radicle-server:main: Server.hssource-dirs: exe- other-modules: [API, Server.DB]+ other-modules: [Server.DB]when:- condition: impl(ghcjs)buildable: falsedependencies:- radicle+ - aeson+ - containers- bytestring- optparse-applicative- postgresql-simple@@ -118,7 +130,7 @@ executables:radicle-client-ghcjs:main: GHCJS.hssource-dirs: exe- other-modules: API+ other-modules: []dependencies:- radicle- ghcjs-base@@ -150,8 +162,10 @@ executables:buildable: falsedependencies:- radicle+ - haskeline- optparse-applicative- pandoc+ - textghc-options: -main-is Docradicle-ref-doc:@@ -165,6 +179,9 @@ executables:- radicle- pandoc- data-default+ - containers+ - haskeline+ - textghc-options: -main-is ReferenceDocradicle-github-issues:@@ -176,6 +193,7 @@ executables:buildable: falsedependencies:- radicle+ - containers- errors- time- githubdiff --git a/src/Radicle/Internal/HttpStorage.hs b/src/Radicle/Internal/HttpStorage.hsnew file mode 100644index 0000000..3c0b218--- /dev/null+++ b/src/Radicle/Internal/HttpStorage.hs@@ -0,0 +1,134 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+-- | Provide Radicle primitives for storing chains through an HTTP API.+module Radicle.Internal.HttpStorage+ ( ChainSubmitEndpoint+ , chainSubmitEndpoint+ , ChainSinceEndpoint+ , chainSinceEndpoint+ , Values(..)++ , createHttpStoragePrimFns+ ) where++import Protolude hiding (TypeError, toList)++import qualified Data.ByteString.Lazy as LBS+import qualified Data.Text as T+import GHC.Exts (IsList(..))+import qualified Network.HTTP.Client as HttpClient+import Servant.API+import Servant.Client++import Radicle+import Radicle.Internal.Annotation (thisPos)+import qualified Radicle.Internal.Number as Num+import qualified Radicle.Internal.PrimFns as PrimFns+++--+-- * API+--++instance MimeRender PlainText Value where+ mimeRender _ x = LBS.fromStrict $ encodeUtf8 $ renderCompactPretty x++instance MimeUnrender PlainText Value where+ mimeUnrender _ x =+ let src = decodeUtf8 $ LBS.toStrict x+ in first T.unpack $ parse "[request body]" src++newtype Values = Values { getValues :: [Value] }+ deriving (Eq, Show, Ord)++instance IsList Values where+ type Item Values = Value+ fromList = Values+ toList = getValues++instance MimeRender PlainText Values where+ mimeRender _ (Values xs)+ = LBS.intercalate "\n" $ mimeRender p <$> xs+ where+ p = Proxy :: Proxy PlainText++instance MimeUnrender PlainText Values where+ mimeUnrender _ x =+ let src = decodeUtf8 $ LBS.toStrict x+ in case parseValues "[request body]" src of+ Right vs -> Right $ Values vs+ Left err -> Left . toS $ renderPrettyDef err'+ where err' :: LangError Value+ err' = LangError [thisPos] (ParseError err)++-- | Endpoint to submit an expression to a chain. Responds with @:ok@ if the+-- expression has been submitted sucessfully.+type ChainSubmitEndpoint = "submit" :> ReqBody '[PlainText] Values :> Post '[PlainText] Value++chainSubmitEndpoint :: Proxy ChainSubmitEndpoint+chainSubmitEndpoint = Proxy++-- | Endpoint to obtain all entries in a chain starting from the given+-- index. Responds with a Radicle vector of the expressions.+type ChainSinceEndpoint = "since" :> Capture "index" Int :> Get '[PlainText] Value++chainSinceEndpoint :: Proxy ChainSinceEndpoint+chainSinceEndpoint = Proxy+++--+-- * Client+--++-- | Returns definitions for the primitive functions+-- @send!@ and @receive@.+createHttpStoragePrimFns :: MonadIO m => IO (PrimFns m)+createHttpStoragePrimFns = do+ httpMgr <- HttpClient.newManager HttpClient.defaultManagerSettings+ pure $ httpStoragePrimFns' httpMgr++httpStoragePrimFns' :: MonadIO m => HttpClient.Manager -> PrimFns m+httpStoragePrimFns' mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]+ where+ sendPrimop =+ ( "send!"+ , "Given a URL (string) and a value, sends the value `v` to the remote\+ \ chain located at the URL for evaluation."+ , PrimFns.twoArg "send!" $ \case+ (String url, Vec v) -> do+ res <- liftIO $ runClientM' url mgr (submit $ toList v)+ case res of+ Left e -> throwErrorHere . OtherError+ $ "send!: failed:" <> show e+ Right r -> pure r+ (String _, v) -> throwErrorHere $ TypeError "send!" 1 TVec v+ (v, _) -> throwErrorHere $ TypeError "send!" 0 TString v+ )+ receivePrimop =+ ( "receive!"+ , "Given a URL (string) and a integral number `n`, queries the remote chain\+ \ for the last `n` inputs that have been evaluated."+ , PrimFns.twoArg "receive!" $ \case+ (String url, Number n) -> do+ case Num.isInt n of+ Left _ -> throwErrorHere . OtherError+ $ "receive!: expecting int argument"+ Right r -> do+ res <- runClientM' url mgr (since r)+ case res of+ Left err -> throwErrorHere . OtherError+ $ "receive!: request failed:" <> show err+ Right v' -> pure v'+ (String _, v) -> throwErrorHere $ TypeError "receive!" 1 TNumber v+ (v, _) -> throwErrorHere $ TypeError "receive!" 0 TString v+ )++submit :: [Value] -> ClientM Value+submit = client chainSubmitEndpoint . Values++since :: Int -> ClientM Value+since = client chainSinceEndpoint++runClientM' :: (MonadIO m) => Text -> HttpClient.Manager -> ClientM a -> m (Either ServantError a)+runClientM' baseUrl manager endpoint = liftIO $ do+ url <- parseBaseUrl $ T.unpack baseUrl+ liftIO $ runClientM endpoint $ mkClientEnv manager url