A peer-to-peer stack for code collaboration
Consolidate IPFS errors (#443)
James Haydona26c6ca8ab5b
diff --git a/exe/Daemon.hs b/exe/Daemon.hsindex ec48a2d..3baccdc 100644--- a/exe/Daemon.hs+++ b/exe/Daemon.hs@@ -24,6 +24,8 @@ import Radicle.Daemon.Ipfsimport Radicle.Daemon.MachineConfigimport Radicle.Daemon.Monad+import qualified Radicle.Ipfs as Ipfs+import Radicle hiding (DaemonError, Env)import qualified Radicle.Internal.CLI as Localimport qualified Radicle.Internal.ConcurrentMap as CMap@@ -145,8 +147,8 @@ init follows = traverse_ initMachine (Map.toList follows)-- /writer/.newMachine :: Daemon Api.NewResponsenewMachine = do- id <- liftExceptT CouldNotCreateMachine createMachine- sub <- ipfs id $ initSubscription id+ id <- createMachine `ipfs` CouldNotCreateMachine+ sub <- machineIpfs id $ initSubscription idlogInfo Normal "Created new IPFS machine" [("machine-id", getMachineId id)]m <- liftIO $ emptyMachine id Writer subinsertNewMachine id (Cached m)@@ -203,14 +205,14 @@ send id (Api.SendRequest expressions) = doNew InputsApplied{ nonce = Just nonce' } | nonce' == nonce -> True_ -> FalseasyncMsg <- 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 asyncMsgcase msg_ of- Right (Just (New InputsApplied{results})) -> do+ Just (New InputsApplied{results}) -> dologInfo Normal"Writer accepted input request"[ ("machine-id", getMachineId id)@@ -218,9 +220,9 @@ send id (Api.SendRequest expressions) = do]bumpPolling idpure 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 baddaemonHandler 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 MachineloadMachine 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 idm <- liftIO $ emptyMachine id mode sub(m', _) <- addInputs is (pure idx) (const (pure ())) minsertNewMachine id (Cached m')@@ -312,8 +316,17 @@ addInputs is getIdx after m =after rspure (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 refreshwhererefresh m = dolet currentIdx = machineLastIndex m- (newIdx, is) <- ipfs id $ machineInputsFrom (machineId m) currentIdx+ (newIdx, is) <- machineIpfs id $ machineInputsFrom (machineId m) currentIdxif currentIdx == Just newIdxthen dologInfo Debug@@ -458,8 +471,8 @@ writeInputs id is nonce = do, ("new-input-index", show idx) ]pure rswhere- 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{..})-- * Pollingdiff --git a/src/Radicle/Daemon/Client.hs b/src/Radicle/Daemon/Client.hsindex b394a9f..df39878 100644--- a/src/Radicle/Daemon/Client.hs+++ b/src/Radicle/Daemon/Client.hs@@ -113,6 +113,8 @@ wrapServantError action = docase result ofLeft (Servant.FailureResponse response) -> throwErrorHere $ DaemonError $ toS $ Servant.responseBody responseLeft 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 eRight 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.hsindex 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.Failimport Data.Aeson (decodeStrict, (.:), (.=))import qualified Data.Aeson as Aesonimport qualified Data.Aeson.Types as Aeson-import qualified Data.HashMap.Strict as HashMapimport qualified Data.Map.Strict as Mapimport qualified Data.Sequence as Seqimport qualified Data.Unique as Unique-import qualified Network.HTTP.Client as Httpimport Radicle.Internal.Coreimport qualified Radicle.Internal.MachineBackend.Ipfs as Ipfsimport Radicle.Internal.Parseimport Radicle.Internal.Prettyimport qualified Radicle.Internal.UUID as UUID+import Radicle.Ipfsimport qualified Radicle.Ipfs as IpfsjsonToValue :: Aeson.Value -> Aeson.Parser Value@@ -60,12 +58,6 @@ instance Aeson.ToJSON MachineId whereinstance Aeson.FromJSON MachineId whereparseJSON 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 -> TopicmachineTopic (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 pubsubHandlerNothing -> 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 MachineIdcreateMachine = do- id_ <- safeIpfs $ Ipfs.ipfsMachineCreate =<< UUID.uuid+ id_ <- Ipfs.ipfsMachineCreate =<< UUID.uuidcase 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 = dohdlrs <- newMVar Map.empty_ <- async $ subscribeForever id (mainHdlr hdlrs)pure $ TopicSubscription hdlrsdiff --git a/src/Radicle/Daemon/Monad.hs b/src/Radicle/Daemon/Monad.hsindex 760f902..46ffbba 100644--- a/src/Radicle/Daemon/Monad.hs+++ b/src/Radicle/Daemon/Monad.hs@@ -20,6 +20,7 @@ import Protoludeimport Radicle (LangError, Value, renderCompactPretty)import Radicle.Daemon.Commonimport Radicle.Daemon.Ipfs+import Radicle.Ipfsnewtype 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 IpfsExceptiondisplayError :: Error -> (Text, [(Text,Text)])displayError = \case@@ -70,7 +73,9 @@ displayError = \caseDaemonError err -> ("Internal error", [mid, ("error", err)])whereipfsErr = \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.hsindex 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.Safeimport Control.Monad.Fail@@ -38,6 +38,7 @@ import Data.Conduit ((.|))import qualified Data.Conduit as Cimport qualified Data.Conduit.Attoparsec as Cimport qualified Data.Conduit.Combinators as C+import qualified Data.HashMap.Strict as HashMapimport Data.IPLD.CIDimport qualified Data.Text as Timport 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 Httpimport qualified Network.HTTP.Conduit as HTTPimport qualified Network.Wreq as Wreqimport 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" messagenewtype 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 $ dolet opts = Wreq.defaults & Wreq.params .~ paramsurl <- ipfsApiUrl pathres <- 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 $ dores <- ipfsHttpPost' path params payloadArgName payloadjsonRes <- Wreq.asJSON res `catch` handleParseException pathpure $ jsonRes ^. Wreq.responseBody