Skip to content

A peer-to-peer stack for code collaboration

Consolidate IPFS errors (#443)

James Haydona26c6ca8ab5b
diff --git a/exe/Daemon.hs b/exe/Daemon.hs
index ec48a2d..3baccdc 100644
--- a/exe/Daemon.hs
+++ b/exe/Daemon.hs
@@ -24,6 +24,8 @@ import Radicle.Daemon.Ipfs
import Radicle.Daemon.MachineConfig
import Radicle.Daemon.Monad
+import qualified Radicle.Ipfs as Ipfs
+
import Radicle hiding (DaemonError, Env)
import qualified Radicle.Internal.CLI as Local
import qualified Radicle.Internal.ConcurrentMap as CMap
@@ -145,8 +147,8 @@ init follows = traverse_ initMachine (Map.toList follows)
-- /writer/.
newMachine :: Daemon Api.NewResponse
newMachine = do
- id <- liftExceptT CouldNotCreateMachine createMachine
- sub <- ipfs id $ initSubscription id
+ id <- createMachine `ipfs` CouldNotCreateMachine
+ sub <- machineIpfs id $ initSubscription id
logInfo Normal "Created new IPFS machine" [("machine-id", getMachineId id)]
m <- liftIO $ emptyMachine id Writer sub
insertNewMachine id (Cached m)
@@ -203,14 +205,14 @@ send id (Api.SendRequest expressions) = do
New InputsApplied{ nonce = Just nonce' } | nonce' == nonce -> True
_ -> False
asyncMsg <- liftIO $ async $ subscribeOne sub ackWaitTime isResponse (logNonDecodableMsg id)
- ipfs id $ publish id (Submit SubmitInputs{..})
+ machineIpfs id $ publish id (Submit SubmitInputs{..})
logInfo Debug
"Sent input request to writer"
[ ("machine-id", getMachineId id)
, ("expressions", prValues expressions) ]
- msg_ <- liftIO $ waitCatch asyncMsg
+ msg_ <- machineIpfs id $ wait asyncMsg
case msg_ of
- Right (Just (New InputsApplied{results})) -> do
+ Just (New InputsApplied{results}) -> do
logInfo Normal
"Writer accepted input request"
[ ("machine-id", getMachineId id)
@@ -218,9 +220,9 @@ send id (Api.SendRequest expressions) = do
]
bumpPolling id
pure Api.SendResponse{..}
- Right Nothing -> throwError $ MachineError id AckTimeout
- Right _ -> throwError $ MachineError id (DaemonError "Didn't filter machine topic messages correctly.")
- Left err -> throwError $ MachineError id (DaemonError (toS (displayException err)))
+ Just _ -> throwError $ MachineError id (DaemonError "Didn't filter machine topic messages correctly.")
+ Nothing -> throwError $ MachineError id AckTimeout
+
prValues = T.intercalate "," . (renderCompactPretty <$>)
@@ -270,6 +272,8 @@ logNonDecodableMsg :: MachineId -> Text -> IO ()
logNonDecodableMsg (MachineId id) bad =
Common.logInfo "Non-decodable message on machine's pubsub topic" [("machine-id", id), ("message", bad)]
+-- | Turns a 'Daemon' subscription handler into an IO one. Errors which are
+-- encountered in a subscription handler are just logged.
daemonHandler :: Env -> MachineId -> (Message -> Daemon ()) -> Either Text Message -> IO ()
daemonHandler _ id _ (Left bad) = logNonDecodableMsg id bad
daemonHandler env _ h (Right msg) = do
@@ -281,8 +285,8 @@ daemonHandler env _ h (Right msg) = do
-- | Loads a machine fresh from IPFS.
loadMachine :: ReaderOrWriter -> MachineId -> Daemon Machine
loadMachine mode id = do
- (idx, is) <- ipfs id $ machineInputsFrom id Nothing
- sub <- ipfs id $ initSubscription id
+ (idx, is) <- machineIpfs id $ machineInputsFrom id Nothing
+ sub <- machineIpfs id $ initSubscription id
m <- liftIO $ emptyMachine id mode sub
(m', _) <- addInputs is (pure idx) (const (pure ())) m
insertNewMachine id (Cached m')
@@ -312,8 +316,17 @@ addInputs is getIdx after m =
after rs
pure (m', (rs, idx))
-ipfs :: MachineId -> ExceptT IpfsError IO a -> Daemon a
-ipfs id = liftExceptT (MachineError id . IpfsError)
+-- | Run some IPFS IO.
+ipfs :: IO a -> (Ipfs.IpfsException -> Error) -> Daemon a
+ipfs io err = do
+ res <- liftIO $ (Right <$> io) `catch` \(e :: Ipfs.IpfsException) -> pure (Left e)
+ case res of
+ Left e -> throwError (err e)
+ Right x -> pure x
+
+-- | Run some IPFS IO related to a specific machine.
+machineIpfs :: MachineId -> IO a -> Daemon a
+machineIpfs id io = ipfs io (MachineError id . IpfsError)
-- | Do some high-freq polling for a while.
bumpPolling :: MachineId -> Daemon ()
@@ -409,7 +422,7 @@ refreshAsReader id = modifyMachine id refresh
where
refresh m = do
let currentIdx = machineLastIndex m
- (newIdx, is) <- ipfs id $ machineInputsFrom (machineId m) currentIdx
+ (newIdx, is) <- machineIpfs id $ machineInputsFrom (machineId m) currentIdx
if currentIdx == Just newIdx
then do
logInfo Debug
@@ -458,8 +471,8 @@ writeInputs id is nonce = do
, ("new-input-index", show idx) ]
pure rs
where
- write = ipfs id $ writeIpfs id is
- pub results = ipfs id $ publish id (New InputsApplied{..})
+ write = machineIpfs id $ writeIpfs id is
+ pub results = machineIpfs id $ publish id (New InputsApplied{..})
-- * Polling
diff --git a/src/Radicle/Daemon/Client.hs b/src/Radicle/Daemon/Client.hs
index b394a9f..df39878 100644
--- a/src/Radicle/Daemon/Client.hs
+++ b/src/Radicle/Daemon/Client.hs
@@ -113,6 +113,8 @@ wrapServantError action = do
case result of
Left (Servant.FailureResponse response) -> throwErrorHere $ DaemonError $ toS $ Servant.responseBody response
Left e -> case e of
- Servant.ConnectionError _ -> throwErrorHere $ DaemonError "Could not connect to radicle-daemon. Most likely it is not running. Please start it with 'radicle-daemon'."
+ Servant.ConnectionError _ -> throwErrorHere $ DaemonError startDaemonHint
_ -> throwErrorHere $ DaemonError $ toS $ displayException e
Right value -> pure value
+ where
+ startDaemonHint = "Could not connect to the Radicle daemon, most likely it is not running. Please see the documentation for how to start it."
diff --git a/src/Radicle/Daemon/Ipfs.hs b/src/Radicle/Daemon/Ipfs.hs
index fee2688..4bf3db7 100644
--- a/src/Radicle/Daemon/Ipfs.hs
+++ b/src/Radicle/Daemon/Ipfs.hs
@@ -1,11 +1,10 @@
module Radicle.Daemon.Ipfs
- ( IpfsError(..)
- , MachineId(..)
+ ( MachineId(..)
, Message(..)
, InputsApplied(..)
, SubmitInputs(..)
, writeIpfs
- , publish
+ , Radicle.Daemon.Ipfs.publish
, machineInputsFrom
, createMachine
, Ipfs.MachineEntryIndex
@@ -24,17 +23,16 @@ import Control.Monad.Fail
import Data.Aeson (decodeStrict, (.:), (.=))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
-import qualified Data.HashMap.Strict as HashMap
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import qualified Data.Unique as Unique
-import qualified Network.HTTP.Client as Http
import Radicle.Internal.Core
import qualified Radicle.Internal.MachineBackend.Ipfs as Ipfs
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import qualified Radicle.Internal.UUID as UUID
+import Radicle.Ipfs
import qualified Radicle.Ipfs as Ipfs
jsonToValue :: Aeson.Value -> Aeson.Parser Value
@@ -60,12 +58,6 @@ instance Aeson.ToJSON MachineId where
instance Aeson.FromJSON MachineId where
parseJSON js = MachineId <$> Aeson.parseJSON js
-data IpfsError
- = IpfsDaemonException Ipfs.IpfsException
- | IpfsDaemonErrMsg Text
- | IpfsDaemonNoErrMsg
- | Timeout
-
-- | Messages sent on a machine's IPFS pubsub topic.
data Message = New InputsApplied | Submit SubmitInputs
@@ -110,30 +102,11 @@ data SubmitInputs = SubmitInputs
-- * Ipfs helpers
--- TODO: All the error handling w.r.t interactions with IPFS should be
--- done in "Radicle.Ipfs".
-safeIpfs :: forall a. IO a -> ExceptT IpfsError IO a
-safeIpfs io = ExceptT $ liftIO $
- catches (Right <$> io)
- [ Handler $ pure . Left . IpfsDaemonException
- , Handler httpHdlr
- ]
- where
- httpHdlr e = pure $ Left $ case e of
- Http.HttpExceptionRequest _
- (Http.StatusCodeException _
- (decodeStrict ->
- Just (Aeson.Object (HashMap.lookup "Message" ->
- Just (Aeson.String msg))))) -> IpfsDaemonErrMsg msg
- Http.HttpExceptionRequest _ Http.ResponseTimeout -> Timeout
- _ -> IpfsDaemonNoErrMsg
-
-
-- | Write and pin some inputs to an IPFS machine.
-- TODO: we might want to make this safer by taking the expected head
-- MachineEntryIndex as an argument.
-writeIpfs :: MachineId -> [Value] -> ExceptT IpfsError IO Ipfs.MachineEntryIndex
-writeIpfs (MachineId id) vs = safeIpfs $ Ipfs.sendIpfs id (Seq.fromList vs)
+writeIpfs :: MachineId -> [Value] -> IO Ipfs.MachineEntryIndex
+writeIpfs (MachineId id) vs = Ipfs.sendIpfs id (Seq.fromList vs)
newtype Topic = Topic { getTopic :: Text }
@@ -142,9 +115,8 @@ machineTopic :: MachineId -> Topic
machineTopic (MachineId id) = Topic ("radicle:machine:" <> id)
-- | Publish a 'Message' on a machine's IPFS pubsub topic.
-publish :: MachineId -> Message -> ExceptT IpfsError IO ()
-publish id msg = safeIpfs $
- Ipfs.publish (getTopic (machineTopic id)) (Aeson.encode msg)
+publish :: MachineId -> Message -> IO ()
+publish id msg = Ipfs.publish (getTopic (machineTopic id)) (Aeson.encode msg)
-- | Subscribe to messages on a machine's IPFS pubsub topic.
subscribeForever :: MachineId -> MsgHandler -> IO ()
@@ -156,15 +128,15 @@ subscribeForever id messageHandler = Ipfs.subscribe topic pubsubHandler
Nothing -> Left (toS messageData)
-- | Get and pin inputs of an IPFS machine from a certain index.
-machineInputsFrom :: MachineId -> Maybe Ipfs.MachineEntryIndex -> ExceptT IpfsError IO (Ipfs.MachineEntryIndex, [Value])
-machineInputsFrom (MachineId id) = safeIpfs . Ipfs.receiveIpfs id
+machineInputsFrom :: MachineId -> Maybe Ipfs.MachineEntryIndex -> IO (Ipfs.MachineEntryIndex, [Value])
+machineInputsFrom = Ipfs.receiveIpfs . getMachineId
-- | Create an IPFS machine and return its ID.
-createMachine :: ExceptT IpfsError IO MachineId
+createMachine :: IO MachineId
createMachine = do
- id_ <- safeIpfs $ Ipfs.ipfsMachineCreate =<< UUID.uuid
+ id_ <- Ipfs.ipfsMachineCreate =<< UUID.uuid
case id_ of
- Left e -> throwError (IpfsDaemonErrMsg e)
+ Left e -> throw (IpfsException e)
Right id -> pure (MachineId id)
-- * Topic subscriptions
@@ -180,8 +152,8 @@ newtype TopicSubscription = TopicSubscription
-- | Given a machine ID, creates a subscription for that machine's
-- pubsub topic. This allows adding and removing handlers for messages
-- on that topic.
-initSubscription :: MachineId -> ExceptT IpfsError IO TopicSubscription
-initSubscription id = safeIpfs $ do
+initSubscription :: MachineId -> IO TopicSubscription
+initSubscription id = do
hdlrs <- newMVar Map.empty
_ <- async $ subscribeForever id (mainHdlr hdlrs)
pure $ TopicSubscription hdlrs
diff --git a/src/Radicle/Daemon/Monad.hs b/src/Radicle/Daemon/Monad.hs
index 760f902..46ffbba 100644
--- a/src/Radicle/Daemon/Monad.hs
+++ b/src/Radicle/Daemon/Monad.hs
@@ -20,6 +20,7 @@ import Protolude
import Radicle (LangError, Value, renderCompactPretty)
import Radicle.Daemon.Common
import Radicle.Daemon.Ipfs
+import Radicle.Ipfs
newtype Daemon a = Daemon (ExceptT Error (ReaderT Env IO) a)
@@ -47,16 +48,18 @@ data Env = Env
-- * Errors
+-- | An error relating to a specific machine managed by the daemon.
data MachineError
= InvalidInput (LangError Value)
- | IpfsError IpfsError
+ | IpfsError IpfsException
| AckTimeout
| DaemonError Text
| MachineNotCached
+-- | An error that the daemon can encounter.
data Error
= MachineError MachineId MachineError
- | CouldNotCreateMachine IpfsError
+ | CouldNotCreateMachine IpfsException
displayError :: Error -> (Text, [(Text,Text)])
displayError = \case
@@ -70,7 +73,9 @@ displayError = \case
DaemonError err -> ("Internal error", [mid, ("error", err)])
where
ipfsErr = \case
- IpfsDaemonErrMsg err -> ("The IPFS daemon returned an error", [("ipfs-error", err)])
- IpfsDaemonException exc -> ("There was an error using the IPFS daemon", [("ipfs-error", toS (displayException exc))])
- IpfsDaemonNoErrMsg -> ("There was an unknown error using IPFS", [])
- Timeout -> ("Timeout communicating with IPFS daemon", [])
+ IpfsException msg -> ("There was an error using the IPFS daemon", [("ipfs-error", msg)])
+ IpfsExceptionErrResp msg -> ("The IPFS daemon returned an error", [("ipfs-error", msg)])
+ IpfsExceptionErrRespNoMsg -> ("There was an unknown error using IPFS", [])
+ IpfsExceptionTimeout -> ("Timeout communicating with IPFS daemon", [])
+ IpfsExceptionInvalidResponse url parseError -> ("Cannot parse IPFS daemon response", [("url", url), ("parse-error", parseError)])
+ IpfsExceptionNoDaemon -> ("The IPFS daemon is not reachable, run 'rad ipfs daemon'", [])
diff --git a/src/Radicle/Ipfs.hs b/src/Radicle/Ipfs.hs
index f9289a3..a982ba5 100644
--- a/src/Radicle/Ipfs.hs
+++ b/src/Radicle/Ipfs.hs
@@ -25,7 +25,7 @@ module Radicle.Ipfs
, subscribe
) where
-import Protolude hiding (TypeError, catch, try)
+import Protolude hiding (TypeError, catch, catches, try)
import Control.Exception.Safe
import Control.Monad.Fail
@@ -38,6 +38,7 @@ import Data.Conduit ((.|))
import qualified Data.Conduit as C
import qualified Data.Conduit.Attoparsec as C
import qualified Data.Conduit.Combinators as C
+import qualified Data.HashMap.Strict as HashMap
import Data.IPLD.CID
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
@@ -45,26 +46,48 @@ import Lens.Micro ((.~), (^.))
import Network.HTTP.Client
(HttpException(..), HttpExceptionContent(..))
import qualified Network.HTTP.Client as HTTP
+import qualified Network.HTTP.Client as Http
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.Wreq as Wreq
import System.Environment (lookupEnv)
data IpfsException
- = IpfsException Text
- -- | JSON response from the IPFS Api cannot be parsed. First
- -- argument is the request path, second argument the JSON parsing
- -- error
- | IpfsExceptionInvalidResponse Text Text
- -- | The IPFS daemon is not running.
- | IpfsExceptionNoDaemon
- deriving (Show, Eq)
+ = IpfsException Text
+ | IpfsExceptionErrResp Text
+ | IpfsExceptionErrRespNoMsg
+ -- | The request to the IPFS daemon timed out.
+ | IpfsExceptionTimeout
+ -- | JSON response from the IPFS Api cannot be parsed. First
+ -- argument is the request path, second argument the JSON parsing
+ -- error
+ | IpfsExceptionInvalidResponse Text Text
+ -- | The IPFS daemon is not running.
+ | IpfsExceptionNoDaemon
+ deriving (Show)
instance Exception IpfsException where
- displayException (IpfsException msg) = "ipfs: " <> toS msg
- displayException IpfsExceptionNoDaemon = "ipfs: Daemon not reachable, run 'rad ipfs daemon"
- displayException (IpfsExceptionInvalidResponse url _) = "ipfs: Cannot parse IPFS daemon response for " <> toS url
-
-
+ displayException e = "ipfs: " <> case e of
+ IpfsException msg -> toS msg
+ IpfsExceptionNoDaemon -> "Cannot connect to " <> name
+ IpfsExceptionInvalidResponse url _ -> "Cannot parse " <> name <> " response for " <> toS url
+ IpfsExceptionTimeout -> name <> " took too long to respond"
+ IpfsExceptionErrResp msg -> toS msg
+ IpfsExceptionErrRespNoMsg -> name <> " failed with no error message"
+ where
+ name = "Radicle IPFS daemon"
+
+-- | Turn HTTP exceptions into 'IpfsException's.
+mapHttpException :: forall a. IO a -> IO a
+mapHttpException io = catch io httpHdlr
+ where
+ httpHdlr = \case
+ Http.HttpExceptionRequest _
+ (Http.StatusCodeException _
+ (Aeson.decodeStrict ->
+ Just (Aeson.Object (HashMap.lookup "Message" ->
+ Just (Aeson.String msg))))) -> throw (IpfsExceptionErrResp msg)
+ Http.HttpExceptionRequest _ Http.ResponseTimeout -> throw IpfsExceptionTimeout
+ _ -> throw IpfsExceptionErrRespNoMsg
-- | Given a CID @"abc...def"@ it returns a IPLD link JSON object
-- @{"/": "abc...def"}@.
@@ -163,7 +186,7 @@ subscribe topic messageHandler = runResourceT $ do
-- | Publish a message to a topic.
publish :: Text -> LByteString -> IO ()
publish topic message =
- void $ ipfsHttpPost' "pubsub/pub" [("arg", topic)] "data" message
+ void $ ipfsHttpPost' "pubsub/pub" [("arg", topic)] "data" message
newtype KeyGenResponse = KeyGenResponse IpnsId
@@ -241,7 +264,7 @@ ipfsHttpGet
=> Text -- ^ Path of the endpoint under "/api/v0/"
-> [(Text, Text)] -- ^ URL query parameters
-> IO a
-ipfsHttpGet path params = do
+ipfsHttpGet path params = mapHttpException $ do
let opts = Wreq.defaults & Wreq.params .~ params
url <- ipfsApiUrl path
res <- Wreq.getWith opts (toS url) `catch` handleRequestException
@@ -255,7 +278,7 @@ ipfsHttpPost
-> Text -- ^ Name of the argument for payload
-> LByteString -- ^ Payload argument
-> IO a
-ipfsHttpPost path params payloadArgName payload = do
+ipfsHttpPost path params payloadArgName payload = mapHttpException $ do
res <- ipfsHttpPost' path params payloadArgName payload
jsonRes <- Wreq.asJSON res `catch` handleParseException path
pure $ jsonRes ^. Wreq.responseBody