A peer-to-peer stack for code collaboration
Daemon doesn't fail if it can't init a reader-mode machine (#420)
James Haydon553ed98711da
diff --git a/README.md b/README.mdindex 40ff89f..7990575 100644--- a/README.md+++ b/README.md@@ -32,19 +32,6 @@ rad> (def-rec fac (fn [n] (if (eq? n 0) 1 (* n (fac (- n 1))))))rad> (fac 6)```-## Radicle Server--`radicle-server` is a service that hosts Radicle state machines and persists-them to PostgreSQL.--The latest master build of this service is distributed as the Docker image-`eu.gcr.io/opensourcecoin/radicle-server:latest`. For every master commit we-also provide an image tagged the current date and a short commit hash. For-example `eu.gcr.io/opensourcecoin/radicle-server:b2018.12.06-a76a52f`.--To build the image locally run `images/radicle-server/build.sh`. You can also-use `images/radicle-server/docker-compose.yaml`.-## IssuesWe are currently using `radicle` itself to manage issues, and have thereforediff --git a/cloudbuild.yaml b/cloudbuild.yamlindex 7ff2d8d..9eab7dc 100644--- a/cloudbuild.yaml+++ b/cloudbuild.yaml@@ -77,8 +77,6 @@ steps:--test \--no-run-tests- ./images/radicle-server/ci-copy-bin.sh-- id: "Test"name: 'haskell:8.6.3'env: ['STACK_ROOT=/workspace/.stack']@@ -129,42 +127,8 @@ steps:RADPATH="$(pwd)/rad" stack exec radicle-doc docs/source/guide/Basics.lrad- - id: "Build radicle-server image"- waitFor:- - "Build"- name: 'gcr.io/cloud-builders/docker'- entrypoint: bash- env:- - COMMIT_SHA=$COMMIT_SHA- - BRANCH_NAME=$BRANCH_NAME- args:- - "-c"- - |- set -euxo pipefail-- image_name="eu.gcr.io/opensourcecoin/radicle-server"- short_sha=$(echo "$COMMIT_SHA" | head --bytes=7)- # Looks like this: b2018.12.06-a76a52f- tag="b$(date +%Y.%m.%d)-${short_sha}"- docker build \- --tag "$image_name" \- --cache-from "$image_name" \- ./images/radicle-server-- if [ "$BRANCH_NAME" == "master" ]; then- image_name="eu.gcr.io/opensourcecoin/radicle-server"- short_sha=$(echo "$COMMIT_SHA" | head --bytes=7)- # Looks like this: b2018.12.06-a76a52f- tag="b$(date +%Y.%m.%d)-${short_sha}"- docker tag "$image_name" "$image_name:$tag"- docker push "$image_name"- docker push "$image_name:$tag"- fi-- - id: "Start radicle-server and IPFS daemon"+ - id: "Start IPFS daemon"name: 'docker/compose:1.23.2'- waitFor:- - "Build radicle-server image"entrypoint: shargs:- "-c"@@ -172,14 +136,11 @@ steps:set -euxo pipefailexport COMPOSE_FILE=test/docker-compose.yaml- docker-compose up -d postgres- sleep 5 # Wait for the DB to be readydocker-compose up -dsleep 3 # Wait for service to be booted# Connect services to 'cloudbuild' network so they can be# accessed by other steps- docker network connect cloudbuild test_radicle-server_1 --alias radicle-serverdocker network connect cloudbuild test_ipfs-test-network_1 --alias ipfs-test-network# Add the empty entry to the IPFS test network. Radicle requires it@@ -187,7 +148,7 @@ steps:- id: "Integration tests"waitFor:- - "Start radicle-server and IPFS daemon"+ - "Start IPFS daemon"name: 'haskell:8.6.3'env: ['STACK_ROOT=/workspace/.stack']entrypoint: 'bash'@@ -202,4 +163,3 @@ steps:stack exec -- radicle-daemon &stack test :e2e- stack exec -- radicle test/machine-backends.rad radicle-serverdiff --git a/exe/Daemon.hs b/exe/Daemon.hsindex 05a47e6..225f8ed 100644--- a/exe/Daemon.hs+++ b/exe/Daemon.hs@@ -12,7 +12,6 @@ import Protolude hiding (fromStrict, option, poll)import qualified Data.Aeson as Aimport Data.ByteString.Lazy (fromStrict)import qualified Data.Map.Strict as Map-import qualified Data.Sequence as Seqimport qualified Data.Text as Timport qualified Data.Time.Clock.System as Timeimport Network.Wai.Handler.Warp (run)@@ -26,7 +25,7 @@ import qualified Radicle.Daemon.Common as Commonimport qualified Radicle.Internal.UUID as UUIDimport Radicle hiding (Env)-import Radicle.Daemon.HttpApi+import qualified Radicle.Daemon.HttpApi as Apiimport Radicle.Daemon.Ipfsimport qualified Radicle.Internal.CLI as Localimport qualified Radicle.Internal.ConcurrentMap as CMap@@ -60,6 +59,7 @@ displayError = \caseIpfsDaemonError err -> ("There was an error using IPFS", [mid, ("error", toS (displayException err))])InternalError err -> ("Internal error", [mid, ("error", err)])NetworkError err -> ("There was an error communicating with the IPFS daemon", [mid, ("error", err)])+ Timeout -> ("Timeout communicating with IPFS daemon", [mid])AckTimeout -> ("The writer appears to be offline", [mid])MachineAlreadyCached -> ("Tried to add already cached machine", [mid])MachineNotCached -> ("Machine was not found in cache", [mid])@@ -108,7 +108,7 @@ data LogLevel = Normal | Debugdata Env = Env{ followFileLock :: FollowFileLock, followFile :: FilePath- , machines :: IpfsMachines+ , machines :: CachedMachines, logLevel :: LogLevel}@@ -124,7 +124,7 @@ main = doOpts{..} <- execParser allOptsfollowFileLock <- newMVar ()followFile <- Local.getRadicleFile (toS filePrefix <> "daemon-follows")- machines <- Chains <$> CMap.empty+ machines <- CachedMachines <$> CMap.emptylet env = Env{ logLevel = if debug then Debug else Normal, ..}follows <- readFollowFileIO followFileLock followFileinitRes <- runDaemon env (init follows)@@ -132,7 +132,7 @@ main = doLeft err -> logErr "Init failed" [] >> logDaemonError errRight _ -> dopolling <- async $ initPolling env- let app = serve daemonApi (server env)+ let app = serve Api.daemonApi (server env)Common.logInfo "Start listening" [("port", show port)]serv <- async $ run port appexc <- waitEitherCatchCancel polling serv@@ -148,14 +148,11 @@ main = do<> header "radicle-daemon")-type IpfsMachine = Chain MachineId MachineEntryIndex TopicSubscription-type IpfsMachines = Chains MachineId MachineEntryIndex TopicSubscription--server :: Env -> Server DaemonApi-server env = hoistServer daemonApi nt daemonServer+server :: Env -> Server Api.DaemonApi+server env = hoistServer Api.daemonApi nt daemonServerwhere- daemonServer :: ServerT DaemonApi Daemon- daemonServer = newMachine :<|> query :<|> send :<|> pure swagger+ daemonServer :: ServerT Api.DaemonApi Daemon+ daemonServer = newMachine :<|> query :<|> send :<|> pure Api.swaggernt :: Daemon a -> Handler ant d = do@@ -179,23 +176,23 @@ server env = hoistServer daemonApi nt daemonServerinit :: Follows -> Daemon ()init follows = traverse_ initMachine (Map.toList follows)where- initMachine (id, Reader) = initAsReader id- initMachine (id, Writer) = initAsWriter id+ initMachine (id, Reader) = initReaderNoFail id+ initMachine (id, Writer) = initAsWriter id $> ()-- * Endpoints-- | Create a new IPFS machine and initialise the daemon as as the-- /writer/.-newMachine :: Daemon NewResponse+newMachine :: Daemon Api.NewResponsenewMachine = doid <- createsub <- ipfs id $ initSubscription idlogInfo Normal "Created new IPFS machine" [("machine-id", getMachineId id)]m <- liftIO $ emptyMachine id Writer sub- insertNewMachine m+ insertNewMachine id (Cached m)actAsWriter mwriteFollowFile- pure (NewResponse id)+ pure (Api.NewResponse id)wherecreate = Daemon $ mapExceptT (lift . fmap (first CouldNotCreateMachine)) $ createMachine@@ -205,15 +202,15 @@ newMachine = do---- Hitting this endpoint will turn on high-frequency polling for a-- fixed amount of time.-query :: MachineId -> QueryRequest -> Daemon QueryResponse-query id (QueryRequest v) = do+query :: MachineId -> Api.QueryRequest -> Daemon Api.QueryResponse+query id (Api.QueryRequest v) = dom <- checkMachineLoaded idbumpPolling id- case fst <$> runIdentity $ runLang (chainState m) $ eval v of+ case fst <$> runIdentity $ runLang (machineState m) $ eval v ofLeft err -> throwError $ MachineError id (InvalidInput err)Right rv -> dologInfo Normal "Query success:" [("result", renderCompactPretty rv)]- pure (QueryResponse rv)+ pure (Api.QueryResponse rv)-- | Write a new expression to an IPFS machine.--@@ -224,17 +221,20 @@ query id (QueryRequest v) = do-- - If the daemon is a reader for the machine, it will request the-- machine's writer daemon to perform the write, and wait for an-- ack.-send :: MachineId -> SendRequest -> Daemon SendResponse-send id (SendRequest expressions) = do- mode_ <- machineMode- case mode_ of- Just (Writer, _) -> do- results <- writeInputs id expressions Nothing- pure SendResponse{..}- Just (Reader, sub) -> requestInput sub+send :: MachineId -> Api.SendRequest -> Daemon Api.SendResponse+send id (Api.SendRequest expressions) = do+ cm_ <- lookupMachine id+ case cm_ ofNothing -> do+ m <- newReader id+ requestInput (machineSubscription m)+ Just (UninitialisedReader _) -> dom <- initAsReader id- requestInput (chainSubscription m)+ requestInput (machineSubscription m)+ Just (Cached Machine{ machineMode = Reader, ..}) -> requestInput machineSubscription+ Just (Cached Machine{ machineMode = Writer }) -> do+ results <- writeInputs id expressions Nothing+ pure Api.SendResponse{..}whererequestInput sub = dononce <- liftIO $ UUID.uuid@@ -256,12 +256,11 @@ send id (SendRequest expressions) = do, ("results", prValues results)]bumpPolling id- pure SendResponse{..}+ pure Api.SendResponse{..}Right Nothing -> throwError $ MachineError id AckTimeoutRight _ -> throwError $ MachineError id (DaemonError "Didn't filter machine topic messages correctly.")Left err -> throwError $ MachineError id (DaemonError (toS (displayException err)))- machineMode = fmap (liftA2 (,) chainMode chainSubscription) <$> lookupMachine idprValues = T.intercalate "," . (renderCompactPretty <$>)-- * Helpers@@ -289,32 +288,36 @@ readFollowFileIO lock ff = withFollowFileLock lock $ dowriteFollowFile :: Daemon ()writeFollowFile = do- lock <- asks followFileLock- Chains cMap <- asks machines- ff <- asks followFile- liftIO $ withFollowFileLock lock $ do- ms <- CMap.nonAtomicRead cMap- let fs = Map.fromList $ second chainMode <$> Map.toList ms- writeFile ff (toS $ A.encode fs)--lookupMachine :: MachineId -> Daemon (Maybe IpfsMachine)+ lock <- asks followFileLock+ CachedMachines cMap <- asks machines+ ff <- asks followFile+ liftIO $ withFollowFileLock lock $ do+ ms <- CMap.nonAtomicRead cMap+ let fs = mode <$> ms+ writeFile ff (toS (A.encode fs))+ where+ mode (UninitialisedReader _) = Reader+ mode (Cached c) = machineMode c++lookupMachine :: MachineId -> Daemon (Maybe CachedMachine)lookupMachine id = do- msVar <- asks machines- liftIO $ CMap.lookup id (getChains msVar)+ msCMap <- asks machines+ liftIO $ CMap.lookup id (getMachines msCMap)-- | Given an 'MachineId', makes sure the machine is in the cache and-- updated.-checkMachineLoaded :: MachineId -> Daemon IpfsMachine+checkMachineLoaded :: MachineId -> Daemon MachinecheckMachineLoaded id = dom_ <- lookupMachine idcase m_ ofNothing -> do-- In this case we have not seen the machine before so we act as-- a reader.- m <- initAsReader id- writeFollowFile- pure m- Just m -> case chainMode m of+ newReader id+ Just (UninitialisedReader _) ->+ -- We try to initialise the reader again.+ initAsReader id+ Just (Cached m) -> case machineMode m ofWriter -> pure mReader -> refreshAsReader id-- TODO(james): For the moment we will just force a@@ -341,13 +344,13 @@ daemonHandler env _ h (Right msg) = doRight _ -> pure ()-- | Loads a machine fresh from IPFS.-loadMachine :: ReaderOrWriter -> MachineId -> Daemon IpfsMachine+loadMachine :: ReaderOrWriter -> MachineId -> Daemon MachineloadMachine mode id = do(idx, is) <- ipfs id $ machineInputsFrom id Nothingsub <- ipfs id $ initSubscription idm <- liftIO $ emptyMachine id mode sub(m', _) <- addInputs is (pure idx) (const (pure ())) m- insertNewMachine m'+ insertNewMachine id (Cached m')pure m'-- | Add inputs to a cached machine.@@ -358,20 +361,18 @@ addInputs-- ^ Determine the new index.-> ([Value] -> Daemon ())-- ^ Performed after the chain is cached.- -> IpfsMachine- -> Daemon (IpfsMachine, ([Value], MachineEntryIndex))+ -> Machine+ -> Daemon (Machine, ([Value], MachineEntryIndex))-- ^ Returns the updated machine, the results and the new index.addInputs is getIdx after m =case advanceChain m is of- Left err -> throwError $ MachineError (chainName m) (InvalidInput err)+ Left err -> throwError $ MachineError (machineId m) (InvalidInput err)Right (rs, newState) -> doidx <- getIdxt <- liftIO $ Time.getSystemTime- let news = Seq.fromList $ zip is rs- m' = m { chainState = newState- , chainLastIndex = Just idx- , chainEvalPairs = chainEvalPairs m Seq.>< news- , chainLastUpdated = t+ let m' = m { machineState = newState+ , machineLastIndex = Just idx+ , machineLastUpdated = t}after rspure (m', (rs, idx))@@ -382,48 +383,45 @@ ipfs id = Daemon . mapExceptT (lift . fmap (first (MachineError id . IpfsError))-- | Do some high-freq polling for a while.bumpPolling :: MachineId -> Daemon ()bumpPolling id = do- modifyMachine id $ \m' -> pure (m' { chainPolling = highFreq }, () )+ modifyMachine id $ \m -> pure (m { machinePolling = highFreq }, () )logInfo Debug "Reset to high-frequency polling" [("machine-id", getMachineId id)]--- | Insert a new machine into the cache. Errors if the machine is--- already cached.-insertNewMachine :: IpfsMachine -> Daemon ()-insertNewMachine m = do- msVar <- asks machines- inserted_ <- liftIO $ CMap.insertNew id m (getChains msVar)- case inserted_ of- Just () -> pure ()- Nothing -> throwError (MachineError id MachineAlreadyCached)- where- id = chainName m+-- | Insert a new machine into the cache.+insertNewMachine :: MachineId -> CachedMachine -> Daemon ()+insertNewMachine id m = do+ msCMap <- asks machines+ liftIO $ CMap.insert id m (getMachines msCMap)-- | Modify a machine that is already in the cache. Errors if the-- machine isn't in the cache already.-modifyMachine :: MachineId -> (IpfsMachine -> Daemon (IpfsMachine, a)) -> Daemon a+modifyMachine :: forall a. MachineId -> (Machine -> Daemon (Machine, a)) -> Daemon amodifyMachine id f = doenv <- ask- res <- liftIO $ CMap.modifyExistingValue id (getChains (machines env)) $ \m -> do- x <- runDaemon env (f m)- pure $ case x of- Left err -> (m, Left err)- Right (m', y) -> (m', Right y)+ res <- liftIO $ CMap.modifyExistingValue id (getMachines (machines env)) (modCached env)case res ofNothing -> throwError (MachineError id MachineNotCached)Just (Left err) -> throwError errJust (Right y) -> pure y+ where+ modCached :: Env -> CachedMachine -> IO (CachedMachine, Either Error a)+ modCached _ u@(UninitialisedReader _) = pure (u, Left (MachineError id MachineNotCached))+ modCached env (Cached m) = do+ x <- runDaemon env (f m)+ pure $ case x of+ Left err -> (Cached m, Left err)+ Right (m', y) -> (Cached m', Right y)-emptyMachine :: MachineId -> ReaderOrWriter -> TopicSubscription -> IO IpfsMachine+emptyMachine :: MachineId -> ReaderOrWriter -> TopicSubscription -> IO MachineemptyMachine id mode sub = dot <- Time.getSystemTime- pure Chain{ chainName = id- , chainState = pureEnv- , chainEvalPairs = mempty- , chainLastIndex = Nothing- , chainMode = mode- , chainSubscription = sub- , chainLastUpdated = t- , chainPolling = highFreq- }+ pure Machine{ machineId = id+ , machineState = pureEnv+ , machineLastIndex = Nothing+ , machineMode = mode+ , machineSubscription = sub+ , machineLastUpdated = t+ , machinePolling = highFreq+ }-- ** Reader@@ -433,13 +431,13 @@ emptyMachine id mode sub = do-- updates on pubsub.---- The machine is added to the deamons machine cache.-initAsReader :: MachineId -> Daemon IpfsMachine+initAsReader :: MachineId -> Daemon MachineinitAsReader id = dom <- loadMachine Reader idenv <- ask- _ <- liftIO $ addHandler (chainSubscription m) (daemonHandler env id onMsg)+ _ <- liftIO $ addHandler (machineSubscription m) (daemonHandler env id onMsg)logInfo Normal "Following as reader" [ ("machine-id", getMachineId id)- , ("current-input-index", show (chainLastIndex m)) ]+ , ("current-input-index", show (machineLastIndex m)) ]pure mwhereonMsg :: Message -> Daemon ()@@ -452,29 +450,48 @@ initAsReader id = dobumpPolling id_ -> pure ()--- | Updates a machine in the cache with the new inputs pulled from IPFS.-refreshAsReader :: MachineId -> Daemon IpfsMachine-refreshAsReader id = modifyMachine id $ \m -> do- let currentIdx = chainLastIndex m- (newIdx, is) <- ipfs id $ machineInputsFrom (chainName m) currentIdx- if currentIdx == Just newIdx- then do- logInfo Debug- "Reader is already up to date"- [mid, ("input-index", show newIdx)]- pure (m, m)- else do- (m', _) <- addInputs is (pure newIdx) (const (pure ())) m- logInfo Debug- "Updated reader"- [mid, ("n", show (length is)), ("input-index", show newIdx)]- pure (m', m')+-- | Initiate a reader the daemon wasn't following before (adds it to the+-- follow-file).+newReader :: MachineId -> Daemon Machine+newReader id = do+ m <- initAsReader id+ writeFollowFile+ pure m++-- | Try to initiate a reader, but don't fail in case of errors; just log a+-- message.+initReaderNoFail :: MachineId -> Daemon ()+initReaderNoFail id = catchError (initAsReader id $> ()) $ \err -> do+ let (msg, infos) = displayError err+ logErr "Could not initiate reader-mode machine on startup" $ ("init-error", msg) : infos+ t <- liftIO Time.getSystemTime+ insertNewMachine id (UninitialisedReader t)++-- | Updates a (already initialised) machine in the cache with new inputs pulled+-- from IPFS.+refreshAsReader :: MachineId -> Daemon Machine+refreshAsReader id = modifyMachine id refreshwhere+ refresh m = do+ let currentIdx = machineLastIndex m+ (newIdx, is) <- ipfs id $ machineInputsFrom (machineId m) currentIdx+ if currentIdx == Just newIdx+ then do+ logInfo Debug+ "Reader is already up to date"+ [mid, ("input-index", show newIdx)]+ pure (m, m)+ else do+ (m', _) <- addInputs is (pure newIdx) (const (pure ())) m+ logInfo Debug+ "Updated reader"+ [mid, ("n", show (length is)), ("input-index", show newIdx)]+ pure (m', m')mid = ("machine-id", getMachineId id)-- ** Writer-initAsWriter :: MachineId -> Daemon IpfsMachine+initAsWriter :: MachineId -> Daemon MachineinitAsWriter id = dom <- loadMachine Writer idactAsWriter m@@ -482,13 +499,13 @@ initAsWriter id = do-- | Subscribes the daemon to the machine's pubsub topic to listen for-- input requests.-actAsWriter :: IpfsMachine -> Daemon ()+actAsWriter :: Machine -> Daemon ()actAsWriter m = doenv <- ask- _ <- liftIO $ addHandler (chainSubscription m) (daemonHandler env id onMsg)+ _ <- liftIO $ addHandler (machineSubscription m) (daemonHandler env id onMsg)logInfo Normal "Acting as writer" [("machine-id", getMachineId id)]where- id = chainName m+ id = machineId monMsg = \caseSubmit SubmitInputs{..} -> writeInputs id expressions (Just nonce) >> pure ()_ -> pure ()@@ -501,7 +518,7 @@ actAsWriter m = do-- outputs and the given nonce.writeInputs :: MachineId -> [Value] -> Maybe Text -> Daemon [Value]writeInputs id is nonce = do- (rs, idx) <- modifyMachine id $ addInputs is write pub+ (rs, idx) <- modifyMachine id (addInputs is write pub)logInfo Debug "Wrote inputs to IPFS" [ ("machine-id", getMachineId id), ("new-input-index", show idx) ]pure rs@@ -515,36 +532,45 @@ writeInputs id is nonce = dopoll :: Daemon ()poll = domsVar <- asks machines- ms <- liftIO $ CMap.nonAtomicRead (getChains msVar)- traverse_ pollMachine ms+ ms <- liftIO $ CMap.nonAtomicRead (getMachines msVar)+ _ <- Map.traverseWithKey pollMachine ms+ pure ()where- pollMachine :: IpfsMachine -> Daemon ()- pollMachine m@Chain{chainMode = Reader, ..} = do- delta <- liftIO $ sinceLastUpdate m- let (shouldPoll, newPoll) =- case chainPolling of- HighFreq more ->- let more' = more - delta- in if more' > 0- then (True, HighFreq more')- else (False, LowFreq)- -- Low frequency polling is every 10 seconds.- LowFreq -> (delta > lowFreqPollPeriod, LowFreq)- when shouldPoll $ do- logInfo Debug "Polling.." [("machine-id", getMachineId chainName)]- refreshAsReader chainName >> pure ()- modifyMachine chainName $ \m' -> pure (m' { chainPolling = newPoll }, () )- pollMachine _ = pure ()+ pollMachine :: MachineId -> CachedMachine -> Daemon ()+ pollMachine id = \case+ Cached m@Machine{ machineMode = Reader, .. } -> do+ delta <- liftIO $ sinceLastUpdate m+ let (shouldPoll, newPoll) =+ case machinePolling of+ HighFreq more ->+ let more' = more - delta+ in if more' > 0+ then (True, HighFreq more')+ else (False, LowFreq)+ -- Low frequency polling is every 10 seconds.+ LowFreq -> (delta > lowFreqPollPeriod, LowFreq)+ when shouldPoll $ do+ logInfo Debug "Polling.." [("machine-id", getMachineId machineId)]+ refreshAsReader machineId >> pure ()+ modifyMachine machineId $ \m' -> pure (m' { machinePolling = newPoll }, ())+ UninitialisedReader t -> do+ delta <- liftIO $ timeSince t+ when (delta > lowFreqPollPeriod) $ initReaderNoFail id $> ()+ _ -> pure () -- Writers don't require any polling.-- | Returns the amount of time since the last time the machine was-- updated.-sinceLastUpdate :: IpfsMachine -> IO Milliseconds-sinceLastUpdate m = timeDelta (chainLastUpdated m) <$> Time.getSystemTime+sinceLastUpdate :: Machine -> IO Milliseconds+sinceLastUpdate = timeSince . machineLastUpdated++timeSince :: Time.SystemTime -> IO Milliseconds+timeSince x = timeDelta x <$> Time.getSystemTimewhere- timeDelta x y =- case (trunc x, trunc y) of- (Time.MkSystemTime s n, Time.MkSystemTime s' n') -> 1000 * (s' - s) + fromIntegral (n' - n) `div` 1000000- trunc = Time.truncateSystemTimeLeapSecond+ timeDelta a b =+ case (trunc a, trunc b) of+ (Time.MkSystemTime s n, Time.MkSystemTime s' n') -> 1000 * (s' - s) + fromIntegral (n' - n) `div` 1000000+ where+ trunc = Time.truncateSystemTimeLeapSecond-- | Polling loop that looks for changes on all loaded reader machines-- and updates them.diff --git a/exe/Server.hs b/exe/Server.hsdeleted file mode 100644index 5e8aa16..0000000--- a/exe/Server.hs+++ /dev/null@@ -1,238 +0,0 @@--- | This file defines a server that can be used as a *centralized* remote for--- chains.-module Server (main) where--import Protolude hiding (fromStrict, option)--import qualified Data.Aeson as A-import Data.ByteString.Lazy (fromStrict)-import qualified Data.Map as Map-import qualified Data.Sequence as Seq-import qualified Data.Time.Clock.System as Time-import Database.PostgreSQL.Simple- (ConnectInfo(..), Connection, connect)-import Network.Wai.Handler.Warp (run)-import Network.Wai.Middleware.Cors (simpleCors)-import Network.Wai.Middleware.Gzip- (GzipFiles(..), def, gzip, gzipFiles)-import Options.Applicative- ( Parser- , auto- , execParser- , fullDesc- , header- , help- , helper- , info- , long- , metavar- , option- , progDesc- , showDefault- , strOption- , value- )-import Servant- ( (:<|>)(..)- , (:>)- , Capture- , Get- , Handler- , JSON- , Raw- , ServantErr(..)- , Server- , err400- , serve- , serveDirectoryFileServer- )--import Radicle-import Radicle.Daemon.Common-import qualified Radicle.Internal.ConcurrentMap as CMap-import Radicle.Internal.MachineBackend.EvalServer-import Server.DB---- * Types--newtype Exprs = Exprs { getExprs :: Seq Value }- deriving (Generic, Eq, Ord)--type ServerApi- = "chains" :> Capture "chain" Text :> (ChainSubmitEndpoint :<|> ChainSinceEndpoint)- :<|> "outputs" :> Capture "chain" Text :> Get '[JSON] [Maybe A.Value]- :<|> Raw--serverApi :: Proxy ServerApi-serverApi = Proxy--type HttpChains = Chains Text Int ()---- * Helpers---- | Returns the ID of the last inserted expression which is the chain--- length minus one.-insertExpr :: Connection -> HttpChains -> Text -> [Value] -> IO (Either Text Int)-insertExpr conn chains name vals = CMap.modifyValue name (getChains chains) $ \maybeChain -> do- chain <- case maybeChain of- Nothing -> do- logInfo "Creating new machine" [("machine", name)]- t <- Time.getSystemTime- pure $ Chain name pureEnv mempty Nothing Writer () t LowFreq- Just chain' -> pure chain'- case advanceChain chain vals of- Left e -> do- logInfo "Submitted expressions failed to evaluate" [("machine", name)]- pure (Nothing, Left $ renderPrettyDef e)- Right (valsRes, newSt) -> do- traverse_ (insertExprDB conn name) vals- let news = Seq.fromList $ zip vals valsRes- let pairs = chainEvalPairs chain Seq.>< news- let lastIndex = Seq.length pairs - 1- let chain' = chain { chainState = newSt- , chainEvalPairs = pairs- , chainLastIndex = Just lastIndex- }- pure (Just chain', Right lastIndex)----- | Load the state from the DB, returning an MVar with resulting state--- and values.-loadState :: Connection -> IO HttpChains-loadState conn = do- createIfNotExists conn- res <- getAllDB conn- chainPairs <- forM res $ \(name, vals) -> do- let go acc x = eval x >>= \v -> pure (acc Seq.|> (x, v))- let st = runIdentity $ runLang pureEnv $ foldM go mempty vals- case st of- (Left err, _) -> do- logInfo "Failed to load machine" [("machine", name)]- panic $ show err- (Right pairs, st') -> do- t <- Time.getSystemTime- let c = Chain { chainName = name- , chainState = st'- , chainEvalPairs = pairs- , chainLastIndex = Just $ Seq.length pairs - 1- , chainMode = Writer- , chainSubscription = ()- , chainLastUpdated = t- , chainPolling = LowFreq- }- pure (name, c)- --chains' <- newMVar $ Map.fromList chainPairs- chains' <- CMap.fromMap $ Map.fromList chainPairs- logInfo "Loaded machines into memory" [("machine-count", show $ length chainPairs)]- pure $ Chains chains'----- * Handlers---- | Submit something to a chain. The value is expected to be a pair, with the--- first item specifying the chain the value is being submitted to, and the--- second the expressions being submitted. The server either accepts all or--- rejects all expressions (though other systems may not provide this--- guarantee).-submit :: Connection -> HttpChains -> Text -> Values -> Handler Value-submit conn chains name (Values vals) = do- logInfo "Submitted expressions" [("machine", name), ("expression-count", show $ length vals)]- res <- liftIO $ insertExpr conn chains name vals- case res of- Left err -> throwError $ err400 { errBody = fromStrict $ encodeUtf8 err }- Right id -> pure $ Number $ toRational id----- | Get all expressions submitted to a chain since 'index'.-since :: Connection -> Text -> Int -> Handler Values-since conn name index = do- logInfo "Requested expressions" [("machine", name), ("from-index", show index)]- liftIO $ Values <$> getSinceDB conn name index--jsonOutputs :: HttpChains -> Text -> Handler [Maybe A.Value]-jsonOutputs st name = do- maybeChain <- liftIO $ CMap.lookup name (getChains st)- pure $ case maybeChain of- Nothing -> []- Just chain -> toList $ maybeJson . snd <$> chainEvalPairs chain--static :: Server Raw-static = serveDirectoryFileServer "static/"---- * Opts--data Opts = Opts- { connectionInfo :: ConnectInfo- , serverPort :: Int- } deriving (Eq, Show, Read)--opts :: Parser Opts-opts = mkOpts- <$> strOption- ( long "host"- <> help "postgres host"- <> metavar "HOST"- <> showDefault- <> value "localhost"- )- <*> option auto- ( long "pgport"- <> help "postgres port"- <> metavar "PGPORT"- <> showDefault- <> value 5432- )- <*> strOption- ( long "user"- <> help "postgres user"- <> metavar "USER"- <> showDefault- <> value "postgres"- )- <*> strOption- ( long "password"- <> help "postgres password"- <> metavar "PWD"- <> showDefault- <> value ""- )- <*> strOption- ( long "db"- <> help "postgres database name"- <> metavar "DB"- <> showDefault- <> value "radserver"- )- <*> option auto- ( long "port"- <> help "server port"- <> metavar "PORT"- <> showDefault- <> value 8000- )- where- mkOpts h pgp u pw db p = Opts (ConnectInfo h pgp u pw db) p----- * Main--main :: IO ()-main = do- opts' <- execParser allOpts- conn <- connect $ connectionInfo opts'- st <- loadState conn- let gzipSettings = def { gzipFiles = GzipPreCompressed GzipIgnore }- app = simpleCors $ gzip gzipSettings (serve serverApi (server conn st))- logInfo "Start listening" [("port", show $ serverPort opts')]- run (serverPort opts') app- where- allOpts = info (opts <**> helper)- ( fullDesc- <> progDesc "Run a centralized radicle server"- <> header "radicle-server"- )--server :: Connection -> HttpChains -> Server ServerApi-server conn chains = chainEndpoints :<|> jsonOutputs chains :<|> static- where- chainEndpoints chainName = submit conn chains chainName :<|> since conn chainNamediff --git a/exe/Server/DB.hs b/exe/Server/DB.hsdeleted file mode 100644index 6668bb9..0000000--- a/exe/Server/DB.hs+++ /dev/null@@ -1,57 +0,0 @@-{-# OPTIONS_GHC -fno-warn-orphans #-}-module Server.DB where--import Data.List (groupBy, head)-import Database.PostgreSQL.Simple-import Database.PostgreSQL.Simple.FromField (FromField(..))-import Database.PostgreSQL.Simple.FromRow-import Database.PostgreSQL.Simple.ToField (ToField(..))-import Protolude hiding (head)-import Radicle---- | Insert a new value into the DB. Note that this should only be done after--- validating the transaction, and atomically also updating the state.-insertExprDB :: Connection -> Text -> Value -> IO ()-insertExprDB conn name val- = void $ execute conn sql (name, name, val)- where- sql = "INSERT INTO txs (id, chain, expr)"- <> "VALUES ((SELECT (COALESCE(MAX(id),-1) + 1) FROM txs WHERE chain = ?), ?, ?)"--getSinceDB :: Connection -> Text -> Int -> IO [Value]-getSinceDB conn name id- = query conn "SELECT expr FROM txs WHERE chain = ? AND id >= ? ORDER BY id ASC" (name, id)---- | Get all txs in all chains. Useful after a server restart.-getAllDB :: Connection -> IO [(Text, [Value])]-getAllDB conn = do- -- The @ORDER BY@ clauses are important, because- -- * 'groupBy' only groups adjacent items in a list, and- -- * inputs are evaluated in order- res :: [(Int, Text, Value)] <- query_ conn "SELECT id, chain, expr FROM txs ORDER BY chain ASC, id ASC"- -- TODO fold over the results and use a 'Map' to group chain inputs- let grouped :: [[(Text, Value)]]- grouped- = fmap (\(_, a, b) -> (a, b)) <$> groupBy (\(_, l, _) (_, r, _) -> l == r) res- pure [ (fst (head each), snd <$> each) | each <- grouped ]----- | Create the tables if they don't exist-createIfNotExists :: Connection -> IO ()-createIfNotExists conn = void $ execute_ conn sql- where- sql = "CREATE TABLE IF NOT EXISTS txs ("- <> " id integer NOT NULL,"- <> " chain text NOT NULL,"- <> " expr text NOT NULL)"--instance ToField Value where- toField = toField . renderCompactPretty--instance FromField Value where- fromField f bs = fromField f bs >>= \x -> case parse "DB" x of- Left _ -> mzero- Right v -> pure v--instance FromRow Value where- fromRow = fielddiff --git a/images/radicle-server/.dockerignore b/images/radicle-server/.dockerignoredeleted file mode 100644index 720e3c1..0000000--- a/images/radicle-server/.dockerignore+++ /dev/null@@ -1,2 +0,0 @@-*-!/bindiff --git a/images/radicle-server/.gitignore b/images/radicle-server/.gitignoredeleted file mode 100644index 5e56e04..0000000--- a/images/radicle-server/.gitignore+++ /dev/null@@ -1 +0,0 @@-/bindiff --git a/images/radicle-server/Dockerfile b/images/radicle-server/Dockerfiledeleted file mode 100644index 4e0e320..0000000--- a/images/radicle-server/Dockerfile+++ /dev/null@@ -1,16 +0,0 @@-FROM debian:stretch-# The distribution must be the same one the binary is build with to-# ensure binary compatibility. We use the `haskell` images on CI and-# `fpco/stack-build` with when building with `stack build --docker`.--RUN apt-get -qq update && \- apt-get -yqq install libpq5 && \- rm -rf /var/lib/apt/lists/*--ADD ./ /--# Executing the binary ensures that all linked libraries are present-RUN radicle-server --help >/dev/null--EXPOSE 8000-CMD ["/bin/radicle-server"]diff --git a/images/radicle-server/build.sh b/images/radicle-server/build.shdeleted file mode 100755index ed9fee1..0000000--- a/images/radicle-server/build.sh+++ /dev/null@@ -1,15 +0,0 @@-#!/bin/bash--set -eo pipefail--image_root=$(dirname $0)--echo "Building radicle-server in container"-stack build --docker :radicle-server--bin_path=$(stack exec --docker -- which radicle-server)--mkdir -p "$image_root/bin"-cp -a "$bin_path" "$image_root/bin"--docker build -t eu.gcr.io/opensourcecoin/radicle-server $image_rootdiff --git a/images/radicle-server/ci-copy-bin.sh b/images/radicle-server/ci-copy-bin.shdeleted file mode 100755index e6751eb..0000000--- a/images/radicle-server/ci-copy-bin.sh+++ /dev/null@@ -1,14 +0,0 @@-#!/bin/bash--set -eo pipefail--image_root=$(dirname $BASH_SOURCE)--if [ "$STACK_DOCKER" = "1" ]; then- bin_path=$(stack exec --docker -- which radicle-server)-else- bin_path=$(stack exec -- which radicle-server)-fi--mkdir -p "$image_root/bin"-cp -a "$bin_path" "$image_root/bin"diff --git a/images/radicle-server/docker-compose.yaml b/images/radicle-server/docker-compose.yamldeleted file mode 100644index b4bce28..0000000--- a/images/radicle-server/docker-compose.yaml+++ /dev/null@@ -1,23 +0,0 @@-version: '3'--services:- postgres:- image: postgres:11-alpine- ports:- - "15432:5432"- volumes:- - pg-data:/var/lib/postgresql/data- radicle-server:- image: eu.gcr.io/opensourcecoin/radicle-server- build: .- depends_on:- - postgres- command:- - radicle-server- - --host=postgres- - --db=postgres- ports:- - "8000:8000"--volumes:- pg-data: {}diff --git a/package.yaml b/package.yamlindex 30daf7e..b959bf2 100644--- a/package.yaml+++ b/package.yaml@@ -127,26 +127,6 @@ executables:- optparse-applicativeghc-options: -main-is RadicleExe- radicle-server:- main: Server.hs- source-dirs: exe- other-modules: [Server.DB]- dependencies:- - radicle- - aeson- - containers- - bytestring- - optparse-applicative- - postgresql-simple- - servant- - servant-server- - text- - warp- - wai-extra- - wai-cors- - time- ghc-options: -main-is Server-radicle-daemon:main: Daemon.hssource-dirs: exediff --git a/src/Radicle/Daemon/Common.hs b/src/Radicle/Daemon/Common.hsindex 7f6c8ff..80c72e7 100644--- a/src/Radicle/Daemon/Common.hs+++ b/src/Radicle/Daemon/Common.hs@@ -1,8 +1,9 @@module Radicle.Daemon.Common( ReaderOrWriter(..), Polling(..)- , Chain(..)- , Chains(..)+ , Machine(..)+ , CachedMachine(..)+ , CachedMachines(..), logInfo, logErr, advanceChain@@ -11,33 +12,48 @@ module Radicle.Daemon.Commonimport Protolude hiding (log)import qualified Data.Aeson as A-import qualified Data.Sequence as Seqimport qualified Data.Text as Timport qualified Data.Time.Clock.System as Timeimport Radicle+import Radicle.Daemon.Ipfsimport qualified Radicle.Internal.ConcurrentMap as CMap+-- | Indicates if the daemon is the writer or a reader for this machine.data ReaderOrWriter = Reader | Writerderiving (Generic)-data Polling = HighFreq Int64 | LowFreq+data Polling+ -- | Indicates that the daemon is performing high-frequency polling for this+ -- machine. Includes the number of milliseconds for how long this will+ -- continue being the case.+ = HighFreq Int64+ -- | Indicates that the daemon is only performing low-frequency polling for+ -- this machine.+ | LowFreqinstance A.ToJSON ReaderOrWriterinstance A.FromJSON ReaderOrWriter-data Chain id idx subs = Chain- { chainName :: id- , chainState :: Bindings (PrimFns Identity)- , chainEvalPairs :: Seq.Seq (Value, Value)- , chainLastIndex :: Maybe idx- , chainMode :: ReaderOrWriter- , chainSubscription :: subs- , chainLastUpdated :: Time.SystemTime- , chainPolling :: Polling+-- A Cached machine with an initialised state and pubsub subscription.+data Machine = Machine+ { machineId :: MachineId+ , machineState :: Bindings (PrimFns Identity)+ , machineLastIndex :: Maybe MachineEntryIndex+ , machineMode :: ReaderOrWriter+ , machineSubscription :: TopicSubscription+ , machineLastUpdated :: Time.SystemTime+ , machinePolling :: Polling} deriving (Generic)-newtype Chains id idx subs = Chains { getChains :: CMap.CMap id (Chain id idx subs) }+data CachedMachine+ -- | A reader which could not be initialised (probably due to IPNS name not+ -- resolving). Includes the time at which the last failed init was attempted.+ = UninitialisedReader Time.SystemTime+ -- | A cached machine with an active pubsub subscription.+ | Cached Machine++newtype CachedMachines = CachedMachines { getMachines :: CMap.CMap MachineId CachedMachine }-- | Log a message to @stdout@.--@@ -58,9 +74,9 @@ logInfo, logErr :: MonadIO m => Text -> [(Text, Text)] -> m ()logInfo = log "INFO "logErr = log "ERROR"-advanceChain :: Chain id idx subs -> [Value] -> Either (LangError Value) ([Value], Bindings (PrimFns Identity))+advanceChain :: Machine -> [Value] -> Either (LangError Value) ([Value], Bindings (PrimFns Identity))advanceChain chain vals =- let (r_, newSt) = runIdentity $ runLang (chainState chain) $ traverse eval vals+ let (r_, newSt) = runIdentity $ runLang (machineState chain) $ traverse eval valsin case r_ ofLeft e -> Left eRight r -> pure (r, newSt)diff --git a/src/Radicle/Daemon/Ipfs.hs b/src/Radicle/Daemon/Ipfs.hsindex e441814..072d682 100644--- a/src/Radicle/Daemon/Ipfs.hs+++ b/src/Radicle/Daemon/Ipfs.hs@@ -62,6 +62,7 @@ data IpfsError= IpfsDaemonError Ipfs.IpfsException| InternalError Text| NetworkError Text+ | Timeout-- | Messages sent on a machine's IPFS pubsub topic.data Message = New InputsApplied | Submit SubmitInputs@@ -122,7 +123,8 @@ safeIpfs io = ExceptT $ liftIO $(decodeStrict ->Just (Aeson.Object (HashMap.lookup "Message" ->Just (Aeson.String msg))))) -> NetworkError msg- _ -> InternalError (toS (displayException e))+ Http.HttpExceptionRequest _ Http.ResponseTimeout -> InternalError (toS (displayException e))+ _ -> Timeout-- | Write some inputs to an IPFS machine.diff --git a/src/Radicle/Internal/ConcurrentMap.hs b/src/Radicle/Internal/ConcurrentMap.hsindex cb4a4e4..6ef5c28 100644--- a/src/Radicle/Internal/ConcurrentMap.hs+++ b/src/Radicle/Internal/ConcurrentMap.hs@@ -3,7 +3,7 @@ module Radicle.Internal.ConcurrentMap, fromMap, lookup, nonAtomicRead- , insertNew+ , insert, modifyExistingValue, modifyValue, CMap@@ -42,16 +42,12 @@ nonAtomicRead (CMap m_) = dom <- readMVar m_traverse readMVar m--- | Atomically insert a key-value pair into a 'CMap' but only if the--- key is not already a member.-insertNew :: Ord k => k -> v -> CMap k v -> IO (Maybe ())-insertNew k v (CMap m_) = modifyMVar m_ $ \m ->- if Map.member k m- then pure (m, Nothing)- else do- v_ <- newMVar v- let m' = Map.insert k v_ m- pure (m', Just ())+-- | Atomically insert a key-value pair into a 'CMap'.+insert :: Ord k => k -> v -> CMap k v -> IO ()+insert k v (CMap m_) = modifyMVar m_ $ \m -> do+ v_ <- newMVar v+ let m' = Map.insert k v_ m+ pure (m', ())-- | Atomically modifies a value associated to a key but only if it-- exists. There is no guarantee the value is still associated withdiff --git a/test/docker-compose.yaml b/test/docker-compose.yamlindex 2c84979..1eb7a5b 100644--- a/test/docker-compose.yaml+++ b/test/docker-compose.yaml@@ -2,32 +2,9 @@version: '3'services:- postgres:- image: postgres:11-alpine- ports:- - "15432:5432"- volumes:- - pg-data:/var/lib/postgresql/data- radicle-server:- image: eu.gcr.io/opensourcecoin/radicle-server- build: ../images/radicle-server- depends_on:- - postgres- command:- - radicle-server- - --host=postgres- - --db=postgres- ports:- - "8000:8000"-ipfs-test-network:image: eu.gcr.io/opensourcecoin/ipfs-test-networkports:- "19301:5001"command:- --enable-pubsub-experiment---volumes:- pg-data: {}-diff --git a/test/machine-backends.rad b/test/machine-backends.raddeleted file mode 100644index ed79c9f..0000000--- a/test/machine-backends.rad+++ /dev/null@@ -1,87 +0,0 @@-#!/usr/bin/env radicle-;;-;; Test correctness of the IPFS and eval-server machine backends.-;;-;; This script tests that the HTTP server and IPFS implement the-;; machine backend protocol with `machine/eval-server/update!` and-;; `machine/eval-server/get-log!` properly.-;;-;; The script accepts the hostname of the server as an optional argument. The-;; hostname defaults to `localhost`. We always use port 8000.-;;---(load! "rad/prelude.rad")--(import prelude/patterns '[/cons] :unqualified)-(import prelude/test '[assert-equal] :unqualified)-(import prelude/test :as 'test)--(def host- (match (get-args!)- (/cons 'h _) h- /nil "localhost"- ))--(def exprs-1 [ :e1 :e2 ])-(def exprs-2 [ :f1 :f2 :f3 ])--(def server-backend {- :update! machine/eval-server/update!- :get-log! machine/eval-server/get-log!- :create! (fn [] (string-append "http://" host ":8000/chains/" (uuid!)))- })--(def ipfs-backend {- :update! machine/ipfs/update!- :get-log! machine/ipfs/get-log!- :create! (fn [] (machine/ipfs/create! (uuid!)))- })--(def tests- (fn [name backend]- (def update! (lookup :update! backend))- (def create! (lookup :create! backend))- (def get-log! (lookup :get-log! backend))- (test/make-suite name {- "receive-all"- ;; Passing `:nothing` to `get-log!` returns all expressions- (fn []- (def machine-id (create!))- (update! machine-id exprs-1)- (update! machine-id exprs-2)- (def all-exprs (<> exprs-1 exprs-2))- (match (get-log! machine-id :nothing)- [_ 'received-exprs] (assert-equal received-exprs all-exprs))- )-- "receive-last-index"- ;; Passing the last index from `update!` to `get-log!` returns no expressions- (fn []- (def machine-id (create!))- (def index (update! machine-id exprs-1))- (match (get-log! machine-id [:just index])- [_ 'received-exprs] (assert-equal received-exprs []))- )- "receive-with-index"- ;; Passing an index from `update!` to `get-log!` returns no expressions- (fn []- (def machine-id (create!))- (def index (update! machine-id exprs-1))- (update! machine-id exprs-2)- (match (get-log! machine-id [:just index])- [_ 'received-exprs] (assert-equal received-exprs exprs-2))- )- "receive-returns-sent-index"- ;; `get-log!` returns the last sent index- (fn []- (def machine-id (create!))- (def index-send (update! machine-id exprs-1))- (match (get-log! machine-id :nothing)- ['index-receive _] (assert-equal index-receive index-send))- )- })- ))--(def tests-ok (test/run-all (<> (tests "server" server-backend) (tests "ipfs" ipfs-backend))))-(if tests-ok (exit! 0) (exit! 1))