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.rstindex 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. Numbersare 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.yamlindex 4cc589d..9406728 100644--- a/package.yaml+++ b/package.yaml@@ -74,6 +74,7 @@ library:- unliftio- unordered-containers- uuid+ - vectortests:spec:diff --git a/src/Radicle/Daemon/HttpApi.hs b/src/Radicle/Daemon/HttpApi.hsindex 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.HttpApiimport Protolude-import Data.Aeson ((.:), (.=))import qualified Data.Aeson as A+import qualified Data.Aeson.Types as Aimport Data.Swaggerimport Data.Version (showVersion)import qualified Network.HTTP.Media as HttpMedia@@ -33,9 +40,11 @@ import Servant.Swaggerimport qualified Paths_radicle as Radicleimport qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Core+import Radicle.Internal.Jsonimport Radicle.Internal.Parseimport Radicle.Internal.Pretty+-- | Content type for values encoded as Radicle expression.data RadicleDatainstance Accept RadicleData where@@ -47,6 +56,30 @@ instance ToRad Ann.WithPos a => MimeRender RadicleData a whereinstance FromRad Ann.WithPos a => MimeUnrender RadicleData a wheremimeUnrender _ = 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 whereparseUrlPiece = Right . MachineId . toSparseQueryParam = parseUrlPiece@@ -54,67 +87,39 @@ instance FromHttpApiData MachineId whereinstance ToHttpApiData MachineId wheretoUrlPiece (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 Valueinstance FromRad Ann.WithPos QueryRequestinstance 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 Valueinstance FromRad Ann.WithPos QueryResponseinstance 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 Valueinstance FromRad Ann.WithPos SendRequestinstance 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 Valueinstance FromRad Ann.WithPos SendResponseinstance 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" :> ttype MachineEndpoint t = MachinesEndpoint (Capture "machineId" MachineId :> t)@@ -143,7 +148,7 @@ type MachineSendEndpoint = MachineEndpoint ("send" :> ReqBody Formats SendRequesmachineSendEndpoint :: Proxy MachineSendEndpointmachineSendEndpoint = Proxy-type NewMachineEndpoint = MachinesEndpoint ("new" :> Post Formats NewResponse)+type NewMachineEndpoint = MachinesEndpoint ("new" :> Post '[JSON, RadicleData] NewResponse)newMachineEndpoint :: Proxy NewMachineEndpointnewMachineEndpoint = Proxydiff --git a/src/Radicle/Daemon/Ipfs.hs b/src/Radicle/Daemon/Ipfs.hsindex fa87ba9..7696674 100644--- a/src/Radicle/Daemon/Ipfs.hs+++ b/src/Radicle/Daemon/Ipfs.hs@@ -34,20 +34,12 @@ import System.Timeoutimport UnliftIO.Asyncimport Radicle.Internal.Core+import Radicle.Internal.Jsonimport Radicle.Internal.Parseimport Radicle.Internal.Prettyimport qualified Radicle.Internal.UUID as UUIDimport 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--- * Typesdiff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex be28039..e27d98c 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -12,6 +12,7 @@ import Radicle.Internal.Effects as Ximport Radicle.Internal.Eval as Ximport Radicle.Internal.Identifier as Ximport Radicle.Internal.Interpret as X+import Radicle.Internal.Json as Ximport Radicle.Internal.Parse as Ximport Radicle.Internal.Pretty as Ximport Radicle.Internal.PrimFns as Xdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 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 Aimport Data.Copointed (Copointed(..))-import qualified Data.HashMap.Strict as HashMapimport qualified Data.IntMap as IntMapimport qualified Data.Map as Mapimport Data.Scientific (Scientific)@@ -98,7 +95,7 @@ noStack (Left (LangError _ err)) = Left errnoStack (Right v) = Right vtypeToValue :: 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 IdentisAtom (Atom i) = pure iisAtom _ = 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.hsnew file mode 100644index 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.hsindex 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.ScientificisSci 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.hsindex 35d34b1..4249565 100644--- a/src/Radicle/Internal/PrimFns.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -20,6 +20,7 @@ import Radicle.Internal.Cryptoimport qualified Radicle.Internal.Doc as Docimport Radicle.Internal.Evalimport Radicle.Internal.Identifier (Ident(..), unsafeToIdent)+import qualified Radicle.Internal.Json as Jsonimport qualified Radicle.Internal.Number as Numimport Radicle.Internal.Parseimport 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.hsindex 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 Typederiving (Eq, Show, Read, Generic)instance Serialise Type++typeString :: Type -> String+typeString = drop 1 . showdiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 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" $ dolet prog = [s|