A peer-to-peer stack for code collaboration
Improve remote chain interaction
Thomas Scholtesda26534579ec
diff --git a/docs/source/guide/Chains.lrad b/docs/source/guide/Chains.lradindex b9ff1dc..89c6fba 100644--- a/docs/source/guide/Chains.lrad+++ b/docs/source/guide/Chains.lrad@@ -31,51 +31,55 @@ In other words, we would like for programs to be *deterministic*.TODO: more.-## Chains+## Exploring remote chains-### Remote chains+First we start up a simple server that hosts remote chains on port 8000.-The basic building blocks of interacting with remote chains are the `send!` and-`receive!` operations. These send expressions to a remote chain, or receive new-ones since a given index, respectively.+```+stack exec -- radicle-server+```-These functions are, however, relatively low-level. Higher-level ones exist-that do the grunt-work of only requesting data you don't already have, and of-allowing interactive explorations of existing chains before submitting-expressions. These are described in the next section.+Now we can start a radicle REPL that will be able to communicate with+the remote chain.-### Exploring chains+```+stack exec -- radicle-client --config rad/repl.rad+```-Chains are a lot like shared environments. You can enter an environment that-corresponds to a chain and explore it:+We start of by sending an expression to the chain that defines the atom `foo`.```-(def x 0)-x ;; ==> 0-(:enter-chain empty-chain) ;; ==> :ok-(def x 1)-x ;; ==> 1-:quit ;; ==> :ok-x ;; ==> 0+(send! "http://localhost:8000/chains/my-first-chain" '(def foo :bar))```-As you can see, between entering a chain (with `:enter-chain`) and leaving it-(with `:quit`), all inputs are evaluated in the context of that chain.+After the expression has been submitted all expression submitted+subsequently will have access to the atom `foo` defined as the keyword+`:bar`.++Using another REPL we can use the `:enter-chain` macro to inspect the+updated remote chain.-(You may be wondering how `(:enter-chain empty-chain)` could possibly be valid,-as it contains a keyword apparently doing the job of a function application.-The short answer is that we can define special macro-like operations, of which-we will see more.)+```+(:enter-chain "http://localhost:8000/chains/my-first-chain")+foo ;; ==> :bar+:quit+```++Every expression put into the REPL after the `:enter-chain` macro will+be evaluated in the context of the chain. The special `:quit` macro+will leave the chain context and revert to the original REPL context.-`:enter-chain` allows you to enter a local chain. More often, you'll want to-explore and interact with chains that exist elsewhere--that are replicated in-a distributed way, or exist in some centralized server. For that, you can use-`:enter-remote-chain`.+Next we will use `:enter-chain` to evaluate and send expressions to the+remote chain.-`:enter-remote-chain` takes an argument just like `:enter-chain`, and indeed-for the most part both behave identically. The main difference is that with-`:enter-remote-chain`, you also have access to the special command `:send`,-which sends all the inputs you have so far to the remote.+```+(:enter-chain "http://localhost:8023/chains/my-first-chain")+(def bar foo)+(def quux 4)+:send ;; ==> :ok+:quit+```-In order to receive new inputs and update the chain state accordingly, you-can use the function `update-chain`.+The `:send` macro will call `send!` for every expression input on the+REPL. This means that the state of “my-first-chain” will no define both+`bar` and `quux`.diff --git a/exe/Server/API.hs b/exe/Server/API.hsindex fde0b54..8dba00e 100644--- a/exe/Server/API.hs+++ b/exe/Server/API.hs@@ -1,7 +1,6 @@{-# OPTIONS_GHC -fno-warn-orphans #-}module API where-import qualified Data.Aeson as Aimport qualified Data.ByteString.Lazy as LBSimport qualified Data.Text as Timport Protolude@@ -14,11 +13,13 @@ instance Show a => MimeRender PlainText a whereinstance Read a => MimeUnrender PlainText a wheremimeUnrender _ x = readEither $ T.unpack $ decodeUtf8 $ LBS.toStrict x-type API- = "submit" :> ReqBody '[PlainText] Value :> Post '[PlainText] ()- :<|> "since" :> Capture "chain" Text :> Capture "index" Int :> Get '[PlainText] [Value]- :<|> "outputs" :> Capture "chain" Text :> Get '[JSON, PlainText] [Maybe A.Value]- :<|> Raw-api :: Proxy API-api = Proxy+type ChainSubmitEndpoint = "submit" :> ReqBody '[PlainText] Value :> Post '[PlainText] ()++chainSubmitEndpoint :: Proxy ChainSubmitEndpoint+chainSubmitEndpoint = Proxy++type ChainSinceEndpoint = "since" :> Capture "index" Int :> Get '[PlainText] [Value]++chainSinceEndpoint :: Proxy ChainSinceEndpoint+chainSinceEndpoint = Proxydiff --git a/exe/Server/Client.hs b/exe/Server/Client.hsindex 0fc4076..8b83161 100644--- a/exe/Server/Client.hs+++ b/exe/Server/Client.hs@@ -1,13 +1,15 @@module Client whereimport API+import Control.Monad.Catch (MonadThrow)import Data.Scientific (floatingOrInteger)+import qualified Data.Text as Timport GHC.Exts (fromList)import Network.HTTP.Client (defaultManagerSettings, newManager)+import qualified Network.HTTP.Client as HttpClientimport Options.Applicativeimport Protolude hiding (TypeError, option)import Radicle-import Servant.API ((:<|>)(..))import Servant.Clientimport System.Console.Haskeline (InputT)@@ -22,8 +24,7 @@ main = doNothing -> getHistoryFileJust h -> pure hmgr <- newManager defaultManagerSettings- let cEnv = mkClientEnv mgr (serverURL opts')- repl (Just hist) (toS cfgFile) cfgSrc (bindings cEnv)+ repl (Just hist) (toS cfgFile) cfgSrc (bindings mgr)whereallOpts = info (opts <**> helper)( fullDesc@@ -35,7 +36,6 @@ main = dodata Opts = Opts{ configFile :: Maybe FilePath- , serverURL :: BaseUrl, histFile :: Maybe FilePath}@@ -46,34 +46,25 @@ opts = Opts<> metavar "FILE"<> help "rad configuration file"))- <*> option (str >>= parseBaseUrl')- ( long "url"- <> metavar "URL"- <> help "URL of server"- )<*> optional (strOption( long "histfile"<> metavar "FILE"<> help "repl history file"))- where- parseBaseUrl' x = case parseBaseUrl x of- Nothing -> readerError "can't parse URL"- Just v -> pure v-- * Primops-bindings :: ClientEnv -> Bindings (PrimFns (InputT IO))-bindings cEnv = addPrimFns (replPrimFns <> clientPrimFns cEnv) pureEnv+bindings :: HttpClient.Manager -> Bindings (PrimFns (InputT IO))+bindings mgr = addPrimFns (replPrimFns <> clientPrimFns mgr) pureEnv-clientPrimFns :: ClientEnv -> PrimFns (InputT IO)-clientPrimFns cEnv = PrimFns (fromList [sendPrimop, receivePrimop])+clientPrimFns :: HttpClient.Manager -> PrimFns (InputT IO)+clientPrimFns mgr = PrimFns (fromList [sendPrimop, receivePrimop])wheresendPrimop =( unsafeToIdent "send!", \case- [String name, v] -> do- res <- liftIO $ runClientM (submit $ List $ [String name, v]) cEnv+ [String url, v] -> do+ res <- liftIO $ runClientM' url mgr (submit v)case res ofLeft e -> throwErrorHere . OtherError$ "send!: failed:" <> show e@@ -84,12 +75,12 @@ clientPrimFns cEnv = PrimFns (fromList [sendPrimop, receivePrimop])receivePrimop =( unsafeToIdent "receive!", \case- [String name, Number n] -> do+ [String url, Number n] -> docase floatingOrInteger n ofLeft (_ :: Float) -> throwErrorHere . OtherError$ "receive!: expecting int argument"Right r -> do- liftIO (runClientM (since name r) cEnv) >>= \case+ liftIO (runClientM' url mgr (since r)) >>= \caseLeft err -> throwErrorHere . OtherError$ "receive!: request failed:" <> show errRight v' -> pure $ List v'@@ -106,5 +97,12 @@ identV = Keyword . unsafeToIdent-- * Client functionssubmit :: Value -> ClientM ()-since :: Text -> Int -> ClientM [Value]-submit :<|> since :<|> _ :<|> _ = client api+submit = client chainSubmitEndpoint++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 urldiff --git a/exe/Server/Server.hs b/exe/Server/Server.hsindex ecdd1d4..a651ff0 100644--- a/exe/Server/Server.hs+++ b/exe/Server/Server.hs@@ -33,7 +33,12 @@ import Options.Applicative)import Servant( (:<|>)(..)+ , (:>)+ , Capture+ , Get, Handler+ , JSON+ , PlainText, Raw, ServantErr(..), Server@@ -61,6 +66,15 @@ data Chain = Chain-- matter for a test server.newtype Chains = Chains { getChains :: MVar (Map Text Chain) }+type ServerApi+ = "chains" :> Capture "chain" Text :> (ChainSubmitEndpoint :<|> ChainSinceEndpoint)+ :<|> "outputs" :> Capture "chain" Text :> Get '[JSON, PlainText] [Maybe A.Value]+ :<|> Raw++serverApi :: Proxy ServerApi+serverApi = Proxy++-- * HelpersinsertExpr :: Connection -> Chains -> Text -> Value -> IO (Either Text ())@@ -98,20 +112,19 @@ loadState conn = dochains' <- newMVar $ Map.fromList chainPairspure $ Chains chains'+-- * Handlers-- | Submit something to a chain. The value is expected to be a pair, with the-- first item specifying the chain the value is being submitted to, and the-- second the expression being submitted.-submit :: Connection -> Chains -> Value -> Handler ()-submit conn chains val = case val of- List [String i, v] -> do- res <- liftIO $ insertExpr conn chains i v- case res of- Left err -> throwError $ err400 { errBody = fromStrict $ encodeUtf8 err }- Right _ -> pure ()- _ -> throwError- $ err400 { errBody = "Expecting pair with chain name and val" }+submit :: Connection -> Chains -> Text -> Value -> Handler ()+submit conn chains name val = do+ res <- liftIO $ insertExpr conn chains name val+ case res of+ Left err -> throwError $ err400 { errBody = fromStrict $ encodeUtf8 err }+ Right _ -> pure ()+-- | Get all expressions submitted to a chain since 'index'.since :: Connection -> Text -> Int -> Handler [Value]@@ -190,7 +203,7 @@ main = doconn <- connect $ connectionInfo opts'st <- loadState connlet gzipSettings = def { gzipFiles = GzipPreCompressed GzipIgnore }- app = simpleCors $ gzip gzipSettings (serve api (server conn st))+ app = simpleCors $ gzip gzipSettings (serve serverApi (server conn st))run (serverPort opts') appwhereallOpts = info (opts <**> helper)@@ -199,7 +212,7 @@ main = do<> header "radicle-server")---server :: Connection -> Chains -> Server API-server conn st = submit conn st :<|> since conn :<|> jsonOutputs st :<|> static+server :: Connection -> Chains -> Server ServerApi+server conn chains = chainEndpoints :<|> jsonOutputs chains :<|> static+ where+ chainEndpoints chainName = submit conn chains chainName :<|> since conn chainNamediff --git a/rad/chain.rad b/rad/chain.radindex 580f94f..cf3e7f6 100644--- a/rad/chain.rad+++ b/rad/chain.rad@@ -5,32 +5,39 @@;; == base-eval');; - A sequence of inputs.-(def empty-chain- {:state (pure-env)- :inputs (list)- :index 0})+(def new-chain+ (fn [url]+ {:state (pure-env)+ :inputs (list)+ :url url+ :index 0}))++(document 'new-chain+ '(("url" string))+ "Return an empty chain dictionary with the given url.")-(def test-chain- {:state (pure-env)- :inputs (list)- :name "test"- :index 0});; eval-in-chain(def eval-in-chain(fn [expr chain](def x (eval expr (lookup :state chain)))- (dict :chain (dict :state (head (tail x))- :input (cons expr (lookup :input chain))- :index (+ 1 (lookup :index chain)))- :result (head x))))+ (def result (nth 0 x))+ (def new-state (nth 1 x))+ (def new-chain+ (insert :state new-state+ (over (@ :input) (fn [input] (cons expr input))+ (over (@ :index) (fn [index] (+ 1 index))+ chain ))))+ {:chain new-chain+ :result result }))(document 'eval-in-chain'(("expr" any) ("chain" chain))"Evaluates 'expr' in the 'chain' and returns a dict with the ':result' and the resulting ':chain'.")((fn []+ (def empty-chain (new-chain ""))(def res (eval-in-chain '(+ 3 2) empty-chain))(def ~~> (fn [comp expected] (should-be "eval-in-chain" (view comp res) expected)))(~~> (@ :result) 5)@@ -42,7 +49,7 @@(def update-chain(fn [chain](def new-inputs- (receive! (lookup :name chain) (lookup :index chain)))+ (receive! (lookup :url chain) (lookup :index chain)))(def upd-ch(fn [ch expr](def x (eval-in-chain expr ch))@@ -53,6 +60,14 @@'(("chain" chain))"Return a new chain updated with the new expressions from the remote chain")+(def load-chain+ (fn [url]+ (update-chain (new-chain url))))++(document 'load-chain+ '(("url" string))+ "Fetch the inputs of a remote chain and return a chain dictionary with the chain state.")+;; add-quit(def add-quit@@ -94,40 +109,31 @@'(("eval-fn" fn))"Add a :send special form that sends the contents of _input to the chain _cur-chain")-;; enter-chain & enter-remote-chain+;; enter-remote-chain+(def enter-remote-chain+ (fn [url]+ (def chain (load-chain url))+ (def chain-state (lookup :state chain))+ (def mod-state1+ (over (@ :env) (fn [x] (insert '_inputs [] x)) chain-state))+ (def mod-state2+ (over (@ :env)+ (fn [x] (insert '_cur-chain (lookup :url chain) x))+ mod-state1))+ (def mod-state3+ (over (.. (@ :env) (@ 'eval))+ (fn [x] (add-send (add-quit (get-current-env) x)))+ mod-state2))+ (list :ok mod-state3)))(def eval__ eval)-(def-rec eval+(def eval(fn [expr env]- ;; The horror, the horror(if (list? expr)- (if (> (length expr) 0)- (cond- (eq? (head expr) :enter-chain) (do- (def arg_ (nth 1 expr))- (def arg (head (eval arg_ env)))- (def mod-state- (over (.. (@ :env) (@ 'eval))- (fn [x] (add-quit env x))- (lookup :state arg)))- (list :ok mod-state))- (eq? (head expr) :enter-remote-chain) (do- (def arg_ (nth 1 expr))- (def arg (head (eval arg_ env)))- (def state (lookup :state arg))- (def mod-state1- (over (@ :env) (fn [x] (insert '_inputs [] x)) state))- (def mod-state2- (over (@ :env)- (fn [x] (insert '_cur-chain (lookup :name arg) x))- mod-state1))- (def mod-state3- (over (.. (@ :env) (@ 'eval))- (fn [x] (add-send (add-quit (get-current-env) x)))- mod-state2))- (list :ok mod-state3))- :else (eval__ expr env))- (eval__ expr env))+ (cond+ (eq? (head expr) :enter-chain)+ (enter-remote-chain (head (eval__ (nth 1 expr) env)))+ :else (eval__ expr env))(eval__ expr env))))(def eval-fn-appdiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 53c5ed0..23cd9ae 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -649,24 +649,6 @@ test_repl =](_, result) <- runInRepl inputresult @==> output-- , testCase "'enter-chain' changes environment" $ do- let input = [ "(def x 0)"- , "(:enter-chain empty-chain)"- , "(def x 1)"- , "x"- , ":quit"- , "x"- ]- output = [ "()"- , ":ok"- , "()"- , "1.0"- , ":ok"- , "0.0"- ]- (_, result) <- runInRepl input- result @==> output]where-- In addition to the output of the lines tested, 'should-be's get