Skip to content

A peer-to-peer stack for code collaboration

feat: Machines define their frontend (#630)

Julian Arnib0b86b59d19d
diff --git a/docs/source/daemon-api.yaml b/docs/source/daemon-api.yaml
index ebcdacb..34b472c 100644
--- a/docs/source/daemon-api.yaml
+++ b/docs/source/daemon-api.yaml
@@ -42,6 +42,8 @@ definitions:
properties:
expression:
$ref: '#/definitions/RadicleValue'
+ HtmlText:
+ type: string
MachineId:
type: string
description: The ID (i.e. IPNS name) of an IPFS machine.
@@ -74,6 +76,26 @@ paths:
produces:
- application/json;charset=utf-8
- application/radicle
+ /v0/machines/{machineId}/frontend/{path}:
+ get:
+ responses:
+ '404':
+ description: '`machineId` or `path` not found'
+ '200':
+ schema:
+ $ref: '#/definitions/HtmlText'
+ description: ''
+ produces:
+ - text/html;charset=utf-8
+ parameters:
+ - required: true
+ in: path
+ name: machineId
+ type: string
+ - required: true
+ in: path
+ name: path
+ type: string
/v0/machines/{machineId}/query:
post:
consumes:
diff --git a/examples/frontend/index.html b/examples/frontend/index.html
new file mode 100644
index 0000000..8446aca
--- /dev/null
+++ b/examples/frontend/index.html
@@ -0,0 +1,5 @@
+<html>
+ <body>
+ <p>Hi!</p>
+ </body>
+</html>
diff --git a/examples/radicle-frontend b/examples/radicle-frontend
new file mode 100755
index 0000000..f976494
--- /dev/null
+++ b/examples/radicle-frontend
@@ -0,0 +1,28 @@
+#!/usr/bin/env radicle
+
+(load! (find-module-file! "prelude.rad"))
+(import prelude/machine '[send! new-machine!] :unqualified)
+
+(def machine-code
+ "The code that will live in the remote machine. Usually it is best to keep
+ this in a separate file.
+
+ The CID is that of the ./frontend directory, which contains a simple
+ index.html page.
+ "
+ '(def get-html
+ (fn []
+ "QmNYGU5355YzzaB4AMUFHDjLKx3L3Yr47TufpM4vbphWHH")) )
+
+
+(def create-machine
+ (fn []
+ (def id (new-machine!))
+ (send! id [ machine-code ])
+ id))
+
+(put-str!
+ (string-append
+ "Created machine. Visit it at: http://localhost:8909/v0/machines/"
+ (create-machine)
+ "/frontend/index.html"))
diff --git a/exe/Daemon.hs b/exe/Daemon.hs
index 8e5cae5..a68fa60 100644
--- a/exe/Daemon.hs
+++ b/exe/Daemon.hs
@@ -122,7 +122,7 @@ server :: Env -> Server Api.DaemonApi
server env = hoistServer Api.daemonApi nt daemonServer
where
daemonServer :: ServerT Api.DaemonApi Daemon
- daemonServer = newMachine :<|> query :<|> send :<|> pure Api.swagger
+ daemonServer = newMachine :<|> query :<|> send :<|> frontend :<|> pure Api.swagger
nt :: Daemon a -> Handler a
nt d = do
@@ -238,6 +238,36 @@ send id (Api.SendRequest expressions) = do
Nothing -> throw $ MachineError id AckTimeout
+-- | Give the HTML specified by a machine (via defining `(get-html)`).
+frontend :: MachineId -> [Text] -> Daemon Api.HtmlText
+frontend id path = do
+ m <- ensureMachineLoaded id
+ bumpPolling id
+ case runIdentity $ interpret "[frontend]" "(get-html)" (machineState m) of
+ Left err -> do
+ logError "Frontend load failed" [("machine-id", getMachineId id)]
+ throw $ MachineError id
+ $ FrontendError
+ $ "(get-html) failed: " <> renderCompactPretty err
+ Right (String v) -> do
+ logInfo "Handled frontend request" [("machine-id", getMachineId id)]
+ case Ipfs.cidFromText v of
+ Left _ -> do
+ logError "Frontend returned invalid CID" [("machine-id", getMachineId id)]
+ throw $ MachineError id
+ $ FrontendError "get-html returned invalid CID"
+ Right v' -> do
+ let ipfsPath = show v' <> "/" <> T.intercalate "/" path
+ logInfo "Query HTML" [ ("CID", show v')
+ , ("machine-id", getMachineId id)
+ , ("ipfs-path", ipfsPath)
+ ]
+ val <- Ipfs.ipfsHttpGet' "cat" [("arg", ipfsPath)]
+ pure $ Api.HtmlText $ toS val
+ Right _ -> do
+ logError "Frontend load failed" [("machine-id", getMachineId id)]
+ throw $ MachineError id $ FrontendError "(get-html) did not evaluate to a string"
+
-- | Given an 'MachineId', makes sure the machine is loaded and
-- fetch the latest inputs.
--
diff --git a/nix/shell.nix b/nix/shell.nix
index b648b21..7705298 100644
--- a/nix/shell.nix
+++ b/nix/shell.nix
@@ -17,9 +17,9 @@ in
stdenv.mkDerivation {
name = "radicle-dev";
- buildInputs = [ ghc zlib glibcLocales python3 wget stack postgresql moreutils fzf docker_compose]
+ buildInputs = [ ghc zlib glibcLocales python3 wget stack moreutils fzf docker_compose ]
++ (if doc then [docstuffs postgresql] else [])
- ++ (if extras then [ vimPlugins.stylish-haskell haskellPackages.apply-refact hlint ] else []);
+ ++ (if extras then [ vimPlugins.stylish-haskell haskellPackages.apply-refact hlint haskellPackages.ghcid haskellPackages.weeder] else []);
LANG = "en_US.UTF-8";
libraryPkgconfigDepends = [ zlib ];
shellHook = ''
@@ -29,6 +29,7 @@ stdenv.mkDerivation {
export IS_NIX_SHELL="true"
export LOCALE_ARCHIVE="${pkgs.glibcLocales}/lib/locale/locale-archive";
export RAD_BIN="$(stack path --docker --local-install-root)/bin"
+ export COMPOSE_FILE=test/docker-compose.yaml
eval $(grep export ${ghc}/bin/ghc)
alias check="pushd $PWD && ./scripts/check-fmt.sh && hlint . && popd"
alias mkdocs="pushd $PWD/docs && make html && popd"
@@ -41,6 +42,5 @@ stdenv.mkDerivation {
alias sts="stack test --fast radicle:spec"
alias str="stack test --fast radicle:spec --ta '--pattern \"Radicle source file tests\"'"
alias server="stack exec radicle-server -- "
- alias rad="stack exec --silent radicle -- rad/repl.rad"
'';
}
diff --git a/src/Radicle/Daemon/Client.hs b/src/Radicle/Daemon/Client.hs
index cd77e12..e262cc3 100644
--- a/src/Radicle/Daemon/Client.hs
+++ b/src/Radicle/Daemon/Client.hs
@@ -9,6 +9,7 @@ module Radicle.Daemon.Client
, query
, send
, MachineId(..)
+ , getMachineIndex
) where
import Protolude hiding (TypeError)
@@ -65,6 +66,10 @@ newMachine client = do
pure machineId
+--- | Get the index page for a machine.
+getMachineIndex :: (ClientM m) => Client -> MachineId -> m HtmlText
+getMachineIndex client mid = runClient client $ Servant.client frontendEndpoint mid ["index.html"]
+
-- | Primitive function defitions for @daemon/send!@, @daemon/query!@, and
-- @daemon/new-machine!@.
createDaemonClientPrimFns ::(MonadIO m) => IO (PrimFns m)
diff --git a/src/Radicle/Daemon/Error.hs b/src/Radicle/Daemon/Error.hs
index d587e88..ea74ee4 100644
--- a/src/Radicle/Daemon/Error.hs
+++ b/src/Radicle/Daemon/Error.hs
@@ -15,6 +15,7 @@ import Radicle.Ipfs
data MachineError
= InvalidInput (LangError Value)
| IpfsError IpfsException
+ | FrontendError Text
| AckTimeout
| DaemonError Text
| MachineNotCached
@@ -39,6 +40,7 @@ displayError = \case
case e of
InvalidInput err -> ("Invalid radicle input", [mid, ("radicle-error", renderCompactPretty err)])
IpfsError (ipfsErr -> (msg, infos)) -> (msg, mid : infos)
+ FrontendError err -> ("Frontend error", [mid, ("error", err)])
AckTimeout -> ("No response received from the machine owner. This could be because they are offline, or that waiting for the response timed out", [mid])
MachineNotCached -> ("Machine was not found in cache", [mid])
DaemonError err -> ("Internal error", [mid, ("error", err)])
diff --git a/src/Radicle/Daemon/HttpApi.hs b/src/Radicle/Daemon/HttpApi.hs
index d58d2f7..b52cc4f 100644
--- a/src/Radicle/Daemon/HttpApi.hs
+++ b/src/Radicle/Daemon/HttpApi.hs
@@ -18,6 +18,9 @@ module Radicle.Daemon.HttpApi
, NewResponse(..)
, newMachineEndpoint
+ , frontendEndpoint
+ , HtmlText(..)
+
, DaemonApi
, daemonApi
@@ -56,6 +59,28 @@ 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
+
+data HTML deriving Typeable
+
+-- | @text/html;charset=utf-8@
+instance Accept HTML where
+ contentTypes _ =
+ "text" HttpMedia.// "html" HttpMedia./: ("charset", "utf-8") :|
+ ["text" HttpMedia.// "html"]
+
+instance MimeRender HTML HtmlText where
+ mimeRender _ (HtmlText h) = toS h
+
+instance MimeUnrender HTML HtmlText where
+ mimeUnrender _ msg = case decodeUtf8' (toS msg) of
+ Left e -> Left $ show e
+ Right v -> Right $ HtmlText v
+
+newtype HtmlText = HtmlText Text
+ deriving (Eq, Show, Read, Generic, IsString)
+
+instance ToSchema HtmlText
+
-- | 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
@@ -164,10 +189,15 @@ type NewMachineEndpoint = MachinesEndpoint ("new" :> Post '[JSON, RadicleData] N
newMachineEndpoint :: Proxy NewMachineEndpoint
newMachineEndpoint = Proxy
+type FrontendEndpoint = MachineEndpoint ("frontend" :> CaptureAll "path" Text :> Get '[HTML] HtmlText)
+frontendEndpoint :: Proxy FrontendEndpoint
+frontendEndpoint = Proxy
+
type DaemonApi =
NewMachineEndpoint
:<|> MachineQueryEndpoint
:<|> MachineSendEndpoint
+ :<|> FrontendEndpoint
:<|> "v0" :> "docs" :> Get '[JSON] Swagger
daemonApi :: Proxy DaemonApi
diff --git a/src/Radicle/Ipfs.hs b/src/Radicle/Ipfs.hs
index 969cf97..83b6edf 100644
--- a/src/Radicle/Ipfs.hs
+++ b/src/Radicle/Ipfs.hs
@@ -12,6 +12,7 @@ module Radicle.Ipfs
, Address(..)
, addressToText
, addressFromText
+ , cidFromText
, VersionResponse(..)
, version
@@ -31,6 +32,11 @@ module Radicle.Ipfs
, PubsubMessage(..)
, publish
, subscribe
+
+ , ipfsHttpGet
+ , ipfsHttpGet'
+ , ipfsHttpPost
+ , ipfsHttpPost'
) where
import Protolude hiding (TypeError, catch, catches, try)
@@ -356,11 +362,19 @@ ipfsHttpGet
-> [(Text, Text)] -- ^ URL query parameters
-> m a
ipfsHttpGet path params = do
+ res <- ipfsHttpGet' path params
+ parseJsonResponse path res
+
+ipfsHttpGet'
+ :: (MonadIpfs m)
+ => Text -- ^ Path of the endpoint under "/api/v0/"
+ -> [(Text, Text)] -- ^ URL query parameters
+ -> m LByteString
+ipfsHttpGet' path params = do
Client{clientHttpManager, clientBaseRequest} <- askClient
liftIO $ mapHttpException path $ do
let request = makeIpfsRequest clientBaseRequest Http.methodGet path params
- response <- HttpClient.httpLbs request clientHttpManager
- parseJsonResponse path $ HttpClient.responseBody response
+ HttpClient.responseBody <$> HttpClient.httpLbs request clientHttpManager
ipfsHttpPost
:: (MonadIpfs m, FromJSON a)