Skip to content

A peer-to-peer stack for code collaboration

Generalization of the storage interface

Thomas Scholtesdf0f399071b6
diff --git a/cloudbuild.yaml b/cloudbuild.yaml
index 435956e..0abcc3b 100644
--- a/cloudbuild.yaml
+++ b/cloudbuild.yaml
@@ -143,7 +143,8 @@ steps:
- "-c"
- |
set -euxo pipefail
- stack exec radicle - <<<'(load! "rad/examples/counter.rad") (counter/run-test)'
+ stack exec -- radicle - <<<'(load! "rad/examples/counter.rad") (counter/run-test)'
+ stack exec -- radicle test/server.rad radicle-server
- id: "Save cache"
waitFor:
diff --git a/exe/Server.hs b/exe/Server.hs
index 5c90cab..31f3488 100644
--- a/exe/Server.hs
+++ b/exe/Server.hs
@@ -77,7 +77,9 @@ serverApi = Proxy
-- * Helpers
-insertExpr :: Connection -> Chains -> Text -> [Value] -> IO (Either Text ())
+-- | Returns the ID of the last inserted expression which is the chain
+-- length minus one.
+insertExpr :: Connection -> Chains -> Text -> [Value] -> IO (Either Text Int)
insertExpr conn chains name vals = modifyMVar (getChains chains) $ \c -> do
let maybeChain = Map.lookup name c
chain <- case maybeChain of
@@ -98,7 +100,7 @@ insertExpr conn chains name vals = modifyMVar (getChains chains) $ \c -> do
let chain' = chain { chainState = newSt
, chainEvalPairs = chainEvalPairs chain Seq.>< news
}
- pure (Map.insert name chain' c, Right ())
+ pure (Map.insert name chain' c, Right $ Seq.length (chainEvalPairs chain') - 1)
-- | Load the state from the DB, returning an MVar with resulting state
@@ -136,7 +138,7 @@ submit conn chains name (Values vals) = do
res <- liftIO $ insertExpr conn chains name vals
case res of
Left err -> throwError $ err400 { errBody = fromStrict $ encodeUtf8 err }
- Right _ -> pure $ Keyword $ unsafeToIdent "ok"
+ Right id -> pure $ Number $ toRational id
-- | Get all expressions submitted to a chain since 'index'.
diff --git a/exe/Server/DB.hs b/exe/Server/DB.hs
index 8c43e6e..d62479b 100644
--- a/exe/Server/DB.hs
+++ b/exe/Server/DB.hs
@@ -19,8 +19,8 @@ insertExprDB conn name val
<> "VALUES ((SELECT (COALESCE(MAX(id),-1) + 1) FROM txs WHERE chain = ?), ?, ?)"
getSinceDB :: Connection -> Text -> Int -> IO [Value]
-getSinceDB conn name index
- = query conn "SELECT expr FROM txs WHERE chain = ? AND id >= ? ORDER BY id ASC" (name, index)
+getSinceDB conn name id
+ = query conn "SELECT expr FROM txs WHERE chain = ? AND id >= ? ORDER BY id ASC" (name, id)
-- | Get all txs in all chains. Useful after a server restart.
getAllDB :: Connection -> IO [(Text, [Value])]
diff --git a/rad/prelude/chain.rad b/rad/prelude/chain.rad
index fd0cdaf..19ebe21 100644
--- a/rad/prelude/chain.rad
+++ b/rad/prelude/chain.rad
@@ -24,7 +24,8 @@
(fn [url]
{:state (pure-env)
:inputs []
- :url url}))
+ :url url
+ :index :nothing}))
;; eval-in-chain
@@ -64,13 +65,16 @@
"Takes a chain, and returns a new chain updated with the new expressions from the remote chain"
(fn [chain]
(def index (length (lookup :inputs chain)))
- (def new-inputs
- (receive! (lookup :url chain) index))
+ (def receive-result
+ (receive! (lookup :url chain) (lookup :index chain)))
+ (def new-index (nth 0 receive-result))
+ (def new-inputs (nth 1 receive-result))
(def upd-ch
(fn [ch expr]
(def x (eval-in-chain expr ch))
(view (@ :chain) x)))
- (foldl upd-ch chain new-inputs)))
+ (def chain (foldl upd-ch chain new-inputs))
+ (insert :index [:just new-index] chain)))
(:test "update-chain!"
[:setup
diff --git a/src/Radicle/Internal/HttpStorage.hs b/src/Radicle/Internal/HttpStorage.hs
index 59a1c49..d6b415a 100644
--- a/src/Radicle/Internal/HttpStorage.hs
+++ b/src/Radicle/Internal/HttpStorage.hs
@@ -59,15 +59,17 @@ instance MimeUnrender PlainText Values where
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.
+-- | Endpoint to submit an expression to a chain. Responds with the
+-- index of the submitted expression. The index is an integer encoded
+-- as a Radicle value.
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.
+-- | Endpoint to obtain all entries in a chain starting from and
+-- including the given index. Responds with a Radicle vector of the
+-- expressions.
type ChainSinceEndpoint = "since" :> Capture "index" Int :> Get '[PlainText] Values
chainSinceEndpoint :: Proxy ChainSinceEndpoint
@@ -90,19 +92,39 @@ httpStoragePrimFns' mgr =
buildStoragePrimFns StorageBackend
{ storageSend =
( "send!"
- , "Given a URL (string) and a value, sends the value `v` to the remote\
- \ chain located at the URL for evaluation."
+ , "Given a URL string and a value, sends the value `v` to the remote\
+ \ chain located at the URL for evaluation. Returns the index of the\
+ \ submitted input."
, \url values -> do
res <- liftIO $ runClientM' url mgr (submit $ toList values)
- pure $ bimap formatServantError (const ()) res
+ pure $ case res of
+ Left servantError -> Left $ formatServantError servantError
+ Right val -> case fromRad val of
+ Left err -> Left $ "cannot parse server response: " <> err
+ Right n -> Right n
)
, storageReceive =
( "receive!"
- , "Given a URL (string) and a integral number `n`, queries the remote chain\
- \ for the last `n` inputs that have been evaluated."
- , \url index -> do
- res <- liftIO $ runClientM' url mgr (since index)
- pure $ first formatServantError res
+ , "Given a URL string and a `[:just n]`, where `n` is an integer, returns\
+ \ all inputs from the remote chain after index `n`. If the second argument\
+ \ is `:nothing` all inputs are returned."
+ , \url maybeIndex -> do
+ -- There is mismatch between the HTTP API and the
+ -- storage interface that we need to account for here.
+ -- 1. If we send the index `n` to the HTTP API the
+ -- response will include the input with index `n`, the
+ -- storage interface however says that it should not.
+ -- To account for this we increase the index we
+ -- receive by one.
+ -- 2. The HTTP API always exepcts an index, so we use
+ -- @-1@ if @Nothing@ is provided.
+ -- 3. Th HTTP API does not return the index of the last
+ -- input in the response. We calculate it locally
+ let index = fromMaybe (-1) maybeIndex
+ res <- liftIO $ runClientM' url mgr (since (index + 1))
+ pure $ case res of
+ Left err -> Left $ formatServantError err
+ Right values -> Right (length values + index, values)
)
}
where
diff --git a/src/Radicle/Internal/Storage.hs b/src/Radicle/Internal/Storage.hs
index 62035bb..adca797 100644
--- a/src/Radicle/Internal/Storage.hs
+++ b/src/Radicle/Internal/Storage.hs
@@ -5,6 +5,9 @@
-- A storage backend defines two functions 'StorageSend' and
-- 'StorageReceive' explained below.
--
+-- Storage backends use /indices/ to identify entries in a chain. These
+-- indices can be used like cursors in a database.
+--
-- For usage examples see "Radicle.Internal.HttpStorage" and
-- "Radicle.Internal.TestCapabilities".
module Radicle.Internal.Storage
@@ -16,9 +19,8 @@ import Protolude hiding (TypeError)
import GHC.Exts (fromList)
+import Radicle.Internal.Annotation (WithPos)
import Radicle.Internal.Core
-import Radicle.Internal.Identifier
-import qualified Radicle.Internal.Number as Num
import qualified Radicle.Internal.PrimFns as PrimFns
import Radicle.Internal.Type
@@ -27,21 +29,30 @@ import Radicle.Internal.Type
--
-- The first tuple item is the Radicle identifier the function will be
-- exposed as. The second tuple item is documentation.
-data StorageBackend m = StorageBackend
- { storageSend :: (Text, Text, StorageSend m)
- , storageReceive :: (Text, Text, StorageReceive m)
+data StorageBackend i m = StorageBackend
+ { storageSend :: (Text, Text, StorageSend i m)
+ , storageReceive :: (Text, Text, StorageReceive i m)
}
-- | Send a list of expressions to a chain identified by the first
--- argument.
-type StorageSend m = Text -> Seq Value -> m (Either Text ())
+-- argument. Returns an error or the index of the expression that was
+-- sent.
+type StorageSend i m = Text -> Seq Value -> m (Either Text i)
--- | Receive a list of expressions from a chain. The chain is identified by the first
--- argument. The second argument is the index from which to start.
--- Morally this is @'Data.List.drop' index chain@.
-type StorageReceive m = Text -> Int -> m (Either Text [Value])
+-- | Receive all expressions following the given expression and a new
+-- index for further queries.
+--
+-- If second arugment is @'Just' i@ then we return all expressions that
+-- follow the expression index by @i@ and not including that
+-- expression.
+--
+-- If the second argument is 'Nothing' we return all expressions.
+--
+-- The first item in the tuple returned is the index of the last entry
+-- in the list of expressions returned.
+type StorageReceive i m = Text -> Maybe i -> m (Either Text (i, [Value]))
-buildStoragePrimFns :: Monad m => StorageBackend m -> PrimFns m
+buildStoragePrimFns :: forall i m. (Monad m, FromRad WithPos i, ToRad WithPos i) => StorageBackend i m -> PrimFns m
buildStoragePrimFns backend =
fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]
where
@@ -54,7 +65,7 @@ buildStoragePrimFns backend =
res <- lift $ send id v
case res of
Left e -> throwErrorHere (SendError e)
- Right _ -> pure $ Keyword $ unsafeToIdent "ok"
+ Right r -> pure $ toRad r
(String _, v) -> throwErrorHere $ TypeError sendName 1 TVec v
(v, _) -> throwErrorHere $ TypeError sendName 0 TString v
)
@@ -64,16 +75,17 @@ buildStoragePrimFns backend =
( receiveName
, receiveDoc
, PrimFns.twoArg receiveName $ \case
- (String id, Number q) -> do
- case Num.isInt q of
- Left _ -> throwErrorHere . OtherError
- $ receiveName <> ": expecting int argument"
- Right n -> do
- res <- lift $ receive id n
- case res of
- Left err -> throwErrorHere . OtherError
- $ receiveName <> ": request failed: " <> err
- Right v' -> pure $ List v'
- (String _, v) -> throwErrorHere $ TypeError receiveName 1 TNumber v
+ (String id, v) -> do
+ index <- case fromRad v of
+ Right Nothing -> pure Nothing
+ Right (Just n) -> pure (Just n)
+ Left e -> throwReceiveError $ "failed to parse second argument: " <> e
+ res <- lift $ receive id index
+ case res of
+ Left err -> throwReceiveError $ "request failed: " <> err
+ Right (newIndex, values) -> pure $ Vec $ fromList [toRad newIndex, Vec $ fromList values]
(v, _) -> throwErrorHere $ TypeError receiveName 0 TString v
)
+
+ throwReceiveError :: Text -> Lang m a
+ throwReceiveError msg = throwErrorHere $ OtherError $ receiveName <> ": " <> msg
diff --git a/test/server.rad b/test/server.rad
new file mode 100644
index 0000000..0e24a31
--- /dev/null
+++ b/test/server.rad
@@ -0,0 +1,74 @@
+#!/usr/bin/env radicle
+;;
+;; Test correctness of the storage interface provided by the server.
+;;
+;; This script tests that the HTTP server implements the storage protocol with
+;; `send!` and `receive!` properly.
+;;
+;; The script accepts the hostname of the server as an optional argument. The
+;; hostname defaults to `localhost`. We always use port 8000.
+;;
+
+
+(load! "rad/prelude.rad")
+
+(import prelude/patterns '[/cons] :unqualified)
+(import prelude/test '[assert-equal] :unqualified)
+
+(def host
+ (match (get-args!)
+ (/cons 'h _) h
+ /nil "localhost"
+ ))
+
+(def create-machine
+ (fn []
+ (string-append "http://" host ":8000/chains/" (uuid!))
+ ))
+
+(def exprs-1 [ :e1 :e2 ])
+(def exprs-2 [ :f1 :f2 :f3 ])
+
+(def test/receive-all
+ "Passing `:nothing` to `receive!` returns all expressions"
+ (fn []
+ (def machine-id (create-machine))
+ (send! machine-id exprs-1)
+ (send! machine-id exprs-2)
+ (def all-exprs (<> exprs-1 exprs-2))
+ (match (receive! machine-id :nothing)
+ [_ 'received-exprs] (assert-equal received-exprs all-exprs))
+ ))
+
+(def test/receive-last-index
+ (fn []
+ "Passing the last index from `send!` to `receive!` returns no expressions"
+ (def machine-id (create-machine))
+ (def index (send! machine-id exprs-1))
+ (match (receive! machine-id [:just index])
+ [_ 'received-exprs] (assert-equal received-exprs []))
+ ))
+
+(def test/receive-with-index
+ (fn []
+ "Passing an index from `send!` to `receive!` returns no expressions"
+ (def machine-id (create-machine))
+ (def index (send! machine-id exprs-1))
+ (send! machine-id exprs-2)
+ (match (receive! machine-id [:just index])
+ [_ 'received-exprs] (assert-equal received-exprs exprs-2))
+ ))
+
+(def test/receive-returns-sent-index
+ "`receive!` returns the last sent index"
+ (fn []
+ (def machine-id (create-machine))
+ (def index-send (send! machine-id exprs-1))
+ (match (receive! machine-id :nothing)
+ ['index-receive _] (assert-equal index-receive index-send))
+ ))
+
+(test/receive-all)
+(test/receive-last-index)
+(test/receive-with-index)
+(test/receive-returns-sent-index)
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index d03e1e1..77176f3 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -127,20 +127,22 @@ storagePrimFns =
( "send!"
, "Mocked version of `send!` that stores sent values in a map with chains as keys."
, \id values -> do
+ chains <- gets worldStateRemoteChains
+ let exprs = Map.findWithDefault mempty id chains
+ let newExprs = exprs Seq.>< values
modify $ \s ->
- s { worldStateRemoteChains
- = Map.insertWith (flip (Seq.><)) id values $ worldStateRemoteChains s }
- pure $ Right ()
+ s { worldStateRemoteChains = Map.insert id newExprs $ worldStateRemoteChains s }
+ pure $ Right $ Seq.length newExprs
)
, storageReceive =
( "receive!"
, "Mocked version of `receive!` that retrieves values from a map with chains as keys."
- , \id index -> do
+ , \id maybeIndex -> do
chains <- gets worldStateRemoteChains
- let exprs = case Map.lookup id chains of
- Nothing -> []
- Just res -> toList $ Seq.drop index res
- pure $ Right exprs
+ let exprs = Map.findWithDefault mempty id chains
+ let index = fromMaybe 0 maybeIndex
+ let newIndex = Seq.length exprs
+ pure $ Right $ (newIndex, toList $ Seq.drop index exprs)
)
}