A peer-to-peer stack for code collaboration
Server persistence
Julian Arni84e7665abb5d
diff --git a/cloudbuild.yaml b/cloudbuild.yamlindex 22ca6bb..a14b17f 100644--- a/cloudbuild.yaml+++ b/cloudbuild.yaml@@ -33,7 +33,13 @@ steps:- id: "Test & Build"name: 'haskell:8.4.3'env: ['STACK_ROOT=/workspace/.stack']- args: ['stack', 'build', '--fast', '--test', '--no-terminal', '--pedantic']+ entrypoint: bash+ args:+ - '-c'+ - |+ apt-get update+ apt-get -y install postgresql libpq-dev+ stack build --fast --test --no-terminal --pedantic- id: "Save cache"name: gcr.io/cloud-builders/gsutildiff --git a/exe/Server/Client.hs b/exe/Server/Client.hsindex 42ddf0e..74339eb 100644--- a/exe/Server/Client.hs+++ b/exe/Server/Client.hs@@ -114,4 +114,4 @@ identV = Keyword . unsafeToIdentsubmit :: Value -> ClientM ()since :: Text -> Int -> ClientM [Value]-submit :<|> since :<|> _ = client api+submit :<|> since :<|> _ :<|> _ = client apidiff --git a/exe/Server/DB.hs b/exe/Server/DB.hsnew file mode 100644index 0000000..a659766--- /dev/null+++ b/exe/Server/DB.hs@@ -0,0 +1,51 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+module 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 index+ = query conn "SELECT expr FROM txs WHERE chain = ? AND id >= ?" (name, index)++-- | Get all txs in all chains. Useful after a server restart.+getAllDB :: Connection -> IO [(Text, [Value])]+getAllDB conn = do+ res <- query_ conn "SELECT chain, expr FROM txs"+ let grouped = groupBy (\l r -> fst l == fst 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/exe/Server/Server.hs b/exe/Server/Server.hsindex 73aad28..ecdd1d4 100644--- a/exe/Server/Server.hs+++ b/exe/Server/Server.hs@@ -1,101 +1,205 @@+-- | This file defines a server that can be used as a *centralized* remote for+-- chains.module Server where-import API+import Protolude hiding (fromStrict, option)+import qualified Data.Aeson as Aimport Data.ByteString.Lazy (fromStrict)+import qualified Data.Map as Mapimport qualified Data.Sequence as Seq-import Network.Wai.Handler.Warp-import Network.Wai.Middleware.Cors+import Database.PostgreSQL.Simple+ (ConnectInfo(..), Connection, connect)+import Network.Wai.Handler.Warp (run)+import Network.Wai.Middleware.Cors (simpleCors)import Network.Wai.Middleware.Gzip-import Protolude hiding (fromStrict)-import Radicle+ (GzipFiles(..), def, gzip, gzipFiles)+import Options.Applicative+ ( Parser+ , auto+ , execParser+ , fullDesc+ , header+ , help+ , helper+ , info+ , long+ , metavar+ , option+ , progDesc+ , showDefault+ , strOption+ , value+ )import Servant-import qualified STMContainers.Map as STMMap+ ( (:<|>)(..)+ , Handler+ , Raw+ , ServantErr(..)+ , Server+ , err400+ , serve+ , serveDirectoryFileServer+ )--- * Main+import API+import DB+import Radicle-main :: IO ()-main = do- st <- newState- let gzipSettings = def { gzipFiles = GzipPreCompressed GzipIgnore }- app = simpleCors $ gzip gzipSettings (serve api (server st))- args <- getArgs- case args of- [portStr] -> case readEither portStr of- Right port -> run port app- Left _ -> die "Expecting argument to be a port (integer)"- [] -> run 80 app- _ -> die "Expecting zero or one arguments (port)"+-- * Types++newtype Exprs = Exprs { getExprs :: Seq Value }+ deriving (Generic, Eq, Ord)++data Chain = Chain+ { chainName :: Text+ , chainState :: Bindings (PrimFns Identity)+ , chainEvalPairs :: Seq.Seq (Value, Value)+ } deriving (Generic)+-- For efficiency we might want keys to also be mvars, but efficiency doesn't+-- matter for a test server.+newtype Chains = Chains { getChains :: MVar (Map Text Chain) }-server :: Chains -> Server API-server st = submit st :<|> since st :<|> jsonOutputs st :<|> static+-- * Helpers++insertExpr :: Connection -> Chains -> Text -> Value -> IO (Either Text ())+insertExpr conn chains name val = modifyMVar (getChains chains) $ \c -> do+ let x = Map.lookup name c+ let chain = fromMaybe (Chain name pureEnv mempty) x+ let (r, newSt) = runIdentity $ runLang (chainState chain) (eval val)+ case r of+ Left e -> pure . (c ,) . Left $ "invalid expression: " <> show e+ Right valRes -> do+ insertExprDB conn name val+ let chain' = chain { chainState = newSt+ , chainEvalPairs = chainEvalPairs chain Seq.|> (val, valRes)+ }+ pure (Map.insert name chain' c, Right ())+++-- | Load the state from the DB, returning an MVar with resulting state+-- and values.+loadState :: Connection -> IO Chains+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, _) -> panic $ show err+ (Right pairs, st') -> do+ let c = Chain { chainName = name+ , chainState = st'+ , chainEvalPairs = pairs+ }+ pure (name, c)+ chains' <- newMVar $ Map.fromList 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 expression being submitted.-submit :: Chains -> Value -> Handler ()-submit st val = case val of+submit :: Connection -> Chains -> Value -> Handler ()+submit conn chains val = case val ofList [String i, v] -> do- r <- liftIO . atomically $ insertExpr st i v- case r of- Right () -> pure ()- Left err -> throwError- $ err400 { errBody = fromStrict $ encodeUtf8 err }+ res <- liftIO $ insertExpr conn chains i v+ case res of+ Left err -> throwError $ err400 { errBody = fromStrict $ encodeUtf8 err }+ Right _ -> pure ()_ -> throwError$ err400 { errBody = "Expecting pair with chain name and val" }-getActivitySince :: Chains -> Text -> Int -> Handler [(Value, Value)]-getActivitySince st name index = do- r <- liftIO . atomically $ getSince st name index- case r of- Nothing -> throwError $ err400 { errBody = "No such chain/index" }- Just v -> pure v--- | Get all expressions submitted to a chain since 'index'.-since :: Chains -> Text -> Int -> Handler [Value]-since st name index =- fmap fst <$> getActivitySince st name index+since :: Connection -> Text -> Int -> Handler [Value]+since conn name index = liftIO $ getSinceDB conn name indexjsonOutputs :: Chains -> Text -> Handler [Maybe A.Value]jsonOutputs st name = do- vs <- fmap snd <$> getActivitySince st name 0- pure (maybeJson <$> vs)+ chains <- liftIO . readMVar $ getChains st+ pure $ case Map.lookup name chains of+ Nothing -> []+ Just chain -> toList $ maybeJson . snd <$> chainEvalPairs chainstatic :: Server Rawstatic = serveDirectoryFileServer "static/"--- * Helpers+-- * 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 "ort"+ <> help "server port"+ <> metavar "PORT"+ <> showDefault+ <> value 8000+ )+ where+ mkOpts h pgp u pw db p = Opts (ConnectInfo h pgp u pw db) p-insertExpr :: Chains -> Text -> Value -> STM (Either Text ())-insertExpr st name val = do- x <- STMMap.lookup name $ getChains st- let chain = fromMaybe (Chain name pureEnv mempty) x- let (r, s) = runIdentity $ runLang (chainState chain) (eval val)- case r of- Left e -> pure . Left $ "invalid expression: " <> show e- Right o -> Right <$> STMMap.insert- (chain { chainState = s- , chainExprs = chainExprs chain Seq.|> (val, o) })- name- (getChains st)--getSince :: Chains -> Text -> Int -> STM (Maybe [(Value, Value)])-getSince st name index = do- x <- STMMap.lookup name $ getChains st- pure $ toList . Seq.drop index . chainExprs <$> x--- * Types+-- * 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 api (server conn st))+ run (serverPort opts') app+ where+ allOpts = info (opts <**> helper)+ ( fullDesc+ <> progDesc "Run a centralized radicle server"+ <> header "radicle-server"+ )-data Chain = Chain- { chainName :: Text- , chainState :: Bindings (PrimFns Identity)- , chainExprs :: Seq (Value, Value)- } deriving (Generic)-newtype Chains = Chains { getChains :: STMMap.Map Text Chain }-newState :: IO Chains-newState = Chains <$> STMMap.newIO+server :: Connection -> Chains -> Server API+server conn st = submit conn st :<|> since conn :<|> jsonOutputs st :<|> staticdiff --git a/nix/shell.nix b/nix/shell.nixindex de0fe15..46a8a0c 100644--- a/nix/shell.nix+++ b/nix/shell.nix@@ -13,7 +13,7 @@ instdenv.mkDerivation {name = "radicle-dev";- buildInputs = [ ghc zlib python3 wget stack ]+ buildInputs = [ ghc zlib python3 wget stack postgresql glibcLocales ]++ (if doc then [docstuffs postgresql] else [])++ (if extras then [ vimPlugins.stylish-haskell haskellPackages.apply-refact hlint ] else []);libraryPkgconfigDepends = [ zlib ];@@ -21,7 +21,11 @@ stdenv.mkDerivation {eval $(grep export ${ghc}/bin/ghc)alias check="pushd $PWD && ./scripts/check-fmt.sh && hlint . && popd"alias mkdocs="pushd $PWD/docs && make html && popd"- alias sb="stack build --system-ghc --nix-packages zlib"+ alias sb="stack build --fast --system-ghc --nix-packages zlib"+ alias sbs="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle-server"+ alias sbc="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle-client"alias st="stack test --fast --system-ghc --nix-packages zlib"+ alias server="stack exec radicle-server -- "+ alias client="stack exec radicle-client -- --config rad/repl.rad"'';}diff --git a/package.yaml b/package.yamlindex 1589640..3464bba 100644--- a/package.yaml+++ b/package.yaml@@ -89,18 +89,17 @@ executables:radicle-server:main: Server.hssource-dirs: exe/Server- other-modules: API+ other-modules: [API, DB]when:- condition: impl(ghcjs)buildable: falsedependencies:- radicle- - optparse-applicative- bytestring+ - optparse-applicative+ - postgresql-simple- servant- servant-server- - stm-containers- - stm- warp- wai-extra- wai-corsdiff --git a/stack.yaml b/stack.yamlindex 11eeef3..53f1355 100644--- a/stack.yaml+++ b/stack.yaml@@ -42,6 +42,7 @@ packages:extra-deps:- serialise-0.2.0.0- cborg-0.2.0.0+- acid-state-0.14.3image:containers: