Skip to content

A peer-to-peer stack for code collaboration

Add content type for easy-to-consume JSON (#586)

James Haydonf827003987fe
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 1e464dd..46b461b 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -447,10 +447,11 @@ right now, formatted according to ISO 8601.
Returns a JSON formatted string representing the input value. Numbers
are only converted if they have a finite decimal expansion. Strings and
-booleans are converted to their JSON counterparts. Keywords are
-converted to JSON strings (dropping the initial ':'). Lists and vectors
-are converted to JSON arrays. Dicts are converted to JSON objects as
-long as all the keys are either strings or keywords.
+booleans are converted to their JSON counterparts. Atoms and keywords
+are converted to JSON strings (dropping the initial ':' for keywords).
+Lists and vectors are converted to JSON arrays. Dicts are converted to
+JSON objects as long as all the keys are strings, atoms, keywords,
+booleans or numbers.
``uuid!``
~~~~~~~~~
diff --git a/package.yaml b/package.yaml
index 4cc589d..9406728 100644
--- a/package.yaml
+++ b/package.yaml
@@ -74,6 +74,7 @@ library:
- unliftio
- unordered-containers
- uuid
+ - vector
tests:
spec:
diff --git a/src/Radicle/Daemon/HttpApi.hs b/src/Radicle/Daemon/HttpApi.hs
index 8eeae68..643eb65 100644
--- a/src/Radicle/Daemon/HttpApi.hs
+++ b/src/Radicle/Daemon/HttpApi.hs
@@ -1,11 +1,18 @@
{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+{-# LANGUAGE QuantifiedConstraints #-}
+
module Radicle.Daemon.HttpApi
- ( QueryRequest(..)
- , QueryResponse(..)
+ ( QueryRequestF(..)
+ , QueryRequest
+ , QueryResponseF(..)
+ , QueryResponse
, machineQueryEndpoint
- , SendRequest(..)
- , SendResponse(..)
+ , SendRequestF(..)
+ , SendRequest
+ , SendResponseF(..)
+ , SendResponse
, machineSendEndpoint
, NewResponse(..)
@@ -21,8 +28,8 @@ module Radicle.Daemon.HttpApi
import Protolude
-import Data.Aeson ((.:), (.=))
import qualified Data.Aeson as A
+import qualified Data.Aeson.Types as A
import Data.Swagger
import Data.Version (showVersion)
import qualified Network.HTTP.Media as HttpMedia
@@ -33,9 +40,11 @@ import Servant.Swagger
import qualified Paths_radicle as Radicle
import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
+import Radicle.Internal.Json
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
+-- | Content type for values encoded as Radicle expression.
data RadicleData
instance Accept RadicleData where
@@ -47,6 +56,30 @@ instance ToRad Ann.WithPos a => MimeRender RadicleData a where
instance FromRad Ann.WithPos a => MimeUnrender RadicleData a where
mimeUnrender _ = first toS . (fromRad <=< parse "[daemon]") . toS
+-- | Content type for values encoded *loosely* as JSON. This encoding is meant
+-- to be convenient (for consuming in the browser) but lossy (since JSON has
+-- less value types and JSON objects can only have strings as keys). In
+-- particular, when dict keys are keywords, booleans or numbers, they are
+-- converted to strings.
+data RadicleJSON
+
+instance Accept RadicleJSON where
+ contentType _ = "application" HttpMedia.// "radicle-json"
+
+instance (Traversable t, A.ToJSON (t A.Value)) => MimeRender RadicleJSON (t Value) where
+ mimeRender _ x = case traverse maybeJson x of
+ Right y -> A.encode y
+ Left e -> A.encode $ A.object [("error", A.String ("Radicle value did not have a JSON representation: " <> e))]
+
+instance (Functor t, A.FromJSON (t A.Value)) => MimeUnrender RadicleJSON (t Value) where
+ mimeUnrender _ = fmap (fmap fromJson) . A.eitherDecode . toS
+
+instance (Traversable t, A.ToJSON (t A.Value)) => MimeRender JSON (t Value) where
+ mimeRender _ = A.encode . fmap valueToJson
+
+instance {-# OVERLAPPING #-} (Traversable t, A.FromJSON (t A.Value)) => MimeUnrender JSON (t Value) where
+ mimeUnrender _ = A.parseEither (traverse jsonToValue) <=< A.eitherDecode . toS
+
instance FromHttpApiData MachineId where
parseUrlPiece = Right . MachineId . toS
parseQueryParam = parseUrlPiece
@@ -54,67 +87,39 @@ instance FromHttpApiData MachineId where
instance ToHttpApiData MachineId where
toUrlPiece (MachineId id) = id
-newtype QueryRequest = QueryRequest { expression :: Value }
- deriving (Generic)
+newtype QueryRequestF a = QueryRequest { expression :: a }
+ deriving (Functor, Foldable, Traversable, Generic, A.ToJSON, A.FromJSON)
+
+type QueryRequest = QueryRequestF Value
instance FromRad Ann.WithPos QueryRequest
instance ToRad Ann.WithPos QueryRequest
-instance A.ToJSON QueryRequest where
- toJSON QueryRequest{..} = A.object
- [ "expression" .= valueToJson expression
- ]
-instance A.FromJSON QueryRequest where
- parseJSON = A.withObject "QueryRequest" $ \o -> do
- expression <- o .: "expression" >>= jsonToValue
- pure $ QueryRequest {..}
+newtype QueryResponseF v = QueryResponse { result :: v }
+ deriving (Functor, Foldable, Traversable, Generic, A.ToJSON, A.FromJSON)
-newtype QueryResponse = QueryResponse { result :: Value }
- deriving (Generic)
+type QueryResponse = QueryResponseF Value
instance FromRad Ann.WithPos QueryResponse
instance ToRad Ann.WithPos QueryResponse
-instance A.ToJSON QueryResponse where
- toJSON QueryResponse{..} = A.object
- [ "result" .= valueToJson result
- ]
-instance A.FromJSON QueryResponse where
- parseJSON = A.withObject "QueryResponse" $ \o -> do
- result <- o .: "result" >>= jsonToValue
- pure $ QueryResponse {..}
+newtype SendRequestF v = SendRequest { expressions :: [v] }
+ deriving (Functor, Foldable, Traversable, Generic, A.ToJSON, A.FromJSON)
-newtype SendRequest = SendRequest { expressions :: [Value] }
- deriving (Generic)
+type SendRequest = SendRequestF Value
instance FromRad Ann.WithPos SendRequest
instance ToRad Ann.WithPos SendRequest
-instance A.FromJSON SendRequest where
- parseJSON = A.withObject "SendRequest" $ \o -> do
- expressions <- o .: "expressions" >>= traverse jsonToValue
- pure $ SendRequest {..}
-instance A.ToJSON SendRequest where
- toJSON SendRequest{..} = A.object
- [ "expressions" .= map valueToJson expressions
- ]
-
-newtype SendResponse = SendResponse
- { results :: [Value]
- } deriving (Generic)
+newtype SendResponseF v = SendResponse
+ { results :: [v]
+ } deriving (Functor, Foldable, Traversable, Generic, A.ToJSON, A.FromJSON)
+
+type SendResponse = SendResponseF Value
instance FromRad Ann.WithPos SendResponse
instance ToRad Ann.WithPos SendResponse
-instance A.FromJSON SendResponse where
- parseJSON = A.withObject "SendResponse" $ \o -> do
- results <- o .: "results" >>= traverse jsonToValue
- pure $ SendResponse {..}
-instance A.ToJSON SendResponse where
- toJSON SendResponse{..} = A.object
- [ "results" .= map valueToJson results
- ]
-
newtype NewResponse = NewResponse
{ machineId :: MachineId
} deriving (Generic)
@@ -130,7 +135,7 @@ instance A.FromJSON NewResponse
-- * APIs
-type Formats = '[JSON, RadicleData]
+type Formats = '[RadicleData, JSON, RadicleJSON]
type MachinesEndpoint t = "v0" :> "machines" :> t
type MachineEndpoint t = MachinesEndpoint (Capture "machineId" MachineId :> t)
@@ -143,7 +148,7 @@ type MachineSendEndpoint = MachineEndpoint ("send" :> ReqBody Formats SendReques
machineSendEndpoint :: Proxy MachineSendEndpoint
machineSendEndpoint = Proxy
-type NewMachineEndpoint = MachinesEndpoint ("new" :> Post Formats NewResponse)
+type NewMachineEndpoint = MachinesEndpoint ("new" :> Post '[JSON, RadicleData] NewResponse)
newMachineEndpoint :: Proxy NewMachineEndpoint
newMachineEndpoint = Proxy
diff --git a/src/Radicle/Daemon/Ipfs.hs b/src/Radicle/Daemon/Ipfs.hs
index fa87ba9..7696674 100644
--- a/src/Radicle/Daemon/Ipfs.hs
+++ b/src/Radicle/Daemon/Ipfs.hs
@@ -34,20 +34,12 @@ import System.Timeout
import UnliftIO.Async
import Radicle.Internal.Core
+import Radicle.Internal.Json
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import qualified Radicle.Internal.UUID as UUID
import qualified Radicle.Ipfs as Ipfs
-jsonToValue :: Aeson.Value -> Aeson.Parser Value
-jsonToValue = Aeson.withText "Value" $ \t -> do
- case parse "[daemon]" t of
- Left err -> fail $ "failed to parse Radicle expression: " <> show err
- Right v -> pure v
-
-valueToJson :: Value -> Aeson.Value
-valueToJson = Aeson.String . renderCompactPretty
-
-- * Types
diff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hs
index be28039..e27d98c 100644
--- a/src/Radicle/Internal.hs
+++ b/src/Radicle/Internal.hs
@@ -12,6 +12,7 @@ import Radicle.Internal.Effects as X
import Radicle.Internal.Eval as X
import Radicle.Internal.Identifier as X
import Radicle.Internal.Interpret as X
+import Radicle.Internal.Json as X
import Radicle.Internal.Parse as X
import Radicle.Internal.Pretty as X
import Radicle.Internal.PrimFns as X
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 85eb4d3..488ebe8 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -11,10 +11,7 @@ import Codec.Serialise (Serialise)
import Control.Monad.Except
(ExceptT(..), MonadError, runExceptT, throwError)
import Control.Monad.State hiding (State)
-import Data.Aeson (ToJSON(..))
-import qualified Data.Aeson as A
import Data.Copointed (Copointed(..))
-import qualified Data.HashMap.Strict as HashMap
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.Scientific (Scientific)
@@ -98,7 +95,7 @@ noStack (Left (LangError _ err)) = Left err
noStack (Right v) = Right v
typeToValue :: Type.Type -> Value
-typeToValue = Keyword . Ident . Identifier.kebabCons . drop 1 . show
+typeToValue = Keyword . Ident . Identifier.kebabCons . Type.typeString
-- | Convert an error to a radicle value, and the label for it. Used for
-- catching exceptions.
@@ -412,42 +409,6 @@ isAtom :: Value -> Maybe Ident
isAtom (Atom i) = pure i
isAtom _ = Nothing
--- | Convert a radicle `Value` into an 'aeson' value, if possible.
---
--- >>> import Data.Aeson (encode)
--- >>> encode $ maybeJson $ List [Number 3, String "hi"]
--- "[3,\"hi\"]"
---
--- >>> import Data.Aeson (encode)
--- >>> encode $ maybeJson $ Dict $ Map.fromList [(String "foo", String "bar")]
--- "{\"foo\":\"bar\"}"
---
--- This fails for lambdas, since lambdas capture an entire environment (possibly
--- recursively). It also fails for dictionaries with non-stringy (string or
--- keyword) keys.
---
--- >>> import Data.Aeson (encode)
--- >>> encode $ maybeJson $ Dict $ Map.fromList [(Number 3, String "bar")]
--- "null"
-maybeJson :: Value -> Maybe A.Value
-maybeJson = \case
- Number n -> A.Number <$> hush (Num.isSci n)
- String s -> pure $ A.String s
- Keyword (Ident i) -> pure $ A.String i
- Boolean b -> pure $ A.Bool b
- List ls -> toJSON <$> traverse maybeJson ls
- Vec xs -> toJSON <$> traverse maybeJson (toList xs)
- Dict m -> do
- let kvs = Map.toList m
- ks <- traverse isStringy (fst <$> kvs)
- vs <- traverse maybeJson (snd <$> kvs)
- pure $ A.Object (HashMap.fromList (zip ks vs))
- _ -> Nothing
- where
- isStringy (String s) = pure s
- isStringy (Keyword (Ident i)) = pure i
- isStringy _ = Nothing
-
-- | The environment, which keeps all known bindings.
newtype Env s = Env { fromEnv :: Map Ident (Doc.Docd s) }
deriving (Eq, Ord, Semigroup, Monoid, Show, Read, Generic, Functor, Foldable, Traversable, Serialise)
diff --git a/src/Radicle/Internal/Json.hs b/src/Radicle/Internal/Json.hs
new file mode 100644
index 0000000..42520e0
--- /dev/null
+++ b/src/Radicle/Internal/Json.hs
@@ -0,0 +1,100 @@
+module Radicle.Internal.Json where
+
+import Protolude
+
+import Control.Monad.Fail
+import qualified Data.Aeson as A
+import qualified Data.Aeson.Types as A
+import qualified Data.HashMap.Strict as HashMap
+import qualified Data.Map.Strict as Map
+import qualified Data.Scientific as Sci
+import qualified Data.Sequence as Seq
+import qualified Data.Vector as JsonVector
+
+import Radicle.Internal.Core
+import Radicle.Internal.Identifier
+import Radicle.Internal.Number
+import Radicle.Internal.Parse
+import Radicle.Internal.Pretty
+import qualified Radicle.Internal.Type as Type
+
+-- | Parses JSON into a Value. It expects the value to be encoded as a radicle
+-- expression in a JSON string. Corresponds to the encoding given by
+-- 'valueToJson'.
+--
+-- >>> import qualified Data.Vector as Vector
+-- >>> renderCompactPretty <$> A.parseMaybe jsonToValue (A.String "{:foo 42}")
+-- Just "{:foo 42}"
+jsonToValue :: A.Value -> A.Parser Value
+jsonToValue = A.withText "Value" $ \t -> do
+ case parse "[daemon]" t of
+ Left err -> fail $ "failed to parse Radicle expression: " <> show err
+ Right v -> pure v
+
+-- | Pretty-prints a Radicle value, and wraps it in a JSON string.
+--
+-- >>> import Data.Aeson (encode)
+-- >>> import Data.Sequence (fromList)
+-- >>> encode $ valueToJson (Vec (fromList [Number 1, String "foo"]))
+-- "\"[1\\n\\\"foo\\\"]\""
+valueToJson :: Value -> A.Value
+valueToJson = A.String . renderCompactPretty
+
+-- | Convert a radicle `Value` into an 'aeson' value, if possible.
+--
+-- >>> import Data.Aeson (encode)
+-- >>> encode $ maybeJson $ List [Number 3, String "hi"]
+-- "{\"Right\":[3,\"hi\"]}"
+--
+-- >>> import Data.Aeson (encode)
+-- >>> encode $ maybeJson $ Dict $ Map.fromList [(String "foo", String "bar")]
+-- "{\"Right\":{\"foo\":\"bar\"}}"
+--
+-- This fails for lambdas, since lambdas capture an entire environment (possibly
+-- recursively). It will convert dicts as long as it can stringify all the keys,
+-- that is, if they are strings, keywords, atoms, numbers of booleans.
+--
+-- >>> import Data.Aeson (encode)
+-- >>> encode $ maybeJson $ Dict $ Map.fromList [(Number 3, String "bar")]
+-- "{\"Right\":{\"3\":\"bar\"}}"
+--
+-- >>> import Data.Aeson (encode)
+-- >>> encode $ maybeJson $ Dict $ Map.fromList [(List [Number 3], String "bar")]
+-- "{\"Left\":\"Cannot convert values of type List to a JSON key\"}"
+maybeJson :: Value -> Either Text A.Value
+maybeJson = \case
+ Number n -> A.Number <$> isSci n
+ String s -> pure $ A.String s
+ Keyword (Ident i) -> pure $ A.String i
+ Atom (Ident i) -> pure $ A.String i
+ Boolean b -> pure $ A.Bool b
+ List ls -> A.toJSON <$> traverse maybeJson ls
+ Vec xs -> A.toJSON <$> traverse maybeJson (toList xs)
+ Dict m -> do
+ let kvs = Map.toList m
+ ks <- traverse jsonKey (fst <$> kvs)
+ vs <- traverse maybeJson (snd <$> kvs)
+ pure $ A.Object (HashMap.fromList (zip ks vs))
+ v -> Left $ cantConvertType v "JSON"
+ where
+ jsonKey (String s) = pure s
+ jsonKey (Keyword (Ident i)) = pure i
+ jsonKey (Atom (Ident i)) = pure i
+ jsonKey n@(Number _) = pure (renderCompactPretty n)
+ jsonKey (Boolean b) = pure $ if b then "true" else "false"
+ jsonKey v = Left $ cantConvertType v "a JSON key"
+
+ cantConvertType v toThis = "Cannot convert values of type " <> toS (Type.typeString (valType v)) <> " to " <> toThis
+
+
+-- | Converts an `aeson` value to a radicle one.
+fromJson :: A.Value -> Value
+fromJson = \case
+ -- Note that using `toRational` would make this function unsafe when reading
+ -- user input.
+ A.Number n -> Number (toRational (Sci.toRealFloat n :: Double))
+ A.String s -> String s
+ A.Bool b -> Boolean b
+ A.Array xs -> Vec $ Seq.fromList (JsonVector.toList (fromJson <$> xs))
+ A.Object kvs -> Dict $ Map.fromList $ bimap String fromJson <$> HashMap.toList kvs
+ A.Null -> Keyword (Ident "nothing")
diff --git a/src/Radicle/Internal/Number.hs b/src/Radicle/Internal/Number.hs
index d8fb5c4..75846d2 100644
--- a/src/Radicle/Internal/Number.hs
+++ b/src/Radicle/Internal/Number.hs
@@ -27,4 +27,4 @@ toBoundedInteger r =
isSci :: Rational -> Either Text Scientific.Scientific
isSci r = case Scientific.fromRationalRepetendUnlimited r of
(s, Nothing) -> pure s
- _ -> Left "Does not have a non-repeating decimal expansion"
+ _ -> Left $ "The rational number " <> show r <> " does not have a non-repeating decimal expansion"
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 35d34b1..4249565 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -20,6 +20,7 @@ import Radicle.Internal.Crypto
import qualified Radicle.Internal.Doc as Doc
import Radicle.Internal.Eval
import Radicle.Internal.Identifier (Ident(..), unsafeToIdent)
+import qualified Radicle.Internal.Json as Json
import qualified Radicle.Internal.Number as Num
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
@@ -567,12 +568,14 @@ purePrimFns = fromList $ allDocs $
, ( "to-json"
, "Returns a JSON formatted string representing the input value. Numbers are only\
\ converted if they have a finite decimal expansion. Strings and booleans are\
- \ converted to their JSON counterparts. Keywords are converted to JSON strings\
- \ (dropping the initial ':'). Lists and vectors are converted to JSON arrays.\
- \ Dicts are converted to JSON objects as long as all the keys are either\
- \ strings or keywords."
+ \ converted to their JSON counterparts. Atoms and keywords are converted to JSON strings\
+ \ (dropping the initial ':' for keywords). Lists and vectors are converted to JSON arrays.\
+ \ Dicts are converted to JSON objects as long as all the keys are strings, atoms,\
+ \ keywords, booleans or numbers."
, oneArg "to-json" $ \v -> String . toS . Aeson.encode <$>
- maybeJson v ?? toLangError (OtherError "Could not serialise value to JSON")
+ case Json.maybeJson v of
+ Left e -> throwErrorHere $ OtherError $ "Could not convert to JSON: " <> e
+ Right js -> pure js
)
, ( "default-ecc-curve"
, "Returns the default elliptic-curve used for generating cryptographic keys."
diff --git a/src/Radicle/Internal/Type.hs b/src/Radicle/Internal/Type.hs
index 1f16bc9..426350d 100644
--- a/src/Radicle/Internal/Type.hs
+++ b/src/Radicle/Internal/Type.hs
@@ -1,5 +1,6 @@
module Radicle.Internal.Type where
+import Prelude (String)
import Protolude hiding (Type)
import Codec.Serialise (Serialise)
@@ -24,3 +25,6 @@ data Type
deriving (Eq, Show, Read, Generic)
instance Serialise Type
+
+typeString :: Type -> String
+typeString = drop 1 . show
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index 92d7657..d72169c 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -479,7 +479,9 @@ test_eval =
runPureCode "(to-json {:foo #t \"bar\" #f})" @?= Right (String "{\"foo\":true,\"bar\":false}")
runPureCode "(to-json (dict \"key\" (list 1 \"value\")))" @?= Right (String "{\"key\":[1,\"value\"]}")
runPureCode "(to-json [3/2 #f])" @?= Right (String "[1.5,false]")
- noStack (runPureCode "(to-json (dict 1 2))") @?= Left (OtherError "Could not serialise value to JSON")
+ runPureCode "(to-json {1 2})" @?= Right (String "{\"1\":2}")
+ runPureCode "(to-json {#t #f})" @?= Right (String "{\"true\":false}")
+ noStack (runPureCode "(to-json {[1] 2})") @?= Left (OtherError "Could not convert to JSON: Cannot convert values of type Vec to a JSON key")
, testCase "def-rec can define recursive functions" $ do
let prog = [s|