From e24e15745b4bcff806f5c24e22fd185b9150b074 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:27:48 +0000 Subject: [PATCH 001/159] tests: time out store log write, database operation, TLS handshake and file receive --- tests/CoreTests/MsgStoreTests.hs | 21 ++++++++++++++++++--- tests/XFTPServerTests.hs | 18 ++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index f680f4701..92448dd6e 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -15,6 +15,7 @@ module CoreTests.MsgStoreTests where import AgentTests.FunctionalAPITests (runRight_) +import Control.Concurrent (threadDelay) import Control.Concurrent.STM import Control.Exception (bracket) import Control.Monad @@ -33,16 +34,18 @@ import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.NtfStore import Simplex.Messaging.Server.QueueStore import Simplex.Messaging.Server.QueueStore.QueueInfo -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..)) +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), withLog') import Simplex.Messaging.Server.QueueStore.Types +import Simplex.Messaging.Server.StoreLog (closeStoreLog, openWriteStoreLog) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM +import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Util #if defined(dbServerPostgres) import AgentTests.FunctionalAPITests (runRight) -import Control.Concurrent (forkIO, threadDelay) +import Control.Concurrent (forkIO) import qualified Control.Exception as E import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB @@ -51,7 +54,6 @@ import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) import Simplex.Messaging.Server.MsgStore.Postgres import Simplex.Messaging.Server.QueueStore.Postgres import SMPClient (testStoreDBOpts) -import System.Timeout (timeout) #endif msgStoreTests :: Spec @@ -59,6 +61,7 @@ msgStoreTests = do describe "STM message store" $ do someMsgStoreTests testSMTStoreConfig it "should remove deleted queues from queue store maps" $ withMsgStore testSMTStoreConfig testDeleteQueueMaps + it "should time out store log write" testStoreLogTimeout #if defined(dbServerPostgres) describe "Postgres-only message store" $ do someMsgStoreTests testPostgresStoreConfig @@ -66,6 +69,7 @@ msgStoreTests = do it "tryDelPeekMsg (ACK not from NSE) should reset message counts when queue is empty" $ withMsgStore testPostgresStoreConfig testResetMessageCounts it "should expire messages across commit batches" $ withMsgStore testPostgresStoreConfig testExpireMessagesInBatches it "should fail database operations after the store is closed" $ withMsgStore testPostgresStoreConfig testClosedStore + it "should time out database operation" $ withMsgStore testPostgresStoreConfig testDBOperationTimeout #endif describe "Notification store" $ do it "should remove keys of expired notifications" testExpireNtfs @@ -323,6 +327,13 @@ testDeleteQueueMaps ms = do where expectAuth = either (`shouldBe` AUTH) (\_ -> expectationFailure "deleted queue is still found") +testStoreLogTimeout :: HasTestEnv => IO () +testStoreLogTimeout = do + sl <- openWriteStoreLog False $ testPath "store.log" + sl_ <- newTVarIO $ Just sl + timeout 100000 (withLog' "test" sl_ $ \_ -> threadDelay 500000) `shouldReturn` Nothing + closeStoreLog sl + mkMsgNtf :: TVar ChaChaDRG -> Int64 -> IO MsgNtf mkMsgNtf g ts = do ntfMsgId <- atomically $ randomMsgId 24 g @@ -492,4 +503,8 @@ testClosedStore ms = do Just (Left (_ :: E.SomeException)) -> pure () Just (Right (_ :: [Only Int])) -> expectationFailure "query succeeded on a closed store" Nothing -> expectationFailure "query waited on a closed store" + +testDBOperationTimeout :: PostgresMsgStore -> IO () +testDBOperationTimeout ms = + timeout 100000 (runExceptT $ withDB' "test" (queueStore ms) $ \_ -> threadDelay 500000) `shouldReturn` Nothing #endif diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 347bc444d..b81547b7d 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -32,14 +32,14 @@ import Data.X509.Validation (Fingerprint (..), getFingerprint) import Network.HPACK.Token (tokenKey) import qualified Network.HTTP2.Client as H2 import qualified Network.TLS as T -import SMPClient (copyWebCredential, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn') +import SMPClient (copyWebCredential, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn, withStallingServerOn') import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A import Simplex.FileTransfer.Description (kb) import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpEncodeAuthTransmission) import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..)) -import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), pattern VersionXFTP) +import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), receiveFile, pattern VersionXFTP) import Simplex.Messaging.Client (NetworkConfig (..), NetworkTimeout (..), ProtocolClientError (..), defaultNetworkConfig) import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.Lazy as LC @@ -74,6 +74,8 @@ xftpServerTests = do it "should expire chunks after set interval" testFileChunkExpiration it "should disconnect inactive clients" testInactiveClientExpiration it "should close connection when connecting client is cancelled" $ \_ -> testCancelledClientConnect + it "should time out TLS handshake when TLS errors are logged" $ \_ -> testTLSHandshakeTimeout + it "should time out receiving file chunk" $ \_ -> testReceiveFileTimeout it "should not allow uploading chunks after specified storage quota" testFileStorageQuota it "should release storage of interrupted uploads" testInterruptedUploadStorage it "should store file records to log and restore them after server restart" testFileLog @@ -256,6 +258,18 @@ testCancelledClientConnect = cancel a timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testTLSHandshakeTimeout :: HasTestEnv => Expectation +testTLSHandshakeTimeout = + withStallingServerOn xftpTestPort $ + timeout 1000000 (runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort Nothing $ \(_ :: TLS 'TClient) -> pure ()) + `shouldReturn` Nothing + where + cfg = defaultTransportClientConfig {logTLSErrors = True} + +testReceiveFileTimeout :: HasTestEnv => Expectation +testReceiveFileTimeout = + timeout 100000 (runExceptT $ receiveFile (\_ -> "" <$ threadDelay maxBound) $ XFTPRcvChunkSpec testChunkPath chSize "") `shouldReturn` Nothing + testFileStorageQuota :: HasTestEnv => AFStoreType -> Expectation testFileStorageQuota fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileSizeQuota = Just $ chSize * 2}) $ \_ -> testXFTPClient $ \c -> runRight_ $ do From bb8c7865f80627fc5b42926d99b71a09b3ace9bb Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:31:29 +0000 Subject: [PATCH 002/159] agent, servers, transport: stop cancelled and timed-out operations --- src/Simplex/FileTransfer/Agent.hs | 6 +++--- src/Simplex/FileTransfer/Client/Agent.hs | 4 ++-- src/Simplex/FileTransfer/Server/Store/Postgres.hs | 4 ++-- src/Simplex/FileTransfer/Transport.hs | 1 + src/Simplex/Messaging/Agent.hs | 4 ++-- src/Simplex/Messaging/Agent/Client.hs | 2 +- src/Simplex/Messaging/Notifications/Server.hs | 15 ++++++++------- src/Simplex/Messaging/Notifications/Server/Env.hs | 3 ++- .../Messaging/Server/QueueStore/Postgres.hs | 4 ++-- src/Simplex/Messaging/Server/QueueStore/STM.hs | 2 +- src/Simplex/Messaging/Transport.hs | 6 +++--- src/Simplex/Messaging/Util.hs | 5 +++++ tests/CoreTests/UtilTests.hs | 7 +++++++ 13 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index 9165d01b3..d24b5b8a9 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -81,7 +81,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (strDecode, strEncode) import Simplex.Messaging.Protocol (ProtocolServer, ProtocolType (..), XFTPServer) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (allFinally, catchAll_, catchAllErrors, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) +import Simplex.Messaging.Util (allFinally, catchAllErrors, catchOwn_, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) import System.FilePath (takeFileName, ()) import UnliftIO import UnliftIO.Directory @@ -360,7 +360,7 @@ xftpDeleteRcvFiles' c rcvFileEntityIds = do void $ batchFiles updateRcvFileDeleted toMarkDeleted workPath <- getXFTPWorkPath liftIO . forM_ toDelete $ \RcvFile {prefixPath} -> - (removePath . (workPath )) prefixPath `catchAll_` pure () + (removePath . (workPath )) prefixPath `catchOwn_` pure () where fileComplete RcvFile {status} = status == RFSComplete || status == RFSError batchFiles :: (DB.Connection -> DBRcvFileId -> IO a) -> [RcvFile] -> AM' [Either AgentErrorType a] @@ -669,7 +669,7 @@ deleteSndFilesInternal c sndFileEntityIds = flip E.finally (atomically $ mapM_ ( let (toDelete, toMarkDeleted) = partition fileComplete sndFiles workPath <- getXFTPWorkPath liftIO . forM_ toDelete $ \SndFile {prefixPath} -> - mapM_ (removePath . (workPath )) prefixPath `catchAll_` pure () + mapM_ (removePath . (workPath )) prefixPath `catchOwn_` pure () batchFiles_ deleteSndFile' toDelete batchFiles_ updateSndFileDeleted toMarkDeleted where diff --git a/src/Simplex/FileTransfer/Client/Agent.hs b/src/Simplex/FileTransfer/Client/Agent.hs index 55cae5d3c..0462b2450 100644 --- a/src/Simplex/FileTransfer/Client/Agent.hs +++ b/src/Simplex/FileTransfer/Client/Agent.hs @@ -34,7 +34,7 @@ import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ProtocolServer (..), XFTPServer) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (catchAll_) +import Simplex.Messaging.Util (catchOwn_) import UnliftIO type XFTPClientVar = TMVar (Either XFTPClientAgentError XFTPClient) @@ -132,5 +132,5 @@ closeXFTPServerClient XFTPClientAgent {xftpClients, config} srv = closeClient cVar = do let NetworkConfig {tcpConnectTimeout} = xftpNetworkConfig $ xftpConfig config netTimeoutInt tcpConnectTimeout NRMBackground `timeout` atomically (readTMVar cVar) >>= \case - Just (Right client) -> closeXFTPClient client `catchAll_` pure () + Just (Right client) -> closeXFTPClient client `catchOwn_` pure () _ -> pure () diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index c9e83c4c5..af040e902 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -56,7 +56,7 @@ import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) import Simplex.Messaging.Server.QueueStore.Postgres () import Simplex.Messaging.Server.StoreLog (openWriteStoreLog) import Simplex.Messaging.SystemTime (roundedSeconds) -import Simplex.Messaging.Util (firstRow, tshow) +import Simplex.Messaging.Util (catchOwn', firstRow, tshow) import System.Directory (renameFile) import System.Exit (exitFailure) import System.IO (IOMode (..), hFlush, stdout) @@ -196,7 +196,7 @@ rowToFileRec (sId, size, digest, sndKeyBs, path, createdAt, expiresAt, status) = withDB :: forall a. Text -> PostgresFileStore -> (DB.Connection -> IO (Either XFTPErrorType a)) -> ExceptT XFTPErrorType IO a withDB op st action = - ExceptT $ E.try (withTransaction (dbStore st) action) >>= either logErr pure + ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either XFTPErrorType a) logErr e = logError ("STORE: " <> err) $> Left INTERNAL diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index 219e65408..bd6c84946 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -204,6 +204,7 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receive h sz = hReceiveFile getBody h sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, + E.Handler $ \(e :: E.SomeAsyncException) -> E.throwIO e, E.Handler $ \(e :: E.SomeException) -> logError (err e) $> Left FILE_IO ] err e = "receiveFile error: " <> tshow e diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 65a6d05b0..2c3b613ec 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -292,7 +292,7 @@ getSMPAgentClient_ clientId cfg initServers@InitialAgentServers {smp, xftp, netC runAgent = do liftIO $ checkServers "SMP" smp >> checkServers "XFTP" xftp currentTs <- liftIO getCurrentTime - notices <- liftIO $ withTransaction store (`getClientNotices` presetServers) `catchAll_` pure [] + notices <- liftIO $ withTransaction store (`getClientNotices` presetServers) `catchOwn_` pure [] c@AgentClient {acThread} <- liftIO . newAgentClient clientId initServers currentTs notices =<< ask t <- runAgentThreads c `forkFinally` const (liftIO $ disconnectAgentClient c) atomically . writeTVar acThread . Just =<< mkWeakThreadId t @@ -2803,7 +2803,7 @@ runSmpQueueMsgDelivery c@AgentClient {subQ} sq@SndQueue {userId, connId, server, notifyDel msgId $ MERR (unId msgId) err msgIds_ <- withStore' c $ \db -> do msgIds_ <- getExpiredSndMessages db connId sq expireTs - forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchAll_` pure () + forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchOwn_` pure () pure msgIds_ forM_ (L.nonEmpty msgIds_) $ \msgIds -> do notify $ MERRS (L.map unId msgIds) err diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 6712075b6..aa2fb8616 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -1083,7 +1083,7 @@ closeClient_ c v = do NetworkConfig {tcpConnectTimeout} <- getNetworkConfig c E.handle (\BlockedIndefinitelyOnSTM -> pure ()) $ netTimeoutInt tcpConnectTimeout NRMBackground `timeout` atomically (readTMVar $ sessionVar v) >>= \case - Just (Right client) -> closeProtocolServerClient (protocolClient client) `catchAll_` pure () + Just (Right client) -> closeProtocolServerClient (protocolClient client) `catchOwn_` pure () _ -> pure () closeXFTPServerClient :: AgentClient -> UserId -> XFTPServer -> FileDigest -> IO () diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index 30dc00b6a..1ae5eae75 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -24,7 +24,6 @@ where import Control.Concurrent (threadDelay) import Control.Concurrent.Async (mapConcurrently) -import qualified Control.Exception as E import Control.Logger.Simple import Control.Monad import Control.Monad.Except @@ -501,12 +500,14 @@ subscribeNtfs NtfSubscriber {smpSubscribers, subscriberSeq, smpAgent = ca} st sm createSMPSubscriber :: SMPSubscriberVar -> IO (Maybe SMPSubscriber) createSMPSubscriber v = - E.handle (\(e :: SomeException) -> logError ("SMP subscriber exception: " <> tshow e) >> removeSubscriber v) $ do - q <- newTQueueIO - tId <- mkWeakThreadId =<< forkIO (runSMPSubscriber smpServer srvId q) - let sub = SMPSubscriber {smpServer, smpServerId = srvId, subscriberSubQ = q, subThreadId = tId} - atomically $ putTMVar (sessionVar v) sub -- this makes it available for other threads - pure $ Just sub + ( do + q <- newTQueueIO + tId <- mkWeakThreadId =<< forkIO (runSMPSubscriber smpServer srvId q) + let sub = SMPSubscriber {smpServer, smpServerId = srvId, subscriberSubQ = q, subThreadId = tId} + atomically $ putTMVar (sessionVar v) sub -- this makes it available for other threads + pure $ Just sub + ) + `catchOwn'` \e -> logError ("SMP subscriber exception: " <> tshow e) >> removeSubscriber v waitForSMPSubscriber :: SMPSubscriberVar -> IO (Maybe SMPSubscriber) waitForSMPSubscriber v = diff --git a/src/Simplex/Messaging/Notifications/Server/Env.hs b/src/Simplex/Messaging/Notifications/Server/Env.hs index 1ad6e09b6..0395f93ef 100644 --- a/src/Simplex/Messaging/Notifications/Server/Env.hs +++ b/src/Simplex/Messaging/Notifications/Server/Env.hs @@ -64,7 +64,7 @@ import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport (ASrvTransport, SMPServiceRole (..), ServiceCredentials (..), THandleParams, TransportPeer (..)) import Simplex.Messaging.Transport.Credentials (genCredentials, tlsCredentials) import Simplex.Messaging.Transport.Server (AddHTTP, ServerCredentials, TransportServerConfig, loadFingerprint, loadServerCredential) -import Simplex.Messaging.Util (liftEitherWith, tshow) +import Simplex.Messaging.Util (isAsyncCancellation, liftEitherWith, tshow) import Simplex.Messaging.Util () import System.Exit (exitFailure) import System.Mem.Weak (Weak) @@ -210,6 +210,7 @@ getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInter E.try (getSessVarIO (pushClientSeq s) pp (pushClients s) ts >>= either (newPushClient s pp) waitForPushClient) >>= \case Right result -> pure result Left e + | isAsyncCancellation e -> E.throwIO e | n < 2 -> do logError $ "getPushClient error (" <> tshow pp <> "): " <> tshow (e :: E.SomeException) loop diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 66e9a91f3..9c6e8d84a 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -89,7 +89,7 @@ import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport (SMPServiceRole (..)) -import Simplex.Messaging.Util (eitherToMaybe, firstRow, maybeFirstRow, maybeFirstRow', tshow, (<$$>), ($>>=)) +import Simplex.Messaging.Util (catchOwn', eitherToMaybe, firstRow, maybeFirstRow, maybeFirstRow', tshow, (<$$>), ($>>=)) import System.Exit (exitFailure) import System.IO (IOMode (..), hFlush, stdout) import UnliftIO.STM @@ -636,7 +636,7 @@ withDB' op st action = withDB op st $ fmap Right . action withDB :: forall a q. Text -> PostgresQueueStore q -> (DB.Connection -> IO (Either ErrorType a)) -> ExceptT ErrorType IO a withDB op st action = - ExceptT $ E.try (withTransaction (dbStore st) action) >>= either logErr pure + ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either ErrorType a) logErr e = logError ("STORE: " <> err) $> Left (STORE err) diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index 3e59fd717..b1ed8cc13 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -427,7 +427,7 @@ readQueueRecIO qr = maybe (Left AUTH) Right <$> readTVarIO qr withLog' :: Text -> TVar (Maybe (StoreLog 'WriteMode)) -> (StoreLog 'WriteMode -> IO ()) -> IO (Either ErrorType ()) withLog' name sl action = readTVarIO sl - >>= maybe (pure $ Right ()) (E.try . E.uninterruptibleMask_ . action >=> bimapM logErr pure) + >>= maybe (pure $ Right ()) (E.uninterruptibleMask_ . E.try . action >=> bimapM logErr pure) where logErr :: E.SomeException -> IO ErrorType logErr e = logError ("STORE: " <> err) $> STORE err diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 7ec590264..4fcf9ead4 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -143,7 +143,7 @@ import Simplex.Messaging.Server.Information import Simplex.Messaging.SystemTime (SystemSeconds) import Simplex.Messaging.Transport.Buffer import Simplex.Messaging.Transport.Shared -import Simplex.Messaging.Util (bshow, catchAll, catchAll_, liftEitherWith, stateTVar', (<$$>)) +import Simplex.Messaging.Util (bshow, catchOwn', catchOwn_, liftEitherWith, stateTVar', (<$$>)) import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal import System.IO.Error (isEOFError) @@ -355,7 +355,7 @@ connectTLS host_ TransportConfig {logTLSErrors} params sock = E.bracketOnError (T.contextNew sock params) closeTLS $ \ctx -> logHandshakeErrors (T.handshake ctx) $> ctx where - logHandshakeErrors = if logTLSErrors then (`catchAll` logThrow) else id + logHandshakeErrors = if logTLSErrors then (`catchOwn'` logThrow) else id logThrow e = putStrLn ("TLS error" <> host <> ": " <> show e) >> E.throwIO e host = maybe "" (\h -> " (" <> h <> ")") host_ @@ -380,7 +380,7 @@ closeTLS :: T.Context -> IO () closeTLS ctx = T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here `E.finally` T.contextClose ctx - `catchAll_` pure () + `catchOwn_` pure () defaultSupportedParams :: T.Supported defaultSupportedParams = diff --git a/src/Simplex/Messaging/Util.hs b/src/Simplex/Messaging/Util.hs index de7ba9236..a3a612d1d 100644 --- a/src/Simplex/Messaging/Util.hs +++ b/src/Simplex/Messaging/Util.hs @@ -41,6 +41,7 @@ module Simplex.Messaging.Util isAsyncCancellation, catchOwn', catchOwn, + catchOwn_, tryAllOwnErrors, tryAllOwnErrors', catchAllOwnErrors, @@ -335,6 +336,10 @@ catchOwn action handleInternal = run action `E.catch` \e -> if isAsyncCancellation e then E.throwIO e else run (handleInternal e) {-# INLINE catchOwn #-} +catchOwn_ :: IO a -> IO a -> IO a +catchOwn_ a = catchOwn' a . const +{-# INLINE catchOwn_ #-} + tryAllOwnErrors :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> ExceptT e m (Either e a) tryAllOwnErrors action = ExceptT $ Right <$> runExceptT action `catchOwn` (pure . Left . fromSomeException) {-# INLINE tryAllOwnErrors #-} diff --git a/tests/CoreTests/UtilTests.hs b/tests/CoreTests/UtilTests.hs index c274cbf32..5819f0bf5 100644 --- a/tests/CoreTests/UtilTests.hs +++ b/tests/CoreTests/UtilTests.hs @@ -108,6 +108,13 @@ utilTests = do runExceptT (throwAsync ThreadKilled `catchAllOwnErrors` handleCatch) `shouldThrow` (\e -> e == ThreadKilled) it "should not throw if there are no errors" $ runExceptT (noErrors `catchAllOwnErrors` throwError) `shouldReturn` Right "no errors" + describe "catchOwn_" $ do + it "should catch SomeException" $ + (throwIO (userError "error") `catchOwn_` pure "caught") `shouldReturn` "caught" + it "should catch StackOverflow" $ + (throwIO StackOverflow `catchOwn_` pure "caught") `shouldReturn` "caught" + it "should rethrow ThreadKilled" $ + (throwIO ThreadKilled `catchOwn_` pure "caught") `shouldThrow` (\e -> e == ThreadKilled) where throwTestError :: ExceptT TestError IO String throwTestError = throwError $ TestError "error" From 29c0b3891de748bf8712a6541e7ec8064f36a7c1 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:44:56 +0000 Subject: [PATCH 003/159] tests: set the type of the TLS client config in the handshake timeout test --- tests/XFTPServerTests.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index b81547b7d..7c3c5a60d 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -264,6 +264,7 @@ testTLSHandshakeTimeout = timeout 1000000 (runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort Nothing $ \(_ :: TLS 'TClient) -> pure ()) `shouldReturn` Nothing where + cfg :: TransportClientConfig cfg = defaultTransportClientConfig {logTLSErrors = True} testReceiveFileTimeout :: HasTestEnv => Expectation From 5412061287e61d291694093e4007e441bbaa5067 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:45:06 +0000 Subject: [PATCH 004/159] ntf server: subscribe after a cancelled SMP subscriber creation --- src/Simplex/Messaging/Notifications/Server.hs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index 1ae5eae75..ae264e548 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -490,14 +490,11 @@ subscribeSrvSubs ca st batchSize (srv, srvId, service_) = do -- this function is concurrency-safe - only onle subscriber per server can be created at a time, -- other threads would wait for the first thread to create it. subscribeNtfs :: NtfSubscriber -> NtfPostgresStore -> SMPServer -> Int64 -> ServerNtfSub -> IO () -subscribeNtfs NtfSubscriber {smpSubscribers, subscriberSeq, smpAgent = ca} st smpServer srvId ntfSub = - getSubscriberVar - >>= either createSMPSubscriber waitForSMPSubscriber +subscribeNtfs NtfSubscriber {smpSubscribers, subscriberSeq, smpAgent = ca} st smpServer srvId ntfSub = do + ts <- getCurrentTime + withGetSessVar' subscriberSeq smpServer smpSubscribers ts createSMPSubscriber waitForSMPSubscriber >>= mapM_ (\sub -> atomically $ writeTQueue (subscriberSubQ sub) ntfSub) where - getSubscriberVar :: IO (Either SMPSubscriberVar SMPSubscriberVar) - getSubscriberVar = getSessVarIO subscriberSeq smpServer smpSubscribers =<< getCurrentTime - createSMPSubscriber :: SMPSubscriberVar -> IO (Maybe SMPSubscriber) createSMPSubscriber v = ( do From f7bc4998a67431798e9fd761135f27511a2a74f9 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:24:54 +0000 Subject: [PATCH 005/159] agent: rethrow a cancellation during the reconnect of a pooled PostgreSQL connection --- src/Simplex/Messaging/Agent/Store/Postgres/Common.hs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs index ca470912f..96eed47e9 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs @@ -34,7 +34,7 @@ import qualified Database.PostgreSQL.Simple as PSQL import qualified Database.PostgreSQL.Simple.Transaction as PSQL import Numeric.Natural (Natural) import Simplex.Messaging.Agent.Store.Postgres.Options -import Simplex.Messaging.Util (ifM, tshow) +import Simplex.Messaging.Util (ifM, isAsyncCancellation, tshow) -- TODO [postgres] use log_min_duration_statement instead of custom slow queries (SQLite's Connection type) data DBStore = DBStore @@ -75,10 +75,14 @@ withConnectionPool DBStorePool {dbPoolConns, dbSem} dbClosed dbConnect action = pure r where reset conn = do - conn' <- E.try dbConnect >>= \case + r <- E.try dbConnect + conn' <- case r of Right conn' -> PSQL.close conn >> pure conn' Left (_ :: E.SomeException) -> pure conn atomically $ writeTBQueue dbPoolConns conn' + case r of + Left e | isAsyncCancellation e -> E.throwIO e + _ -> pure () withConnection :: DBStore -> (PSQL.Connection -> IO a) -> IO a withConnection st = withConnectionPriority st False From c14a31224c60a1e6be0390436ce2e17dcea3ee33 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:45:09 +0000 Subject: [PATCH 006/159] xftp server: handle overflow and allocation limit in a file receive as before, rethrow only cancellations --- src/Simplex/FileTransfer/Transport.hs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index bd6c84946..f32b4ad70 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -65,7 +65,7 @@ import Simplex.Messaging.Parsers import Simplex.Messaging.Protocol (BlockingInfo, CommandError) import Simplex.Messaging.Transport (ALPN, CertChainPubKey, ServiceCredentials, SessionId, THandle (..), THandleParams (..), TransportError (..), TransportPeer (..)) import Simplex.Messaging.Transport.HTTP2.File -import Simplex.Messaging.Util (bshow, tshow, (<$?>), (<$$>)) +import Simplex.Messaging.Util (bshow, isAsyncCancellation, tshow, (<$?>), (<$$>)) import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal #if __GLASGOW_HASKELL__ == 810 @@ -204,8 +204,7 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receive h sz = hReceiveFile getBody h sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, - E.Handler $ \(e :: E.SomeAsyncException) -> E.throwIO e, - E.Handler $ \(e :: E.SomeException) -> logError (err e) $> Left FILE_IO + E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO ] err e = "receiveFile error: " <> tshow e From 552bac5190ddb682f83c2031974359baccd2e931 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 01:00:25 -0500 Subject: [PATCH 007/159] fix: make HTTP/2 transport shutdown interruptible Prevent Windows XFTP server tests from hanging during TLS and HTTP/2 teardown. Cancel HTTP/2 workers asynchronously, allow client finalizers to be interrupted, and close TLS contexts without waiting for peer close notifications. --- src/Simplex/Messaging/Transport/Client.hs | 2 +- src/Simplex/Messaging/Transport/HTTP2/Client.hs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Transport/Client.hs b/src/Simplex/Messaging/Transport/Client.hs index 1fd81e5b1..7472b35e6 100644 --- a/src/Simplex/Messaging/Transport/Client.hs +++ b/src/Simplex/Messaging/Transport/Client.hs @@ -183,7 +183,7 @@ runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, sent <- readIORef clientCredsSent client =<< set CHTransport (getTransportConnection tCfg sent chain tls) where - closeConn = readIORef >=> mapM_ (\c -> E.uninterruptibleMask_ $ closeConn_ c `catchAll_` pure ()) + closeConn = readIORef >=> mapM_ (\c -> closeConn_ c `catchAll_` pure ()) closeConn_ = \case CHSocket sock -> close sock CHContext tls -> closeTLS tls diff --git a/src/Simplex/Messaging/Transport/HTTP2/Client.hs b/src/Simplex/Messaging/Transport/HTTP2/Client.hs index 170e8740f..0e106e30b 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/Client.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/Client.hs @@ -184,7 +184,7 @@ getVerifiedHTTP2ClientWith config host port disconnected setup = -- | Disconnects client from the server and terminates client threads. closeHTTP2Client :: HTTP2Client -> IO () -closeHTTP2Client = mapM_ uninterruptibleCancel . action +closeHTTP2Client = mapM_ (void . async . cancel) . action sendRequest :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) sendRequest HTTP2Client {client_ = HClient {config, reqQ}} req reqTimeout_ = do From 411776a5ebe2d794abe42656a111b686b183d82d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:43:05 +0000 Subject: [PATCH 008/159] agent, clients: prevent hangs while a server or event processing is slow --- src/Simplex/FileTransfer/Agent.hs | 2 +- src/Simplex/Messaging/Agent.hs | 401 +++++++++++++--------- src/Simplex/Messaging/Agent/Client.hs | 71 +++- src/Simplex/Messaging/Agent/Env/SQLite.hs | 2 + src/Simplex/Messaging/Client.hs | 81 +++-- tests/AgentTests/FunctionalAPITests.hs | 329 +++++++++++++++++- tests/CoreTests/BatchingTests.hs | 78 +++++ tests/SMPAgentClient.hs | 1 + tests/SMPClient.hs | 22 +- tests/SMPProxyTests.hs | 53 ++- 10 files changed, 829 insertions(+), 211 deletions(-) diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index d24b5b8a9..980100e36 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -682,7 +682,7 @@ deleteSndFileRemote c userId sndFileEntityId sfd = deleteSndFilesRemote c userId deleteSndFilesRemote :: AgentClient -> UserId -> [(SndFileId, ValidFileDescription 'FSender)] -> AM' () deleteSndFilesRemote c userId sndFileIdsDescrs = do - deleteSndFilesInternal c (map fst sndFileIdsDescrs) `E.catchAny` (notify c "" . SFERR . INTERNAL . show) + deleteSndFilesInternal c (map fst sndFileIdsDescrs) `E.catchAny` (notifySub' c "" . SFERR . INTERNAL . show) let rs = concatMap (mapMaybe chunkReplica . fdChunks . snd) sndFileIdsDescrs void $ withStoreBatch' c (\db -> map (uncurry $ createDeletedSndChunkReplica db userId) rs) let servers = S.fromList $ map (\(FileChunkReplica {server}, _) -> server) rs diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 2c3b613ec..9cbc82d61 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -326,13 +326,13 @@ logServersStats c = do liftIO $ threadDelay' int saveServersStats :: AgentClient -> AM' () -saveServersStats c@AgentClient {subQ, smpServersStats, xftpServersStats, ntfServersStats} = do +saveServersStats c@AgentClient {smpServersStats, xftpServersStats, ntfServersStats} = do sss <- mapM (liftIO . getAgentSMPServerStats) =<< readTVarIO smpServersStats xss <- mapM (liftIO . getAgentXFTPServerStats) =<< readTVarIO xftpServersStats nss <- mapM (liftIO . getAgentNtfServerStats) =<< readTVarIO ntfServersStats let stats = AgentPersistedServerStats {smpServersStats = sss, xftpServersStats = xss, ntfServersStats = OptionalMap nss} tryAllErrors' (withStore' c (`updateServersStats` stats)) >>= \case - Left e -> atomically $ writeTBQueue subQ ("", "", AEvt SAEConn $ ERR $ INTERNAL $ show e) + Left e -> notifySub' c "" $ ERR $ INTERNAL $ show e Right () -> pure () restoreServersStats :: AgentClient -> AM' () @@ -355,11 +355,13 @@ disconnectAgentClient c@AgentClient {agentEnv = Env {ntfSupervisor = ns, xftpAge -- only used in the tests disposeAgentClient :: AgentClient -> IO () -disposeAgentClient c@AgentClient {acThread, agentEnv = Env {store}} = do +disposeAgentClient c@AgentClient {acThread, connLockViolations, agentEnv = Env {store}} = do t_ <- atomically (swapTVar acThread Nothing) $>>= (liftIO . deRefWeak) disconnectAgentClient c mapM_ killThread t_ liftIO $ closeDBStore store + violations <- readTVarIO connLockViolations + unless (null violations) $ E.throwIO $ INTERNAL $ "server requests in connection locks " <> show violations resumeAgentClient :: AgentClient -> IO () resumeAgentClient c = atomically $ writeTVar (active c) True @@ -927,8 +929,8 @@ deleteUser' c@AgentClient {smpServersStats, xftpServersStats} userId delSMPQueue lift $ saveServersStats c where delUser = - whenM (withStore' c (`deleteUserWithoutConns` userId)) . atomically $ - writeTBQueue (subQ c) ("", "", AEvt SAENone $ DEL_USER userId) + whenM (withStore' c (`deleteUserWithoutConns` userId)) . liftIO $ + nonBlockingWriteTBQueue (subQ c) ("", "", AEvt SAENone $ DEL_USER userId) setUserService' :: AgentClient -> UserId -> Bool -> AM () setUserService' c userId enable = do @@ -1175,8 +1177,11 @@ createRcvQueue c nm userId connId srvWithAuth@(ProtoServerWithAuth srv _) enable newRcvQueue_ c nm userId connId srvWithAuth vr qd (isJust ntfServer_) subMode nonce_ e2eKeys `catchAllErrors` \e -> liftIO (print e) >> throwE e incSMPServerStat c userId srv connCreated - rq' <- withStore c $ \db -> updateNewConnRcv db connId rq subMode - lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + recorded <- withConnLock c connId "createRcvQueue" $ do + r <- tryAllErrors $ withStore c $ \db -> updateNewConnRcv db connId rq subMode + forM_ r $ \rq' -> lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + pure r + rq' <- either (\e -> tryAllErrors (deleteNewQueue c nm tSess rq) >> throwE e) pure recorded mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure (rq', qUri) @@ -1239,15 +1244,15 @@ getConnShortLinkAsync' c userId corrId connId_ shortLink@(CSLContact _ _ srv _) createNewConn db g cData SCMInvitation setConnShortLink' :: AgentClient -> NetworkRequestMode -> ConnId -> SConnectionMode c -> UserConnLinkData c -> Maybe CRClientData -> NewRatchetKeys -> Maybe CR.InitialKeys -> AM (ConnShortLink c) -setConnShortLink' c nm connId cMode userLinkData clientData rotateKeys pqKeys_ = - withConnLock c connId "setConnShortLink" $ do +setConnShortLink' c nm connId cMode userLinkData clientData rotateKeys pqKeys_ = do + (rq, lnkId, sl, d) <- withConnLock c connId "setConnShortLink" $ do SomeConn _ conn <- withStore c (`getConn` connId) - (rq, lnkId, sl, d) <- case (conn, cMode, userLinkData) of + case (conn, cMode, userLinkData) of (ContactConnection cData rq, SCMContact, d@UserContactLinkData {}) -> prepareContactLinkData cData rq d (RcvConnection _ rq, SCMInvitation, d@UserInvLinkData {}) -> prepareInvLinkData rq d _ -> throwE $ CMD PROHIBITED "setConnShortLink: invalid connection or mode" - addQueueLink c nm rq lnkId d - pure sl + addQueueLink c nm rq lnkId d + pure sl where prepareContactLinkData :: ConnData -> RcvQueue -> UserConnLinkData 'CMContact -> AM (RcvQueue, SMP.LinkId, ConnShortLink 'CMContact, QueueLinkData) prepareContactLinkData ConnData {} rq@RcvQueue {shortLink} (UserContactLinkData ucd) = do @@ -1306,13 +1311,14 @@ prepareConnShortLink' c connId clientData = _ -> throwE $ CMD PROHIBITED "prepareConnShortLink: not contact address" deleteConnShortLink' :: AgentClient -> NetworkRequestMode -> ConnId -> SConnectionMode c -> AM () -deleteConnShortLink' c nm connId cMode = - withConnLock c connId "deleteConnShortLink" $ do +deleteConnShortLink' c nm connId cMode = do + rq <- withConnLock c connId "deleteConnShortLink" $ do SomeConn _ conn <- withStore c (`getConn` connId) case (conn, cMode) of - (ContactConnection _ rq, SCMContact) -> deleteQueueLink c nm rq - (RcvConnection _ rq, SCMInvitation) -> deleteQueueLink c nm rq + (ContactConnection _ rq, SCMContact) -> pure rq + (RcvConnection _ rq, SCMInvitation) -> pure rq _ -> throwE $ CMD PROHIBITED "deleteConnShortLink: not contact address" + deleteQueueLink c nm rq getConnLinkPrivKey' :: AgentClient -> ConnId -> AM (Maybe C.PrivateKeyEd25519) getConnLinkPrivKey' c connId = do @@ -1737,7 +1743,7 @@ allowConnection' c cmdId_ connId confId ownConnInfo = withConnLock c connId "all -- | Accept contact (ACPT command) in Reader monad acceptContact' :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> InvitationId -> ConnInfo -> PQSupport -> SubscriptionMode -> AM SndQueueSecured -acceptContact' c nm userId connId enableNtfs invId ownConnInfo pqSupport subMode = withConnLock c connId "acceptContact" $ do +acceptContact' c nm userId connId enableNtfs invId ownConnInfo pqSupport subMode = withInvLock c invId "acceptContact" $ do Invitation {connReq} <- withStore c $ \db -> getInvitation db "acceptContact'" invId r <- case connReq of CRInvitation cReq -> joinConn c nm userId connId enableNtfs cReq ownConnInfo pqSupport subMode @@ -1906,7 +1912,7 @@ subscribeConnections_ :: AgentClient -> [(ConnId, Either StoreError SomeConnSub) subscribeConnections_ c conns = do let (subRs, cs) = foldr partitionResultsConns ([], []) conns resumeDelivery cs - resumeConnCmds c $ map fst cs + resumeConnCmds c False $ map fst cs -- queue/service association is handled in the client rcvRs <- lift $ connResults <$> subscribeQueues c False (concatMap rcvQueues cs) ns <- asks ntfSupervisor @@ -1980,8 +1986,8 @@ subscribeConnections_ c conns = do notifyResultError rs = do let actual = M.size rs expected = length conns - when (actual /= expected) . atomically $ - writeTBQueue (subQ c) ("", "", AEvt SAEConn $ ERR $ INTERNAL $ "subscribeConnections result size: " <> show actual <> ", expected " <> show expected) + when (actual /= expected) $ + notifySub' c "" $ ERR $ INTERNAL $ "subscribeConnections result size: " <> show actual <> ", expected " <> show expected subscribeAllConnections' :: AgentClient -> Bool -> Maybe UserId -> AM () subscribeAllConnections' c onlyNeeded activeUserId_ = handleErr $ do @@ -2028,7 +2034,7 @@ subscribeAllConnections' c onlyNeeded activeUserId_ = handleErr $ do Just SSErrorQueueCount {expectedQueueCount = n, subscribedQueueCount = n'} | n > 0 && n' == 0 -> unassocQueues _ -> pure True Left e -> do - atomically $ writeTBQueue (subQ c) ("", "", AEvt SAEConn $ ERR e) + notifySub' c "" $ ERR e if clientServiceError e then False <$ withStore' c (\db -> unassocUserServerRcvQueueSubs' db userId srv) else pure True @@ -2220,10 +2226,10 @@ resumeSrvCmds :: AgentClient -> ConnId -> Maybe SMPServer -> AM' () resumeSrvCmds = void .:. getAsyncCmdWorker False {-# INLINE resumeSrvCmds #-} -resumeConnCmds :: AgentClient -> [ConnId] -> AM () -resumeConnCmds c connIds = do +resumeConnCmds :: AgentClient -> Bool -> [ConnId] -> AM () +resumeConnCmds c hasWork connIds = do connSrvs <- withStore' c (`getPendingCommandServers` connIds) - lift $ mapM_ (\(connId, srvs) -> mapM_ (resumeSrvCmds c connId) srvs) connSrvs + lift $ mapM_ (\(connId, srvs) -> mapM_ (void . getAsyncCmdWorker hasWork c connId) srvs) connSrvs resumeAllCommands :: AgentClient -> AM () resumeAllCommands c = do @@ -2289,36 +2295,46 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do JOIN (JRServiceReq cReq@(CRContactUri ConnReqUriData {crSmpQueues = q :| _} _) pqEnc signKey_) subMode connInfo -> noServer $ do triedHosts <- newTVarIO S.empty tryCommand . withNextSrv c userId storageSrvs triedHosts [qServer q] $ \srv -> - withConnLock c connId "JOIN service request" $ - atomically (TM.lookup connId (serviceRequests c)) >>= \case - Nothing -> pure () - Just v -> do - let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo - void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) - `catchAllErrors` \e -> + atomically (TM.lookup connId (serviceRequests c)) >>= \case + Nothing -> pure () + Just v -> do + let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo + void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) + `catchAllErrors` \e -> + whenM (atomically $ TM.member connId (serviceRequests c)) $ if temporaryOrHostError e then throwE e else atomically $ void $ tryPutTMVar v $ Left e -- will not overwrite existing result LET confId ownCInfo -> withServer' . tryAtomicCommand $ allowConnection' c (Just cmdId) connId confId ownCInfo >> notify OK ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >> notify OK SWCH -> - noServer . tryAtomicWithLock "switchConnection" $ - withStore c (`getConn` connId) >>= \case + noServer . tryAtomicCommand $ + withConnLock c connId "switchConnection" getConnToSwitch >>= \case SomeConn _ conn@(DuplexConnection _ (replaced :| _rqs) _) -> switchDuplexConnection c NRMBackground (Just cmdId) conn replaced >>= notify . SWITCH QDRcv SPStarted _ -> throwE $ CMD PROHIBITED "SWCH: not duplex" + where + getConnToSwitch = + withStore c (`getConn` connId) >>= \case + SomeConn _ (DuplexConnection cData (rq :| _) _) + | ratchetSyncSendProhibited cData -> do + when (rcvSwchStatus rq == Just RSSwitchStarted) . void . withStore' c $ \db -> setRcvSwitchStatus db rq Nothing + throwE $ CMD PROHIBITED "switchConnection: send prohibited" + conn -> pure conn DEL -> withServer' . tryAtomicCommand $ deleteConnection' c NRMBackground connId >> notify OK AInternalCommand cmd -> case cmd of ICAckDel rId srvMsgId msgId -> withServer $ \srv -> - tryAtomicCommand $ withConnLockNotify c connId "ICAckDel" $ do - t_ <- ack srv rId srvMsgId - withStore' c (\db -> deleteMsg db connId msgId >> deleteCommand db cmdId) - pure t_ + tryAtomicCommand $ do + recordAck <- ack srv rId srvMsgId + withConnLockNotify c connId "ICAckDel" $ do + t_ <- recordAck + withStore' c (\db -> deleteMsg db connId msgId >> deleteCommand db cmdId) + pure t_ ICAck rId srvMsgId -> withServer $ \srv -> - tryCommand $ withConnLockNotify c connId "ICAck" $ ack srv rId srvMsgId - ICAllowSecure _rId senderKey -> withServer' . tryMoveableWithLock "ICAllowSecure" $ do + tryCommand $ ack srv rId srvMsgId >>= withConnLockNotify c connId "ICAck" + ICAllowSecure _rId senderKey -> withServer' . tryMoveableCommand $ do (SomeConn _ conn, AcceptedConfirmation {senderConf, ownConnInfo}) <- - withStore c $ \db -> runExceptT $ (,) <$> ExceptT (getConn db connId) <*> ExceptT (getAcceptedConfirmation db connId) + withConnLock c connId "ICAllowSecure" . withStore c $ \db -> runExceptT $ (,) <$> ExceptT (getConn db connId) <*> ExceptT (getAcceptedConfirmation db connId) let connectReplyQueues_ cData sq_ = case L.nonEmpty $ smpReplyQueues senderConf of Just qs -> connectReplyQueues c cmdId cData ownConnInfo sq_ qs $> CCDeleted Nothing -> pure CCCompleted @@ -2340,95 +2356,120 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do where server = qServer sq _ -> throwE $ INTERNAL $ "incorrect connection type " <> show (internalCmdTag cmd) - ICDuplexSecure _rId senderKey -> withServer' . tryAtomicWithLock "ICDuplexSecure" . withDuplexConn $ \(DuplexConnection cData (rq :| _) (sq :| _)) -> do - secure rq senderKey - void $ enqueueMessage c (Just cmdId) cData sq SMP.MsgFlags {notification = True} HELLO - ICReplyDel -> withServer' . tryWithLock "ICReplyDel" $ + ICDuplexSecure _rId senderKey -> withServer' . tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICDuplexSecure" . withDuplexConn $ \_ (rq :| _) _ -> pure $ Just rq + forM_ rq_ $ \rq -> do + secure rq senderKey + withConnLock c connId "ICDuplexSecure" . withDuplexConn $ \cData _ (sq :| _) -> + Just <$> enqueueMessage c (Just cmdId) cData sq SMP.MsgFlags {notification = True} HELLO + ICReplyDel -> withServer' . tryCommand $ withStore c (`getConn` connId) >>= \case SomeConn _ (SndConnection cData sq) -> sendReplySync c NRMBackground (cData, sq) _ -> throwE $ INTERNAL "ICReplyDel: incorrect connection type" -- ICDeleteConn is no longer used, but it can be present in old client databases ICDeleteConn -> withStore' c (`deleteCommand` cmdId) - ICDeleteRcvQueue rId -> withServer $ \srv -> tryAtomicWithLock "ICDeleteRcvQueue" $ do + ICDeleteRcvQueue rId -> withServer $ \srv -> tryAtomicCommand $ do rq <- withStore c (\db -> getDeletedRcvQueue db connId srv rId) maxErrs <- asks $ deleteErrorCount . config - tryAllErrors (deleteQueue c NRMBackground rq) >>= \case + deleted <- tryAllErrors (deleteQueue c NRMBackground rq) + withConnLock c connId "ICDeleteRcvQueue" $ case deleted of Left e | temporaryOrHostError e && deleteErrors rq + 1 < maxErrs -> do withStore' c (`incRcvDeleteErrors` rq) throwE e _ -> withStore' c $ \db -> deleteConnRcvQueue db rq >> deleteCommand db cmdId ICQSecure rId senderKey -> - withServer $ \srv -> tryAtomicWithLock "ICQSecure" . withDuplexConn $ \(DuplexConnection cData rqs sqs) -> - case find (sameQueue (srv, rId)) rqs of - Just rq'@RcvQueue {server, sndId, status, dbReplaceQueueId = Just replaceQId} -> - case find ((replaceQId ==) . dbQId) rqs of - Just rq1 -> if status /= Confirmed then withStore' c (`deleteCommand` cmdId) else do - secureQueue c NRMBackground rq' senderKey - -- we may add more statistics special to queue rotation later on, - -- not accounting secure during rotation for now: - -- incSMPServerStat c userId server connSecured - rq1' <- withStore' c $ \db -> setRcvQueueStatus db rq' Secured >> setRcvSwitchStatus db rq1 (Just RSSendingQUSE) - void . enqueueMessages c cData sqs SMP.noMsgFlags $ QUSE [((server, sndId), True)] - withStore' c (`deleteCommand` cmdId) - let rqs' = updatedQs rq1' rqs - conn' = DuplexConnection cData rqs' sqs - cStats <- connectionStats c conn' - notify $ SWITCH QDRcv SPSecured cStats - _ -> internalErr "ICQSecure: no switching queue found" - _ -> internalErr "ICQSecure: queue address not found in connection" + withServer $ \srv -> tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICQSecure" . withSwitchingQueues srv $ \_ _ _ rq' _ -> pure rq' + forM_ rq_ $ \rq -> do + secureQueue c NRMBackground rq senderKey + -- we may add more statistics special to queue rotation later on, + -- not accounting secure during rotation for now: + -- incSMPServerStat c userId server connSecured + withConnLock c connId "ICQSecure" . withSwitchingQueues srv $ \cData rqs sqs rq'@RcvQueue {server, sndId} rq1 -> do + rq1' <- withStore' c $ \db -> setRcvQueueStatus db rq' Secured >> setRcvSwitchStatus db rq1 (Just RSSendingQUSE) + void . enqueueMessages c cData sqs SMP.noMsgFlags $ QUSE [((server, sndId), True)] + withStore' c (`deleteCommand` cmdId) + let rqs' = updatedQs rq1' rqs + conn' = DuplexConnection cData rqs' sqs + cStats <- connectionStats c conn' + notify $ SWITCH QDRcv SPSecured cStats + where + withSwitchingQueues :: SMPServer -> (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> RcvQueue -> RcvQueue -> AM a) -> AM (Maybe a) + withSwitchingQueues srv a = withDuplexConn $ \cData rqs sqs -> + case find (sameQueue (srv, rId)) rqs of + Just rq'@RcvQueue {status, dbReplaceQueueId = Just replaceQId} -> + case find ((replaceQId ==) . dbQId) rqs of + Just rq1 + | status /= Confirmed -> Nothing <$ withStore' c (`deleteCommand` cmdId) + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | otherwise -> Just <$> a cData rqs sqs rq' rq1 + _ -> Nothing <$ internalErr "ICQSecure: no switching queue found" + _ -> Nothing <$ internalErr "ICQSecure: queue address not found in connection" ICQSndSecure sId -> - withServer $ \srv -> tryWithLock "ICQSndSecure" . withDuplexConn $ \(DuplexConnection cData@ConnData {connAgentVersion} rqs sqs) -> - case findQ (srv, sId) sqs of - Nothing -> internalErr "ICQSndSecure: queue address not found in connection" - Just sq'@SndQueue {dbReplaceQueueId} -> - case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of - Just oldSq -> do - secureSndQueue c NRMBackground sq' - let confMsg = smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_ = Nothing, encConnInfo = ""} - void $ sendConfirmation c NRMBackground sq' confMsg - oldSq' <- withStore' c $ \db -> do - setSndQueueStatus db sq' Active - setSndQueuePrimary db connId sq' - setSndSwitchStatus db oldSq $ Just SSSendingQEND - let sq'' = (sq' :: SndQueue) {status = Active, primary = True, dbReplaceQueueId = Nothing} - pending <- withStore' c $ \db -> countSndQueueDeliveries db sq'' - atomically $ modifyTVar' (msgDeliveryOp c) $ \s -> s {opsInProgress = opsInProgress s + pending} - lift $ resumeMsgDelivery c sq'' - void $ enqueueMessages c cData [oldSq, sq''] SMP.noMsgFlags $ QEND [qAddress oldSq] - let conn' = DuplexConnection cData rqs (updatedQs oldSq' $ updatedQs sq'' sqs) - cStats <- connectionStats c conn' - notify $ SWITCH QDSnd SPSecured cStats - Nothing -> - forM_ (find (\q -> sndSwchStatus q == Just SSSendingQEND) sqs) $ \oldSq -> - void $ enqueueMessages c cData [oldSq, sq'] SMP.noMsgFlags $ QEND [qAddress oldSq] + withServer $ \srv -> tryCommand $ do + sq_ <- withConnLock c connId "ICQSndSecure" . withSecuringQueues srv $ \ConnData {connAgentVersion} _ _ sq' _ -> pure (connAgentVersion, sq') + forM_ sq_ $ \(connAgentVersion, sq) -> do + secureSndQueue c NRMBackground sq + let confMsg = smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_ = Nothing, encConnInfo = ""} + void $ sendConfirmation c NRMBackground sq confMsg + withConnLock c connId "ICQSndSecure" . withSecuringQueues srv $ \cData rqs sqs sq' oldSq -> do + oldSq' <- withStore' c $ \db -> do + setSndQueueStatus db sq' Active + setSndQueuePrimary db connId sq' + setSndSwitchStatus db oldSq $ Just SSSendingQEND + let sq'' = (sq' :: SndQueue) {status = Active, primary = True, dbReplaceQueueId = Nothing} + pending <- withStore' c $ \db -> countSndQueueDeliveries db sq'' + atomically $ modifyTVar' (msgDeliveryOp c) $ \s -> s {opsInProgress = opsInProgress s + pending} + lift $ resumeMsgDelivery c sq'' + void $ enqueueMessages c cData [oldSq, sq''] SMP.noMsgFlags $ QEND [qAddress oldSq] + let conn' = DuplexConnection cData rqs (updatedQs oldSq' $ updatedQs sq'' sqs) + cStats <- connectionStats c conn' + notify $ SWITCH QDSnd SPSecured cStats + where + withSecuringQueues :: SMPServer -> (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> SndQueue -> SndQueue -> AM a) -> AM (Maybe a) + withSecuringQueues srv a = withDuplexConn $ \cData rqs sqs -> + case findQ (srv, sId) sqs of + Nothing -> Nothing <$ internalErr "ICQSndSecure: queue address not found in connection" + Just sq'@SndQueue {dbReplaceQueueId} + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | otherwise -> case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of + Just oldSq -> Just <$> a cData rqs sqs sq' oldSq + Nothing -> do + forM_ (find (\q -> sndSwchStatus q == Just SSSendingQEND) sqs) $ \oldSq -> + void $ enqueueMessages c cData [oldSq, sq'] SMP.noMsgFlags $ QEND [qAddress oldSq] + pure Nothing ICQDelete rId -> do - withServer $ \srv -> tryAtomicWithLock "ICQDelete" . withDuplexConn $ \(DuplexConnection cData@ConnData {enableNtfs} rqs sqs) -> do - case removeQ (srv, rId) rqs of - Nothing -> internalErr "ICQDelete: queue address not found in connection" - Just (rq'@RcvQueue {primary}, rq'' : rqs') - | primary -> internalErr "ICQDelete: cannot delete primary rcv queue" - | otherwise -> do - checkRQSwchStatus rq' RSReceivedMessage - tryAllErrors (deleteQueue c NRMBackground rq') >>= \case - Right () -> finalizeSwitch - Left e - | temporaryOrHostError e -> throwE e - | otherwise -> finalizeSwitch >> notify (ERR e) - where - finalizeSwitch = do - withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId - when enableNtfs $ do - ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) - let conn' = DuplexConnection cData (rq'' :| rqs') sqs - cStats <- connectionStats c conn' - notify $ SWITCH QDRcv SPCompleted cStats - _ -> internalErr "ICQDelete: cannot delete the only queue in connection" + withServer $ \srv -> tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICQDelete" . withRemovedQueue srv $ \_ rq' _ _ -> pure rq' + forM_ rq_ $ \rq -> do + deleted <- tryAllErrors (deleteQueue c NRMBackground rq) + case deleted of + Left e | temporaryOrHostError e -> throwE e + _ -> withConnLock c connId "ICQDelete" . withRemovedQueue srv $ \cData@ConnData {enableNtfs} rq' rqs sqs -> do + withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId + when enableNtfs $ do + ns <- asks ntfSupervisor + liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + let conn' = DuplexConnection cData rqs sqs + cStats <- connectionStats c conn' + notify $ SWITCH QDRcv SPCompleted cStats + either (notify . ERR) pure deleted + where + withRemovedQueue :: SMPServer -> (ConnData -> RcvQueue -> NonEmpty RcvQueue -> NonEmpty SndQueue -> AM a) -> AM (Maybe a) + withRemovedQueue srv a = withDuplexConn $ \cData rqs sqs -> + case removeQ (srv, rId) rqs of + Nothing -> Nothing <$ internalErr "ICQDelete: queue address not found in connection" + Just (rq'@RcvQueue {primary}, rq'' : rqs') + | primary -> Nothing <$ internalErr "ICQDelete: cannot delete primary rcv queue" + | otherwise -> do + checkRQSwchStatus rq' RSReceivedMessage + Just <$> a cData rq' (rq'' :| rqs') sqs + _ -> Nothing <$ internalErr "ICQDelete: cannot delete the only queue in connection" where ack srv rId srvMsgId = withStore' c (\db -> getRcvQueue db connId srv rId) >>= \case Right rq -> ackQueueMessage c rq srvMsgId - Left SEConnNotFound -> pure Nothing + Left SEConnNotFound -> pure (pure Nothing) Left e -> throwE $ storeError e secure :: RcvQueue -> SMP.SndPublicAuthKey -> AM () secure rq@RcvQueue {server} senderKey = do @@ -2443,11 +2484,11 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do noServer a = case server_ of Nothing -> a _ -> internalErr "command requires no server" - withDuplexConn :: (Connection 'CDuplex -> AM ()) -> AM () + withDuplexConn :: (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> AM (Maybe a)) -> AM (Maybe a) withDuplexConn a = withStore c (`getConn` connId) >>= \case - SomeConn _ conn@DuplexConnection {} -> a conn - _ -> internalErr "command requires duplex connection" + SomeConn _ (DuplexConnection cData rqs sqs) -> a cData rqs sqs + _ -> Nothing <$ internalErr "command requires duplex connection" tryCommand action = tryMoveableCommand (action $> CCCompleted) tryAtomicCommand action = tryMoveableCommand (action $> CCDeleted) tryMoveableCommand action = withRetryInterval2 ri $ \_ loop -> do @@ -2466,11 +2507,15 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do Right CCCompleted -> withStore' c (`deleteCommand` cmdId) Right CCMoved -> pure () -- command processing moved to another command queue Right CCDeleted -> pure () - tryWithLock name = tryCommand . withConnLock c connId name - tryAtomicWithLock name = tryAtomicCommand . withConnLock c connId name - tryMoveableWithLock name = tryMoveableCommand . withConnLock c connId name internalErr s = cmdError $ INTERNAL $ s <> ": " <> show (agentCommandTag command) cmdError e = notify (ERR e) >> withStore' c (`deleteCommand` cmdId) + postponeCommand = do + liftIO $ noWorkToDo doWork + otherCmds <- withStore c $ \db -> runExceptT $ do + liftIO $ deleteCommand db cmdId + pending <- liftIO $ either (const True) isJust <$> getPendingServerCommand db connId server_ + pending <$ ExceptT (createCommand db corrId connId server_ command) + when otherCmds . atomically $ hasWorkToDo' doWork notify :: forall e. AEntityI e => AEvent e -> AM () notify cmd = let t = (corrId, connId, AEvt (sAEntity @e) cmd) @@ -2835,30 +2880,34 @@ retrySndOp c loop = do withConnLockNotify :: AgentClient -> ConnId -> Text -> AM (Maybe ATransmission) -> AM () withConnLockNotify c connId name action = do t_ <- withConnLock c connId name action - forM_ t_ $ atomically . writeTBQueue (subQ c) + forM_ t_ $ liftIO . nonBlockingWriteTBQueue (subQ c) ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM () -ackMessage' c cmdId_ connId msgId rcptInfo_ = withConnLockNotify c connId "ackMessage" $ do - SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection {} -> do - t_ <- ack - sendRcpt conn - del - pure t_ - RcvConnection {} -> do - t_ <- ack - del - pure t_ - SndConnection {} -> throwE $ CONN SIMPLEX "ackMessage" - ContactConnection {} -> throwE $ CMD PROHIBITED "ackMessage: ContactConnection" - NewConnection _ -> throwE $ CMD PROHIBITED "ackMessage: NewConnection" +ackMessage' c cmdId_ connId msgId rcptInfo_ = do + ack_ <- withConnLock c connId "ackMessage" $ do + SomeConn _ conn <- withStore c (`getConn` connId) + case conn of + DuplexConnection {} -> markUserAck + RcvConnection {} -> markUserAck + SndConnection {} -> throwE $ CONN SIMPLEX "ackMessage" + ContactConnection {} -> throwE $ CMD PROHIBITED "ackMessage: ContactConnection" + NewConnection _ -> throwE $ CMD PROHIBITED "ackMessage: NewConnection" + forM_ ack_ $ \(rq, srvMsgId) -> do + recordAck <- ackQueueMessage c rq srvMsgId + withConnLockNotify c connId "ackMessage" $ do + t_ <- recordAck + withStore c (`getConn` connId) >>= \case + SomeConn _ conn@DuplexConnection {} -> sendRcpt conn + _ -> pure () + t_ <$ del where - ack :: AM (Maybe ATransmission) - ack = do - -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged - (rq, srvMsgId) <- withStore c $ \db -> setMsgUserAck db connId $ InternalId msgId - ackQueueMessage c rq srvMsgId + -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged + markUserAck :: AM (Maybe (RcvQueue, SMP.MsgId)) + markUserAck = + withStore' c (\db -> setMsgUserAck db connId $ InternalId msgId) >>= \case + Right r -> pure $ Just r + Left (SEMsgNotFound _) -> Nothing <$ del + Left e -> throwE $ storeError e del :: AM () del = withStore' c $ \db -> deleteMsg db connId (InternalId msgId) >> mapM_ (deleteCommand db) cmdId_ sendRcpt :: Connection 'CDuplex -> AM () @@ -2887,19 +2936,20 @@ getConnectionQueueInfo' c nm connId = do NewConnection _ -> throwE $ CMD PROHIBITED "getConnectionQueueInfo: NewConnection" switchConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM ConnectionStats -switchConnection' c nm connId = - withConnLock c connId "switchConnection" $ +switchConnection' c nm connId = do + (cData, rqs, sqs, rq') <- withConnLock c connId "switchConnection" $ withStore c (`getConn` connId) >>= \case - SomeConn _ conn@(DuplexConnection cData rqs@(rq :| _rqs) _) + SomeConn _ (DuplexConnection cData rqs@(rq :| _rqs) sqs) | isJust (switchingRQ rqs) -> throwE $ CMD PROHIBITED "switchConnection: already switching" | otherwise -> do when (ratchetSyncSendProhibited cData) $ throwE $ CMD PROHIBITED "switchConnection: send prohibited" rq' <- withStore' c $ \db -> setRcvSwitchStatus db rq $ Just RSSwitchStarted - switchDuplexConnection c nm Nothing conn rq' + pure (cData, rqs, sqs, rq') _ -> throwE $ CMD PROHIBITED "switchConnection: not duplex" + switchDuplexConnection c nm Nothing (DuplexConnection cData rqs sqs) rq' switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats -switchDuplexConnection c nm cmdId_ (DuplexConnection cData@ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do +switchDuplexConnection c nm cmdId_ (DuplexConnection ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do checkRQSwchStatus rq RSSwitchStarted clientVRange <- asks $ smpClientVRange . config -- try to get the server that is different from all queues, or at least from the primary rcv queue @@ -2909,12 +2959,23 @@ switchDuplexConnection c nm cmdId_ (DuplexConnection cData@ConnData {connId, use -- The problem is that currently subscription already exists, and we do not support queues with credentials but without subscriptions. (q, qUri, tSess, sessId, serviceId_) <- newRcvQueue c nm userId connId srv' clientVRange SCMInvitation False SMSubscribe let rq' = (q :: NewRcvQueue) {primary = True, dbReplaceQueueId = Just dbQueueId} - rq'' <- withStore c $ \db -> addConnRcvQueue db connId rq' SMSubscribe - lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ - void . enqueueMessages c cData sqs SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] - rq1 <- withStore' c $ \db -> setRcvSwitchStatus db rq (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ - let rqs' = updatedQs rq1 rqs <> [rq''] - connectionStats c $ DuplexConnection cData rqs' sqs + switched <- withConnLock c connId "switchConnection" $ do + recorded <- tryAllErrors $ + withStore c (`getConn` connId) >>= \case + SomeConn _ (DuplexConnection cData rqs' sqs') | Just rq1 <- findQ (qAddress rq) rqs' -> + (cData,rqs',sqs',rq1,) <$> withStore c (\db -> addConnRcvQueue db connId rq' SMSubscribe) + _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" + forM recorded $ \(cData, rqs', sqs', rq1, rq'') -> do + when (rcvSwchStatus rq1 /= Just RSSwitchStarted) $ deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: aborted") + when (ratchetSyncSendProhibited cData) $ do + void $ withStore' c $ \db -> setRcvSwitchStatus db rq1 Nothing + deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: send prohibited") + lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ + void . enqueueMessages c cData sqs' SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] + rq1' <- withStore' c $ \db -> setRcvSwitchStatus db rq1 (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ + let rqs'' = updatedQs rq1' rqs' <> [rq''] + connectionStats c $ DuplexConnection cData rqs'' sqs' + either (\e -> tryAllErrors (deleteNewQueue c nm tSess q) >> throwE e) pure switched abortConnectionSwitch' :: AgentClient -> ConnId -> AM ConnectionStats abortConnectionSwitch' c connId = @@ -2964,12 +3025,12 @@ synchronizeRatchet' c connId pqSupport' force = withConnLock c connId "synchroni | otherwise -> throwE $ CMD PROHIBITED "synchronizeRatchet: not allowed" _ -> throwE $ CMD PROHIBITED "synchronizeRatchet: not duplex" -ackQueueMessage :: AgentClient -> RcvQueue -> SMP.MsgId -> AM (Maybe ATransmission) +ackQueueMessage :: AgentClient -> RcvQueue -> SMP.MsgId -> AM (AM (Maybe ATransmission)) ackQueueMessage c rq@RcvQueue {userId, connId, server, rcvSwchStatus} srvMsgId = do incSMPServerStat c userId server ackAttempts tryAllErrors (sendAck c rq srvMsgId) >>= \case - Right drained -> sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND - Left (SMP _ SMP.NO_MSG) -> sendMsgNtf ackNoMsgErrs False + Right drained -> pure $ sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND + Left (SMP _ SMP.NO_MSG) -> pure $ sendMsgNtf ackNoMsgErrs False Left e -> do unless (temporaryOrHostError e) $ incSMPServerStat c userId server ackOtherErrs throwE e @@ -2989,14 +3050,16 @@ deleteRcvQueueAsync c rq@RcvQueue {connId, server, rcvId} = do -- | Suspend SMP agent connection (OFF command) in Reader monad suspendConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM () -suspendConnection' c nm connId = withConnLock c connId "suspendConnection" $ do - SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection _ rqs _ -> mapM_ (suspendQueue c nm) rqs - RcvConnection _ rq -> suspendQueue c nm rq - ContactConnection _ rq -> suspendQueue c nm rq - SndConnection _ _ -> throwE $ CONN SIMPLEX "suspendConnection" - NewConnection _ -> throwE $ CMD PROHIBITED "suspendConnection" +suspendConnection' c nm connId = do + rqs <- withConnLock c connId "suspendConnection" $ do + SomeConn _ conn <- withStore c (`getConn` connId) + case conn of + DuplexConnection _ rqs _ -> pure $ L.toList rqs + RcvConnection _ rq -> pure [rq] + ContactConnection _ rq -> pure [rq] + SndConnection _ _ -> throwE $ CONN SIMPLEX "suspendConnection" + NewConnection _ -> throwE $ CMD PROHIBITED "suspendConnection" + mapM_ (suspendQueue c nm) (rqs :: [RcvQueue]) -- | Delete SMP agent connection (DEL command) in Reader monad -- unlike deleteConnectionAsync, this function does not mark connection as deleted in case of deletion failure @@ -3059,7 +3122,7 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do unsubNtfConnIds connIds' = do ns <- asks ntfSupervisor atomically $ writeTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds') - notify = atomically . writeTBQueue (subQ c) + notify = liftIO . nonBlockingWriteTBQueue (subQ c) deleteConnQueues :: AgentClient -> NetworkRequestMode -> Bool -> Bool -> [RcvQueue] -> AM' (Map ConnId (Either AgentErrorType ())) deleteConnQueues c nm waitDelivery ntf rqs = do @@ -3129,8 +3192,8 @@ deleteConnections_ getConnections ntf waitDelivery c nm connIds = do notifyResultError rs = do let actual = M.size rs expected = length connIds - when (actual /= expected) . atomically $ - writeTBQueue (subQ c) ("", "", AEvt SAEConn $ ERR $ INTERNAL $ "deleteConnections result size: " <> show actual <> ", expected " <> show expected) + when (actual /= expected) $ + notifySub' c "" $ ERR $ INTERNAL $ "deleteConnections result size: " <> show actual <> ", expected " <> show expected getConnectionServers' :: AgentClient -> ConnId -> AM ConnectionStats getConnectionServers' c connId = do @@ -3454,6 +3517,7 @@ suspendAgent c@AgentClient {agentState = as} maxDelay = do suspendOperation c AOSndFiles $ suspendMsgDelivery c readTVar as + void . forkIO $ notifySuspended c when (state == ASSuspending) $ do void . forkIO $ removeDeletedOrFailedSndFilesInProgress c void . forkIO $ do @@ -3575,7 +3639,7 @@ cleanupManager c@AgentClient {subQ} = do expiredConns <- withStore' c $ \db -> do deleteExpiredServiceRequests db $ addUTCTime (negate serviceResponseTimeout) now getExpiredServiceConns db now - deleteConnectionsAsync' c False expiredConns + ExceptT . withConnLocks c (S.fromList expiredConns) "cleanupManager" . runExceptT $ deleteConnectionsAsync' c False expiredConns expireEndedRcvQueues = do maxErrs <- asks $ deleteErrorCount . config connIds <- withStore' c getEndedRcvQueueConnIds @@ -3775,6 +3839,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr cStats <- connectionStats c conn'' notify $ RSYNC RSOk Nothing cStats withStore' c $ \db -> setConnRatchetSync db connId RSOk + resumeConnCmds c True [connId] pure conn'' | otherwise = pure conn' Right Nothing -> prohibited "msg: bad agent msg" >> ack @@ -3816,6 +3881,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr cStats <- connectionStats c conn'' notify $ RSYNC rss' (Just e) cStats withStore' c $ \db -> setConnRatchetSync db connId rss' + when (rss' == RSAllowed) $ resumeConnCmds c True [connId] Left e -> do incSMPServerStat c userId srv recvErrs checkDuplicateHash e encryptedMsgHash >> ack @@ -4401,11 +4467,14 @@ connectReplyQueues c cmdId cData@ConnData {userId, connId} ownConnInfo sq_ (qInf -- in case of SKEY retry the connection is already duplex sq' <- maybe upgradeConn pure sq_ void $ agentSecureSndQueue c NRMBackground cData sq' - enqueueConfirmation c cmdId cData sq' ownConnInfo Nothing + withConnLock c connId "connectReplyQueues" $ + withStore c (`getConn` connId) >>= \case + SomeConn _ (DuplexConnection cData' _ (sq :| _)) -> enqueueConfirmation c cmdId cData' sq ownConnInfo Nothing + _ -> throwE $ INTERNAL "connectReplyQueues: incorrect connection type" where upgradeConn = do (sq, _) <- lift $ newSndQueue userId connId qInfo' Nothing - withStore c $ \db -> upgradeRcvConnToDuplex db connId sq + withConnLock c connId "connectReplyQueues" . withStore c $ \db -> upgradeRcvConnToDuplex db connId sq secureConfirmQueueAsync :: AgentClient -> AsyncCmdId -> ConnData -> Maybe RcvQueue -> SndQueue -> SMPServerWithAuth -> ConnInfo -> Maybe (CR.SndE2ERatchetParams 'C.X448) -> SubscriptionMode -> AM SndQueueSecured secureConfirmQueueAsync c cmdId cData rq_ sq srv connInfo e2eEncryption_ subMode = do diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index aa2fb8616..e77a59838 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -99,6 +99,7 @@ module Simplex.Messaging.Agent.Client sendAck, suspendQueue, deleteQueue, + deleteNewQueue, deleteQueues, logServer, logSecret, @@ -137,6 +138,7 @@ module Simplex.Messaging.Agent.Client waitForWork, hasWorkToDo, hasWorkToDo', + noWorkToDo, withWork, withWork_, withWorkItems, @@ -229,6 +231,7 @@ import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) +import qualified Data.Text as T import Data.Text.Encoding import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) @@ -325,7 +328,7 @@ import System.Mem.Weak (Weak, deRefWeak) import System.Random (randomR) import UnliftIO (mapConcurrently, timeout) import UnliftIO.Async (async) -import UnliftIO.Concurrent (forkIO, mkWeakThreadId) +import UnliftIO.Concurrent (forkIO, mkWeakThreadId, myThreadId) import UnliftIO.Directory (doesFileExist, getTemporaryDirectory, removeFile) import qualified UnliftIO.Exception as E import UnliftIO.STM @@ -386,6 +389,8 @@ data AgentClient = AgentClient getMsgLocks :: TMap (SMPServer, SMP.RecipientId) (TMVar ()), -- locks to prevent concurrent operations with connection connLocks :: TMap ConnId Lock, + connLockHolders :: TMap ThreadId Text, + connLockViolations :: TVar [Text], -- locks to prevent concurrent operations with connection request invitations invLocks :: TMap ByteString Lock, -- lock to prevent concurrency between periodic and async connection deletions @@ -556,6 +561,8 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState <- newTVarIO ASForeground getMsgLocks <- TM.emptyIO connLocks <- TM.emptyIO + connLockHolders <- TM.emptyIO + connLockViolations <- newTVarIO [] invLocks <- TM.emptyIO deleteLock <- createLockIO smpSubWorkers <- TM.emptyIO @@ -602,6 +609,8 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState, getMsgLocks, connLocks, + connLockHolders, + connLockViolations, invLocks, deleteLock, smpSubWorkers, @@ -693,6 +702,7 @@ instance ProtocolServerClient XFTPVersion XFTPErrorType FileResponse where getSMPServerClient :: AgentClient -> NetworkRequestMode -> SMPTransportSession -> AM SMPConnectedClient getSMPServerClient c@AgentClient {active, smpClients, workerSeq} nm tSess = do unlessM (readTVarIO active) $ throwE INACTIVE + checkNoConnLock c ts <- liftIO getCurrentTime withGetSessVar workerSeq tSess smpClients ts newClient (waitForProtocolClient c nm tSess smpClients) where @@ -703,6 +713,7 @@ getSMPServerClient c@AgentClient {active, smpClients, workerSeq} nm tSess = do getSMPProxyClient :: AgentClient -> NetworkRequestMode -> Maybe SMPServerWithAuth -> SMPTransportSession -> AM (SMPConnectedClient, Either AgentErrorType ProxiedRelay) getSMPProxyClient c@AgentClient {active, smpClients, smpProxiedRelays, workerSeq} nm proxySrv_ destSess@(userId, destSrv, qId) = do unlessM (readTVarIO active) $ throwE INACTIVE + checkNoConnLock c proxySrv <- maybe (getNextServer c userId proxySrvs [destSrv]) pure proxySrv_ ts <- liftIO getCurrentTime (tSess, auth) <- liftIO $ proxiedTransportSession proxySrv @@ -872,6 +883,7 @@ notifySub c = notifySub' c "" getNtfServerClient :: AgentClient -> NetworkRequestMode -> NtfTransportSession -> AM NtfClient getNtfServerClient c@AgentClient {active, ntfClients, workerSeq, proxySessTs, presetDomains} nm tSess@(_, srv, _) = do unlessM (readTVarIO active) $ throwE INACTIVE + checkNoConnLock c ts <- liftIO getCurrentTime withGetSessVar workerSeq tSess ntfClients ts (newProtocolClient c tSess ntfClients connectClient) (waitForProtocolClient c nm tSess ntfClients) where @@ -893,6 +905,7 @@ getNtfServerClient c@AgentClient {active, ntfClients, workerSeq, proxySessTs, pr getXFTPServerClient :: AgentClient -> XFTPTransportSession -> AM XFTPClient getXFTPServerClient c@AgentClient {active, xftpClients, userEntitlements, workerSeq, proxySessTs, presetDomains} tSess@(userId, srv, _) = do unlessM (readTVarIO active) $ throwE INACTIVE + checkNoConnLock c ts <- liftIO getCurrentTime withGetSessVar workerSeq tSess xftpClients ts (newProtocolClient c tSess xftpClients connectClient) (waitForProtocolClient c NRMBackground tSess xftpClients) where @@ -1096,7 +1109,7 @@ withConnLock c connId name = ExceptT . withConnLock' c connId name . runExceptT withConnLock' :: AgentClient -> ConnId -> Text -> AM' a -> AM' a withConnLock' _ "" _ = id -withConnLock' AgentClient {connLocks} connId name = withLockMap connLocks connId name +withConnLock' AgentClient {connLocks, connLockHolders} connId name = withLockMap connLocks connId name . withLockHolder connLockHolders name {-# INLINE withConnLock' #-} withInvLock :: AgentClient -> ByteString -> Text -> AM a -> AM a @@ -1108,7 +1121,7 @@ withInvLock' AgentClient {invLocks} = withLockMap invLocks {-# INLINE withInvLock' #-} withConnLocks :: AgentClient -> Set ConnId -> Text -> AM' a -> AM' a -withConnLocks AgentClient {connLocks} = withLocksMap connLocks +withConnLocks AgentClient {connLocks, connLockHolders} connIds name = withLocksMap connLocks connIds name . withLockHolder connLockHolders name {-# INLINE withConnLocks #-} withLockMap :: (Ord k, MonadUnliftIO m) => TMap k Lock -> k -> Text -> m a -> m a @@ -1122,6 +1135,29 @@ withLocksMap = withGetLocks . getMapLock getMapLock :: Ord k => TMap k Lock -> k -> IO Lock getMapLock locks key = either id id <$> TM.lookupOrInsertIO key createLock locks +withLockHolder :: MonadUnliftIO m => TMap ThreadId Text -> Text -> m a -> m a +withLockHolder holders name a = do + t <- myThreadId + E.bracket + (atomically $ TM.lookupInsert t name holders) + (\prev_ -> atomically $ TM.alter (const prev_) t holders) + (const a) + +checkNoConnLock :: AgentClient -> AM () +checkNoConnLock AgentClient {connLockHolders, connLockViolations} = do + t <- myThreadId + name_ <- liftIO $ TM.lookupIO t connLockHolders + forM_ name_ $ \name -> do + let err = "server request in connection lock " <> name + logError err + whenM (asks $ prohibitRequestsInConnLock . config) $ do + atomically $ modifyTVar' connLockViolations (name :) + throwE $ INTERNAL $ T.unpack err + +checkBatchOutsideConnLock :: AgentClient -> [q] -> AM' [(q, Either AgentErrorType r)] -> AM' [(q, Either AgentErrorType r)] +checkBatchOutsideConnLock _ [] batch = batch +checkBatchOutsideConnLock c qs batch = tryAllErrors' (checkNoConnLock c) >>= either (\e -> pure $ map (,Left e) qs) (const batch) + withClient_ :: forall a v err msg. ProtocolServerClient v err msg => AgentClient -> NetworkRequestMode -> TransportSession msg -> (Client msg -> AM a) -> AM a withClient_ c nm tSess@(_, srv, _) action = do cl <- getProtocolServerClient c nm tSess @@ -1643,7 +1679,7 @@ serverHostError = \case -- | Batch by transport session and subscribe queues. The list of results can have a different order. subscribeQueues :: AgentClient -> Bool -> [RcvQueueSub] -> AM' [(RcvQueueSub, Either AgentErrorType (Maybe ServiceId))] subscribeQueues _ _ [] = pure [] -subscribeQueues c withEvents qs = do +subscribeQueues c withEvents qs = checkBatchOutsideConnLock c qs $ do (errs, qs') <- checkQueues c qs atomically $ modifyTVar' (subscrConns c) (`S.union` S.fromList (map qConnId qs')) qss <- batchQueues mkSMPTSession qs' <$> getSessionModeIO c @@ -1841,7 +1877,7 @@ type BatchResponses q e r = NonEmpty (q, Either e r) -- Please note: this function does not preserve order of results to be the same as the order of arguments, -- it includes arguments in the results instead. sendTSessionBatches :: forall q r. ByteString -> (q -> TransportSessionMode -> SMPTransportSession) -> (SMPClient -> NonEmpty q -> IO (BatchResponses q SMPClientError r)) -> AgentClient -> NetworkRequestMode -> [q] -> AM' [(q, Either AgentErrorType r)] -sendTSessionBatches statCmd mkSession action c nm qs = do +sendTSessionBatches statCmd mkSession action c nm qs = checkBatchOutsideConnLock c qs $ do qs' <- batchQueues mkSession qs <$> getSessionModeIO c concatMap L.toList <$> mapConcurrently (sendClientBatch statCmd action c nm) qs' @@ -2118,6 +2154,11 @@ deleteQueue c nm rq@RcvQueue {rcvId, rcvPrivateKey} = do withSMPClient c nm rq "DEL" $ \smp -> deleteSMPQueue smp nm rcvPrivateKey rcvId +deleteNewQueue :: AgentClient -> NetworkRequestMode -> SMPTransportSession -> NewRcvQueue -> AM () +deleteNewQueue c nm tSess RcvQueue {rcvId, rcvPrivateKey} = + withLogClient c nm tSess (unEntityId rcvId) "DEL" $ \smp -> + deleteSMPQueue (connectedClient smp) nm rcvPrivateKey rcvId + deleteQueues :: AgentClient -> NetworkRequestMode -> [RcvQueue] -> AM' [(RcvQueue, Either AgentErrorType ())] deleteQueues c nm = sendTSessionBatches "DEL" mkSMPTSession deleteQueues_ c nm where @@ -2374,9 +2415,9 @@ endAgentOperation c op = endOperation c op $ case op of suspendSendingAndDatabase c AOSndNetwork -> suspendOperation c AODatabase $ - notifySuspended c + setSuspended c AODatabase -> - notifySuspended c + setSuspended c suspendMsgDelivery :: AgentClient -> STM () suspendMsgDelivery c = @@ -2387,7 +2428,7 @@ suspendSendingAndDatabase :: AgentClient -> STM () suspendSendingAndDatabase c = suspendOperation c AOSndNetwork $ suspendOperation c AODatabase $ - notifySuspended c + setSuspended c suspendOperation :: AgentClient -> AgentOperation -> STM () -> STM () suspendOperation c op endedAction = do @@ -2395,11 +2436,15 @@ suspendOperation c op endedAction = do -- unsafeIOToSTM $ putStrLn $ "suspendOperation_ " <> show op <> " " <> show n when (n == 0) $ whenSuspending c endedAction -notifySuspended :: AgentClient -> STM () -notifySuspended c = do - -- unsafeIOToSTM $ putStrLn "notifySuspended" - writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) - writeTVar (agentState c) ASSuspended +setSuspended :: AgentClient -> STM () +setSuspended c = writeTVar (agentState c) ASSuspended + +notifySuspended :: AgentClient -> IO () +notifySuspended AgentClient {agentState, subQ} = do + suspended <- atomically $ readTVar agentState >>= \case + ASSuspending -> retry + s -> pure $ s == ASSuspended + when suspended . atomically $ writeTBQueue subQ ("", "", AEvt SAENone SUSPENDED) endOperation :: AgentClient -> AgentOperation -> STM () -> STM () endOperation c op endedAction = do diff --git a/src/Simplex/Messaging/Agent/Env/SQLite.hs b/src/Simplex/Messaging/Agent/Env/SQLite.hs index d32be79b1..afe1ded1a 100644 --- a/src/Simplex/Messaging/Agent/Env/SQLite.hs +++ b/src/Simplex/Messaging/Agent/Env/SQLite.hs @@ -171,6 +171,7 @@ data AgentConfig = AgentConfig logStatsInterval :: Int64, cleanupStepInterval :: Int, maxWorkerRestartsPerMin :: Int, + prohibitRequestsInConnLock :: Bool, storedMsgDataTTL :: NominalDiffTime, rcvFilesTTL :: NominalDiffTime, sndFilesTTL :: NominalDiffTime, @@ -249,6 +250,7 @@ defaultAgentConfig = logStatsInterval = 10 * 1000000, -- 10 seconds cleanupStepInterval = 200000, -- 200ms maxWorkerRestartsPerMin = 5, + prohibitRequestsInConnLock = False, storedMsgDataTTL = 21 * nominalDay, rcvFilesTTL = 2 * nominalDay, sndFilesTTL = nominalDay, diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 884e783d0..6ad316db4 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -119,7 +119,10 @@ module Simplex.Messaging.Client PCTransmission, mkTransmission, authTransmission, + pClientSndQ, + pClientSentCommandsCount, smpClientStub, + sendProtocolCommand_, -- * For debugging TBQueueInfo (..), @@ -151,10 +154,11 @@ import Data.Int (Int64) import Data.List (find, isSuffixOf) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as L -import Data.Maybe (catMaybes, fromMaybe) +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -210,7 +214,7 @@ data PClient v err msg = PClient smpClientStub :: TVar ChaChaDRG -> ByteString -> VersionSMP -> Maybe (THandleAuth 'TClient) -> IO SMPClient smpClientStub g sessionId thVersion thAuth = do let ts = UTCTime (read "2024-03-31") 0 - connected <- newTVarIO False + connected <- newTVarIO True clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -254,6 +258,9 @@ smpClientStub g sessionId thVersion thAuth = do } } +pClientSndQ :: ProtocolClient v err msg -> TBQueue (Maybe (Request err msg), ByteString) +pClientSndQ ProtocolClient {client_ = PClient {sndQ}} = sndQ + type SMPClient = ProtocolClient SMPVersion ErrorType BrokerMsg -- | Type for client command data @@ -476,6 +483,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, + sentCommandsTTL :: NominalDiffTime, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -496,6 +504,7 @@ defaultClientConfig clientALPN useSNI serverVRange = { qSize = 64, defaultTransport = ("443", transport @TLS), networkConfig = defaultNetworkConfig, + sentCommandsTTL = 15 * 60, clientALPN, serviceCredentials = Nothing, serverVRange, @@ -519,6 +528,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, + createdAt :: UTCTime, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -574,7 +584,7 @@ type SMPTransportSession = TransportSession BrokerMsg -- A single queue can be used for multiple 'SMPClient' instances, -- as 'SMPServerTransmission' includes server information. getProtocolClient :: forall v err msg. Protocol v err msg => TVar ChaChaDRG -> NetworkRequestMode -> TransportSession msg -> ProtocolClientConfig v -> [HostName] -> Maybe (TBQueue (ServerTransmissionBatch v err msg)) -> UTCTime -> (ProtocolClient v err msg -> IO ()) -> IO (Either (ProtocolClientError err) (ProtocolClient v err msg)) -getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do +getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, sentCommandsTTL, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do case chooseTransportHost networkConfig (host srv) of Right useHost -> (getCurrentTime >>= mkProtocolClient useHost >>= runClient useTransport useHost) @@ -655,10 +665,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS `E.finally` (failPendingRequests c >> disconnected c') failPendingRequests :: PClient v err msg -> IO () - failPendingRequests PClient {sentCommands} = atomically $ swapTVar sentCommands mempty >>= mapM_ failRequest - where - failRequest Request {pending, responseVar} = - whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + failPendingRequests PClient {connected, sentCommands} = atomically $ do + writeTVar connected False + swapTVar sentCommands mempty >>= mapM_ failRequest send :: Transport c => ProtocolClient v err msg -> THandle v c 'TClient -> IO () send ProtocolClient {client_ = PClient {sndQ}} h = forever $ atomically (readTBQueue sndQ) >>= sendPending @@ -677,12 +686,14 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS atomically $ writeTVar timeoutErrorCount 0 monitor :: ProtocolClient v err msg -> IO () - monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount}} = loop smpPingInterval + monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount, sentCommands}} = loop smpPingInterval where loop :: Int64 -> IO () loop delay = do threadDelay' delay - diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived + ts <- getCurrentTime + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL + diff <- diffUTCTime ts <$> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -763,6 +774,9 @@ closeProtocolClient :: ProtocolClient v err msg -> IO () closeProtocolClient = mapM_ (deRefWeak >=> mapM_ killThread) . action {-# INLINE closeProtocolClient #-} +pClientSentCommandsCount :: ProtocolClient v err msg -> IO Int +pClientSentCommandsCount ProtocolClient {client_ = PClient {sentCommands}} = M.size <$> readTVarIO sentCommands + -- | SMP client error type. data ProtocolClientError err = -- | Correctly parsed SMP server ERR response. @@ -888,7 +902,7 @@ processSUBResponse_ c rId = \case r' -> pure . Left $ unexpectedResponse r' writeSMPMessage :: SMPClient -> RecipientId -> BrokerMsg -> IO () -writeSMPMessage c rId msg = atomically $ mapM_ (`writeTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) +writeSMPMessage c rId msg = mapM_ (`nonBlockingWriteTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) serverTransmission :: ProtocolClient v err msg -> NonEmpty (RecipientId, ServerTransmission err msg) -> ServerTransmissionBatch v err msg serverTransmission ProtocolClient {thParams, client_ = PClient {transportSession}} ts = (transportSession, thParams, ts) @@ -1344,19 +1358,15 @@ streamProtocolCommands c@ProtocolClient {thParams} nm cs cb = do mapM_ (cb <=< sendBatch c nm) bs sendBatch :: ProtocolClient v err msg -> NetworkRequestMode -> TransportBatch (Request err msg) -> IO [Response err msg] -sendBatch c@ProtocolClient {client_ = PClient {sndQ}} nm b = do +sendBatch c nm b = do case b of TBError e Request {entityId} -> do putStrLn "send error: large message" pure [Response entityId $ Left $ PCETransportError e] TBTransmissions s n rs - | n > 0 -> do - nonBlockingWriteTBQueue sndQ (Nothing, s) -- do not expire batched responses - mapConcurrently (getResponse c nm Nothing) rs + | n > 0 -> sendBlock c rs (Nothing, s) $ mapConcurrently (getResponse c nm Nothing) rs -- do not expire batched responses | otherwise -> pure [] - TBTransmission s r -> do - nonBlockingWriteTBQueue sndQ (Nothing, s) - (: []) <$> getResponse c nm Nothing r + TBTransmission s r -> sendBlock c [r] (Nothing, s) $ (: []) <$> getResponse c nm Nothing r -- | Send Protocol command sendProtocolCommand :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg @@ -1369,28 +1379,41 @@ sendProtocolCommand c nm = sendProtocolCommand_ c nm Nothing Nothing -- -- Please note: if nonce is passed it is also used as a correlation ID sendProtocolCommand_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.CbNonce -> Maybe Int -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg -sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = +sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = ExceptT $ uncurry sendRecv =<< mkTransmission_ c nonce_ (entId, pKey, cmd) where - -- two separate "atomically" needed to avoid blocking sendRecv :: Either TransportError SentRawTransmission -> Request err msg -> IO (Either (ProtocolClientError err) msg) sendRecv t_ r = case t_ of Left e -> pure . Left $ PCETransportError e Right t | B.length s > blockSize - 2 -> pure . Left $ PCETransportError TELargeMsg - | otherwise -> do - nonBlockingWriteTBQueue sndQ (Just r, s) - response <$> getResponse c nm tOut r + | otherwise -> response <$> sendBlock c [r] (Just r, s) (getResponse c nm tOut r) where s = tEncodeBatch1 serviceAuth t +sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do + ts <- getCurrentTime + -- two separate "atomically" needed to avoid blocking + E.bracketOnError + (atomically $ ifM (readTVar connected) (mapM_ (addRequest ts) rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) + (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) + (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) + where + addRequest ts r@Request {corrId} = TM.insert corrId r {createdAt = ts} sentCommands + removeRequest Request {corrId} = TM.delete corrId sentCommands + +failRequest :: Request err msg -> STM () +failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do sent <- atomically $ tryWriteTBQueue q x unless sent $ void $ forkIO $ atomically $ writeTBQueue q x getResponse :: ProtocolClient v err msg -> NetworkRequestMode -> Maybe Int -> Request err msg -> IO (Response err msg) -getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} nm tOut Request {entityId, pending, responseVar} = do +getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, sentCommands, msgQ}} nm tOut Request {corrId, entityId, pending, responseVar} = do r <- fromMaybe (netTimeoutInt tcpTimeout nm) tOut `timeout` atomically (takeTMVar responseVar) response <- atomically $ do writeTVar pending False @@ -1399,14 +1422,17 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} n -- See `processMsg`. ((r <|>) <$> tryTakeTMVar responseVar) >>= \case Just r' -> writeTVar timeoutErrorCount 0 $> r' - Nothing -> modifyTVar' timeoutErrorCount (+ 1) $> Left PCEResponseTimeout + Nothing -> do + modifyTVar' timeoutErrorCount (+ 1) + when (isNothing msgQ) $ TM.delete corrId sentCommands + pure $ Left PCEResponseTimeout pure Response {entityId, response} mkTransmission :: Protocol v err msg => ProtocolClient v err msg -> ClientCommand msg -> IO (PCTransmission err msg) mkTransmission c = mkTransmission_ c Nothing mkTransmission_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> Maybe C.CbNonce -> ClientCommand msg -> IO (PCTransmission err msg) -mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentCommands}} nonce_ (entityId, pKey_, command) = do +mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonce_ (entityId, pKey_, command) = do nonce@(C.CbNonce corrId) <- maybe (atomically $ C.randomCbNonce clientCorrId) pure nonce_ let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth thParams (CorrId corrId, entityId, command) auth = authTransmission (thAuth thParams) (useServiceAuth command) pKey_ (Just nonce) tForAuth @@ -1415,6 +1441,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentC where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do + createdAt <- getCurrentTime pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = @@ -1422,10 +1449,10 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentC { corrId, entityId, command, + createdAt, pending, responseVar } - atomically $ TM.insert corrId r sentCommands pure r authTransmission :: Maybe (THandleAuth 'TClient) -> Bool -> Maybe C.APrivateAuthKey -> Maybe C.CbNonce -> ByteString -> Either TransportError (Maybe TAuthorizations) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 18ee7dd8a..0d8bf9348 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -105,7 +105,7 @@ import Simplex.Messaging.Agent.Store.Common (DBStore (..), withTransaction) import Simplex.Messaging.Agent.Store.Interface import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationConfirmation (..), MigrationError (..)) -import Simplex.Messaging.Client (pattern NRMInteractive, NetworkConfig (..), ProtocolClientConfig (..), TransportSessionMode (..), defaultClientConfig, defaultSMPClientConfig, getProtocolClient, sendSMPMessage) +import Simplex.Messaging.Client (pattern NRMInteractive, NetworkConfig (..), NetworkTimeout (..), ProtocolClientConfig (..), TransportSessionMode (..), defaultClientConfig, defaultSMPClientConfig, getProtocolClient, sendSMPMessage) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.File (CryptoFile (..)) import Simplex.Messaging.Crypto.Ratchet (InitialKeys (..), PQEncryption (..), PQSupport (..), pattern IKPQOff, pattern IKPQOn, pattern PQEncOff, pattern PQEncOn, pattern PQSupportOff, pattern PQSupportOn) @@ -123,7 +123,7 @@ import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..)) import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, VersionSMP, currentServerSMPRelayVersion, minClientSMPRelayVersion, minServerSMPRelayVersion, alpnSupportedSMPHandshakes) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) -import Simplex.Messaging.Util (bshow, diffToMicroseconds) +import Simplex.Messaging.Util (bshow, diffToMicroseconds, unlessM) import Simplex.Messaging.Version (VersionRange (..)) import qualified Simplex.Messaging.Version as V import Simplex.Messaging.Version.Internal (Version (..)) @@ -270,6 +270,9 @@ agentCfgVPrevPQ = agentCfgRatchetVPrev :: HasTestEnv => AgentConfig agentCfgRatchetVPrev = agentCfg {e2eEncryptVRange = prevRange $ e2eEncryptVRange agentCfg} +initAgentServersLongConnect :: HasTestEnv => InitialAgentServers +initAgentServersLongConnect = initAgentServers {netCfg = (netCfg initAgentServers) {tcpConnectTimeout = NetworkTimeout 15_000000 15_000000}} + mkVersionRange :: Word16 -> Word16 -> VersionRange v mkVersionRange v1 v2 = V.mkVersionRange (Version v1) (Version v2) @@ -369,6 +372,7 @@ functionalAPITests ps = do describe "Establish duplex connection via contact address" $ do testMatrix2 ps runAgentClientContactTest it "should not decrypt contact request with zero DH secret" $ testContactRequestZeroSecret ps + it "should not block the connection while the server of the contact request does not respond" $ testAcceptContactStallingServer ps describe "should delete contact request when it is accepted" $ do it "request without double ratchet" $ withSmpServer ps $ testDeleteAcceptedContactRequest False False it "request without double ratchet, async accept" $ withSmpServer ps $ testDeleteAcceptedContactRequest False True @@ -421,6 +425,10 @@ functionalAPITests ps = do withSmpServer ps testSignedServiceRequestAsync it "should deliver a service response across server outages" $ testServiceRequestResilient ps + it "should expire the service request while the server of the service does not respond" $ + testServiceRequestStallingServer ps + it "should delete the reply queue when the service request expires while the queue is created" $ + testServiceRequestExpiringReplyQueue ps describe "Changing connection user id" $ do it "should change user id for new connections" $ do withSmpServer ps testUpdateConnectionUserId @@ -513,6 +521,8 @@ functionalAPITests ps = do describe "Subscription mode OnlyCreate" $ do it "messages delivered only when polled" $ withSmpServer ps testOnlyCreatePull + it "should acknowledge polled message when event queue is full" $ + withSmpServer ps testAckMessageFullQueue describe "Inactive client disconnection" $ do it "should disconnect clients without subs if they were inactive longer than TTL" $ testInactiveNoSubs ps @@ -529,6 +539,8 @@ functionalAPITests ps = do testSuspendingAgentTimeout ps it "should send messages queued after file is sent before agent is suspended" $ testSuspendingAgentCompleteSendingFile ps + it "should suspend agent when event queue is full" $ + testSuspendingAgentFullQueue describe "Batching SMP commands" $ do it "should subscribe to multiple (200) subscriptions with batching" $ testBatchedSubscriptions 200 20 ps @@ -537,6 +549,10 @@ functionalAPITests ps = do it "should subscribe to multiple connections with pending messages" $ withSmpServer ps $ testBatchedPendingMessages 10 5 + it "should subscribe to connections with pending messages when event queue is full" $ + withSmpServer ps testBatchedPendingMessagesFullQueues + it "should subscribe and delete repeated connection IDs when event queue is full" $ + withSmpServer ps testDuplicateConnIdsFullQueue describe "Batch send messages" $ do it "should send multiple messages to the same connection" $ withSmpServer ps testSendMessagesB it "should send messages to the 2 connections" $ withSmpServer ps testSendMessagesB2 @@ -553,6 +569,8 @@ functionalAPITests ps = do testBasicMatrix2 ps testAcceptContactAsync it "should delete connections using async command when server connection fails" $ testDeleteConnectionAsync ps + it "should delete connection without receive queue when event queue is full" $ + testDeleteConnectionAsyncFullQueue it "join connection when reply queue creation fails" $ testJoinConnectionAsyncReplyError ps describe "delete connection waiting for delivery" $ do @@ -571,6 +589,10 @@ functionalAPITests ps = do withSmpServer ps testUsers it "should create and delete user without connections" $ withSmpServer ps testDeleteUserQuietly + it "should delete user without connections when event queue is full" $ + testDeleteUserFullQueue + it "should delete user when statistics are not saved and event queue is full" $ + testDeleteUserStatsErrorFullQueue it "should create and delete user with connections when server connection fails" $ testUsersNoServer ps it "should connect two users and switch session mode" $ @@ -581,6 +603,7 @@ functionalAPITests ps = do it "should clear pending service sub when service unavailable" $ testServiceUnavailableClearsPending ps it "should recover when service ID changes on reconnect" $ testServiceIdChangeOnReconnect ps it "should handle service unavailable on startup" $ testServiceUnavailableOnStartup ps + it "should handle service unavailable on startup when event queue is full" $ testServiceUnavailableFullQueue ps it "migrate connections to and from service" $ testMigrateConnectionsToService ps describe "Connection switch" $ do describe "should switch delivery to the new queue with fast rotation" $ @@ -591,6 +614,18 @@ functionalAPITests ps = do testFastSwitchDrainOldQueue ps it "should drain the old queue after QEND on the new queue and restart" $ testFastSwitchDrainOldQueueRestart ps + it "should receive messages while the server of the new queue does not respond" $ + testFastSwitchStallingNewServer ps + it "should delete the new queue when the switch is aborted while the queue is created" $ + testSwitchChangedWhileNewQueue abortConnectionSwitch "switchConnection: aborted" ps + it "should delete the new queue when ratchet synchronization starts while the queue is created" $ + testSwitchChangedWhileNewQueue (\c connId -> synchronizeRatchet c connId PQSupportOn True) "switchConnection: send prohibited" ps + it "should delete the new queue when the connection is deleted while the queue is created" $ + testSwitchConnectionDeletedWhileNewQueue ps + it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ + testSwitchRatchetSyncBeforeNewQueue ps + it "should secure the new queue and complete the switch after ratchet synchronization" $ + testFastSwitchRatchetSyncWhileSecuring ps describe "should switch delivery to the new queue" $ testServerMatrix2 ps testSwitchConnection describe "should switch to new queue asynchronously" $ @@ -644,6 +679,9 @@ functionalAPITests ps = do describe "getConnectionVerifyCodes" $ it "should return the same codes for both peers" $ withSmpServer ps testConnectionVerifyCodes + describe "Connection locks" $ + it "should prohibit server requests in connection lock" $ + withSmpServer ps testServerRequestInConnLock describe "Delivery receipts" $ do it "should send and receive delivery receipt" $ withSmpServer ps testDeliveryReceipts it "send delivery receipts concurrently with messages" $ testDeliveryReceiptsConcurrent ps @@ -1153,6 +1191,25 @@ testContactRequestZeroSecret ps = withSmpServer ps $ withAgentClients2 $ \alice void $ joinConnection bob 1 True qInfo "bob's connInfo" SMSubscribe get alice =##> \case ("", c, REQ _ _ "bob's connInfo") -> c == contactId; _ -> False +testAcceptContactStallingServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testAcceptContactStallingServer ps@(t, ASType qsType _) = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServersLongConnect testDB $ \a -> do + (bId, invId) <- withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> + withAgent 2 agentCfg bServers testDB2 $ \b -> runRight $ do + (_, cReq) <- createConnection a 1 True SCMContact Nothing SMSubscribe + void $ joinConnection b 1 True cReq "bob's connInfo" SMSubscribe + ("", _, REQ invId _ "bob's connInfo") <- get a + (bId, _) <- A.prepareConnectionToAccept a 1 True invId PQSupportOn + pure (bId, invId) + withStallingServerOn' testPort2 $ \accepted _ -> + withAsync (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) $ \_ -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + Just (Left (A.CMD PROHIBITED _)) <- timeout 5_000000 . runExceptT $ synchronizeRatchet a bId PQSupportOn False + timeout 1_000000 (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) `shouldReturn` Nothing + where + bServers = initAgentServers {smp = userServers [testSMPServer2]} + testDeleteAcceptedContactRequest :: (HasCallStack, HasTestEnv) => Bool -> Bool -> IO () testDeleteAcceptedContactRequest useDR asyncAccept = withAgentClients2 $ \alice bob -> runRight_ $ do @@ -1638,6 +1695,42 @@ testServiceRequestResilient ps = withAgentClients2 $ \service client -> do wait reqAsync resp `shouldBe` Right "resilient response" +testServiceRequestStallingServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testServiceRequestStallingServer ps@(t, ASType qsType _) = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServersLongConnect testDB $ \client -> do + connReq <- withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> + withAgent 2 agentCfg serviceServers testDB2 $ \service -> runRight $ do + (_, CCLink connReq _) <- A.createConnection service NRMInteractive 1 True True SCMContact (Just serviceUserLinkData) Nothing IKPQOn True SMSubscribe + pure connReq + withStallingServerOn testPort2 $ do + timeout 5_000000 (runExceptT $ sendServiceRequestAsync client 1 connReq (Just 1) Nothing "service request") + `shouldReturn` Just (Left $ AGENT $ A_SERVICE ASETimeout) + threadDelay 500000 + withTransaction (store $ agentEnv client) getConnIds `shouldReturn` [] + where + serviceServers = initAgentServers {smp = userServers [testSMPServer2]} + +testServiceRequestExpiringReplyQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testServiceRequestExpiringReplyQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServers testDB2 $ \service -> do + (_, CCLink connReq _) <- runRight $ A.createConnection service NRMInteractive 1 True True SCMContact (Just serviceUserLinkData) Nothing IKPQOn True SMSubscribe + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAgent 1 agentCfg clientServers testDB $ \client -> + withAsync (runExceptT $ sendServiceRequestAsync client 1 connReq (Just 1) Nothing "service request") $ \req -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + timeout 5_000000 (wait req) `shouldReturn` Just (Left $ AGENT $ A_SERVICE ASETimeout) + get client =##> \case ("", "", DEL_CONNS [_]) -> True; _ -> False + withTransaction (store $ agentEnv client) getConnIds `shouldReturn` [] + atomically $ putTMVar opened () + suspendAgent client 5_000000 + nGet client ##> ("", "", SUSPENDED) + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + where + clientServers = initAgentServersLongConnect {smp = userServers [testSMPServer2]} + testUpdateConnectionUserId :: (HasCallStack, HasTestEnv) => IO () testUpdateConnectionUserId = withAgentClients2 $ \alice bob -> runRight_ $ do @@ -3190,6 +3283,21 @@ testOnlyCreatePull = withAgentClients2 $ \alice bob -> runRight_ $ do ackMessage alice bobId 3 Nothing getMSGNTF alice bobId +testAckMessageFullQueue :: HasTestEnv => IO () +testAckMessageFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ makeConnection a b + runRight_ $ do + msgId <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT msgId) + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight_ $ do + ("", _, Msg' msgId _ "hello") <- getMsg b aId $ get b + liftIO $ do + fillSubQ b + timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ b + getMSGNTF b aId + makeConnection :: AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId) makeConnection = makeConnection_ PQSupportOn @@ -3356,6 +3464,15 @@ testSuspendingAgentCompleteSendingFile ps = suspendedOps :: AgentClient -> IO [Bool] suspendedOps c = mapM (\op -> opSuspended <$> readTVarIO (op c)) [rcvNetworkOp, sndFilesOp, msgDeliveryOp] +testSuspendingAgentFullQueue :: HasTestEnv => IO () +testSuspendingAgentFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + threadDelay 100000 + fillSubQ a + timeout 5_000000 (suspendAgent a 1_000000) `shouldReturn` Just () + void . atomically . flushTBQueue $ subQ a + nGet a ##> ("", "", SUSPENDED) + testBatchedSubscriptions :: HasTestEnv => Int -> Int -> (ASrvTransport, AStoreType) -> IO () testBatchedSubscriptions nCreate nDel ps@(t, ASType qsType _) = do (conns, conns') <- withAgentClientsCfgServers2 agentCfg agentCfg initAgentServers2 $ \a b -> do @@ -3457,6 +3574,35 @@ testBatchedPendingMessages nCreate nMsgs = ("", cId, AEvt SAEConn (Msg' msgId _ "hello")) -> pure $ Right (cId, msgId) r -> error $ "unexpected event: " <> show r +testBatchedPendingMessagesFullQueues :: HasTestEnv => IO () +testBatchedPendingMessagesFullQueues = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + conns <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ replicateM 6 $ makeConnection a b + runRight_ $ forM_ conns $ \(_, bId) -> do + msgId <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT msgId) + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do + fillSubQ b + timeout 5_000000 (runExceptT $ subscribeAllConnections b False Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ b + timeout 5_000000 (receiveMsgs b $ map ((,"hello") . fst) conns) `shouldReturn` Just () + +testDuplicateConnIdsFullQueue :: HasTestEnv => IO () +testDuplicateConnIdsFullQueue = withAgentClients2 $ \a b -> do + (_, bId) <- runRight $ makeConnection a b + fillSubQ a + Just (Right subRs) <- timeout 5_000000 . runExceptT $ subscribeConnections a [bId, bId] + M.keys subRs `shouldBe` [bId] + Just (Right delRs) <- timeout 5_000000 . runExceptT $ deleteConnections a [bId, bId] + M.keys delRs `shouldBe` [bId] + void . atomically . flushTBQueue $ subQ a + getInAnyOrder a [resultSizeErr "subscribeConnections", resultSizeErr "deleteConnections"] + where + resultSizeErr :: String -> ATransmission -> Bool + resultSizeErr name = \case + ("", "", AEvt SAEConn (ERR (INTERNAL e))) -> (name <> " result size") `isPrefixOf` e + _ -> False + testSendMessagesB :: HasTestEnv => IO () testSendMessagesB = withAgentClients2 $ \a b -> runRight_ $ do (aId, bId) <- makeConnection a b @@ -3700,6 +3846,20 @@ testDeleteConnectionAsync ps = get a =##> \case ("", "", DEL_CONNS cs) -> length cs == 3 && all (`elem` connIds) cs; _ -> False liftIO $ noMessages a "nothing else should be delivered to alice" +testDeleteConnectionAsyncFullQueue :: HasTestEnv => IO () +testDeleteConnectionAsyncFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + (connId, _) <- runRight $ A.prepareConnectionToJoin a 1 True (CRInvitationUri connReqData testE2ERatchetParams12) PQSupportOn + fillSubQ a + timeout 5000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ a + get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False + +fillSubQ :: AgentClient -> IO () +fillSubQ c = atomically fill + where + fill = unlessM (isFullTBQueue $ subQ c) $ writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) >> fill + testWaitDeliveryNoPending :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () testWaitDeliveryNoPending ps = withAgentClients2 $ \alice bob -> withSmpServerStoreLogOn ps testPort $ \_ -> runRight_ $ do @@ -3991,6 +4151,26 @@ testDeleteUserQuietly = exchangeGreetingsMsgId 4 a bId b aId liftIO $ noMessages a "nothing else should be delivered to alice" +testDeleteUserFullQueue :: HasTestEnv => IO () +testDeleteUserFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] + fillSubQ a + timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ a + nGet a =##> \case ("", "", DEL_USER u) -> u == auId; _ -> False + +testDeleteUserStatsErrorFullQueue :: HasTestEnv => IO () +testDeleteUserStatsErrorFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] + withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats RENAME TO servers_stats_") + fillSubQ a + timeout 5_000000 (runExceptT $ deleteUser a auId False) `shouldReturn` Just (Right ()) + withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats_ RENAME TO servers_stats") + void . atomically . flushTBQueue $ subQ a + get a =##> \case ("", "", ERR (INTERNAL _)) -> True; _ -> False + testUsersNoServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testUsersNoServer ps = withAgentClientsCfg2 aCfg agentCfg $ \a b -> do (aId, bId, auId, _aId', bId') <- withSmpServerStoreLogOn ps testPort $ \_ -> runRight $ do @@ -4127,6 +4307,120 @@ testFastSwitchDrainOldQueueRestart ps = subscribeConnection a bId drainOldQueue a bId b aId +testFastSwitchStallingNewServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testFastSwitchStallingNewServer ps@(t, ASType qsType _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do + (aId, bId, aId', bId') <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ do + (aId, bId) <- makeConnection a b + (aId', bId') <- makeConnection a b + pure (aId, bId, aId', bId') + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do + _ <- switchConnectionAsync b "" aId + phaseRcv b aId SPStarted [Just RSSendingQADD, Nothing] + withStallingServerOn testPort2 $ + withAgent 1 agentCfg initAgentServersLongConnect testDB $ \a -> runRight_ $ do + void $ subscribeConnections a [bId, bId'] + void $ sendMessage b aId SMP.noMsgFlags "hello" + void $ sendMessage b aId' SMP.noMsgFlags "hello too" + liftIO $ timeout 5_000000 (receiveMsgs a [(bId, "hello"), (bId', "hello too")]) `shouldReturn` Just () + +receiveMsgs :: AgentClient -> [(ConnId, MsgBody)] -> IO () +receiveMsgs _ [] = pure () +receiveMsgs c msgs = + pGet c >>= \case + (_, cId, AEvt SAEConn (MSG _ _ body)) -> receiveMsgs c $ filter (/= (cId, body)) msgs + _ -> receiveMsgs c msgs + +testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () +testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ changeSwitch b aId + atomically $ putTMVar opened () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitRcvQueueRecords b 1 + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + +testSwitchConnectionDeletedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + runRight_ $ deleteConnection b aId + atomically $ putTMVar opened () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + +testSwitchRatchetSyncBeforeNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchRatchetSyncBeforeNewQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort2 $ \_ -> do + setUserNetworkInfo b $ UserNetworkInfo UNNone False + runRight_ $ do + void $ switchConnectionAsync b "" aId + void $ synchronizeRatchet b aId PQSupportOn True + setUserNetworkInfo b $ UserNetworkInfo UNWifi True + get b =##> \case ("", c, ERR (A.CMD PROHIBITED "switchConnection: send prohibited")) -> c == aId; _ -> False + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + storeLogQueues testStoreLogFile2 `shouldReturn` (0, 0) + +waitRcvQueueRecords :: HasCallStack => AgentClient -> Int -> IO () +waitRcvQueueRecords c n = go (50 :: Int) + where + go i = do + qs :: [(ConnId, Int64)] <- withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, rcv_queue_id FROM rcv_queues") + unless (length qs == n) $ + if i > 0 + then threadDelay 100000 >> go (i - 1) + else expectationFailure $ "receive queue records: " <> show qs + +storeLogQueues :: FilePath -> IO (Int, Int) +storeLogQueues storeLogFile = do + records <- B.lines <$> B.readFile storeLogFile + pure (count "CREATE " records, count "DELETE " records) + where + count tag = length . filter (tag `B.isPrefixOf`) + +testFastSwitchRatchetSyncWhileSecuring :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer ps $ do + a <- getSMPAgentClient' 1 agentCfg initAgentServers testDB + (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ makeConnection a b + setProtocolServers a 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do + _ <- switchConnectionAsync a "" bId + phaseRcv a bId SPStarted [Just RSSendingQADD, Nothing] + withAgent 3 agentCfg initAgentServers testDB2 $ \b -> do + runRight_ $ do + subscribeConnection b aId + phaseSnd b aId SPStarted [Just SSSecuringQueue, Nothing] + disposeAgentClient a + ConnectionStats {ratchetSyncState} <- runRight $ synchronizeRatchet b aId PQSupportOn True + ratchetSyncState `shouldBe` RSStarted + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> do + threadDelay 3000000 + withAgent 4 agentCfg initAgentServers testDB $ \a' -> do + runRight_ $ subscribeConnection a' bId + concurrently_ + (timeout 20_000000 (runRight_ $ drainSwitchCompleted a' bId QDRcv) `shouldReturn` Just ()) + (timeout 20_000000 (runRight_ $ drainSwitchCompleted b aId QDSnd) `shouldReturn` Just ()) + endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b @@ -4599,6 +4893,19 @@ testConnectionVerifyCodes = codes1'' <- getConnectionVerifyCodes a bId liftIO $ codes1'' `shouldBe` codes1 +testServerRequestInConnLock :: (HasCallStack, HasTestEnv) => IO () +testServerRequestInConnLock = + withAgentClients2 $ \a b -> do + (_, bId) <- runRight $ makeConnection a b + let queueInfo = getConnectionQueueInfo a NRMInteractive bId + Left (A.INTERNAL e) <- runExceptT . withAgentEnv a . withConnLock a bId "test" . ExceptT . liftIO $ runExceptT queueInfo + e `shouldBe` "server request in connection lock test" + atomically (swapTVar (connLockViolations a) []) `shouldReturn` ["test"] + runRight_ $ void queueInfo + rs <- runRight $ withAgentEnv a . withConnLock a bId "batch" . ExceptT . liftIO $ runExceptT (subscribeConnections a [bId]) + M.lookup bId rs `shouldBe` Just (Left $ A.INTERNAL "server request in connection lock batch") + atomically (swapTVar (connLockViolations a) []) `shouldReturn` ["batch"] + testDeliveryReceipts :: (HasCallStack, HasTestEnv) => IO () testDeliveryReceipts = withAgentClients2 $ \a b -> runRight_ $ do @@ -5244,6 +5551,24 @@ testServiceUnavailableOnStartup (t, msType) = do ("", "", UP _ [_]) <- nGet user exchangeGreetingsMsgId 6 service uId user sId +testServiceUnavailableFullQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testServiceUnavailableFullQueue (t, msType) = do + withAgentClientsServers2 (agentCfg, initAgentServersClientService) (agentCfg, initAgentServers) $ \service user -> + withSmpServerStoreLogOn (t, msType) testPort $ \_ -> runRight_ . void $ makeConnection service user + let cfgNoService = updateCfg (cfgMS msType) $ \(cfg' :: ServerConfig s) -> + let ServerConfig {transportConfig} = cfg' + in cfg' {transportConfig = transportConfig {askClientCert = False}} :: ServerConfig s + withAgent 1 agentCfg initAgentServersClientService testDB $ \service -> + withSmpServerConfigOn t cfgNoService testPort $ \_ -> do + fillSubQ service + timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ service + getInAnyOrder + service + [ \case ("", "", AEvt SAEConn (ERR (BROKER _ NO_SERVICE))) -> True; _ -> False, + \case ("", "", AEvt SAENone (UP _ [_])) -> True; _ -> False + ] + testMigrateConnectionsToService :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testMigrateConnectionsToService ps = do (((sId1, uId1), (uId2, sId2)), ((sId3, uId3), (uId4, sId4)), ((sId5, uId5), (uId6, sId6))) <- diff --git a/tests/CoreTests/BatchingTests.hs b/tests/CoreTests/BatchingTests.hs index fef0d584f..ec4790bbd 100644 --- a/tests/CoreTests/BatchingTests.hs +++ b/tests/CoreTests/BatchingTests.hs @@ -9,8 +9,11 @@ module CoreTests.BatchingTests (batchingTests) where +import Control.Concurrent (threadDelay) +import Control.Concurrent.Async (async, cancel) import Control.Concurrent.STM import Control.Monad +import Control.Monad.Trans.Except (runExceptT) import Crypto.Random (ChaChaDRG) import qualified Data.ByteString as B import Data.ByteString.Char8 (ByteString) @@ -44,6 +47,14 @@ batchingTests = do it "should break on large message" testClientBatchWithLargeMessage describe "tDecodeServer" $ it "should copy IDs out of received block" testDecodeServerCopiesIds + describe "sendProtocolCommand_" $ do + it "should not queue command after timeout or cancellation" testCommandNotQueuedAfterEnd + it "should not keep timed out command" testTimedOutCommandNotKept + it "should not keep command of cancelled thread" testCancelledCommandNotKept + describe "sendProtocolCommands" $ do + it "should not keep command that is too large" testLargeBatchCommandNotKept + it "should not keep commands of cancelled batch" testCancelledBatchNotKept + it "should not queue batch after cancellation" testBatchNotQueuedAfterEnd testBatchSubscriptions :: IO () testBatchSubscriptions = do @@ -185,6 +196,67 @@ testDecodeServerCopiesIds = do sharesBuffer s (bs corrId') `shouldReturn` False sharesBuffer s (unEntityId entId') `shouldReturn` False +testCommandNotQueuedAfterEnd :: IO () +testCommandNotQueuedAfterEnd = do + client <- testClientStub + let sndQ = pClientSndQ client + ping tOut = runExceptT $ sendProtocolCommand_ client NRMBackground Nothing tOut Nothing NoEntity (Cmd SIdleClient PING) + replicateM_ 100 $ atomically $ writeTBQueue sndQ (Nothing, "") + ping (Just 100000) `shouldReturn` Left PCEResponseTimeout + cancelled <- async $ ping Nothing + threadDelay 100000 + cancel cancelled + replicateM_ 2 $ atomically $ readTBQueue sndQ + threadDelay 100000 + atomically (lengthTBQueue sndQ) `shouldReturn` 98 + +testTimedOutCommandNotKept :: IO () +testTimedOutCommandNotKept = do + c <- testClientStub + runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) Nothing NoEntity (Cmd SIdleClient PING)) + `shouldReturn` Left PCEResponseTimeout + pClientSentCommandsCount c `shouldReturn` 0 + +testCancelledCommandNotKept :: IO () +testCancelledCommandNotKept = do + c <- testClientStub + a <- async $ runExceptT $ sendProtocolCommand c NRMBackground Nothing NoEntity (Cmd SIdleClient PING) + threadDelay 100000 + pClientSentCommandsCount c `shouldReturn` 1 + cancel a + pClientSentCommandsCount c `shouldReturn` 0 + +testLargeBatchCommandNotKept :: IO () +testLargeBatchCommandNotKept = do + c <- testClientStub + msg <- atomically . C.randomBytes 17000 =<< C.newRandom + [Response _ (Left (PCETransportError TELargeMsg))] <- L.toList <$> sendProtocolCommands c NRMBackground (L.fromList [(NoEntity, Nothing, Cmd SSender $ SEND noMsgFlags msg)]) + pClientSentCommandsCount c `shouldReturn` 0 + +testCancelledBatchNotKept :: IO () +testCancelledBatchNotKept = do + c <- testClientStub + g <- C.newRandom + subs <- replicateM 300 $ atomically $ randomSUBClientCmd g + a <- async $ sendProtocolCommands c NRMBackground $ L.fromList subs + _ <- atomically $ readTBQueue $ pClientSndQ c + pClientSentCommandsCount c `shouldReturn` 30 + cancel a + pClientSentCommandsCount c `shouldReturn` 0 + +testBatchNotQueuedAfterEnd :: IO () +testBatchNotQueuedAfterEnd = do + c <- testClientStub + let sndQ = pClientSndQ c + replicateM_ 100 $ atomically $ writeTBQueue sndQ (Nothing, "") + sub <- atomically . randomSUBClientCmd =<< C.newRandom + a <- async $ sendProtocolCommands c NRMBackground $ L.fromList [sub] + threadDelay 100000 + cancel a + _ <- atomically $ readTBQueue sndQ + threadDelay 100000 + atomically (lengthTBQueue sndQ) `shouldReturn` 99 + sharesBuffer :: ByteString -> ByteString -> IO Bool sharesBuffer block s = unsafeUseAsCString block $ \blockPtr -> unsafeUseAsCString s $ \ptr -> @@ -216,6 +288,12 @@ randomSUBCmd c = do (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g mkTransmission c (EntityId rId, Just rpKey, Cmd SRecipient SUB) +randomSUBClientCmd :: TVar ChaChaDRG -> STM (ClientCommand BrokerMsg) +randomSUBClientCmd g = do + rId <- C.randomBytes 24 g + (_, rpKey) <- C.generateAuthKeyPair C.SEd25519 g + pure (EntityId rId, Just rpKey, Cmd SRecipient SUB) + randomENDCmd :: IO (Transmission BrokerMsg) randomENDCmd = do g <- C.newRandom diff --git a/tests/SMPAgentClient.hs b/tests/SMPAgentClient.hs index feb43387e..0e4b2cacc 100644 --- a/tests/SMPAgentClient.hs +++ b/tests/SMPAgentClient.hs @@ -99,6 +99,7 @@ agentCfg = ntfCfg = defaultNTFClientConfig {qSize = 1, defaultTransport = (ntfTestPort, transport @TLS), networkConfig}, reconnectInterval = fastRetryInterval, persistErrorInterval = 1, + prohibitRequestsInConnLock = True, caCertificateFile = "tests/fixtures/ca.crt", privateKeyFile = "tests/fixtures/server.key", certificateFile = "tests/fixtures/server.crt" diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 24f49cea7..ec602dc06 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -24,7 +24,7 @@ import qualified Data.X509 as X import qualified Data.X509.File as XF import qualified Data.X509.Validation as XV import Network.Socket -import Network.Socket.ByteString (recv) +import Network.Socket.ByteString (recv, sendAll) import qualified Network.TLS as TLS import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) @@ -45,6 +45,7 @@ import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal import System.Directory (copyFile, removeFile) import Test.Hspec hiding (fit, it) +import UnliftIO.Async (race_) import UnliftIO.Concurrent import qualified UnliftIO.Exception as E import UnliftIO.STM (TMVar, atomically, checkSTM, newEmptyTMVarIO, orElse, putTMVar, readTMVar, readTVar, registerDelay, takeTMVar, tryPutTMVar) @@ -81,6 +82,9 @@ testPort = testServerPort 1 testPort2 :: HasTestEnv => ServiceName testPort2 = testServerPort 2 +testPort3 :: HasTestEnv => ServiceName +testPort3 = testServerPort 8 + ntfTestPort :: HasTestEnv => ServiceName ntfTestPort = testServerPort 3 @@ -494,6 +498,22 @@ withStallingServerOn' port action = do (pure ()) (const $ action accepted closed) +withGatedServerOn :: HasCallStack => ServiceName -> ServiceName -> (TMVar () -> TMVar () -> IO a) -> IO a +withGatedServerOn port srvPort action = do + accepted <- newEmptyTMVarIO + opened <- newEmptyTMVarIO + let forward from to = recv from 4096 >>= \s -> unless (B.null s) $ sendAll to s >> forward from to + serverBracket + (\started -> runLocalTCPServer started port $ \sock -> do + void $ atomically $ tryPutTMVar accepted () + atomically $ readTMVar opened + addr : _ <- getAddrInfo (Just defaultHints {addrSocketType = Stream}) (Just "127.0.0.1") (Just srvPort) + E.bracket (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close $ \srvSock -> do + connect srvSock $ addrAddress addr + race_ (forward sock srvSock) (forward srvSock sock)) + (pure ()) + (const $ action accepted opened) + withSmpServerOn :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> ServiceName -> IO a -> IO a withSmpServerOn ps port' = withSmpServerThreadOn ps port' . const diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 59bb14b53..c606d73ff 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -21,6 +21,7 @@ import Control.Logger.Simple import Control.Monad (forM, forM_, forever, replicateM_) import Control.Monad.Trans.Except (ExceptT, runExceptT) import Data.ByteString.Char8 (ByteString) +import qualified Data.ByteString.Char8 as B import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as L import Data.Time.Clock (getCurrentTime) @@ -50,7 +51,6 @@ import UnliftIO import Util #if defined(dbServerPostgres) -import qualified Data.ByteString.Char8 as B import Data.Hashable (hash) import Data.Int (Int64) import Database.PostgreSQL.Simple (Binary (..), Only (..)) @@ -72,6 +72,12 @@ smpProxyTests = do testProxyReconnectAfterRelayRestart it "closes connection to relay after sender disconnects mid-connection" $ \_ -> testProxyClosesRelayConnectionAfterDisconnect + it "does not keep oversized forwarded command" $ \_ -> + testForwardOversizedNotKept + it "fails commands of closed client at once" $ \_ -> + testClosedClientCommandsFail + it "releases command kept for late response" $ \_ -> + testLateResponseCommandReleased describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -625,6 +631,51 @@ testProxyClosesRelayConnectionAfterDisconnect = race_ (atomically $ takeTMVar accepted) requestRelaySession timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testForwardOversizedNotKept :: HasTestEnv => IO () +testForwardOversizedNotKept = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let proxyClientCfg = defaultSMPClientConfig {serverVRange = supportedProxyClientSMPRelayVRange, agreeSecret = True, proxyServer = True} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) proxyClientCfg [] Nothing ts (\_ -> pure ()) + (k, _) <- atomically $ C.generateKeyPair @'C.X25519 g + let et = SMP.EncTransmission $ B.replicate smpBlockSize 'a' + runExceptT (forwardSMPTransmission c (either error id $ C.corrCbNonce "123456789012345678901234") currentClientSMPRelayVersion k et) + `shouldReturn` Left (PCETransportError TELargeMsg) + pClientSentCommandsCount c `shouldReturn` 0 + +testClosedClientCommandsFail :: HasTestEnv => IO () +testClosedClientCommandsFail = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + closed <- newEmptyTMVarIO + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) + closeProtocolClient c + atomically $ takeTMVar closed + Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) + forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) + pClientSentCommandsCount c `shouldReturn` 0 + atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 + +testLateResponseCommandReleased :: HasTestEnv => IO () +testLateResponseCommandReleased = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + msgQ <- newTBQueueIO 4 + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) + rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) + `shouldReturn` Left PCEResponseTimeout + pClientSentCommandsCount c `shouldReturn` 1 + threadDelay 1000000 + pClientSentCommandsCount c `shouldReturn` 0 + (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ + pure () + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From 642be366bd0aaec52a2c684aa694556a48ea7149 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:46:57 +0000 Subject: [PATCH 009/159] agent: write acknowledgement event without waiting only in the API call --- src/Simplex/Messaging/Agent.hs | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 9cbc82d61..216d262ca 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -662,7 +662,7 @@ sendMessagesB c = withAgentEnv c . sendMessagesB' c {-# INLINE sendMessagesB #-} ackMessage :: AgentClient -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AE () -ackMessage c = withAgentEnv c .:. ackMessage' c Nothing +ackMessage c connId msgId rcptInfo_ = withAgentEnv c $ ackMessage' c Nothing connId msgId rcptInfo_ >>= mapM_ (liftIO . nonBlockingWriteTBQueue (subQ c)) {-# INLINE ackMessage #-} getConnectionQueueInfo :: AgentClient -> NetworkRequestMode -> ConnId -> AE ServerQueueInfo @@ -2306,7 +2306,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do then throwE e else atomically $ void $ tryPutTMVar v $ Left e -- will not overwrite existing result LET confId ownCInfo -> withServer' . tryAtomicCommand $ allowConnection' c (Just cmdId) connId confId ownCInfo >> notify OK - ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >> notify OK + ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >>= mapM_ (atomically . writeTBQueue subQ) >> notify OK SWCH -> noServer . tryAtomicCommand $ withConnLock c connId "switchConnection" getConnToSwitch >>= \case @@ -2880,27 +2880,28 @@ retrySndOp c loop = do withConnLockNotify :: AgentClient -> ConnId -> Text -> AM (Maybe ATransmission) -> AM () withConnLockNotify c connId name action = do t_ <- withConnLock c connId name action - forM_ t_ $ liftIO . nonBlockingWriteTBQueue (subQ c) + forM_ t_ $ atomically . writeTBQueue (subQ c) -ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM () -ackMessage' c cmdId_ connId msgId rcptInfo_ = do - ack_ <- withConnLock c connId "ackMessage" $ do - SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection {} -> markUserAck - RcvConnection {} -> markUserAck - SndConnection {} -> throwE $ CONN SIMPLEX "ackMessage" - ContactConnection {} -> throwE $ CMD PROHIBITED "ackMessage: ContactConnection" - NewConnection _ -> throwE $ CMD PROHIBITED "ackMessage: NewConnection" - forM_ ack_ $ \(rq, srvMsgId) -> do +ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM (Maybe ATransmission) +ackMessage' c cmdId_ connId msgId rcptInfo_ = + withConnLock c connId "ackMessage" markConnUserAck $>>= \(rq, srvMsgId) -> do recordAck <- ackQueueMessage c rq srvMsgId - withConnLockNotify c connId "ackMessage" $ do + withConnLock c connId "ackMessage" $ do t_ <- recordAck withStore c (`getConn` connId) >>= \case SomeConn _ conn@DuplexConnection {} -> sendRcpt conn _ -> pure () t_ <$ del where + markConnUserAck :: AM (Maybe (RcvQueue, SMP.MsgId)) + markConnUserAck = do + SomeConn _ conn <- withStore c (`getConn` connId) + case conn of + DuplexConnection {} -> markUserAck + RcvConnection {} -> markUserAck + SndConnection {} -> throwE $ CONN SIMPLEX "ackMessage" + ContactConnection {} -> throwE $ CMD PROHIBITED "ackMessage: ContactConnection" + NewConnection _ -> throwE $ CMD PROHIBITED "ackMessage: NewConnection" -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged markUserAck :: AM (Maybe (RcvQueue, SMP.MsgId)) markUserAck = From 2ce8fd6524d4e68dd77182ba74f700f5cb1688d5 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:58:24 +0000 Subject: [PATCH 010/159] tests: qualify agent INTERNAL error --- tests/AgentTests/FunctionalAPITests.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 0d8bf9348..de6f50d67 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -3600,7 +3600,7 @@ testDuplicateConnIdsFullQueue = withAgentClients2 $ \a b -> do where resultSizeErr :: String -> ATransmission -> Bool resultSizeErr name = \case - ("", "", AEvt SAEConn (ERR (INTERNAL e))) -> (name <> " result size") `isPrefixOf` e + ("", "", AEvt SAEConn (ERR (A.INTERNAL e))) -> (name <> " result size") `isPrefixOf` e _ -> False testSendMessagesB :: HasTestEnv => IO () @@ -4169,7 +4169,7 @@ testDeleteUserStatsErrorFullQueue = timeout 5_000000 (runExceptT $ deleteUser a auId False) `shouldReturn` Just (Right ()) withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats_ RENAME TO servers_stats") void . atomically . flushTBQueue $ subQ a - get a =##> \case ("", "", ERR (INTERNAL _)) -> True; _ -> False + get a =##> \case ("", "", ERR (A.INTERNAL _)) -> True; _ -> False testUsersNoServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testUsersNoServer ps = withAgentClientsCfg2 aCfg agentCfg $ \a b -> do From e1dd28379c4db89855b2c47f6d6b36843548d2ed Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:28:12 +0000 Subject: [PATCH 011/159] tests: acknowledge message when event and message queues are full --- tests/AgentTests/FunctionalAPITests.hs | 33 +++++++++++++++----------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index de6f50d67..48e64b62e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -549,8 +549,8 @@ functionalAPITests ps = do it "should subscribe to multiple connections with pending messages" $ withSmpServer ps $ testBatchedPendingMessages 10 5 - it "should subscribe to connections with pending messages when event queue is full" $ - withSmpServer ps testBatchedPendingMessagesFullQueues + it "should acknowledge message when event and message queues are full" $ + withSmpServer ps testAckMessageFullQueues it "should subscribe and delete repeated connection IDs when event queue is full" $ withSmpServer ps testDuplicateConnIdsFullQueue describe "Batch send messages" $ do @@ -3574,18 +3574,23 @@ testBatchedPendingMessages nCreate nMsgs = ("", cId, AEvt SAEConn (Msg' msgId _ "hello")) -> pure $ Right (cId, msgId) r -> error $ "unexpected event: " <> show r -testBatchedPendingMessagesFullQueues :: HasTestEnv => IO () -testBatchedPendingMessagesFullQueues = - withAgent 1 agentCfg initAgentServers testDB $ \a -> do - conns <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ replicateM 6 $ makeConnection a b - runRight_ $ forM_ conns $ \(_, bId) -> do - msgId <- sendMessage a bId SMP.noMsgFlags "hello" - get a ##> ("", bId, SENT msgId) - withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do - fillSubQ b - timeout 5_000000 (runExceptT $ subscribeAllConnections b False Nothing) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ b - timeout 5_000000 (receiveMsgs b $ map ((,"hello") . fst) conns) `shouldReturn` Just () +testAckMessageFullQueues :: HasTestEnv => IO () +testAckMessageFullQueues = withAgentClients2 $ \a b -> do + (aId, bId) : conns <- runRight $ replicateM 6 $ makeConnection a b + runRight_ $ do + msgId1 <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT msgId1) + msgId2 <- sendMessage a bId SMP.noMsgFlags "hello 2" + get a ##> ("", bId, SENT msgId2) + ("", _, Msg' msgId _ "hello") <- get b + fillSubQ b + runRight_ $ forM_ conns $ \(_, bId') -> do + msgId' <- sendMessage a bId' SMP.noMsgFlags "hello" + get a ##> ("", bId', SENT msgId') + timeout 5_000000 (atomically $ isFullTBQueue (msgQ b) >>= checkSTM) `shouldReturn` Just () + timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ b + timeout 5_000000 (receiveMsgs b $ (aId, "hello 2") : map ((,"hello") . fst) conns) `shouldReturn` Just () testDuplicateConnIdsFullQueue :: HasTestEnv => IO () testDuplicateConnIdsFullQueue = withAgentClients2 $ \a b -> do From bdf6a562409037385174c927c0a43306427c2dcf Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:42:17 +0000 Subject: [PATCH 012/159] tests: exchange greetings before polling a message after restart --- tests/AgentTests/FunctionalAPITests.hs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 48e64b62e..05769cbaa 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -3286,12 +3286,15 @@ testOnlyCreatePull = withAgentClients2 $ \alice bob -> runRight_ $ do testAckMessageFullQueue :: HasTestEnv => IO () testAckMessageFullQueue = withAgent 1 agentCfg initAgentServers testDB $ \a -> do - (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ makeConnection a b + (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ do + (aId, bId) <- makeConnection a b + exchangeGreetings a bId b aId + pure (aId, bId) runRight_ $ do - msgId <- sendMessage a bId SMP.noMsgFlags "hello" + msgId <- sendMessage a bId SMP.noMsgFlags "hello again" get a ##> ("", bId, SENT msgId) withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight_ $ do - ("", _, Msg' msgId _ "hello") <- getMsg b aId $ get b + ("", _, Msg' msgId _ "hello again") <- getMsg b aId $ get b liftIO $ do fillSubQ b timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) From 4b50358cc01bf873f9e8df433c44dca4a634ad2d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:50:22 +0000 Subject: [PATCH 013/159] agent: write SUSPENDED once for each suspension --- src/Simplex/Messaging/Agent.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 216d262ca..373474e47 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3510,15 +3510,15 @@ suspendAgent c 0 = do where suspend opSel = atomically $ modifyTVar' (opSel c) $ \s -> s {opSuspended = True} suspendAgent c@AgentClient {agentState = as} maxDelay = do - state <- + (prevState, state) <- atomically $ do - writeTVar as ASSuspending + prevState <- swapTVar as ASSuspending suspendOperation c AONtfNetwork $ pure () suspendOperation c AORcvNetwork $ suspendOperation c AOSndFiles $ suspendMsgDelivery c - readTVar as - void . forkIO $ notifySuspended c + (prevState,) <$> readTVar as + unless (prevState == ASSuspending) . void . forkIO $ notifySuspended c when (state == ASSuspending) $ do void . forkIO $ removeDeletedOrFailedSndFilesInProgress c void . forkIO $ do From 021fcfd6741d9308ee079fe82bfb397bc5b3b850 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:02:22 +0000 Subject: [PATCH 014/159] agent, clients: prevent leaked reply queues and stale HTTP/2 requests --- .github/workflows/build.yml | 4 +- scripts/ci/README.md | 2 +- simplexmq.cabal | 9 ++++ src/Simplex/Messaging/Agent.hs | 29 +++++++---- src/Simplex/Messaging/Agent/Client.hs | 43 +++++++++++----- src/Simplex/Messaging/Agent/Env/SQLite.hs | 2 - .../Messaging/Transport/HTTP2/Client.hs | 13 ++--- tests/AgentTests/FunctionalAPITests.hs | 48 ++++++++++++++++- tests/SMPAgentClient.hs | 1 - tests/XFTPServerTests.hs | 51 +++++++++++++++++-- 10 files changed, 162 insertions(+), 40 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 33309c0ea..0df0a8875 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -290,7 +290,7 @@ jobs: if: matrix.should_run == true && matrix.client_postgres == true shell: docker exec -t builder sh -eu {0} run: | - cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers ${{ env.ghc_options }} simplexmq-test + cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks ${{ env.ghc_options }} simplexmq-test bin=$(find /project/dist-client-postgres -name simplexmq-test -type f -executable) cp "$bin" /out/simplexmq-test-client-postgres @@ -495,7 +495,7 @@ jobs: cabal build --builddir=dist-postgres --jobs=$(nproc) --enable-tests -fserver_postgres --ghc-options=-O0 cabal build --jobs=$(nproc) --ghc-options=-O0 if [ "${{ matrix.client_postgres }}" = true ]; then - cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers --ghc-options=-O0 simplexmq-test + cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks --ghc-options=-O0 simplexmq-test fi - name: Record source hashes for -O0 build (GHC 8.10.7) diff --git a/scripts/ci/README.md b/scripts/ci/README.md index dd57e687d..e19dd5523 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -9,7 +9,7 @@ | a push to a draft pull request
a manual run (workflow_dispatch)
a push to master or stable in a fork | reduced | build-reduced: ubuntu-24.04 x86-64, GHC 9.6.3, at -O0 (-O2 on pushes), without the standard build | | a pull request marked ready for review, and later pushes to it
a push to master or stable in simplex-chat/simplexmq
a push of a v* tag | full | build: 5 entries (GHC 8.10.7 and 9.6.3, x86-64 and aarch64), at -O0 on pull requests and -O2 on pushes | -Both builds also run maybe-release and resolver (python). Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. The ubuntu-24.04 x86-64 entry also runs the tests built with `-fclient_postgres -fslow_servers` (agent with the PostgreSQL store, and XFTP servers that delay responses for the slow-server test, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store". After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. +Both builds also run maybe-release and resolver (python). Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. The ubuntu-24.04 x86-64 entry also runs the tests built with `-fclient_postgres -fslow_servers -fconn_lock_checks` (agent with the PostgreSQL store, XFTP servers that delay responses for the slow-server test, and an agent that fails server requests made inside a connection lock, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store". After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. ## Test selection diff --git a/simplexmq.cabal b/simplexmq.cabal index 3b70db982..323b14314 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -94,6 +94,11 @@ flag slow_servers manual: True default: False +flag conn_lock_checks + description: Fail agent server requests made inside a connection lock, for tests. + manual: True + default: False + flag server_postgres description: Build server with support of PostgreSQL. manual: True @@ -429,6 +434,8 @@ library cpp-options: -DswiftJSON if flag(slow_servers) cpp-options: -Dslow_servers + if flag(conn_lock_checks) + cpp-options: -Dconn_lock_checks if !flag(client_library) build-depends: case-insensitive ==1.2.* @@ -683,6 +690,8 @@ test-suite simplexmq-test cpp-options: -DdbServerPostgres if flag(slow_servers) cpp-options: -Dslow_servers + if flag(conn_lock_checks) + cpp-options: -Dconn_lock_checks if flag(client_postgres) cpp-options: -DdbPostgres else diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 373474e47..b7626385f 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1,4 +1,5 @@ {-# LANGUAGE BangPatterns #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} @@ -355,13 +356,15 @@ disconnectAgentClient c@AgentClient {agentEnv = Env {ntfSupervisor = ns, xftpAge -- only used in the tests disposeAgentClient :: AgentClient -> IO () -disposeAgentClient c@AgentClient {acThread, connLockViolations, agentEnv = Env {store}} = do +disposeAgentClient c@AgentClient {acThread, agentEnv = Env {store}} = do t_ <- atomically (swapTVar acThread Nothing) $>>= (liftIO . deRefWeak) disconnectAgentClient c mapM_ killThread t_ liftIO $ closeDBStore store - violations <- readTVarIO connLockViolations +#if defined(conn_lock_checks) + violations <- readTVarIO $ connLockViolations c unless (null violations) $ E.throwIO $ INTERNAL $ "server requests in connection locks " <> show violations +#endif resumeAgentClient :: AgentClient -> IO () resumeAgentClient c = atomically $ writeTVar (active c) True @@ -1030,8 +1033,10 @@ deleteConnectionsAsync_ :: AM () -> AgentClient -> Bool -> [ConnId] -> AM () deleteConnectionsAsync_ onSuccess c waitDelivery connIds = case connIds of [] -> onSuccess _ -> do - (_, rqs, connIds') <- prepareDeleteConnections_ getConns c waitDelivery connIds - withStore' c $ \db -> forM_ connIds' $ setConnDeleted db waitDelivery + rqs <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnectionsAsync" . runExceptT $ do + (_, rqs, connIds') <- prepareDeleteConnections_ getConns c waitDelivery connIds + withStore' c $ \db -> forM_ connIds' $ setConnDeleted db waitDelivery + pure rqs void . lift . forkIO $ withLock' (deleteLock c) "deleteConnectionsAsync" $ deleteConnQueues c NRMBackground waitDelivery True rqs >> void (runExceptT onSuccess) @@ -1724,8 +1729,11 @@ createReplyQueue c nm ConnData {userId, connId, enableNtfs} SndQueue {smpClientV (rq, qUri, tSess, sessId, serviceId_) <- newRcvQueue c nm userId connId srv (versionToRange smpClientVersion) SCMInvitation (isJust ntfServer_) subMode incSMPServerStat c userId (qServer rq) connCreated let qInfo = toVersionT qUri smpClientVersion - rq' <- withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode - lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + recorded <- withConnLock c connId "createReplyQueue" $ do + r <- tryAllErrors $ withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode + forM_ r $ \rq' -> lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + pure r + rq' <- either (\e -> tryAllErrors (deleteNewQueue c nm tSess rq) >> throwE e) pure recorded mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure qInfo @@ -1865,9 +1873,8 @@ serviceRequest_ c userId cReqUri@(CRContactUri _ addrKeys_) timeout_ doSend = do liftIO $ do expired <- registerDelay $ round (reqTimeout * 1000000) atomically $ takeTMVar var `orElse` (readTVar expired >>= \e -> if e then pure (Left $ AGENT $ A_SERVICE ASETimeout) else retry) - withConnLock c connId "serviceRequest_" $ do - atomically $ TM.delete connId (serviceRequests c) - deleteConnectionAsync' c True connId + atomically $ TM.delete connId (serviceRequests c) + deleteConnectionAsync' c True connId liftEither $ join r syncConnections' :: AgentClient -> [UserId] -> [ConnId] -> AM (DatabaseDiff UserId, DatabaseDiff ConnId) @@ -3183,7 +3190,7 @@ deleteConnections_ :: AM (Map ConnId (Either AgentErrorType ())) deleteConnections_ _ _ _ _ _ [] = pure M.empty deleteConnections_ getConnections ntf waitDelivery c nm connIds = do - (rs, rqs, _) <- prepareDeleteConnections_ getConnections c waitDelivery connIds + (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ prepareDeleteConnections_ getConnections c waitDelivery connIds rcvRs <- lift $ deleteConnQueues c nm waitDelivery ntf rqs let rs' = M.union rs rcvRs notifyResultError rs' @@ -3640,7 +3647,7 @@ cleanupManager c@AgentClient {subQ} = do expiredConns <- withStore' c $ \db -> do deleteExpiredServiceRequests db $ addUTCTime (negate serviceResponseTimeout) now getExpiredServiceConns db now - ExceptT . withConnLocks c (S.fromList expiredConns) "cleanupManager" . runExceptT $ deleteConnectionsAsync' c False expiredConns + deleteConnectionsAsync' c False expiredConns expireEndedRcvQueues = do maxErrs <- asks $ deleteErrorCount . config connIds <- withStore' c getEndedRcvQueueConnIds diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index e77a59838..b1fb1e2f8 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -231,7 +231,6 @@ import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) -import qualified Data.Text as T import Data.Text.Encoding import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) @@ -328,13 +327,17 @@ import System.Mem.Weak (Weak, deRefWeak) import System.Random (randomR) import UnliftIO (mapConcurrently, timeout) import UnliftIO.Async (async) -import UnliftIO.Concurrent (forkIO, mkWeakThreadId, myThreadId) +import UnliftIO.Concurrent (forkIO, mkWeakThreadId) import UnliftIO.Directory (doesFileExist, getTemporaryDirectory, removeFile) import qualified UnliftIO.Exception as E import UnliftIO.STM #if !defined(dbPostgres) import qualified Database.SQLite.Simple as SQL #endif +#if defined(conn_lock_checks) +import qualified Data.Text as T +import UnliftIO.Concurrent (myThreadId) +#endif type ClientVar msg = SessionVar (Either (AgentErrorType, Maybe UTCTime) (Client msg)) @@ -389,8 +392,10 @@ data AgentClient = AgentClient getMsgLocks :: TMap (SMPServer, SMP.RecipientId) (TMVar ()), -- locks to prevent concurrent operations with connection connLocks :: TMap ConnId Lock, +#if defined(conn_lock_checks) connLockHolders :: TMap ThreadId Text, connLockViolations :: TVar [Text], +#endif -- locks to prevent concurrent operations with connection request invitations invLocks :: TMap ByteString Lock, -- lock to prevent concurrency between periodic and async connection deletions @@ -561,8 +566,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState <- newTVarIO ASForeground getMsgLocks <- TM.emptyIO connLocks <- TM.emptyIO +#if defined(conn_lock_checks) connLockHolders <- TM.emptyIO connLockViolations <- newTVarIO [] +#endif invLocks <- TM.emptyIO deleteLock <- createLockIO smpSubWorkers <- TM.emptyIO @@ -609,8 +616,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState, getMsgLocks, connLocks, +#if defined(conn_lock_checks) connLockHolders, connLockViolations, +#endif invLocks, deleteLock, smpSubWorkers, @@ -1109,7 +1118,7 @@ withConnLock c connId name = ExceptT . withConnLock' c connId name . runExceptT withConnLock' :: AgentClient -> ConnId -> Text -> AM' a -> AM' a withConnLock' _ "" _ = id -withConnLock' AgentClient {connLocks, connLockHolders} connId name = withLockMap connLocks connId name . withLockHolder connLockHolders name +withConnLock' c@AgentClient {connLocks} connId name = withLockMap connLocks connId name . withLockHolder c name {-# INLINE withConnLock' #-} withInvLock :: AgentClient -> ByteString -> Text -> AM a -> AM a @@ -1121,7 +1130,7 @@ withInvLock' AgentClient {invLocks} = withLockMap invLocks {-# INLINE withInvLock' #-} withConnLocks :: AgentClient -> Set ConnId -> Text -> AM' a -> AM' a -withConnLocks AgentClient {connLocks, connLockHolders} connIds name = withLocksMap connLocks connIds name . withLockHolder connLockHolders name +withConnLocks c@AgentClient {connLocks} connIds name = withLocksMap connLocks connIds name . withLockHolder c name {-# INLINE withConnLocks #-} withLockMap :: (Ord k, MonadUnliftIO m) => TMap k Lock -> k -> Text -> m a -> m a @@ -1135,12 +1144,13 @@ withLocksMap = withGetLocks . getMapLock getMapLock :: Ord k => TMap k Lock -> k -> IO Lock getMapLock locks key = either id id <$> TM.lookupOrInsertIO key createLock locks -withLockHolder :: MonadUnliftIO m => TMap ThreadId Text -> Text -> m a -> m a -withLockHolder holders name a = do +#if defined(conn_lock_checks) +withLockHolder :: MonadUnliftIO m => AgentClient -> Text -> m a -> m a +withLockHolder AgentClient {connLockHolders} name a = do t <- myThreadId E.bracket - (atomically $ TM.lookupInsert t name holders) - (\prev_ -> atomically $ TM.alter (const prev_) t holders) + (atomically $ TM.lookupInsert t name connLockHolders) + (\prev_ -> atomically $ TM.alter (const prev_) t connLockHolders) (const a) checkNoConnLock :: AgentClient -> AM () @@ -1148,15 +1158,22 @@ checkNoConnLock AgentClient {connLockHolders, connLockViolations} = do t <- myThreadId name_ <- liftIO $ TM.lookupIO t connLockHolders forM_ name_ $ \name -> do - let err = "server request in connection lock " <> name - logError err - whenM (asks $ prohibitRequestsInConnLock . config) $ do - atomically $ modifyTVar' connLockViolations (name :) - throwE $ INTERNAL $ T.unpack err + atomically $ modifyTVar' connLockViolations (name :) + throwE $ INTERNAL $ "server request in connection lock " <> T.unpack name checkBatchOutsideConnLock :: AgentClient -> [q] -> AM' [(q, Either AgentErrorType r)] -> AM' [(q, Either AgentErrorType r)] checkBatchOutsideConnLock _ [] batch = batch checkBatchOutsideConnLock c qs batch = tryAllErrors' (checkNoConnLock c) >>= either (\e -> pure $ map (,Left e) qs) (const batch) +#else +withLockHolder :: AgentClient -> Text -> m a -> m a +withLockHolder _ _ = id + +checkNoConnLock :: AgentClient -> AM () +checkNoConnLock _ = pure () + +checkBatchOutsideConnLock :: AgentClient -> [q] -> AM' [(q, Either AgentErrorType r)] -> AM' [(q, Either AgentErrorType r)] +checkBatchOutsideConnLock _ _ = id +#endif withClient_ :: forall a v err msg. ProtocolServerClient v err msg => AgentClient -> NetworkRequestMode -> TransportSession msg -> (Client msg -> AM a) -> AM a withClient_ c nm tSess@(_, srv, _) action = do diff --git a/src/Simplex/Messaging/Agent/Env/SQLite.hs b/src/Simplex/Messaging/Agent/Env/SQLite.hs index afe1ded1a..d32be79b1 100644 --- a/src/Simplex/Messaging/Agent/Env/SQLite.hs +++ b/src/Simplex/Messaging/Agent/Env/SQLite.hs @@ -171,7 +171,6 @@ data AgentConfig = AgentConfig logStatsInterval :: Int64, cleanupStepInterval :: Int, maxWorkerRestartsPerMin :: Int, - prohibitRequestsInConnLock :: Bool, storedMsgDataTTL :: NominalDiffTime, rcvFilesTTL :: NominalDiffTime, sndFilesTTL :: NominalDiffTime, @@ -250,7 +249,6 @@ defaultAgentConfig = logStatsInterval = 10 * 1000000, -- 10 seconds cleanupStepInterval = 200000, -- 200ms maxWorkerRestartsPerMin = 5, - prohibitRequestsInConnLock = False, storedMsgDataTTL = 21 * nominalDay, rcvFilesTTL = 2 * nominalDay, sndFilesTTL = nominalDay, diff --git a/src/Simplex/Messaging/Transport/HTTP2/Client.hs b/src/Simplex/Messaging/Transport/HTTP2/Client.hs index 0e106e30b..5fa7dd971 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/Client.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/Client.hs @@ -44,7 +44,7 @@ import Simplex.Messaging.Protocol (NetworkError (..), toNetworkError) import Simplex.Messaging.Transport (ALPN, STransportPeer (..), SessionId, TLS (tlsALPN, tlsPeerCert, tlsUniq), TransportPeer (..), TransportPeerI (..), getServerVerifyKey) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTcpConnectTimeout, runTLSTransportClient) import Simplex.Messaging.Transport.HTTP2 -import Simplex.Messaging.Util (eitherToMaybe) +import Simplex.Messaging.Util (eitherToMaybe, whenM) import UnliftIO.STM import UnliftIO.Timeout @@ -65,7 +65,7 @@ data HClient = HClient host :: TransportHost, port :: ServiceName, config :: HTTP2ClientConfig, - reqQ :: TBQueue (Request, TMVar HTTP2Response) + reqQ :: TBQueue (Request, TVar Bool, TMVar HTTP2Response) } data HTTP2Response = HTTP2Response @@ -175,8 +175,8 @@ getVerifiedHTTP2ClientWith config host port disconnected setup = process :: HTTP2Client -> H.Client HTTP2Response process HTTP2Client {client_ = HClient {reqQ}} sendReq = forever $ do - (req, respVar) <- atomically $ readTBQueue reqQ - sendReq req $ \r -> do + (req, pending, respVar) <- atomically $ readTBQueue reqQ + whenM (readTVarIO pending) . void . sendReq req $ \r -> do respBody <- getHTTP2Body r (bodyHeadSize config) let resp = HTTP2Response {response = r, respBody} atomically $ putTMVar respVar resp @@ -189,9 +189,10 @@ closeHTTP2Client = mapM_ (void . async . cancel) . action sendRequest :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) sendRequest HTTP2Client {client_ = HClient {config, reqQ}} req reqTimeout_ = do resp <- newEmptyTMVarIO - atomically $ writeTBQueue reqQ (req, resp) + pending <- newTVarIO True let reqTimeout = http2RequestTimeout config reqTimeout_ - maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` atomically (takeTMVar resp)) + maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` (atomically (writeTBQueue reqQ (req, pending, resp)) >> atomically (takeTMVar resp))) + `E.finally` atomically (writeTVar pending False) -- | this function should not be used until HTTP2 is thread safe, use sendRequest sendRequestDirect :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 05769cbaa..bf657f7ef 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -360,6 +360,8 @@ functionalAPITests ps = do withSmpServer ps testConfClientVersionBelowAgentVersion it "should create X25519 sender keys" $ withSmpServer ps testX25519SndKeys + it "should delete the reply queue when the connection is deleted while the queue is created" $ + testJoinConnectionDeletedWhileReplyQueue ps describe "Duplex connection - delivery stress test" $ do describe "one way (50)" $ testMatrix2Stress ps $ runAgentClientStressTestOneWay 50 describe "one way (200)" $ testMatrix2Stress ps $ runAgentClientStressTestOneWay 200 @@ -679,9 +681,13 @@ functionalAPITests ps = do describe "getConnectionVerifyCodes" $ it "should return the same codes for both peers" $ withSmpServer ps testConnectionVerifyCodes - describe "Connection locks" $ + describe "Connection locks" $ do +#if defined(conn_lock_checks) it "should prohibit server requests in connection lock" $ withSmpServer ps testServerRequestInConnLock +#endif + it "should delete connections after connection lock is released" $ + testDeleteConnectionsAfterConnLock describe "Delivery receipts" $ do it "should send and receive delivery receipt" $ withSmpServer ps testDeliveryReceipts it "send delivery receipts concurrently with messages" $ testDeliveryReceiptsConcurrent ps @@ -4373,6 +4379,24 @@ testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testJoinConnectionDeletedWhileReplyQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testJoinConnectionDeletedWhileReplyQueue ps@(t, _) = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> + withAgent 2 agentCfg bServers testDB2 $ \b -> do + (_, cReq) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe + (aId, _) <- runRight $ A.prepareConnectionToJoin b 1 True cReq PQSupportOn + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAsync (runExceptT $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe) $ \joined -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + runRight_ $ deleteConnection b aId + atomically $ putTMVar opened () + timeout 5_000000 (wait joined) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + where + bServers = initAgentServersLongConnect {smp = userServers [testSMPServer2]} + testSwitchRatchetSyncBeforeNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchRatchetSyncBeforeNewQueue ps@(t, _) = withSmpServer ps $ @@ -4901,6 +4925,7 @@ testConnectionVerifyCodes = codes1'' <- getConnectionVerifyCodes a bId liftIO $ codes1'' `shouldBe` codes1 +#if defined(conn_lock_checks) testServerRequestInConnLock :: (HasCallStack, HasTestEnv) => IO () testServerRequestInConnLock = withAgentClients2 $ \a b -> do @@ -4913,6 +4938,27 @@ testServerRequestInConnLock = rs <- runRight $ withAgentEnv a . withConnLock a bId "batch" . ExceptT . liftIO $ runExceptT (subscribeConnections a [bId]) M.lookup bId rs `shouldBe` Just (Left $ A.INTERNAL "server request in connection lock batch") atomically (swapTVar (connLockViolations a) []) `shouldReturn` ["batch"] +#endif + +testDeleteConnectionsAfterConnLock :: HasTestEnv => IO () +testDeleteConnectionsAfterConnLock = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let newConnId = runRight $ fst <$> A.prepareConnectionToJoin a 1 True (CRInvitationUri connReqData testE2ERatchetParams12) PQSupportOn + connId1 <- newConnId + deleteAfterLock a connId1 $ deleteConnectionsAsync a False [connId1] + connId2 <- newConnId + deleteAfterLock a connId2 . void $ deleteConnections a [connId2] + where + deleteAfterLock c connId delete = do + locked <- newEmptyTMVarIO + unlocked <- newEmptyTMVarIO + let holdLock = atomically (putTMVar locked ()) >> atomically (takeTMVar unlocked) + withAsync (runExceptT . withAgentEnv c . withConnLock c connId "test" $ liftIO holdLock) $ \_ -> do + atomically $ takeTMVar locked + withAsync (runExceptT delete) $ \deleted -> do + timeout 500000 (wait deleted) `shouldReturn` Nothing + atomically $ putTMVar unlocked () + timeout 5_000000 (wait deleted) `shouldReturn` Just (Right ()) testDeliveryReceipts :: (HasCallStack, HasTestEnv) => IO () testDeliveryReceipts = diff --git a/tests/SMPAgentClient.hs b/tests/SMPAgentClient.hs index 0e4b2cacc..feb43387e 100644 --- a/tests/SMPAgentClient.hs +++ b/tests/SMPAgentClient.hs @@ -99,7 +99,6 @@ agentCfg = ntfCfg = defaultNTFClientConfig {qSize = 1, defaultTransport = (ntfTestPort, transport @TLS), networkConfig}, reconnectInterval = fastRetryInterval, persistErrorInterval = 1, - prohibitRequestsInConnLock = True, caCertificateFile = "tests/fixtures/ca.crt", privateKeyFile = "tests/fixtures/server.key", certificateFile = "tests/fixtures/server.crt" diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 7c3c5a60d..28599873e 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -30,9 +30,11 @@ import Data.Time.Clock (getCurrentTime) import qualified Data.X509 as X import Data.X509.Validation (Fingerprint (..), getFingerprint) import Network.HPACK.Token (tokenKey) +import Network.HTTP.Types (ok200) import qualified Network.HTTP2.Client as H2 +import Network.HTTP2.Server (responseNoBody) import qualified Network.TLS as T -import SMPClient (copyWebCredential, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn, withStallingServerOn') +import SMPClient (copyWebCredential, serverBracket, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn, withStallingServerOn') import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A @@ -48,15 +50,16 @@ import Simplex.Messaging.Protocol (BasicAuth, EntityId (..), RecipientId, Sender import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTransportClientConfig, runTLSTransportClient) -import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..)) +import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..), defaultHTTP2BufferSize) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC +import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential) import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts) import Simplex.Messaging.Version (mkVersionRange) import System.Directory (listDirectory, removeFile) import System.FilePath (()) import Test.Hspec hiding (fit, it) -import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_) +import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_, wait, withAsync) import UnliftIO.STM import UnliftIO.Timeout (timeout) import Util @@ -89,6 +92,8 @@ xftpServerTests = do it "should not change content for uploaded and committed files" testFileSkipCommitted it "should close connection when handshake times out" testHandshakeTimeout it "should close connection when cancelled during handshake" testCancelledHandshake + it "should not send request after it times out" testRequestNotSentAfterTimeout + it "should time out request while request queue is full" testRequestTimeoutInFullQueue it "should decode handshake of servers before v6.5.0 and refuse an invalid signature" testOldServerHandshake describe "XFTP SNI and CORS" $ beforeWith (const (pure ())) $ do it "should select web certificate when SNI is used" testSNICertSelection @@ -455,6 +460,46 @@ testCancelledHandshake _ = cancel a timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testRequestNotSentAfterTimeout :: HasTestEnv => AFStoreType -> Expectation +testRequestNotSentAfterTimeout _ = + withHeldHTTP2Requests $ \send received release -> + withAsync (send $ Just 5000000) $ \held -> do + atomically $ readTVar received >>= checkSTM . (1 ==) + Left HC.HCResponseTimeout <- send Nothing + atomically $ putTMVar release () + Right _ <- wait held + threadDelay 500000 + readTVarIO received `shouldReturn` 1 + +testRequestTimeoutInFullQueue :: HasTestEnv => AFStoreType -> Expectation +testRequestTimeoutInFullQueue _ = + withHeldHTTP2Requests $ \send received _ -> + withAsync (send $ Just 5000000) $ \_ -> do + atomically $ readTVar received >>= checkSTM . (1 ==) + Left HC.HCResponseTimeout <- send Nothing + Just (Left HC.HCResponseTimeout) <- timeout 5000000 $ send Nothing + pure () + +withHeldHTTP2Requests :: HasTestEnv => ((Maybe Int -> IO (Either HC.HTTP2ClientError HC.HTTP2Response)) -> TVar Int -> TMVar () -> IO a) -> IO a +withHeldHTTP2Requests action = do + received <- newTVarIO 0 + release <- newEmptyTMVarIO + creds <- loadServerCredential xftpCredentials + Fingerprint fp <- loadFileFingerprint "tests/fixtures/ca.crt" + let hold _ _ _ _ respond = do + atomically $ modifyTVar' received (+ 1) + atomically $ readTMVar release + respond $ responseNoBody ok200 [] + cfg = HC.defaultHTTP2ClientConfig {HC.qSize = 1, HC.connTimeout = 1000000, HC.suportedTLSParams = defaultSupportedParams} + connect = either (error . show) pure =<< HC.getVerifiedHTTP2Client Nothing (THDomainName "localhost") xftpTestPort (Just $ C.KeyHash fp) Nothing cfg (pure ()) + serverBracket + (\started -> runHTTP2Server started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> pure ()) hold) + (pure ()) + $ \_ -> bracket connect HC.closeHTTP2Client $ \c -> + action (HC.sendRequest c $ H2.requestNoBody "POST" "/" []) received release + where + XFTPServerConfig {xftpCredentials, transportConfig} = testXFTPServerConfig + testOldServerHandshake :: HasTestEnv => AFStoreType -> Expectation testOldServerHandshake _ = do (chain, pk) <- loadServerCredential xftpCredentials From 775e6ae0919665c57c144fdcf0f5dd3200a365b5 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:59:25 +0000 Subject: [PATCH 015/159] tests: name the test proxy that holds connections until resumed withPausedProxyOn --- tests/AgentTests/FunctionalAPITests.hs | 16 ++++++++-------- tests/SMPClient.hs | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index bf657f7ef..d81929a85 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -1723,14 +1723,14 @@ testServiceRequestExpiringReplyQueue ps@(t, _) = withAgent 2 agentCfg initAgentServers testDB2 $ \service -> do (_, CCLink connReq _) <- runRight $ A.createConnection service NRMInteractive 1 True True SCMContact (Just serviceUserLinkData) Nothing IKPQOn True SMSubscribe withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> withAgent 1 agentCfg clientServers testDB $ \client -> withAsync (runExceptT $ sendServiceRequestAsync client 1 connReq (Just 1) Nothing "service request") $ \req -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () timeout 5_000000 (wait req) `shouldReturn` Just (Left $ AGENT $ A_SERVICE ASETimeout) get client =##> \case ("", "", DEL_CONNS [_]) -> True; _ -> False withTransaction (store $ agentEnv client) getConnIds `shouldReturn` [] - atomically $ putTMVar opened () + atomically $ putTMVar resume () suspendAgent client 5_000000 nGet client ##> ("", "", SUSPENDED) storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) @@ -4354,11 +4354,11 @@ testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () void . runRight $ changeSwitch b aId - atomically $ putTMVar opened () + atomically $ putTMVar resume () timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' waitRcvQueueRecords b 1 @@ -4371,11 +4371,11 @@ testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () runRight_ $ deleteConnection b aId - atomically $ putTMVar opened () + atomically $ putTMVar resume () timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) @@ -4387,11 +4387,11 @@ testJoinConnectionDeletedWhileReplyQueue ps@(t, _) = (_, cReq) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe (aId, _) <- runRight $ A.prepareConnectionToJoin b 1 True cReq PQSupportOn withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> withAsync (runExceptT $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe) $ \joined -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () runRight_ $ deleteConnection b aId - atomically $ putTMVar opened () + atomically $ putTMVar resume () timeout 5_000000 (wait joined) `shouldReturn` Just (Left $ CONN NOT_FOUND "") storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) where diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index ec602dc06..80fc06fef 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -498,21 +498,21 @@ withStallingServerOn' port action = do (pure ()) (const $ action accepted closed) -withGatedServerOn :: HasCallStack => ServiceName -> ServiceName -> (TMVar () -> TMVar () -> IO a) -> IO a -withGatedServerOn port srvPort action = do +withPausedProxyOn :: HasCallStack => ServiceName -> ServiceName -> (TMVar () -> TMVar () -> IO a) -> IO a +withPausedProxyOn port srvPort action = do accepted <- newEmptyTMVarIO - opened <- newEmptyTMVarIO + resume <- newEmptyTMVarIO let forward from to = recv from 4096 >>= \s -> unless (B.null s) $ sendAll to s >> forward from to serverBracket (\started -> runLocalTCPServer started port $ \sock -> do void $ atomically $ tryPutTMVar accepted () - atomically $ readTMVar opened + atomically $ readTMVar resume addr : _ <- getAddrInfo (Just defaultHints {addrSocketType = Stream}) (Just "127.0.0.1") (Just srvPort) E.bracket (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close $ \srvSock -> do connect srvSock $ addrAddress addr race_ (forward sock srvSock) (forward srvSock sock)) (pure ()) - (const $ action accepted opened) + (const $ action accepted resume) withSmpServerOn :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> ServiceName -> IO a -> IO a withSmpServerOn ps port' = withSmpServerThreadOn ps port' . const From 3a6c879abf1f4b7c6cc6bf417947fc0d595f6421 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:01:32 +0000 Subject: [PATCH 016/159] agent: inline the connection lock checks of builds without conn_lock_checks --- src/Simplex/Messaging/Agent/Client.hs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index b1fb1e2f8..f3284fc3d 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -1167,12 +1167,15 @@ checkBatchOutsideConnLock c qs batch = tryAllErrors' (checkNoConnLock c) >>= eit #else withLockHolder :: AgentClient -> Text -> m a -> m a withLockHolder _ _ = id +{-# INLINE withLockHolder #-} checkNoConnLock :: AgentClient -> AM () checkNoConnLock _ = pure () +{-# INLINE checkNoConnLock #-} checkBatchOutsideConnLock :: AgentClient -> [q] -> AM' [(q, Either AgentErrorType r)] -> AM' [(q, Either AgentErrorType r)] checkBatchOutsideConnLock _ _ = id +{-# INLINE checkBatchOutsideConnLock #-} #endif withClient_ :: forall a v err msg. ProtocolServerClient v err msg => AgentClient -> NetworkRequestMode -> TransportSession msg -> (Client msg -> AM a) -> AM a From 666a11a3c6e25e0f3dfcd57db0ec778c7cb4ff12 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 02:48:55 -0500 Subject: [PATCH 017/159] xftp: prevent concurrent transfers from overwriting or removing files Consolidated from PR #2064, preserving the cancellation semantics of PR #2088. --- src/Simplex/FileTransfer/Client/Main.hs | 29 ++-- src/Simplex/FileTransfer/Server.hs | 93 ++++++++---- src/Simplex/FileTransfer/Server/Env.hs | 11 +- src/Simplex/FileTransfer/Server/Store.hs | 17 ++- .../FileTransfer/Server/Store/Postgres.hs | 21 ++- src/Simplex/FileTransfer/Server/StoreLog.hs | 5 +- src/Simplex/FileTransfer/Transport.hs | 1 + src/Simplex/FileTransfer/Util.hs | 17 +++ src/Simplex/Messaging/Agent/Client.hs | 36 +++-- tests/CoreTests/XFTPStoreTests.hs | 23 ++- tests/Test.hs | 4 +- tests/XFTPAgent.hs | 9 +- tests/XFTPCLI.hs | 143 +++++++++++++++++- tests/XFTPClient.hs | 30 +++- tests/XFTPServerTests.hs | 120 ++++++++++++++- 15 files changed, 468 insertions(+), 91 deletions(-) diff --git a/src/Simplex/FileTransfer/Client/Main.hs b/src/Simplex/FileTransfer/Client/Main.hs index 59dfc5e33..6421d5b80 100644 --- a/src/Simplex/FileTransfer/Client/Main.hs +++ b/src/Simplex/FileTransfer/Client/Main.hs @@ -12,11 +12,13 @@ module Simplex.FileTransfer.Client.Main ( SendOptions (..), + ReceiveOptions (..), CLIError (..), xftpClientCLI, xftpClientDeprecationNotice, cliSendFile, cliSendFileOpts, + cliReceiveFile, encodeWebURI, decodeWebURI, fileWebLink, @@ -61,7 +63,7 @@ import Simplex.FileTransfer.Description import Simplex.FileTransfer.Protocol import Simplex.FileTransfer.Transport (XFTPRcvChunkSpec (..)) import Simplex.FileTransfer.Types -import Simplex.FileTransfer.Util (uniqueCombine) +import Simplex.FileTransfer.Util (createNewFile, createUniqueDirectory, createUniqueFile, uniqueCombine) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.File (CryptoFile (..), FTCryptoError (..)) import qualified Simplex.Messaging.Crypto.File as CF @@ -287,7 +289,7 @@ cliSendFileOpts SendOptions {filePath, outputDir, numRecipients, xftpServers, re encryptFileForUpload g fileName = do fileSize <- fromInteger <$> getFileSize filePath when (fileSize > maxFileSize) $ throwE $ CLIError $ "Files bigger than " <> maxFileSizeStr <> " are not supported" - encPath <- getEncPath tempPath "xftp" + encPath <- liftIO $ getTempPath tempPath >>= (`createUniqueFile` "xftp.encrypted") key <- atomically $ C.randomSbKey g nonce <- atomically $ C.randomCbNonce g let fileHdr = smpEncode FileHeader {fileName, fileExtra = Nothing} @@ -397,8 +399,8 @@ cliSendFileOpts SendOptions {filePath, outputDir, numRecipients, xftpServers, re sndReplicas (SentFileChunkReplica {server} : _) replicaId replicaKey = [FileChunkReplica {server, replicaId, replicaKey}] writeFileDescriptions :: String -> [FileDescription 'FRecipient] -> FileDescription 'FSender -> IO ([FilePath], FilePath) writeFileDescriptions fileName fdRcvs fdSnd = do - outDir <- uniqueCombine (fromMaybe "." outputDir) (fileName <> ".xftp") - createDirectoryIfMissing True outDir + forM_ outputDir $ createDirectoryIfMissing True + outDir <- createUniqueDirectory (fromMaybe "." outputDir) (fileName <> ".xftp") fdRcvPaths <- forM (zip [1 ..] fdRcvs) $ \(i :: Int, fd) -> do let fdPath = outDir ("rcv" <> show i <> ".xftp") B.writeFile fdPath $ strEncode fd @@ -419,8 +421,7 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, | otherwise = getFileDescription' fileDescription receive :: Int -> ValidFileDescription 'FRecipient -> ExceptT CLIError IO () receive depth (ValidFileDescription FileDescription {size, digest, key, nonce, chunks, redirect}) = do - encPath <- getEncPath tempPath "xftp" - createDirectory encPath + encPath <- liftIO $ getTempPath tempPath >>= (`createUniqueDirectory` "xftp.encrypted") a <- liftIO $ newXFTPAgent defaultXFTPClientAgentConfig liftIO $ printNoNewLine "Downloading file..." downloadedChunks <- newTVarIO [] @@ -448,7 +449,7 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, | otherwise -> throwE $ CLIError "Redirect chain too long" Nothing -> do liftIO $ printNoNewLine "Decrypting file..." - CryptoFile path _ <- withExceptT cliCryptoError $ decryptChunks encSize chunkPaths key nonce $ fmap CF.plain . getFilePath + CryptoFile path _ <- withExceptT cliCryptoError $ decryptChunks encSize chunkPaths key nonce $ fmap CF.plain . createFilePath whenM (doesPathExist encPath) $ removeDirectoryRecursive encPath liftIO $ do printNoNewLine $ "File downloaded: " <> path @@ -469,12 +470,12 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, when verbose $ putStrLn "" pure (chunkNo, chunkPath) downloadFileChunk _ _ _ _ _ _ = throwE $ CLIError "chunk has no replicas" - getFilePath :: Text -> ExceptT String IO FilePath - getFilePath name = case filePath of + createFilePath :: Text -> ExceptT String IO FilePath + createFilePath name = case filePath of Just path -> - ifM (doesDirectoryExist path) (uniqueCombine path name') $ - ifM (doesFileExist path) (throwE "File already exists") (pure path) - _ -> (`uniqueCombine` name') . ( "Downloads") =<< getHomeDirectory + ifM (doesDirectoryExist path) (liftIO $ createUniqueFile path name') $ + ifM (doesFileExist path) (throwE "File already exists") (path <$ createNewFile path) + _ -> liftIO . (`createUniqueFile` name') . ( "Downloads") =<< getHomeDirectory where name' = T.unpack name @@ -534,8 +535,8 @@ getFileDescription' path = getFileDescription path >>= \case AVFD fd -> either (throwE . CLIError) pure $ checkParty fd -getEncPath :: MonadIO m => Maybe FilePath -> String -> m FilePath -getEncPath path name = (`uniqueCombine` (name <> ".encrypted")) =<< maybe (liftIO getCanonicalTemporaryDirectory) pure path +getTempPath :: Maybe FilePath -> IO FilePath +getTempPath = maybe getCanonicalTemporaryDirectory pure withReconnect :: Show e => XFTPClientAgent -> XFTPServer -> Int -> (XFTPClient -> ExceptT e IO a) -> ExceptT CLIError IO a withReconnect a srv n run = withRetry n $ do diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index 35cab97e1..034800b6e 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -25,15 +25,17 @@ import Control.Monad.Reader import Control.Monad.Trans.Except import qualified Data.Aeson as J import Data.Bifunctor (first) +import qualified Data.ByteString.Base64.URL as B64 import Data.ByteString.Builder (Builder, byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB +import Data.Either (fromRight) import Data.Int (Int64) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) @@ -84,12 +86,13 @@ import System.Environment (lookupEnv) import System.Exit (exitFailure) import System.FilePath (()) import System.IO (hPrint, hPutStrLn, universalNewlineMode) +import System.IO.Error (isDoesNotExistError) #ifdef slow_servers import System.Random (getStdRandom, randomR) #endif import UnliftIO import UnliftIO.Concurrent (threadDelay) -import UnliftIO.Directory (canonicalizePath, doesFileExist, removeFile, renameFile) +import UnliftIO.Directory (canonicalizePath, doesFileExist, listDirectory, removeFile, renameFile) import qualified UnliftIO.Exception as E type M s a = ReaderT (XFTPEnv s) IO a @@ -134,6 +137,7 @@ data EntitlementChecked = EntNotChecked | EntChecked (Maybe SessionEntitlement) xftpServer :: forall s. FileStoreClass s => XFTPServerConfig s -> TMVar Bool -> M s () xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpiration, fileExpiration, xftpServerVRange, information} started = do expireServerFiles Nothing fileExpiration + removeUnstoredFiles restoreServerStats raceAny_ ( runServer @@ -573,13 +577,28 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case pure $ FRRcvIds rIds pure $ either FRErr id r receiveServerFile :: FileRec -> M s FileResponse - receiveServerFile FileRec {senderId, fileInfo = FileInfo {size, digest}, filePath} = case bodyPart of + receiveServerFile FileRec {senderId, fileInfo = FileInfo {size, digest}} = case bodyPart of Nothing -> pure $ FRErr SIZE -- TODO validate body size from request before downloading, once it's populated - Just getBody -> skipCommitted $ mask $ \restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA) + Just getBody -> replaceUpload $ receiveUncommitted >>= maybe skipCommitted pure where + replaceUpload upload = do + uploads <- asks uploadingFiles + prevUpload <- newEmptyTMVarIO + let startUpload = do + a <- asyncWithUnmask $ \unmask -> uninterruptibleMask_ (atomically $ readTMVar prevUpload) >>= mapM_ uninterruptibleCancel >> unmask upload + a <$ atomically (TM.lookupInsert senderId a uploads >>= putTMVar prevUpload) + removeUpload a = uninterruptibleCancel a >> atomically (TM.alter (mfilter (/= a)) senderId uploads) + fromRight (FRErr TIMEOUT) <$> bracket startUpload removeUpload waitCatch -- having a filePath means the file is already uploaded and committed, must not change anything - skipCommitted = ifM (isJust <$> readTVarIO filePath) (liftIO $ drain $ fromIntegral size) + receiveUncommitted = do + st <- asks fileStore + liftIO (getFile st SFSender senderId) >>= \case + Right (FileRec {filePath}, _) -> + ifM (isJust <$> readTVarIO filePath) (pure Nothing) $ + Just <$> mask (\restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA)) + Left e -> pure $ Just $ FRErr e + skipCommitted = liftIO $ drain $ fromIntegral size where -- can't send FROk without reading the request body or a client will block on sending it -- can't send any old error as the client would fail or restart indefinitely @@ -652,28 +671,32 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case -- pure FROk deleteServerFile_ :: FileStoreClass s => FileRec -> M s (Either XFTPErrorType ()) -deleteServerFile_ fr@FileRec {senderId} = do - withFileLog (`logDeleteFile` senderId) - deleteOrBlockServerFile_ fr filesDeleted (`deleteFile` senderId) +deleteServerFile_ fr@FileRec {senderId} = mask_ $ do + r <- deleteOrBlockServerFile_ fr filesDeleted (`deleteFile` senderId) + forM_ r $ \_ -> withFileLog (`logDeleteFile` senderId) + pure r -- this also deletes the file from storage, but doesn't include it in delete statistics blockServerFile :: FileStoreClass s => FileRec -> BlockingInfo -> M s (Either XFTPErrorType ()) -blockServerFile fr@FileRec {senderId} info = do - withFileLog $ \sl -> logBlockFile sl senderId info - deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info True +blockServerFile fr@FileRec {senderId} info = mask_ $ do + r <- deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info True + forM_ r $ \_ -> withFileLog $ \sl -> logBlockFile sl senderId info + pure r -deleteOrBlockServerFile_ :: FileStoreClass s => FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType ())) -> M s (Either XFTPErrorType ()) -deleteOrBlockServerFile_ FileRec {filePath, fileInfo} stat storeAction = mask_ $ runExceptT $ do +deleteOrBlockServerFile_ :: FileStoreClass s => FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType (Maybe FilePath))) -> M s (Either XFTPErrorType ()) +deleteOrBlockServerFile_ FileRec {filePath, fileInfo} stat storeAction = runExceptT $ do path <- readTVarIO filePath stats <- asks serverStats - ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (forM_ path $ \p -> whenM (doesFileExist p) (removeFile p >> deletedStats stats)) + ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (mapM_ (removeServerFile stats) path) st <- asks fileStore - ExceptT $ liftIO $ storeAction st - forM_ path $ \_ -> do + path' <- ExceptT $ liftIO $ storeAction st + lift $ incFileStat stat + forM_ path' $ \p -> do us <- asks usedStorage atomically $ modifyTVar' us $ subtract (fromIntegral $ size fileInfo) - lift $ incFileStat stat + when (path /= Just p) $ lift $ removeServerFile stats p `catch` \(e :: SomeException) -> logError $ "failed to remove file " <> tshow p <> ": " <> tshow e where + removeServerFile stats p = (removeFile p >> deletedStats stats) `catch` \e -> unless (isDoesNotExistError e) $ throwIO e deletedStats stats = do liftIO $ atomicModifyIORef'_ (filesCount stats) (subtract 1) liftIO $ atomicModifyIORef'_ (filesSize stats) (subtract $ fromIntegral $ size fileInfo) @@ -699,18 +722,36 @@ expireServerFiles itemDelay expCfg = do expired <- liftIO $ expiredFiles st now old 10000 forM_ expired $ \(_, filePath_, _) -> do mapM_ threadDelay itemDelay - forM_ filePath_ $ \fp -> - whenM (doesFileExist fp) $ - removeFile fp `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e + mapM_ removeExpiredFile filePath_ let sIds = map (\(sId, _, _) -> sId) expired unless (null sIds) $ do - withFileLog $ \sl -> mapM_ (logDeleteFile sl) sIds - liftIO $ deleteFiles st sIds - forM_ expired $ \(_, filePath_, fileSize) -> do - forM_ filePath_ $ \_ -> - atomically $ modifyTVar' us $ subtract (fromIntegral fileSize) - incFileStat filesExpired + deleted <- M.fromList <$> liftIO (deleteFiles st sIds) + forM_ expired $ \(sId, filePath_, fileSize) -> + forM_ (M.lookup sId deleted) $ \path -> do + forM_ path $ \fp -> do + when (filePath_ /= Just fp) $ removeExpiredFile fp + atomically $ modifyTVar' us $ subtract (fromIntegral fileSize) + incFileStat filesExpired + withFileLog $ \sl -> mapM_ (logDeleteFile sl) (M.keys deleted) expireLoop st us now old + removeExpiredFile fp = + removeFile fp `catch` \e -> unless (isDoesNotExistError e) $ logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e + +removeUnstoredFiles :: FileStoreClass s => M s () +removeUnstoredFiles = do + dir <- asks $ filesPath . config + st <- asks fileStore + whenM ((> 0) <$> liftIO (getFileCount st)) $ do + removed <- filterM (unstored st) =<< listDirectory dir + forM_ removed $ \f -> removeFile (dir f) `catchAny` \_ -> pure () + unless (null removed) $ logNote $ "Removed " <> tshow (length removed) <> " files without records" + where + unstored st name = case B64.decode $ B.pack name of + Right sId -> + liftIO (getFile st SFSender $ EntityId sId) >>= \case + Right (FileRec {filePath}, _) -> isNothing <$> readTVarIO filePath + Left e -> pure $ e == AUTH + Left _ -> pure False randomId :: Int -> M s ByteString randomId n = atomically . C.randomBytes n =<< asks random diff --git a/src/Simplex/FileTransfer/Server/Env.hs b/src/Simplex/FileTransfer/Server/Env.hs index 516e83bbc..679e3f8cc 100644 --- a/src/Simplex/FileTransfer/Server/Env.hs +++ b/src/Simplex/FileTransfer/Server/Env.hs @@ -32,6 +32,7 @@ module Simplex.FileTransfer.Server.Env exportFromDatabase, ) where +import Control.Concurrent.Async (Async) import Control.Logger.Simple import Control.Monad import Crypto.Random @@ -45,7 +46,7 @@ import Data.Word (Word16, Word32) import Data.X509.Validation (Fingerprint (..)) import Network.Socket import qualified Network.TLS as T -import Simplex.FileTransfer.Protocol (FileCmd, FileInfo (..), XFTPFileId) +import Simplex.FileTransfer.Protocol (FileCmd, FileInfo (..), FileResponse, XFTPFileId) import Simplex.FileTransfer.Server.Stats import Data.Either (fromRight) import Data.Ini (Ini, lookupValue) @@ -66,9 +67,11 @@ import Simplex.FileTransfer.Server.StoreLog import Simplex.FileTransfer.Transport (VersionRangeXFTP) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.BBS (BBSPublicKey) -import Simplex.Messaging.Protocol (BasicAuth, RcvPublicAuthKey) +import Simplex.Messaging.Protocol (BasicAuth, RcvPublicAuthKey, SenderId) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.Information (ServerPublicInfo) +import Simplex.Messaging.TMap (TMap) +import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport (EntitlementConfig (..)) import Simplex.Messaging.Transport.Server (ReloadableCredential, ServerCredentials (..), TransportServerConfig (..), acceptCredential, loadFingerprint, loadServerCredential, newReloadableCredential) import Simplex.Messaging.Util (tshow) @@ -131,6 +134,7 @@ data XFTPEnv s = XFTPEnv { config :: XFTPServerConfig s, store :: FileStore s, usedStorage :: TVar Int64, + uploadingFiles :: TMap SenderId (Async FileResponse), storeLog :: Maybe (StoreLog 'WriteMode), random :: TVar ChaChaDRG, serverIdentity :: C.KeyHash, @@ -203,6 +207,7 @@ newXFTPServerEnv config@XFTPServerConfig {serverStoreCfg, fileSizeQuota, fileExp #endif used <- getUsedStorage (fromFileStore store) usedStorage <- newTVarIO used + uploadingFiles <- TM.emptyIO forM_ fileSizeQuota $ \quota -> do logNote $ "Total / available storage: " <> tshow quota <> " / " <> tshow (quota - used) when (quota < used) $ logWarn "WARNING: storage quota is less than used storage, no files can be uploaded!" @@ -210,7 +215,7 @@ newXFTPServerEnv config@XFTPServerConfig {serverStoreCfg, fileSizeQuota, fileExp httpServerCreds <- forM httpCredentials $ \creds -> newReloadableCredential acceptCredential creds =<< loadServerCredential creds Fingerprint fp <- loadFingerprint xftpCredentials serverStats <- newFileServerStats =<< getCurrentTime - pure XFTPEnv {config, store, usedStorage, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats} + pure XFTPEnv {config, store, usedStorage, uploadingFiles, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats} data XFTPRequest = XFTPReqNew FileInfo (NonEmpty RcvPublicAuthKey) (Maybe BasicAuth) (Maybe Word32) diff --git a/src/Simplex/FileTransfer/Server/Store.hs b/src/Simplex/FileTransfer/Server/Store.hs index 371a5eea4..2a8bb9287 100644 --- a/src/Simplex/FileTransfer/Server/Store.hs +++ b/src/Simplex/FileTransfer/Server/Store.hs @@ -24,6 +24,7 @@ import Data.Kind (Type) import Control.Concurrent.STM import Control.Monad import qualified Data.Attoparsec.ByteString.Char8 as A +import Data.Either (rights) import Data.Int (Int64) import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, isJust) @@ -78,10 +79,10 @@ class FileStoreClass s where addFile :: s -> SenderId -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> IO (Either XFTPErrorType ()) setFilePath :: s -> SenderId -> FilePath -> IO (Either XFTPErrorType ()) addRecipient :: s -> SenderId -> FileRecipient -> IO (Either XFTPErrorType ()) - deleteFile :: s -> SenderId -> IO (Either XFTPErrorType ()) - deleteFiles :: s -> [SenderId] -> IO () - deleteFiles s = mapM_ (void . deleteFile s) - blockFile :: s -> SenderId -> BlockingInfo -> Bool -> IO (Either XFTPErrorType ()) + deleteFile :: s -> SenderId -> IO (Either XFTPErrorType (Maybe FilePath)) + deleteFiles :: s -> [SenderId] -> IO [(SenderId, Maybe FilePath)] + deleteFiles s = fmap rights . mapM (\sId -> fmap (sId,) <$> deleteFile s sId) + blockFile :: s -> SenderId -> BlockingInfo -> Bool -> IO (Either XFTPErrorType (Maybe FilePath)) deleteRecipient :: s -> RecipientId -> FileRec -> IO () getFile :: s -> SFileParty p -> XFTPFileId -> IO (Either XFTPErrorType (FileRec, C.APublicAuthKey)) ackFile :: s -> RecipientId -> IO (Either XFTPErrorType ()) @@ -138,15 +139,15 @@ instance FileStoreClass STMFileStore where deleteFile STMFileStore {files, recipients} senderId = atomically $ do TM.lookupDelete senderId files >>= \case - Just FileRec {recipientIds} -> do + Just FileRec {recipientIds, filePath} -> do readTVar recipientIds >>= mapM_ (`TM.delete` recipients) - pure $ Right () + Right <$> readTVar filePath _ -> pure $ Left AUTH blockFile st senderId info _deleted = atomically $ - withFile st senderId $ \FileRec {fileStatus} -> do + withFile st senderId $ \FileRec {fileStatus, filePath} -> do writeTVar fileStatus $! EntityBlocked info - pure $ Right () + Right <$> swapTVar filePath Nothing deleteRecipient STMFileStore {recipients} rId FileRec {recipientIds} = atomically $ do TM.delete rId recipients diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index af040e902..7c48b13f4 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -112,19 +112,26 @@ instance FileStoreClass PostgresFileStore where withLog "addRecipient" st $ \s -> logAddRecipients s senderId (pure $ FileRecipient rId rKey) deleteFile st sId = E.uninterruptibleMask_ $ runExceptT $ do - assertUpdated $ withDB' "deleteFile" st $ \db -> - DB.execute db "DELETE FROM files WHERE sender_id = ?" (Only sId) + path <- withDB "deleteFile" st $ \db -> + firstRow fromOnly AUTH $ DB.query db "DELETE FROM files WHERE sender_id = ? RETURNING file_path" (Only sId) withLog "deleteFile" st $ \s -> logDeleteFile s sId + pure path deleteFiles st sIds = E.uninterruptibleMask_ $ do - withTransaction (dbStore st) $ \db -> - DB.execute db "DELETE FROM files WHERE sender_id IN ?" (Only (In sIds)) - withLog "deleteFiles" st $ \s -> mapM_ (logDeleteFile s) sIds + deleted <- withTransaction (dbStore st) $ \db -> + DB.query db "DELETE FROM files WHERE sender_id IN ? RETURNING sender_id, file_path" (Only (In sIds)) + withLog "deleteFiles" st $ \s -> mapM_ (logDeleteFile s . fst) deleted + pure deleted blockFile st sId info _deleted = E.uninterruptibleMask_ $ runExceptT $ do - assertUpdated $ withDB' "blockFile" st $ \db -> - DB.execute db "UPDATE files SET status = ? WHERE sender_id = ?" (EntityBlocked info, sId) + path <- withDB "blockFile" st $ \db -> + firstRow fromOnly AUTH $ + DB.query + db + "UPDATE files f SET status = ?, file_path = NULL FROM (SELECT file_path FROM files WHERE sender_id = ? FOR NO KEY UPDATE) old WHERE f.sender_id = ? RETURNING old.file_path" + (EntityBlocked info, sId, sId) withLog "blockFile" st $ \s -> logBlockFile s sId info + pure path deleteRecipient st rId _fr = void $ runExceptT $ withDB' "deleteRecipient" st $ \db -> diff --git a/src/Simplex/FileTransfer/Server/StoreLog.hs b/src/Simplex/FileTransfer/Server/StoreLog.hs index 5a6d99c7a..29ab0d8b0 100644 --- a/src/Simplex/FileTransfer/Server/StoreLog.hs +++ b/src/Simplex/FileTransfer/Server/StoreLog.hs @@ -23,6 +23,7 @@ where import Control.Applicative (optional, (<|>)) import Control.Concurrent.STM +import Control.Monad (void) import Control.Monad.Except import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString.Base64.URL as B64 @@ -125,8 +126,8 @@ readFileStore f st = mapM_ (addFileLogRecord . LB.toStrict) . LB.lines =<< LB.re | takeFileName path == serverFileName qId -> setFilePath st qId path | otherwise -> pure $ Left AUTH AddRecipients sId rcps -> runExceptT $ addRecipients sId rcps - DeleteFile sId -> deleteFile st sId - BlockFile sId info -> blockFile st sId info True + DeleteFile sId -> void <$> deleteFile st sId + BlockFile sId info -> void <$> blockFile st sId info True AckFile rId -> ackFile st rId addRecipients sId rcps = mapM_ (ExceptT . addRecipient st sId) rcps diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index f32b4ad70..8619dcc16 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -205,6 +205,7 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO + ] err e = "receiveFile error: " <> tshow e diff --git a/src/Simplex/FileTransfer/Util.hs b/src/Simplex/FileTransfer/Util.hs index 661a2fd5c..38025fea5 100644 --- a/src/Simplex/FileTransfer/Util.hs +++ b/src/Simplex/FileTransfer/Util.hs @@ -1,14 +1,19 @@ module Simplex.FileTransfer.Util ( uniqueCombine, createUniqueDirectory, + createUniqueFile, + createNewFile, safeFileNameStr, removePath, ) where +import Data.Bits ((.|.)) +import Foreign.C.Error (throwErrnoPathIfMinus1, throwErrnoPathIfMinus1_) import Simplex.Messaging.Util (ifM, whenM) import System.FilePath (makeValid, splitExtensions, takeFileName, ()) import System.IO.Error (isAlreadyExistsError) +import System.Posix.Internals (c_close, c_safe_open, o_CREAT, o_EXCL, o_WRONLY, withFilePath) import UnliftIO import UnliftIO.Directory @@ -32,6 +37,18 @@ createUniqueDirectory filePath dirName = tryCreate (0 :: Int) let d = candidatePath filePath dirName n in (d <$ createDirectory d) `catch` \e -> if isAlreadyExistsError e then tryCreate (n + 1) else throwIO e +createUniqueFile :: MonadUnliftIO m => FilePath -> String -> m FilePath +createUniqueFile filePath fileName = tryCreate (0 :: Int) + where + tryCreate n = + let f = candidatePath filePath fileName n + in (f <$ createNewFile f) `catch` \e -> if isAlreadyExistsError e then tryCreate (n + 1) else throwIO e + +createNewFile :: MonadIO m => FilePath -> m () +createNewFile f = liftIO . mask_ $ do + fd <- withFilePath f $ \p -> throwErrnoPathIfMinus1 "createNewFile" f $ c_safe_open p (o_WRONLY .|. o_CREAT .|. o_EXCL) 0o666 + throwErrnoPathIfMinus1_ "createNewFile" f $ c_close fd + candidatePath :: FilePath -> String -> Int -> FilePath candidatePath filePath fileName n = filePath (name <> suffix <> ext) where diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index f3284fc3d..ccbdeeb2a 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -1433,21 +1433,23 @@ runXFTPServerTest c@AgentClient {presetDomains} nm userId (ProtoServerWithAuth s let tSess = (userId, srv, Nothing) ts <- readTVarIO $ proxySessTs c X.getXFTPClient tSess cfg {xftpNetworkConfig} presetDomains ts (\_ -> pure Nothing) (\_ -> pure ()) >>= \case - Right xftp -> withTestChunk filePath $ do - (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - digest <- liftIO $ C.sha256Hash <$> B.readFile filePath - let file = FileInfo {sndKey, size = chSize, digest} - chunkSpec = X.XFTPChunkSpec {filePath, chunkOffset = 0, chunkSize = chSize} - r <- runExceptT $ do - (sId, [rId], _) <- liftError (testErr TSCreateFile) $ X.createXFTPChunk xftp spKey file [rcvKey] auth Nothing - liftError (testErr TSUploadFile) $ X.uploadXFTPChunk xftp spKey sId chunkSpec - liftError (testErr TSDownloadFile) $ X.downloadXFTPChunk g xftp rpKey rId $ XFTPRcvChunkSpec rcvPath chSize digest - rcvDigest <- liftIO $ C.sha256Hash <$> B.readFile rcvPath - unless (digest == rcvDigest) $ throwE $ ProtocolTestFailure TSCompareFile $ XFTP (B.unpack $ strEncode srv) DIGEST - liftError (testErr TSDeleteFile) $ X.deleteXFTPChunk xftp spKey sId - ok <- netTimeoutInt (tcpTimeout xftpNetworkConfig) nm `timeout` X.closeXFTPClient xftp - pure $ r >> maybe (Left (ProtocolTestFailure TSDisconnect $ BROKER addr TIMEOUT)) (const $ Right $ serverInfo (X.thParams xftp)) ok + Right xftp -> withTestChunk filePath test `E.finally` removeTestFile rcvPath + where + test = do + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + digest <- liftIO $ C.sha256Hash <$> B.readFile filePath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = X.XFTPChunkSpec {filePath, chunkOffset = 0, chunkSize = chSize} + r <- runExceptT $ do + (sId, [rId], _) <- liftError (testErr TSCreateFile) $ X.createXFTPChunk xftp spKey file [rcvKey] auth Nothing + liftError (testErr TSUploadFile) $ X.uploadXFTPChunk xftp spKey sId chunkSpec + liftError (testErr TSDownloadFile) $ X.downloadXFTPChunk g xftp rpKey rId $ XFTPRcvChunkSpec rcvPath chSize digest + rcvDigest <- liftIO $ C.sha256Hash <$> B.readFile rcvPath + unless (digest == rcvDigest) $ throwE $ ProtocolTestFailure TSCompareFile $ XFTP (B.unpack $ strEncode srv) DIGEST + liftError (testErr TSDeleteFile) $ X.deleteXFTPChunk xftp spKey sId + ok <- netTimeoutInt (tcpTimeout xftpNetworkConfig) nm `timeout` X.closeXFTPClient xftp + pure $ r >> maybe (Left (ProtocolTestFailure TSDisconnect $ BROKER addr TIMEOUT)) (const $ Right $ serverInfo (X.thParams xftp)) ok Left e -> pure $ Left (testErr TSConnect e) where addr = B.unpack $ strEncode srv @@ -1464,7 +1466,9 @@ runXFTPServerTest c@AgentClient {presetDomains} nm userId (ProtoServerWithAuth s withTestChunk fp = E.bracket_ (createTestChunk fp) - (whenM (doesFileExist fp) $ removeFile fp `catchAll_` pure ()) + (removeTestFile fp) + removeTestFile :: FilePath -> IO () + removeTestFile fp = whenM (doesFileExist fp) $ removeFile fp `catchAll_` pure () -- this creates a new DRG on purpose to avoid blocking the one used in the agent createTestChunk :: FilePath -> IO () createTestChunk fp = B.writeFile fp =<< atomically . C.randomBytes chSize =<< C.newRandom diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index cb121b8d8..8b5ce46cf 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -9,6 +9,7 @@ import Data.Word (Word32) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore, importFileStore, exportFileStore) +import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..)) import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, readWriteFileStore, serverFileName, writeFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (..)) import qualified Simplex.Messaging.Crypto as C @@ -39,6 +40,7 @@ xftpStoreTests = do it "should ack file reception" testAckFile it "should return expired files with limit" testExpiredFiles it "should expire files by stored expiration" testExpiredFilesStoredExpiration + it "should log each file deletion once" testDeleteFilesLog it "should compute committed used storage and file count" testStorageAndCount xftpMigrationTests :: Spec @@ -152,7 +154,7 @@ testDeleteFileCascade = withPgStore $ \st -> do let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () - deleteFile st testSenderId `shouldReturn` Right () + deleteFile st testSenderId `shouldReturn` Right Nothing -- File and recipient should both be gone getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) getFile st SFRecipient testRecipientId >>= (`shouldBe` Left AUTH) . fmap (const ()) @@ -164,7 +166,7 @@ testBlockFile = withPgStore $ \st -> do let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () let blockInfo = BlockingInfo {reason = BRContent, notice = Nothing} - blockFile st testSenderId blockInfo False `shouldReturn` Right () + blockFile st testSenderId blockInfo False `shouldReturn` Right Nothing result <- getFile st SFSender testSenderId case result of Right (FileRec {fileStatus}, _) -> readTVarIO fileStatus `shouldReturn` EntityBlocked blockInfo @@ -219,6 +221,21 @@ testExpiredFilesStoredExpiration = withPgStore $ \st -> do expired <- expiredFiles st (RoundedSystemTime 500000) 0 100 map (\(sId, _, _) -> sId) expired `shouldBe` [EntityId "expired_file____"] +testDeleteFilesLog :: HasTestEnv => Expectation +testDeleteFilesLog = do + let storeLogPath = testPath "xftp-delete-files.log" + otherId = EntityId "other_file______" + st <- newFileStore testXFTPPostgresCfg {dbStoreLogPath = Just storeLogPath} :: IO PostgresFileStore + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let fileInfo = testFileInfo sndKey + addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () + addFile st otherId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () + void $ deleteFile st testSenderId + void $ deleteFiles st [testSenderId, otherId] + closeFileStore st + map (take 4) . lines <$> readFile storeLogPath `shouldReturn` ["FNEW", "FNEW", "FDEL", "FDEL"] + testStorageAndCount :: HasTestEnv => Expectation testStorageAndCount = withPgStore $ \st -> do testStorageAndCountForStore st @@ -247,6 +264,8 @@ testStorageAndCountForStore st = do getUsedStorage st `shouldReturn` 128000 setFilePath st fileB "/tmp/file_b" `shouldReturn` Right () getUsedStorage st `shouldReturn` 192000 + void $ blockFile st fileA BlockingInfo {reason = BRSpam, notice = Nothing} True + getUsedStorage st `shouldReturn` 64000 -- Migration round-trip test diff --git a/tests/Test.hs b/tests/Test.hs index 021ff4dd2..8e89cf090 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -36,7 +36,7 @@ import Test.Hspec hiding (fit, it) import Test.Hspec.Core.Runner (defaultConfig, evalSpec, evaluateResult, readConfig, runSpecForest) import Util import XFTPAgent -import XFTPCLI (xftpCLIFileTests) +import XFTPCLI (xftpCLIConcurrentTests, xftpCLIFileTests) import Simplex.FileTransfer.Server.Env (AFStoreType (..)) import Simplex.FileTransfer.Server.Store (SFSType (..)) import XFTPServerTests (xftpServerTests) @@ -168,7 +168,7 @@ main = do describe "SMP proxy capabilities, memory message store" $ before (pure $ ASType SQSMemory SMSMemory) smpProxyCapabilityTests describe "XFTP CLI (memory)" $ - before (pure $ AFSType SFSMemory) xftpCLIFileTests + before (pure $ AFSType SFSMemory) $ xftpCLIFileTests >> xftpCLIConcurrentTests #if defined(dbServerPostgres) describe "XFTP CLI (PostgreSQL)" $ before (pure $ AFSType SFSPostgres) xftpCLIFileTests diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index 8dc8c0bb7..4b001a4ab 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -148,8 +148,13 @@ testXFTPServerTest :: (HasCallStack, HasTestEnv) => Maybe BasicAuth -> XFTPServe testXFTPServerTest newFileBasicAuth srv = withXFTPServerCfg testXFTPServerConfig {newFileBasicAuth, xftpPort = xftpTestPort2, information = Just testServerInformation} $ \_ -> -- initially passed server is not running - withAgent 1 agentCfg initAgentServers testDB $ \a -> - testProtocolServer a NRMInteractive 1 srv + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let workPath = testPath "xftp-work-files" + createDirectory workPath + runRight_ $ xftpStartWorkers a (Just workPath) + r <- testProtocolServer a NRMInteractive 1 srv + listDirectory workPath `shouldReturn` [] + pure r rfProgress :: forall m. (HasCallStack, MonadIO m, MonadFail m) => AgentClient -> Int64 -> m () rfProgress c expected = loop 0 diff --git a/tests/XFTPCLI.hs b/tests/XFTPCLI.hs index 6ec442aab..f5be021ab 100644 --- a/tests/XFTPCLI.hs +++ b/tests/XFTPCLI.hs @@ -1,20 +1,31 @@ -module XFTPCLI (xftpCLIFileTests, xftpCLI) where +{-# LANGUAGE DisambiguateRecordFields #-} +module XFTPCLI (xftpCLIFileTests, xftpCLIConcurrentTests, xftpCLI) where + +import Control.Concurrent (yield) +import Control.Concurrent.Async (forConcurrently_) +import Control.Concurrent.STM (atomically, modifyTVar', newTVarIO, readTVarIO) import Control.Exception (try) +import Control.Monad (forM_, when) +import Control.Monad.Trans.Except (runExceptT) import qualified Data.ByteString as LB +import Data.Int (Int64) import Data.List (isInfixOf, isPrefixOf, isSuffixOf) +import Data.String (fromString) import Simplex.FileTransfer.Client.Main ( prepareChunkSizes, xftpClientCLI, xftpClientDeprecationNotice, ) +import qualified Simplex.FileTransfer.Client.Main as CLI import Simplex.FileTransfer.Description (kb, mb) import Simplex.FileTransfer.Util (safeFileNameStr, uniqueCombine) -import System.Directory (getFileSize, listDirectory) +import Simplex.Messaging.Util (unlessM) +import System.Directory (copyFile, createDirectory, createDirectoryIfMissing, getFileSize, listDirectory) import System.Environment (withArgs) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (takeFileName, ()) -import System.IO.Silently (capture, capture_) +import System.IO.Silently (capture, capture_, silence) import Test.Hspec hiding (fit, it) import Util import Simplex.FileTransfer.Server.Env (AFStoreType) @@ -43,6 +54,14 @@ xftpCLIFileTests = do sanitized n = let n' = safeFileNameStr n in n' /= "" && n' /= "." && n' /= ".." bareName n = let n' = safeFileNameStr n in n' == takeFileName n' +xftpCLIConcurrentTests :: SpecWith AFStoreType +xftpCLIConcurrentTests = + describe "concurrent transfers" $ do + it "should send files with one temporary folder" $ withXFTPServer testXFTPCLISendSharedTemp + it "should save file descriptions in one folder" $ withXFTPServer testXFTPCLISendSharedOutput + it "should receive files with one temporary folder" $ withXFTPServer testXFTPCLIReceiveSharedTemp + it "should save received files in one folder" $ withXFTPServer testXFTPCLIReceiveSharedOutput + xftpCLI :: [String] -> IO [String] xftpCLI params = lines <$> capture_ (withArgs params xftpClientCLI) @@ -161,6 +180,62 @@ testXFTPCLIDelete_ = do xftpCLI ["recv", fdRcv2, recipientFiles, "--tmp=" <> testDir] `shouldThrow` anyException +testXFTPCLISendSharedTemp :: HasTestEnv => IO () +testXFTPCLISendSharedTemp = do + let tmpPath = testPath "xftp-tmp" + sndPath r i = senderFiles show r show i + rcvPath r i = recipientFiles show r show i + createDirectory tmpPath + forM_ [1 .. rounds] $ \r -> do + forM_ [1 .. transfers] $ \i -> do + createDirectoryIfMissing True $ sndPath r i + createDirectoryIfMissing True $ rcvPath r i + createTestFile $ sndPath r i + silence $ atOnce $ \i -> sendFile (\_ _ -> pure ()) (sndPath r i "testfile") (sndPath r i) tmpPath + silence $ forConcurrently_ [1 .. transfers] $ \i -> receiveFile (sndPath r i "testfile.xftp" "rcv1.xftp") (rcvPath r i) (rcvPath r i) + forM_ [1 .. transfers] $ \i -> do + file <- LB.readFile $ sndPath r i "testfile" + LB.readFile (rcvPath r i "testfile") `shouldReturn` file + listDirectory tmpPath `shouldReturn` [] + +testXFTPCLISendSharedOutput :: HasTestEnv => IO () +testXFTPCLISendSharedOutput = do + filePath <- createTestFile senderFiles + let tmpPath i = testPath "xftp-tmp" show i + forM_ [1 .. transfers] $ createDirectoryIfMissing True . tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + let outPath = senderFiles show r + uploaded <- newBarrier transfers + forConcurrently_ [1 .. transfers] $ \i -> + sendFile (\sent total -> when (sent == total) uploaded) filePath outPath (tmpPath i) + length <$> listDirectory outPath `shouldReturn` transfers + +testXFTPCLIReceiveSharedTemp :: HasTestEnv => IO () +testXFTPCLIReceiveSharedTemp = do + (file, fdRcv) <- sendTestFile + let tmpPath = testPath "xftp-tmp" + outPath r i = recipientFiles show r show i + createDirectory tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + forM_ [1 .. transfers] $ \i -> copyFile fdRcv (fdCopy i) >> createDirectoryIfMissing True (outPath r i) + atOnce $ \i -> receiveFile (fdCopy i) (outPath r i) tmpPath + forM_ [1 .. transfers] $ \i -> LB.readFile (outPath r i "testfile") `shouldReturn` file + listDirectory tmpPath `shouldReturn` [] + +testXFTPCLIReceiveSharedOutput :: HasTestEnv => IO () +testXFTPCLIReceiveSharedOutput = do + (file, fdRcv) <- sendTestFile + let tmpPath i = testPath "xftp-tmp" show i + forM_ [1 .. transfers] $ createDirectoryIfMissing True . tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + let outPath = recipientFiles show r + createDirectory outPath + forM_ [1 .. transfers] $ \i -> copyFile fdRcv (fdCopy i) + atOnce $ \i -> receiveFile (fdCopy i) outPath (tmpPath i) + files <- listDirectory outPath + length files `shouldBe` transfers + forM_ files $ \f -> LB.readFile (outPath f) `shouldReturn` file + testReceivedFileNameCombine :: HasTestEnv => IO () testReceivedFileNameCombine = uniqueCombine recipientFiles "../../escaped.txt" `shouldReturn` (recipientFiles "escaped.txt") @@ -193,3 +268,65 @@ downloadProgress fileName s = "Downloading file..." `isPrefixOf` s && "Decrypting file..." `isInfixOf` s && ("File downloaded: " <> recipientFiles fileName <> "\r") `isSuffixOf` s + +transfers :: Int +transfers = 8 + +rounds :: Int +rounds = 20 + +createTestFile :: FilePath -> IO FilePath +createTestFile dir = do + let filePath = dir "testfile" + xftpCLI ["rand", filePath, "1kb"] `shouldReturn` ["File created: " <> filePath] + pure filePath + +sendTestFile :: HasTestEnv => IO (LB.ByteString, FilePath) +sendTestFile = do + filePath <- createTestFile senderFiles + silence $ sendFile (\_ _ -> pure ()) filePath senderFiles testDir + file <- LB.readFile filePath + pure (file, filePath <> ".xftp" "rcv1.xftp") + +sendFile :: HasTestEnv => (Int64 -> Int64 -> IO ()) -> FilePath -> FilePath -> FilePath -> IO () +sendFile notifyProgress src outPath tmpPath = + runExceptT (CLI.cliSendFileOpts opts False notifyProgress) `shouldReturn` Right () + where + opts = + CLI.SendOptions + { filePath = src, + outputDir = Just outPath, + numRecipients = 1, + xftpServers = [fromString testXFTPServerStr], + retryCount = 3, + tempPath = Just tmpPath, + verbose = False + } + +receiveFile :: FilePath -> FilePath -> FilePath -> IO () +receiveFile fd outPath tmpPath = + runExceptT (CLI.cliReceiveFile opts) `shouldReturn` Right () + where + opts = + CLI.ReceiveOptions + { fileDescription = fd, + filePath = Just outPath, + retryCount = 3, + tempPath = Just tmpPath, + verbose = False, + yes = True + } + +fdCopy :: HasTestEnv => Int -> FilePath +fdCopy i = testPath $ "rcv" <> show i <> ".xftp" + +atOnce :: (Int -> IO ()) -> IO () +atOnce action = do + started <- newBarrier transfers + forConcurrently_ [1 .. transfers] $ \i -> started >> action i + +newBarrier :: Int -> IO (IO ()) +newBarrier n = do + arrived <- newTVarIO 0 + let waitAll = unlessM ((== n) <$> readTVarIO arrived) $ yield >> waitAll + pure $ atomically (modifyTVar' arrived (+ 1)) >> waitAll diff --git a/tests/XFTPClient.hs b/tests/XFTPClient.hs index 233b0af4f..f8631e626 100644 --- a/tests/XFTPClient.hs +++ b/tests/XFTPClient.hs @@ -9,21 +9,27 @@ module XFTPClient where import Control.Concurrent (ThreadId, threadDelay) +import Control.Exception (bracket) +import Control.Monad (forM_) import Data.String (fromString) import Data.Time.Clock (getCurrentTime) import Network.Socket (ServiceName) import SMPClient (serverBracket) import Simplex.FileTransfer.Client import Simplex.FileTransfer.Description +import Simplex.FileTransfer.Protocol (FileInfo) import Simplex.FileTransfer.Server (runXFTPServerBlocking) import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig (..), AFStoreType (..), defaultFileExpiration, defaultInactiveClientExpiration) -import Simplex.FileTransfer.Server.Store (FileStoreClass, SFSType (..), STMFileStore) +import Simplex.FileTransfer.Server.Store (FileStoreClass, RoundedFileTime, SFSType (..), STMFileStore) +import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, logAddFile) import Simplex.FileTransfer.Transport (alpnSupportedXFTPhandshakes, supportedFileServerVRange) import Simplex.FileTransfer.Types (SndFileId) import qualified Simplex.Messaging.Agent as A import Simplex.Messaging.Agent.Protocol (UserId) import Simplex.Messaging.Crypto.File (CryptoFile) -import Simplex.Messaging.Protocol (XFTPServer) +import Simplex.Messaging.Protocol (SenderId, XFTPServer) +import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) +import Simplex.Messaging.Server.StoreLog (openWriteStoreLog) import Simplex.Messaging.Transport (defaultSupportedParams) import Simplex.Messaging.Transport.HTTP2 (defaultHTTP2BufferSize, httpALPN) import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) @@ -37,6 +43,8 @@ import Control.Monad (void) import qualified Database.PostgreSQL.Simple as PSQL import Database.PostgreSQL.Simple (ConnectInfo (..), defaultConnectInfo) import Database.PostgreSQL.Simple.Types (Query (..)) +import Simplex.FileTransfer.Server.Store (FileStoreClass (addFile, closeFileStore, newFileStore)) +import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore) import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..), defaultXFTPDBOpts) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) @@ -68,6 +76,24 @@ cfgFS2 (AFSType fs) = case fs of SFSPostgres -> error "no postgres support" #endif +cfgFSTestFiles :: HasTestEnv => AFStoreType -> AXFTPServerConfig +cfgFSTestFiles fsType@(AFSType fs) = case fs of + SFSMemory -> AXFTPSrvCfg testXFTPServerConfig {serverStoreCfg = XSCMemory (Just testXFTPLogFile), storeLogFile = Just testXFTPLogFile} + SFSPostgres -> cfgFS fsType + +addTestFiles :: HasTestEnv => AFStoreType -> [SenderId] -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> IO () +addTestFiles (AFSType fs) sIds file createdAt expiresAt = case fs of + SFSMemory -> + bracket (openWriteStoreLog False testXFTPLogFile) closeStoreLog $ \sl -> + forM_ sIds $ \sId -> logAddFile sl sId file createdAt expiresAt EntityActive +#if defined(dbServerPostgres) + SFSPostgres -> + bracket (newFileStore testXFTPPostgresCfg) closeFileStore $ \(st :: PostgresFileStore) -> + forM_ sIds $ \sId -> addFile st sId file createdAt expiresAt EntityActive >>= either (error . show) pure +#else + SFSPostgres -> error "no postgres support" +#endif + withXFTPServerConfigOn :: HasCallStack => AXFTPServerConfig -> (HasCallStack => ThreadId -> IO a) -> IO a withXFTPServerConfigOn (AXFTPSrvCfg cfg) = withXFTPServerCfg cfg diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 28599873e..cd6c543a8 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -17,7 +17,6 @@ import Control.Monad.Except import Control.Monad.IO.Unlift import qualified Crypto.PubKey.RSA as RSA import Data.Bifunctor (first) -import qualified Data.ByteString.Base64.URL as B64 import Data.ByteString.Builder (byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B @@ -39,8 +38,9 @@ import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A import Simplex.FileTransfer.Description (kb) -import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpEncodeAuthTransmission) +import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), FileResponse (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpDecodeTClient, xftpEncodeAuthTransmission) import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..)) +import Simplex.FileTransfer.Server.StoreLog (serverFileName) import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), receiveFile, pattern VersionXFTP) import Simplex.Messaging.Client (NetworkConfig (..), NetworkTimeout (..), ProtocolClientError (..), defaultNetworkConfig) import qualified Simplex.Messaging.Crypto as C @@ -48,6 +48,7 @@ import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding (smpDecode, smpEncode) import Simplex.Messaging.Protocol (BasicAuth, EntityId (..), RecipientId, SenderId, pattern NoEntity) import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) +import Simplex.Messaging.SystemTime (RoundedSystemTime (..), getSystemSeconds) import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTransportClientConfig, runTLSTransportClient) import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..), defaultHTTP2BufferSize) @@ -55,8 +56,9 @@ import qualified Simplex.Messaging.Transport.HTTP2.Client as HC import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential) import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts) +import Simplex.Messaging.Util (bshow, unlessM, whenM) import Simplex.Messaging.Version (mkVersionRange) -import System.Directory (listDirectory, removeFile) +import System.Directory (doesFileExist, listDirectory, removeFile) import System.FilePath (()) import Test.Hspec hiding (fit, it) import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_, wait, withAsync) @@ -81,7 +83,11 @@ xftpServerTests = do it "should time out receiving file chunk" $ \_ -> testReceiveFileTimeout it "should not allow uploading chunks after specified storage quota" testFileStorageQuota it "should release storage of interrupted uploads" testInterruptedUploadStorage + it "should complete a new upload of a chunk without waiting for the paused upload it replaces" testConcurrentChunkUpload + it "should cancel a stalled upload and release its storage when its chunk is uploaded again" testCancelStalledChunkUpload + it "should remove a chunk uploaded while its file expires" testUploadDuringExpiration it "should store file records to log and restore them after server restart" testFileLog + it "should remove files without stored chunks when the server starts" testRemoveUnstoredFiles describe "XFTP basic auth" $ do -- allow FNEW | server auth | clnt auth | success it "prohibited without basic auth" $ testFileBasicAuth True (Just "pwd") Nothing False @@ -124,7 +130,7 @@ createXFTPChunk :: XFTPClient -> C.APrivateAuthKey -> FileInfo -> NonEmpty C.APu createXFTPChunk c spKey file rcps auth = (\(sId, rIds, _) -> (sId, rIds)) <$> A.createXFTPChunk c spKey file rcps auth Nothing readChunk :: HasTestEnv => XFTPFileId -> IO ByteString -readChunk sId = B.readFile (xftpServerFiles B.unpack (B64.encode $ unEntityId sId)) +readChunk sId = B.readFile (xftpServerFiles serverFileName sId) testFileChunkDelivery :: HasTestEnv => AFStoreType -> Expectation testFileChunkDelivery = xftpTest $ \c -> runRight_ $ runTestFileChunkDelivery c c @@ -329,6 +335,112 @@ testInterruptedUploadStorage fsType = withXFTPServerConfigOn (updateXFTPCfg (cfg listDirectory xftpServerFiles `shouldReturn` [] testXFTPClient $ \c -> runRight_ $ forM_ (take 10 sIds) $ \sId -> uploadXFTPChunk c spKey sId chunkSpec +testConcurrentChunkUpload :: HasTestEnv => AFStoreType -> Expectation +testConcurrentChunkUpload = xftpTest2 $ \c@XFTPClient {http2Client, thParams} c' -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey file [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + resume <- newEmptyTMVarIO + let (part1, part2) = B.splitAt (chSize `div` 2) bytes + req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send $ byteString t + send $ byteString part1 + flush + atomically $ takeTMVar resume + send $ byteString part2 + flush + serverFile = xftpServerFiles serverFileName sId + waitServerFile = unlessM (doesFileExist serverFile) $ threadDelay 10000 >> waitServerFile + upload1 <- async $ HC.sendRequest http2Client req Nothing + timeout 5000000 waitServerFile `shouldReturn` Just () + timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) + atomically $ putTMVar resume () + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} <- either (error . show) pure =<< wait upload1 + case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr TIMEOUT)) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + listDirectory xftpServerFiles `shouldReturn` [serverFileName sId] + runRight_ $ downloadXFTPChunk g c' rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest + B.readFile (testPath "received_chunk1") `shouldReturn` bytes + +testCancelStalledChunkUpload :: HasTestEnv => AFStoreType -> Expectation +testCancelStalledChunkUpload fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileSizeQuota = Just chSize}) $ + \_ -> testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> testXFTPClient $ \c' -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, _) <- runRight $ createXFTPChunk c spKey file [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send $ byteString t + send $ byteString $ B.replicate 1024 'x' + flush + threadDelay maxBound + serverFile = xftpServerFiles serverFileName sId + waitServerFile = unlessM (doesFileExist serverFile) $ threadDelay 10000 >> waitServerFile + upload1 <- async $ HC.sendRequest http2Client req Nothing + timeout 5000000 waitServerFile `shouldReturn` Just () + timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} <- either (error . show) pure =<< wait upload1 + case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr TIMEOUT)) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + +testUploadDuringExpiration :: HasTestEnv => AFStoreType -> Expectation +testUploadDuringExpiration fsType = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + RoundedSystemTime now <- getSystemSeconds + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + fileId i = EntityId $ "expiring_file_" <> bshow (i :: Int) + sId = fileId 0 + uploadedIds = map fileId [1 .. 20] + uploadedFiles = map ((xftpServerFiles ) . serverFileName) uploadedIds + waitExpiration = whenM (and <$> mapM doesFileExist uploadedFiles) $ threadDelay 10000 >> waitExpiration + waitRemoved = unlessM (null <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitRemoved + addTestFiles fsType (sId : uploadedIds) file (RoundedSystemTime now) (Just $ RoundedSystemTime $ now + 5) + withXFTPServerConfigOn (updateXFTPCfg (cfgFSTestFiles fsType) $ \c -> c {fileExpiration}) $ \_ -> do + testXFTPClient $ \c -> do + runRight_ $ forM_ uploadedIds $ \fId -> uploadXFTPChunk c spKey fId chunkSpec + timeout 10000000 waitExpiration `shouldReturn` Just () + runRight_ $ uploadXFTPChunk c spKey sId chunkSpec + timeout 10000000 waitRemoved `shouldReturn` Just () + where + fileExpiration = ExpirationConfig {ttl = 3600, checkInterval = 1} + +testRemoveUnstoredFiles :: HasTestEnv => AFStoreType -> Expectation +testRemoveUnstoredFiles fsType = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, rId, partialId) <- withXFTPServerConfigOn (cfgFSTestFiles fsType) $ \_ -> testXFTPClient $ \c -> runRight $ do + (sId, [rId]) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId chunkSpec + (partialId, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + pure (sId, rId, partialId) + forM_ ([partialId, EntityId "orphan_file_0000"] :: [SenderId]) $ \fId -> B.writeFile (xftpServerFiles serverFileName fId) "partial" + withXFTPServerConfigOn (cfgFSTestFiles fsType) $ \_ -> do + listDirectory xftpServerFiles `shouldReturn` [serverFileName sId] + testXFTPClient $ \c -> runRight_ $ downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest + B.readFile (testPath "received_chunk1") `shouldReturn` bytes + testFileLog :: HasTestEnv => AFStoreType -> Expectation testFileLog _ = do g <- C.newRandom From 7a3b198a535f993256ac6bdd605b781b353d16f7 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 02:49:55 -0500 Subject: [PATCH 018/159] agent, xftp: check message size before storing and require file chunks Consolidated from PR #2073. --- src/Simplex/FileTransfer/Description.hs | 1 + src/Simplex/Messaging/Agent.hs | 22 +++---- .../Messaging/Agent/Store/AgentStore.hs | 9 ++- tests/AgentTests/FunctionalAPITests.hs | 65 +++++++++++-------- tests/FileDescriptionTests.hs | 1 + 5 files changed, 59 insertions(+), 39 deletions(-) diff --git a/src/Simplex/FileTransfer/Description.hs b/src/Simplex/FileTransfer/Description.hs index bfc1896fd..9e90783da 100644 --- a/src/Simplex/FileTransfer/Description.hs +++ b/src/Simplex/FileTransfer/Description.hs @@ -234,6 +234,7 @@ instance StrEncoding AFileDescription where validateFileDescription :: FileDescription p -> Either String (ValidFileDescription p) validateFileDescription fd@FileDescription {size, chunks, redirect} + | null chunks = Left "no chunks" | chunkNos /= [1 .. length chunks] = Left "chunk numbers are not sequential" | chunksSize chunks /= unFileSize size = Left "chunks total size is different than file size" | any incorrectChunkSize chunks = Left "incorrect chunk size" diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index b7626385f..fbbbe1fae 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2589,25 +2589,21 @@ storeSentMsg db cfg aMessageIds = \case Nothing -> do (mbId_, r) <- case csqs_ of Left e -> pure (Nothing, Left e) - Right (cData, sq :| _) -> do - mbId <- createSndMsgBody db aMessage - (Just mbId,) <$> storeSentMsg_ cData sq mbId aMessage + Right (cData, sq :| _) -> storeSentMsg_ cData sq Nothing aMessage let aMessageIds' = maybe id (`IM.insert` (mbId_, aMessage)) i_ aMessageIds pure (aMessageIds', r) VRRef i -> case csqs_ of Left e -> pure $ (aMessageIds, Left e) Right (cData, sq :| _) -> case IM.lookup i aMessageIds of - Just (Just mbId, aMessage) -> (aMessageIds,) <$> storeSentMsg_ cData sq mbId aMessage - Just (Nothing, aMessage) -> do - mbId <- createSndMsgBody db aMessage - let aMessageIds' = IM.insert i (Just mbId, aMessage) aMessageIds - (aMessageIds',) <$> storeSentMsg_ cData sq mbId aMessage + Just (mbId_, aMessage) -> do + (mbId_', r) <- storeSentMsg_ cData sq mbId_ aMessage + pure (IM.insert i (mbId_', aMessage) aMessageIds, r) Nothing -> pure (aMessageIds, Left $ INTERNAL "enqueueMessageB: storeSentMsg missing saved message body id") where - storeSentMsg_ cData@ConnData {connId} sq sndMsgBodyId aMessage = fmap (first storeError) $ runExceptT $ do + storeSentMsg_ cData@ConnData {connId, pqSupport} sq mbId_ aMessage = fmap (either (\e -> (mbId_, Left $ storeError e)) (bimap Just Right)) $ runExceptT $ do let AgentConfig {e2eEncryptVRange} = cfg internalTs <- liftIO getCurrentTime - (internalId, internalSndId, prevMsgHash) <- ExceptT $ updateSndIds db connId + (internalId, internalSndId, prevMsgHash) <- ExceptT $ getNextSndIds db connId -- We need to do pre-flight encoding that is not stored in database -- to calculate its hash and remember it on connection (createSndMsg -> updateSndMsgHash) -- to enable next enqueue. @@ -2615,14 +2611,16 @@ storeSentMsg db cfg aMessageIds = \case let agentMsgStr = encodeAgentMsgStr aMessage internalSndId prevMsgHash internalHash = C.sha256Hash agentMsgStr currentE2EVersion = maxVersion e2eEncryptVRange + withExceptT (SEAgentError . cryptoError) $ CR.rcCheckCanPad (e2eEncAgentMsgLength pqSupport) agentMsgStr + sndMsgBodyId <- liftIO $ maybe (createSndMsgBody db aMessage) pure mbId_ + liftIO $ updateLastIdsSnd_ db connId internalId internalSndId (mek, paddedLen, pqEnc) <- agentRatchetEncryptHeader db cData e2eEncAgentMsgLength pqEnc_ currentE2EVersion - withExceptT (SEAgentError . cryptoError) $ CR.rcCheckCanPad paddedLen agentMsgStr let msgType = aMessageType aMessage -- msgBody is empty, because snd_messages record is linked to snd_message_bodies msgData = SndMsgData {internalId, internalSndId, internalTs, msgType, msgFlags, msgBody = "", pqEncryption = pqEnc, internalHash, prevMsgHash, sndMsgPrepData_ = Just SndMsgPrepData {encryptKey = mek, paddedLen, sndMsgBodyId}} liftIO $ createSndMsg db connId msgData liftIO $ createSndMsgDelivery db sq internalId - pure (req, internalId, pqEnc) + pure (sndMsgBodyId, (req, internalId, pqEnc)) encodeAgentMsgStr :: AMessage -> InternalSndId -> PrevSndMsgHash -> ByteString encodeAgentMsgStr aMessage internalSndId prevMsgHash = do diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index f77434bf6..138f8f8e7 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -130,6 +130,8 @@ module Simplex.Messaging.Agent.Store.AgentStore updateRcvMsgHash, createSndMsgBody, updateSndIds, + getNextSndIds, + updateLastIdsSnd_, createSndMsg, updateSndMsgHash, createSndMsgDelivery, @@ -1041,10 +1043,15 @@ createSndMsgBody db aMessage = updateSndIds :: DB.Connection -> ConnId -> IO (Either StoreError (InternalId, InternalSndId, PrevSndMsgHash)) updateSndIds db connId = runExceptT $ do + ids@(internalId, internalSndId, _) <- ExceptT $ getNextSndIds db connId + liftIO $ updateLastIdsSnd_ db connId internalId internalSndId + pure ids + +getNextSndIds :: DB.Connection -> ConnId -> IO (Either StoreError (InternalId, InternalSndId, PrevSndMsgHash)) +getNextSndIds db connId = runExceptT $ do (lastInternalId, lastInternalSndId, prevSndHash) <- ExceptT $ retrieveLastIdsAndHashSnd_ db connId let internalId = InternalId $ unId lastInternalId + 1 internalSndId = InternalSndId $ unSndId lastInternalSndId + 1 - liftIO $ updateLastIdsSnd_ db connId internalId internalSndId pure (internalId, internalSndId, prevSndHash) createSndMsg :: DB.Connection -> ConnId -> SndMsgData -> IO () diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index d81929a85..8c14f642c 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -354,6 +354,8 @@ functionalAPITests ps = do withSmpServer ps testAgentClient3 it "should establish connection without PQ encryption and enable it" $ withSmpServer ps testEnablePQEncryption + it "should not store messages that are too large" $ + withSmpServer ps testLargeMessageNotStored it "should refuse joining already used invitation and keep connection" $ withSmpServer ps testJoinUsedInvitation it "should refuse confirmation with client version below the version of its agent" $ @@ -1053,37 +1055,30 @@ testEnablePQEncryption = sml <- largeMsg g PQSupportOn -- fail because of message size Left (A.CMD LARGE _) <- tryError $ A.sendMessage ca bId PQEncOn SMP.noMsgFlags lrg - (7, PQEncOff) <- A.sendMessage ca bId PQEncOn SMP.noMsgFlags sml - get ca =##> \case ("", connId, SENT 7) -> connId == bId; _ -> False - get cb =##> \case ("", connId, MsgErr' 6 MsgSkipped {} PQEncOff msg') -> connId == aId && msg' == sml; _ -> False - ackMessage cb aId 6 Nothing - -- -- fail in reply to sync IDss + (a, 6, sml) \#>! b Left (A.CMD LARGE _) <- tryError $ A.sendMessage cb aId PQEncOn SMP.noMsgFlags lrg - (8, PQEncOff) <- A.sendMessage cb aId PQEncOn SMP.noMsgFlags sml - get cb =##> \case ("", connId, SENT 8) -> connId == aId; _ -> False - get ca =##> \case ("", connId, MsgErr' 8 MsgSkipped {} PQEncOff msg') -> connId == bId && msg' == sml; _ -> False - ackMessage ca bId 8 Nothing - (a, 9, sml) \#>! b + (b, 7, sml) \#>! a + (a, 8, sml) \#>! b -- PQ encryption now enabled - (b, 10, sml) !#>! a - (a, 11, sml) !#>! b - (b, 12, sml) !#>! a + (b, 9, sml) !#>! a + (a, 10, sml) !#>! b + (b, 11, sml) !#>! a -- disabling PQ encryption - (a, 13, sml) !#>\ b - (b, 14, sml) !#>\ a - (a, 15, sml) \#>\ b - (b, 16, sml) \#>\ a + (a, 12, sml) !#>\ b + (b, 13, sml) !#>\ a + (a, 14, sml) \#>\ b + (b, 15, sml) \#>\ a -- enabling PQ encryption again - (a, 17, sml) \#>! b - (b, 18, sml) \#>! a - (a, 19, sml) \#>! b - (b, 20, sml) !#>! a - (a, 21, sml) !#>! b + (a, 16, sml) \#>! b + (b, 17, sml) \#>! a + (a, 18, sml) \#>! b + (b, 19, sml) !#>! a + (a, 20, sml) !#>! b -- disabling PQ encryption again - (b, 22, sml) !#>\ a - (a, 23, sml) !#>\ b - (b, 24, sml) \#>\ a - (a, 25, sml) \#>\ b + (b, 21, sml) !#>\ a + (a, 22, sml) !#>\ b + (b, 23, sml) \#>\ a + (a, 24, sml) \#>\ b -- PQ encryption is now disabled, but support remained enabled, so we still cannot send larger messages Left (A.CMD LARGE _) <- tryError $ A.sendMessage ca bId PQEncOff SMP.noMsgFlags (sml <> "123456") Left (A.CMD LARGE _) <- tryError $ A.sendMessage cb aId PQEncOff SMP.noMsgFlags (sml <> "123456") @@ -1102,6 +1097,18 @@ sndRcv pqEnc pqEnc' ((c1, id1), mId, msg) (c2, id2) = do get c2 =##> \case ("", connId, Msg' mId' pq msg') -> connId == id1 && mId' == mId && msg' == msg && pq == pqEnc; _ -> False ackMessage c2 id1 mId Nothing +testLargeMessageNotStored :: (HasCallStack, HasTestEnv) => IO () +testLargeMessageNotStored = + withAgentClients2 $ \a b -> runRight_ $ do + (aId, bId) <- makeConnection a b + Left (A.CMD LARGE _) <- tryError $ A.sendMessage a bId PQEncOn SMP.noMsgFlags $ B.replicate (e2eEncAgentMsgLength PQSupportOn) 'a' + liftIO $ unreferencedMsgBodies a `shouldReturn` [] + 2 <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT 2) + get b =##> \case ("", c, Msg' 2 PQEncOn "hello") -> c == aId; _ -> False + ackMessage b aId 2 Nothing + liftIO $ skippedMsgKeys b `shouldReturn` [] + testAgentClient3 :: (HasCallStack, HasTestEnv) => IO () testAgentClient3 = withAgentClients3 $ \a b c -> runRight_ $ do @@ -3250,6 +3257,12 @@ sndMessages c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_i connInvitations :: AgentClient -> IO [(InvitationId, Maybe ConnId)] connInvitations c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT invitation_id, contact_conn_id FROM conn_invitations") +unreferencedMsgBodies :: AgentClient -> IO [(Int64, Int64)] +unreferencedMsgBodies c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT snd_message_body_id, length(agent_msg) FROM snd_message_bodies b WHERE NOT EXISTS (SELECT 1 FROM snd_messages m WHERE m.snd_message_body_id = b.snd_message_body_id)") + +skippedMsgKeys :: AgentClient -> IO [(ConnId, Int64)] +skippedMsgKeys c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, msg_n FROM skipped_messages") + getMsg :: AgentClient -> ConnId -> ExceptT AgentErrorType IO a -> ExceptT AgentErrorType IO a getMsg c cId action = do liftIO $ noMessages c "nothing should be delivered before GET" diff --git a/tests/FileDescriptionTests.hs b/tests/FileDescriptionTests.hs index 21c62c476..a1f55afd7 100644 --- a/tests/FileDescriptionTests.hs +++ b/tests/FileDescriptionTests.hs @@ -203,6 +203,7 @@ testFileDescriptionLimits = do split64GB = prepareChunkSizes (gb 64 - mb 1) length largestSplit `shouldBe` 1282 length split64GB `shouldBe` 16386 + validateFileDescription (descriptionOf [] 1) `shouldBe` Left "no chunks" validateFileDescription (descriptionOf largestSplit 16) `shouldSatisfy` isRight validateFileDescription (descriptionOf largestSplit 17) `shouldBe` Left "too many chunk replicas" validateFileDescription (descriptionOf split64GB 4) `shouldSatisfy` isRight From e6913170e6699ce6c4d8d6f8015fa611000a3af0 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 02:51:25 -0500 Subject: [PATCH 019/159] xftp: limit connections to file servers outside the user list Consolidated from PR #2044. --- src/Simplex/FileTransfer/Agent.hs | 21 +++-- src/Simplex/Messaging/Agent/Client.hs | 48 +++++++++- src/Simplex/Messaging/Agent/Env/SQLite.hs | 2 + tests/XFTPAgent.hs | 110 ++++++++++++++++++++-- 4 files changed, 160 insertions(+), 21 deletions(-) diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index 980100e36..ce79699bf 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -196,11 +196,15 @@ runXFTPRcvWorker c srv Worker {doWork} = do cfg <- asks config forever $ do lift $ waitForWork doWork - liftIO $ assertAgentForeground c - runXFTPOperation cfg + withXFTPDownloadPermit c $ downloadChunks cfg where - runXFTPOperation :: AgentConfig -> AM () - runXFTPOperation AgentConfig {rcvFilesTTL, reconnectInterval = ri, xftpConsecutiveRetries} = + downloadChunks :: AgentConfig -> XFTPDownloadPermit -> AM () + downloadChunks cfg permit = do + liftIO $ assertAgentForeground c + runXFTPOperation cfg permit + unlessM (atomically $ isEmptyTMVar doWork) $ downloadChunks cfg permit + runXFTPOperation :: AgentConfig -> XFTPDownloadPermit -> AM () + runXFTPOperation AgentConfig {rcvFilesTTL, reconnectInterval = ri, xftpConsecutiveRetries} permit = withWork c doWork (\db -> getNextRcvChunkToDownload db srv rcvFilesTTL) $ \case (RcvFileChunk {rcvFileId, rcvFileEntityId, fileTmpPath, replicas = []}, _, redirectEntityId_) -> rcvWorkerInternalError c rcvFileId rcvFileEntityId redirectEntityId_ (Just fileTmpPath) (INTERNAL "chunk has no replicas") @@ -210,11 +214,12 @@ runXFTPRcvWorker c srv Worker {doWork} = do liftIO $ waitWhileSuspended c liftIO $ waitForUserNetwork c incXFTPServerStat c userId srv downloadAttempts - downloadFileChunk fc replica approvedRelays + downloadFileChunk permit fc replica approvedRelays `catchAllErrors` \e -> retryOnError "XFTP rcv worker" (retryLoop loop e delay') (retryDone e) e where retryLoop loop e replicaDelay = do flip catchAllErrors (\_ -> pure ()) $ do + liftIO $ releaseXFTPDownloadPermit c permit when (serverHostError e) $ notify c (fromMaybe rcvFileEntityId redirectEntityId_) (RFWARN e) liftIO $ closeXFTPServerClient c userId server digest withStore' c $ \db -> updateRcvChunkReplicaDelay db rcvChunkReplicaId replicaDelay @@ -225,15 +230,15 @@ runXFTPRcvWorker c srv Worker {doWork} = do XFTP _ XFTP.AUTH -> downloadAuthErrs _ -> downloadErrs rcvWorkerInternalError c rcvFileId rcvFileEntityId redirectEntityId_ (Just fileTmpPath) e - downloadFileChunk :: RcvFileChunk -> RcvFileChunkReplica -> Bool -> AM () - downloadFileChunk RcvFileChunk {userId, rcvFileId, rcvFileEntityId, rcvChunkId, chunkNo, chunkSize, digest, fileTmpPath} replica approvedRelays = do + downloadFileChunk :: XFTPDownloadPermit -> RcvFileChunk -> RcvFileChunkReplica -> Bool -> AM () + downloadFileChunk permit RcvFileChunk {userId, rcvFileId, rcvFileEntityId, rcvChunkId, chunkNo, chunkSize, digest, fileTmpPath} replica approvedRelays = do unlessM ((approvedRelays ||) <$> ipAddressProtected') $ throwE $ FILE NOT_APPROVED fsFileTmpPath <- lift $ toFSFilePath fileTmpPath chunkPath <- uniqueCombine fsFileTmpPath $ show chunkNo let chSize = unFileSize chunkSize chunkSpec = XFTPRcvChunkSpec chunkPath chSize (unFileDigest digest) relChunkPath = fileTmpPath takeFileName chunkPath - agentXFTPDownloadChunk c userId digest replica chunkSpec + agentXFTPDownloadChunk c permit userId digest replica chunkSpec liftIO $ waitUntilForeground c (entityId, complete, progress) <- handleAllErrors (rcvFileError c rcvFileId) . withStore c $ \db -> runExceptT $ do liftIO $ lockRcvFileForUpdate db rcvFileId diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index ccbdeeb2a..46c105eaa 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -89,6 +89,8 @@ module Simplex.Messaging.Agent.Client agentNtfCheckSubscription, agentNtfCheckSubscriptions, agentNtfDeleteSubscription, + withXFTPDownloadPermit, + releaseXFTPDownloadPermit, agentXFTPDownloadChunk, agentXFTPNewChunk, agentXFTPUploadChunk, @@ -194,6 +196,7 @@ module Simplex.Messaging.Agent.Client SMPTransportSession, NtfTransportSession, XFTPTransportSession, + XFTPDownloadPermit, ProxiedRelay (..), SMPConnectedClient (..), ) @@ -325,7 +328,7 @@ import Simplex.Messaging.Util import Simplex.Messaging.Version import System.Mem.Weak (Weak, deRefWeak) import System.Random (randomR) -import UnliftIO (mapConcurrently, timeout) +import UnliftIO (QSem, mapConcurrently, newQSem, signalQSem, timeout, waitQSem) import UnliftIO.Async (async) import UnliftIO.Concurrent (forkIO, mkWeakThreadId) import UnliftIO.Directory (doesFileExist, getTemporaryDirectory, removeFile) @@ -351,6 +354,8 @@ type NtfTransportSession = TransportSession NtfResponse type XFTPTransportSession = TransportSession FileResponse +type XFTPDownloadPermit = TVar (Maybe XFTPTransportSession) + data AgentClient = AgentClient { acThread :: TVar (Maybe (Weak ThreadId)), active :: TVar Bool, @@ -367,6 +372,7 @@ data AgentClient = AgentClient ntfClients :: TMap NtfTransportSession NtfClientVar, xftpServers :: TMap UserId (UserServers 'PXFTP), xftpClients :: TMap XFTPTransportSession XFTPClientVar, + xftpDownloadSessions :: QSem, userEntitlements :: TMap UserId EntitlementCredential, useNetworkConfig :: TVar (NetworkConfig, NetworkConfig), -- (slow, fast) networks presetDomains :: [HostName], @@ -544,6 +550,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf ntfClients <- TM.emptyIO xftpServers <- newTVarIO $ M.map mkUserServers xftp xftpClients <- TM.emptyIO + xftpDownloadSessions <- newQSem $ xftpMaxDownloadSessions cfg userEntitlements <- newTVarIO entitlements useNetworkConfig <- newTVarIO (slowNetworkConfig netCfg, netCfg) userNetworkInfo <- newTVarIO $ UserNetworkInfo UNOther True @@ -592,6 +599,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf ntfClients, xftpServers, xftpClients, + xftpDownloadSessions, userEntitlements, useNetworkConfig, presetDomains, @@ -983,7 +991,7 @@ newProtocolClient :: newProtocolClient c tSess@(userId, srv, entityId_) clients connectClient v = tryAllErrors (connectClient v) >>= \case Right client -> do - logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv <> " (user " <> bshow userId <> maybe "" (" for entity " <>) entityId_ <> ")" + logInfo . safeDecodeUtf8 $ "Agent connected to " <> showServer srv <> " (user " <> bshow userId <> maybe "" (" for entity " <>) entityId_ <> ")" atomically $ putTMVar (sessionVar v) (Right client) liftIO $ nonBlockingWriteTBQueue (subQ c) ("", "", AEvt SAENone $ hostEvent CONNECT client) pure client @@ -2281,10 +2289,40 @@ agentNtfDeleteSubscription :: AgentClient -> NtfSubscriptionId -> NtfToken -> AM agentNtfDeleteSubscription c subId NtfToken {ntfServer, ntfPrivKey} = withNtfClient c NRMBackground ntfServer subId "SDEL" $ \ntf -> ntfDeleteSubscription ntf ntfPrivKey subId -agentXFTPDownloadChunk :: AgentClient -> UserId -> FileDigest -> RcvFileChunkReplica -> XFTPRcvChunkSpec -> AM () -agentXFTPDownloadChunk c userId (FileDigest chunkDigest) RcvFileChunkReplica {server, replicaId = ChunkReplicaId fId, replicaKey} chunkSpec = do +withXFTPDownloadPermit :: AgentClient -> (XFTPDownloadPermit -> AM a) -> AM a +withXFTPDownloadPermit c action = + ExceptT $ E.bracket (newTVarIO Nothing) (liftIO . releaseXFTPDownloadPermit c) (runExceptT . action) + +agentXFTPDownloadChunk :: AgentClient -> XFTPDownloadPermit -> UserId -> FileDigest -> RcvFileChunkReplica -> XFTPRcvChunkSpec -> AM () +agentXFTPDownloadChunk c@AgentClient {xftpServers} permit userId (FileDigest chunkDigest) RcvFileChunkReplica {server, replicaId = ChunkReplicaId fId, replicaKey} chunkSpec = do g <- asks random - withXFTPClient c (userId, server, chunkDigest) "FGET" $ \xftp -> X.downloadXFTPChunk g xftp replicaKey fId chunkSpec + tSess@(_, _, entId_) <- mkTransportSession c userId server chunkDigest + let download = withLogClient c NRMBackground tSess chunkDigest "FGET" $ \xftp -> X.downloadXFTPChunk g xftp replicaKey fId chunkSpec + downloadAndClose = download `allFinally` liftIO (closeClient c xftpClients tSess) + downloadWithPermit = liftIO (holdXFTPDownloadPermit c permit tSess) >> download + ifM + (liftIO userServer) + (if isJust entId_ then downloadAndClose else download) + downloadWithPermit + where + userServer :: IO Bool + userServer = maybe False (\srvs -> any (`S.member` knownHosts srvs) $ serverHosts server) <$> TM.lookupIO userId xftpServers + +holdXFTPDownloadPermit :: AgentClient -> XFTPDownloadPermit -> XFTPTransportSession -> IO () +holdXFTPDownloadPermit c permit tSess = + readTVarIO permit >>= \case + Nothing -> E.mask_ $ waitQSem (xftpDownloadSessions c) >> setSession + Just tSess' + | tSess' == tSess -> pure () + | otherwise -> closeClient c xftpClients tSess' >> setSession + where + setSession = atomically $ writeTVar permit $ Just tSess + +releaseXFTPDownloadPermit :: AgentClient -> XFTPDownloadPermit -> IO () +releaseXFTPDownloadPermit c permit = + readTVarIO permit >>= mapM_ (\tSess -> closeClient c xftpClients tSess >> returnPermit) + where + returnPermit = E.mask_ $ signalQSem (xftpDownloadSessions c) >> atomically (writeTVar permit Nothing) agentXFTPNewChunk :: AgentClient -> SndFileChunk -> Int -> XFTPServerWithAuth -> Maybe Word32 -> AM NewSndChunkReplica agentXFTPNewChunk c SndFileChunk {userId, chunkSpec = XFTPChunkSpec {chunkSize}, digest = FileDigest chunkDigest} n (ProtoServerWithAuth srv auth) storageHours = do diff --git a/src/Simplex/Messaging/Agent/Env/SQLite.hs b/src/Simplex/Messaging/Agent/Env/SQLite.hs index d32be79b1..47b4da520 100644 --- a/src/Simplex/Messaging/Agent/Env/SQLite.hs +++ b/src/Simplex/Messaging/Agent/Env/SQLite.hs @@ -176,6 +176,7 @@ data AgentConfig = AgentConfig sndFilesTTL :: NominalDiffTime, xftpConsecutiveRetries :: Int, xftpMaxRecipientsPerRequest :: Int, + xftpMaxDownloadSessions :: Int, deleteErrorCount :: Int, keepAddressKeys :: Int, ntfCron :: Word16, @@ -254,6 +255,7 @@ defaultAgentConfig = sndFilesTTL = nominalDay, xftpConsecutiveRetries = 3, xftpMaxRecipientsPerRequest = 200, + xftpMaxDownloadSessions = 16, deleteErrorCount = 10, keepAddressKeys = 3, ntfCron = 20, -- minutes diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index 4b001a4ab..026dfe9de 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -22,23 +22,25 @@ import qualified Data.ByteString.Lazy as LB import Data.Either (isLeft) import Data.Int (Int64) import Data.List (find, isSuffixOf) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M -import Data.Maybe (fromJust) +import Data.Maybe (fromJust, isJust) import qualified Data.Set as S import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay) import Data.Time.Clock.System (getSystemTime, systemSeconds) -import SMPAgentClient (agentCfg, initAgentServers, testDB, testDB2, testDB3) +import SMPAgentClient (agentCfg, initAgentServers, noAuthSrvCfg, testDB, testDB2, testDB3, userServers) +import SMPClient (testHost2, withStallingServerOn', xit'') import Simplex.FileTransfer.Client (XFTPClientConfig (..)) -import Simplex.FileTransfer.Description (FileChunk (..), FileDescription (..), FileDescriptionURI (..), ValidFileDescription, fileDescriptionURI, kb, mb, qrSizeLimit, pattern ValidFileDescription) -import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..)) +import Simplex.FileTransfer.Description (ChunkReplicaId (..), FileChunk (..), FileChunkReplica (..), FileDescription (..), FileDescriptionURI (..), FileDigest (..), FileSize (..), ValidFileDescription, fileDescriptionURI, kb, mb, qrSizeLimit, validateFileDescription, pattern ValidFileDescription) +import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..), SFileParty (..)) import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..), defaultFileExpiration) import Simplex.FileTransfer.Server.Store (STMFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (AUTH)) import Simplex.FileTransfer.Types (FileErrorType (NO_FILE), RcvFileId, SndFileId) import Simplex.Messaging.Agent (AgentClient, testProtocolServer, xftpDeleteRcvFile, xftpDeleteSndFileInternal, xftpDeleteSndFileRemote, xftpPrepareReceiveFile, xftpPrepareSendFile, xftpReceiveFile, xftpSendDescription, xftpStartReceiveFile, xftpStartSendFile, xftpStartWorkers) import qualified Simplex.Messaging.Agent as XA -import Simplex.Messaging.Agent.Client (AgentClient (xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, xftpCfg) +import Simplex.Messaging.Agent.Client (AgentClient (subQ, xftpClients, xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, InitialAgentServers, xftpCfg) import qualified Simplex.Messaging.Agent.Env.SQLite as AEnv import Simplex.Messaging.Agent.Protocol hiding (SFDONE) import qualified Simplex.Messaging.Agent.Protocol as A @@ -46,14 +48,14 @@ import Simplex.Messaging.Agent.Stats (AgentXFTPServerStats (downloadAttempts, up import Simplex.Messaging.Agent.Store.Common (withTransaction) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Interface (closeDBStore) -import Simplex.Messaging.Client (pattern NRMInteractive) +import Simplex.Messaging.Client (TransportSessionMode (..), pattern NRMInteractive) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.BBS (bbsKeyGen) import Simplex.Messaging.Crypto.Entitlement (Entitlement (..), MasterKey (..), signEntitlement) import Simplex.Messaging.Crypto.File (CryptoFile (..), CryptoFileArgs) import qualified Simplex.Messaging.Crypto.File as CF import Simplex.Messaging.Encoding.String (StrEncoding (..)) -import Simplex.Messaging.Protocol (BasicAuth, NetworkError (..), ProtoServerWithAuth (..), ProtocolServer (..), XFTPServer, XFTPServerWithAuth) +import Simplex.Messaging.Protocol (AProtocolType (..), BasicAuth, EntityId (..), NetworkError (..), ProtoServerWithAuth (..), ProtocolServer (..), SProtocolType (..), XFTPServer, XFTPServerWithAuth) import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) import Simplex.Messaging.Server.Information (ServerPublicInfo) import Simplex.Messaging.Transport (EntitlementConfig (..)) @@ -91,6 +93,20 @@ xftpAgentTests = it "should resume receiving file after restart" $ \_ -> testXFTPAgentReceiveRestore it "should cleanup rcv tmp path after permanent error" $ \_ -> testXFTPAgentReceiveCleanup it "should report permanent error even when rcv tmp path cannot be removed" $ \_ -> testXFTPAgentReceiveCleanupError + it "should limit download sessions with servers outside the user's list" $ + testXFTPAgentDownloadSessionsLimit xftpServer2Only + it "should limit download sessions with servers outside the user's list in entity session mode" $ + testXFTPAgentDownloadSessionsLimit $ entitySessionMode xftpServer2Only + it "should release download sessions of stopped workers" testXFTPAgentDownloadSessionsStopped + it "should keep download session with a server outside the user's list for all chunks of a file" $ + testXFTPAgentDownloadSessionChunks xftpServer2Only 1 + it "should open download session per chunk with a server outside the user's list in entity session mode" $ + testXFTPAgentDownloadSessionChunks (entitySessionMode xftpServer2Only) 2 + it "should close download sessions in entity session mode" $ + testXFTPAgentDownloadSessions (entitySessionMode initAgentServers) 0 + it "should keep download session shared with the user's server" $ testXFTPAgentDownloadSessions initAgentServers 1 + it "should keep download session with a disabled server in the user's list" $ + testXFTPAgentDownloadSessions initAgentServers {AEnv.xftp = M.fromList [(1, noAuthSrvCfg testXFTPServer2 {host = testHost2} :| [(noAuthSrvCfg testXFTPServer) {AEnv.enabled = False}])]} 1 it "should resume sending file after restart" $ \_ -> testXFTPAgentSendRestore it "should cleanup snd prefix path after permanent error" $ \_ -> testXFTPAgentSendCleanup it "should delete sent file on server" testXFTPAgentDelete @@ -633,6 +649,84 @@ testXFTPAgentReceiveCleanupError = withGlobalLogging logCfgNoLogs $ do `finally` setPermissions prefixPath perms doesDirectoryExist tmpPath `shouldReturn` True +testXFTPAgentDownloadSessionsLimit :: (HasCallStack, HasTestEnv) => InitialAgentServers -> AFStoreType -> IO () +testXFTPAgentDownloadSessionsLimit rcpServers = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers {AEnv.xftp = userServers $ testXFTPServer {host = testHost2} :| []} + silentRfd <- silentServersDescription 6 + withStallingServerOn' xftpTestPort2 $ \accepted _ -> + withAgent 2 agentCfg {AEnv.xftpMaxDownloadSessions = 1} rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 silentRfd Nothing True + timeout 5000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + threadDelay 500000 + M.size <$> readTVarIO (xftpClients rcp) `shouldReturn` 1 + timeout 5000000 (runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320)) >>= (`shouldSatisfy` isJust) + +testXFTPAgentDownloadSessionsStopped :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () +testXFTPAgentDownloadSessionsStopped = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers + silentRfd <- silentServersDescription 1 + withStallingServerOn' xftpTestPort2 $ \accepted _ -> + withAgent 2 agentCfg {AEnv.xftpMaxDownloadSessions = 1} xftpServer2Only testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 silentRfd Nothing True + timeout 5000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + XA.disconnectAgentClient rcp + XA.resumeAgentClient rcp + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + timeout 10000000 (runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320)) >>= (`shouldSatisfy` isJust) + +silentServersDescription :: HasTestEnv => Int -> IO (ValidFileDescription 'FRecipient) +silentServersDescription n = do + g <- C.newRandom + key <- atomically $ C.randomSbKey g + nonce <- atomically $ C.randomCbNonce g + (_, replicaKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let chunk i = FileChunk {chunkNo = i, chunkSize = FileSize $ kb 64, digest = FileDigest "abc", replicas = [FileChunkReplica {server = testXFTPServer2 {keyHash = C.KeyHash $ B.pack $ show i}, replicaId = ChunkReplicaId $ EntityId "abc", replicaKey}]} + either fail pure . validateFileDescription $ + FileDescription {party = SFRecipient, size = FileSize $ kb 64 * fromIntegral n, digest = FileDigest "abc", key, nonce, chunkSize = FileSize $ kb 64, chunks = map chunk [1 .. n], redirect = Nothing} + +testXFTPAgentDownloadSessions :: (HasCallStack, HasTestEnv) => InitialAgentServers -> Int -> AFStoreType -> IO () +testXFTPAgentDownloadSessions rcpServers sessions = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers + withAgent 2 agentCfg rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320) + M.size <$> readTVarIO (xftpClients rcp) `shouldReturn` sessions + +testXFTPAgentDownloadSessionChunks :: (HasCallStack, HasTestEnv) => InitialAgentServers -> Int -> AFStoreType -> IO () +testXFTPAgentDownloadSessionChunks rcpServers connects = withXFTPServer $ do + (_, rfd) <- sendTwoChunkFile initAgentServers + withAgent 2 agentCfg rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 rfd Nothing True + timeout 10000000 (xftpConnectsUntilReceived rcp) `shouldReturn` Just connects + timeout 5000000 (atomically $ readTVar (xftpClients rcp) >>= checkSTM . M.null) `shouldReturn` Just () + +sendTwoChunkFile :: (HasCallStack, HasTestEnv) => InitialAgentServers -> IO (FilePath, ValidFileDescription 'FRecipient) +sendTwoChunkFile sndServers = do + filePath <- createRandomFile_ (kb 319 :: Integer) "testfile" + rfd <- withAgent 1 agentCfg sndServers testDB $ \sndr -> runRight $ do + (_, _, rfd, _) <- testSendCF' sndr (CF.plain filePath) (kb 320) + pure rfd + pure (filePath, rfd) + +xftpServer2Only :: HasTestEnv => InitialAgentServers +xftpServer2Only = initAgentServers {AEnv.xftp = userServers $ testXFTPServer2 {host = testHost2} :| []} + +entitySessionMode :: InitialAgentServers -> InitialAgentServers +entitySessionMode servers = servers {AEnv.netCfg = (AEnv.netCfg servers) {AEnv.sessionMode = TSMEntity}} + +xftpConnectsUntilReceived :: AgentClient -> IO Int +xftpConnectsUntilReceived c = count 0 + where + count :: Int -> IO Int + count n = + atomically (readTBQueue $ subQ c) >>= \case + (_, _, AEvt _ (CONNECT (AProtocolType SPXFTP) _)) -> count (n + 1) + (_, _, AEvt _ RFDONE {}) -> pure n + _ -> count n + testXFTPAgentSendRestore :: (HasCallStack, HasTestEnv) => IO () testXFTPAgentSendRestore = withGlobalLogging logCfgNoLogs $ do filePath <- createRandomFile From ccc36b1c14cb746c5003e1310afbca68a39a47c5 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 03:03:32 -0500 Subject: [PATCH 020/159] xftp-server: close stalled connections and reduce memory Consolidated from PR #2058, preserving the fixes from PRs #2044, #2064, #2079 and #2088. --- simplexmq.cabal | 3 +- src/Simplex/FileTransfer/Agent.hs | 2 +- src/Simplex/FileTransfer/Server.hs | 262 ++++++------ src/Simplex/FileTransfer/Server/Env.hs | 34 +- src/Simplex/FileTransfer/Server/Main.hs | 30 +- src/Simplex/FileTransfer/Server/Prometheus.hs | 27 +- src/Simplex/FileTransfer/Server/Stats.hs | 8 +- src/Simplex/FileTransfer/Server/Store.hs | 55 ++- .../FileTransfer/Server/Store/Postgres.hs | 41 +- src/Simplex/FileTransfer/Server/StoreLog.hs | 5 +- src/Simplex/FileTransfer/Transport.hs | 27 +- src/Simplex/Messaging/Transport/HTTP2/File.hs | 10 +- .../Messaging/Transport/HTTP2/Server.hs | 67 ++- src/Simplex/Messaging/Transport/Server.hs | 17 +- tests/AgentTests/FunctionalAPITests.hs | 2 - tests/CLITests.hs | 62 ++- tests/CoreTests/TransportTests.hs | 91 ++++ tests/CoreTests/XFTPStoreTests.hs | 76 +++- tests/Test.hs | 2 + tests/XFTPClient.hs | 4 +- tests/XFTPServerTests.hs | 401 +++++++++++++++++- 21 files changed, 960 insertions(+), 266 deletions(-) create mode 100644 tests/CoreTests/TransportTests.hs diff --git a/simplexmq.cabal b/simplexmq.cabal index 323b14314..1fb2272cd 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -555,7 +555,7 @@ executable xftp-server apps/common default-extensions: StrictData - ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=incomplete-uni-patterns -Werror=missing-methods -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -O2 -threaded -rtsopts + ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=incomplete-uni-patterns -Werror=missing-methods -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -O2 -threaded -rtsopts "-with-rtsopts=-N -F1.2 -A16m -I0.01 -Iw15 -T -ki2k --disable-delayed-os-memory-return" build-depends: base , bytestring @@ -593,6 +593,7 @@ test-suite simplexmq-test CoreTests.SOCKSSettings CoreTests.StoreLogTests CoreTests.TSessionSubs + CoreTests.TransportTests CoreTests.UtilTests CoreTests.VersionRangeTests FileDescriptionTests diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index ce79699bf..7aeb2f627 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -81,7 +81,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (strDecode, strEncode) import Simplex.Messaging.Protocol (ProtocolServer, ProtocolType (..), XFTPServer) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (allFinally, catchAllErrors, catchOwn_, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) +import Simplex.Messaging.Util (allFinally, catchAll_, catchAllErrors, catchOwn_, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) import System.FilePath (takeFileName, ()) import UnliftIO import UnliftIO.Directory diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index 034800b6e..ca24a9c9e 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -38,7 +38,7 @@ import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Text as T import qualified Data.Text.IO as T -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (systemSeconds, utcToSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import Data.Word (Word32) @@ -78,13 +78,13 @@ import Simplex.Messaging.Transport.Buffer (trimCR) import Simplex.Messaging.Transport.HTTP2 import Simplex.Messaging.Transport.HTTP2.File (fileBlockSize) import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) -import Simplex.Messaging.Transport.Server (SNICredentialUsed, TransportServerConfig (..), runLocalTCPServer) +import Simplex.Messaging.Transport.Server (SNICredentialUsed, SocketState, TransportServerConfig (..), getSocketStats, runLocalTCPServer) import Simplex.Messaging.Server.Web (serveStaticPageH2) import Simplex.Messaging.Util import Simplex.Messaging.Version import System.Environment (lookupEnv) import System.Exit (exitFailure) -import System.FilePath (()) +import System.FilePath (takeExtension, ()) import System.IO (hPrint, hPutStrLn, universalNewlineMode) import System.IO.Error (isDoesNotExistError) #ifdef slow_servers @@ -92,7 +92,7 @@ import System.Random (getStdRandom, randomR) #endif import UnliftIO import UnliftIO.Concurrent (threadDelay) -import UnliftIO.Directory (canonicalizePath, doesFileExist, listDirectory, removeFile, renameFile) +import UnliftIO.Directory (canonicalizePath, doesDirectoryExist, doesFileExist, listDirectory, removeFile, renameFile) import qualified UnliftIO.Exception as E type M s a = ReaderT (XFTPEnv s) IO a @@ -102,6 +102,7 @@ data XFTPTransportRequest = XFTPTransportRequest reqBody :: HTTP2Body, request :: H.Request, sendResponse :: H.Response -> IO (), + closeSession :: IO (), sniUsed :: SNICredentialUsed, addCORS :: Bool } @@ -137,8 +138,9 @@ data EntitlementChecked = EntNotChecked | EntChecked (Maybe SessionEntitlement) xftpServer :: forall s. FileStoreClass s => XFTPServerConfig s -> TMVar Bool -> M s () xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpiration, fileExpiration, xftpServerVRange, information} started = do expireServerFiles Nothing fileExpiration - removeUnstoredFiles + removeTmpUploads restoreServerStats + expireServerFiles Nothing fileExpiration `onException` stopServer raceAny_ ( runServer : expireFiles fileExpiration @@ -160,25 +162,28 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira let cleanup sessionId = atomically $ TM.delete sessionId sessions srvParams = if isJust httpCreds_ then defaultSupportedParamsHTTPS else defaultSupportedParams webCanonicalRoot_ <- liftIO $ mapM canonicalizePath (webStaticPath cfg) - liftIO . runHTTP2Server started xftpPort defaultHTTP2BufferSize srvParams srvCreds httpCreds_ transportConfig inactiveClientExpiration cleanup $ \sniUsed sessionId sessionALPN r sendResponse -> do + socketState <- asks sockets + liftIO . runHTTP2Server socketState started xftpPort defaultHTTP2BufferSize srvParams srvCreds httpCreds_ transportConfig inactiveClientExpiration cleanup $ \sniUsed closeSession sessionId sessionALPN r sendResponse -> do let addCORS' = sniUsed && addCORSHeaders transportConfig case H.requestMethod r of Just "OPTIONS" | addCORS' -> sendResponse $ H.responseNoBody N.ok200 corsPreflightHeaders Just "GET" | sniUsed -> forM_ webCanonicalRoot_ $ \root -> serveStaticPageH2 root r sendResponse - _ -> do - reqBody <- getHTTP2Body r xftpBlockSize - let v = VersionXFTP 1 - thServerVRange = versionToRange v - thParams0 = THandleParams {sessionId, blockSize = xftpBlockSize, thVersion = v, thServerVRange, thAuth = Nothing, implySessId = False, encryptBlock = Nothing, serviceAuth = False, serverInfo = Nothing} - req0 = XFTPTransportRequest {thParams = thParams0, request = r, reqBody, sendResponse, sniUsed, addCORS = addCORS'} - flip runReaderT env $ case sessionALPN of - Nothing -> processRequest req0 - Just alpn - | alpn == xftpALPNv1 || alpn == httpALPN11 || (sniUsed && alpn == "h2") -> - xftpServerHandshakeV1 chain signKey sessions req0 >>= \case - Nothing -> pure () - Just thParams -> processRequest req0 {thParams} - | otherwise -> liftIO . sendResponse $ H.responseNoBody N.ok200 (corsHeaders addCORS') + _ -> + timeout (fileTimeout cfg) (getHTTP2Body r xftpBlockSize) >>= \case + Nothing -> logWarn "request receiving timeout, closing connection" >> closeSession + Just reqBody -> do + let v = VersionXFTP 1 + thServerVRange = versionToRange v + thParams0 = THandleParams {sessionId, blockSize = xftpBlockSize, thVersion = v, thServerVRange, thAuth = Nothing, implySessId = False, encryptBlock = Nothing, serviceAuth = False, serverInfo = Nothing} + req0 = XFTPTransportRequest {thParams = thParams0, request = r, reqBody, sendResponse, closeSession, sniUsed, addCORS = addCORS'} + flip runReaderT env $ case sessionALPN of + Nothing -> processRequest req0 + Just alpn + | alpn == xftpALPNv1 || alpn == httpALPN11 || (sniUsed && alpn == "h2") -> + xftpServerHandshakeV1 chain signKey sessions req0 >>= \case + Nothing -> pure () + Just thParams -> processRequest req0 {thParams} + | otherwise -> liftIO . sendResponse $ H.responseNoBody N.ok200 (corsHeaders addCORS') xftpServerHandshakeV1 :: X.CertificateChain -> C.APrivateSignKey -> TMap SessionId Handshake -> XFTPTransportRequest -> M s (Maybe (THandleParams XFTPVersion 'TServer)) xftpServerHandshakeV1 chain serverSignKey sessions XFTPTransportRequest {thParams = thParams0@THandleParams {sessionId}, request, reqBody = HTTP2Body {bodyHead}, sendResponse, sniUsed, addCORS} = do s <- atomically $ TM.lookup sessionId sessions @@ -286,13 +291,21 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira serverStatsThread_ :: XFTPServerConfig s -> [M s ()] serverStatsThread_ XFTPServerConfig {logStatsInterval = Just interval, logStatsStartTime, serverStatsLogFile} = [logServerStats logStatsStartTime interval serverStatsLogFile] - serverStatsThread_ _ = [] + serverStatsThread_ XFTPServerConfig {logStatsStartTime} = [resetPeriodStats logStatsStartTime] + + resetPeriodStats :: Int64 -> M s () + resetPeriodStats startAt = do + FileServerStats {filesDownloaded} <- asks serverStats + liftIO $ do + delayUntilDayTime startAt + forever $ do + void . periodStatCounts filesDownloaded =<< getCurrentTime + threadDelay' $ 1_000_000 * periodStatsInterval logServerStats :: Int64 -> Int64 -> FilePath -> M s () logServerStats startAt logInterval statsFilePath = do - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime liftIO $ putStrLn $ "server stats log enabled: " <> statsFilePath - liftIO $ threadDelay' $ 1_000_000 * (initialDelay + if initialDelay < 0 then 86_400 else 0) + liftIO $ delayUntilDayTime startAt FileServerStats {fromTime, filesCreated, fileRecipients, filesUploaded, filesExpired, filesDeleted, filesDownloaded, fileDownloads, fileDownloadAcks, filesCount, filesSize} <- asks serverStats let interval = 1_000_000 * logInterval forever $ do @@ -339,21 +352,23 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira labelMyThread "savePrometheusMetrics" liftIO $ putStrLn $ "Prometheus metrics saved every " <> show saveInterval <> " seconds to " <> metricsFile ss <- asks serverStats + socketState <- asks sockets rtsOpts <- liftIO $ maybe ("set " <> rtsOptionsEnv) T.pack <$> lookupEnv (T.unpack rtsOptionsEnv) let interval = 1000000 * saveInterval saveMetrics = do ts <- getCurrentTime - sm <- getFileServerMetrics ss rtsOpts + sm <- getFileServerMetrics ss socketState rtsOpts writeFileAtomic metricsFile (xftpPrometheusMetrics sm ts) liftIO $ forever $ do threadDelay interval saveMetrics `catchAny` \e -> logError $ "Prometheus metrics error: " <> tshow e - getFileServerMetrics :: FileServerStats -> T.Text -> IO FileServerMetrics - getFileServerMetrics ss rtsOptions = do + getFileServerMetrics :: FileServerStats -> SocketState -> T.Text -> IO FileServerMetrics + getFileServerMetrics ss socketState rtsOptions = do d <- getFileServerStatsData ss + socketStats <- (xftpPort,) <$> getSocketStats socketState let fd = periodStatDataCounts $ _filesDownloaded d - pure FileServerMetrics {statsData = d, filesDownloadedPeriods = fd, rtsOptions} + pure FileServerMetrics {statsData = d, filesDownloadedPeriods = fd, socketStats, rtsOptions} controlPortThread_ :: XFTPServerConfig s -> [M s ()] controlPortThread_ XFTPServerConfig {controlPort = Just port} = [runCPServer port] @@ -427,7 +442,7 @@ data ServerFile = ServerFile } processRequest :: FileStoreClass s => XFTPTransportRequest -> M s () -processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHead}, sendResponse, addCORS} +processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHead}, sendResponse, closeSession, addCORS} | B.length bodyHead /= xftpBlockSize = sendXFTPResponse ("", NoEntity, FRErr BLOCK) Nothing | otherwise = case xftpDecodeTServer thParams bodyHead of @@ -444,21 +459,25 @@ processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHea where sendXFTPResponse t' serverFile_ = do let t_ = xftpEncodeTransmission thParams t' + sendTimeout <- asks $ fileTimeout . config #ifdef slow_servers randomDelay #endif - liftIO $ sendResponse $ H.responseStreaming N.ok200 (corsHeaders addCORS) $ streamBody t_ + liftIO $ case t_ of + Left _ -> sendResponse $ responseBuilder paddingError + Right t -> case serverFile_ of + Nothing -> sendResponse $ responseBuilder $ byteString t + Just serverFile -> withAsync (closeAfter sendTimeout) $ \_ -> sendResponse $ H.responseStreaming N.ok200 (corsHeaders addCORS) $ streamBody t serverFile where - streamBody t_ send done = do - case t_ of - Left _ -> do - send "padding error" -- TODO respond with BLOCK error? - done - Right t -> do - send $ byteString t - -- timeout sending file in the same way as receiving - forM_ serverFile_ $ \ServerFile {filePath, fileSize, sbState} -> do - withFile filePath ReadMode $ \h -> sendEncFile h send sbState fileSize + responseBuilder = H.responseBuilder N.ok200 (corsHeaders addCORS) + paddingError = "padding error" -- TODO respond with BLOCK error? + closeAfter sendTimeout = do + threadDelay sendTimeout + logWarn "file sending timeout, closing connection" + closeSession + streamBody t ServerFile {filePath, fileSize, sbState} send done = do + send $ byteString t + withFile filePath ReadMode $ \h -> sendEncFile h send sbState fileSize done #ifdef slow_servers @@ -504,7 +523,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case XFTPServerConfig {allowNewFiles, newFileBasicAuth} <- asks config pure $ allowNewFiles && maybe True ((== auth) . Just) newFileBasicAuth XFTPReqCmd fId fr (FileCmd _ cmd) -> case cmd of - FADD rks -> noFile =<< addRecipients fId rks + FADD rks -> noFile =<< addFileRecipients fId rks FPUT -> noFile =<< receiveServerFile fr FDEL -> noFile =<< deleteServerFile fr FGET rDhKey -> sendServerFile fr rDhKey @@ -531,7 +550,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case fileExpiresAt = RoundedSystemTime $ ((nowSeconds + secs + fileTimePrecision - 1) `div` fileTimePrecision) * fileTimePrecision -- TODO validate body empty sId <- ExceptT $ addFileRetry st file 3 ts (Just fileExpiresAt) - rcps <- mapM (ExceptT . addRecipientRetry st 3 sId) rks + rcps <- ExceptT $ addRecipientsRetry st 3 sId rks lift $ withFileLog $ \sl -> do logAddFile sl sId file ts (Just fileExpiresAt) EntityActive logAddRecipients sl sId rcps @@ -549,27 +568,22 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case _ -> defaultMax addFileRetry :: s -> FileInfo -> Int -> RoundedFileTime -> Maybe RoundedFileTime -> M s (Either XFTPErrorType XFTPFileId) addFileRetry st file n ts expiresAt = - retryAdd n $ \sId -> runExceptT $ do - ExceptT $ addFile st sId file ts expiresAt EntityActive - pure sId - addRecipientRetry :: s -> Int -> XFTPFileId -> RcvPublicAuthKey -> M s (Either XFTPErrorType FileRecipient) - addRecipientRetry st n sId rpk = - retryAdd n $ \rId -> runExceptT $ do - let rcp = FileRecipient rId rpk - ExceptT $ addRecipient st sId rcp - pure rcp - retryAdd :: Int -> (XFTPFileId -> IO (Either XFTPErrorType a)) -> M s (Either XFTPErrorType a) - retryAdd 0 _ = pure $ Left INTERNAL - retryAdd n add = do - fId <- getFileId - liftIO (add fId) >>= \case - Left DUPLICATE_ -> retryAdd (n - 1) add + retryAdd n getFileId $ \sId -> (sId <$) <$> addFile st sId file ts expiresAt EntityActive + addRecipientsRetry :: s -> Int -> XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s (Either XFTPErrorType (NonEmpty FileRecipient)) + addRecipientsRetry st n sId rks = + retryAdd n (mapM (\rpk -> (`FileRecipient` rpk) <$> getFileId) rks) $ \rcps -> (rcps <$) <$> addRecipients st sId rcps + retryAdd :: Int -> M s a -> (a -> IO (Either XFTPErrorType b)) -> M s (Either XFTPErrorType b) + retryAdd 0 _ _ = pure $ Left INTERNAL + retryAdd n newIds add = do + ids <- newIds + liftIO (add ids) >>= \case + Left DUPLICATE_ -> retryAdd (n - 1) newIds add r -> pure r - addRecipients :: XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s FileResponse - addRecipients sId rks = do + addFileRecipients :: XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s FileResponse + addFileRecipients sId rks = do st <- asks fileStore r <- runExceptT $ do - rcps <- mapM (ExceptT . addRecipientRetry st 3 sId) rks + rcps <- ExceptT $ addRecipientsRetry st 3 sId rks lift $ withFileLog $ \sl -> logAddRecipients sl sId rcps stats <- asks serverStats liftIO $ atomicModifyIORef'_ (fileRecipients stats) (+ length rks) @@ -598,8 +612,11 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case ifM (isJust <$> readTVarIO filePath) (pure Nothing) $ Just <$> mask (\restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA)) Left e -> pure $ Just $ FRErr e - skipCommitted = liftIO $ drain $ fromIntegral size + skipCommitted = ifM (isJust <$> readTVarIO filePath) drainCommitted where + drainCommitted = do + t <- asks $ fileTimeout . config + liftIO $ fromMaybe (FRErr TIMEOUT) <$> timeout t (drain $ fromIntegral size) -- can't send FROk without reading the request body or a client will block on sending it -- can't send any old error as the client would fail or restart indefinitely drain s = do @@ -615,9 +632,12 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case \used -> let used' = used + fromIntegral size in if used' <= quota then (True, used') else (False, used) receive restore = do path <- asks $ filesPath . config + tmpId <- randomId 12 let fPath = path serverFileName senderId - (restore (receiveChunk $ XFTPRcvChunkSpec fPath size digest) `onException` release fPath) >>= \case + tmpPath = fPath <> "." <> B.unpack (strEncode tmpId) <> tmpUploadExtension + (restore (receiveChunk $ XFTPRcvChunkSpec tmpPath size digest) `onException` release tmpPath) >>= \case Right () -> do + renameFile tmpPath fPath stats <- asks serverStats st <- asks fileStore liftIO (setFilePath st senderId fPath) >>= \case @@ -627,12 +647,23 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case incFileStat filesCount liftIO $ atomicModifyIORef'_ (filesSize stats) (+ fromIntegral size) pure FROk - Left _e -> FRErr AUTH <$ release fPath - Left e -> FRErr e <$ release fPath - release fPath = do + Left _e -> releaseQuota >> uploadedResponse fPath + Left e -> FRErr e <$ release tmpPath + uploadedResponse fPath = do + st <- asks fileStore + liftIO (getFile st SFSender senderId) >>= \case + Right (FileRec {filePath = uploadedPath, fileStatus}, _) -> + (,) <$> readTVarIO uploadedPath <*> readTVarIO fileStatus >>= \case + (Just _, _) -> pure FROk + (Nothing, EntityActive) -> pure $ FRErr AUTH + _ -> FRErr AUTH <$ removeUpload fPath + Left AUTH -> FRErr AUTH <$ removeUpload fPath + Left e -> pure $ FRErr e + release fPath = releaseQuota >> removeUpload fPath + releaseQuota = do us <- asks usedStorage atomically $ modifyTVar' us $ subtract (fromIntegral size) - liftIO $ whenM (doesFileExist fPath) (removeFile fPath) `catch` logFileError + removeUpload fPath = liftIO $ whenM (doesFileExist fPath) (removeFile fPath) `catch` logFileError receiveChunk spec = do t <- asks $ fileTimeout . config liftIO $ fromMaybe (Left TIMEOUT) <$> timeout t (runExceptT $ receiveFile getBody spec) @@ -678,28 +709,21 @@ deleteServerFile_ fr@FileRec {senderId} = mask_ $ do -- this also deletes the file from storage, but doesn't include it in delete statistics blockServerFile :: FileStoreClass s => FileRec -> BlockingInfo -> M s (Either XFTPErrorType ()) -blockServerFile fr@FileRec {senderId} info = mask_ $ do - r <- deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info True - forM_ r $ \_ -> withFileLog $ \sl -> logBlockFile sl senderId info - pure r +blockServerFile fr@FileRec {senderId} info = do + withFileLog $ \sl -> logBlockFile sl senderId info + deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info -deleteOrBlockServerFile_ :: FileStoreClass s => FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType (Maybe FilePath))) -> M s (Either XFTPErrorType ()) -deleteOrBlockServerFile_ FileRec {filePath, fileInfo} stat storeAction = runExceptT $ do +deleteOrBlockServerFile_ :: FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType (Maybe FilePath))) -> M s (Either XFTPErrorType ()) +deleteOrBlockServerFile_ FileRec {filePath, fileInfo} stat storeAction = mask_ $ runExceptT $ do path <- readTVarIO filePath - stats <- asks serverStats - ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (mapM_ (removeServerFile stats) path) + ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (forM_ path $ \p -> whenM (doesFileExist p) (removeFile p)) st <- asks fileStore - path' <- ExceptT $ liftIO $ storeAction st + removed <- ExceptT $ liftIO $ storeAction st + forM_ removed $ \p -> lift $ do + subtractStoredFile $ size fileInfo + whenM (doesFileExist p) $ + removeFile p `catch` \(e :: SomeException) -> logError $ "failed to remove file " <> tshow p <> ": " <> tshow e lift $ incFileStat stat - forM_ path' $ \p -> do - us <- asks usedStorage - atomically $ modifyTVar' us $ subtract (fromIntegral $ size fileInfo) - when (path /= Just p) $ lift $ removeServerFile stats p `catch` \(e :: SomeException) -> logError $ "failed to remove file " <> tshow p <> ": " <> tshow e - where - removeServerFile stats p = (removeFile p >> deletedStats stats) `catch` \e -> unless (isDoesNotExistError e) $ throwIO e - deletedStats stats = do - liftIO $ atomicModifyIORef'_ (filesCount stats) (subtract 1) - liftIO $ atomicModifyIORef'_ (filesSize stats) (subtract $ fromIntegral $ size fileInfo) entitlementValid :: SystemSeconds -> SystemSeconds -> Bool entitlementValid now expiresAt = roundedSeconds expiresAt + 86400 > roundedSeconds now @@ -713,45 +737,28 @@ expireServerFiles itemDelay expCfg = do old <- liftIO $ expireBeforeEpoch expCfg filesCount <- liftIO $ getFileCount st logNote $ "Expiration check: " <> tshow filesCount <> " files" - expireLoop st us now old + expireLoop st now old usedEnd <- readTVarIO us logNote $ "Used " <> mbs usedStart <> " -> " <> mbs usedEnd <> ", " <> mbs (usedStart - usedEnd) <> " reclaimed." where mbs bs = tshow (bs `div` 1048576) <> "mb" - expireLoop st us now old = do + expireLoop st now old = do expired <- liftIO $ expiredFiles st now old 10000 - forM_ expired $ \(_, filePath_, _) -> do - mapM_ threadDelay itemDelay - mapM_ removeExpiredFile filePath_ + forM_ expired $ \(_, filePath_, _) -> + forM_ filePath_ $ \fp -> + whenM (doesFileExist fp) $ + (removeFile fp >> mapM_ threadDelay itemDelay) `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e let sIds = map (\(sId, _, _) -> sId) expired unless (null sIds) $ do - deleted <- M.fromList <$> liftIO (deleteFiles st sIds) - forM_ expired $ \(sId, filePath_, fileSize) -> - forM_ (M.lookup sId deleted) $ \path -> do - forM_ path $ \fp -> do - when (filePath_ /= Just fp) $ removeExpiredFile fp - atomically $ modifyTVar' us $ subtract (fromIntegral fileSize) - incFileStat filesExpired - withFileLog $ \sl -> mapM_ (logDeleteFile sl) (M.keys deleted) - expireLoop st us now old - removeExpiredFile fp = - removeFile fp `catch` \e -> unless (isDoesNotExistError e) $ logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e - -removeUnstoredFiles :: FileStoreClass s => M s () -removeUnstoredFiles = do - dir <- asks $ filesPath . config - st <- asks fileStore - whenM ((> 0) <$> liftIO (getFileCount st)) $ do - removed <- filterM (unstored st) =<< listDirectory dir - forM_ removed $ \f -> removeFile (dir f) `catchAny` \_ -> pure () - unless (null removed) $ logNote $ "Removed " <> tshow (length removed) <> " files without records" - where - unstored st name = case B64.decode $ B.pack name of - Right sId -> - liftIO (getFile st SFSender $ EntityId sId) >>= \case - Right (FileRec {filePath}, _) -> isNothing <$> readTVarIO filePath - Left e -> pure $ e == AUTH - Left _ -> pure False + withFileLog $ \sl -> mapM_ (logDeleteFile sl) sIds + deleted <- liftIO $ deleteFiles st sIds + forM_ deleted $ \(_, filePath_, fileSize) -> do + forM_ filePath_ $ \_ -> subtractStoredFile fileSize + incFileStat filesExpired + expireLoop st now old + +periodStatsInterval :: Int64 +periodStatsInterval = 86400 randomId :: Int -> M s ByteString randomId n = atomically . C.randomBytes n =<< asks random @@ -767,6 +774,24 @@ incFileStat statSel = do stats <- asks serverStats liftIO $ atomicModifyIORef'_ (statSel stats) (+ 1) +tmpUploadExtension :: String +tmpUploadExtension = ".tmp" + +removeTmpUploads :: M s () +removeTmpUploads = do + path <- asks $ filesPath . config + whenM (doesDirectoryExist path) $ + listDirectory path >>= mapM_ (removeFile . (path )) . filter ((tmpUploadExtension ==) . takeExtension) + +subtractStoredFile :: Word32 -> M s () +subtractStoredFile storedSize = do + us <- asks usedStorage + atomically $ modifyTVar' us $ subtract (fromIntegral storedSize) + stats <- asks serverStats + liftIO $ do + atomicModifyIORef'_ (filesCount stats) (subtract 1) + atomicModifyIORef'_ (filesSize stats) (subtract $ fromIntegral storedSize) + saveServerStats :: M s () saveServerStats = asks (serverStatsBackupFile . config) @@ -777,7 +802,7 @@ saveServerStats = B.writeFile f $ strEncode stats logNote "server stats saved" -restoreServerStats :: FileStoreClass s => M s () +restoreServerStats :: M s () restoreServerStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStats where restoreStats f = whenM (doesFileExist f) $ do @@ -785,9 +810,8 @@ restoreServerStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStat liftIO (strDecode <$> B.readFile f) >>= \case Right d@FileServerStatsData {_filesCount = statsFilesCount, _filesSize = statsFilesSize} -> do s <- asks serverStats - st <- asks fileStore - _filesCount <- liftIO $ getFileCount st - _filesSize <- readTVarIO =<< asks usedStorage + _filesCount <- readIORef $ filesCount s + _filesSize <- readIORef $ filesSize s liftIO $ setFileServerStats s d {_filesCount, _filesSize} renameFile f $ f <> ".bak" logNote "server stats restored" diff --git a/src/Simplex/FileTransfer/Server/Env.hs b/src/Simplex/FileTransfer/Server/Env.hs index 679e3f8cc..1f95fd0e7 100644 --- a/src/Simplex/FileTransfer/Server/Env.hs +++ b/src/Simplex/FileTransfer/Server/Env.hs @@ -22,11 +22,14 @@ module Simplex.FileTransfer.Server.Env fileStore, fromFileStore, defaultInactiveClientExpiration, + defaultXFTPKeepAlive, + defaultXFTPUserTimeout, defFileExpirationHours, defaultFileExpiration, newXFTPServerEnv, readFileStoreType, runWithStoreConfig, + migrateFileStore, checkFileStoreMode, importToDatabase, exportFromDatabase, @@ -73,7 +76,8 @@ import Simplex.Messaging.Server.Information (ServerPublicInfo) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport (EntitlementConfig (..)) -import Simplex.Messaging.Transport.Server (ReloadableCredential, ServerCredentials (..), TransportServerConfig (..), acceptCredential, loadFingerprint, loadServerCredential, newReloadableCredential) +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts (..)) +import Simplex.Messaging.Transport.Server (ReloadableCredential, ServerCredentials (..), SocketState, TransportServerConfig (..), acceptCredential, loadFingerprint, loadServerCredential, newReloadableCredential, newSocketState) import Simplex.Messaging.Util (tshow) import System.IO (IOMode (..)) import UnliftIO.STM @@ -130,6 +134,17 @@ defaultInactiveClientExpiration = checkInterval = 3600 -- seconds, 1 hours } +defaultXFTPKeepAlive :: KeepAliveOpts +defaultXFTPKeepAlive = + KeepAliveOpts + { keepIdle = 60, + keepIntvl = 10, + keepCnt = 6 + } + +defaultXFTPUserTimeout :: Int +defaultXFTPUserTimeout = 180000 + data XFTPEnv s = XFTPEnv { config :: XFTPServerConfig s, store :: FileStore s, @@ -140,7 +155,8 @@ data XFTPEnv s = XFTPEnv serverIdentity :: C.KeyHash, tlsServerCreds :: T.Credential, httpServerCreds :: Maybe ReloadableCredential, - serverStats :: FileServerStats + serverStats :: FileServerStats, + sockets :: SocketState } fileStore :: XFTPEnv s -> s @@ -205,7 +221,7 @@ newXFTPServerEnv config@XFTPServerConfig {serverStoreCfg, fileSizeQuota, fileExp st <- newFileStore dbCfg pure (StoreDatabase st, Nothing) #endif - used <- getUsedStorage (fromFileStore store) + (storedCount, used) <- getUsedStorage (fromFileStore store) usedStorage <- newTVarIO used uploadingFiles <- TM.emptyIO forM_ fileSizeQuota $ \quota -> do @@ -214,8 +230,9 @@ newXFTPServerEnv config@XFTPServerConfig {serverStoreCfg, fileSizeQuota, fileExp tlsServerCreds <- loadServerCredential xftpCredentials httpServerCreds <- forM httpCredentials $ \creds -> newReloadableCredential acceptCredential creds =<< loadServerCredential creds Fingerprint fp <- loadFingerprint xftpCredentials - serverStats <- newFileServerStats =<< getCurrentTime - pure XFTPEnv {config, store, usedStorage, uploadingFiles, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats} + serverStats <- newFileServerStats storedCount used =<< getCurrentTime + sockets <- newSocketState + pure XFTPEnv {config, store, usedStorage, uploadingFiles, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats, sockets} data XFTPRequest = XFTPReqNew FileInfo (NonEmpty RcvPublicAuthKey) (Maybe BasicAuth) (Maybe Word32) @@ -252,6 +269,13 @@ runWithStoreConfig (AFSType SFSPostgres) ini storeLogFilePath confirmMigrations error "server binary is compiled without support for PostgreSQL database" #endif +migrateFileStore :: XFTPStoreConfig s -> IO () +migrateFileStore = \case + XSCMemory _ -> pure () +#if defined(dbServerPostgres) + XSCDatabase dbCfg -> (newFileStore dbCfg :: IO PostgresFileStore) >>= closeFileStore +#endif + -- | Validate startup config when store_files=database. checkFileStoreMode :: Ini -> AFStoreType -> FilePath -> IO () checkFileStoreMode ini (AFSType SFSPostgres) storeLogFilePath = do diff --git a/src/Simplex/FileTransfer/Server/Main.hs b/src/Simplex/FileTransfer/Server/Main.hs index 18b6a620c..d1d78d12d 100644 --- a/src/Simplex/FileTransfer/Server/Main.hs +++ b/src/Simplex/FileTransfer/Server/Main.hs @@ -32,7 +32,7 @@ import Options.Applicative import Simplex.FileTransfer.Chunks import Simplex.FileTransfer.Description (FileSize (..)) import Simplex.FileTransfer.Server (runXFTPServer) -import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig, AFStoreType (..), defFileExpirationHours, defaultFileExpiration, defaultInactiveClientExpiration, readFileStoreType, runWithStoreConfig, checkFileStoreMode, importToDatabase, exportFromDatabase) +import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig, AFStoreType (..), defFileExpirationHours, defaultFileExpiration, defaultInactiveClientExpiration, defaultXFTPKeepAlive, defaultXFTPUserTimeout, readFileStoreType, runWithStoreConfig, migrateFileStore, checkFileStoreMode, importToDatabase, exportFromDatabase) import Simplex.FileTransfer.Transport (alpnSupportedXFTPhandshakes, supportedFileServerVRange) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Entitlement (entitlementIssuerKeys) @@ -50,6 +50,7 @@ import Simplex.Messaging.Transport.HTTP2 (httpALPN) import Simplex.Messaging.Transport.Server (ServerCredentials (..), TransportServerConfig (..), acceptCredential, defaultCredentialCheckInterval, mkTransportServerConfig) import Simplex.Messaging.Util (eitherToMaybe, safeDecodeUtf8, tshow) import System.Directory (createDirectoryIfMissing, doesFileExist) +import System.Exit (exitSuccess) import System.FilePath (combine) import System.IO (BufferMode (..), hSetBuffering, stderr, stdout) import Text.Read (readMaybe) @@ -201,9 +202,9 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do <> "\n\ \[INACTIVE_CLIENTS]\n\ \# TTL and interval to check inactive clients\n\ - \disconnect = off\n" - <> ("# ttl = " <> tshow (ttl defaultInactiveClientExpiration) <> "\n") - <> ("# check_interval = " <> tshow (checkInterval defaultInactiveClientExpiration) <> "\n") + \disconnect = on\n" + <> ("ttl = " <> tshow (ttl defaultInactiveClientExpiration) <> "\n") + <> ("check_interval = " <> tshow (checkInterval defaultInactiveClientExpiration) <> "\n") <> "\n\ \[WEB]\n\ \# Set path to generate static mini-site for server information\n" @@ -213,7 +214,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do \# TLS credentials for HTTPS web server on the same port as XFTP.\n\ \# cert = " <> T.pack (cfgPath `combine` "web.crt") <> "\n\ \# key = " <> T.pack (cfgPath `combine` "web.key") <> "\n" - runServer StartOptions {confirmMigrations} ini = do + runServer StartOptions {maintenance, confirmMigrations} ini = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering fp <- checkSavedFingerprint cfgPath defaultX509Config @@ -228,6 +229,10 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do Right fsType -> do checkFileStoreMode ini fsType storeLogFilePath runWithStoreConfig fsType ini storeLogFilePath confirmMigrations $ \storeCfg -> do + when maintenance $ do + migrateFileStore storeCfg + putStrLn "Server started in 'maintenance' mode, exiting" + exitSuccess let cfg = serverConfig storeCfg printXFTPConfig cfg case webStaticPath' of @@ -331,7 +336,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do (fromMaybe False $ iniOnOff "TRANSPORT" "log_tls_errors" ini) (Just $ alpnSupportedXFTPhandshakes <> httpALPN) False - in cfg {addCORSHeaders = isJust httpCredentials_}, + in cfg {addCORSHeaders = isJust httpCredentials_, tcpKeepAlive = Just defaultXFTPKeepAlive, tcpUserTimeout = Just defaultXFTPUserTimeout}, responseDelay = 0, webStaticPath = webStaticPath' } @@ -345,8 +350,9 @@ data CliCommand data StoreCmd = SCImport | SCExport -newtype StartOptions = StartOptions - { confirmMigrations :: MigrationConfirmation +data StartOptions = StartOptions + { maintenance :: Bool, + confirmMigrations :: MigrationConfirmation } data InitOptions = InitOptions @@ -435,6 +441,12 @@ cliCommandP cfgPath logPath iniFile = pure InitOptions {enableStoreLog, signAlgorithm, ip, fqdn, filesPath, fileSizeQuota, webStaticPath} startOptsP :: Parser StartOptions startOptsP = do + maintenance <- + switch + ( long "maintenance" + <> short 'm' + <> help "Do not start the server, only apply database migrations" + ) confirmMigrations <- option parseConfirmMigrations @@ -443,7 +455,7 @@ cliCommandP cfgPath logPath iniFile = <> help "Confirm PostgreSQL database migration: up, down (default is manual confirmation)" <> value MCConsole ) - pure StartOptions {confirmMigrations} + pure StartOptions {maintenance, confirmMigrations} storeCmdP :: Parser StoreCmd storeCmdP = hsubparser diff --git a/src/Simplex/FileTransfer/Server/Prometheus.hs b/src/Simplex/FileTransfer/Server/Prometheus.hs index f30525822..987d20766 100644 --- a/src/Simplex/FileTransfer/Server/Prometheus.hs +++ b/src/Simplex/FileTransfer/Server/Prometheus.hs @@ -16,14 +16,17 @@ import qualified Data.Text as T import Data.Time.Clock (UTCTime (..), diffUTCTime) import Data.Time.Clock.System (systemEpochDay) import Data.Time.Format.ISO8601 (iso8601Show) +import Network.Socket (ServiceName) import Simplex.FileTransfer.Server.Stats import Simplex.Messaging.Server.Stats (PeriodStatCounts (..)) import Simplex.Messaging.Transport (simplexMQVersion) +import Simplex.Messaging.Transport.Server (SocketStats (..)) import Simplex.Messaging.Util (tshow) data FileServerMetrics = FileServerMetrics { statsData :: FileServerStatsData, filesDownloadedPeriods :: PeriodStatCounts, + socketStats :: (ServiceName, SocketStats), rtsOptions :: Text } @@ -35,7 +38,7 @@ xftpPrometheusMetrics :: FileServerMetrics -> UTCTime -> Text xftpPrometheusMetrics sm ts = time <> files <> info where - FileServerMetrics {statsData, filesDownloadedPeriods, rtsOptions} = sm + FileServerMetrics {statsData, filesDownloadedPeriods, socketStats = (port, sockets), rtsOptions} = sm FileServerStatsData { _fromTime, _filesCreated, @@ -87,7 +90,7 @@ xftpPrometheusMetrics sm ts = \simplex_xftp_files_blocked " <> mshow _filesBlocked <> "\n\ \# filesBlocked\n\ \\n\ - \# HELP simplex_xftp_file_downloads File downloads\n\ + \# HELP simplex_xftp_file_downloads Started file downloads\n\ \# TYPE simplex_xftp_file_downloads counter\n\ \simplex_xftp_file_downloads " <> mshow _fileDownloads <> "\n\ \# fileDownloads\n\ @@ -97,27 +100,27 @@ xftpPrometheusMetrics sm ts = \simplex_xftp_file_download_acks " <> mshow _fileDownloadAcks <> "\n\ \# fileDownloadAcks\n\ \\n\ - \# HELP simplex_xftp_files_count_total Total files count \n\ + \# HELP simplex_xftp_files_count_total Stored files\n\ \# TYPE simplex_xftp_files_count_total gauge\n\ \simplex_xftp_files_count_total " <> mshow _filesCount <> "\n\ \# filesCount\n\ \\n\ - \# HELP simplex_xftp_files_size Size of files \n\ + \# HELP simplex_xftp_files_size Size of stored files, bytes\n\ \# TYPE simplex_xftp_files_size gauge\n\ \simplex_xftp_files_size " <> mshow _filesSize <> "\n\ \# filesSize \n\ \\n\ - \# HELP simplex_xftp_files_count_daily Daily files count\n\ + \# HELP simplex_xftp_files_count_daily Distinct files downloaded in the current day\n\ \# TYPE simplex_xftp_files_count_daily gauge\n\ \simplex_xftp_files_count_daily " <> mstr (dayCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.dayCount\n\ \\n\ - \# HELP simplex_xftp_files_count_weekly Weekly files count\n\ + \# HELP simplex_xftp_files_count_weekly Distinct files downloaded in the current week\n\ \# TYPE simplex_xftp_files_count_weekly gauge\n\ \simplex_xftp_files_count_weekly " <> mstr (weekCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.weekCount\n\ \\n\ - \# HELP simplex_xftp_files_count_monthly Monthly files count\n\ + \# HELP simplex_xftp_files_count_monthly Distinct files downloaded in the current month\n\ \# TYPE simplex_xftp_files_count_monthly gauge\n\ \simplex_xftp_files_count_monthly " <> mstr (monthCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.monthCount\n\ @@ -130,6 +133,16 @@ xftpPrometheusMetrics sm ts = \# TYPE simplex_xftp_info gauge\n\ \simplex_xftp_info{version=\"" <> T.pack simplexMQVersion <> "\",rts_options=\"" <> rtsOptions <> "\"} 1\n\ \\n" + <> socketsMetric socketsAccepted "simplex_xftp_sockets_accepted" "Accepted sockets" + <> socketsMetric socketsClosed "simplex_xftp_sockets_closed" "Closed sockets" + <> socketsMetric socketsActive "simplex_xftp_sockets_active" "Active sockets" + <> socketsMetric socketsLeaked "simplex_xftp_sockets_leaked" "Leaked sockets" + socketsMetric :: (SocketStats -> Int) -> Text -> Text -> Text + socketsMetric sel metric descr = + "# HELP " <> metric <> " " <> descr <> "\n" + <> "# TYPE " <> metric <> " gauge\n" + <> metric <> "{port=\"" <> T.pack port <> "\"} " <> mshow (sel sockets) <> "\n" + <> "\n" mstr a = a <> " " <> tsEpoch mshow :: Show a => a -> Text mshow = mstr . tshow diff --git a/src/Simplex/FileTransfer/Server/Stats.hs b/src/Simplex/FileTransfer/Server/Stats.hs index 619413839..9e7f8ec31 100644 --- a/src/Simplex/FileTransfer/Server/Stats.hs +++ b/src/Simplex/FileTransfer/Server/Stats.hs @@ -50,8 +50,8 @@ data FileServerStatsData = FileServerStatsData } deriving (Show) -newFileServerStats :: UTCTime -> IO FileServerStats -newFileServerStats ts = do +newFileServerStats :: Int -> Int64 -> UTCTime -> IO FileServerStats +newFileServerStats storedCount storedSize ts = do fromTime <- newIORef ts filesCreated <- newIORef 0 fileRecipients <- newIORef 0 @@ -62,8 +62,8 @@ newFileServerStats ts = do filesDownloaded <- newPeriodStats fileDownloads <- newIORef 0 fileDownloadAcks <- newIORef 0 - filesCount <- newIORef 0 - filesSize <- newIORef 0 + filesCount <- newIORef storedCount + filesSize <- newIORef storedSize pure FileServerStats {fromTime, filesCreated, fileRecipients, filesUploaded, filesExpired, filesDeleted, filesBlocked, filesDownloaded, fileDownloads, fileDownloadAcks, filesCount, filesSize} getFileServerStatsData :: FileServerStats -> IO FileServerStatsData diff --git a/src/Simplex/FileTransfer/Server/Store.hs b/src/Simplex/FileTransfer/Server/Store.hs index 2a8bb9287..fc37296da 100644 --- a/src/Simplex/FileTransfer/Server/Store.hs +++ b/src/Simplex/FileTransfer/Server/Store.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} @@ -26,6 +27,8 @@ import Control.Monad import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Either (rights) import Data.Int (Int64) +import Data.List.NonEmpty (NonEmpty) +import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, isJust) import Data.Set (Set) @@ -42,7 +45,7 @@ import System.IO (IOMode (..)) import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (ifM) +import Simplex.Messaging.Util (anyM, ifM) data FSType = FSMemory | FSPostgres @@ -78,16 +81,15 @@ class FileStoreClass s where closeFileStore :: s -> IO () addFile :: s -> SenderId -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> IO (Either XFTPErrorType ()) setFilePath :: s -> SenderId -> FilePath -> IO (Either XFTPErrorType ()) - addRecipient :: s -> SenderId -> FileRecipient -> IO (Either XFTPErrorType ()) + addRecipients :: s -> SenderId -> NonEmpty FileRecipient -> IO (Either XFTPErrorType ()) deleteFile :: s -> SenderId -> IO (Either XFTPErrorType (Maybe FilePath)) - deleteFiles :: s -> [SenderId] -> IO [(SenderId, Maybe FilePath)] - deleteFiles s = fmap rights . mapM (\sId -> fmap (sId,) <$> deleteFile s sId) - blockFile :: s -> SenderId -> BlockingInfo -> Bool -> IO (Either XFTPErrorType (Maybe FilePath)) + deleteFiles :: s -> [SenderId] -> IO [(SenderId, Maybe FilePath, Word32)] + blockFile :: s -> SenderId -> BlockingInfo -> IO (Either XFTPErrorType (Maybe FilePath)) deleteRecipient :: s -> RecipientId -> FileRec -> IO () getFile :: s -> SFileParty p -> XFTPFileId -> IO (Either XFTPErrorType (FileRec, C.APublicAuthKey)) ackFile :: s -> RecipientId -> IO (Either XFTPErrorType ()) expiredFiles :: s -> SystemSeconds -> Int64 -> Int -> IO [(SenderId, Maybe FilePath, Word32)] - getUsedStorage :: s -> IO Int64 + getUsedStorage :: s -> IO (Int, Int64) getFileCount :: s -> IO Int -- STM in-memory store @@ -126,28 +128,31 @@ instance FileStoreClass STMFileStore where pure $ Right () _ -> pure $ Left AUTH - addRecipient st@STMFileStore {recipients} senderId (FileRecipient rId rKey) = atomically $ + addRecipients st@STMFileStore {recipients} senderId rcps = atomically $ withFile st senderId $ \FileRec {recipientIds} -> do rIds <- readTVar recipientIds - mem <- TM.member rId recipients - if rId `S.member` rIds || mem + let newIds = map (\(FileRecipient rId _) -> rId) $ L.toList rcps + newIdSet = S.fromList newIds + stored <- anyM $ map (`TM.member` recipients) newIds + if S.size newIdSet /= length newIds || not (S.disjoint newIdSet rIds) || stored then pure $ Left DUPLICATE_ else do - writeTVar recipientIds $! S.insert rId rIds - TM.insert rId (senderId, rKey) recipients + writeTVar recipientIds $! S.union newIdSet rIds + forM_ rcps $ \(FileRecipient rId rKey) -> TM.insert rId (senderId, rKey) recipients pure $ Right () - deleteFile STMFileStore {files, recipients} senderId = atomically $ do - TM.lookupDelete senderId files >>= \case - Just FileRec {recipientIds, filePath} -> do - readTVar recipientIds >>= mapM_ (`TM.delete` recipients) - Right <$> readTVar filePath - _ -> pure $ Left AUTH + deleteFile st senderId = atomically $ deleteFileRec st senderId >>= maybe (pure $ Left AUTH) (fmap Right . readTVar . filePath) + + deleteFiles st = fmap catMaybes . mapM (atomically . deleteFileSize) + where + deleteFileSize sId = + deleteFileRec st sId >>= mapM (\FileRec {fileInfo = FileInfo {size}, filePath} -> (sId,,size) <$> readTVar filePath) - blockFile st senderId info _deleted = atomically $ - withFile st senderId $ \FileRec {fileStatus, filePath} -> do + blockFile st senderId info = atomically $ + withFile st senderId $ \FileRec {filePath, fileStatus} -> do + path <- swapTVar filePath Nothing writeTVar fileStatus $! EntityBlocked info - Right <$> swapTVar filePath Nothing + pure $ Right path deleteRecipient STMFileStore {recipients} rId FileRec {recipientIds} = atomically $ do TM.delete rId recipients @@ -180,15 +185,19 @@ instance FileStoreClass STMFileStore where pure $ Just (sId, path, size) else pure Nothing - getUsedStorage STMFileStore {files} = foldM addSize 0 =<< readTVarIO files + getUsedStorage STMFileStore {files} = foldM addSize (0, 0) =<< readTVarIO files where - addSize acc FileRec {fileInfo = FileInfo {size}, filePath} = - ifM (isJust <$> readTVarIO filePath) (pure $! acc + fromIntegral size) (pure acc) + addSize acc@(!n, !used) FileRec {fileInfo = FileInfo {size}, filePath} = + ifM (isJust <$> readTVarIO filePath) (pure (n + 1, used + fromIntegral size)) (pure acc) getFileCount STMFileStore {files} = M.size <$> readTVarIO files -- Internal STM helpers +deleteFileRec :: STMFileStore -> SenderId -> STM (Maybe FileRec) +deleteFileRec STMFileStore {files, recipients} senderId = + TM.lookupDelete senderId files >>= mapM (\fr@FileRec {recipientIds} -> fr <$ (readTVar recipientIds >>= mapM_ (`TM.delete` recipients))) + newFileRec :: SenderId -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> STM FileRec newFileRec senderId fileInfo createdAt expiresAt status = do recipientIds <- newTVar S.empty diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index 7c48b13f4..027793729 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -100,16 +100,16 @@ instance FileStoreClass PostgresFileStore where DB.execute db "UPDATE files SET file_path = ? WHERE sender_id = ? AND file_path IS NULL AND status = 'active'" (fPath, sId) withLog "setFilePath" st $ \s -> logPutFile s sId fPath - addRecipient st senderId (FileRecipient rId rKey) = E.uninterruptibleMask_ $ runExceptT $ do - void $ withDB "addRecipient" st $ \db -> + addRecipients st senderId rcps = E.uninterruptibleMask_ $ runExceptT $ do + void $ withDB "addRecipients" st $ \db -> E.try - ( DB.execute + ( DB.executeMany db "INSERT INTO recipients (recipient_id, sender_id, recipient_key) VALUES (?,?,?)" - (rId, senderId, Binary (C.encodePubKey rKey)) + (map (\(FileRecipient rId rKey) -> (rId, senderId, Binary (C.encodePubKey rKey))) $ L.toList rcps) ) >>= either handleDuplicate (pure . Right) - withLog "addRecipient" st $ \s -> logAddRecipients s senderId (pure $ FileRecipient rId rKey) + withLog "addRecipients" st $ \s -> logAddRecipients s senderId rcps deleteFile st sId = E.uninterruptibleMask_ $ runExceptT $ do path <- withDB "deleteFile" st $ \db -> @@ -118,18 +118,15 @@ instance FileStoreClass PostgresFileStore where pure path deleteFiles st sIds = E.uninterruptibleMask_ $ do - deleted <- withTransaction (dbStore st) $ \db -> - DB.query db "DELETE FROM files WHERE sender_id IN ? RETURNING sender_id, file_path" (Only (In sIds)) - withLog "deleteFiles" st $ \s -> mapM_ (logDeleteFile s . fst) deleted + deleted <- fmap toFileSizes $ withTransaction (dbStore st) $ \db -> + DB.query db "DELETE FROM files WHERE sender_id IN ? RETURNING sender_id, file_path, file_size" (Only (In sIds)) + withLog "deleteFiles" st $ \s -> mapM_ (\(sId, _, _) -> logDeleteFile s sId) deleted pure deleted - blockFile st sId info _deleted = E.uninterruptibleMask_ $ runExceptT $ do + blockFile st sId info = E.uninterruptibleMask_ $ runExceptT $ do path <- withDB "blockFile" st $ \db -> - firstRow fromOnly AUTH $ - DB.query - db - "UPDATE files f SET status = ?, file_path = NULL FROM (SELECT file_path FROM files WHERE sender_id = ? FOR NO KEY UPDATE) old WHERE f.sender_id = ? RETURNING old.file_path" - (EntityBlocked info, sId, sId) + firstRow fromOnly AUTH (DB.query db "SELECT file_path FROM files WHERE sender_id = ? FOR UPDATE" (Only sId)) + >>= mapM (\p -> p <$ DB.execute db "UPDATE files SET status = ?, file_path = NULL WHERE sender_id = ?" (EntityBlocked info, sId)) withLog "blockFile" st $ \s -> logBlockFile s sId info pure path @@ -161,19 +158,16 @@ instance FileStoreClass PostgresFileStore where withLog "ackFile" st $ \s -> logAckFile s rId expiredFiles st now old limit = - fmap toResult $ withTransaction (dbStore st) $ \db -> + fmap toFileSizes $ withTransaction (dbStore st) $ \db -> DB.query db - "(SELECT sender_id, file_path, file_size FROM files WHERE expires_at < ? LIMIT ?) UNION ALL (SELECT sender_id, file_path, file_size FROM files WHERE expires_at IS NULL AND created_at < ? LIMIT ?)" - (roundedSeconds now, limit, old - fileTimePrecision, limit) - where - toResult :: [(SenderId, Maybe FilePath, Int32)] -> [(SenderId, Maybe FilePath, Word32)] - toResult = map (\(sId, path, size) -> (sId, path, fromIntegral size)) + "SELECT sender_id, file_path, file_size FROM ((SELECT sender_id, file_path, file_size FROM files WHERE expires_at < ? LIMIT ?) UNION ALL (SELECT sender_id, file_path, file_size FROM files WHERE expires_at IS NULL AND created_at < ? LIMIT ?)) expired LIMIT ?" + (roundedSeconds now, limit, old - fileTimePrecision, limit, limit) getUsedStorage st = withTransaction (dbStore st) $ \db -> do - [Only total] <- DB.query_ db "SELECT COALESCE(SUM(file_size::BIGINT), 0)::BIGINT FROM files WHERE file_path IS NOT NULL" - pure total + [(count, total)] <- DB.query_ db "SELECT COUNT(*), COALESCE(SUM(file_size::BIGINT), 0)::BIGINT FROM files WHERE file_path IS NOT NULL" + pure (fromIntegral (count :: Int64), total) getFileCount st = withTransaction (dbStore st) $ \db -> do @@ -182,6 +176,9 @@ instance FileStoreClass PostgresFileStore where -- Internal helpers +toFileSizes :: [(SenderId, Maybe FilePath, Int32)] -> [(SenderId, Maybe FilePath, Word32)] +toFileSizes = map (\(sId, path, size) -> (sId, path, fromIntegral size)) + mkFileRec :: SenderId -> FileInfo -> Maybe FilePath -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> IO FileRec mkFileRec senderId fileInfo path createdAt expiresAt status = do filePath <- newTVarIO path diff --git a/src/Simplex/FileTransfer/Server/StoreLog.hs b/src/Simplex/FileTransfer/Server/StoreLog.hs index 29ab0d8b0..82479f2b5 100644 --- a/src/Simplex/FileTransfer/Server/StoreLog.hs +++ b/src/Simplex/FileTransfer/Server/StoreLog.hs @@ -125,11 +125,10 @@ readFileStore f st = mapM_ (addFileLogRecord . LB.toStrict) . LB.lines =<< LB.re PutFile qId path | takeFileName path == serverFileName qId -> setFilePath st qId path | otherwise -> pure $ Left AUTH - AddRecipients sId rcps -> runExceptT $ addRecipients sId rcps + AddRecipients sId rcps -> addRecipients st sId rcps DeleteFile sId -> void <$> deleteFile st sId - BlockFile sId info -> void <$> blockFile st sId info True + BlockFile sId info -> void <$> blockFile st sId info AckFile rId -> ackFile st rId - addRecipients sId rcps = mapM_ (ExceptT . addRecipient st sId) rcps writeFileStore :: StoreLog 'WriteMode -> STMFileStore -> IO () writeFileStore s STMFileStore {files, recipients} = do diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index 8619dcc16..1878dc7d2 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -45,6 +45,8 @@ import Control.Monad import Control.Monad.Except import Control.Monad.IO.Class import Control.Monad.Trans.Except +import Crypto.Hash (Context, hashFinalize, hashInit, hashUpdate) +import Crypto.Hash.Algorithms (SHA256) import qualified Data.Aeson.TH as J import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Bifunctor (first) @@ -52,8 +54,8 @@ import qualified Data.ByteArray as BA import Data.ByteString.Builder (Builder, byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B -import qualified Data.ByteString.Lazy.Char8 as LB import Data.Functor (($>)) +import Data.IORef (modifyIORef', newIORef, readIORef) import Data.Word (Word16, Word32) import Network.HTTP2.Client (HTTP2Error) import qualified Simplex.Messaging.Crypto as C @@ -195,13 +197,13 @@ sendEncFile h send = go go sbState sz = getFileChunk h sz >>= \ch -> do let (encCh, sbState') = LC.sbEncryptChunk sbState ch - send (byteString encCh) `E.catch` \(e :: E.SomeException) -> print e >> E.throwIO e + send (byteString encCh) `E.catch` \(e :: E.SomeException) -> logInfo ("sendEncFile: " <> tshow e) >> E.throwIO e go sbState' $ sz - fromIntegral (B.length ch) receiveFile :: (Int -> IO ByteString) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E.catches` handlers where - receive h sz = hReceiveFile getBody h sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE + receive write sz = receiveFileBlocks getBody write sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO @@ -212,14 +214,17 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receiveEncFile :: (Int -> IO ByteString) -> LC.SbState -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveEncFile getBody = receiveFile_ . receive where - receive sbState h sz = first err <$> receiveSbFile getBody h sbState sz + receive sbState write sz = first err <$> receiveSbBlocks getBody write sbState sz err RFESize = SIZE err RFECrypto = CRYPTO data ReceiveFileError = RFESize | RFECrypto receiveSbFile :: (Int -> IO ByteString) -> Handle -> LC.SbState -> Word32 -> IO (Either ReceiveFileError ()) -receiveSbFile getBody h = receive +receiveSbFile getBody h = receiveSbBlocks getBody (B.hPut h) + +receiveSbBlocks :: (Int -> IO ByteString) -> (ByteString -> IO ()) -> LC.SbState -> Word32 -> IO (Either ReceiveFileError ()) +receiveSbBlocks getBody write = receive where receive sbState sz = do ch <- getBody fileBlockSize @@ -230,7 +235,7 @@ receiveSbFile getBody h = receive let (ch', rest) = B.splitAt (fromIntegral sz) ch (decCh, sbState') = LC.sbDecryptChunk sbState ch' sz' = sz - fromIntegral (B.length ch') - B.hPut h decCh + write decCh if sz' > 0 then receive sbState' sz' else do @@ -242,14 +247,16 @@ receiveSbFile getBody h = receive | otherwise -> pure $ Left RFESize authSz = fromIntegral C.authTagSize -receiveFile_ :: (Handle -> Word32 -> IO (Either XFTPErrorType ())) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () +receiveFile_ :: ((ByteString -> IO ()) -> Word32 -> IO (Either XFTPErrorType ())) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveFile_ receive XFTPRcvChunkSpec {filePath, chunkSize, chunkDigest} = do + hashCtx <- liftIO $ newIORef (hashInit :: Context SHA256) + let write h ch = B.hPut h ch >> modifyIORef' hashCtx (`hashUpdate` ch) #if __GLASGOW_HASKELL__ == 810 - ExceptT $ UE.bracket (openFile filePath WriteMode) hClose (`receive` chunkSize) + ExceptT $ UE.bracket (openFile filePath WriteMode) hClose $ \h -> receive (write h) chunkSize #else - ExceptT $ withFile filePath WriteMode (`receive` chunkSize) + ExceptT $ withFile filePath WriteMode $ \h -> receive (write h) chunkSize #endif - digest' <- liftIO $ LC.sha256Hash <$> LB.readFile filePath + digest' <- liftIO $ BA.convert . hashFinalize <$> readIORef hashCtx when (digest' /= chunkDigest) $ throwE DIGEST data XFTPErrorType diff --git a/src/Simplex/Messaging/Transport/HTTP2/File.hs b/src/Simplex/Messaging/Transport/HTTP2/File.hs index 8e65c1cc3..e35476529 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/File.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/File.hs @@ -2,7 +2,7 @@ module Simplex.Messaging.Transport.HTTP2.File ( fileBlockSize, - hReceiveFile, + receiveFileBlocks, hSendFile, getFileChunk, ) where @@ -18,16 +18,16 @@ import System.IO (Handle) fileBlockSize :: Int fileBlockSize = 16384 -hReceiveFile :: (Int -> IO ByteString) -> Handle -> Word32 -> IO Int64 -hReceiveFile _ _ 0 = pure 0 -hReceiveFile getBody h size = get $ fromIntegral size +receiveFileBlocks :: (Int -> IO ByteString) -> (ByteString -> IO ()) -> Word32 -> IO Int64 +receiveFileBlocks _ _ 0 = pure 0 +receiveFileBlocks getBody write size = get $ fromIntegral size where get sz = do ch <- getBody fileBlockSize let chSize = fromIntegral $ B.length ch if | chSize > sz -> pure (chSize - sz) - | chSize > 0 -> B.hPut h ch >> get (sz - chSize) + | chSize > 0 -> write ch >> get (sz - chSize) | otherwise -> pure (-sz) hSendFile :: Handle -> (Builder -> IO ()) -> Word32 -> IO () diff --git a/src/Simplex/Messaging/Transport/HTTP2/Server.hs b/src/Simplex/Messaging/Transport/HTTP2/Server.hs index 23a99e43c..704f3b21f 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/Server.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/Server.hs @@ -6,7 +6,8 @@ module Simplex.Messaging.Transport.HTTP2.Server where import Control.Concurrent.Async (Async, async, uninterruptibleCancel) import Control.Concurrent.STM import Control.Monad -import Data.Time.Clock.System (getSystemTime, systemSeconds) +import Data.Maybe (catMaybes) +import Data.Time.Clock.System (SystemTime, getSystemTime, systemSeconds) import Network.HPACK (BufferSize) import Network.HTTP2.Server (Request, Response) import qualified Network.HTTP2.Server as H @@ -16,10 +17,10 @@ import Numeric.Natural (Natural) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Transport (ALPN, SessionId, TLS, tlsALPN, tlsUniq) import Simplex.Messaging.Transport.HTTP2 -import Simplex.Messaging.Transport.Server (ReloadableCredential, SNICredentialUsed, ServerCredentials, TLSServerCredential (..), TransportServerConfig (..), loadServerCredential, newSocketState, runTransportServerState_) -import Simplex.Messaging.Util (threadDelay') -import UnliftIO (finally) -import UnliftIO.Concurrent (forkIO, killThread, myThreadId) +import Simplex.Messaging.Transport.Server (ReloadableCredential, SNICredentialUsed, ServerCredentials, SocketState, TLSServerCredential (..), TransportServerConfig (..), loadServerCredential, newSocketState, runTransportServerState_) +import Simplex.Messaging.Util (threadDelay', unlessM) +import UnliftIO (bracket_, finally) +import UnliftIO.Concurrent (forkIO, killThread, myThreadId, threadDelay) type HTTP2ServerFunc = SessionId -> Maybe ALPN -> Request -> (Response -> IO ()) -> IO () @@ -54,7 +55,7 @@ getHTTP2Server HTTP2ServerConfig {qSize, http2Port, bufferSize, bodyHeadSize, se started <- newEmptyTMVarIO reqQ <- newTBQueueIO qSize action <- async $ - runHTTP2Server started http2Port bufferSize serverSupported srvCreds Nothing transportConfig Nothing (const $ pure ()) $ \_sniUsed sessionId sessionALPN r sendResponse -> do + newSocketState >>= \ss -> runHTTP2Server ss started http2Port bufferSize serverSupported srvCreds Nothing transportConfig Nothing (const $ pure ()) $ \_sniUsed _closeSession sessionId sessionALPN r sendResponse -> do reqBody <- getHTTP2Body r bodyHeadSize atomically $ writeTBQueue reqQ HTTP2Request {sessionId, sessionALPN, request = r, reqBody, sendResponse} void . atomically $ takeTMVar started @@ -63,11 +64,10 @@ getHTTP2Server HTTP2ServerConfig {qSize, http2Port, bufferSize, bodyHeadSize, se closeHTTP2Server :: HTTP2Server -> IO () closeHTTP2Server = uninterruptibleCancel . action -runHTTP2Server :: TMVar Bool -> ServiceName -> BufferSize -> T.Supported -> T.Credential -> Maybe ReloadableCredential -> TransportServerConfig -> Maybe ExpirationConfig -> (SessionId -> IO ()) -> (SNICredentialUsed -> HTTP2ServerFunc) -> IO () -runHTTP2Server started port bufferSize srvSupported srvCreds httpCreds_ transportConfig expCfg_ clientFinished = runHTTP2ServerWith_ expCfg_ clientFinished bufferSize setup +runHTTP2Server :: SocketState -> TMVar Bool -> ServiceName -> BufferSize -> T.Supported -> T.Credential -> Maybe ReloadableCredential -> TransportServerConfig -> Maybe ExpirationConfig -> (SessionId -> IO ()) -> (SNICredentialUsed -> IO () -> HTTP2ServerFunc) -> IO () +runHTTP2Server ss started port bufferSize srvSupported srvCreds httpCreds_ transportConfig expCfg_ clientFinished = runHTTP2ServerWith_ expCfg_ (Just $ firstRequestTimeout transportConfig) clientFinished bufferSize setup where setup handler = do - ss <- newSocketState let combinedCreds = TLSServerCredential {credential = srvCreds, sniCredential = httpCreds_} runTransportServerState_ ss started port srvSupported combinedCreds transportConfig $ \_ -> handler @@ -75,28 +75,53 @@ runHTTP2Server started port bufferSize srvSupported srvCreds httpCreds_ transpor runHTTP2ServerWith :: BufferSize -> ((TLS p -> IO ()) -> a) -> HTTP2ServerFunc -> a runHTTP2ServerWith bufferSize tlsSetup http2Server = runHTTP2ServerWith_ + Nothing Nothing (\_sessId -> pure ()) bufferSize (\handler -> tlsSetup $ \tls -> handler (False, tls)) - (const http2Server) + (\_ _ -> http2Server) -runHTTP2ServerWith_ :: Maybe ExpirationConfig -> (SessionId -> IO ()) -> BufferSize -> (((SNICredentialUsed, TLS p) -> IO ()) -> a) -> (SNICredentialUsed -> HTTP2ServerFunc) -> a -runHTTP2ServerWith_ expCfg_ clientFinished bufferSize setup http2Server = setup $ \(sniUsed, tls) -> do - activeAt <- newTVarIO =<< getSystemTime +runHTTP2ServerWith_ :: Maybe ExpirationConfig -> Maybe Int -> (SessionId -> IO ()) -> BufferSize -> (((SNICredentialUsed, TLS p) -> IO ()) -> a) -> (SNICredentialUsed -> IO () -> HTTP2ServerFunc) -> a +runHTTP2ServerWith_ expCfg_ firstRequestTimeout_ clientFinished bufferSize setup http2Server = setup $ \(sniUsed, tls) -> do + activity <- newClientActivity sessionThread <- myThreadId - tid_ <- mapM (forkIO . expireInactiveClient sessionThread activeAt) expCfg_ - withHTTP2 bufferSize (run sniUsed tls activeAt) (clientFinished $ tlsUniq tls) tls `finally` mapM_ killThread tid_ + tids <- + sequence $ + catMaybes + [ forkIO . expireInactiveClient sessionThread activity <$> expCfg_, + forkIO . closeWithoutRequest sessionThread activity <$> firstRequestTimeout_ + ] + withHTTP2 bufferSize (run sniUsed tls sessionThread activity) (clientFinished $ tlsUniq tls) tls `finally` mapM_ killThread tids where - run sniUsed tls activeAt cfg = H.run cfg $ \req _aux sendResp -> do - getSystemTime >>= atomically . writeTVar activeAt - http2Server sniUsed (tlsUniq tls) (tlsALPN tls) req (`sendResp` []) - expireInactiveClient sessionThread activeAt expCfg = loop + run sniUsed tls sessionThread activity cfg = H.run cfg $ \req _aux sendResp -> + trackRequest activity $ http2Server sniUsed (killThread sessionThread) (tlsUniq tls) (tlsALPN tls) req (`sendResp` []) + expireInactiveClient sessionThread ClientActivity {requestsInFlight, idleSince} expCfg = loop where loop = do threadDelay' $ checkInterval expCfg * 1000000 old <- expireBeforeEpoch expCfg - ts <- readTVarIO activeAt - if systemSeconds ts < old + (n, ts) <- atomically $ (,) <$> readTVar requestsInFlight <*> readTVar idleSince + if n == 0 && systemSeconds ts < old then killThread sessionThread else loop + closeWithoutRequest sessionThread ClientActivity {requestStarted} t = do + threadDelay t + unlessM (readTVarIO requestStarted) $ killThread sessionThread + +data ClientActivity = ClientActivity + { requestStarted :: TVar Bool, + requestsInFlight :: TVar Int, + idleSince :: TVar SystemTime + } + +newClientActivity :: IO ClientActivity +newClientActivity = ClientActivity <$> newTVarIO False <*> newTVarIO 0 <*> (newTVarIO =<< getSystemTime) + +trackRequest :: ClientActivity -> IO a -> IO a +trackRequest ClientActivity {requestStarted, requestsInFlight, idleSince} = bracket_ started ended + where + started = atomically $ writeTVar requestStarted True >> modifyTVar' requestsInFlight (+ 1) + ended = do + ts <- getSystemTime + atomically $ modifyTVar' requestsInFlight (subtract 1) >> writeTVar idleSince ts diff --git a/src/Simplex/Messaging/Transport/Server.hs b/src/Simplex/Messaging/Transport/Server.hs index 7915f64b3..29586cd92 100644 --- a/src/Simplex/Messaging/Transport/Server.hs +++ b/src/Simplex/Messaging/Transport/Server.hs @@ -73,8 +73,9 @@ import GHC.IO.Exception (IOException, ioe_errno) import Network.Socket import qualified Network.TLS as T import Simplex.Messaging.Transport +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts, setSocketKeepAlive) import Simplex.Messaging.Transport.Shared -import Simplex.Messaging.Util (catchAll_, labelMyThread, stateTVar', tshow, unlessM) +import Simplex.Messaging.Util (catchAll, catchAll_, labelMyThread, stateTVar', tshow, unlessM) import System.Exit (exitFailure) import System.IO.Error (tryIOError) import System.Mem.Weak (Weak, deRefWeak) @@ -90,6 +91,9 @@ data TransportServerConfig = TransportServerConfig addCORSHeaders :: Bool, tlsSetupTimeout :: Int, transportTimeout :: Int, + firstRequestTimeout :: Int, + tcpKeepAlive :: Maybe KeepAliveOpts, + tcpUserTimeout :: Maybe Int, credentialCheckInterval :: Int } deriving (Eq, Show) @@ -144,6 +148,9 @@ mkTransportServerConfig logTLSErrors serverALPN askClientCert = addCORSHeaders = False, tlsSetupTimeout = 60000000, transportTimeout = 40000000, + firstRequestTimeout = 60000000, + tcpKeepAlive = Nothing, + tcpUserTimeout = Nothing, credentialCheckInterval = defaultCredentialCheckInterval } @@ -179,6 +186,7 @@ runTransportServerSocket started getSocket threadLabel srvParams cfg server = do where tCfg = serverTransportConfig cfg setupTLS conn = do + setServerSocketOptions cfg conn tls <- connectTLS Nothing tCfg srvParams conn (False,) <$> getTransportConnection tCfg True (X.CertificateChain []) tls @@ -191,6 +199,7 @@ runTransportServerSocketState ss started getSocket threadLabel srvSupported srvC runServer = runTransportServerSocketState_ ss started getSocket threadLabel (tlsSetupTimeout cfg) setupTLS server tCfg = serverTransportConfig cfg setupTLS conn = do + setServerSocketOptions cfg conn sniUsed <- newTVarIO False let srvParams = supportedTLSServerParams srvSupported srvCreds sniUsed $ serverALPN cfg h <- setupTLS_ srvParams @@ -207,6 +216,12 @@ runTransportServerSocketState ss started getSocket threadLabel srvSupported srvC tls <- connectTLS Nothing tCfg srvParams conn getTransportConnection tCfg True (X.CertificateChain []) tls +setServerSocketOptions :: TransportServerConfig -> Socket -> IO () +setServerSocketOptions TransportServerConfig {tcpKeepAlive, tcpUserTimeout} conn = do + mapM_ (setSocketKeepAlive conn) tcpKeepAlive `catchAll` \e -> logError ("Error setting TCP keep-alive " <> tshow e) + when (isSupportedSocketOption UserTimeout) $ + mapM_ (setSocketOption conn UserTimeout) tcpUserTimeout `catchAll` \e -> logError ("Error setting TCP user timeout " <> tshow e) + -- | Run a transport server with provided connection setup and handler. runTransportServerSocketState_ :: Transport c => SocketState -> TMVar Bool -> IO Socket -> String -> Int -> (Socket -> IO (SNICredentialUsed, c 'TServer)) -> (Socket -> (SNICredentialUsed, c 'TServer) -> IO ()) -> IO () runTransportServerSocketState_ ss started getSocket threadLabel tlsSetupTimeout setupTLS server = do diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 8c14f642c..c06b7c44d 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -1222,7 +1222,6 @@ testAcceptContactStallingServer ps@(t, ASType qsType _) = timeout 1_000000 (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) `shouldReturn` Nothing where bServers = initAgentServers {smp = userServers [testSMPServer2]} - testDeleteAcceptedContactRequest :: (HasCallStack, HasTestEnv) => Bool -> Bool -> IO () testDeleteAcceptedContactRequest useDR asyncAccept = withAgentClients2 $ \alice bob -> runRight_ $ do @@ -3262,7 +3261,6 @@ unreferencedMsgBodies c = withTransaction (store $ agentEnv c) (`DB.query_` "SEL skippedMsgKeys :: AgentClient -> IO [(ConnId, Int64)] skippedMsgKeys c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, msg_n FROM skipped_messages") - getMsg :: AgentClient -> ConnId -> ExceptT AgentErrorType IO a -> ExceptT AgentErrorType IO a getMsg c cId action = do liftIO $ noMessages c "nothing should be delivered before GET" diff --git a/tests/CLITests.hs b/tests/CLITests.hs index 38fcb90cf..8cd711bfe 100644 --- a/tests/CLITests.hs +++ b/tests/CLITests.hs @@ -42,7 +42,7 @@ import System.Directory (doesFileExist) import System.Environment (withArgs) import System.Exit (ExitCode (..)) import System.FilePath (()) -import System.IO.Silently (capture_) +import System.IO.Silently (capture, capture_) import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Test.Main (ProcessResult (..), captureProcessResult, withStdin) @@ -57,6 +57,7 @@ import qualified Database.PostgreSQL.Simple as PSQL import Database.PostgreSQL.Simple.Types (Query (..)) import NtfClient (ntfTestServerDBConnectInfo, ntfTestServerDBConnstr, ntfTestServerDBOpts) import SMPClient (postgressBracket) +import XFTPClient (testXFTPDBConnectInfo) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Notifications.Server.Main #endif @@ -101,6 +102,12 @@ cliTests = do describe "XFTP server CLI" $ do it "should initialize, start and delete the server (no store log)" $ xftpServerTest False it "should initialize, start and delete the server (with store log)" $ xftpServerTest True + it "should exit in maintenance mode without starting the server" xftpServerMaintenanceTest +#if defined(dbServerPostgres) + around_ (postgressBracket testXFTPDBConnectInfo) $ + describe "XFTP server CLI with PostgreSQL" $ + it "should apply database migrations in maintenance mode" xftpServerMaintenanceDBTest +#endif describe "Static site on HTTPS port" $ do it "should serve the replaced web certificate with a 4096-bit RSA key without restart" testStaticSiteCertReload it "should throw the error of an invalid credential at start" testStaticSiteInvalidCredential @@ -324,17 +331,64 @@ ntfServerTest storeLog = do xftpServerTest :: HasTestEnv => Bool -> IO () xftpServerTest storeLog = do - capture_ (withArgs (["init", "-p", testDir, "-q", "10gb"] <> ["--disable-store-log" | not storeLog]) $ xftpServerCLI fileCfgPath fileLogPath) - >>= (`shouldSatisfy` (("Server initialized, you can modify configuration in " <> fileCfgPath <> "/file-server.ini") `isPrefixOf`)) + xftpServerInit storeLog Right ini <- readIniFile $ fileCfgPath <> "/file-server.ini" lookupValue "STORE_LOG" "enable" ini `shouldBe` Right (if storeLog then "on" else "off") lookupValue "STORE_LOG" "log_stats" ini `shouldBe` Right "off" lookupValue "TRANSPORT" "port" ini `shouldBe` Right "443" + lookupValue "INACTIVE_CLIENTS" "disconnect" ini `shouldBe` Right "on" + lookupValue "INACTIVE_CLIENTS" "ttl" ini `shouldBe` Right "21600" + lookupValue "INACTIVE_CLIENTS" "check_interval" ini `shouldBe` Right "3600" doesFileExist (fileCfgPath <> "/ca.key") `shouldReturn` True r <- lines <$> capture_ (withArgs ["start"] $ (100000 `timeout` xftpServerCLI fileCfgPath fileLogPath) `catchAll_` pure (Just ())) r `shouldContain` ["SimpleX XFTP server v" <> simplexmqVersionCommit] r `shouldContain` (if storeLog then ["Store log: " <> fileLogPath <> "/file-server-store.log"] else ["Store log disabled."]) r `shouldContain` ["Listening on port 443..."] + xftpServerDelete + +xftpMaintenanceMessage :: String +xftpMaintenanceMessage = "Server started in 'maintenance' mode, exiting" + +xftpServerInit :: HasTestEnv => Bool -> IO () +xftpServerInit storeLog = + capture_ (withArgs (["init", "-p", testDir, "-q", "10gb"] <> ["--disable-store-log" | not storeLog]) $ xftpServerCLI fileCfgPath fileLogPath) + >>= (`shouldSatisfy` (("Server initialized, you can modify configuration in " <> fileCfgPath <> "/file-server.ini") `isPrefixOf`)) + +xftpServerMaintenance :: HasTestEnv => [String] -> IO () +xftpServerMaintenance opts = do + (out, r) <- capture (withArgs (["start", "--maintenance"] <> opts) (5000000 `timeout` xftpServerCLI fileCfgPath fileLogPath) `catchAll_` pure (Just ())) + r `shouldBe` Just () + let ls = lines out + ls `shouldContain` [xftpMaintenanceMessage] + ls `shouldNotContain` ["Listening on port 443..."] + +xftpServerDelete :: HasTestEnv => IO () +xftpServerDelete = do capture_ (withStdin "Y" . withArgs ["delete"] $ xftpServerCLI fileCfgPath fileLogPath) >>= (`shouldSatisfy` ("WARNING: deleting the server will make all queues inaccessible" `isPrefixOf`)) - doesFileExist (cfgPath <> "/ca.key") `shouldReturn` False + doesFileExist (fileCfgPath <> "/ca.key") `shouldReturn` False + +xftpServerMaintenanceTest :: HasTestEnv => IO () +xftpServerMaintenanceTest = do + xftpServerInit False + xftpServerMaintenance [] + xftpServerDelete + +#if defined(dbServerPostgres) +xftpServerMaintenanceDBTest :: HasTestEnv => IO () +xftpServerMaintenanceDBTest = do + xftpServerInit False + let iniFile = fileCfgPath <> "/file-server.ini" + schema = "xftp_server_cli" + dbSettings = [("store_files", "database"), ("db_connection", "postgresql://test_xftp_server_user@/test_xftp_server_db"), ("db_schema", T.pack schema)] + setDB = (<> dbSettings) . filter ((/= "store_files") . fst) + Right ini <- readIniFile iniFile + writeIniFile iniFile ini {iniSections = HM.adjust setDB "STORE_LOG" (iniSections ini)} + db <- PSQL.connect testXFTPDBConnectInfo + void $ PSQL.execute_ db $ Query $ "CREATE SCHEMA " <> B.pack schema + xftpServerMaintenance ["--confirm-migrations", "up"] + [PSQL.Only migrations] <- PSQL.query_ db $ Query $ "SELECT count(*) FROM " <> B.pack schema <> ".migrations" + migrations `shouldSatisfy` (> (0 :: Int)) + PSQL.close db + xftpServerDelete +#endif diff --git a/tests/CoreTests/TransportTests.hs b/tests/CoreTests/TransportTests.hs new file mode 100644 index 000000000..aa07ec33b --- /dev/null +++ b/tests/CoreTests/TransportTests.hs @@ -0,0 +1,91 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} + +module CoreTests.TransportTests (transportTests) where + +import Control.Concurrent (threadDelay) +import Control.Exception (uninterruptibleMask_) +import Control.Monad +import qualified Data.ByteString.Char8 as B +import Data.Either (isLeft) +import Data.X509.Validation (Fingerprint (..)) +import Network.Socket (ServiceName, Socket, SocketOption (KeepAlive, UserTimeout), getSocketOption) +import SMPClient (serverBracket) +import qualified Simplex.Messaging.Crypto as C +import Simplex.Messaging.Transport +import Simplex.Messaging.Transport.Client (defaultTransportClientConfig, runTLSTransportClient) +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts, defaultKeepAliveOpts) +import Simplex.Messaging.Transport.Server +import Test.Hspec hiding (fit, it) +import UnliftIO.Async (async, wait, waitCatch) +import UnliftIO.STM +import UnliftIO.Timeout (timeout) +import Util + +transportTests :: Spec +transportTests = do + describe "TLS connection close" $ + it "should close TLS connection while its peer does not read and data is sent" testCloseBlockedTLS + describe "TCP keep-alive" $ do + it "should enable keep-alive on accepted sockets when configured" $ + testServerKeepAlive (Just defaultKeepAliveOpts) True + it "should not enable keep-alive on accepted sockets by default" $ + testServerKeepAlive Nothing False + describe "TCP user timeout" $ do + it "should set user timeout on accepted sockets when configured" $ + testServerUserTimeout (Just 180000) 180000 + it "should not set user timeout on accepted sockets by default" $ + testServerUserTimeout Nothing 0 + +transportTestPort :: HasTestEnv => ServiceName +transportTestPort = testServerPort 9 + +testCredentials :: ServerCredentials +testCredentials = + ServerCredentials + { caCertificateFile = Just "tests/fixtures/ca.crt", + privateKeyFile = "tests/fixtures/server.key", + certificateFile = "tests/fixtures/server.crt" + } + +withTLSConnection :: HasTestEnv => TransportServerConfig -> (TLS 'TClient -> (Socket, TLS 'TServer) -> IO a) -> IO a +withTLSConnection cfg action = do + credential <- loadServerCredential testCredentials + Fingerprint fp <- loadFingerprint testCredentials + ss <- newSocketState + serverConn <- newEmptyTMVarIO + let creds = TLSServerCredential {credential, sniCredential = Nothing} + server sock (_, tls) = atomically (putTMVar serverConn (sock, tls)) >> threadDelay maxBound + serverBracket + (\started -> runTransportServerState_ ss started transportTestPort defaultSupportedParams creds cfg server) + (pure ()) + $ \_ -> + runTLSTransportClient defaultSupportedParams Nothing defaultTransportClientConfig Nothing "localhost" transportTestPort (Just $ C.KeyHash fp) $ \client -> + atomically (takeTMVar serverConn) >>= action client + +testCloseBlockedTLS :: HasTestEnv => Expectation +testCloseBlockedTLS = withTLSConnection (mkTransportServerConfig True Nothing False) $ \_client (_, server) -> do + sent <- newTVarIO (0 :: Int) + sender <- async . forever $ cPut server block >> atomically (modifyTVar' sent (+ 1)) + timeout 30000000 (waitBlocked sent 0) `shouldReturn` Just () + closing <- async . uninterruptibleMask_ $ closeConnection server + timeout 5000000 (wait closing) `shouldReturn` Just () + timeout 5000000 (isLeft <$> waitCatch sender) `shouldReturn` Just True + where + block = B.replicate 1048576 'x' + waitBlocked sent n = do + threadDelay 500000 + n' <- readTVarIO sent + unless (n' == n) $ waitBlocked sent n' + +testServerUserTimeout :: HasTestEnv => Maybe Int -> Int -> Expectation +testServerUserTimeout tcpUserTimeout expected = + withTLSConnection (mkTransportServerConfig True Nothing False) {tcpUserTimeout} $ \_client (sock, _) -> + getSocketOption sock UserTimeout `shouldReturn` expected + +testServerKeepAlive :: HasTestEnv => Maybe KeepAliveOpts -> Bool -> Expectation +testServerKeepAlive tcpKeepAlive enabled = + withTLSConnection (mkTransportServerConfig True Nothing False) {tcpKeepAlive} $ \_client (sock, _) -> + ((/= 0) <$> getSocketOption sock KeepAlive) `shouldReturn` enabled diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index 8b5ce46cf..b7c415563 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -5,6 +5,8 @@ module CoreTests.XFTPStoreTests (xftpStoreTests, xftpMigrationTests) where import Control.Monad +import qualified Data.ByteString.Char8 as B +import Data.List.NonEmpty (NonEmpty (..)) import Data.Word (Word32) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store @@ -26,8 +28,9 @@ import XFTPClient (testXFTPPostgresCfg) xftpStoreTests :: Spec xftpStoreTests = do - describe "STMFileStore operations" $ + describe "STMFileStore operations" $ do it "should compute committed used storage and file count" testSTMStorageAndCount + it "should add all recipients or none" $ (newFileStore () :: IO STMFileStore) >>= testAddRecipientsAtomically describe "PostgresFileStore operations" $ do it "should add and get file by sender" testAddGetFileSender it "should add and get file by recipient" testAddGetFileRecipient @@ -35,12 +38,14 @@ xftpStoreTests = do it "should return AUTH for nonexistent file" testGetNonexistent it "should set file path with IS NULL guard" testSetFilePath it "should reject duplicate recipient" testDuplicateRecipient + it "should add all recipients or none" $ withPgStore testAddRecipientsAtomically it "should delete file and cascade recipients" testDeleteFileCascade it "should block file and update status" testBlockFile it "should ack file reception" testAckFile it "should return expired files with limit" testExpiredFiles it "should expire files by stored expiration" testExpiredFilesStoredExpiration it "should log each file deletion once" testDeleteFilesLog + it "should return at most limit expired files of both kinds" testExpiredFilesTotalLimit it "should compute committed used storage and file count" testStorageAndCount xftpMigrationTests :: Spec @@ -100,7 +105,7 @@ testAddGetFileRecipient = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () result <- getFile st SFRecipient testRecipientId case result of Right (FileRec {senderId}, key) -> do @@ -143,8 +148,27 @@ testDuplicateRecipient = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Left DUPLICATE_ + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Left DUPLICATE_ + +testAddRecipientsAtomically :: FileStoreClass s => s -> Expectation +testAddRecipientsAtomically st = do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + [keyA, keyB, keyC] <- replicateM 3 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) + let rcpA = FileRecipient (EntityId "recipient_a_____") keyA + rcpB = FileRecipient (EntityId "recipient_b_____") keyB + rcpC = FileRecipient (EntityId "recipient_c_____") keyC + recipientKey (FileRecipient rId _) = fmap snd <$> getFile st SFRecipient rId + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + addRecipients st testSenderId (rcpA :| []) `shouldReturn` Right () + addRecipients st testSenderId (rcpB :| [rcpA]) `shouldReturn` Left DUPLICATE_ + recipientKey rcpB `shouldReturn` Left AUTH + addRecipients st testSenderId (rcpB :| [rcpC, rcpB]) `shouldReturn` Left DUPLICATE_ + recipientKey rcpB `shouldReturn` Left AUTH + addRecipients st testSenderId (rcpB :| [rcpC]) `shouldReturn` Right () + mapM recipientKey [rcpA, rcpB, rcpC] `shouldReturn` [Right keyA, Right keyB, Right keyC] + addRecipients st (EntityId "no_such_sender__") (FileRecipient (EntityId "recipient_d_____") keyA :| []) `shouldReturn` Left AUTH testDeleteFileCascade :: HasTestEnv => Expectation testDeleteFileCascade = withPgStore $ \st -> do @@ -153,7 +177,7 @@ testDeleteFileCascade = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () deleteFile st testSenderId `shouldReturn` Right Nothing -- File and recipient should both be gone getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) @@ -166,7 +190,7 @@ testBlockFile = withPgStore $ \st -> do let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () let blockInfo = BlockingInfo {reason = BRContent, notice = Nothing} - blockFile st testSenderId blockInfo False `shouldReturn` Right Nothing + blockFile st testSenderId blockInfo `shouldReturn` Right Nothing result <- getFile st SFSender testSenderId case result of Right (FileRec {fileStatus}, _) -> readTVarIO fileStatus `shouldReturn` EntityBlocked blockInfo @@ -179,7 +203,7 @@ testAckFile = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () ackFile st testRecipientId `shouldReturn` Right () -- Recipient gone, but file still exists getFile st SFRecipient testRecipientId >>= (`shouldBe` Left AUTH) . fmap (const ()) @@ -236,6 +260,18 @@ testDeleteFilesLog = do closeFileStore st map (take 4) . lines <$> readFile storeLogPath `shouldReturn` ["FNEW", "FNEW", "FDEL", "FDEL"] +testExpiredFilesTotalLimit :: HasTestEnv => Expectation +testExpiredFilesTotalLimit = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let fileInfo = testFileInfo sndKey + oldTime = RoundedSystemTime 100000 + addExpired i expiresAt = addFile st (EntityId $ "expired_file_" <> B.pack (show i) <> "__") fileInfo oldTime expiresAt EntityActive `shouldReturn` Right () + forM_ [1 .. 3 :: Int] $ \i -> addExpired i $ Just (RoundedSystemTime 400000) + forM_ [4 .. 6 :: Int] $ \i -> addExpired i Nothing + length <$> expiredFiles st (RoundedSystemTime 500000) 500000 4 `shouldReturn` 4 + length <$> expiredFiles st (RoundedSystemTime 500000) 500000 10 `shouldReturn` 6 + testStorageAndCount :: HasTestEnv => Expectation testStorageAndCount = withPgStore $ \st -> do testStorageAndCountForStore st @@ -250,22 +286,34 @@ testStorageAndCountForStore :: FileStoreClass s => s -> Expectation testStorageAndCountForStore st = do g <- C.newRandom (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - getUsedStorage st `shouldReturn` 0 + getUsedStorage st `shouldReturn` (0, 0) getFileCount st `shouldReturn` 0 let fileInfoA = testFileInfo sndKey fileInfoB = fileInfoA {size = 64000} fileA = EntityId "file_a__________" fileB = EntityId "file_b__________" + fileC = EntityId "file_c__________" addFile st fileA fileInfoA testCreatedAt Nothing EntityActive `shouldReturn` Right () addFile st fileB fileInfoB testCreatedAt Nothing EntityActive `shouldReturn` Right () getFileCount st `shouldReturn` 2 - getUsedStorage st `shouldReturn` 0 + getUsedStorage st `shouldReturn` (0, 0) setFilePath st fileA "/tmp/file_a" `shouldReturn` Right () - getUsedStorage st `shouldReturn` 128000 + getUsedStorage st `shouldReturn` (1, 128000) setFilePath st fileB "/tmp/file_b" `shouldReturn` Right () - getUsedStorage st `shouldReturn` 192000 - void $ blockFile st fileA BlockingInfo {reason = BRSpam, notice = Nothing} True - getUsedStorage st `shouldReturn` 64000 + getUsedStorage st `shouldReturn` (2, 192000) + let blockInfo = BlockingInfo {reason = BRContent, notice = Nothing} + blockFile st fileB blockInfo `shouldReturn` Right (Just "/tmp/file_b") + blockFile st fileB blockInfo `shouldReturn` Right Nothing + getUsedStorage st `shouldReturn` (1, 128000) + getFileCount st `shouldReturn` 2 + addFile st fileC fileInfoA testCreatedAt Nothing EntityActive `shouldReturn` Right () + setFilePath st fileC "/tmp/file_c" `shouldReturn` Right () + deleteFile st fileC `shouldReturn` Right (Just "/tmp/file_c") + deleteFile st fileC `shouldReturn` Left AUTH + deleteFiles st [fileA, fileB, fileC] >>= (`shouldMatchList` [(fileA, Just "/tmp/file_a", 128000), (fileB, Nothing, 64000)]) + deleteFiles st [fileA, fileB] `shouldReturn` [] + getUsedStorage st `shouldReturn` (0, 0) + getFileCount st `shouldReturn` 0 -- Migration round-trip test @@ -286,7 +334,7 @@ testMigrationRoundTrip = do rId1 = EntityId "migration_rcp_1_" addFile stmStore sId1 fileInfo1 testCreatedAt (Just testExpiresAt) EntityActive `shouldReturn` Right () void $ setFilePath stmStore sId1 ("/tmp" serverFileName sId1) - addRecipient stmStore sId1 (FileRecipient rId1 rcpKey1) `shouldReturn` Right () + addRecipients stmStore sId1 (FileRecipient rId1 rcpKey1 :| []) `shouldReturn` Right () let testBlockInfo = BlockingInfo {reason = BRSpam, notice = Nothing} addFile stmStore sId2 fileInfo2 testCreatedAt Nothing (EntityBlocked testBlockInfo) `shouldReturn` Right () -- 2. Write to StoreLog diff --git a/tests/Test.hs b/tests/Test.hs index 8e89cf090..535780ae6 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -17,6 +17,7 @@ import CoreTests.RetryIntervalTests import CoreTests.SOCKSSettings import CoreTests.StoreLogTests import CoreTests.TSessionSubs +import CoreTests.TransportTests import CoreTests.UtilTests import CoreTests.VersionRangeTests import FileDescriptionTests (fileDescriptionTests) @@ -100,6 +101,7 @@ main = do describe "XFTP store log tests" fileStoreLogTests fileExpirationTests describe "TSessionSubs tests" tSessionSubsTests + describe "Transport tests" transportTests describe "Util tests" utilTests describe "Names resolver tests" smpNamesTests describe "RSLV functional API tests" rslvTests diff --git a/tests/XFTPClient.hs b/tests/XFTPClient.hs index f8631e626..f7a4a65ae 100644 --- a/tests/XFTPClient.hs +++ b/tests/XFTPClient.hs @@ -166,9 +166,9 @@ withStallingXFTPServer action = do requested <- newEmptyTMVarIO closed <- newEmptyTMVarIO creds <- loadServerCredential xftpCredentials - let stall _ _ _ _ _ = atomically (putTMVar requested ()) >> threadDelay maxBound + let stall _ _ _ _ _ _ = atomically (putTMVar requested ()) >> threadDelay maxBound serverBracket - (\started -> runHTTP2Server started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> atomically $ putTMVar closed ()) stall) + (\started -> newSocketState >>= \ss -> runHTTP2Server ss started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> atomically $ putTMVar closed ()) stall) (pure ()) (const $ action requested closed) where diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index cd6c543a8..b3afe4192 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -1,5 +1,6 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} @@ -11,12 +12,14 @@ module XFTPServerTests (xftpServerTests) where import AgentTests.FunctionalAPITests (runRight, runRight_) import Control.Concurrent (threadDelay) -import Control.Exception (SomeException, bracket) +import Control.Exception (IOException, SomeException, bracket, catch) import Control.Monad import Control.Monad.Except import Control.Monad.IO.Unlift import qualified Crypto.PubKey.RSA as RSA import Data.Bifunctor (first) +import qualified Data.ByteArray as BA +import qualified Data.ByteString.Base64.URL as B64 import Data.ByteString.Builder (byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B @@ -25,7 +28,10 @@ import qualified Data.CaseInsensitive as CI import Data.Either (isLeft) import Data.List (find, isInfixOf) import Data.List.NonEmpty (NonEmpty) -import Data.Time.Clock (getCurrentTime) +import Data.Maybe (listToMaybe) +import qualified Data.Text as T +import qualified Data.Text.IO as T +import Data.Time.Clock (UTCTime (..), getCurrentTime) import qualified Data.X509 as X import Data.X509.Validation (Fingerprint (..), getFingerprint) import Network.HPACK.Token (tokenKey) @@ -37,31 +43,35 @@ import SMPClient (copyWebCredential, serverBracket, testCredentialCheckInterval, import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A -import Simplex.FileTransfer.Description (kb) +import Simplex.FileTransfer.Description (kb, mb) import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), FileResponse (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpDecodeTClient, xftpEncodeAuthTransmission) -import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..)) -import Simplex.FileTransfer.Server.StoreLog (serverFileName) -import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), receiveFile, pattern VersionXFTP) +import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..), XFTPStoreConfig (..), defaultInactiveClientExpiration) +import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, logAddFile, logPutFile, serverFileName) +import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), alpnSupportedXFTPhandshakes, receiveEncFile, receiveFile, pattern VersionXFTP) import Simplex.Messaging.Client (NetworkConfig (..), NetworkTimeout (..), ProtocolClientError (..), defaultNetworkConfig) import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding (smpDecode, smpEncode) import Simplex.Messaging.Protocol (BasicAuth, EntityId (..), RecipientId, SenderId, pattern NoEntity) import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) +import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) +import Simplex.Messaging.Server.StoreLog (openWriteStoreLog) import Simplex.Messaging.SystemTime (RoundedSystemTime (..), getSystemSeconds) -import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS) +import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), Transport (cGet), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTransportClientConfig, runTLSTransportClient) import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..), defaultHTTP2BufferSize) +import Simplex.Messaging.Transport.HTTP2.File (fileBlockSize) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential) import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts) import Simplex.Messaging.Util (bshow, unlessM, whenM) import Simplex.Messaging.Version (mkVersionRange) -import System.Directory (doesFileExist, listDirectory, removeFile) -import System.FilePath (()) +import System.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getSymbolicLinkTarget, listDirectory, removeFile) +import System.FilePath (takeExtension, ()) import Test.Hspec hiding (fit, it) import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_, wait, withAsync) +import UnliftIO.Exception (tryAny) import UnliftIO.STM import UnliftIO.Timeout (timeout) import Util @@ -77,7 +87,9 @@ xftpServerTests = do it "should delete file chunk (2 clients)" testFileChunkDelete2 it "should not allow chunks of wrong size" testWrongChunkSize it "should expire chunks after set interval" testFileChunkExpiration + it "should expire chunks that were never uploaded without delays" testExpireNotUploadedFiles it "should disconnect inactive clients" testInactiveClientExpiration + it "should not disconnect clients during downloads longer than inactivity ttl" testLongDownloadExpiration it "should close connection when connecting client is cancelled" $ \_ -> testCancelledClientConnect it "should time out TLS handshake when TLS errors are logged" $ \_ -> testTLSHandshakeTimeout it "should time out receiving file chunk" $ \_ -> testReceiveFileTimeout @@ -87,7 +99,11 @@ xftpServerTests = do it "should cancel a stalled upload and release its storage when its chunk is uploaded again" testCancelStalledChunkUpload it "should remove a chunk uploaded while its file expires" testUploadDuringExpiration it "should store file records to log and restore them after server restart" testFileLog - it "should remove files without stored chunks when the server starts" testRemoveUnstoredFiles + it "should reset daily download stats without stats log" testPeriodStatsReset + it "should export socket counts in Prometheus metrics" testSocketMetrics + it "should count stored files after restart without stats backup" $ testFileStatsRestart False + it "should count stored files after restart with stats backup" $ testFileStatsRestart True + it "should count stored files after deletion" testFileStatsDelete describe "XFTP basic auth" $ do -- allow FNEW | server auth | clnt auth | success it "prohibited without basic auth" $ testFileBasicAuth True (Just "pwd") Nothing False @@ -96,11 +112,23 @@ xftpServerTests = do it "allowed with correct basic auth" $ testFileBasicAuth True (Just "pwd") (Just "pwd") True it "allowed with auth on server without auth" $ testFileBasicAuth True Nothing (Just "any") True it "should not change content for uploaded and committed files" testFileSkipCommitted + it "should close connection and file when download stalls" testStalledDownload + it "should close connection when the end of a download stalls" testStalledDownloadEnd + it "should close connection when request body stalls" testStalledRequestBody + it "should time out a stalled upload of a committed chunk" $ testStalledUpload True + it "should time out a stalled upload of a new chunk" $ testStalledUpload False + it "should accept a repeated upload of a chunk while its first upload is stalled" testRepeatedUploadDuringStalledUpload + it "should return OK to an upload completed after another upload of the chunk" testUploadAfterCommittedUpload + it "should remove unfinished uploads at start" testRemoveTmpUploads + it "should close connections without requests" testNoRequestTimeout it "should close connection when handshake times out" testHandshakeTimeout it "should close connection when cancelled during handshake" testCancelledHandshake it "should not send request after it times out" testRequestNotSentAfterTimeout it "should time out request while request queue is full" testRequestTimeoutInFullQueue it "should decode handshake of servers before v6.5.0 and refuse an invalid signature" testOldServerHandshake + describe "XFTP chunk receiving" $ beforeWith (const (pure ())) $ do + it "should verify digest of received chunk without reading the file back" testReceiveChunkDigest + it "should verify digest of received encrypted chunk without reading the file back" testReceiveEncChunkDigest describe "XFTP SNI and CORS" $ beforeWith (const (pure ())) $ do it "should select web certificate when SNI is used" testSNICertSelection it "should select XFTP certificate when SNI is not used" testNoSNICertSelection @@ -244,11 +272,29 @@ testFileChunkExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fs where fileExpiration = ExpirationConfig {ttl = 1, checkInterval = 1} +testExpireNotUploadedFiles :: HasTestEnv => AFStoreType -> Expectation +testExpireNotUploadedFiles _ = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + now <- getSystemSeconds + let sIds = map (\i -> EntityId $ "never_uploaded" <> B.pack (show i)) [10 .. 59 :: Int] + fileInfo = FileInfo {sndKey, size = chSize, digest = "digest"} + createdAt = RoundedSystemTime $ roundedSeconds now + expiresAt = RoundedSystemTime $ roundedSeconds now + 2 + sl <- openWriteStoreLog False testXFTPLogFile + forM_ sIds $ \sId -> logAddFile sl sId fileInfo createdAt (Just expiresAt) EntityActive + closeStoreLog sl + withXFTPServerCfg testXFTPServerConfig {serverStoreCfg = XSCMemory (Just testXFTPLogFile), storeLogFile = Just testXFTPLogFile, fileExpiration} $ \_ -> do + threadDelay 6000000 + testXFTPClient $ \c -> forM_ sIds $ \sId -> + runExceptT (addXFTPRecipients c spKey sId [rcvKey]) `shouldReturn` Left (PCEProtocolError AUTH) + where + fileExpiration = ExpirationConfig {ttl = 86400, checkInterval = 1} + testInactiveClientExpiration :: HasTestEnv => AFStoreType -> Expectation testInactiveClientExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {inactiveClientExpiration}) $ \_ -> runRight_ $ do - disconnected <- newEmptyTMVarIO - ts <- liftIO getCurrentTime - c <- ExceptT $ getXFTPClient (1, testXFTPServer, Nothing) testXFTPClientConfig [] ts (\_ -> pure Nothing) (\_ -> atomically $ putTMVar disconnected ()) + (c, disconnected) <- liftIO connectXFTPClient pingXFTP c liftIO $ do threadDelay 100000 @@ -260,6 +306,30 @@ testInactiveClientExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfg where inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} +testLongDownloadExpiration :: HasTestEnv => AFStoreType -> Expectation +testLongDownloadExpiration fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {inactiveClientExpiration}) $ \_ -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyPart}} <- sendFGET c rpKey rId + getPart <- maybe (error "no response body") pure bodyPart + slowBytes <- readBody getPart (mb 2) 25000 + restBytes <- timeout 15000000 (readBody getPart maxBound 0) >>= maybe (error "body not read within 15 seconds") pure + slowBytes + restBytes `shouldBe` mb 4 + C.authTagSize + runRight_ $ pingXFTP c + expectDisconnected disconnected + where + inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} + +readBody :: (Int -> IO ByteString) -> Int -> Int -> IO Int +readBody getPart limit delay = go 0 + where + go n + | n >= limit = pure n + | otherwise = do + threadDelay delay + len <- B.length <$> getPart fileBlockSize + if len == 0 then pure n else go (n + len) + testCancelledClientConnect :: HasTestEnv => Expectation testCancelledClientConnect = withStallingServerOn' xftpTestPort $ \accepted closed -> do @@ -513,6 +583,112 @@ testFileLog _ = do downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest liftIO $ B.readFile (testPath "received_chunk1") `shouldReturn` bytes +testPeriodStatsReset :: HasTestEnv => AFStoreType -> Expectation +testPeriodStatsReset fsType = do + ts <- getCurrentTime + let resetTime = floor (utctDayTime ts) + 10 + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {logStatsInterval = Nothing, logStatsStartTime = resetTime, prometheusInterval = Just 1}) $ \_ -> do + testXFTPClient $ \c -> runRight_ $ runTestFileChunkDelivery c c + threadDelay 1500000 + dailyDownloads `shouldReturn` Just "1" + threadDelay 10000000 + dailyDownloads `shouldReturn` Just "0" + where + dailyDownloads = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure $ listToMaybe [n | l <- metrics, ["simplex_xftp_files_count_daily", n, _] <- [T.words l]] + +testSocketMetrics :: HasTestEnv => AFStoreType -> Expectation +testSocketMetrics fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {prometheusInterval = Just 1}) $ \_ -> do + testXFTPClient $ \c -> do + runRight_ $ pingXFTP c + threadDelay 1500000 + socketMetrics `shouldReturn` [("accepted", "1"), ("closed", "0"), ("active", "1"), ("leaked", "0")] + closeXFTPClient c + threadDelay 2500000 + socketMetrics `shouldReturn` [("accepted", "1"), ("closed", "1"), ("active", "0"), ("leaked", "0")] + where + socketMetrics = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure + [ (name, n) + | l <- metrics, + [metric, n, _] <- [T.words l], + Just name <- [T.stripPrefix "simplex_xftp_sockets_" =<< T.stripSuffix portLabel metric] + ] + portLabel = "{port=\"" <> T.pack xftpTestPort <> "\"}" + +testFileStatsRestart :: HasTestEnv => Bool -> AFStoreType -> Expectation +testFileStatsRestart statsBackup _ = do + when statsBackup $ do + withXFTPServerCfg cfg $ \_ -> pure () + doesFileExist testXFTPStatsBackupFile `shouldReturn` True + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + createDirectoryIfMissing True xftpServerFiles + sl <- openWriteStoreLog False testXFTPLogFile + let fileInfo = FileInfo {sndKey, size = chSize, digest = "digest"} + addTestFile sId expiresAt = logAddFile sl sId fileInfo (RoundedSystemTime 0) (Just $ RoundedSystemTime expiresAt) EntityActive + putTestFile sId = do + let path = xftpServerFiles serverFileName sId + void $ createTestChunk path + logPutFile sl sId path + expiredId = EntityId "expired_file____" + storedId = EntityId "stored_file_____" + addTestFile expiredId 3600 + putTestFile expiredId + addTestFile storedId 4102444800 + putTestFile storedId + addTestFile (EntityId "new_file________") 4102444800 + closeStoreLog sl + withXFTPServerCfg cfg $ \_ -> threadDelay 2500000 + fileMetrics `shouldReturn` [("expired", "1"), ("deleted", "0"), ("count_total", "1"), ("size", "131072")] + where + cfg = + testXFTPServerConfig + { serverStoreCfg = XSCMemory (Just testXFTPLogFile), + storeLogFile = Just testXFTPLogFile, + serverStatsBackupFile = if statsBackup then Just testXFTPStatsBackupFile else Nothing, + prometheusInterval = Just 1 + } + +testFileStatsDelete :: HasTestEnv => AFStoreType -> Expectation +testFileStatsDelete fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {prometheusInterval = Just 1}) $ \_ -> + testXFTPClient $ \c -> runRight_ $ do + g <- liftIO C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ liftIO $ createTestChunk testChunkPath + digest <- liftIO $ LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId1, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId1 chunkSpec + (sId2, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId2 chunkSpec + liftIO $ do + threadDelay 1500000 + fileMetrics `shouldReturn` [("expired", "0"), ("deleted", "0"), ("count_total", "2"), ("size", "262144")] + removeFile $ xftpServerFiles serverFileName sId2 + deleteXFTPChunk c spKey sId1 + deleteXFTPChunk c spKey sId2 + liftIO $ do + threadDelay 1500000 + fileMetrics `shouldReturn` [("expired", "0"), ("deleted", "2"), ("count_total", "0"), ("size", "0")] + +fileMetrics :: HasTestEnv => IO [(T.Text, T.Text)] +fileMetrics = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure + [ (name, n) + | l <- metrics, + [metric, n, _] <- [T.words l], + Just name <- [T.stripPrefix "simplex_xftp_files_" metric], + name `elem` (["expired", "deleted", "count_total", "size"] :: [T.Text]) + ] + testFileBasicAuth :: HasTestEnv => Bool -> Maybe BasicAuth -> Maybe BasicAuth -> Bool -> AFStoreType -> IO () testFileBasicAuth allowNewFiles newFileBasicAuth clntAuth success fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {allowNewFiles, newFileBasicAuth}) $ @@ -554,6 +730,178 @@ testFileSkipCommitted fsType = downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest liftIO $ B.readFile (testPath "received_chunk") `shouldReturn` bytes -- new chunk content got ignored +testStalledDownload :: HasTestEnv => AFStoreType -> Expectation +testStalledDownload fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration = Nothing}) $ \_ -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + void $ sendFGET c rpKey rId + expectDisconnected disconnected + filesClosed (20 :: Int) `shouldReturn` True + where + filesClosed n = do + closed <- all (maybe True (== 0)) <$> (mapM (openDescriptors . (xftpServerFiles )) =<< listDirectory xftpServerFiles) + if closed || n <= 0 then pure closed else threadDelay 100000 >> filesClosed (n - 1) + +testStalledDownloadEnd :: HasTestEnv => AFStoreType -> Expectation +testStalledDownloadEnd fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration}) $ \_ -> + forM_ [mb 1 + kb k | k <- [0, 64 .. 320]] $ \unread -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyPart}} <- sendFGET c rpKey rId + getPart <- maybe (error "no response body") pure bodyPart + void $ readBody getPart (mb 4 + C.authTagSize - unread) 0 + expectDisconnected disconnected + where + inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} + +testStalledRequestBody :: HasTestEnv => AFStoreType -> Expectation +testStalledRequestBody fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration = Nothing}) $ \_ -> do + (XFTPClient {http2Client}, disconnected) <- connectXFTPClient + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send "x" >> flush >> threadDelay maxBound + withAsync (HC.sendRequest http2Client req Nothing) $ \_ -> expectDisconnected disconnected + +testStalledUpload :: HasTestEnv => Bool -> AFStoreType -> Expectation +testStalledUpload committed fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000}) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + sId <- runRight $ do + (sId, _) <- createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + when committed $ uploadXFTPChunk c spKey sId chunkSpec + pure sId + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send (byteString t) >> flush >> threadDelay maxBound + timeout 5000000 (HC.sendRequest http2Client req Nothing) >>= \case + Just (Right HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}}) -> case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr e)) -> e `shouldBe` TIMEOUT + r -> expectationFailure $ "unexpected response: " <> show r + Just (Left e) -> expectationFailure $ "request error: " <> show e + Nothing -> expectationFailure "no response within 5 seconds" + +testRepeatedUploadDuringStalledUpload :: HasTestEnv => AFStoreType -> Expectation +testRepeatedUploadDuringStalledUpload fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000}) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send (byteString t) >> flush >> threadDelay maxBound + download c' = do + runRight_ $ downloadXFTPChunk g c' rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest + B.readFile (testPath "received_chunk") `shouldReturn` bytes + withAsync (HC.sendRequest http2Client req Nothing) $ \_ -> do + threadDelay 500000 + testXFTPClient $ \c' -> do + runRight_ $ uploadXFTPChunk c' spKey sId chunkSpec + download c' + threadDelay 2500000 + download c' + filter ((".tmp" ==) . takeExtension) <$> listDirectory xftpServerFiles `shouldReturn` [] + +testUploadAfterCommittedUpload :: HasTestEnv => AFStoreType -> Expectation +testUploadAfterCommittedUpload fsType = + withXFTPServerConfigOn (cfgFS fsType) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + bodyAllowed <- newEmptyTMVarIO + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send (byteString t) >> flush + atomically $ takeTMVar bodyAllowed + send (byteString bytes) >> flush + withAsync (HC.sendRequest http2Client req Nothing) $ \firstUpload -> do + threadDelay 500000 + testXFTPClient $ \c' -> runRight_ $ uploadXFTPChunk c' spKey sId chunkSpec + atomically $ putTMVar bodyAllowed () + wait firstUpload >>= \case + Right HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} -> case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right FROk) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + Left e -> expectationFailure $ "request error: " <> show e + runRight_ $ downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest + B.readFile (testPath "received_chunk") `shouldReturn` bytes + +testRemoveTmpUploads :: HasTestEnv => AFStoreType -> Expectation +testRemoveTmpUploads _ = do + createDirectoryIfMissing True xftpServerFiles + writeFile (xftpServerFiles "chunk") "chunk" + writeFile (xftpServerFiles "chunk.upload.tmp") "partial upload" + withXFTPServerThreadOn $ \_ -> listDirectory xftpServerFiles `shouldReturn` ["chunk"] + +testNoRequestTimeout :: HasTestEnv => AFStoreType -> Expectation +testNoRequestTimeout fsType = + forM_ ([Nothing, Just defaultInactiveClientExpiration] :: [Maybe ExpirationConfig]) $ \inactiveClientExpiration -> + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c@XFTPServerConfig {transportConfig = tc} -> c {inactiveClientExpiration, transportConfig = tc {firstRequestTimeout = 1000000}}) $ \_ -> do + Fingerprint fp <- loadFileFingerprint "tests/fixtures/ca.crt" + let cfg = defaultTransportClientConfig {clientALPN = Just alpnSupportedXFTPhandshakes} :: TransportClientConfig + runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort (Just $ C.KeyHash fp) $ \(tls :: TLS 'TClient) -> + timeout 5000000 (tryAny $ cGet tls 1) >>= (`shouldSatisfy` maybe False (either (const True) B.null)) + (c, disconnected) <- connectXFTPClient + threadDelay 2000000 + atomically (tryReadTMVar disconnected) `shouldReturn` Nothing + runRight_ $ pingXFTP c + +connectXFTPClient :: HasTestEnv => IO (XFTPClient, TMVar ()) +connectXFTPClient = do + disconnected <- newEmptyTMVarIO + ts <- getCurrentTime + c <- either (error . show) pure =<< getXFTPClient (1, testXFTPServer, Nothing) testXFTPClientConfig [] ts (\_ -> pure Nothing) (\_ -> atomically $ putTMVar disconnected ()) + pure (c, disconnected) + +uploadLargeChunk :: HasTestEnv => IO (XFTPClient, TMVar (), RecipientId, C.APrivateAuthKey) +uploadLargeChunk = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let size = mb 4 + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = size} + B.writeFile testChunkPath =<< atomically (C.randomBytes (fromIntegral size) g) + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + (c, disconnected) <- connectXFTPClient + rId <- runRight $ do + (sId, [rId]) <- createXFTPChunk c spKey FileInfo {sndKey, size, digest} [rcvKey] Nothing + uploadXFTPChunk c spKey sId chunkSpec + pure rId + pure (c, disconnected, rId, rpKey) + +expectDisconnected :: TMVar () -> Expectation +expectDisconnected disconnected = timeout 5000000 (atomically $ takeTMVar disconnected) `shouldReturn` Just () + +sendFGET :: XFTPClient -> C.APrivateAuthKey -> RecipientId -> IO HC.HTTP2Response +sendFGET XFTPClient {http2Client, thParams} rpKey rId = do + (rDhKey, _) <- atomically . C.generateKeyPair =<< C.newRandom + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams rpKey ("", rId, FileCmd SFRecipient $ FGET rDhKey) + either (error . show) pure =<< HC.sendRequest http2Client (H2.requestBuilder "POST" "/" [] $ byteString t) Nothing + +openDescriptors :: FilePath -> IO (Maybe Int) +openDescriptors path = + doesDirectoryExist fdDir >>= \case + False -> pure Nothing + True -> do + target <- canonicalizePath path + fds <- listDirectory fdDir + Just . length . filter (== target) <$> mapM linkTarget fds + where + fdDir = "/proc/self/fd" + linkTarget fd = getSymbolicLinkTarget (fdDir fd) `catch` \(_ :: IOException) -> pure "" + testHandshakeTimeout :: HasTestEnv => AFStoreType -> Expectation testHandshakeTimeout _ = withStallingXFTPServer $ \_ closed -> do @@ -627,6 +975,33 @@ testOldServerHandshake _ = do where XFTPServerConfig {xftpCredentials} = testXFTPServerConfig +testReceiveChunkDigest :: Expectation +testReceiveChunkDigest = do + bytes <- atomically . C.randomBytes chSize =<< C.newRandom + let digest = LC.sha256Hash $ LB.fromStrict bytes + receive d = bodyReader bytes >>= \getBody -> runExceptT $ receiveFile getBody $ XFTPRcvChunkSpec "/dev/null" chSize d + receive digest `shouldReturn` Right () + receive (digest <> "_wrong") `shouldReturn` Left DIGEST + +testReceiveEncChunkDigest :: Expectation +testReceiveEncChunkDigest = do + g <- C.newRandom + bytes <- atomically $ C.randomBytes chSize g + key <- atomically $ C.randomSbKey g + nonce <- atomically $ C.randomCbNonce g + sbState <- either (error . show) pure $ LC.sbInit key nonce + let (encrypted, sbState') = LC.sbEncryptChunk sbState bytes + body = encrypted <> BA.convert (LC.sbAuth sbState') + digest = LC.sha256Hash $ LB.fromStrict bytes + receive d = bodyReader body >>= \getBody -> runExceptT $ receiveEncFile getBody sbState $ XFTPRcvChunkSpec "/dev/null" chSize d + receive digest `shouldReturn` Right () + receive (digest <> "_wrong") `shouldReturn` Left DIGEST + +bodyReader :: ByteString -> IO (Int -> IO ByteString) +bodyReader bytes = do + rest <- newTVarIO bytes + pure $ \n -> atomically $ stateTVar rest $ B.splitAt n + -- SNI and CORS tests lookupResponseHeader :: B.ByteString -> H2.Response -> Maybe B.ByteString From 39c1ef00dd11675b73fb455d366f1e0f6c3bcdd4 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 03:32:16 -0500 Subject: [PATCH 021/159] agent: retry deadlocked PostgreSQL transactions Consolidated from PR #2082 while preserving cancellation and file-count semantics. --- .../FileTransfer/Server/Store/Postgres.hs | 6 +- src/Simplex/Messaging/Agent.hs | 10 +- src/Simplex/Messaging/Agent/Client.hs | 20 ++- .../Messaging/Agent/Store/AgentStore.hs | 32 +++- .../Messaging/Agent/Store/Postgres/Common.hs | 43 ++++- .../Messaging/Agent/Store/SQLite/Common.hs | 6 +- .../Notifications/Server/Store/Postgres.hs | 4 +- .../Messaging/Server/QueueStore/Postgres.hs | 2 +- tests/AgentTests.hs | 4 +- tests/AgentTests/FunctionalAPITests.hs | 164 +++++++++++++++++- tests/CoreTests/MsgStoreTests.hs | 14 +- tests/CoreTests/XFTPStoreTests.hs | 25 ++- tests/NtfServerTests.hs | 18 +- tests/SMPClient.hs | 5 +- tests/Test.hs | 3 +- 15 files changed, 316 insertions(+), 40 deletions(-) diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index 027793729..d9c244170 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -46,7 +46,7 @@ import Simplex.FileTransfer.Server.Store.Postgres.Migrations (xftpServerMigratio import Simplex.FileTransfer.Server.StoreLog import Simplex.FileTransfer.Transport (XFTPErrorType (..)) import Simplex.Messaging.Agent.Store.Postgres (closeDBStore, createDBStore) -import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withRetriedTransaction, withTransaction) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationConfirmation (..)) import qualified Simplex.Messaging.Crypto as C @@ -118,7 +118,7 @@ instance FileStoreClass PostgresFileStore where pure path deleteFiles st sIds = E.uninterruptibleMask_ $ do - deleted <- fmap toFileSizes $ withTransaction (dbStore st) $ \db -> + deleted <- fmap toFileSizes $ withRetriedTransaction (dbStore st) $ \db -> DB.query db "DELETE FROM files WHERE sender_id IN ? RETURNING sender_id, file_path, file_size" (Only (In sIds)) withLog "deleteFiles" st $ \s -> mapM_ (\(sId, _, _) -> logDeleteFile s sId) deleted pure deleted @@ -200,7 +200,7 @@ rowToFileRec (sId, size, digest, sndKeyBs, path, createdAt, expiresAt, status) = withDB :: forall a. Text -> PostgresFileStore -> (DB.Connection -> IO (Either XFTPErrorType a)) -> ExceptT XFTPErrorType IO a withDB op st action = - ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr + ExceptT $ withRetriedTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either XFTPErrorType a) logErr e = logError ("STORE: " <> err) $> Left INTERNAL diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index fbbbe1fae..007aaaf5a 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2561,7 +2561,9 @@ enqueueMessageB :: forall t. Traversable t => AgentClient -> Maybe AsyncCmdId -> enqueueMessageB c cmdId_ reqs = do cfg <- asks config (_, reqMids) <- unsafeWithStore c $ \db -> do - res@(_, rs) <- mapAccumLM (\ids r -> storeSentMsg db cfg ids r `E.catchAny` \e -> (ids,) <$> handleInternal e) IM.empty reqs + res@(_, rs) <- + mapAccumLM (\ids r -> storeSentMsg db cfg ids r `catchItemError` \e -> (ids,) <$> handleInternal e) IM.empty reqs + `catchRolledBack` \e -> pure (IM.empty, Left e <$ reqs) when (all isRight rs) $ mapM_ (deleteCommand db) cmdId_ pure res forME reqMids $ submitSentMsg c @@ -2853,7 +2855,7 @@ runSmpQueueMsgDelivery c@AgentClient {subQ} sq@SndQueue {userId, connId, server, notifyDel msgId $ MERR (unId msgId) err msgIds_ <- withStore' c $ \db -> do msgIds_ <- getExpiredSndMessages db connId sq expireTs - forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchOwn_` pure () + forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchItemError` \_ -> pure () pure msgIds_ forM_ (L.nonEmpty msgIds_) $ \msgIds -> do notify $ MERRS (L.map unId msgIds) err @@ -3143,6 +3145,7 @@ deleteConnQueues c nm waitDelivery ntf rqs = do deleteQueueRecs rs = do maxErrs <- asks $ deleteErrorCount . config rs' <- rights <$> withStoreBatch' c (\db -> map (deleteQueueRec db maxErrs) rs) + forM_ [rq | ((rq, _), Just (Just _)) <- rs'] $ \RcvQueue {userId, server} -> incSMPServerStat c userId server connDeleted let delQ ((rq, _), err_) = (qConnId rq,qServer rq,queueId rq,) <$> err_ delQs_ = L.nonEmpty $ mapMaybe delQ rs' forM_ delQs_ $ \delQs -> notify ("", "", AEvt SAEConn $ DEL_RCVQS delQs) @@ -3153,14 +3156,13 @@ deleteConnQueues c nm waitDelivery ntf rqs = do Int -> (RcvQueue, Either AgentErrorType ()) -> IO ((RcvQueue, Either AgentErrorType ()), Maybe (Maybe AgentErrorType)) -- Nothing - no event, Just Nothing - no error - deleteQueueRec db maxErrs (rq@RcvQueue {userId, server}, r) = case r of + deleteQueueRec db maxErrs (rq, r) = case r of Right _ -> deleteConnRcvQueue db rq $> ((rq, r), Just Nothing) Left e | temporaryOrHostError e && deleteErrors rq + 1 < maxErrs -> incRcvDeleteErrors db rq $> ((rq, r), Nothing) | otherwise -> do deleteConnRcvQueue db rq -- attempts and successes are counted in deleteQueues function - incSMPServerStat c userId server connDeleted pure ((rq, Right ()), Just (Just e)) notify = when ntf . atomically . writeTBQueue (subQ c) connResults :: [(RcvQueue, Either AgentErrorType ())] -> Map ConnId (Either AgentErrorType ()) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 46c105eaa..137e78e70 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -173,6 +173,8 @@ module Simplex.Messaging.Agent.Client withStoreIsolation', withStoreBatch, withStoreBatch', + catchItemError, + catchRolledBack, unsafeWithStore, storeError, notifySub, @@ -255,7 +257,7 @@ import Simplex.Messaging.Agent.RetryInterval import Simplex.Messaging.Agent.Stats import Simplex.Messaging.Agent.Store import Simplex.Messaging.Agent.Store.AgentStore -import Simplex.Messaging.Agent.Store.Common (DBStore, IsolationLevel (..), withTransactionIsolation) +import Simplex.Messaging.Agent.Store.Common (DBStore, IsolationLevel (..), abortsTransaction, isTransactionConflict, withTransactionIsolation) import Simplex.Messaging.Agent.Store.DB (SQLError) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Entity @@ -2595,7 +2597,7 @@ withStore' c action = withStore c $ fmap Right . action {-# INLINE withStore' #-} withStore :: AgentClient -> (DB.Connection -> IO (Either StoreError a)) -> AM a -withStore c action = withStore_ c (`withTransaction` action) +withStore c = withStoreIsolation c ReadCommitted withStoreIsolation' :: AgentClient -> IsolationLevel -> (DB.Connection -> IO a) -> AM a withStoreIsolation' c isolation action = withStoreIsolation c isolation $ fmap Right . action @@ -2625,18 +2627,26 @@ withStore_ c transaction = do unsafeWithStore :: AgentClient -> (DB.Connection -> IO a) -> AM' a unsafeWithStore c action = do st <- asks store - liftIO $ agentOperationBracket c AODatabase (\_ -> pure ()) $ withTransaction st action + liftIO $ agentOperationBracket c AODatabase (\_ -> pure ()) $ withTransactionIsolation st ReadCommitted action withStoreBatch :: Traversable t => AgentClient -> (DB.Connection -> t (IO (Either AgentErrorType a))) -> AM' (t (Either AgentErrorType a)) withStoreBatch c actions = do st <- asks store liftIO . agentOperationBracket c AODatabase (\_ -> pure ()) $ - withTransaction st $ - mapM (`E.catch` handleInternal) . actions + withTransactionIsolation st ReadCommitted $ \db -> do + let items = actions db + mapM (`catchItemError` handleInternal) items `catchRolledBack` \e -> pure (Left e <$ items) where handleInternal :: E.SomeException -> IO (Either AgentErrorType a) handleInternal = pure . Left . INTERNAL . show +catchItemError :: IO a -> (E.SomeException -> IO a) -> IO a +catchItemError = E.catchJust $ \e -> if isTransactionConflict e || abortsTransaction e then Nothing else Just e + +catchRolledBack :: IO a -> (AgentErrorType -> IO a) -> IO a +catchRolledBack = E.catchJust $ \e -> + if abortsTransaction e && not (isTransactionConflict e) then Just (INTERNAL $ "transaction rolled back after " <> show e) else Nothing + withStoreBatch' :: Traversable t => AgentClient -> (DB.Connection -> t (IO a)) -> AM' (t (Either AgentErrorType a)) withStoreBatch' c actions = withStoreBatch c (fmap (fmap Right) . actions) {-# INLINE withStoreBatch' #-} diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 138f8f8e7..9032db05f 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -287,6 +287,7 @@ module Simplex.Messaging.Agent.Store.AgentStore fromOnlyBI, getWorkItem, getWorkItems, + catchNonConflict, ) where @@ -361,7 +362,7 @@ import Database.SQLite.Simple.QQ (sql) #endif checkConstraint :: StoreError -> IO (Either StoreError a) -> IO (Either StoreError a) -checkConstraint err action = action `E.catch` (pure . Left . handleSQLError err) +checkConstraint err action = action `catchNonConflict` (pure . Left . handleSQLError err) handleSQLError :: StoreError -> SQLError -> StoreError #if defined(dbPostgres) @@ -1179,7 +1180,12 @@ getWorkItems itemName getIds getItem markFailed = tryGetItem :: (Show i, AnyStoreError e) => String -> (i -> IO (Either e a)) -> (i -> IO ()) -> i -> ExceptT e IO a tryGetItem itemName getItem markFailed itemId = ExceptT getItem' `catchE` \e -> mark >> throwE e where - getItem' = E.handleJust workItemError (pure . Left . fromSomeException) $ getItem itemId + getItem' = getItem itemId `catchNonConflict` readError + readError e +#if defined(dbPostgres) + | abortsTransaction e = E.throwIO $ RetryAfter (markFailed itemId) $ itemName <> " ID " <> show itemId <> " read error: " <> show e +#endif + | otherwise = pure $ Left $ fromSomeException e mark = handleWrkErr itemName ("markFailed ID " <> show itemId) $ markFailed itemId -- Errors caught by this function will suspend worker as if there is no more work, @@ -1189,8 +1195,11 @@ handleWrkErr itemName opName action = ExceptT $ first mkError <$> E.tryJust work mkError :: E.SomeException -> e mkError e = mkWorkItemError $ itemName <> " " <> opName <> " error: " <> show e -workItemError :: E.SomeException -> Maybe E.SomeException -workItemError e = if isTransactionConflict e then Nothing else Just e +workItemError :: E.Exception e => e -> Maybe e +workItemError e = if isTransactionConflict (E.toException e) then Nothing else Just e + +catchNonConflict :: E.Exception e => IO a -> (e -> IO a) -> IO a +catchNonConflict = E.catchJust workItemError updatePendingMsgRIState :: DB.Connection -> ConnId -> InternalId -> RI2State -> IO () updatePendingMsgRIState db connId msgId RI2State {slowInterval, fastInterval} = @@ -1644,10 +1653,17 @@ createCommand db corrId connId srv_ cmd = runExceptT $ do (host_, port_, serverKeyHash_) <- serverFields createdAt <- liftIO getCurrentTime liftIO . E.handle handleErr $ +#if defined(dbPostgres) + DB.execute + db + "INSERT INTO commands (host, port, corr_id, conn_id, command_tag, command, server_key_hash, created_at) SELECT ?, ?, ?, conn_id, ?, ?, ?::BYTEA, ?::TIMESTAMPTZ FROM connections WHERE conn_id = ? FOR KEY SHARE" + (host_, port_, Binary corrId, cmdTag, cmd, serverKeyHash_, createdAt, connId) +#else DB.execute db "INSERT INTO commands (host, port, corr_id, conn_id, command_tag, command, server_key_hash, created_at) VALUES (?,?,?,?,?,?,?,?)" (host_, port_, Binary corrId, connId, cmdTag, cmd, serverKeyHash_, createdAt) +#endif where cmdTag = agentCommandTag cmd #if defined(dbPostgres) @@ -2106,7 +2122,7 @@ getNextNtfSubNTFActions db ntfServer@(NtfServer ntfHost ntfPort _) ntfBatchSize markNtfSubActionNtfFailed_ :: DB.Connection -> ConnId -> IO () markNtfSubActionNtfFailed_ db connId = - DB.execute db "UPDATE ntf_subscriptions SET ntf_failed = 1 where conn_id = ?" (Only connId) + DB.execute db "UPDATE ntf_subscriptions SET ntf_failed = 1, updated_by_supervisor = 0 where conn_id = ?" (Only connId) getNextNtfSubSMPActions :: DB.Connection -> SMPServer -> Int -> IO (Either StoreError [Either StoreError (NtfSubSMPAction, NtfSubscription)]) getNextNtfSubSMPActions db smpServer@(SMPServer smpHost smpPort _) ntfBatchSize = @@ -2151,7 +2167,7 @@ getNextNtfSubSMPActions db smpServer@(SMPServer smpHost smpPort _) ntfBatchSize markNtfSubActionSMPFailed_ :: DB.Connection -> ConnId -> IO () markNtfSubActionSMPFailed_ db connId = - DB.execute db "UPDATE ntf_subscriptions SET smp_failed = 1 where conn_id = ?" (Only connId) + DB.execute db "UPDATE ntf_subscriptions SET smp_failed = 1, updated_by_supervisor = 0 where conn_id = ?" (Only connId) markUpdatedByWorker :: DB.Connection -> ConnId -> IO () markUpdatedByWorker db connId = @@ -3163,7 +3179,9 @@ createWithRandomId' db gVar create = tryCreate 3 #if defined(dbPostgres) handleErr n e = case constraintViolation e of Just _ -> tryCreate (n - 1) - Nothing -> pure . Left . SEInternal $ bshow e + Nothing + | isTransactionConflict (E.toException e) -> E.throwIO e + | otherwise -> pure . Left . SEInternal $ bshow e #else handleErr n e | SQL.sqlError e == SQL.ErrorConstraint = tryCreate (n - 1) diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs index 96eed47e9..9b68ab124 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Agent.Store.Postgres.Common DBStorePool (..), DBOpts (..), IsolationLevel (..), + RetryAfter (..), newDBStorePool, withConnection, withConnection', @@ -17,12 +18,15 @@ module Simplex.Messaging.Agent.Store.Postgres.Common withTransaction', withTransactionPriority, withTransactionIsolation, + withRetriedTransaction, + withRetriedTransactionPriority, isTransactionConflict, + abortsTransaction, withSavepoint, ) where -import Control.Logger.Simple (logWarn) +import Control.Logger.Simple (logError, logWarn) import Control.Monad (void) import Control.Concurrent.MVar import Control.Concurrent.STM @@ -107,15 +111,41 @@ withTransactionPriority st priority action = withConnectionPriority st priority transaction conn = PSQL.withTransaction conn $ action conn -- isolation for agent transactions; postgresql-simple is not a dependency of SQLite builds -data IsolationLevel = RepeatableRead +data IsolationLevel = ReadCommitted | RepeatableRead + +data RetryAfter = RetryAfter (IO ()) String + +instance Show RetryAfter where + show (RetryAfter _ reason) = reason + +instance E.Exception RetryAfter withTransactionIsolation :: DBStore -> IsolationLevel -> (PSQL.Connection -> IO a) -> IO a -withTransactionIsolation st isolation action = withConnection st transaction +withTransactionIsolation st isolation action = withConnection st $ transaction (3 :: Int) where - transaction conn = retryTransaction 3 $ PSQL.withTransactionLevel level conn $ action conn + transaction n conn + | n > 0 = + E.try (inTransaction conn $ action conn) >>= \case + Right r -> pure r + Left e@(RetryAfter prepare _) -> do + logError $ "transaction rolled back after " <> tshow e + inTransaction conn prepare + transaction (n - 1) conn + | otherwise = inTransaction conn $ action conn + inTransaction conn = retryTransaction 3 . PSQL.withTransactionLevel level conn level = case isolation of + ReadCommitted -> PSQL.ReadCommitted RepeatableRead -> PSQL.RepeatableRead +withRetriedTransaction :: DBStore -> (PSQL.Connection -> IO a) -> IO a +withRetriedTransaction st = withRetriedTransactionPriority st False +{-# INLINE withRetriedTransaction #-} + +withRetriedTransactionPriority :: DBStore -> Bool -> (PSQL.Connection -> IO a) -> IO a +withRetriedTransactionPriority st priority action = withConnectionPriority st priority transaction + where + transaction conn = retryTransaction 3 $ PSQL.withTransaction conn $ action conn + retryTransaction :: Int -> IO a -> IO a retryTransaction n transaction | n > 0 = E.tryJust conflict transaction >>= either retryAfter pure @@ -129,6 +159,11 @@ retryTransaction n transaction isTransactionConflict :: E.SomeException -> Bool isTransactionConflict = maybe False conflictState . E.fromException +abortsTransaction :: E.SomeException -> Bool +abortsTransaction e = case E.fromException e of + Just (_ :: PSQL.SqlError) -> True + Nothing -> False + conflictState :: PSQL.SqlError -> Bool conflictState = (`elem` ["40001", "40P01"]) . PSQL.sqlState diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs index 46ea836dc..28160e64d 100644 --- a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs @@ -16,6 +16,7 @@ module Simplex.Messaging.Agent.Store.SQLite.Common withTransactionPriority, withTransactionIsolation, isTransactionConflict, + abortsTransaction, withSavepoint, dbBusyLoop, storeKey, @@ -109,7 +110,7 @@ withTransactionPriority st@DBStore {dbClosed} priority action = withConnectionPr transaction db@DB.Connection {conn} = SQL.withImmediateTransaction conn $ action db -- isolation for agent transactions; postgresql-simple is not a dependency of SQLite builds -data IsolationLevel = RepeatableRead +data IsolationLevel = ReadCommitted | RepeatableRead withTransactionIsolation :: DBStore -> IsolationLevel -> (DB.Connection -> IO a) -> IO a withTransactionIsolation st _ = withTransaction st @@ -117,6 +118,9 @@ withTransactionIsolation st _ = withTransaction st isTransactionConflict :: E.SomeException -> Bool isTransactionConflict _ = False +abortsTransaction :: E.SomeException -> Bool +abortsTransaction _ = False + -- No-op for SQLite, just tries the action. -- This provides a consistent interface with the PostgreSQL version. withSavepoint :: DB.Connection -> SQL.Query -> IO a -> IO (Either SQLError a) diff --git a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs index fd739993b..233a8b68a 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs +++ b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs @@ -757,7 +757,7 @@ withDB op st = withDB_ op st False withDB_ :: forall a. Text -> NtfPostgresStore -> Bool -> (DB.Connection -> IO (Either ErrorType a)) -> IO (Either ErrorType a) withDB_ op st priority action = - E.uninterruptibleMask_ $ E.try (withTransactionPriority (dbStore st) priority action) >>= either logErr pure + E.uninterruptibleMask_ $ E.try (withRetriedTransactionPriority (dbStore st) priority action) >>= either logErr pure where logErr :: E.SomeException -> IO (Either ErrorType a) logErr e = logError ("STORE: " <> err) $> Left (STORE err) @@ -766,7 +766,7 @@ withDB_ op st priority action = withClientDB :: Text -> NtfPostgresStore -> (DB.Connection -> IO a) -> IO (Either SMPClientError a) withClientDB op st action = - E.uninterruptibleMask_ $ E.try (withTransaction (dbStore st) action) >>= bimapM logErr pure + E.uninterruptibleMask_ $ E.try (withRetriedTransaction (dbStore st) action) >>= bimapM logErr pure where logErr :: E.SomeException -> IO SMPClientError logErr e = logError ("STORE: " <> op <> ", withDB, " <> tshow e) $> PCEIOError (E.displayException e) diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 9c6e8d84a..5a11fbbf6 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -636,7 +636,7 @@ withDB' op st action = withDB op st $ fmap Right . action withDB :: forall a q. Text -> PostgresQueueStore q -> (DB.Connection -> IO (Either ErrorType a)) -> ExceptT ErrorType IO a withDB op st action = - ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr + ExceptT $ withRetriedTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either ErrorType a) logErr e = logError ("STORE: " <> err) $> Left (STORE err) diff --git a/tests/AgentTests.hs b/tests/AgentTests.hs index cb14f5fff..44b664169 100644 --- a/tests/AgentTests.hs +++ b/tests/AgentTests.hs @@ -20,7 +20,7 @@ import Simplex.Messaging.Transport (ASrvTransport) import Test.Hspec hiding (fit, it) #if defined(dbPostgres) -import AgentTests.FunctionalAPITests (workItemReadTests) +import AgentTests.FunctionalAPITests (abortedTransactionTests, transactionDeadlockTests, workItemReadTests) #else import AgentTests.SQLiteTests (storeTests) #endif @@ -38,6 +38,8 @@ agentCoreTests = do describe "resolve names" resolveNameTests #if defined(dbPostgres) describe "Work item reads" workItemReadTests + describe "Transaction deadlocks" transactionDeadlockTests + describe "Aborted transactions" abortedTransactionTests #endif agentTests :: (ASrvTransport, AStoreType) -> Spec diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index c06b7c44d..36688ba40 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -59,6 +59,8 @@ module AgentTests.FunctionalAPITests testServerInformation, #if defined(dbPostgres) workItemReadTests, + transactionDeadlockTests, + abortedTransactionTests, #endif ) where @@ -137,11 +139,12 @@ import XFTPClient (testXFTPServer, withXFTPServerThreadOn) #if defined(dbPostgres) import Database.PostgreSQL.Simple (Only (..), Query) import Fixtures -import Simplex.Messaging.Agent.Client (withStoreIsolation', withWork, withWorkItems) +import Simplex.Messaging.Agent.Client (withStore, withStore', withStoreBatch', withStoreIsolation', withWork, withWorkItems) import Simplex.Messaging.Agent.Env.SQLite (AM) -import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), RcvQueue, RcvQueueSub (..), ServiceAssoc) -import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNtfSubscription, createServer, createSndFile, deleteClientService, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile) +import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), ConnData (..), InternalId (..), RcvQueue, RcvQueueSub (..), ServiceAssoc) +import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNewConn, createNtfSubscription, createServer, createSndFile, createSndMsgDelivery, createUserRecord, deleteClientService, deleteConn, deleteSndMsgDelivery, deleteUserRecord, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile, updateNewConnSnd) import Simplex.Messaging.Agent.Store.Common (IsolationLevel (..)) +import Simplex.Messaging.Agent.Store.Entity (DBEntityId' (..)) import Simplex.Messaging.Notifications.Types (NtfAgentSubStatus (NASNew), NtfSubAction (NSANtf, NSASMP), NtfSubNTFAction (NSACreate), NtfSubSMPAction (NSASmpKey), newNtfSubscription) #endif #if defined(dbServerPostgres) @@ -560,6 +563,9 @@ functionalAPITests ps = do describe "Batch send messages" $ do it "should send multiple messages to the same connection" $ withSmpServer ps testSendMessagesB it "should send messages to the 2 connections" $ withSmpServer ps testSendMessagesB2 +#if defined(dbPostgres) + it "should report every message of a batch rolled back after a database error" $ withSmpServer ps testSendMessagesRolledBack +#endif describe "Async agent commands" $ do describe "connect using async agent commands" $ testBasicMatrix2 ps testAsyncCommands @@ -5286,10 +5292,35 @@ workItemReadTests = do let st = store $ agentEnv a withTransaction st $ \db -> createCmd db >> DB.execute_ db "UPDATE commands SET command = 'bad'::bytea" doWork <- newTMVarIO () - runReaderT (runExceptT $ readCommand a doWork $ \_ -> pure ()) (agentEnv a) `shouldReturn` Right () + runAM a (readCommand a doWork $ \_ -> pure ()) `shouldReturn` Right () events <- atomically $ flushTBQueue $ subQ a length (filter workerError events) `shouldBe` 1 withTransaction st (`DB.query_` "SELECT failed FROM commands") `shouldReturn` [Only (1 :: Int)] + it "should mark a command failed when a server error aborts its read" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createCmd db + DB.execute_ db "CREATE FUNCTION fail_read() RETURNS BOOLEAN LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END $$; ALTER TABLE connections ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY; CREATE POLICY fail_read ON connections FOR SELECT USING (fail_read())" + doWork <- newTMVarIO () + runAM a (readCommand a doWork $ \_ -> pure ()) `shouldReturn` Right () + events <- atomically $ flushTBQueue $ subQ a + filter workerError events `shouldBe` [] + withTransaction st (`DB.query_` "SELECT failed FROM commands") `shouldReturn` [Only (1 :: Int)] + it "should report INTERNAL when a server error aborts the read of a command that stays unmarked" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createCmd db + DB.execute_ db "CREATE FUNCTION fail_read() RETURNS BOOLEAN LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END $$; ALTER TABLE connections ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY; CREATE POLICY fail_read ON connections FOR SELECT USING (fail_read())" + DB.execute_ db "CREATE FUNCTION skip_update() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END $$; CREATE TRIGGER skip_update BEFORE UPDATE ON commands FOR EACH ROW EXECUTE FUNCTION skip_update()" + doWork <- newTMVarIO () + Just (Left (A.INTERNAL e)) <- timeout 5000000 $ runAM a (readCommand a doWork $ \_ -> pure ()) + e `shouldContain` "sqlState = \\\"XX001\\\"" + it "should mark a ntf subscription failed when a server error aborts its read in a batch" $ + readBatchAfterServerError (NSANtf NSACreate) "ntf_failed" (readNtfActions testNtfServer) + it "should mark a ntf SMP action failed when a server error aborts its read in a batch" $ + readBatchAfterServerError (NSASMP NSASmpKey) "smp_failed" (readSMPActions testSMPServer) it "should retry the read 3 times on the same connection after serialization failures" $ do (r, pids) <- readWithErrors 3 "40001" r `shouldBe` Right () @@ -5323,6 +5354,22 @@ workItemReadTests = do createNtfSubscription db (newNtfSubscription 1 "conn1" testSMPServer Nothing testNtfServer NASNew) action `shouldReturn` Right () readNtfActions srv a doWork = withWorkItems a doWork $ withStoreIsolation' a RepeatableRead $ \db -> getNextNtfSubNTFActions db srv 10 readSMPActions srv a doWork = withWorkItems a doWork $ withStoreIsolation' a RepeatableRead $ \db -> getNextNtfSubSMPActions db srv 10 + readBatchAfterServerError :: HasTestEnv => NtfSubAction -> Query -> (AgentClient -> TMVar () -> (NonEmpty a -> AM ()) -> AM ()) -> IO () + readBatchAfterServerError action failedColumn readItems = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createNtfSub action db + DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (?,?,?)" (1 :: Int64, "conn2" :: ConnId, SCMInvitation) + createNtfSubscription db (newNtfSubscription 1 "conn2" testSMPServer Nothing testNtfServer NASNew) action `shouldReturn` Right () + DB.execute_ db $ "UPDATE ntf_subscriptions SET updated_by_supervisor = 1; CREATE FUNCTION fail_update() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.conn_id = 'conn1' AND NEW." <> failedColumn <> " = OLD." <> failedColumn <> " THEN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_update BEFORE UPDATE ON ntf_subscriptions FOR EACH ROW EXECUTE FUNCTION fail_update()" + doWork <- newTMVarIO () + itemsRead <- newTVarIO (0 :: Int) + runAM a (readItems a doWork $ atomically . writeTVar itemsRead . length) `shouldReturn` Right () + readTVarIO itemsRead `shouldReturn` 1 + events <- atomically $ flushTBQueue $ subQ a + filter workerError events `shouldBe` [] + withTransaction st (\db -> DB.query_ db $ "SELECT conn_id, " <> failedColumn <> ", updated_by_supervisor FROM ntf_subscriptions ORDER BY conn_id") + `shouldReturn` [("conn1" :: ConnId, 1 :: Int, 0 :: Int), ("conn2", 0, 0)] createSndFile' :: DB.Connection -> IO () createSndFile' db = do g <- C.newRandom @@ -5347,7 +5394,7 @@ readWhileDeleting createItem lockItem waitingQuery deleteItem readItem = withAge reading <- withTransaction st $ \db -> do lockItem db [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" - r <- async $ runReaderT (runExceptT $ readItem a doWork $ \_ -> atomically $ writeTVar itemRead True) (agentEnv a) + r <- async $ runAM a (readItem a doWork $ \_ -> atomically $ writeTVar itemRead True) waitForLock st holder waitingQuery DB.execute_ db deleteItem pure r @@ -5365,7 +5412,7 @@ workerError (_, _, AEvt _ e) = case e of readWithErrors :: HasTestEnv => Int -> Query -> IO (Either AgentErrorType (), [Int]) readWithErrors failures errCode = withAgent 1 agentCfg initAgentServers testDB $ \a -> do pids <- newIORef [] - r <- runReaderT (runExceptT $ withStoreIsolation' a RepeatableRead $ readItem pids) (agentEnv a) + r <- runAM a (withStoreIsolation' a RepeatableRead $ readItem pids) (r,) <$> readIORef pids where readItem pids db = do @@ -5381,6 +5428,111 @@ waitForLock st holder waitingQuery = timeout 5000000 waitLoop `shouldReturn` Jus withTransaction st $ \db -> DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE ? = ANY (pg_blocking_pids(pid)) AND position(? IN query) > 0)" (holder, waitingQuery) unless waiting $ threadDelay 10000 >> waitLoop + +transactionDeadlockTests :: Spec +transactionDeadlockTests = do + it "should retry deadlocked deletions of a delivered message and its user" $ + deleteWithDeliveredMessage "DELETE FROM users" deleteUserInTransaction 0 + it "should retry deadlocked deletions of a delivered message and its user after deadlock_timeout" $ + deleteWithDeliveredMessage "DELETE FROM users" deleteUserInTransaction 2000000 + it "should retry deadlocked deletions of a delivered message and its connection in a batch" $ + deleteWithDeliveredMessage "DELETE FROM connections" deleteConnInBatch 2000000 + it "should retry the creation of a connection after a conflict" $ + createConnAfterConflict "conn1" `shouldReturn` Right "conn1" + it "should retry the creation of a connection with a random ID after a conflict" $ + isRight <$> createConnAfterConflict "" `shouldReturn` True + where + deleteUserInTransaction a recordPid userId _ = runAM a (withStore a $ \db -> recordPid db >> deleteUserRecord db userId) `shouldReturn` Right () + deleteConnInBatch a recordPid _ connId = runReaderT (withStoreBatch' a $ \db -> [recordPid db >> deleteConn db Nothing connId]) (agentEnv a) `shouldReturn` ([Right (Just connId)] :: [Either AgentErrorType (Maybe ConnId)]) + +abortedTransactionTests :: Spec +abortedTransactionTests = do + it "should keep the transaction that creates a command for a deleted connection" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + runAM a (withStore a $ \db -> createUserRecord db >> createCommand db "1" "deleted" Nothing (AClientCommand $ NEW True (ACM SCMInvitation) IKPQOn SMSubscribe False)) `shouldReturn` Right () + withTransaction (store $ agentEnv a) (`DB.query_` "SELECT count(*) FROM users") `shouldReturn` [Only (2 :: Int)] + it "should report every item of a batch rolled back after a database error" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + rs <- runReaderT (withStoreBatch' a $ \db -> [void $ createUserRecord db, DB.execute_ db "DO $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = '23505'; END $$"]) (agentEnv a) + map isRight rs `shouldBe` [False, False] + withTransaction (store $ agentEnv a) (`DB.query_` "SELECT count(*) FROM users") `shouldReturn` [Only (1 :: Int)] + +testSendMessagesRolledBack :: HasTestEnv => IO () +testSendMessagesRolledBack = withAgentClients2 $ \a b -> do + (_, bId1) <- runRight $ makeConnection a b + (_, bId2) <- runRight $ makeConnection a b + withTransaction (store $ agentEnv a) $ \db -> do + DB.execute_ db "CREATE TABLE failing_conns (conn_id BYTEA); CREATE FUNCTION fail_snd_message() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.conn_id IN (SELECT conn_id FROM failing_conns) THEN RAISE EXCEPTION 'test' USING ERRCODE = '23505'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_snd_message BEFORE INSERT ON snd_messages FOR EACH ROW EXECUTE FUNCTION fail_snd_message()" + DB.execute db "INSERT INTO failing_conns (conn_id) VALUES (?)" (Only bId2) + rs <- runRight $ sendMessages a [(bId1, PQEncOn, SMP.noMsgFlags, vrValue "hello"), (bId2, PQEncOn, SMP.noMsgFlags, vrValue "hello")] + map isRight rs `shouldBe` [False, False] + +runAM :: AgentClient -> AM a -> IO (Either AgentErrorType a) +runAM a action = runReaderT (runExceptT action) (agentEnv a) + +createConnAfterConflict :: HasTestEnv => ConnId -> IO (Either AgentErrorType ConnId) +createConnAfterConflict connId = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + withTransaction (store $ agentEnv a) (`DB.execute_` "CREATE SEQUENCE inserts; CREATE FUNCTION fail_first_insert() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF nextval('inserts') = 1 THEN RAISE EXCEPTION 'test' USING ERRCODE = '40P01'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_first_insert BEFORE INSERT ON connections FOR EACH ROW EXECUTE FUNCTION fail_first_insert()") + g <- C.newRandom + runAM a . withStore a $ \db -> + createNewConn db g ConnData {userId = 1, connId, connAgentVersion = VersionSMPA 1, enableNtfs = True, lastExternalSndId = 0, deleted = False, ratchetSyncState = RSOk, pqSupport = PQSupportOn, serviceRequestExpiresAt = Nothing} SCMInvitation + +deleteWithDeliveredMessage :: HasTestEnv => String -> (AgentClient -> (DB.Connection -> IO ()) -> UserId -> ConnId -> IO ()) -> Int -> IO () +deleteWithDeliveredMessage deleteQuery deleteRecord lockTime = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + g <- C.newRandom + (userId, sq) <- withTransaction st $ createMessage g + msgPids <- newIORef [] + deleterPids <- newIORef [] + (deletingMsg, deleting) <- withTransaction st $ \db -> do + void (DB.query db "SELECT 1 FROM commands WHERE conn_id = ? FOR UPDATE" (Only connId) :: IO [Only Int]) + [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" + deleting <- async $ deleteRecord a (recordPid deleterPids) userId connId + waitForLock st holder deleteQuery + [deleter] <- readIORef deleterPids + deletingMsg <- async $ runAM a (withStore' a $ \db' -> recordPid msgPids db' >> deleteSndMsgDelivery db' connId sq (InternalId 1) False) `shouldReturn` Right () + waitForLock st deleter "DELETE FROM messages" + threadDelay lockTime + pure (deletingMsg, deleting) + wait deletingMsg + wait deleting + withTransaction st (\db -> DB.query db "SELECT count(*) FROM connections WHERE conn_id = ?" (Only connId)) `shouldReturn` [Only (0 :: Int)] + attempts <- (+) <$> (length <$> readIORef msgPids) <*> (length <$> readIORef deleterPids) + attempts `shouldSatisfy` (> 2) + where + connId = "conn1" :: ConnId + recordPid :: IORef [Int] -> DB.Connection -> IO () + recordPid pids db = do + [Only pid] <- DB.query_ db "SELECT pg_backend_pid()" + atomicModifyIORef' pids $ \ps -> (pid : ps, ()) + createMessage g db = do + userId <- createUserRecord db + DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (?,?,?)" (userId, connId, SCMInvitation) + (_, sndPrivateKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPubKey, dhPrivKey) <- atomically $ C.generateKeyPair g + let newSq = + SndQueue + { userId, + connId, + server = testSMPServer, + sndId = SMP.EntityId "1234", + queueMode = Just SMP.QMMessaging, + sndPrivateKey, + e2ePubKey = Nothing, + e2eDhSecret = C.dh' dhPubKey dhPrivKey, + status = New, + dbQueueId = DBNewEntity, + primary = True, + dbReplaceQueueId = Nothing, + sndSwchStatus = Nothing, + smpClientVersion = SMP.VersionSMPC 1 + } + Right sq <- updateNewConnSnd db connId newSq + DB.execute db "INSERT INTO messages (conn_id, internal_id, internal_ts, internal_snd_id, msg_type) VALUES (?, 1, now(), 1, '')" (Only connId) + DB.execute db "INSERT INTO snd_messages (conn_id, internal_snd_id, internal_id, internal_hash) VALUES (?, 1, 1, '')" (Only connId) + createSndMsgDelivery db sq (InternalId 1) + createCommand db "1" connId Nothing (AClientCommand $ NEW True (ACM SCMInvitation) IKPQOn SMSubscribe False) `shouldReturn` Right () + pure (userId, sq) #endif testClientServiceConnection :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index 92448dd6e..3ee9d1c71 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -53,7 +53,7 @@ import Simplex.Messaging.Agent.Store.Postgres.Common import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) import Simplex.Messaging.Server.MsgStore.Postgres import Simplex.Messaging.Server.QueueStore.Postgres -import SMPClient (testStoreDBOpts) +import SMPClient (deadlockOnce, testStoreDBOpts) #endif msgStoreTests :: Spec @@ -70,6 +70,7 @@ msgStoreTests = do it "should expire messages across commit batches" $ withMsgStore testPostgresStoreConfig testExpireMessagesInBatches it "should fail database operations after the store is closed" $ withMsgStore testPostgresStoreConfig testClosedStore it "should time out database operation" $ withMsgStore testPostgresStoreConfig testDBOperationTimeout + it "should retry a message write aborted by a deadlock" $ withMsgStore testPostgresStoreConfig testWriteMsgDeadlock #endif describe "Notification store" $ do it "should remove keys of expired notifications" testExpireNtfs @@ -507,4 +508,15 @@ testClosedStore ms = do testDBOperationTimeout :: PostgresMsgStore -> IO () testDBOperationTimeout ms = timeout 100000 (runExceptT $ withDB' "test" (queueStore ms) $ \_ -> threadDelay 500000) `shouldReturn` Nothing + +testWriteMsgDeadlock :: PostgresMsgStore -> IO () +testWriteMsgDeadlock ms = do + g <- C.newRandom + (rId, qr) <- testNewQueueRec g QMMessaging + void $ withTransaction (dbStore $ queueStore ms) $ \db -> DB.execute_ db $ deadlockOnce "INSERT ON messages" + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + Just (_, True) <- writeMsg ms q True =<< mkMessage "message 1" + Msg "message 1" <- tryPeekMsg ms q + checkQueueSize ms q (1, True) #endif diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index b7c415563..07141ea8c 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -8,12 +8,14 @@ import Control.Monad import qualified Data.ByteString.Char8 as B import Data.List.NonEmpty (NonEmpty (..)) import Data.Word (Word32) +import qualified Database.PostgreSQL.Simple as DB +import SMPClient (deadlockOnce) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store -import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore, importFileStore, exportFileStore) -import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..)) +import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore) import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, readWriteFileStore, serverFileName, writeFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (withTransaction) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Protocol (BlockingInfo (..), BlockingReason (..), EntityId (..)) import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) @@ -47,6 +49,8 @@ xftpStoreTests = do it "should log each file deletion once" testDeleteFilesLog it "should return at most limit expired files of both kinds" testExpiredFilesTotalLimit it "should compute committed used storage and file count" testStorageAndCount + it "should retry a file creation aborted by a deadlock" testAddFileDeadlock + it "should retry a file deletion aborted by a deadlock" testDeleteFilesDeadlock xftpMigrationTests :: Spec xftpMigrationTests = describe "XFTP migration round-trip" $ do @@ -315,6 +319,23 @@ testStorageAndCountForStore st = do getUsedStorage st `shouldReturn` (0, 0) getFileCount st `shouldReturn` 0 +testAddFileDeadlock :: HasTestEnv => Expectation +testAddFileDeadlock = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ withTransaction (dbStore st) $ \db -> DB.execute_ db $ deadlockOnce "INSERT ON files" + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + getFile st SFSender testSenderId >>= (`shouldBe` Right sndKey) . fmap snd + +testDeleteFilesDeadlock :: HasTestEnv => Expectation +testDeleteFilesDeadlock = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + void $ withTransaction (dbStore st) $ \db -> DB.execute_ db $ deadlockOnce "DELETE ON files" + deleteFiles st [testSenderId] + getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) + -- Migration round-trip test testMigrationRoundTrip :: HasTestEnv => Expectation diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index 947142402..a554d1eef 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -14,6 +14,7 @@ module NtfServerTests where import Control.Concurrent (threadDelay) +import Control.Exception (bracket) import Control.Monad (forM, unless, void) import qualified Data.Aeson as J import qualified Data.Aeson.Types as JT @@ -42,6 +43,7 @@ import ServerTests ) import qualified Simplex.Messaging.Agent.Protocol as AP import Simplex.Messaging.Agent.RetryInterval (RetryInterval (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (withTransaction) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Client.Agent (SMPClientAgentConfig (..)) import qualified Simplex.Messaging.Crypto as C @@ -49,7 +51,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Env (NtfServerConfig (..)) import Simplex.Messaging.Notifications.Server.Push.APNS -import Simplex.Messaging.Notifications.Server.Store.Postgres (closeNtfDbStore, newNtfDbStore, withDB') +import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfPostgresStore (dbStore), closeNtfDbStore, newNtfDbStore, withClientDB, withDB') import Simplex.Messaging.Notifications.Transport (THandleNTF) import Simplex.Messaging.Parsers (parse, parseAll) import Simplex.Messaging.Protocol hiding (notification) @@ -82,6 +84,20 @@ ntfServerTests ps@(t, _) = do describe "Notification service" $ do it "resubscribes queues when service ID changes" $ testResubscribeOnServiceIdChange ps +ntfStoreTests :: Spec +ntfStoreTests = do + it "should retry a transaction aborted by a deadlock" $ + withDeadlockedTokens $ \st -> withDB' "test" st updateTokens `shouldReturn` Right 0 + it "should retry a client transaction aborted by a deadlock" $ + withDeadlockedTokens $ \st -> withClientDB "test" st updateTokens `shouldReturn` Right 0 + where + updateTokens db = PSQL.execute_ db "UPDATE tokens SET cron_interval = 0" + +withDeadlockedTokens :: HasTestEnv => (NtfPostgresStore -> IO ()) -> IO () +withDeadlockedTokens test = bracket (newNtfDbStore ntfTestDBCfg) closeNtfDbStore $ \st -> do + void $ withTransaction (dbStore st) $ \db -> PSQL.execute_ db $ deadlockOnce "UPDATE ON tokens" + test st + ntfSyntaxTests :: ASrvTransport -> Spec ntfSyntaxTests (ATransport t) = do it "unknown command" $ ("", "abcd", "1234", ('H', 'E', 'L', 'L', 'O')) >#> ("", "abcd", "1234", NRErr $ CMD UNKNOWN) diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 80fc06fef..9bfa04d10 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -53,7 +53,7 @@ import UnliftIO.Timeout (timeout) import Util #if defined(dbServerPostgres) -import Database.PostgreSQL.Simple (defaultConnectInfo) +import Database.PostgreSQL.Simple (Query, defaultConnectInfo) import Simplex.Messaging.Server.QueueStore.Postgres.Config (PostgresStoreCfg (..)) #endif @@ -125,6 +125,9 @@ testServerDBConnectInfo = connectUser = "test_server_user", connectDatabase = "test_server_db" } + +deadlockOnce :: Query -> Query +deadlockOnce event = "CREATE SEQUENCE deadlocks; CREATE FUNCTION deadlock() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF nextval('deadlocks') = 1 THEN RAISE EXCEPTION 'test' USING ERRCODE = '40P01'; END IF; RETURN NULL; END $$; CREATE TRIGGER deadlock AFTER " <> event <> " FOR EACH STATEMENT EXECUTE FUNCTION deadlock()" #endif testStoreMsgsFile :: HasTestEnv => FilePath diff --git a/tests/Test.hs b/tests/Test.hs index 535780ae6..346c24e82 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -53,7 +53,7 @@ import AgentTests.SchemaDump (schemaDumpTest) #if defined(dbServerPostgres) import CoreTests.XFTPStoreTests (xftpStoreTests, xftpMigrationTests) -import NtfServerTests (ntfServerTests) +import NtfServerTests (ntfServerTests, ntfStoreTests) import NtfClient (ntfTestServerDBConnectInfo, ntfTestServerDBOpts) import SMPClient (testServerDBConnectInfo, testServerDBOpts) import SMPProxyTests (smpProxyPostgresTests) @@ -122,6 +122,7 @@ main = do ntfServerTests (transport @TLS, ASType SQSMemory SMSMemory) describe "Notifications server (SMP server: postgres-only store)" $ ntfServerTests (transport @TLS, ASType SQSPostgres SMSPostgres) + describe "Notifications store" ntfStoreTests describe "SMP client agent, server postgres-only message store" $ agentTests (transport @TLS, ASType SQSPostgres SMSPostgres) describe "SMP proxy, postgres-only message store" $ do before (pure $ ASType SQSPostgres SMSPostgres) smpProxyTests From 36173d9606b29426e546491f2a69c1bdea7dd061 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 03:38:44 -0500 Subject: [PATCH 022/159] servers: preserve store changes and cancellation semantics Consolidated from PR #2038, retaining deadlock retries and file-count fixes. --- src/Simplex/FileTransfer/Server.hs | 11 +++--- .../FileTransfer/Server/Store/Postgres.hs | 1 + src/Simplex/Messaging/Server.hs | 2 +- .../Messaging/Server/QueueStore/STM.hs | 28 +++++++------- tests/CoreTests/MsgStoreTests.hs | 38 ++++++++++++++++++- tests/CoreTests/XFTPStoreTests.hs | 15 +++++++- tests/Util.hs | 28 ++++++++++++-- 7 files changed, 96 insertions(+), 27 deletions(-) diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index ca24a9c9e..72e10d502 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -537,7 +537,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case createFile :: FileInfo -> NonEmpty RcvPublicAuthKey -> Maybe Word32 -> M s FileResponse createFile file rks storageHours = do st <- asks fileStore - r <- runExceptT $ do + r <- mask_ $ runExceptT $ do sizes <- asks $ allowedChunkSizes . config unless (size file `elem` sizes) $ throwE SIZE now <- liftIO getSystemSeconds @@ -582,7 +582,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case addFileRecipients :: XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s FileResponse addFileRecipients sId rks = do st <- asks fileStore - r <- runExceptT $ do + r <- mask_ $ runExceptT $ do rcps <- ExceptT $ addRecipientsRetry st 3 sId rks lift $ withFileLog $ \sl -> logAddRecipients sl sId rcps stats <- asks serverStats @@ -703,13 +703,12 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case deleteServerFile_ :: FileStoreClass s => FileRec -> M s (Either XFTPErrorType ()) deleteServerFile_ fr@FileRec {senderId} = mask_ $ do - r <- deleteOrBlockServerFile_ fr filesDeleted (`deleteFile` senderId) - forM_ r $ \_ -> withFileLog (`logDeleteFile` senderId) - pure r + withFileLog (`logDeleteFile` senderId) + deleteOrBlockServerFile_ fr filesDeleted (`deleteFile` senderId) -- this also deletes the file from storage, but doesn't include it in delete statistics blockServerFile :: FileStoreClass s => FileRec -> BlockingInfo -> M s (Either XFTPErrorType ()) -blockServerFile fr@FileRec {senderId} info = do +blockServerFile fr@FileRec {senderId} info = mask_ $ do withFileLog $ \sl -> logBlockFile sl senderId info deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index d9c244170..dfb15567b 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -11,6 +11,7 @@ module Simplex.FileTransfer.Server.Store.Postgres ( PostgresFileStore (..), importFileStore, exportFileStore, + withDB', ) where diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 314069373..ff364a9ae 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1932,7 +1932,7 @@ client if qCnt == expectedCnt then logNote $ logMsg <> tshow qCnt <> " queues)" else logError $ logMsg <> "expected " <> tshow expectedCnt <> "," <> tshow qCnt <> " queues)" - Left e -> do + Left e -> whenM (readTVarIO $ connected clnt) $ do logError $ "Service subscription error for " <> tshow serviceId <> ": " <> tshow e atomically $ writeTBQueue msgQ [(NoCorrId, NoEntity, ERR e)] deliverQueueMsg :: (Int64, Int, Int, NonEmpty (Transmission BrokerMsg)) -> RecipientId -> Either ErrorType (Maybe (QueueRec, Message)) -> IO (Int64, Int, Int, NonEmpty (Transmission BrokerMsg)) diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index b1ed8cc13..c95f91c02 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -118,7 +118,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where addQueue_ :: STMQueueStore q -> (RecipientId -> QueueRec -> IO q) -> RecipientId -> QueueRec -> IO (Either ErrorType q) addQueue_ st mkQ rId qr@QueueRec {senderId = sId, notifier, queueData, rcvServiceId} = do sq <- mkQ rId qr - add sq $>> withLog "addStoreQueue" st (\s -> logCreateQueue s rId qr) $> Right sq + E.uninterruptibleMask_ $ add sq $>> withLog "addStoreQueue" st (\s -> logCreateQueue s rId qr) $> Right sq where STMQueueStore {queues, senders, notifiers, links} = st add q = atomically $ ifM hasId (pure $ Left DUPLICATE_) $ Right () <$ do @@ -165,7 +165,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where _ -> Left AUTH addQueueLinkData :: STMQueueStore q -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) - addQueueLinkData st sq lnkId d = + addQueueLinkData st sq lnkId d = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= add) $>> withLog "addQueueLinkData" st (\s -> logCreateLink s rId lnkId d) where @@ -187,7 +187,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure $ Right () deleteQueueLinkData :: STMQueueStore q -> q -> IO (Either ErrorType ()) - deleteQueueLinkData st sq = + deleteQueueLinkData st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>> withLog "deleteQueueLinkData" st (`logDeleteLink` recipientId sq) where @@ -197,7 +197,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where writeTVar qr $ Just q {queueData = Nothing} updateKeys :: STMQueueStore q -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) - updateKeys st sq rKeys = + updateKeys st sq rKeys = E.uninterruptibleMask_ $ withQueueRec qr update $>> withLog "updateKeys" st (\s -> logUpdateKeys s (recipientId sq) rKeys) where @@ -205,7 +205,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where update q = writeTVar qr $ Just q {recipientKeys = rKeys} secureQueue :: STMQueueStore q -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) - secureQueue st sq sKey = + secureQueue st sq sKey = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= secure) $>> withLog "secureQueue" st (\s -> logSecureQueue s (recipientId sq) sKey) where @@ -217,7 +217,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure $ Right () addQueueNotifier :: STMQueueStore q -> q -> NtfCreds -> IO (Either ErrorType (Maybe NtfCreds)) - addQueueNotifier st sq ntfCreds@NtfCreds {notifierId = nId} = + addQueueNotifier st sq ntfCreds@NtfCreds {notifierId = nId} = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= add) $>>= \nc_ -> nc_ <$$ withLog "addQueueNotifier" st (\s -> logAddNotifier s rId ntfCreds) where @@ -232,7 +232,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure $ Right nc_ deleteQueueNotifier :: STMQueueStore q -> q -> IO (Either ErrorType (Maybe NtfCreds)) - deleteQueueNotifier st sq = + deleteQueueNotifier st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>>= (<$$ withLog "deleteQueueNotifier" st (`logDeleteNotifier` recipientId sq)) where @@ -243,22 +243,22 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure nc suspendQueue :: STMQueueStore q -> q -> IO (Either ErrorType ()) - suspendQueue st sq = + suspendQueue st sq = E.uninterruptibleMask_ $ setStatus (queueRec sq) EntityOff $>> withLog "suspendQueue" st (`logSuspendQueue` recipientId sq) blockQueue :: STMQueueStore q -> q -> BlockingInfo -> IO (Either ErrorType ()) - blockQueue st sq info = + blockQueue st sq info = E.uninterruptibleMask_ $ setStatus (queueRec sq) (EntityBlocked info) $>> withLog "blockQueue" st (\sl -> logBlockQueue sl (recipientId sq) info) unblockQueue :: STMQueueStore q -> q -> IO (Either ErrorType ()) - unblockQueue st sq = + unblockQueue st sq = E.uninterruptibleMask_ $ setStatus (queueRec sq) EntityActive $>> withLog "unblockQueue" st (`logUnblockQueue` recipientId sq) updateQueueTime :: STMQueueStore q -> q -> SystemDate -> IO (Either ErrorType QueueRec) - updateQueueTime st sq t = withQueueRec qr update $>>= log' + updateQueueTime st sq t = E.uninterruptibleMask_ $ withQueueRec qr update $>>= log' where qr = queueRec sq update q@QueueRec {updatedAt} @@ -271,7 +271,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where | otherwise = pure $ Right q deleteStoreQueue :: STMQueueStore q -> q -> IO (Either ErrorType QueueRec) - deleteStoreQueue st sq = + deleteStoreQueue st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>>= (<$$ withLog "deleteStoreQueue" st (`logDeleteQueue` rId)) where @@ -287,7 +287,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure q getCreateService :: STMQueueStore q -> ServiceRec -> IO (Either ErrorType ServiceId) - getCreateService st sr@ServiceRec {serviceId = newSrvId, serviceRole, serviceCertHash = XV.Fingerprint fp} = + getCreateService st sr@ServiceRec {serviceId = newSrvId, serviceRole, serviceCertHash = XV.Fingerprint fp} = E.uninterruptibleMask_ $ TM.lookupIO fp serviceCerts >>= maybe (atomically $ TM.lookup fp serviceCerts >>= maybe newService checkService) @@ -315,7 +315,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure STMService {serviceRec = sr, serviceRcvQueues, serviceNtfQueues} setQueueService :: (PartyI p, ServiceParty p) => STMQueueStore q -> q -> SParty p -> Maybe ServiceId -> IO (Either ErrorType ()) - setQueueService st sq party serviceId = + setQueueService st sq party serviceId = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= setService) $>> withLog "setQueueService" st (\sl -> logQueueService sl rId party serviceId) where diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index 3ee9d1c71..c10579b04 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -23,11 +23,14 @@ import Control.Monad.IO.Class import Control.Monad.Trans.Except import Crypto.Random (ChaChaDRG) import Data.ByteString.Char8 (ByteString) +import qualified Data.ByteString.Char8 as B +import Data.Functor (($>)) import Data.Int (Int64) import qualified Data.Map.Strict as M import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Simplex.Messaging.Crypto (pattern MaxLenBS) import qualified Simplex.Messaging.Crypto as C +import Simplex.Messaging.Encoding.String (strEncode) import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), noMsgFlags, randomMsgId) import Simplex.Messaging.Server.MsgStore.STM import Simplex.Messaging.Server.MsgStore.Types @@ -36,16 +39,18 @@ import Simplex.Messaging.Server.QueueStore import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), withLog') import Simplex.Messaging.Server.QueueStore.Types -import Simplex.Messaging.Server.StoreLog (closeStoreLog, openWriteStoreLog) +import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..), closeStoreLog, openWriteStoreLog) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM +import SMPClient (testStoreLogFile) +import System.IO.Unsafe (unsafeInterleaveIO) import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Util #if defined(dbServerPostgres) import AgentTests.FunctionalAPITests (runRight) -import Control.Concurrent (forkIO) +import Control.Concurrent (forkIO, threadDelay) import qualified Control.Exception as E import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB @@ -62,6 +67,8 @@ msgStoreTests = do someMsgStoreTests testSMTStoreConfig it "should remove deleted queues from queue store maps" $ withMsgStore testSMTStoreConfig testDeleteQueueMaps it "should time out store log write" testStoreLogTimeout + it "should end the thread cancelled during store log write" testCancelStoreLogWrite + it "should log the queue change of the thread cancelled before store log write" $ withMsgStore testSMTStoreConfig testCancelBeforeStoreLogWrite #if defined(dbServerPostgres) describe "Postgres-only message store" $ do someMsgStoreTests testPostgresStoreConfig @@ -71,6 +78,8 @@ msgStoreTests = do it "should fail database operations after the store is closed" $ withMsgStore testPostgresStoreConfig testClosedStore it "should time out database operation" $ withMsgStore testPostgresStoreConfig testDBOperationTimeout it "should retry a message write aborted by a deadlock" $ withMsgStore testPostgresStoreConfig testWriteMsgDeadlock + it "should end the thread cancelled during database transaction" $ withMsgStore testPostgresStoreConfig testCancelDBTransaction + it "should end the thread cancelled during database query" $ withMsgStore testPostgresStoreConfig testCancelDBQuery #endif describe "Notification store" $ do it "should remove keys of expired notifications" testExpireNtfs @@ -334,6 +343,23 @@ testStoreLogTimeout = do sl_ <- newTVarIO $ Just sl timeout 100000 (withLog' "test" sl_ $ \_ -> threadDelay 500000) `shouldReturn` Nothing closeStoreLog sl +testCancelStoreLogWrite :: HasTestEnv => IO () +testCancelStoreLogWrite = + bracket (openWriteStoreLog False testStoreLogFile) closeStoreLog $ \sl -> do + sl' <- newTVarIO $ Just sl + testCancelledInside $ \waitCancel -> withLog' "test" sl' $ \_ -> waitCancel + +testCancelBeforeStoreLogWrite :: HasTestEnv => STMMsgStore -> IO () +testCancelBeforeStoreLogWrite ms = do + g <- C.newRandom + (rId, qr) <- testNewQueueRec g QMMessaging + Right q <- addQueue ms rId qr + bracket (openWriteStoreLog False testStoreLogFile) closeStoreLog $ \sl -> + testCancelledInside $ \waitCancel -> do + slAfterCancel <- unsafeInterleaveIO $ waitCancel $> Just sl + sl' <- newTVarIO slAfterCancel + deleteStoreQueue (queueStore ms) {storeLog = sl'} q + B.readFile testStoreLogFile `shouldReturn` strEncode (DeleteQueue rId) <> "\n" mkMsgNtf :: TVar ChaChaDRG -> Int64 -> IO MsgNtf mkMsgNtf g ts = do @@ -519,4 +545,12 @@ testWriteMsgDeadlock ms = do Just (_, True) <- writeMsg ms q True =<< mkMessage "message 1" Msg "message 1" <- tryPeekMsg ms q checkQueueSize ms q (1, True) +testCancelDBTransaction :: PostgresMsgStore -> IO () +testCancelDBTransaction ms = + testCancelledInside $ \waitCancel -> runExceptT $ withDB' "test" (queueStore ms) $ \_ -> waitCancel + +testCancelDBQuery :: PostgresMsgStore -> IO () +testCancelDBQuery ms = + testCancelledWhenBlocked $ \started -> runExceptT $ withDB' "test" (queueStore ms) $ \db -> + started >> (DB.query_ db "SELECT pg_sleep(10)" :: IO [Only ()]) #endif diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index 07141ea8c..914c22725 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -5,14 +5,16 @@ module CoreTests.XFTPStoreTests (xftpStoreTests, xftpMigrationTests) where import Control.Monad +import Control.Monad.Trans.Except (runExceptT) import qualified Data.ByteString.Char8 as B import Data.List.NonEmpty (NonEmpty (..)) import Data.Word (Word32) +import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB import SMPClient (deadlockOnce) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store -import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore) +import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore, withDB') import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, readWriteFileStore, serverFileName, writeFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (..)) import Simplex.Messaging.Agent.Store.Postgres.Common (withTransaction) @@ -51,6 +53,8 @@ xftpStoreTests = do it "should compute committed used storage and file count" testStorageAndCount it "should retry a file creation aborted by a deadlock" testAddFileDeadlock it "should retry a file deletion aborted by a deadlock" testDeleteFilesDeadlock + it "should end the thread cancelled during database transaction" testCancelDBTransaction + it "should end the thread cancelled during database query" testCancelDBQuery xftpMigrationTests :: Spec xftpMigrationTests = describe "XFTP migration round-trip" $ do @@ -336,6 +340,15 @@ testDeleteFilesDeadlock = withPgStore $ \st -> do deleteFiles st [testSenderId] getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) +testCancelDBTransaction :: HasTestEnv => Expectation +testCancelDBTransaction = withPgStore $ \st -> + testCancelledInside $ \waitCancel -> runExceptT $ withDB' "test" st $ \_ -> waitCancel + +testCancelDBQuery :: HasTestEnv => Expectation +testCancelDBQuery = withPgStore $ \st -> + testCancelledWhenBlocked $ \started -> runExceptT $ withDB' "test" st $ \db -> + started >> (DB.query_ db "SELECT pg_sleep(10)" :: IO [Only ()]) + -- Migration round-trip test testMigrationRoundTrip :: HasTestEnv => Expectation diff --git a/tests/Util.hs b/tests/Util.hs index 41361af51..8e266a024 100644 --- a/tests/Util.hs +++ b/tests/Util.hs @@ -8,16 +8,16 @@ module Util where -import Control.Concurrent (threadDelay) +import Control.Concurrent (ThreadId, myThreadId, threadDelay) import Control.Concurrent.Async import Control.Concurrent.STM import Control.Exception as E import Control.Logger.Simple -import Control.Monad (replicateM, when) +import Control.Monad (replicateM, unless, when) import Data.Either (partitionEithers) import Data.List (tails) import Data.String (IsString (..)) -import GHC.Conc (getNumCapabilities, getNumProcessors, setNumCapabilities) +import GHC.Conc (BlockReason (..), ThreadStatus (..), getNumCapabilities, getNumProcessors, setNumCapabilities, threadStatus) import GHC.IO.Exception (IOException (..)) import qualified GHC.IO.Exception as IOException import Network.Socket (ServiceName) @@ -44,6 +44,28 @@ inParrallel n action = do map show es `shouldBe` [] length rs `shouldBe` n +testCancelledInside :: (IO () -> IO a) -> IO () +testCancelledInside action = do + canceller <- myThreadId + testCancelledWhenBlocked $ \started -> action $ started >> waitStatus canceller (== ThreadBlocked BlockedOnException) + +testCancelledWhenBlocked :: (IO () -> IO a) -> IO () +testCancelledWhenBlocked action = do + started <- newEmptyTMVarIO + a <- async $ action $ atomically $ putTMVar started () + atomically $ takeTMVar started + waitStatus (asyncThreadId a) (/= ThreadRunning) + cancel a + waitCatch a >>= \case + Left e -> fromException e `shouldBe` Just AsyncCancelled + Right _ -> expectationFailure "cancelled thread continued" + +waitStatus :: ThreadId -> (ThreadStatus -> Bool) -> IO () +waitStatus t done = do + threadDelay 1000 + status <- threadStatus t + unless (done status) $ waitStatus t done + combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations k xs = [y : ys | y : xs' <- tails xs, ys <- combinations (k - 1) xs'] From d77ceb7961979e970aa5bc16affb8d9d370bfee6 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 03:39:04 -0500 Subject: [PATCH 023/159] lib: reject keys and certificates with invalid encoding Consolidated from PR #2039. --- src/Simplex/Messaging/Crypto.hs | 15 ++++++----- src/Simplex/Messaging/Encoding/String.hs | 5 ++-- src/Simplex/Messaging/Util.hs | 4 +++ tests/AgentTests/ConnectionRequestTests.hs | 5 ++++ tests/CoreTests/CryptoTests.hs | 31 ++++++++++++++++++++++ 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/Simplex/Messaging/Crypto.hs b/src/Simplex/Messaging/Crypto.hs index 16d5b3d22..9495e7abe 100644 --- a/src/Simplex/Messaging/Crypto.hs +++ b/src/Simplex/Messaging/Crypto.hs @@ -263,7 +263,7 @@ import Simplex.Messaging.Agent.Store.DB (Binary (..), FromField (..), ToField (. import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll, parseString) -import Simplex.Messaging.Util (packZipWith, stateTVar', (<$?>)) +import Simplex.Messaging.Util (forceDecoded, packZipWith, stateTVar', (<$?>)) -- | Cryptographic algorithms. data Algorithm = Ed25519 | Ed448 | X25519 | X448 @@ -1274,9 +1274,9 @@ newtype SignedObject a = SignedObject {getSignedExact :: X.SignedExact a} instance (Typeable a, Eq a, Show a, ASN1Object a) => FromField (SignedObject a) where #if defined(dbPostgres) - fromField f dat = SignedObject <$> blobFieldDecoder X.decodeSignedObject f dat + fromField f dat = SignedObject <$> blobFieldDecoder decodeSignedObject f dat #else - fromField = fmap SignedObject . blobFieldDecoder X.decodeSignedObject + fromField = fmap SignedObject . blobFieldDecoder decodeSignedObject #endif instance (Eq a, Show a, ASN1Object a) => ToField (SignedObject a) where @@ -1284,7 +1284,10 @@ instance (Eq a, Show a, ASN1Object a) => ToField (SignedObject a) where instance (Eq a, Show a, ASN1Object a) => Encoding (SignedObject a) where smpEncode (SignedObject exact) = smpEncode . Large $ X.encodeSignedObject exact - smpP = fmap SignedObject . X.decodeSignedObject . unLarge <$?> smpP + smpP = fmap SignedObject . decodeSignedObject . unLarge <$?> smpP + +decodeSignedObject :: (Eq a, Show a, ASN1Object a) => ByteString -> Either String (X.SignedExact a) +decodeSignedObject = forceDecoded (length . show) . X.decodeSignedObject encodeCertChain :: X.CertificateChain -> L.NonEmpty Large encodeCertChain cc = L.fromList $ map Large blobs @@ -1294,7 +1297,7 @@ encodeCertChain cc = L.fromList $ map Large blobs certChainP :: A.Parser X.CertificateChain certChainP = do rawChain <- X.CertificateChainRaw . map unLarge . L.toList <$> smpP - either (fail . show) pure $ X.decodeCertificateChain rawChain + either fail pure . forceDecoded (length . show) . first show $ X.decodeCertificateChain rawChain -- | Signature verification. -- @@ -1590,7 +1593,7 @@ x509ToPrivate' pk = x509ToPrivate (pk, []) >>= privKey {-# INLINE x509ToPrivate' #-} decodeASNKey :: ASN1Object a => ByteString -> Either String (a, [ASN1]) -decodeASNKey = fromASN1 <=< first show . decodeASN1 DER . fromStrict +decodeASNKey = forceDecoded (length . snd) . fromASN1 <=< first show . decodeASN1 DER . fromStrict asnKeyError :: (a, [ASN1]) -> Either String b asnKeyError = \case diff --git a/src/Simplex/Messaging/Encoding/String.hs b/src/Simplex/Messaging/Encoding/String.hs index bde94e4a7..0ec1df18a 100644 --- a/src/Simplex/Messaging/Encoding/String.hs +++ b/src/Simplex/Messaging/Encoding/String.hs @@ -30,6 +30,7 @@ import qualified Data.Aeson.Encoding as JE import qualified Data.Aeson.Types as JT import Data.Attoparsec.ByteString.Char8 (Parser) import qualified Data.Attoparsec.ByteString.Char8 as A +import Data.Bifunctor (first) import qualified Data.ByteString.Base64.URL as U import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B @@ -52,7 +53,7 @@ import qualified Data.X509.Validation as XV import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import Simplex.Messaging.Encoding import Simplex.Messaging.Parsers (parseAll) -import Simplex.Messaging.Util (bshow, safeDecodeUtf8, (<$?>)) +import Simplex.Messaging.Util (bshow, forceDecoded, safeDecodeUtf8, (<$?>)) class TextEncoding a where textEncode :: a -> Text @@ -164,7 +165,7 @@ instance StrEncoding UTCTime where instance StrEncoding X.CertificateChain where strEncode = (\(X.CertificateChainRaw blobs) -> strEncodeList blobs) . X.encodeCertificateChain {-# INLINE strEncode #-} - strP = either (fail . show) pure . X.decodeCertificateChain . X.CertificateChainRaw =<< strListP + strP = forceDecoded (length . show) . first show . X.decodeCertificateChain . X.CertificateChainRaw <$?> strListP {-# INLINE strP #-} instance StrEncoding XV.Fingerprint where diff --git a/src/Simplex/Messaging/Util.hs b/src/Simplex/Messaging/Util.hs index a3a612d1d..8c384f596 100644 --- a/src/Simplex/Messaging/Util.hs +++ b/src/Simplex/Messaging/Util.hs @@ -46,6 +46,7 @@ module Simplex.Messaging.Util tryAllOwnErrors', catchAllOwnErrors, catchAllOwnErrors', + forceDecoded, eitherToMaybe, listToEither, firstRow, @@ -356,6 +357,9 @@ catchAllOwnErrors' :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> (e -> m catchAllOwnErrors' action handler = tryAllOwnErrors' action >>= either handler pure {-# INLINE catchAllOwnErrors' #-} +forceDecoded :: (a -> Int) -> Either String a -> Either String a +forceDecoded force r = either (Left . show) (const r) $ pureTry $ either length force r + eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just {-# INLINE eitherToMaybe #-} diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index 40ca12cf9..71dad0dfe 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -290,6 +290,11 @@ connectionRequestTests = it "should reject KEM ciphertext without KEM key in e2e params" $ strDecode @(RcvE2ERatchetParamsUri 'C.X448) (strEncode testE2ERatchetParams <> "&kem_ct=" <> strEncode (B.replicate 1039 '\0')) `shouldSatisfy` isLeft + it "should reject links with invalid key encoding" $ do + let invalidDhKeyQueueStr = "smp://1234-w==@smp.simplex.im:5223/3456-w==#/?v=1-4&dh=" <> url "MCowBQYDK2VuAyE9jiswwI3O_NlS8Fk3HJUW870EY2bAwmttMBsvRB9eV3o=" + invalidE2EParamsStrUri = "v%3D3%26x3dh%3DMEIwBQYDK2VvAzk9mKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D%2CMEIwBQYDK2VvAzkAmKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D" + strDecode @AConnectionRequestUri ("simplex:/contact#/?v=6-8&smp=" <> url invalidDhKeyQueueStr) `shouldSatisfy` isLeft + strDecode @AConnectionRequestUri ("simplex:/invitation#/?v=6-8&smp=" <> url queueStr <> "&e2e=" <> invalidE2EParamsStrUri) `shouldSatisfy` isLeft it "should serialize / parse queue address, connection invitations and contact addresses as binary" $ do smpEncodingTest queue smpEncodingTest queueNoQM -- this passes, no queue mode patch in SMPQueueUri encoding diff --git a/tests/CoreTests/CryptoTests.hs b/tests/CoreTests/CryptoTests.hs index 27ee6680c..26d0c4251 100644 --- a/tests/CoreTests/CryptoTests.hs +++ b/tests/CoreTests/CryptoTests.hs @@ -21,6 +21,7 @@ import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Either (isLeft, isRight) import Data.Int (Int64) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) @@ -46,6 +47,7 @@ import Simplex.Messaging.Crypto.SNTRUP761.Bindings.FFI (c_sntrup761_keypair) import Simplex.Messaging.Crypto.SNTRUP761.Bindings.RNG (RNGFunc) import Simplex.Messaging.Encoding (Large (..), smpDecode, smpEncode) import Simplex.Messaging.Encoding.String (strDecode, strEncode) +import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Transport.Client import Simplex.Messaging.Transport.Credentials (genCredentials) import System.Timeout (timeout) @@ -124,8 +126,10 @@ cryptoTests = do describe "Ed448" $ testEncoding C.SEd448 describe "X25519" $ testEncoding C.SX25519 describe "X448" $ testEncoding C.SX448 + it "should not decode keys with invalid encoding" testInvalidKeyEncoding describe "X509 chains" $ do it "should validate certificates" testValidateX509 + it "should not decode certificates with invalid encoding" testInvalidCertEncoding describe "sntrup761" $ do it "should enc/dec key" testSNTRUP761 it "should reject malformed KEM encodings" testSNTRUP761RejectsMalformedEncodings @@ -289,6 +293,15 @@ testEncoding alg = it "should encode / decode key" . ioProperty $ do C.decodePubKey (C.encodePubKey k) == Right k && C.decodePrivKey (C.encodePrivKey pk) == Right pk +testInvalidKeyEncoding :: IO () +testInvalidKeyEncoding = do + C.decodePubKey @C.APublicKey "\x30\x0a\x30\x05\x06\x03\x2b\x65\x6e\x03\x01\x3d" `shouldBe` Left bitStringError + C.decodePubKey @C.APublicKey "\x02\x01\x00\x03\x01\x3d" `shouldBe` Left bitStringError + C.decodePubKey @C.APublicKey ("\x30\x2a\x30\x05\x06\x03\x2b\x65\x6e\x03\x21\x00" <> B.replicate 32 '\1' <> "\x03\x01\x3d") `shouldBe` Left bitStringError + C.decodePrivKey @C.APrivateKey "\x30\x0f\x02\x01\x00\x30\x05\x06\x03\x2b\x65\x6e\x04\x03\x03\x01\x3d" `shouldBe` Left bitStringError + where + bitStringError = "TypeDecodingFailed \"bitstring: skip number not within bound 61 \\\"=\\\"\"" + testValidateX509 :: IO () testValidateX509 = do let checkChain = validateCertificateChain SMPClient.testKeyHash "localhost" "5223" . X.CertificateChain @@ -349,6 +362,24 @@ testValidateX509 = do otherLeaf <- genCredentials g (Just otherCA) (1, 24) "leaf" checkPinned [otherLeaf, ident, otherCA] `shouldReturn` [XV.UnknownCA, XV.UnknownCA] +testInvalidCertEncoding :: IO () +testInvalidCertEncoding = do + g <- C.newRandom + (k, _) <- atomically $ C.generateSignatureKeyPair C.SEd25519 g + (_, cert) <- genCredentials g Nothing (1, 24) "root" + let invalidBitString = "\x30\x03\x03\x01\x3d" + emptySignatureOID = "\x30\x35\x30\x2c" <> C.encodePubKey k <> "\x30\x02\x06\x00\x03\x01\x00" + emptySignatureOIDCert = "\x30\x82" <> smpEncode (Large $ X.getSignedData cert <> "\x30\x02\x06\x00\x03\x01\x00") + signedKey invalidBitString `shouldSatisfy` isLeft + signedKey emptySignatureOID `shouldSatisfy` isLeft + parseAll C.certChainP (smpEncode $ Large invalidBitString :| []) `shouldSatisfy` isLeft + strDecode @X.CertificateChain (strEncode invalidBitString) `shouldSatisfy` isLeft + X.decodeCertificateChain (X.CertificateChainRaw [emptySignatureOIDCert]) `shouldSatisfy` isRight + parseAll C.certChainP (smpEncode $ Large emptySignatureOIDCert :| []) `shouldSatisfy` isLeft + strDecode @X.CertificateChain (strEncode emptySignatureOIDCert) `shouldSatisfy` isLeft + where + signedKey s = C.getSignedExact <$> smpDecode @(C.SignedObject X.PubKey) (smpEncode $ Large s) + testSNTRUP761 :: IO () testSNTRUP761 = do drg <- C.newRandom From d573516f47d711c5a28cead84c07b94481f0966b Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 03:42:09 -0500 Subject: [PATCH 024/159] servers: consolidate SMP and notification reliability fixes Consolidates PRs #2042, #2043, #2045, #2049 and #2050. --- protocol/simplex-messaging.md | 2 + src/Simplex/Messaging/Client/Agent.hs | 8 +- src/Simplex/Messaging/Notifications/Server.hs | 18 ++-- .../Messaging/Notifications/Server/Env.hs | 6 +- .../Notifications/Server/Prometheus.hs | 12 ++- .../Messaging/Notifications/Server/Stats.hs | 11 +++ .../Notifications/Server/Store/Migrations.hs | 29 ++++++- .../Notifications/Server/Store/Postgres.hs | 82 +++++++------------ .../Server/Store/ntf_server_schema.sql | 10 ++- src/Simplex/Messaging/Server.hs | 2 +- .../Messaging/Server/MsgStore/Postgres.hs | 24 +++--- .../Messaging/Server/QueueStore/Postgres.hs | 9 +- .../Server/QueueStore/Postgres/Migrations.hs | 15 +++- .../QueueStore/Postgres/server_schema.sql | 4 + .../Messaging/Server/QueueStore/STM.hs | 10 ++- .../Messaging/Server/QueueStore/Types.hs | 2 +- .../Messaging/Server/StoreLog/ReadWrite.hs | 2 +- tests/CoreTests/MsgStoreTests.hs | 42 ++++++++++ tests/NtfServerTests.hs | 67 ++++++++++++--- 19 files changed, 249 insertions(+), 106 deletions(-) diff --git a/protocol/simplex-messaging.md b/protocol/simplex-messaging.md index 989884e3f..109c43cb8 100644 --- a/protocol/simplex-messaging.md +++ b/protocol/simplex-messaging.md @@ -708,6 +708,8 @@ recipientKey = length x509encoded This command added to allow multiple group owners manage data of the same queue link. +The router MUST respond with `AUTH` error and keep the current keys if the queue recipient keys changed after the command was authorized. + #### Set short link This command is used to associate a short link with the queue: diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index 46d36a03c..feb169548 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -194,8 +194,7 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize } data DBService = DBService - { getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials), - updateServiceId :: SMPServer -> Maybe ServiceId -> IO (Either SMPClientError ()) + { getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials) } -- | Get or create SMP client for SMPServer @@ -258,10 +257,7 @@ connectClient :: SMPClientAgent p -> SMPServer -> SMPClientVar -> IO (Either SMP connectClient ca@SMPClientAgent {agentCfg, dbService, smpClients, smpSessions, msgQ, randomDrg, startedAt} srv v = case dbService of Just dbs -> runExceptT $ do creds <- ExceptT $ getCredentials dbs srv - smp <- ExceptT $ getClient cfg {serviceCredentials = Just creds} - whenM (atomically $ activeClientSession ca smp srv) $ - ExceptT $ updateServiceId dbs srv $ smpClientServiceId smp - pure smp + ExceptT $ getClient cfg {serviceCredentials = Just creds} Nothing -> getClient cfg where cfg = smpCfg agentCfg diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index ae264e548..1b2dfa86f 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -253,8 +253,9 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} d <- getNtfServerStatsData ss let psTkns = periodStatDataCounts $ _activeTokens d psSubs = periodStatDataCounts $ _activeSubs d - (tokenCount, approxSubCount, lastNtfCount) <- getEntityCounts st - pure NtfServerMetrics {statsData = d, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, approxSubCount, lastNtfCount, rtsOptions} + NtfEntityCounts {tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount} <- getEntityCounts st + let tokenCount = sum $ map snd tokenStatusCounts + pure NtfServerMetrics {statsData = d, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount, rtsOptions} getNtfRealTimeMetrics :: NtfEnv -> IO NtfRealTimeMetrics getNtfRealTimeMetrics NtfEnv {subscriber, pushServer} = do @@ -395,6 +396,7 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} putStat "ntfReceived" ntfReceived putStat "ntfDelivered" ntfDelivered putStat "ntfFailed" ntfFailed + putStat "ntfDropped" ntfDropped putStat "ntfCronDelivered" ntfCronDelivered putStat "ntfCronFailed" ntfCronFailed putStat "ntfVrfQueued" ntfVrfQueued @@ -550,7 +552,7 @@ ntfSubscriber NtfSubscriber {smpAgent = ca@SMPClientAgent {msgQ = msgQ_, agentQ} isOwn = isOwnServer ca srv liftIO (addTokenLastNtf st newNtf) >>= \case Right (tkn, lastNtfs) -> do - pushNotification ps (Just srvHost) isOwn tkn $ PNMessage lastNtfs + tryPushNotification ps (Just srvHost) isOwn tkn $ PNMessage lastNtfs liftIO $ incNtfStat_ stats ntfReceived when isOwn $ liftIO $ incServerStat srvHost (ntfReceivedOwn stats) Left AUTH -> liftIO $ do @@ -641,10 +643,16 @@ showServer' :: SMPServer -> Text showServer' = decodeLatin1 . strEncode . host pushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () -pushNotification s srvHost_ isOwn tkn@NtfTknRec {ntfTknId, token = token@(DeviceToken pp _)} ntf = +pushNotification = pushNotification_ $ \q -> atomically . writeTBQueue q + +tryPushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () +tryPushNotification = pushNotification_ $ \q x -> unlessM (atomically $ tryWriteTBQueue q x) $ incNtfStat ntfDropped + +pushNotification_ :: (TBQueue (NtfTknRec, PushNotification) -> (NtfTknRec, PushNotification) -> M ()) -> NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () +pushNotification_ enqueue s srvHost_ isOwn tkn@NtfTknRec {ntfTknId, token = token@(DeviceToken pp _)} ntf = ifM (pushProviderAllowed token) - (getOrCreatePushWorker s (srvHost_, pp, hash (unEntityId ntfTknId) `mod` pushWorkersPerServer) isOwn >>= atomically . (`writeTBQueue` (tkn, ntf))) + (getOrCreatePushWorker s (srvHost_, pp, hash (unEntityId ntfTknId) `mod` pushWorkersPerServer) isOwn >>= (`enqueue` (tkn, ntf))) (logWarn "skipping disabled APNS test push provider") where pushWorkersPerServer = 8 diff --git a/src/Simplex/Messaging/Notifications/Server/Env.hs b/src/Simplex/Messaging/Notifications/Server/Env.hs index 0395f93ef..2f5761d1a 100644 --- a/src/Simplex/Messaging/Notifications/Server/Env.hs +++ b/src/Simplex/Messaging/Notifications/Server/Env.hs @@ -54,7 +54,7 @@ import Simplex.Messaging.Notifications.Server.Stats import Simplex.Messaging.Notifications.Server.Store.Postgres import Simplex.Messaging.Notifications.Server.Store.Types import Simplex.Messaging.Notifications.Transport (NTFVersion, VersionRangeNTF) -import Simplex.Messaging.Protocol (BasicAuth, CorrId, Party (..), SMPServer, SParty (..), ServiceId, Transmission) +import Simplex.Messaging.Protocol (BasicAuth, CorrId, Party (..), SMPServer, SParty (..), Transmission) import Simplex.Messaging.Server.Env.STM (StartOptions (..)) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.QueueStore.Postgres.Config (PostgresStoreCfg (..)) @@ -132,7 +132,7 @@ newNtfServerEnv config@NtfServerConfig {pushQSize, smpAgentCfg, apnsConfig, dbSt serverStats <- newNtfServerStats =<< getCurrentTime pure NtfEnv {config, subscriber, pushServer, store, random, tlsServerCreds, serverIdentity = C.KeyHash fp, serverStats} where - mkDbService g st = DBService {getCredentials, updateServiceId} + mkDbService g st = DBService {getCredentials} where getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials) getCredentials srv = runExceptT $ do @@ -148,8 +148,6 @@ newNtfServerEnv config@NtfServerConfig {pushQSize, smpAgentCfg, apnsConfig, dbSt let tlsCreds = tlsCredentials [cred] setNtfServiceCredentials db srvId tlsCreds pure tlsCreds - updateServiceId :: SMPServer -> Maybe ServiceId -> IO (Either SMPClientError ()) - updateServiceId srv serviceId_ = withClientDB "" st $ \db -> updateNtfServiceId db srv serviceId_ data NtfSubscriber = NtfSubscriber { smpSubscribers :: TMap SMPServer SMPSubscriberVar, diff --git a/src/Simplex/Messaging/Notifications/Server/Prometheus.hs b/src/Simplex/Messaging/Notifications/Server/Prometheus.hs index 8277da632..0f1ac4cdf 100644 --- a/src/Simplex/Messaging/Notifications/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Notifications/Server/Prometheus.hs @@ -31,7 +31,9 @@ data NtfServerMetrics = NtfServerMetrics activeTokensCounts :: PeriodStatCounts, activeSubsCounts :: PeriodStatCounts, tokenCount :: Int64, + tokenStatusCounts :: [(Text, Int64)], approxSubCount :: Int64, + subStatusCounts :: [(Text, Int64)], lastNtfCount :: Int64, rtsOptions :: Text } @@ -61,7 +63,7 @@ ntfPrometheusMetrics :: NtfServerMetrics -> NtfRealTimeMetrics -> UTCTime -> Tex ntfPrometheusMetrics sm rtm ts = time <> tokens <> subscriptions <> notifications <> info where - NtfServerMetrics {statsData, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, approxSubCount, lastNtfCount, rtsOptions} = sm + NtfServerMetrics {statsData, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount, rtsOptions} = sm NtfRealTimeMetrics { threadsCount, srvSubscribers, @@ -86,6 +88,7 @@ ntfPrometheusMetrics sm rtm ts = _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -137,6 +140,7 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_tokens_total gauge\n\ \simplex_ntf_tokens_total " <> mshow tokenCount <> "\n# tokenCount\n\ \\n" + <> gaugeMetrics "simplex_pg_ntf_token_status_total" (statusMetrics tokenStatusCounts) "Total count of each token status" "tokenStatusCounts" subscriptions = "# Subscriptions\n\ \# -------------\n\ @@ -165,6 +169,7 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_subscriptions_approx_total gauge\n\ \simplex_ntf_subscriptions_approx_total " <> mshow approxSubCount <> "\n# approxSubCount\n\ \\n" + <> gaugeMetrics "simplex_pg_ntf_subscription_status_total" (statusMetrics subStatusCounts) "Total count of each subscription status, approximate for ACTIVE, DELETED and AUTH" "subStatusCounts" <> showSubMetric ntfActiveServiceSubs "simplex_ntf_smp_service_subscription_active_" "Active" <> showSubMetric ntfActiveQueueSubs "simplex_ntf_smp_subscription_active_" "Active" <> showSubMetric ntfPendingServiceSubs "simplex_ntf_smp_service_subscription_pending_" "Pending" @@ -189,6 +194,10 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_notifications_failed counter\n\ \simplex_ntf_notifications_failed " <> mshow _ntfFailed <> "\n# ntfFailed\n\ \\n\ + \# HELP simplex_ntf_notifications_dropped Notifications not pushed because the push queue is full\n\ + \# TYPE simplex_ntf_notifications_dropped counter\n\ + \simplex_ntf_notifications_dropped " <> mshow _ntfDropped <> "\n# ntfDropped\n\ + \\n\ \# HELP simplex_ntf_notifications_periodic_delivered Delivered periodic notifications\n\ \# TYPE simplex_ntf_notifications_periodic_delivered counter\n\ \simplex_ntf_notifications_periodic_delivered " <> mshow _ntfCronDelivered <> "\n# ntfCronDelivered\n\ @@ -284,6 +293,7 @@ ntfPrometheusMetrics sm rtm ts = <> T.concat (map (\(param, value) -> name <> param <> " " <> mshow value <> "\n") subMetrics) <> "# " <> codeRef <> "\n\n" metricHost host = "{server=\"" <> host <> "\"}" + statusMetrics = map (\(status, cnt) -> ("{status=\"" <> status <> "\"}", fromIntegral cnt)) mstr a = a <> " " <> tsEpoch mshow :: Show a => a -> Text mshow = mstr . tshow diff --git a/src/Simplex/Messaging/Notifications/Server/Stats.hs b/src/Simplex/Messaging/Notifications/Server/Stats.hs index b23fc6301..7162cc44f 100644 --- a/src/Simplex/Messaging/Notifications/Server/Stats.hs +++ b/src/Simplex/Messaging/Notifications/Server/Stats.hs @@ -41,6 +41,7 @@ data NtfServerStats = NtfServerStats ntfReceivedAuth :: IORef Int, ntfDelivered :: IORef Int, ntfFailed :: IORef Int, + ntfDropped :: IORef Int, ntfReceivedOwn :: StatsByServer, ntfReceivedAuthOwn :: StatsByServer, ntfDeliveredOwn :: StatsByServer, @@ -67,6 +68,7 @@ data NtfServerStatsData = NtfServerStatsData _ntfReceivedAuth :: Int, _ntfDelivered :: Int, _ntfFailed :: Int, + _ntfDropped :: Int, _ntfReceivedOwn :: StatsByServerData, _ntfReceivedAuthOwn :: StatsByServerData, _ntfDeliveredOwn :: StatsByServerData, @@ -94,6 +96,7 @@ newNtfServerStats ts = do ntfReceivedAuth <- newIORef 0 ntfDelivered <- newIORef 0 ntfFailed <- newIORef 0 + ntfDropped <- newIORef 0 ntfReceivedOwn <- TM.emptyIO ntfReceivedAuthOwn <- TM.emptyIO ntfDeliveredOwn <- TM.emptyIO @@ -119,6 +122,7 @@ newNtfServerStats ts = do ntfReceivedAuth, ntfDelivered, ntfFailed, + ntfDropped, ntfReceivedOwn, ntfReceivedAuthOwn, ntfDeliveredOwn, @@ -146,6 +150,7 @@ getNtfServerStatsData s@NtfServerStats {fromTime} = do _ntfReceivedAuth <- readIORef $ ntfReceivedAuth s _ntfDelivered <- readIORef $ ntfDelivered s _ntfFailed <- readIORef $ ntfFailed s + _ntfDropped <- readIORef $ ntfDropped s _ntfReceivedOwn <- getStatsByServer $ ntfReceivedOwn s _ntfReceivedAuthOwn <- getStatsByServer $ ntfReceivedAuthOwn s _ntfDeliveredOwn <- getStatsByServer $ ntfDeliveredOwn s @@ -171,6 +176,7 @@ getNtfServerStatsData s@NtfServerStats {fromTime} = do _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -199,6 +205,7 @@ setNtfServerStats s@NtfServerStats {fromTime} d@NtfServerStatsData {_fromTime} = writeIORef (ntfReceivedAuth s) $! _ntfReceivedAuth d writeIORef (ntfDelivered s) $! _ntfDelivered d writeIORef (ntfFailed s) $! _ntfFailed d + writeIORef (ntfDropped s) $! _ntfDropped d setStatsByServer (ntfReceivedOwn s) $! _ntfReceivedOwn d setStatsByServer (ntfReceivedAuthOwn s) $! _ntfReceivedAuthOwn d setStatsByServer (ntfDeliveredOwn s) $! _ntfDeliveredOwn d @@ -226,6 +233,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -251,6 +259,7 @@ instance StrEncoding NtfServerStatsData where "ntfReceivedAuth=" <> strEncode _ntfReceivedAuth, "ntfDelivered=" <> strEncode _ntfDelivered, "ntfFailed=" <> strEncode _ntfFailed, + "ntfDropped=" <> strEncode _ntfDropped, "ntfReceivedOwn=" <> strEncode _ntfReceivedOwn, "ntfReceivedAuthOwn=" <> strEncode _ntfReceivedAuthOwn, "ntfDeliveredOwn=" <> strEncode _ntfDeliveredOwn, @@ -278,6 +287,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth <- opt "ntfReceivedAuth=" _ntfDelivered <- "ntfDelivered=" *> strP <* A.endOfLine _ntfFailed <- opt "ntfFailed=" + _ntfDropped <- opt "ntfDropped=" _ntfReceivedOwn <- statByServerP "ntfReceivedOwn=" _ntfReceivedAuthOwn <- statByServerP "ntfReceivedAuthOwn=" _ntfDeliveredOwn <- statByServerP "ntfDeliveredOwn=" @@ -305,6 +315,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, diff --git a/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs b/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs index eae815a5b..ac4d44edd 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs +++ b/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs @@ -18,7 +18,8 @@ ntfServerSchemaMigrations = [ ("20250417_initial", m20250417_initial, Nothing), ("20250517_service_cert", m20250517_service_cert, Just down_m20250517_service_cert), ("20250830_queue_ids_hash", m20250830_queue_ids_hash, Just down_m20250830_queue_ids_hash), - ("20251219_service_cert_per_server", m20251219_service_cert_per_server, Just down_m20251219_service_cert_per_server) + ("20251219_service_cert_per_server", m20251219_service_cert_per_server, Just down_m20251219_service_cert_per_server), + ("20261112_status_counts_autovacuum", m20261112_status_counts_autovacuum, Just down_m20261112_status_counts_autovacuum) ] -- | The list of migrations in ascending order by date @@ -250,6 +251,32 @@ ALTER TABLE smp_servers |] <> resetNtfServices +m20261112_status_counts_autovacuum :: Text +m20261112_status_counts_autovacuum = + [r| +CREATE INDEX idx_subscriptions_uncommon_status ON subscriptions(status) WHERE status NOT IN ('ACTIVE', 'DELETED', 'AUTH'); + +ALTER TABLE subscriptions SET ( + autovacuum_vacuum_scale_factor = 0.02, + autovacuum_analyze_scale_factor = 0.01, + autovacuum_vacuum_cost_limit = 1000 +); + +ALTER TABLE last_notifications SET ( + autovacuum_vacuum_scale_factor = 0.02, + autovacuum_analyze_scale_factor = 0.01 +); + |] + +down_m20261112_status_counts_autovacuum :: Text +down_m20261112_status_counts_autovacuum = + [r| +ALTER TABLE last_notifications RESET (autovacuum_vacuum_scale_factor, autovacuum_analyze_scale_factor); +ALTER TABLE subscriptions RESET (autovacuum_vacuum_scale_factor, autovacuum_analyze_scale_factor, autovacuum_vacuum_cost_limit); + +DROP INDEX idx_subscriptions_uncommon_status; + |] + resetNtfServices :: Text resetNtfServices = [r| diff --git a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs index 233a8b68a..95bea2fe1 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs +++ b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs @@ -31,7 +31,6 @@ module Simplex.Messaging.Notifications.Server.Store.Postgres getUsedSMPServers, getNtfServiceCredentials, setNtfServiceCredentials, - updateNtfServiceId, getServerNtfSubscriptions, findNtfSubscription, getNtfSubscription, @@ -49,6 +48,7 @@ module Simplex.Messaging.Notifications.Server.Store.Postgres batchUpdateSrvSubErrors, removeServiceAndAssociations, addTokenLastNtf, + NtfEntityCounts (..), getEntityCounts, withDB', withClientDB, @@ -88,7 +88,6 @@ import Simplex.Messaging.Agent.Store.Postgres.DB (fromTextField_) import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..)) import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError) import Simplex.Messaging.Encoding -import Simplex.Messaging.Encoding.String import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Store.Migrations @@ -105,6 +104,7 @@ import Text.Hex (decodeHex) #if !defined(dbPostgres) import qualified Data.X509 as X import Simplex.Messaging.Agent.Store.Postgres.DB (blobFieldDecoder) +import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Util (eitherToMaybe) #endif @@ -316,44 +316,6 @@ setNtfServiceCredentials db srvId (kh, (cert, pk)) = |] (kh, cert, pk, srvId) -updateNtfServiceId :: DB.Connection -> SMPServer -> Maybe ServiceId -> IO () -updateNtfServiceId db srv newServiceId_ = do - maybeFirstRow id (getSMPServiceForUpdate_ db srv) >>= mapM_ updateService - where - updateService (srvId, currServiceId_) = unless (currServiceId_ == newServiceId_) $ do - when (isJust currServiceId_) $ do - void $ removeServiceAssociation_ db srvId - logError $ "STORE: service ID for " <> enc (host srv) <> toServiceId <> ", removed sub associations" - void $ case newServiceId_ of - Just newServiceId -> - DB.execute - db - [sql| - UPDATE smp_servers - SET ntf_service_id = ?, - smp_notifier_count = 0, - smp_notifier_ids_hash = DEFAULT - WHERE smp_server_id = ? - |] - (newServiceId, srvId) - Nothing -> - DB.execute - db - [sql| - UPDATE smp_servers - SET ntf_service_id = NULL, - ntf_service_cert = NULL, - ntf_service_cert_hash = NULL, - ntf_service_priv_key = NULL, - smp_notifier_count = 0, - smp_notifier_ids_hash = DEFAULT - WHERE smp_server_id = ? - |] - (Only srvId) - toServiceId = maybe " removed" ((" changed to " <>) . enc) newServiceId_ - enc :: StrEncoding a => a -> Text - enc = decodeLatin1 . strEncode - getServerNtfSubscriptions :: NtfPostgresStore -> Int64 -> Maybe NtfSubscriptionId -> Int -> IO (Either ErrorType [ServerNtfSub]) getServerNtfSubscriptions st srvId afterSubId_ count = withDB' "getServerNtfSubscriptions" st $ \db -> do @@ -619,11 +581,11 @@ removeServiceAssociation_ db srvId = db [sql| UPDATE subscriptions s - SET status = ?, ntf_service_assoc = FALSE + SET status = CASE WHEN s.status IN ? THEN ? ELSE s.status END, ntf_service_assoc = FALSE WHERE smp_server_id = ? - AND (s.status != ? OR s.ntf_service_assoc != FALSE) + AND ((s.status IN ? AND s.status != ?) OR s.ntf_service_assoc != FALSE) |] - (NSInactive, srvId, NSInactive) + (In subscribeNtfStatuses, NSInactive, srvId, In subscribeNtfStatuses, NSInactive) removeServiceAndAssociations :: NtfPostgresStore -> SMPServer -> IO (Either ErrorType (Int64, Int)) removeServiceAndAssociations st srv = do @@ -650,9 +612,6 @@ removeServiceAndAssociations st srv = do [sql| UPDATE smp_servers SET ntf_service_id = NULL, - ntf_service_cert = NULL, - ntf_service_cert_hash = NULL, - ntf_service_priv_key = NULL, smp_notifier_count = 0, smp_notifier_ids_hash = DEFAULT WHERE smp_server_id = ? @@ -728,13 +687,32 @@ toLastNtf (qRow :. (ts, nonce, Binary encMeta)) = let ntfTs = MkSystemTime (systemSeconds $ utcToSystemTime ts) 0 in PNMessageData {smpQueue = rowToSMPQueue qRow, ntfTs, nmsgNonce = nonce, encNMsgMeta = encMeta} -getEntityCounts :: NtfPostgresStore -> IO (Int64, Int64, Int64) +data NtfEntityCounts = NtfEntityCounts + { tokenStatusCounts :: [(Text, Int64)], + approxSubCount :: Int64, + subStatusCounts :: [(Text, Int64)], + lastNtfCount :: Int64 + } + +getEntityCounts :: NtfPostgresStore -> IO NtfEntityCounts getEntityCounts st = - fmap (fromRight (0, 0, 0)) $ withDB' "getEntityCounts" st $ \db -> do - tCnt <- count <$> DB.query_ db "SELECT count(1) FROM tokens" - sCnt <- count <$> DB.query_ db "SELECT reltuples::BIGINT FROM pg_class WHERE relname = 'subscriptions' AND relkind = 'r'" - nCnt <- count <$> DB.query_ db "SELECT count(1) FROM last_notifications" - pure (tCnt, sCnt, nCnt) + fmap (fromRight $ NtfEntityCounts [] 0 [] 0) $ withDB' "getEntityCounts" st $ \db -> do + tokenStatusCounts <- DB.query_ db "SELECT status, count(1) FROM tokens GROUP BY status" + approxSubCount <- count <$> DB.query_ db "SELECT reltuples::BIGINT FROM pg_class WHERE relname = 'subscriptions' AND relkind = 'r'" + uncommonSubCounts <- DB.query_ db "SELECT status, count(1) FROM subscriptions WHERE status NOT IN ('ACTIVE', 'DELETED', 'AUTH') GROUP BY status" + commonSubCounts <- + DB.query_ + db + [sql| + SELECT v.status, (v.freq * GREATEST(c.reltuples, 0))::BIGINT + FROM pg_stats s + CROSS JOIN LATERAL unnest(s.most_common_vals::TEXT::TEXT[], s.most_common_freqs) AS v(status, freq) + JOIN pg_class c ON c.oid = 'subscriptions'::regclass + WHERE s.schemaname = current_schema() AND s.tablename = 'subscriptions' AND s.attname = 'status' + AND v.status IN ('ACTIVE', 'DELETED', 'AUTH') + |] + lastNtfCount <- count <$> DB.query_ db "SELECT count(1) FROM last_notifications" + pure NtfEntityCounts {tokenStatusCounts, approxSubCount, subStatusCounts = commonSubCounts <> uncommonSubCounts, lastNtfCount} where count (Only n : _) = n count [] = 0 diff --git a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql index 627ee9dcf..c68b59668 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql +++ b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql @@ -140,7 +140,8 @@ CREATE TABLE ntf_server.last_notifications ( sent_at timestamp with time zone NOT NULL, nmsg_nonce bytea NOT NULL, nmsg_data bytea NOT NULL -); +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); @@ -197,7 +198,8 @@ CREATE TABLE ntf_server.subscriptions ( smp_notifier_key bytea NOT NULL, status text NOT NULL, ntf_service_assoc boolean DEFAULT false NOT NULL -); +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01', autovacuum_vacuum_cost_limit='1000'); @@ -270,6 +272,10 @@ CREATE INDEX idx_subscriptions_token_id ON ntf_server.subscriptions USING btree +CREATE INDEX idx_subscriptions_uncommon_status ON ntf_server.subscriptions USING btree (status) WHERE (status <> ALL (ARRAY['ACTIVE'::text, 'DELETED'::text, 'AUTH'::text])); + + + CREATE UNIQUE INDEX idx_tokens_push_provider_token ON ntf_server.tokens USING btree (push_provider, push_provider_token, verify_key); diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index ff364a9ae..a8920f92d 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1685,7 +1685,7 @@ client GET -> withQueue getMessage ACK msgId -> withQueue $ acknowledgeMsg msgId KEY sKey -> withQueue $ \q _ -> either err (corrId,entId,) <$> secureQueue_ q sKey - RKEY rKeys -> withQueue $ \q qr -> checkMode QMContact qr $ OK <$$ liftIO (updateKeys (queueStore ms) q rKeys) + RKEY rKeys -> withQueue $ \q qr -> checkMode QMContact qr $ OK <$$ liftIO (updateKeys (queueStore ms) q (Just $ recipientKeys qr) rKeys) LSET lnkId d -> withQueue $ \q qr -> case queueData qr of _ | isSecuredMsgQueue qr -> pure $ err AUTH diff --git a/src/Simplex/Messaging/Server/MsgStore/Postgres.hs b/src/Simplex/Messaging/Server/MsgStore/Postgres.hs index 1b91b698e..201590513 100644 --- a/src/Simplex/Messaging/Server/MsgStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/MsgStore/Postgres.hs @@ -29,6 +29,7 @@ where import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad +import Control.Monad.IO.Class import Control.Monad.Trans.Except import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB @@ -109,9 +110,13 @@ instance MsgStoreClass PostgresMsgStore where foldRcvServiceMessages :: PostgresMsgStore -> ServiceId -> (a -> RecipientId -> Either ErrorType (Maybe (QueueRec, Message)) -> IO a) -> a -> IO (Either ErrorType a) foldRcvServiceMessages ms serviceId f acc = - runExceptT $ withDB' "foldRcvServiceMessages" (queueStore_ ms) $ \db -> - DB.fold - db + runExceptT $ foldPages NoEntity acc + where + foldPages afterId a = do + rows <- withDB' "foldRcvServiceMessages" (queueStore_ ms) $ \db -> DB.query db query (serviceId, afterId, pageSize) + (lastId, a') <- liftIO $ foldM f' (afterId, a) rows + if length rows < pageSize then pure a' else foldPages lastId a' + query = [sql| SELECT q.recipient_id, q.recipient_keys, q.rcv_dh_secret, q.sender_id, q.sender_key, q.queue_mode, @@ -126,16 +131,15 @@ instance MsgStoreClass PostgresMsgStore where ORDER BY message_id ASC LIMIT 1 ) m ON true - WHERE q.rcv_service_id = ? AND q.deleted_at IS NULL; + WHERE q.rcv_service_id = ? AND q.deleted_at IS NULL AND q.recipient_id > ? + ORDER BY q.recipient_id ASC + LIMIT ?; |] - (Only serviceId) - acc - f' - where - f' a (qRow :. mRow) = + f' (_, a) (qRow :. mRow) = let (rId, qr) = rowToQueueRec qRow msg_ = toMaybeMessage mRow - in f a rId $ Right ((qr,) <$> msg_) + in (rId,) <$> f a rId (Right ((qr,) <$> msg_)) + pageSize = 100 :: Int queueStore = queueStore_ {-# INLINE queueStore #-} diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 5a11fbbf6..891877c1b 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -245,11 +245,12 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where Just k | sKey /= k -> throwE AUTH _ -> pure () - updateKeys :: PostgresQueueStore q -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) - updateKeys st sq rKeys = + updateKeys :: PostgresQueueStore q -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys st sq prevKeys_ rKeys = withQueueRec sq $ \q -> do - assertUpdated $ withDB' "updateKeys" st $ \db -> - DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL" (rKeys, rId) + assertUpdated $ withDB' "updateKeys" st $ \db -> case prevKeys_ of + Just prevKeys -> DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL AND recipient_keys = ?" (rKeys, rId, prevKeys) + Nothing -> DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL" (rKeys, rId) atomically $ writeTVar (queueRec sq) $ Just q {recipientKeys = rKeys} withLog "updateKeys" st $ \s -> logUpdateKeys s rId rKeys where diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs index 165623258..9b3d3bdd2 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs @@ -23,7 +23,8 @@ serverSchemaMigrations = ("20250915_queue_ids_hash", m20250915_queue_ids_hash, Just down_m20250915_queue_ids_hash), ("20260916_prometheus_indexes", m20260916_prometheus_indexes, Just down_m20260916_prometheus_indexes), ("20260917_msg_queues_hot", m20260917_msg_queues_hot, Just down_m20260917_msg_queues_hot), - ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages) + ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), + ("20261108_rcv_service_queues", m20261108_rcv_service_queues, Just down_m20261108_rcv_service_queues) ] -- | The list of migrations in ascending order by date @@ -1236,3 +1237,15 @@ BEGIN END; $$; |] + +m20261108_rcv_service_queues :: Text +m20261108_rcv_service_queues = + [r| +CREATE INDEX idx_msg_queues_rcv_service_active ON msg_queues (rcv_service_id, recipient_id) WHERE deleted_at IS NULL AND rcv_service_id IS NOT NULL; + |] + +down_m20261108_rcv_service_queues :: Text +down_m20261108_rcv_service_queues = + [r| +DROP INDEX idx_msg_queues_rcv_service_active; + |] diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql index cea2e0835..74ede79f6 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql @@ -513,6 +513,10 @@ CREATE INDEX idx_msg_queues_ntf_service_id ON smp_server.msg_queues USING btree +CREATE INDEX idx_msg_queues_rcv_service_active ON smp_server.msg_queues USING btree (rcv_service_id, recipient_id) WHERE ((deleted_at IS NULL) AND (rcv_service_id IS NOT NULL)); + + + CREATE INDEX idx_msg_queues_rcv_service_id ON smp_server.msg_queues USING btree (rcv_service_id, deleted_at); diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index c95f91c02..f7f3e9acb 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -196,13 +196,15 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where TM.delete lnkId $ links st writeTVar qr $ Just q {queueData = Nothing} - updateKeys :: STMQueueStore q -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) - updateKeys st sq rKeys = E.uninterruptibleMask_ $ - withQueueRec qr update + updateKeys :: STMQueueStore q -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys st sq prevKeys_ rKeys = + atomically (readQueueRec qr $>>= update) $>> withLog "updateKeys" st (\s -> logUpdateKeys s (recipientId sq) rKeys) where qr = queueRec sq - update q = writeTVar qr $ Just q {recipientKeys = rKeys} + update q + | maybe True (recipientKeys q ==) prevKeys_ = Right <$> writeTVar qr (Just q {recipientKeys = rKeys}) + | otherwise = pure $ Left AUTH secureQueue :: STMQueueStore q -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) secureQueue st sq sKey = E.uninterruptibleMask_ $ diff --git a/src/Simplex/Messaging/Server/QueueStore/Types.hs b/src/Simplex/Messaging/Server/QueueStore/Types.hs index e8d47751b..372c411a1 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Types.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Types.hs @@ -35,7 +35,7 @@ class StoreQueueClass q => QueueStoreClass q s where addQueueLinkData :: s -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) deleteQueueLinkData :: s -> q -> IO (Either ErrorType ()) secureQueue :: s -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) - updateKeys :: s -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys :: s -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) addQueueNotifier :: s -> q -> NtfCreds -> IO (Either ErrorType (Maybe NtfCreds)) deleteQueueNotifier :: s -> q -> IO (Either ErrorType (Maybe NtfCreds)) suspendQueue :: s -> q -> IO (Either ErrorType ()) diff --git a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs index 21a5470aa..14e0461ad 100644 --- a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs +++ b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs @@ -46,7 +46,7 @@ readQueueStore tty mkQ f st = readLogLines tty f $ \_ -> processLine CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> addQueueLinkData st q lnkId d DeleteLink rId -> withQueue rId "DeleteLink" $ \q -> deleteQueueLinkData st q SecureQueue qId sKey -> withQueue qId "SecureQueue" $ \q -> secureQueue st q sKey - UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q rKeys + UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q Nothing rKeys AddNotifier qId ntfCreds -> withQueue qId "AddNotifier" $ \q -> addQueueNotifier st q ntfCreds SuspendQueue qId -> withQueue qId "SuspendQueue" $ suspendQueue st BlockQueue qId info -> withQueue qId "BlockQueue" $ \q -> blockQueue st q info diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index c10579b04..f892ed162 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -52,10 +52,12 @@ import Util import AgentTests.FunctionalAPITests (runRight) import Control.Concurrent (forkIO, threadDelay) import qualified Control.Exception as E +import Data.List (sortOn) import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB import Simplex.Messaging.Agent.Store.Postgres.Common import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) +import Simplex.Messaging.Protocol (messageId) import Simplex.Messaging.Server.MsgStore.Postgres import Simplex.Messaging.Server.QueueStore.Postgres import SMPClient (deadlockOnce, testStoreDBOpts) @@ -74,6 +76,7 @@ msgStoreTests = do someMsgStoreTests testPostgresStoreConfig it "should correctly update message counts and canWrite flag" $ withMsgStore testPostgresStoreConfig testUpdateMessageCounts it "tryDelPeekMsg (ACK not from NSE) should reset message counts when queue is empty" $ withMsgStore testPostgresStoreConfig testResetMessageCounts + it "should fold service messages in pages without holding a database connection" $ withMsgStore testPostgresStoreConfig testFoldServiceMessagesInPages it "should expire messages across commit batches" $ withMsgStore testPostgresStoreConfig testExpireMessagesInBatches it "should fail database operations after the store is closed" $ withMsgStore testPostgresStoreConfig testClosedStore it "should time out database operation" $ withMsgStore testPostgresStoreConfig testDBOperationTimeout @@ -91,6 +94,7 @@ msgStoreTests = do it "should write/ack messages" $ withMsgStore cfg testWriteAckMessages it "should peek the first message of each queue in a batch" $ withMsgStore cfg testPeekMsgs it "should not add link data to secured messaging queue" $ withMsgStore cfg testLinkDataSecuredQueue + it "should not update recipient keys changed after the command was verified" $ withMsgStore cfg testUpdateChangedKeys -- TODO constrain to STM stores? withMsgStore :: MsgStoreClass s => MsgStoreConfig s -> (s -> IO ()) -> IO () @@ -290,6 +294,21 @@ testLinkDataSecuredQueue ms = do void $ ExceptT $ deleteQueue ms q void $ ExceptT $ deleteQueue ms cq +testUpdateChangedKeys :: MsgStoreClass s => s -> IO () +testUpdateChangedKeys ms = do + g <- C.newRandom + (k1, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (k2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let st = queueStore ms + (rId, qr@QueueRec {recipientKeys = ks}) <- testNewQueueRec g QMContact + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + ExceptT $ updateKeys st q (Just ks) [k1] + liftIO $ updateKeys st q (Just ks) [k2] `shouldReturn` Left AUTH + (_, QueueRec {recipientKeys}) <- ExceptT $ getQueueRec ms SRecipient rId + liftIO $ recipientKeys `shouldBe` [k1] + void $ ExceptT $ deleteQueue ms q + -- sizes of queues, senders, links and notifiers maps type QueueMapSizes = (Int, Int, Int, Int) @@ -482,6 +501,29 @@ testResetMessageCounts ms = do void $ withTransaction (dbStore $ queueStore ms) $ \db -> DB.execute db "UPDATE msg_queues SET msg_queue_size = ?, msg_can_write = ? WHERE recipient_id = ?" (size, canWrt, recipientId q) +testFoldServiceMessagesInPages :: PostgresMsgStore -> IO () +testFoldServiceMessagesInPages ms = do + g <- C.newRandom + serviceId <- atomically $ EntityId <$> C.randomBytes 24 g + void $ withTransaction st $ \db -> + DB.execute db "INSERT INTO services (service_id, service_role, service_cert, service_cert_hash, created_at) VALUES (?, 'M', '', '', 0)" (Only serviceId) + void $ newQueue g Nothing + qs <- replicateM 150 $ newQueue g (Just serviceId) + runRight_ $ forM_ (take 75 qs) $ \q -> writeMsg ms q True =<< mkMessage "message" + expected <- runRight $ forM qs $ \q -> do + msg_ <- tryPeekMsg ms q + pure (recipientId q, (Right (messageId <$> msg_), dbPoolSize st)) + Right folded <- foldRcvServiceMessages ms serviceId collect [] + sortOn fst folded `shouldBe` sortOn fst expected + where + st = dbStore $ queueStore ms + newQueue g rcvServiceId = do + (rId, qr) <- testNewQueueRec g QMMessaging + runRight $ ExceptT $ addQueue ms rId qr {rcvServiceId} + collect acc rId r = do + freeConns <- fromIntegral <$> atomically (lengthTBQueue $ dbPoolConns $ dbPool st) + pure $ (rId, (fmap (messageId . snd) <$> r, freeConns)) : acc + testExpireMessagesInBatches :: PostgresMsgStore -> IO () testExpireMessagesInBatches ms = do g <- C.newRandom diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index a554d1eef..db49434de 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -15,7 +15,7 @@ module NtfServerTests where import Control.Concurrent (threadDelay) import Control.Exception (bracket) -import Control.Monad (forM, unless, void) +import Control.Monad (forM, replicateM, unless, void) import qualified Data.Aeson as J import qualified Data.Aeson.Types as JT import Data.Bifunctor (first) @@ -51,7 +51,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Env (NtfServerConfig (..)) import Simplex.Messaging.Notifications.Server.Push.APNS -import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfPostgresStore (dbStore), closeNtfDbStore, newNtfDbStore, withClientDB, withDB') +import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfPostgresStore (dbStore), closeNtfDbStore, getEntityCounts, newNtfDbStore, withClientDB, withDB') import Simplex.Messaging.Notifications.Transport (THandleNTF) import Simplex.Messaging.Parsers (parse, parseAll) import Simplex.Messaging.Protocol hiding (notification) @@ -74,6 +74,7 @@ ntfServerTests ps@(t, _) = do describe "APNS push delivery" $ do it "resumes sending notifications after the push provider is unreachable" $ testPushWorkerResumesAfterOutage t it "does not connect to the push provider when the key file is not configured" testNoConnectWithoutKeyFile + it "receives notifications from other servers when one server's push queue is full" $ testFullPushQueue ps describe "Database pool" $ do it "answers SNEW with one database connection" $ testSNEWOneDBConnection t describe "Notification subscriptions (NKEY)" $ testNotificationSubscription ps createNtfQueueNKEY @@ -168,6 +169,36 @@ testNoConnectWithoutKeyFile = apnsCfgMissingKey = apnsConfig {authKeyFileEnv = "APNS_KEY_FILE_MISSING"} keyFileError (e :: IOError) = "APNS_KEY_FILE_MISSING" `isInfixOf` show e +testFullPushQueue :: HasTestEnv => (ASrvTransport, AStoreType) -> Expectation +testFullPushQueue (ATransport t, msType) = do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + withAPNSMockServer $ \apns -> + smpTest2 t msType $ \rh sh -> + ntfTest t $ \nh -> bracket (newNtfDbStore ntfTestDBCfg) closeNtfDbStore $ \st -> do + (tknKey, _, tId, regCode) <- registerToken nh apns "abcd" + RespNtf "1" _ NROk <- signSendRecvNtf nh tknKey ("1", tId, TVFY regCode) + (tknKey2, _, tId2, regCode2) <- registerToken nh apns "efgh" + RespNtf "2" _ NROk <- signSendRecvNtf nh tknKey2 ("2", tId2, TVFY regCode2) + let subscribe key tknId srv = do + ((sId, _, _, _), nId, _) <- createNtfQueueNKEY rh sPub nPub + RespNtf "3" NoEntity (NRSubId _) <- signSendRecvNtf nh key ("3", NoEntity, SNEW $ NewNtfSub tknId (SMPQueueNtf srv nId) nKey) + pure sId + sendMsg sId = do + Resp "4" _ OK <- signSendRecv sh sKey ("4", sId, _SEND' "hello") + pure () + checkLastNtfs n = do + (_, _, cnt) <- getEntityCounts st + unless (cnt == n) $ threadDelay 100000 >> checkLastNtfs n + waitLastNtfs n = timeout 5000000 (checkLastNtfs n) `shouldReturn` Just () + sIds <- replicateM 6 $ subscribe tknKey tId $ SMPServer SMP.testHost SMP.testPort SMP.testKeyHash + sId2 <- subscribe tknKey2 tId2 $ SMPServer SMP.testHost2 SMP.testPort SMP.testKeyHash + mapM_ sendMsg sIds + waitLastNtfs 6 + sendMsg sId2 + waitLastNtfs 7 + testSNEWOneDBConnection :: HasTestEnv => ASrvTransport -> Expectation testSNEWOneDBConnection (ATransport (t :: TProxy c 'TServer)) = do g <- C.newRandom @@ -423,25 +454,35 @@ testResubscribeOnServiceIdChange ps@(ATransport (t :: TProxy c 'TServer), _) = d testNtfClient $ \(nh :: THandleNTF c 'TClient) -> do (tknKey, _dhSecret, tId, regCode) <- registerToken nh apns "abcd" RespNtf "2" _ NROk <- signSendRecvNtf nh tknKey ("2", tId, TVFY regCode) - let checkActive subId = do + let checkStatus expected subId = do RespNtf "4" _ (NRSub status) <- signSendRecvNtf nh tknKey ("4", subId, SCHK) - unless (status == NSActive) $ threadDelay 100000 >> checkActive subId - waitActive subIds = timeout 5000000 (mapM_ checkActive subIds) `shouldReturn` Just () - (sId, subIds) <- withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do + unless (status == expected) $ threadDelay 100000 >> checkStatus expected subId + waitStatus expected subIds = timeout 5000000 (mapM_ (checkStatus expected) subIds) `shouldReturn` Just () + waitActive = waitStatus NSActive + (sId, subIds, endedSubId) <- withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do ((sId, _, _, _), nId1, _) <- createNtfQueueNKEY h sPub nPub (_, nId2, _) <- createNtfQueueNKEY h sPub nPub - subIds <- forM [nId1, nId2] $ \nId -> do + (_, nId3, _) <- createNtfQueueNKEY h sPub nPub + [subId1, subId2, endedSubId] <- forM [nId1, nId2, nId3] $ \nId -> do RespNtf "3" NoEntity (NRSubId subId) <- signSendRecvNtf nh tknKey ("3", NoEntity, SNEW $ NewNtfSub tId (SMPQueueNtf srv nId) nKey) pure subId - waitActive subIds - pure (sId, subIds) + waitActive [subId1, subId2, endedSubId] + Resp "4" _ (SOK Nothing) <- signSendRecv h nKey ("4", nId3, NSUB) + waitStatus NSEnd [endedSubId] + pure (sId, [subId1, subId2], endedSubId) st <- newNtfDbStore ntfTestDBCfg Right 1 <- withDB' "test" st $ \db -> PSQL.execute_ db "UPDATE smp_servers SET ntf_service_cert = NULL, ntf_service_cert_hash = NULL, ntf_service_priv_key = NULL" + let checkNotificationAfterRestart = withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do + Resp "5" _ OK <- signSendRecv h sKey ("5", sId, _SEND' "hello") + APNSMockRequest {notification = APNSNotification {aps = APNSMutableContent {}}} <- getMockNotification apns $ DeviceToken PPApnsTest "abcd" + waitActive subIds + getServiceId = withDB' "test" st $ \db -> PSQL.query_ db "SELECT ntf_service_id FROM smp_servers" + checkNotificationAfterRestart + Right [PSQL.Only (Just (newServiceId :: ServiceId))] <- getServiceId + checkNotificationAfterRestart + getServiceId `shouldReturn` Right [PSQL.Only (Just newServiceId)] + RespNtf "5" _ (NRSub NSEnd) <- signSendRecvNtf nh tknKey ("5", endedSubId, SCHK) closeNtfDbStore st - withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do - Resp "5" _ OK <- signSendRecv h sKey ("5", sId, _SEND' "hello") - APNSMockRequest {notification = APNSNotification {aps = APNSMutableContent {}}} <- getMockNotification apns $ DeviceToken PPApnsTest "abcd" - waitActive subIds type CreateQueueFunc = forall c. From 64c040f7b938eb89eecea9a97383a0b50dd9fae6 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:38:12 +0000 Subject: [PATCH 025/159] smp server: end the replaced service subscription on each accepted SUB --- src/Simplex/Messaging/Server.hs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index a8920f92d..7d1bf69fa 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1681,7 +1681,7 @@ client case command of SUB -> case batchSubs >>= \(msgs, rcvAssocs, _, subs) -> sequence (M.lookup entId rcvAssocs) $> (msgs, subs) of Left e -> pure $ Just (err e, Nothing) - Right (msgs, subs) -> withQueue' $ deliverSubMsg (M.lookup entId msgs) (M.lookup entId subs) + Right (msgs, rcvAssoc_) -> withQueue' $ \_ -> subscribeQueueAndDeliver (M.lookup entId msgs) rcvAssoc_ GET -> withQueue getMessage ACK msgId -> withQueue $ acknowledgeMsg msgId KEY sKey -> withQueue $ \q _ -> either err (corrId,entId,) <$> secureQueue_ q sKey @@ -1822,12 +1822,25 @@ client suspendQueue_ :: (StoreQueue s, QueueRec) -> M s (Transmission BrokerMsg) suspendQueue_ (q, _) = liftIO $ either err (const ok) <$> suspendQueue (queueStore ms) q - deliverSubMsg :: Maybe Message -> Maybe (Either ErrorType (Bool, Maybe Sub)) -> StoreQueue s -> QueueRec -> M s ResponseAndMessage - deliverSubMsg msg_ r_ _ qr = case r_ of - Just (Right r) -> deliver r - Just (Left e) -> pure (err e, Nothing) - Nothing -> pure (err INTERNAL, Nothing) + subscribeQueueAndDeliver :: Maybe Message -> Maybe (TVar (Maybe ServiceId)) -> QueueRec -> M s ResponseAndMessage + subscribeQueueAndDeliver msg_ rcvAssoc_ qr = + liftIO (TM.lookupIO entId $ subscriptions clnt) >>= \case + Nothing -> + deliver =<< subscribeQueue + Just s@Sub {subThread} -> do + stats <- asks serverStats + case subThread of + ProhibitSub -> do + -- cannot use SUB in the same connection where GET was used + incStat $ qSubProhibited stats + pure (err (CMD PROHIBITED), Nothing) + _ -> do + incStat $ qSubDuplicate stats + atomically (writeTVar (delivered s) Nothing) >> subscribeQueue >> deliver (True, Just s) where + subscribeQueue = do + rcvServiceId <- replacedServiceId rcvAssoc_ + sharedSubscribeQueue rcvServiceId subscribers subscriptions serviceSubsCount (newSubscription NoSub) rcvServices deliver :: (Bool, Maybe Sub) -> M s ResponseAndMessage deliver (hasSub, sub_) = do stats <- asks serverStats From 910783ad8c594f5ecc35d08e0ac2d47ed7b862a7 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:40:28 +0000 Subject: [PATCH 026/159] smp server: keep the service association of a blocked queue on SUB --- src/Simplex/Messaging/Server.hs | 11 ++-- tests/ServerTests.hs | 96 +++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 5 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 7d1bf69fa..67e94cc25 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1432,11 +1432,12 @@ client prepareBatchSubs clntServiceId_ batch = do let (subMsgQs, rcvAssocQs, ntfAssocQs) = foldr partitionSubs ([], [], []) batch partitionSubs t (msgQs, rcvQs, ntfQs) = case t of - (Just (q, qr), (_, _, Cmd SRecipient SUB)) - | clntServiceId_ /= rcvServiceId qr -> ((q, qr) : msgQs, q : rcvQs, ntfQs) - | otherwise -> ((q, qr) : msgQs, rcvQs, ntfQs) - (Just (q, qr), (_, _, Cmd SNotifier NSUB)) - | clntServiceId_ /= (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, q : ntfQs) + (Just (_, QueueRec {status = EntityBlocked _}), (_, _, Cmd SRecipient SUB)) -> (msgQs, rcvQs, ntfQs) + (Just (q, qr), (_, entId, Cmd SRecipient SUB)) + | clntServiceId_ /= rcvServiceId qr -> (q : msgQs, M.insert entId q rcvQs, ntfQs) + | otherwise -> (q : msgQs, rcvQs, ntfQs) + (Just (q, qr), (_, entId, Cmd SNotifier NSUB)) + | clntServiceId_ /= (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, M.insert entId q ntfQs) _ -> (msgQs, rcvQs, ntfQs) runExceptT $ do rcvAssocs <- ifNotNull rcvAssocQs $ setService SRecipientService clntServiceId_ diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index daef9034c..e3102b2c3 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -110,6 +110,9 @@ serverTests = do testServiceSubAssociatedQueue testServiceDowngradeConnected testServiceSubsReplacesConnection + testServiceRepeatedSUB + testServiceSubsReturnsToConnection + testServiceSubBlockedQueue describe "Store log" testWithStoreLog describe "Restore messages" testRestoreMessages describe "Restore messages (old / v2)" testRestoreExpireMessages @@ -1353,6 +1356,99 @@ testServiceSubsReplacesConnection = Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg sh1 pure () +testServiceRepeatedSUB :: SpecWith (ASrvTransport, AStoreType) +testServiceRepeatedSUB = + it "should count the queue once when the service repeats SUB in one block" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + Resp "1" NoEntity (Ids rId _ _) <- signSendRecv h rKey ("1", NoEntity, New rPub dhPub) + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1@THandle {params} -> do + let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth params (CorrId "2", rId, SUB) + Right auth <- pure $ authTransmission (thAuth params) True (Just rKey) Nothing tForAuth + let sub = Right (auth, tToSend) + [Right (), Right ()] <- tPut sh1 [sub, sub] + [Resp "2" _ (SOK (Just serviceId)), Resp "2" _ (SOK (Just _))] <- tGetClient sh1 + Resp "" rId' END <- tGet1 h + rId' `shouldBe` rId + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeServiceQueues sh2 aServicePK "3" serviceId [rId] + Resp "" _ (ENDS n idsHash) <- tGet1 sh1 + (n, idsHash) `shouldBe` (1, queueIdsHash [rId]) + +testServiceSubsReturnsToConnection :: SpecWith (ASrvTransport, AStoreType) +testServiceSubsReturnsToConnection = + it "should move the service subscription back to the replaced connection when it subscribes again" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + (rId, sId, dec, serviceId) <- runSMPServiceClient t (tlsCred, serviceKeys) $ \sh -> do + Resp "1" NoEntity (Ids_ rId sId srvDh serviceId) <- serviceSignSendRecv sh rKey servicePK ("1", NoEntity, New rPub dhPub) + pure (rId, sId, decryptMsgV3 $ C.dh' srvDh dhPriv, serviceId) + let subscribeService sh corrId = subscribeServiceQueues sh aServicePK corrId serviceId [rId] + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1 -> do + subscribeService sh1 "2" + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeService sh2 "3" + Resp "" _ (ENDS 1 _) <- tGet1 sh1 + subscribeService sh1 "4" + Resp "" _ (ENDS 1 _) <- tGet1 sh2 + Resp "5" _ OK <- sendRecv h ("", "5", sId, _SEND "hello") + Resp "" _ (Msg mId msg) <- tGet1 sh1 + dec mId msg `shouldBe` Right "hello" + Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg sh2 + pure () + +testServiceSubBlockedQueue :: SpecWith (ASrvTransport, AStoreType) +testServiceSubBlockedQueue = + it "should keep the service subscription to a blocked queue when another connection subscribes it" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + cpPort = testServerPort 8 + cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {controlPort = Just cpPort, controlPortAdminAuth = Just "admin"} + info = BlockingInfo BRContent Nothing + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1 -> do + Resp "1" NoEntity (Ids_ rId sId _ serviceId) <- serviceSignSendRecv sh1 rKey servicePK ("1", NoEntity, New rPub dhPub) + [_, blocked] <- controlPortCommands cpPort ["auth admin", "block " <> B.unpack (strEncode sId) <> " " <> B.unpack (strEncode info)] + blocked `shouldStartWith` "ok, queue blocked" + Resp "2" _ (ERR (BLOCKED _)) <- signSendRecv h rKey ("2", rId, SUB) + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeServiceQueues sh2 aServicePK "3" serviceId [rId] + Resp "" _ (ENDS n idsHash) <- tGet1 sh1 + (n, idsHash) `shouldBe` (1, queueIdsHash [rId]) + +subscribeServiceQueues :: (HasCallStack, Transport c) => THandleSMP c 'TClient -> C.APrivateAuthKey -> ByteString -> ServiceId -> [RecipientId] -> IO () +subscribeServiceQueues sh servicePK corrId serviceId rIds = do + let n = fromIntegral $ length rIds + idsHash = queueIdsHash rIds + signSend_ sh servicePK Nothing (corrId, serviceId, SUBS n idsHash) + void $ + receiveInAnyOrder + sh + [ \case + Resp corrId' serviceId' (SOKS n' idsHash') | corrId' == CorrId corrId -> Just () <$ ((serviceId', n', idsHash') `shouldBe` (serviceId, n, idsHash)) + _ -> pure Nothing, + \case + Resp "" NoEntity ALLS -> pure $ Just () + _ -> pure Nothing + ] + readServiceSubsMetric :: String -> Maybe Int readServiceSubsMetric content = case filter ("simplex_smp_subscribtion_service_subs_total " `isPrefixOf`) (lines content) of From 9977e2dd9866e668a66421da7f9f0ccb9a66daab Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:41:56 +0000 Subject: [PATCH 027/159] smp server: associate every service SUB and NSUB in the queue store --- src/Simplex/Messaging/Server.hs | 4 +-- .../Messaging/Server/QueueStore/Postgres.hs | 8 ++--- .../Messaging/Server/QueueStore/STM.hs | 32 +++++++++++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 67e94cc25..95496eb04 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1434,10 +1434,10 @@ client partitionSubs t (msgQs, rcvQs, ntfQs) = case t of (Just (_, QueueRec {status = EntityBlocked _}), (_, _, Cmd SRecipient SUB)) -> (msgQs, rcvQs, ntfQs) (Just (q, qr), (_, entId, Cmd SRecipient SUB)) - | clntServiceId_ /= rcvServiceId qr -> (q : msgQs, M.insert entId q rcvQs, ntfQs) + | isJust clntServiceId_ || isJust (rcvServiceId qr) -> (q : msgQs, M.insert entId q rcvQs, ntfQs) | otherwise -> (q : msgQs, rcvQs, ntfQs) (Just (q, qr), (_, entId, Cmd SNotifier NSUB)) - | clntServiceId_ /= (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, M.insert entId q ntfQs) + | isJust clntServiceId_ || isJust (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, M.insert entId q ntfQs) _ -> (msgQs, rcvQs, ntfQs) runExceptT $ do rcvAssocs <- ifNotNull rcvAssocQs $ setService SRecipientService clntServiceId_ diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 891877c1b..8aad583c4 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -388,11 +388,9 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where (rId,) <$> if S.member rId updated then readQueueRecIO (queueRec sq) $>>= \q -> do atomically $ writeTVar (queueRec sq) $ Just $ updateRec q - withLog "setQueueServices" st $ \sl -> logQueueService sl rId party serviceId - pure $ Right () - else pure $ Left AUTH - pure $ M.fromList results - where + when (prevSrvId /= serviceId) $ withLog "setQueueServices" st $ \sl -> logQueueService sl (recipientId sq) party serviceId + pure $ Right prevSrvId + Nothing -> pure $ Left AUTH updateQuery = case party of SRecipientService -> "UPDATE msg_queues SET rcv_service_id = ? WHERE recipient_id IN ? AND deleted_at IS NULL RETURNING recipient_id" diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index f7f3e9acb..0f164592a 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -372,6 +372,38 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where SRecipientService -> serviceRcvQueues SNotifierService -> serviceNtfQueues +setQueueService_ :: (StoreQueueClass q, PartyI p, ServiceParty p) => STMQueueStore q -> Maybe QueueId -> q -> SParty p -> Maybe ServiceId -> IO (Either ErrorType (Maybe ServiceId)) +setQueueService_ st qId_ sq party serviceId = + atomically (readQueueRec qr $>>= setService) + $>>= \prevSrvId -> + if prevSrvId == serviceId + then pure $ Right prevSrvId + else prevSrvId <$$ withLog "setQueueService" st (\sl -> logQueueService sl rId party serviceId) + where + qr = queueRec sq + rId = recipientId sq + setService :: QueueRec -> STM (Either ErrorType (Maybe ServiceId)) + setService q@QueueRec {rcvServiceId = prevSrvId} = case party of + SRecipientService + | prevSrvId == serviceId -> pure $ Right prevSrvId + | otherwise -> do + updateServiceQueues serviceRcvQueues rId prevSrvId + let !q' = Just q {rcvServiceId = serviceId} + writeTVar qr q' $> Right prevSrvId + SNotifierService -> case notifier q of + Nothing -> pure $ Left AUTH + Just nc@NtfCreds {notifierId = nId, ntfServiceId = prevNtfSrvId} + | any (/= nId) qId_ -> pure $ Left AUTH + | prevNtfSrvId == serviceId -> pure $ Right prevNtfSrvId + | otherwise -> do + let !q' = Just q {notifier = Just nc {ntfServiceId = serviceId}} + updateServiceQueues serviceNtfQueues nId prevNtfSrvId + writeTVar qr q' $> Right prevNtfSrvId + updateServiceQueues :: (STMService -> TVar (Set QueueId, IdsHash)) -> QueueId -> Maybe ServiceId -> STM () + updateServiceQueues serviceSel qId prevSrvId = do + mapM_ (removeServiceQueue st serviceSel qId) prevSrvId + mapM_ (addServiceQueue st serviceSel qId) serviceId + foldRcvServiceQueues :: StoreQueueClass q => STMQueueStore q -> ServiceId -> (a -> (q, QueueRec) -> IO a) -> a -> IO a foldRcvServiceQueues st serviceId f acc = TM.lookupIO serviceId (services st) >>= \case From cbd27b508c64ce13b246b816bb77383f81613420 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:43:06 +0000 Subject: [PATCH 028/159] smp server: count a deleted queue only for the service it belongs to --- src/Simplex/Messaging/Server.hs | 6 ++---- tests/ServerTests.hs | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 95496eb04..ed4ae8274 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -2297,10 +2297,8 @@ client -- we delete subscription here, so the client with no subscriptions can be disconnected. sub <- atomically $ TM.lookupDelete entId $ subscriptions clnt liftIO $ mapM_ cancelSub sub - when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ whenM (((0 /=) . fst) <$> readTVar (serviceSubsCount clnt)) $ do - modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) - modifyTVar' (totalServiceSubs subscribers) $ subtractServiceSubs (1, queueIdHash (recipientId q)) - liftIO $ processSub clnt $ CSDeleted entId rcvServiceId + when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) + atomically $ writeTQueue (subQ subscribers) (CSDeleted entId rcvServiceId, clientId) forM_ (notifier qr) $ \NtfCreds {notifierId = nId, ntfServiceId} -> do -- queue is deleted by a different client from the one subscribed to notifications, -- so we don't need to remove subscription from the current client. diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index e3102b2c3..090115263 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -113,6 +113,7 @@ serverTests = do testServiceRepeatedSUB testServiceSubsReturnsToConnection testServiceSubBlockedQueue + testServiceDeletesOtherServiceQueue describe "Store log" testWithStoreLog describe "Restore messages" testRestoreMessages describe "Restore messages (old / v2)" testRestoreExpireMessages @@ -1433,6 +1434,32 @@ testServiceSubBlockedQueue = Resp "" _ (ENDS n idsHash) <- tGet1 sh1 (n, idsHash) `shouldBe` (1, queueIdsHash [rId]) +testServiceDeletesOtherServiceQueue :: SpecWith (ASrvTransport, AStoreType) +testServiceDeletesOtherServiceQueue = + it "should keep the subscription count of a service connection that deletes a queue of another service" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + credsA <- genCredentials g Nothing (0, 2400) "localhost" + credsB <- genCredentials g Nothing (0, 2400) "localhost" + let (_, tlsCredA) = tlsCredentials [credsA] + (_, tlsCredB) = tlsCredentials [credsB] + serviceKeysA@(_, servicePKA) <- atomically $ C.generateKeyPair g + serviceKeysB@(_, servicePKB) <- atomically $ C.generateKeyPair g + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> do + (rPubA, rKeyA) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rPubB, rKeyB) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + runSMPServiceClient t (tlsCredA, serviceKeysA) $ \shA -> do + Resp "1" NoEntity (Ids_ rIdA _ _ _) <- serviceSignSendRecv shA rKeyA servicePKA ("1", NoEntity, New rPubA dhPub) + runSMPServiceClient t (tlsCredB, serviceKeysB) $ \shB -> do + Resp "2" NoEntity (Ids_ rIdB _ _ serviceIdB) <- serviceSignSendRecv shB rKeyB servicePKB ("2", NoEntity, New rPubB dhPub) + Resp "3" _ OK <- signSendRecv shB rKeyA ("3", rIdA, DEL) + Resp "" rIdA' DELD <- tGet1 shA + rIdA' `shouldBe` rIdA + runSMPServiceClient t (tlsCredB, serviceKeysB) $ \shB' -> do + subscribeServiceQueues shB' (C.APrivateAuthKey C.SEd25519 servicePKB) "4" serviceIdB [rIdB] + Resp "" _ (ENDS n idsHash) <- tGet1 shB + (n, idsHash) `shouldBe` (1, queueIdsHash [rIdB]) + subscribeServiceQueues :: (HasCallStack, Transport c) => THandleSMP c 'TClient -> C.APrivateAuthKey -> ByteString -> ServiceId -> [RecipientId] -> IO () subscribeServiceQueues sh servicePK corrId serviceId rIds = do let n = fromIntegral $ length rIds From ea24bc2d90382e164a7df15987f1aa46f1fb0432 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:43:56 +0000 Subject: [PATCH 029/159] tests: replaced notification service connection subscribing again --- tests/ServerTests.hs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 090115263..62045b4bb 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -126,6 +126,8 @@ serverTests = do testMessageServiceNotifications testServiceNotificationsTwoRestarts testNotificationsInChunks + testServiceNotificationsRepeatedNSUB + testServiceNotificationsReturnToConnection describe "Message expiration" $ do testMsgExpireOnSend testMsgExpireOnInterval @@ -2270,6 +2272,39 @@ testNotificationsInChunks = do ts <- 5000000 `timeout` tGetClient h >>= maybe (error "receive timeout") (pure . toList) (ts :) <$> receiveBlocks h (n - length ts) +testServiceNotificationsReturnToConnection :: SpecWith (ASrvTransport, AStoreType) +testServiceNotificationsReturnToConnection = + it "should move the notification service subscription back to the replaced connection when it subscribes again" $ \(ATransport t, msType) -> do + g <- C.newRandom + smpTest2 t msType $ \rh sh -> do + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (sId, rId, rKey, _) <- createAndSecureQueue rh sPub + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvNtfPubDhKey, _) <- atomically $ C.generateKeyPair g + Resp "1" _ (NID nId _) <- signSendRecv rh rKey ("1", rId, NKEY nPub rcvNtfPubDhKey) + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + serviceId <- testNtfServiceClient t serviceKeys $ \nh -> do + Resp "2" _ (SOK (Just serviceId)) <- serviceSignSendRecv nh nKey servicePK ("2", nId, NSUB) + pure serviceId + let idsHash = queueIdsHash [nId] + subscribeService nh corrId = do + Resp _ serviceId' (SOKS n idsHash') <- signSendRecv nh (C.APrivateAuthKey C.SEd25519 servicePK) (corrId, serviceId, NSUBS 1 idsHash) + (serviceId', n, idsHash') `shouldBe` (serviceId, 1, idsHash) + testNtfServiceClient t serviceKeys $ \nh1 -> do + subscribeService nh1 "3" + testNtfServiceClient t serviceKeys $ \nh2 -> do + subscribeService nh2 "4" + Resp "" _ (ENDS 1 _) <- tGet1 nh1 + subscribeService nh1 "5" + Resp "" _ (ENDS 1 _) <- tGet1 nh2 + Resp "6" _ OK <- signSendRecv sh sKey ("6", sId, _SEND' "hello") + Resp "" _ (Msg mId _) <- tGet1 rh + Resp "7" _ OK <- signSendRecv rh rKey ("7", rId, ACK mId) + Resp "" nId' (NMSG _ _) <- tGet1 nh1 + nId' `shouldBe` nId + Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg nh2 + pure () + testMsgExpireOnSend :: SpecWith (ASrvTransport, AStoreType) testMsgExpireOnSend = it "should expire messages that are not received before messageTTL on SEND" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do From 072c0a24f9b52286c3ec7a0ab2f237acf85e00aa Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:18:49 +0000 Subject: [PATCH 030/159] lib: reject server without key hash, except in short links --- src/Simplex/Messaging/Agent/Protocol.hs | 8 ++++---- src/Simplex/Messaging/Notifications/Protocol.hs | 6 +----- src/Simplex/Messaging/Protocol.hs | 9 +++++++-- tests/AgentTests/ConnectionRequestTests.hs | 6 ++++++ tests/SMPProxyTests.hs | 14 ++++++++++++++ 5 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Protocol.hs b/src/Simplex/Messaging/Agent/Protocol.hs index 35ae55b5e..91949aba0 100644 --- a/src/Simplex/Messaging/Agent/Protocol.hs +++ b/src/Simplex/Messaging/Agent/Protocol.hs @@ -1799,12 +1799,12 @@ instance Encoding AConnShortLink where smpP = smpP >>= \case CMInvitation -> do - (srv, lnkId, k) <- smpP - pure $ ACSL SCMInvitation $ CSLInvitation SLSServer srv lnkId (LinkKey k) + ((hs, p, kh), lnkId, k) <- smpP + pure $ ACSL SCMInvitation $ CSLInvitation SLSServer (SMPServer hs p kh) lnkId (LinkKey k) CMContact -> do ct <- ctTypeP =<< A.anyChar - (srv, k) <- smpP - pure $ ACSL SCMContact $ CSLContact SLSServer ct srv (LinkKey k) + ((hs, p, kh), k) <- smpP + pure $ ACSL SCMContact $ CSLContact SLSServer ct (SMPServer hs p kh) (LinkKey k) ctTypeP :: Char -> Parser ContactConnType ctTypeP = \case diff --git a/src/Simplex/Messaging/Notifications/Protocol.hs b/src/Simplex/Messaging/Notifications/Protocol.hs index 423a048e1..44f096f9b 100644 --- a/src/Simplex/Messaging/Notifications/Protocol.hs +++ b/src/Simplex/Messaging/Notifications/Protocol.hs @@ -384,13 +384,9 @@ data SMPQueueNtf = SMPQueueNtf instance Encoding SMPQueueNtf where smpEncode SMPQueueNtf {smpServer, notifierId} = smpEncode (smpServer, notifierId) smpP = do - smpServer <- updateSMPServerHosts <$> (requireKeyHash <$?> smpP) + smpServer <- updateSMPServerHosts <$> smpP notifierId <- smpP pure SMPQueueNtf {smpServer, notifierId} - where - requireKeyHash srv - | B.null (C.unKeyHash (keyHash srv)) = Left "SMP server without key hash" - | otherwise = Right srv instance StrEncoding SMPQueueNtf where strEncode SMPQueueNtf {smpServer, notifierId} = strEncode smpServer <> "/" <> strEncode notifierId diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 05efa40c5..242de05e3 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -1334,7 +1334,7 @@ instance ProtocolTypeI p => IsString (ProtocolServer p) where instance ProtocolTypeI p => Encoding (ProtocolServer p) where smpEncode ProtocolServer {host, port, keyHash} = smpEncode (host, port, keyHash) - smpP = do + smpP = requireKeyHash <$?> do (host, port, keyHash) <- smpP pure ProtocolServer {scheme = protocolTypeI @p, host, port, keyHash} @@ -1353,6 +1353,11 @@ instance ProtocolTypeI p => ToJSON (ProtocolServer p) where instance ProtocolTypeI p => FromJSON (ProtocolServer p) where parseJSON = strParseJSON "ProtocolServer" +requireKeyHash :: ProtocolServer p -> Either String (ProtocolServer p) +requireKeyHash srv@ProtocolServer {keyHash} + | B.null (C.unKeyHash keyHash) = Left "server without key hash" + | otherwise = Right srv + newtype BasicAuth = BasicAuth {unBasicAuth :: ByteString} deriving (Ord, Show) @@ -1419,7 +1424,7 @@ legacyEncodeServer ProtocolServer {host, port, keyHash} = smpEncode (L.head host, port, keyHash) legacyServerP :: forall p. ProtocolTypeI p => Parser (ProtocolServer p) -legacyServerP = do +legacyServerP = requireKeyHash <$?> do (h, port, keyHash) <- smpP pure ProtocolServer {scheme = protocolTypeI @p, host = [h], port, keyHash} diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index 71dad0dfe..b61f589ad 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -321,6 +321,12 @@ connectionRequestTests = smpEncodingTest (aBinaryConnReq contactAddress2queuesNew) smpEncodingTest (aBinaryConnReq contactAddressV6) smpEncodingTest (aBinaryConnReq contactAddressClientData) + it "should parse server without key hash only in short links as binary" $ do + let addr = queueAddr {smpServer = shortSrv} + smpDecode @SMPQueueUri (smpEncode $ SMPQueueUri supportedSMPClientVRange addr) `shouldSatisfy` isLeft + smpDecode @SMPQueueInfo (smpEncode $ SMPQueueInfo (VersionSMPC 1) addr) `shouldSatisfy` isLeft + smpEncodingTest $ ACSL SCMContact $ CSLContact SLSServer CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") + smpEncodingTest $ ACSL SCMInvitation $ CSLInvitation SLSServer shortSrv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") it "should serialize / parse short links" $ do CSLContact SLSServer CCTContact srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLContact SLSServer CCTGroup srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/g#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index c606d73ff..079ac1668 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -82,6 +82,13 @@ smpProxyTests = do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel describe "proxy requests" $ do + describe "bad relay URIs" $ do + it "relay without key hash" testRelayWithoutKeyHash + xit "host not resolved" todo + xit "when SMP port blackholed" todo + xit "no SMP service at host/port" todo + xit "bad SMP fingerprint" todo + xit "batching proxy requests" todo it "relay rejects forwarded command with changed version" $ \_ -> testChangedFwdVersion it "proxy rejects forwarded correlation ID that is not 24 bytes" $ \_ -> @@ -464,6 +471,13 @@ testProxyAuth msType = do where proxyCfgAuth = updateCfg (proxyCfgMS msType) $ \cfg_ -> cfg_ {newQueueBasicAuth = Just "correct"} +testRelayWithoutKeyHash :: HasTestEnv => AStoreType -> IO () +testRelayWithoutKeyHash msType = do + withSmpServerConfigOn (transport @TLS) (proxyCfgMS msType) testPort $ \_ -> do + testSMPClient_ "127.0.0.1" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (_, _, reply) <- sendRecv th (Nothing, "0", NoEntity, SMP.PRXY (SMPServer testHost testPort2 (C.KeyHash "")) Nothing) + reply `shouldBe` Right (SMP.ERR $ SMP.CMD SMP.SYNTAX) + -- Connect a sender client to the proxy and request a relay session to testSMPServer2 (PRXY). -- On success the reply is PKEY; otherwise it is the proxy error for the relay connection. requestRelaySession :: HasTestEnv => IO (Either SMP.ErrorType SMP.BrokerMsg) From f90e5a23a805a40d0e568b0228fa43aa86e20b28 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:47:35 +0000 Subject: [PATCH 031/159] agent: reject short link to server without key hash --- src/Simplex/Messaging/Agent.hs | 6 ++++++ src/Simplex/Messaging/Protocol.hs | 1 + tests/AgentTests/FunctionalAPITests.hs | 15 +++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 007aaaf5a..00f418ded 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1216,6 +1216,7 @@ setConnShortLinkAsync' c corrId connId userLinkData clientData = getConnShortLinkAsync' :: AgentClient -> UserId -> ACorrId -> Maybe ConnId -> ConnShortLink 'CMContact -> AM ConnId getConnShortLinkAsync' c userId corrId connId_ shortLink@(CSLContact _ _ srv _) = do + checkShortLinkServer srv connId <- case connId_ of Just existingConnId -> do -- connId and srv can be unrelated: connId is used as "mailbox" for LDATA delivery, @@ -1248,6 +1249,9 @@ getConnShortLinkAsync' c userId corrId connId_ shortLink@(CSLContact _ _ srv _) } createNewConn db g cData SCMInvitation +checkShortLinkServer :: SMPServer -> AM () +checkShortLinkServer = void . liftEitherWith (CMD PROHIBITED . ("short link: " <>)) . SMP.requireKeyHash + setConnShortLink' :: AgentClient -> NetworkRequestMode -> ConnId -> SConnectionMode c -> UserConnLinkData c -> Maybe CRClientData -> NewRatchetKeys -> Maybe CR.InitialKeys -> AM (ConnShortLink c) setConnShortLink' c nm connId cMode userLinkData clientData rotateKeys pqKeys_ = do (rq, lnkId, sl, d) <- withConnLock c connId "setConnShortLink" $ do @@ -1337,6 +1341,7 @@ getConnLinkPrivKey' c connId = do getConnShortLink' :: forall c. AgentClient -> NetworkRequestMode -> UserId -> ConnShortLink c -> AM (FixedLinkData c, ConnLinkData c, ConnectionRequestUri c) getConnShortLink' c nm userId = \case CSLInvitation _ srv linkId linkKey -> do + checkShortLinkServer srv g <- asks random C.AuthAlg a <- asks $ sndAuthAlg . config invLink <- withStore' c $ \db -> do @@ -1352,6 +1357,7 @@ getConnShortLink' c nm userId = \case withStore' c $ \db -> setInvShortLinkSndId db invLink sndId decryptData srv linkKey k ld CSLContact _ _ srv linkKey -> do + checkShortLinkServer srv let (linkId, k) = SL.contactShortLinkKdf linkKey ld <- getQueueLink c nm userId srv linkId decryptData srv linkKey k ld diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 242de05e3..ef9eac7bf 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -213,6 +213,7 @@ module Simplex.Messaging.Protocol sameSrvAddr, sameSrvAddr', noAuthSrv, + requireKeyHash, toMsgInfo, -- * TCP transport functions diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 36688ba40..27f7bc3e4 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -472,6 +472,7 @@ functionalAPITests ps = do it "should not create connection for prepared invitation link with too large data" $ testPrepareInvitationLinkTooLarge ps it "should not create connection for prepared contact link with too large data" $ testPrepareContactLinkTooLarge ps it "should connect via short link prepared for existing contact connection" $ testPrepareConnShortLink ps + it "should refuse short links to servers without key hash" $ testShortLinkWithoutKeyHash ps describe "Message delivery" $ do describe "update connection agent version on received messages" $ do it "should increase if compatible, shouldn'ps decrease" $ @@ -2429,6 +2430,20 @@ testPrepareConnShortLink ps = withSmpServer ps $ withAgentClients2 $ \a b -> do get b ##> ("", aId, CON) exchangeGreetings a bId b aId +testShortLinkWithoutKeyHash :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testShortLinkWithoutKeyHash ps = withSmpServer ps $ withAgentClients2 $ \a b -> do + let userCtData = UserContactData {direct = True, owners = [], relays = [], userData = UserLinkData "test user data", ratchetKeys = Nothing} + (_, CCLink _ (Just contactLink)) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMContact (Just $ UserContactLinkData userCtData) Nothing CR.IKPQOn False SMSubscribe + (_, CCLink _ (Just invLink)) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMInvitation (Just $ UserInvLinkData $ UserLinkData "test user data") Nothing CR.IKUsePQ False SMSubscribe + let hostOnlyLink = shortenShortLink [testSMPServer] contactLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLink b 1 hostOnlyLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLink b 1 $ shortenShortLink [testSMPServer] invLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLinkAsync b 1 "1" Nothing hostOnlyLink + withTransaction (store $ agentEnv b) (`DB.query_` "SELECT host, port FROM servers") `shouldReturn` ([] :: [(T.Text, T.Text)]) + withTransaction (store $ agentEnv b) getConnIds `shouldReturn` [] + (_, ContactLinkData _ userCtData', _) <- runRight $ getConnShortLink b 1 $ restoreShortLink [testSMPServer] hostOnlyLink + userCtData' `shouldBe` userCtData + connReqWithKeys :: BinaryConnectionRequestUri m -> Maybe AddressRatchetKeys -> ConnectionRequestUri m connReqWithKeys cr rk = case cr of BCRInvitationUri crData e2eParams -> CRInvitationUri crData e2eParams From bd5d1816fddcb1e751176d5a782987ddcf3937f3 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:19:47 +0000 Subject: [PATCH 032/159] agent: compare announced minimum version with the client version --- src/Simplex/Messaging/Agent/Client.hs | 21 ++++++++++++++- tests/AgentTests/FunctionalAPITests.hs | 37 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 137e78e70..831a9dcc5 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -796,7 +796,7 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm where connectClient :: SMPClientVar -> AM SMPConnectedClient connectClient v' = do - cfg <- lift $ getClientConfig c smpCfg + cfg@ProtocolClientConfig {serverVRange} <- lift $ getClientConfig c smpCfg g <- asks random service <- getServiceCredentials c userId srv let cfg' = cfg {serviceCredentials = fst <$> service} @@ -806,6 +806,7 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm ExceptT $ getProtocolClient g nm tSess cfg' presetDomains (Just msgQ) ts $ smpClientDisconnected c tSess env v' prs atomically $ SS.setSessionId tSess (sessionId $ thParams smp) $ currentSubs c updateClientService service smp + when (isPresetServer srv presetServers) $ updateClientSupport (maxVersion serverVRange) smp pure SMPConnectedClient {connectedClient = smp, proxiedRelays = prs} updateClientService service smp = case (service, smpClientServiceId smp) of (Just (_, serviceId_), Just serviceId) -> withStore' c $ \db -> do @@ -814,6 +815,24 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm (Just _, Nothing) -> withStore' c $ \db -> deleteClientService db userId srv -- e.g., server version downgrade (Nothing, Just _) -> logError "server returned serviceId without service credentials in request" (Nothing, Nothing) -> pure () + updateClientSupport clientVersion smp = + forM_ (clientSupport =<< eitherToMaybe =<< serverInfo (thParams smp)) $ \cs -> + atomically (stateTVar (presetClientSupport c) $ mergeClientSupport clientVersion cs) + >>= mapM_ (notifySub c . CLIENT_SUPPORT) + +mergeClientSupport :: VersionSMP -> ClientSupport -> ClientSupport -> (Maybe ClientSupport, ClientSupport) +mergeClientSupport v new cs = + (cs' <$ guard (cs' /= cs), cs') + where + cs' = + ClientSupport + { minClientVersion = case (minClientVersion cs, mfilter unsupported $ minClientVersion new) of + (Just m, Just m') | fromDate m <= fromDate m' -> Just m + (m_, m_') -> m_' <|> m_, + stableRelease = stableRelease new <|> stableRelease cs, + betaRelease = betaRelease new <|> betaRelease cs + } + unsupported MinClientVersion {protocolVersion} = VersionSMP protocolVersion > v smpClientDisconnected :: AgentClient -> SMPTransportSession -> Env -> SMPClientVar -> TMap SMPServer ProxiedRelayVar -> SMPClient -> IO () smpClientDisconnected c@AgentClient {active, smpClients, smpProxiedRelays} tSess@(userId, srv, cId) env v prs client = do diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 27f7bc3e4..eb7983177 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4939,6 +4939,43 @@ testServerInformation = serverCountry = Nothing } +testClientSupport :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () +testClientSupport ps = + withClientSupportServers ps cs1 cs2 $ + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer], presetServers = [testSMPServer, testSMPServer2]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB2 $ \bob -> runRight_ $ do + (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing IKPQOn False SMSubscribe + nGet alice ##> ("", "", CLIENT_SUPPORT cs1) + (aliceId, _) <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn + _ <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + ("", _, CONF confId _ "bob's connInfo") <- get alice + allowConnection alice bobId confId "alice's connInfo" + nGet alice ##> ("", "", CLIENT_SUPPORT cs1 {stableRelease = Just "7.2.0"}) + get alice ##> ("", bobId, CON) + get bob ##> ("", aliceId, INFO "alice's connInfo") + get bob ##> ("", aliceId, CON) + where + Version v = currentClientSMPRelayVersion + cs1 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 1, fromDate = fromGregorian 2027 5 1}, stableRelease = Nothing, betaRelease = Nothing} + cs2 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 2, fromDate = fromGregorian 2027 9 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} + +testClientSupportNoEvent :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () +testClientSupportNoEvent ps = + withClientSupportServers ps cs1 cs2 $ + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer], presetServers = [testSMPServer]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB2 $ \bob -> + runRight_ . void $ makeConnection alice bob + where + Version v = currentClientSMPRelayVersion + cs1 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v, fromDate = fromGregorian 2027 5 1}, stableRelease = Nothing, betaRelease = Nothing} + cs2 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 1, fromDate = fromGregorian 2027 5 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} + +withClientSupportServers :: HasTestEnv => (ASrvTransport, AStoreType) -> ClientSupport -> ClientSupport -> IO a -> IO a +withClientSupportServers (t, msType@(ASType qs _)) cs1 cs2 = + withSmpServerConfigOn t (withClientSupport cs1 $ cfgMS msType) testPort . const . withSmpServerConfigOn t (withClientSupport cs2 $ cfgS2QS qs) testPort2 . const + where + withClientSupport cs cfg' = updateCfg cfg' $ \cfg_ -> cfg_ {information = Just testServerInformation {clientSupport = Just cs}} + testConnectionVerifyCodes :: (HasCallStack, HasTestEnv) => IO () testConnectionVerifyCodes = withAgentClients2 $ \a b -> runRight_ $ do From c7471e5112fc116a5effd1753f513259de7bd3af Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:20:09 +0000 Subject: [PATCH 033/159] smp server, agent: evaluate the new TVar state in stateTVar updates --- src/Simplex/Messaging/Agent/Client.hs | 2 +- src/Simplex/Messaging/Server.hs | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 831a9dcc5..494d03522 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -817,7 +817,7 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm (Nothing, Nothing) -> pure () updateClientSupport clientVersion smp = forM_ (clientSupport =<< eitherToMaybe =<< serverInfo (thParams smp)) $ \cs -> - atomically (stateTVar (presetClientSupport c) $ mergeClientSupport clientVersion cs) + atomically (stateTVar' (presetClientSupport c) $ mergeClientSupport clientVersion cs) >>= mapM_ (notifySub c . CLIENT_SUPPORT) mergeClientSupport :: VersionSMP -> ClientSupport -> ClientSupport -> (Maybe ClientSupport, ClientSupport) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index ed4ae8274..e1b478954 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -2206,6 +2206,12 @@ client | tCorrId == C.unCbNonce fwdCorrId -> pure $ tDecodeServer clntTHParams t | otherwise -> throwE CRYPTO _ -> throwE BLOCK + when (fwdVersion < fwdNoncesSMPVersion) $ do + let fwdId = SBS.toShort $ C.unCbNonce fwdCorrId + (used, recorded) <- atomically $ stateTVar' fwdCorrIds $ \ids -> ((S.member fwdId ids, S.size ids), S.insert fwdId ids) + when used $ throwE CRYPTO + maxIds <- asks $ maxFwdCorrIds . config + when (recorded >= maxIds) $ throwIO $ userError "too many forwarded commands below version 23" let clntThAuth = Just $ THAuthServer {serverPrivKey, peerClientService = Nothing, peerEntitlement = Nothing, sessSecret' = Just clientSecret} encodeResp r = do r' <- case batchTransmissions clntTHParams [Right (Nothing, encodeTransmission clntTHParams r)] of From a407853ff851b55acf924a9e94f21c2d08d6250c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:22:28 +0000 Subject: [PATCH 034/159] Revert "agent: require version 23 for private routing to preset servers" This reverts commit beca5081b99f34253cc8d94cb3b17b3f8ef1bc4e, keeping the test of private routing to a server below version 23. --- src/Simplex/Messaging/Agent/Client.hs | 2 +- tests/SMPProxyTests.hs | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 494d03522..2b32a806d 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -323,7 +323,7 @@ import Simplex.Messaging.Session import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), newNtfCredsSMPVersion) +import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, newNtfCredsSMPVersion, pattern VersionSMP) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Credentials import Simplex.Messaging.Util diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 079ac1668..32c409f4f 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -165,6 +165,7 @@ smpProxyTests = do agentViaProxyRetryOffline it "retries sending when destination relay session disconnects in proxy" $ \_ -> agentViaProxyRetryNoSession + it "sends via proxy to relay below version 23" $ twoServersPrevRelay agentViaProxyPrevRelay describe "stress test 1k" $ do let deliver nAgents nMsgs = agentDeliverMessagesViaProxyConc (replicate nAgents [srv1]) (map bshow [1 :: Int .. nMsgs]) it "2 agents, 250 messages" $ oneServer $ deliver 2 250 @@ -455,6 +456,15 @@ agentViaProxyRetryNoSession = do withServer2 = withSmpServerConfigOn (transport @TLS) proxyCfgS2 testPort2 servers srv = initAgentServersProxy {smp = userServers [srv]} +agentViaProxyPrevRelay :: HasTestEnv => IO () +agentViaProxyPrevRelay = + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServersProxy {smp = userServers [testSMPServer]} testDB2 $ \bob -> runRight_ $ do + (aliceId, bobId) <- makeConnection alice bob + 2 <- sendMessage bob aliceId noMsgFlags "hello" + get bob ##> ("", aliceId, A.SENT 2 (Just testSMPServer)) + get alice =##> \case ("", c, Msg "hello") -> c == bobId; _ -> False + testNoProxy :: HasTestEnv => AStoreType -> IO () testNoProxy msType = do withSmpServerConfigOn (transport @TLS) (cfgMS msType) testPort2 $ \_ -> do From 2ca80eea421561f69c8f3e325e493fa521ab7599 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:23:57 +0000 Subject: [PATCH 035/159] smp server: describe version counters by forwarded command version --- src/Simplex/Messaging/Server/Prometheus.hs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index d0c8f4480..9410f0317 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -384,6 +384,11 @@ prometheusMetrics sm rtm ts = \simplex_smp_relay_messages_requests{source=\"all\"} " <> mshow (_pRequests _pMsgFwds) <> "\n# pMsgFwds_pRequests\n\ \simplex_smp_relay_messages_requests{source=\"own\"} " <> mshow (_pRequests _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pRequests\n\ \\n\ + \# HELP simplex_smp_relay_messages_requests_version Message requests sent through relay, by forwarded command version.\n\ + \# TYPE simplex_smp_relay_messages_requests_version counter\n\ + \simplex_smp_relay_messages_requests_version{version=\"below_23\"} " <> mshow _pMsgFwdsBelow23 <> "\n# pMsgFwdsBelow23\n\ + \simplex_smp_relay_messages_requests_version{version=\"from_23\"} " <> mshow _pMsgFwdsFrom23 <> "\n# pMsgFwdsFrom23\n\ + \\n\ \# HELP simplex_smp_relay_messages_successes Successful messages sent through relay.\n\ \# TYPE simplex_smp_relay_messages_successes counter\n\ \simplex_smp_relay_messages_successes{source=\"all\"} " <> mshow (_pSuccesses _pMsgFwds) <> "\n# pMsgFwds_pSuccesses\n\ @@ -414,6 +419,10 @@ prometheusMetrics sm rtm ts = \# HELP simplex_smp_forward_worker_queue_length Forwarded commands waiting in forward worker queues.\n\ \# TYPE simplex_smp_forward_worker_queue_length gauge\n\ \simplex_smp_forward_worker_queue_length " <> mshow fwdWorkerQLength <> "\n# fwdWorkerQLength\n\ + \# HELP simplex_smp_relay_messages_received_version Messages received from proxies, by forwarded command version.\n\ + \# TYPE simplex_smp_relay_messages_received_version counter\n\ + \simplex_smp_relay_messages_received_version{version=\"below_23\"} " <> mshow _pMsgFwdsRecvBelow23 <> "\n# pMsgFwdsRecvBelow23\n\ + \simplex_smp_relay_messages_received_version{version=\"from_23\"} " <> mshow _pMsgFwdsRecvFrom23 <> "\n# pMsgFwdsRecvFrom23\n\ \\n" services = "# Services\n\ From 0200059ed20358ef3bebbd4c10c9d12290b54cc1 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:23:32 +0000 Subject: [PATCH 036/159] smp server: log closing proxy session at the limit of forwarded commands --- src/Simplex/Messaging/Server.hs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index e1b478954..16d8741c3 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -2211,7 +2211,9 @@ client (used, recorded) <- atomically $ stateTVar' fwdCorrIds $ \ids -> ((S.member fwdId ids, S.size ids), S.insert fwdId ids) when used $ throwE CRYPTO maxIds <- asks $ maxFwdCorrIds . config - when (recorded >= maxIds) $ throwIO $ userError "too many forwarded commands below version 23" + when (recorded >= maxIds) $ do + logWarn $ "Closing proxy session: limit of " <> tshow maxIds <> " forwarded commands below version 23" + throwIO $ userError "too many forwarded commands below version 23" let clntThAuth = Just $ THAuthServer {serverPrivKey, peerClientService = Nothing, peerEntitlement = Nothing, sessSecret' = Just clientSecret} encodeResp r = do r' <- case batchTransmissions clntTHParams [Right (Nothing, encodeTransmission clntTHParams r)] of From 2ce36836fafc0035f88295d48408c272158dedc8 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:18:18 +0000 Subject: [PATCH 037/159] smp server: remove a kept relay error at once if its timer cannot start --- src/Simplex/Messaging/Client/Agent.hs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index feb169548..bc6fa2136 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -244,7 +244,9 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke else do ts <- addUTCTime ei <$> liftIO getCurrentTime atomically $ putTMVar (sessionVar v) (Left (e, Just ts)) - reconnectClient ca srv + let removeError = atomically $ removeSessVar v srv smpClients >> modifyTVar' persistedErrors (subtract 1) + void (forkIO $ restore (threadDelay' $ diffToMicroseconds ei) `E.finally` removeError) `E.onException` removeError + restore $ reconnectClient ca srv pure $ Left e isOwnServer :: SMPClientAgent p -> SMPServer -> OwnServer From 866f0786b3d479a26eb1522d06b86cd37e48e444 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:23:13 +0000 Subject: [PATCH 038/159] smp server: metrics of proxy relay sessions, connections and kept errors --- src/Simplex/Messaging/Server.hs | 7 +++++-- src/Simplex/Messaging/Server/Prometheus.hs | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 16d8741c3..136df0d32 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -685,7 +685,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt pure ServerMetrics {statsData = d, activeQueueCounts = ps, activeNtfCounts = psNtf, entityCounts, rtsOptions} getRealTimeMetrics :: Env s -> IO RealTimeMetrics - getRealTimeMetrics Env {sockets, msgStore_ = ms, server = srv@Server {subscribers, ntfSubscribers}} = do + getRealTimeMetrics Env {sockets, msgStore_ = ms, server = srv@Server {subscribers, ntfSubscribers}, proxyAgent = ProxyAgent {smpAgent = SMPClientAgent {smpSessions, connectingClients, persistedErrors}}} = do socketStats <- mapM (traverse getSocketStats) =<< readTVarIO sockets #if MIN_VERSION_base(4,18,0) threadsCount <- length <$> listThreads @@ -693,12 +693,15 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt let threadsCount = 0 #endif clientsCount <- IM.size <$> getServerClients srv + relaySessionsCount <- M.size <$> readTVarIO smpSessions + relayConnectingCount <- readTVarIO connectingClients + relayPersistedErrorsCount <- readTVarIO persistedErrors (deliveredSubs, deliveredTimes) <- getDeliveredMetrics =<< getSystemSeconds smpSubs <- getSubscribersMetrics subscribers ntfSubs <- getSubscribersMetrics ntfSubscribers loadedCounts <- loadedQueueCounts $ fromMsgStore ms fwdWorkerQLength <- fmap sum . mapM fwdQLength =<< getServerClients srv - pure RealTimeMetrics {socketStats, threadsCount, clientsCount, deliveredSubs, deliveredTimes, smpSubs, ntfSubs, loadedCounts, fwdWorkerQLength} + pure RealTimeMetrics {socketStats, threadsCount, clientsCount, relaySessionsCount, relayConnectingCount, relayPersistedErrorsCount, deliveredSubs, deliveredTimes, smpSubs, ntfSubs, loadedCounts, fwdWorkerQLength} where fwdQLength Client {fwdWorkers} = atomically $ readTVar fwdWorkers >>= fmap sum . mapM lengthTBQueue getSubscribersMetrics ServerSubscribers {queueSubscribers, serviceSubscribers, totalServiceSubs, subClients} = do diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index 9410f0317..069cf3424 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -43,6 +43,9 @@ data RealTimeMetrics = RealTimeMetrics { socketStats :: [(ServiceName, SocketStats)], threadsCount :: Int, clientsCount :: Int, + relaySessionsCount :: Int, + relayConnectingCount :: Int, + relayPersistedErrorsCount :: Int, deliveredSubs :: RTSubscriberMetrics, deliveredTimes :: TimeBuckets, smpSubs :: RTSubscriberMetrics, @@ -68,6 +71,9 @@ prometheusMetrics sm rtm ts = { socketStats, threadsCount, clientsCount, + relaySessionsCount, + relayConnectingCount, + relayPersistedErrorsCount, deliveredSubs, deliveredTimes, smpSubs, @@ -423,6 +429,17 @@ prometheusMetrics sm rtm ts = \# TYPE simplex_smp_relay_messages_received_version counter\n\ \simplex_smp_relay_messages_received_version{version=\"below_23\"} " <> mshow _pMsgFwdsRecvBelow23 <> "\n# pMsgFwdsRecvBelow23\n\ \simplex_smp_relay_messages_received_version{version=\"from_23\"} " <> mshow _pMsgFwdsRecvFrom23 <> "\n# pMsgFwdsRecvFrom23\n\ + \# HELP simplex_smp_relay_sessions_total Relay sessions of SMP proxy.\n\ + \# TYPE simplex_smp_relay_sessions_total gauge\n\ + \simplex_smp_relay_sessions_total " <> mshow relaySessionsCount <> "\n# relaySessionsCount\n\ + \\n\ + \# HELP simplex_smp_relay_connecting_total Relay connections being established by SMP proxy.\n\ + \# TYPE simplex_smp_relay_connecting_total gauge\n\ + \simplex_smp_relay_connecting_total " <> mshow relayConnectingCount <> "\n# relayConnectingCount\n\ + \\n\ + \# HELP simplex_smp_relay_persisted_errors_total Relay connection errors persisted by SMP proxy.\n\ + \# TYPE simplex_smp_relay_persisted_errors_total gauge\n\ + \simplex_smp_relay_persisted_errors_total " <> mshow relayPersistedErrorsCount <> "\n# relayPersistedErrorsCount\n\ \\n" services = "# Services\n\ From ab3901565b18206845a847d555215b50c0399fbc Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:08:08 +0000 Subject: [PATCH 039/159] smp server: read peer address only in proxy, consistent own-relay stats --- src/Simplex/Messaging/Client.hs | 3 +- src/Simplex/Messaging/Client/Agent.hs | 10 ++-- src/Simplex/Messaging/Server.hs | 4 +- tests/SMPProxyTests.hs | 69 +++++++++++++++++++++++++++ 4 files changed, 78 insertions(+), 8 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 6ad316db4..9a45ec706 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -656,7 +656,8 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS Left e -> atomically . putTMVar cVar . Left $ PCETransportError e Right th@THandle {params} -> do sessionTs <- getCurrentTime - let c' = ProtocolClient {action = Nothing, client_ = c, thParams = params, sessionTs} + connectedServer <- if proxyServer then (\(connectedHost, connectedPort) -> srv {host = [connectedHost], port = connectedPort}) <$> connectedAddress else pure srv + let c' = ProtocolClient {action = Nothing, client_ = c, thParams = params, sessionTs, connectedServer} atomically $ writeTVar (lastReceived c) sessionTs atomically $ do writeTVar (connected c) True diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index bc6fa2136..06283e1a2 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -230,11 +230,11 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv let !owned = isOwnServer ca srv !c = (owned, smp) - atomically $ do - putTMVar (sessionVar v) (Right c) - TM.insert (sessionId $ thParams smp) c smpSessions - notify ca $ CAConnected srv $ smpClientServiceId smp - pure $ Right c + atomically (sharedSession smp c) >>= \case + Just c0 -> Right c0 <$ E.uninterruptibleMask_ (closeProtocolClient smp) + Nothing -> do + notify ca $ CAConnected srv $ smpClientServiceId smp + pure $ Right c Left e -> do let ei = persistErrorInterval agentCfg if ei == 0 diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 136df0d32..761191b9d 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1546,14 +1546,14 @@ client proxyServerResponse a smp_ = do ServerStats {pRelays, pRelaysOwn} <- asks serverStats let inc = mkIncProxyStats pRelays pRelaysOwn + own = isOwnServer a srv case smp_ of - Right (own, smp) -> do + Right (_, smp) -> do inc own pRequests case proxyResp smp of r@PKEY {} -> r <$ inc own pSuccesses r -> r <$ inc own pErrorsCompat Left e -> do - let own = isOwnServer a srv inc own pRequests inc own $ if temporaryClientError e then pErrorsConnect else pErrorsOther logWarn $ "Error connecting: " <> decodeLatin1 (strEncode $ host srv) <> " " <> tshow e diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 32c409f4f..cda55e3be 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -81,6 +81,15 @@ smpProxyTests = do describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel + describe "relay sessions" $ do + it "uses one session for addresses of one relay" $ \_ -> + testRelaySessionPerServer + it "refuses a new relay session when connections are at the limit" $ \_ -> + testRelayConnectLimit + it "removes connection errors after the interval, above the limit at once" $ \_ -> + testPersistedErrorsLimit + it "refuses a connection at the limit without keeping its error" $ \_ -> + testConnectLimitRefusal describe "proxy requests" $ do describe "bad relay URIs" $ do it "relay without key hash" testRelayWithoutKeyHash @@ -728,6 +737,66 @@ testAgentClientReconnectAfterCancel = netCfg = (netCfg initAgentServers) {tcpConnectTimeout = NetworkTimeout 4000000 4000000} } +testRelaySessionPerServer :: HasTestEnv => IO () +testRelaySessionPerServer = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + sessId <- withRelay $ \_ -> relaySessionId th + threadDelay 100000 + sessId' <- withRelay $ \_ -> relaySessionId th + sessId' `shouldNotBe` sessId + where + withRelay = withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 + relaySessionId th = do + sessId : sessIds <- forM relayServers $ \srv -> do + (_, _, Right (SMP.PKEY sessId _ _)) <- sendRecv th (Nothing, "1", NoEntity, SMP.PRXY srv Nothing) + pure sessId + sessIds `shouldBe` [sessId, sessId, sessId] + pure sessId + relayServers = map (\h -> SMPServer h testPort2 testKeyHash) ["127.0.0.1", "127.0.0.2", "::ffff:127.0.0.1", "127.0.0.1,unused.example"] + +testRelayConnectLimit :: HasTestEnv => IO () +testRelayConnectLimit = + withSmpServerConfigOn (transport @TLS) proxyCfgConnectLimit testPort $ \_ -> + withStallingServerOn' testPort2 $ \accepted _ -> + withAsync requestRelaySession $ \_ -> do + atomically $ takeTMVar accepted + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (t, (_, _, reply)) <- responseTime $ sendRecv th (Nothing, "1", NoEntity, SMP.PRXY (SMPServer testHost2 testPort2 "1234") Nothing) + reply `shouldBe` Right (SMP.ERR $ SMP.PROXY $ SMP.BROKER SMP.TIMEOUT) + t `shouldSatisfy` (< 1) + where + proxyCfgConnectLimit = updateCfg proxyCfgShortTimeout $ \cfg' -> cfg' {smpAgentCfg = (smpAgentCfg cfg') {CA.maxConnectingClients = Just 1}} + +testPersistedErrorsLimit :: HasTestEnv => IO () +testPersistedErrorsLimit = do + g <- C.newRandom + a@CA.SMPClientAgent {CA.smpClients, CA.persistedErrors} <- CA.newSMPClientAgent SMP.SSender CA.defaultSMPClientAgentConfig {CA.persistErrorInterval = 1, CA.maxPersistedErrors = 2} Nothing g + forM_ ([testSMPServer, testSMPServer2, SMPServer testHost testPort2 testKeyHash] :: [SMPServer]) $ \srv -> + runExceptT (CA.getSMPServerClient'' a srv) >>= \case + Left _ -> pure () + Right _ -> expectationFailure "connected to a server that is not running" + length <$> readTVarIO smpClients `shouldReturn` 2 + readTVarIO persistedErrors `shouldReturn` 2 + threadDelay 1500000 + length <$> readTVarIO smpClients `shouldReturn` 0 + readTVarIO persistedErrors `shouldReturn` 0 + CA.closeSMPClientAgent a + +testConnectLimitRefusal :: HasTestEnv => IO () +testConnectLimitRefusal = do + g <- C.newRandom + a@CA.SMPClientAgent {CA.smpClients, CA.connectingClients} <- CA.newSMPClientAgent SMP.SSender CA.defaultSMPClientAgentConfig {CA.maxConnectingClients = Just 0} Nothing g + runExceptT (CA.getSMPServerClient'' a testSMPServer) >>= \case + Left e -> e `shouldBe` PCEResponseTimeout + Right _ -> expectationFailure "connected above the connection limit" + length <$> readTVarIO smpClients `shouldReturn` 0 + readTVarIO connectingClients `shouldReturn` 0 + CA.closeSMPClientAgent a + +todo :: AStoreType -> IO () +todo _ = fail "TODO" + runExceptT' :: Exception e => ExceptT e IO a -> IO a runExceptT' a = runExceptT a >>= either throwIO pure From f226357181dea1f9df92e18df685eba6ecb8da3a Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:12:24 +0000 Subject: [PATCH 040/159] smp server: evaluate the new count when a proxy connection slot is taken --- src/Simplex/Messaging/Client/Agent.hs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index 06283e1a2..c20ae768e 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -248,6 +248,28 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke void (forkIO $ restore (threadDelay' $ diffToMicroseconds ei) `E.finally` removeError) `E.onException` removeError restore $ reconnectClient ca srv pure $ Left e + where + sharedSession :: SMPClient -> (OwnServer, SMPClient) -> STM (Maybe (OwnServer, SMPClient)) + sharedSession smp c = + (pure connectedServerSessions $>>= TM.lookup (connectedServer smp) $>>= (`TM.lookup` smpSessions)) >>= \case + Just c0 -> Just c0 <$ putTMVar (sessionVar v) (Right c0) + Nothing -> do + putTMVar (sessionVar v) (Right c) + whenM (activeClientSession ca smp srv) $ do + TM.insert sessId c smpSessions + forM_ connectedServerSessions $ TM.insert (connectedServer smp) sessId + pure Nothing + where + sessId = sessionId $ thParams smp + + withConnectSlot :: (Bool -> IO a) -> IO a + withConnectSlot = + E.bracket + (atomically $ takeSlot connectingClients $ fromMaybe maxBound $ maxConnectingClients agentCfg) + (`when` atomically (modifyTVar' connectingClients (subtract 1))) + + takeSlot :: TVar Int -> Int -> STM Bool + takeSlot slots limit = stateTVar' slots $ \n -> if n < limit then (True, n + 1) else (False, n) isOwnServer :: SMPClientAgent p -> SMPServer -> OwnServer isOwnServer SMPClientAgent {agentCfg} ProtocolServer {host} = From b0699b38d727059225364099c4efb8898556d383 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:47:40 +0000 Subject: [PATCH 041/159] smp server: wait for delayed AUTH responses with timers --- src/Simplex/Messaging/Server.hs | 11 ++++++++++- src/Simplex/Messaging/Server/Env/STM.hs | 1 + 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 761191b9d..7665edae9 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1202,11 +1202,20 @@ sendAfterDelay c@Client {sndQ, clientTHParams = THandleParams {sessionId}} stats | delay > 0 = do elapsed <- subtract (microseconds since) . microseconds <$> getSystemTime when (elapsed >= delay) $ incStat $ authDelayExceeded stats - forkClient c (B.unpack $ "client $" <> encode sessionId <> " auth") $ threadDelay' (delay - elapsed `mod` delay) >> write + due <- registerDelay $ fromIntegral $ delay - elapsed `mod` delay + atomically $ writeTBQueue delayedQ (due, rs) | otherwise = write where write = atomically $ writeTBQueue sndQ rs +sendDelayed :: Client s -> IO () +sendDelayed Client {sndQ, delayedQ, clientTHParams = THandleParams {sessionId}} = do + labelMyThread . B.unpack $ "client $" <> encode sessionId <> " auth" + forever $ do + (due, rs) <- atomically $ readTBQueue delayedQ + atomically $ unlessM (readTVar due) retry + atomically $ writeTBQueue sndQ rs + updateSlotWaitStats :: ServerStats -> SystemTime -> Bool -> IO () updateSlotWaitStats ServerStats {cmdSlotWaits, cmdSlotWaitMs, cmdSlotWaitMaxMs, cmdSlotWaitTimeouts} since taken = do waitMs <- fromIntegral . (`div` 1000) . subtract (microseconds since) . microseconds <$> getSystemTime diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 608efb0f5..1fc73b0a9 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -442,6 +442,7 @@ data Client s = Client rcvQ :: TBQueue (NonEmpty (VerifiedTransmission s)), sndQ :: TBQueue (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]), msgQ :: TBQueue (NonEmpty (Transmission BrokerMsg)), + delayedQ :: TBQueue (TVar Bool, (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg])), procThreads :: TVar Int, fwdWorkers :: TVar (IntMap (TBQueue (M s ()))), endThreads :: TVar (IntMap (Weak ThreadId)), From 149c8b5d7d5f96608af1c92e98240853c8d65e58 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:42:49 +0000 Subject: [PATCH 042/159] smp server: build notification groups strictly --- src/Simplex/Messaging/Server/QueueStore/Postgres.hs | 10 +++------- src/Simplex/Messaging/Server/QueueStore/STM.hs | 10 ++++++---- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 8aad583c4..4357cea63 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -414,13 +414,9 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where let snIds' = foldl' (\m (sId, nId) -> M.alter (Just . maybe (S.singleton nId) (S.insert nId)) sId m) M.empty snIds in foldr addService ([], ntfs) (M.assocs snIds') where - addService :: - (Maybe ServiceId, S.Set NotifierId) -> - ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)]) -> - ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)]) - addService (serviceId, snIds) (ssNtfs, ntfs') = - let (sNtfs, restNtfs) = partition (\(nId, _) -> S.member nId snIds) ntfs' - in ((serviceId, sNtfs) : ssNtfs, restNtfs) + addNtf nsIds ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId nsIds of + Just serviceId -> (M.alter (Just . maybe [ntf] (ntf :)) serviceId ssNtfs, deleteNtfs) + Nothing -> (ssNtfs, ntf : deleteNtfs) getServiceQueueCountHash :: (PartyI p, ServiceParty p) => PostgresQueueStore q -> SParty p -> ServiceId -> IO (Either ErrorType (Int64, IdsHash)) getServiceQueueCountHash st party serviceId = diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index 0f164592a..8edc3b975 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -357,10 +357,12 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where ssNtfs' = (Nothing, ntfs') : ssNtfs pure $ Right (ssNtfs', deleteNtfs) where - addService (ssNtfs, ntfs') (serviceId, s) = do - (snIds, _) <- readTVarIO $ serviceNtfQueues s - let (sNtfs, restNtfs) = partition (\(nId, _) -> S.member nId snIds) ntfs' - pure ((Just serviceId, sNtfs) : ssNtfs, restNtfs) + addNtf ns qs ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId ns >>= (`M.lookup` qs) of + Just q -> do + qr <- readTVarIO (queueRec q) + let serviceId = qr >>= notifier >>= ntfServiceId + pure (M.alter (Just . maybe [ntf] (ntf :)) serviceId ssNtfs, deleteNtfs) + Nothing -> pure (ssNtfs, ntf : deleteNtfs) getServiceQueueCountHash :: (PartyI p, ServiceParty p) => STMQueueStore q -> SParty p -> ServiceId -> IO (Either ErrorType (Int64, IdsHash)) getServiceQueueCountHash st party serviceId = From 8c494579e9e6b0a8a4227bf1cea9ad0211275bdc Mon Sep 17 00:00:00 2001 From: sh-agents <350651734+sh-agents@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:51:42 +0000 Subject: [PATCH 043/159] smp server: count resolver rejections separately --- src/Simplex/Messaging/Server.hs | 9 +-- src/Simplex/Messaging/Server/Names.hs | 31 ++++++--- .../Messaging/Server/Names/HttpResolver.hs | 11 ++-- src/Simplex/Messaging/Server/Prometheus.hs | 8 ++- src/Simplex/Messaging/Server/Stats.hs | 26 +++++--- tests/RSLVTests.hs | 48 +++++++++++--- tests/SMPNamesTests.hs | 65 ++++++++++++++----- tests/ServerTests.hs | 6 +- 8 files changed, 148 insertions(+), 56 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 7665edae9..7b8a635d2 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -106,7 +106,7 @@ import Simplex.Messaging.Server.Control import Simplex.Messaging.Server.Env.STM as Env import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.MsgStore -import Simplex.Messaging.Server.Names (NamesEnv, closeNamesEnv, resolveName) +import Simplex.Messaging.Server.Names (NameFailure (..), NamesEnv, closeNamesEnv, resolveName) import Simplex.Messaging.Server.MsgStore.STM import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.NtfStore @@ -650,8 +650,8 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt map tshow [_pRequests, _pSuccesses, _pErrorsConnect, _pErrorsCompat, _pErrorsOther] showServiceStats ServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} = map tshow [_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd] - showNameResolverStats NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = - map tshow [_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled] + showNameResolverStats NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = + map tshow [_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected] prometheusMetricsThread_ :: ServerConfig s -> [M s ()] prometheusMetricsThread_ ServerConfig {prometheusInterval = Just interval, prometheusMetricsFile} = @@ -1649,7 +1649,8 @@ client (selector, msg) <- liftIO (resolveName nenv q) <&> \case Right res -> (if answered (registration res) then rslvSucc else rslvNotFound, RNAME res) - Left e -> (rslvResolverErrs, ERR $ NAME e) + Left (QueryRejected e) -> (rslvRejected, ERR $ NAME e) + Left (ResolverFailed e) -> (rslvResolverErrs, ERR $ NAME e) incStat (selector st) $> msg where -- below v22 the encoder answers anything but a record as NAME NOT_FOUND diff --git a/src/Simplex/Messaging/Server/Names.hs b/src/Simplex/Messaging/Server/Names.hs index 601519c56..2cac91349 100644 --- a/src/Simplex/Messaging/Server/Names.hs +++ b/src/Simplex/Messaging/Server/Names.hs @@ -8,6 +8,7 @@ module Simplex.Messaging.Server.Names ( NamesConfig (..), RpcAuth (..), NamesEnv (..), + NameFailure (..), newNamesEnv, closeNamesEnv, pingEndpoint, @@ -59,25 +60,35 @@ pingEndpoint :: NamesEnv -> IO (Either ResolverError ()) pingEndpoint NamesEnv {resolverEnv, config} = fromMaybe (Left ResolverTimeout) <$> timeout (resolverTimeoutMs config * 1000) (healthHttp resolverEnv) -resolveName :: NamesEnv -> NameQuery -> IO (Either NameErrorType NameResponse) +data NameFailure + = QueryRejected NameErrorType + | ResolverFailed NameErrorType + deriving (Eq, Show) + +resolveName :: NamesEnv -> NameQuery -> IO (Either NameFailure NameResponse) resolveName env q = do r <- E.try (timeout (resolverTimeoutMs (config env) * 1000) (fetch env q)) case r of - Right result -> pure (fromMaybe (Left (RESOLVER "timeout")) result) + Right result -> pure (fromMaybe (Left (ResolverFailed (RESOLVER "timeout"))) result) Left e | Just (_ :: E.SomeAsyncException) <- E.fromException e -> E.throwIO e | otherwise -> do logError $ "[NAMES] resolver fetch raised " <> T.pack (E.displayException e) - pure (Left (RESOLVER "resolver error")) + pure (Left (ResolverFailed (RESOLVER "resolver error"))) -fetch :: NamesEnv -> NameQuery -> IO (Either NameErrorType NameResponse) +fetch :: NamesEnv -> NameQuery -> IO (Either NameFailure NameResponse) fetch NamesEnv {resolverEnv} q = first mapResolverError <$> resolveHttp resolverEnv (decodeLatin1 $ smpEncode q) -mapResolverError :: ResolverError -> NameErrorType +mapResolverError :: ResolverError -> NameFailure mapResolverError = \case - HttpStatusErr code -> RESOLVER ("HTTP " <> T.pack (show code)) - HttpFailure _ -> RESOLVER "transport failure" - BodyTooLarge -> RESOLVER "response too large" - InvalidJson _ -> RESOLVER "invalid response" - ResolverTimeout -> RESOLVER "timeout" + HttpStatusErr code (Just c) | c `elem` queryErrors -> QueryRejected (httpErr code) + HttpStatusErr code _ -> ResolverFailed (httpErr code) + HttpFailure _ -> ResolverFailed $ RESOLVER "transport failure" + BodyTooLarge -> ResolverFailed $ RESOLVER "response too large" + InvalidJson _ -> ResolverFailed $ RESOLVER "invalid response" + ResolverTimeout -> ResolverFailed $ RESOLVER "timeout" + where + httpErr code = RESOLVER ("HTTP " <> T.pack (show code)) + -- error codes of /v2/resolve listed in scripts/resolver/README.md + queryErrors = ["tldNotConfigured", "notFullyQualified", "labelNotRecorded", "noPriceOracle"] diff --git a/src/Simplex/Messaging/Server/Names/HttpResolver.hs b/src/Simplex/Messaging/Server/Names/HttpResolver.hs index b1620447b..73c6db1e7 100644 --- a/src/Simplex/Messaging/Server/Names/HttpResolver.hs +++ b/src/Simplex/Messaging/Server/Names/HttpResolver.hs @@ -9,8 +9,8 @@ -- The Python REST resolver (see scripts/resolver/snrc-resolve.py) exposes -- -- GET /v2/resolve/ -> 200 with a NameRegistration JSON document, for --- all three registration shapes; 400 for unknown --- TLDs, 502 for upstream RPC failures +-- all three registration shapes; 400 or 502 with +-- a fixed `error` code in the body -- GET /v1/resolve/ -> 200 with a NameRecord, what relays before SMP -- v22 call as /resolve -- GET /health -> 200 when the resolver process is ready @@ -34,7 +34,9 @@ module Simplex.Messaging.Server.Names.HttpResolver where import qualified Control.Exception as E +import Control.Monad ((<=<)) import qualified Data.Aeson as J +import qualified Data.Aeson.Types as JT import Data.Bifunctor (first) import qualified Data.ByteArray.Encoding as BAE import Data.ByteString.Char8 (ByteString) @@ -79,7 +81,7 @@ data ResolverEnv = ResolverEnv data ResolverError = HttpFailure HttpException - | HttpStatusErr Int + | HttpStatusErr Int (Maybe Text) | BodyTooLarge | InvalidJson String | ResolverTimeout @@ -137,7 +139,7 @@ httpGet ResolverEnv {manager, baseUrl, authHdr, timeoutMicro, maxResponseBytes} result <- E.try $ withResponse req manager $ \res -> do let status = HT.statusCode (responseStatus res) if status >= 400 - then pure (Left (HttpStatusErr status)) + then Left . HttpStatusErr status . errorCode <$> brReadSome (responseBody res) maxResponseBytes else do bs <- brReadSome (responseBody res) (maxResponseBytes + 1) pure $ if BL.length bs > fromIntegral maxResponseBytes then Left BodyTooLarge else Right bs @@ -146,3 +148,4 @@ httpGet ResolverEnv {manager, baseUrl, authHdr, timeoutMicro, maxResponseBytes} httpError = \case HC.HttpExceptionRequest _ HC.ResponseTimeout -> ResolverTimeout e -> HttpFailure e + errorCode = JT.parseMaybe (J..: "error") <=< J.decode diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index 069cf3424..1934a4cd5 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -528,7 +528,7 @@ prometheusMetrics sm rtm ts = \simplex_smp_" <> pfx <> "_services_sub_fewer_total " <> mshow (_srvSubFewerTotal ss) <> "\n# " <> pfx <> ".srvSubFewerTotal\n\ \\n" names = - let NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = _rslvStats + let NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = _rslvStats in "# Names\n\ \# -----\n\ \\n\ @@ -544,10 +544,14 @@ prometheusMetrics sm rtm ts = \# TYPE simplex_smp_names_not_found counter\n\ \simplex_smp_names_not_found " <> mshow _rslvNotFound <> "\n# rslvNotFound\n\ \\n\ - \# HELP simplex_smp_names_resolver_errs Resolver backend errors (HTTP 5xx, transport, decode, or timeout).\n\ + \# HELP simplex_smp_names_resolver_errs Failures of the resolver or its chain RPC: upstream errors, transport, decode, or timeout.\n\ \# TYPE simplex_smp_names_resolver_errs counter\n\ \simplex_smp_names_resolver_errs " <> mshow _rslvResolverErrs <> "\n# rslvResolverErrs\n\ \\n\ + \# HELP simplex_smp_names_rejected Lookups the resolver rejected: TLD not configured, name not fully qualified, label not recorded, or no price oracle.\n\ + \# TYPE simplex_smp_names_rejected counter\n\ + \simplex_smp_names_rejected " <> mshow _rslvRejected <> "\n# rslvRejected\n\ + \\n\ \# HELP simplex_smp_names_disabled RSLV requests rejected because no resolver is configured (names role off).\n\ \# TYPE simplex_smp_names_disabled counter\n\ \simplex_smp_names_disabled " <> mshow _rslvDisabled <> "\n# rslvDisabled\n\ diff --git a/src/Simplex/Messaging/Server/Stats.hs b/src/Simplex/Messaging/Server/Stats.hs index 70a450652..a3e57d1cd 100644 --- a/src/Simplex/Messaging/Server/Stats.hs +++ b/src/Simplex/Messaging/Server/Stats.hs @@ -953,7 +953,8 @@ data NameResolverStats = NameResolverStats rslvSucc :: IORef Int, rslvNotFound :: IORef Int, rslvResolverErrs :: IORef Int, - rslvDisabled :: IORef Int + rslvDisabled :: IORef Int, + rslvRejected :: IORef Int } newNameResolverStats :: IO NameResolverStats @@ -963,14 +964,16 @@ newNameResolverStats = do rslvNotFound <- newIORef 0 rslvResolverErrs <- newIORef 0 rslvDisabled <- newIORef 0 - pure NameResolverStats {rslvReqs, rslvSucc, rslvNotFound, rslvResolverErrs, rslvDisabled} + rslvRejected <- newIORef 0 + pure NameResolverStats {rslvReqs, rslvSucc, rslvNotFound, rslvResolverErrs, rslvDisabled, rslvRejected} data NameResolverStatsData = NameResolverStatsData { _rslvReqs :: Int, _rslvSucc :: Int, _rslvNotFound :: Int, _rslvResolverErrs :: Int, - _rslvDisabled :: Int + _rslvDisabled :: Int, + _rslvRejected :: Int } deriving (Show) @@ -981,7 +984,8 @@ newNameResolverStatsData = _rslvSucc = 0, _rslvNotFound = 0, _rslvResolverErrs = 0, - _rslvDisabled = 0 + _rslvDisabled = 0, + _rslvRejected = 0 } getNameResolverStatsData :: NameResolverStats -> IO NameResolverStatsData @@ -991,7 +995,8 @@ getNameResolverStatsData s = do _rslvNotFound <- readIORef $ rslvNotFound s _rslvResolverErrs <- readIORef $ rslvResolverErrs s _rslvDisabled <- readIORef $ rslvDisabled s - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- readIORef $ rslvRejected s + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} getResetNameResolverStatsData :: NameResolverStats -> IO NameResolverStatsData getResetNameResolverStatsData s = do @@ -1000,7 +1005,8 @@ getResetNameResolverStatsData s = do _rslvNotFound <- atomicSwapIORef (rslvNotFound s) 0 _rslvResolverErrs <- atomicSwapIORef (rslvResolverErrs s) 0 _rslvDisabled <- atomicSwapIORef (rslvDisabled s) 0 - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- atomicSwapIORef (rslvRejected s) 0 + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} -- not thread safe; used on server start only setNameResolverStats :: NameResolverStats -> NameResolverStatsData -> IO () @@ -1010,9 +1016,10 @@ setNameResolverStats s d = do writeIORef (rslvNotFound s) $! _rslvNotFound d writeIORef (rslvResolverErrs s) $! _rslvResolverErrs d writeIORef (rslvDisabled s) $! _rslvDisabled d + writeIORef (rslvRejected s) $! _rslvRejected d instance StrEncoding NameResolverStatsData where - strEncode NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = + strEncode NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = "reqs=" <> strEncode _rslvReqs <> "\nsucc=" @@ -1023,13 +1030,16 @@ instance StrEncoding NameResolverStatsData where <> strEncode _rslvResolverErrs <> "\ndisabled=" <> strEncode _rslvDisabled + <> "\nrejected=" + <> strEncode _rslvRejected strP = do _rslvReqs <- "reqs=" *> strP <* A.endOfLine _rslvSucc <- "succ=" *> strP <* A.endOfLine _rslvNotFound <- "notFound=" *> strP <* A.endOfLine _rslvResolverErrs <- "resolverErrs=" *> strP <* A.endOfLine _rslvDisabled <- "disabled=" *> strP - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- (A.endOfLine *> "rejected=" *> strP) <|> pure 0 + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} data ServiceStats = ServiceStats { srvAssocNew :: IORef Int, diff --git a/tests/RSLVTests.hs b/tests/RSLVTests.hs index e9b931314..1a2e38a91 100644 --- a/tests/RSLVTests.hs +++ b/tests/RSLVTests.hs @@ -29,7 +29,7 @@ import SMPClient import Simplex.Messaging.Client import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (strDecode) -import SMPNamesTests (availableBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) +import SMPNamesTests (availableBody, errorBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) import Simplex.Messaging.Protocol ( BrokerMsg (..), Cmd (..), @@ -88,6 +88,8 @@ rslvTests = do describe "RSLV direct (non-forwarded)" $ do it "resolver without the v2 route (404) -> NAME RESOLVER, not NOT_FOUND" testRslvBackendNotFound it "resolver replies 502 -> NAME (RESOLVER ..)" testRslvBackendHttpErr + it "a rejected name counts as rejected, not as a resolver error" testRslvRejectedStats + it "a resolver failure counts as a resolver error" testRslvResolverErrStats it "no names config -> NAME NO_RESOLVER" testRslvDisabled it "refuses to send RSLV on a session below namesSMPVersion" testRslvVersion describe "RSLV forwarded (PFWD)" $ do @@ -128,6 +130,27 @@ testRslvBackendHttpErr = (_, _, resp) <- sendRslv h "rs05" (domain "alice.simplex") resp `shouldBe` Right (ERR (NAME (RESOLVER "HTTP 502"))) +testRslvRejectedStats :: HasTestEnv => IO () +testRslvRejectedStats = + rslvStatsTest (status502, errorBody "labelNotRecorded") `shouldReturn` (1, 0) + +testRslvResolverErrStats :: HasTestEnv => IO () +testRslvResolverErrStats = + rslvStatsTest (status502, errorBody "upstreamError") `shouldReturn` (0, 1) + +rslvStatsTest :: HasTestEnv => (Status, LB.ByteString) -> IO (Int, Int) +rslvStatsTest (st, body) = + NRS.withResolverServer (NRS.resolveResp st body) $ \port _ -> + withSmpServerConfigOn (transport @TLS) (metricsCfg port) testPort $ const $ do + testSMPClient @TLS $ \h -> do + (_, _, resp) <- sendRslv h "rs08" (domain "alice.simplex") + resp `shouldBe` Right (ERR (NAME (RESOLVER "HTTP 502"))) + threadDelay 1500000 + ms <- readMetrics + (,) <$> metric ms "simplex_smp_names_rejected" <*> metric ms "simplex_smp_names_resolver_errs" + where + metricsCfg port = updateCfg (withNames port memCfg) $ \c -> c {prometheusInterval = Just 1} + testRslvDisabled :: HasTestEnv => IO () testRslvDisabled = withSmpServerConfigOn (transport @TLS) memCfg testPort $ const $ @@ -336,16 +359,21 @@ data SlotWaitMetrics = SlotWaitMetrics {waits :: Int, waitTimeouts :: Int, waitM readSlotWaitMetrics :: HasTestEnv => IO SlotWaitMetrics readSlotWaitMetrics = do - ms <- map words . lines <$> readFile testPrometheusMetricsFile - -- metric lines are "name value timestamp" - let metric name = case [v | n : v : _ <- ms, n == name] of - [v] -> pure $ read v - _ -> fail $ "no metric " <> name + ms <- readMetrics SlotWaitMetrics - <$> metric "simplex_smp_cmd_slot_wait_ms_count" - <*> metric "simplex_smp_cmd_slot_wait_timeouts" - <*> metric "simplex_smp_cmd_slot_wait_ms_max" - <*> metric "simplex_smp_cmd_slot_wait_ms_sum" + <$> metric ms "simplex_smp_cmd_slot_wait_ms_count" + <*> metric ms "simplex_smp_cmd_slot_wait_timeouts" + <*> metric ms "simplex_smp_cmd_slot_wait_ms_max" + <*> metric ms "simplex_smp_cmd_slot_wait_ms_sum" + +readMetrics :: HasTestEnv => IO [[String]] +readMetrics = map words . lines <$> readFile testPrometheusMetricsFile + +-- metric lines are "name value timestamp" +metric :: [[String]] -> String -> IO Int +metric ms name = case [v | n : v : _ <- ms, n == name] of + [v] -> pure $ read v + _ -> fail $ "no metric " <> name -- | One RSLV per block, so no batch limit applies. sendRslvs :: THandleSMP TLS 'TClient -> String -> Int -> IO () diff --git a/tests/SMPNamesTests.hs b/tests/SMPNamesTests.hs index 452c99428..a5e9c78e6 100644 --- a/tests/SMPNamesTests.hs +++ b/tests/SMPNamesTests.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, availableBody, reservedBody, responseBody, resolved) where +module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, availableBody, reservedBody, responseBody, errorBody, resolved) where import qualified Data.Aeson as J import qualified Data.ByteString.Char8 as B @@ -17,17 +17,19 @@ import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Types (status200, status400, status404, status500, status502) import NamesResolverServer (resolveResp, testNamesConfig, withResolverServer, withResolverServerDelayed) import Simplex.Messaging.Encoding (smpDecode, smpEncode) -import Simplex.Messaging.Encoding.String (strDecode) +import Simplex.Messaging.Encoding.String (strDecode, strEncode) import Simplex.Messaging.Protocol (Command (..), ErrorType (..), NameErrorType (..), NamePricing (..), NameQuery (..), NameRecord (..), NameRegistration (..), NameResponse (..), NameReservedReason (..), ProtocolEncoding (..), USDCents (..)) import Simplex.Messaging.Server.Main (validateUrl) import Simplex.Messaging.Server.Names - ( NamesConfig (..), + ( NameFailure (..), + NamesConfig (..), RpcAuth (..), newNamesEnv, pingEndpoint, resolveName, ) import Simplex.Messaging.Server.Names.HttpResolver (ResolverError (..)) +import Simplex.Messaging.Server.Stats (NameResolverStatsData (..)) import Simplex.Messaging.SimplexName (SimplexDomain (..), SimplexTLD (..), labelHash) import Simplex.Messaging.SystemTime (RoundedSystemTime (..)) import Simplex.Messaging.Transport (nameAvailSMPVersion, serverInfoSMPVersion) @@ -62,6 +64,9 @@ availableBody = responseBody "{\"type\":\"available\",\"pricing\":{\"registratio reservedBody :: LB.ByteString reservedBody = responseBody "{\"type\":\"reserved\",\"reservedReason\":\"trademark\"}" +errorBody :: LB.ByteString -> LB.ByteString +errorBody code = "{\"name\":\"alice.simplex\",\"error\":\"" <> code <> "\"}" + -- | The registration, and the block the resolver read it at. responseBody :: LB.ByteString -> LB.ByteString responseBody reg = "{\"lastBlockTs\":" <> testReadAt <> ",\"registration\":" <> reg <> "}" @@ -86,6 +91,7 @@ smpNamesTests = do describe "HTTP resolver" resolverSpec describe "name availability" availabilitySpec describe "Resolver health probe" healthSpec + describe "name resolver stats" nameStatsSpec describe "resolver_endpoint validation" validateUrlSpec nameRecordEncodingSpec :: Spec @@ -263,37 +269,57 @@ resolverSpec = do it "returns RESOLVER on 404 (a resolver without the v2 route)" $ withResolverServer (resolveResp status404 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 404") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 404")) + + it "rejects the query on 400 tldNotConfigured" $ + withResolverServer (resolveResp status400 (errorBody "tldNotConfigured")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 400")) - it "returns RESOLVER on 400 (TLD not configured)" $ - withResolverServer (resolveResp status400 "{}") $ \port _ -> do + it "rejects the query on 400 notFullyQualified" $ + withResolverServer (resolveResp status400 (errorBody "notFullyQualified")) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 400") + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 400")) - it "returns RESOLVER on 502 (upstream failure)" $ + it "rejects the query on 502 labelNotRecorded" $ + withResolverServer (resolveResp status502 (errorBody "labelNotRecorded")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 502")) + + it "rejects the query on 502 noPriceOracle" $ + withResolverServer (resolveResp status502 (errorBody "noPriceOracle")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 502")) + + it "fails on 502 upstreamError" $ + withResolverServer (resolveResp status502 (errorBody "upstreamError")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 502")) + + it "fails on an error status without an error code" $ withResolverServer (resolveResp status502 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 502") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 502")) it "returns RESOLVER when the body exceeds the response cap" $ withResolverServer (resolveResp status200 (LB.fromStrict (B.replicate 500 'x'))) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) {resolverMaxResponseBytes = 100} - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "response too large") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "response too large")) it "returns RESOLVER on malformed JSON from the resolver" $ withResolverServer (resolveResp status200 "this is not json") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "invalid response") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "invalid response")) it "returns RESOLVER when JSON parses but isn't a NameRegistration shape" $ withResolverServer (resolveResp status200 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "invalid response") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "invalid response")) it "returns RESOLVER (timeout) when the resolver is slower than resolverTimeoutMs" $ withResolverServerDelayed 1500 (resolveResp status200 (registeredBody testNameRecord)) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) {resolverTimeoutMs = 300} - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "timeout") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "timeout")) it "sends one HTTP request per lookup (no cache)" $ withResolverServer (resolveResp status200 (registeredBody testNameRecord)) $ \port reqs -> do @@ -324,8 +350,8 @@ healthSpec = do withResolverServer healthFails $ \port _ -> do env <- newNamesEnv (testNamesConfig port) pingEndpoint env >>= \case - Left (HttpStatusErr 500) -> pure () - r -> expectationFailure $ "expected Left (HttpStatusErr 500), got " <> show r + Left (HttpStatusErr 500 _) -> pure () + r -> expectationFailure $ "expected Left (HttpStatusErr 500 _), got " <> show r it "pingEndpoint queries /health" $ withResolverServer (resolveResp status200 "{}") $ \port reqs -> do @@ -337,6 +363,15 @@ healthSpec = do ["health"] -> (status500, "{}") _ -> (status404, "{}") +nameStatsSpec :: Spec +nameStatsSpec = do + it "round-trips the rejected count" $ + (_rslvRejected <$> strDecode (strEncode stats {_rslvRejected = 3})) `shouldBe` Right 3 + it "reads stats saved before the rejected count as zero" $ + (_rslvRejected <$> strDecode "reqs=5\nsucc=1\nnotFound=1\nresolverErrs=2\ndisabled=1") `shouldBe` Right 0 + where + stats = NameResolverStatsData {_rslvReqs = 5, _rslvSucc = 1, _rslvNotFound = 1, _rslvResolverErrs = 1, _rslvDisabled = 0, _rslvRejected = 0} + validateUrlSpec :: Spec validateUrlSpec = do it "accepts an https URL with a path prefix" $ diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 62045b4bb..cf0003da8 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -1641,7 +1641,7 @@ testRestoreMessages = pure () rId <- readTVarIO recipientId logSize testStoreLogFile `shouldReturn` 2 - logSize testServerStatsBackupFile `shouldReturn` 101 + logSize testServerStatsBackupFile `shouldReturn` 102 Right stats1 <- strDecode <$> B.readFile testServerStatsBackupFile checkStats stats1 [rId] 5 1 withSmpServerConfigOn at cfg' testPort . runTest t $ \h -> do @@ -1657,7 +1657,7 @@ testRestoreMessages = logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) -- the last message is not removed because it was not ACK'd -- logSize testStoreMsgsFile `shouldReturn` 3 - logSize testServerStatsBackupFile `shouldReturn` 101 + logSize testServerStatsBackupFile `shouldReturn` 102 Right stats2 <- strDecode <$> B.readFile testServerStatsBackupFile checkStats stats2 [rId] 5 3 @@ -1675,7 +1675,7 @@ testRestoreMessages = pure () logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) removeFile testStoreLogFile - logSize testServerStatsBackupFile `shouldReturn` 101 + logSize testServerStatsBackupFile `shouldReturn` 102 Right stats3 <- strDecode <$> B.readFile testServerStatsBackupFile checkStats stats3 [rId] 5 5 removeFileIfExists testStoreMsgsFile From caeac50e7c3f7ad5f36ee63b2f4632d333a1380b Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:11:23 +0000 Subject: [PATCH 044/159] smp server: close idle relay connections --- src/Simplex/Messaging/Client.hs | 2 +- tests/SMPClient.hs | 7 +++++++ tests/SMPProxyTests.hs | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 9a45ec706..750c3c39a 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -704,7 +704,7 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS -- sendProtocolCommand/getResponse updates counter for each command cnt <- readTVarIO timeoutErrorCount -- drop client when maxCnt of commands have timed out in sequence, but only after some time has passed after last received response - when (maxCnt == 0 || cnt < maxCnt || diff < recoverWindow) $ loop smpPingInterval + when (not proxyServer && (maxCnt == 0 || cnt < maxCnt || diff < recoverWindow)) $ loop smpPingInterval recoverWindow = 15 * 60 -- seconds maxCnt = smpPingCount networkConfig diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 9bfa04d10..74576031e 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -361,6 +361,13 @@ proxyCfgShortTimeout = nt = NetworkTimeout {backgroundTimeout = 4_000000, interactiveTimeout = 4_000000} in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {tcpConnectTimeout = nt}}}} +proxyCfgShortPingInterval :: HasTestEnv => AServerConfig +proxyCfgShortPingInterval = + updateCfg proxyCfg $ \cfg' -> + let aCfg = smpAgentCfg cfg' + cCfg = smpCfg aCfg + in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {smpPingInterval = 1_000000}}}} + proxyCfgVPrev :: HasTestEnv => AStoreType -> AServerConfig proxyCfgVPrev msType = updateCfg (proxyCfgMS msType) $ \cfg' -> diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index cda55e3be..b0890202d 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -104,6 +104,8 @@ smpProxyTests = do testFwdCorrIdSize it "relay delays AUTH errors to forwarded commands" $ \_ -> testForwardedAuthErrorDelay + it "proxy closes idle relay connection" $ \_ -> + testProxyClosesIdleRelay describe "deliver message via SMP proxy" $ do let srv1, srv2 :: HasTestEnv => SMPServer srv1 = SMPServer testHost testPort testKeyHash @@ -536,6 +538,18 @@ testFwdCorrIdSize = (_, _, reply) <- sendRecv th (Nothing, corrId, SMP.EntityId sessId, SMP.PFWD currentClientSMPRelayVersion cmdPubKey (SMP.EncTransmission "")) reply `shouldBe` Right (SMP.ERR $ SMP.CMD SMP.SYNTAX) +testProxyClosesIdleRelay :: HasTestEnv => IO () +testProxyClosesIdleRelay = + withSmpServerConfigOn (transport @TLS) proxyCfgShortPingInterval testPort $ \_ -> + withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 $ \_ -> + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (_, _, Right (SMP.PKEY sessId _ _)) <- sendRecv th (Nothing, "1", NoEntity, SMP.PRXY testSMPServer2 Nothing) + threadDelay 2000000 + g <- C.newRandom + (cmdPubKey, _) <- atomically $ C.generateKeyPair g + (_, _, reply) <- sendRecv th (Nothing, "2", SMP.EntityId sessId, SMP.PFWD currentClientSMPRelayVersion cmdPubKey (SMP.EncTransmission "")) + reply `shouldBe` Right (SMP.ERR $ SMP.PROXY SMP.NO_SESSION) + testForwardedAuthErrorDelay :: HasTestEnv => IO () testForwardedAuthErrorDelay = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> From 966ff5dbac0c3ccfd994b02aba53179994f0e0df Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:11:23 +0000 Subject: [PATCH 045/159] agent: check connection when adding send queue --- src/Simplex/Messaging/Agent/Store.hs | 2 +- src/Simplex/Messaging/Agent/Store/AgentStore.hs | 17 +++++++++-------- tests/AgentTests/SQLiteTests.hs | 5 ++--- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Store.hs b/src/Simplex/Messaging/Agent/Store.hs index 67415c718..9ccedc120 100644 --- a/src/Simplex/Messaging/Agent/Store.hs +++ b/src/Simplex/Messaging/Agent/Store.hs @@ -809,7 +809,7 @@ data StoreError SEServerNotFound | -- | Connection already used. SEConnDuplicate - | -- | Confirmed snd queue already exists. + | -- | Snd queue already exists: confirmed, or in another connection. SESndQueueExists | -- | Wrong connection type, e.g. "send" connection when "receive" or "duplex" is expected, or vice versa. -- 'upgradeRcvConnToDuplex' and 'upgradeSndConnToDuplex' do not allow duplex connections - they would also return this error. diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 9032db05f..aa8b9c9dd 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -574,7 +574,7 @@ createSndConn :: DB.Connection -> TVar ChaChaDRG -> ConnData -> NewSndQueue -> I createSndConn db gVar cData q@SndQueue {server} = -- check confirmed snd queue doesn't already exist, to prevent it being deleted by REPLACE in insertSndQueue_ ifM (liftIO $ checkConfirmedSndQueueExists_ db q) (pure $ Left SESndQueueExists) $ - createConn_ db gVar cData $ \connId -> do + fmap (>>= sequence) . createConn_ db gVar cData $ \connId -> do serverKeyHash_ <- createServer db server createConnRecord db connId cData SCMInvitation insertSndQueue_ db connId q serverKeyHash_ @@ -673,10 +673,9 @@ addConnSndQueue db connId sq = _ -> pure $ Left SEConnNotFound addConnSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> IO (Either StoreError SndQueue) -addConnSndQueue_ db connId sq@SndQueue {server} = - ifM (checkConfirmedSndQueueExists_ db sq) (pure $ Left SESndQueueExists) $ do - serverKeyHash_ <- createServer db server - Right <$> insertSndQueue_ db connId sq serverKeyHash_ +addConnSndQueue_ db connId sq@SndQueue {server} = do + serverKeyHash_ <- createServer db server + insertSndQueue_ db connId sq serverKeyHash_ setRcvQueueStatus :: DB.Connection -> RcvQueue -> QueueStatus -> IO () setRcvQueueStatus db RcvQueue {rcvId, server = ProtocolServer {host, port}} status = @@ -2421,13 +2420,13 @@ insertRcvQueue_ db connId' rq@RcvQueue {..} subMode serverKeyHash_ = do -- * createSndConn helpers -insertSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> Maybe C.KeyHash -> IO SndQueue +insertSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> Maybe C.KeyHash -> IO (Either StoreError SndQueue) insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do -- to preserve ID if the queue already exists. -- possibly, it can be done in one query. currQId_ <- maybeFirstRow fromOnly $ DB.query db "SELECT snd_queue_id FROM snd_queues WHERE conn_id = ? AND host = ? AND port = ? AND snd_id = ?" (connId', host server, port server, sndId) qId <- maybe (newQueueId_ <$> DB.query db "SELECT snd_queue_id FROM snd_queues WHERE conn_id = ? ORDER BY snd_queue_id DESC LIMIT 1" (Only connId')) pure currQId_ - DB.execute + (rs :: [Only Int]) <- DB.query db [sql| INSERT INTO snd_queues @@ -2449,10 +2448,12 @@ insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do replace_snd_queue_id=EXCLUDED.replace_snd_queue_id, smp_client_version=EXCLUDED.smp_client_version, server_key_hash=EXCLUDED.server_key_hash + WHERE snd_queues.conn_id = EXCLUDED.conn_id + RETURNING 1 |] ((host server, port server, sndId, queueMode, connId', sndPrivateKey, e2ePubKey, e2eDhSecret) :. (status, qId, BI primary, dbReplaceQueueId, smpClientVersion, serverKeyHash_)) - pure (sq :: NewSndQueue) {connId = connId', dbQueueId = qId} + pure $ if null rs then Left SESndQueueExists else Right (sq :: NewSndQueue) {connId = connId', dbQueueId = qId} newQueueId_ :: [Only Int64] -> DBEntityId newQueueId_ [] = DBEntityId 1 diff --git a/tests/AgentTests/SQLiteTests.hs b/tests/AgentTests/SQLiteTests.hs index 165df9a58..c73b3a0e9 100644 --- a/tests/AgentTests/SQLiteTests.hs +++ b/tests/AgentTests/SQLiteTests.hs @@ -475,10 +475,9 @@ testUpgradeRcvConnToDuplex = testSndQueueOfAnotherConn :: SpecWith DBStore testSndQueueOfAnotherConn = - it "should not add confirmed SndQueue of another connection" . withStoreTransaction $ \db -> do + it "should not add SndQueue of another connection" . withStoreTransaction $ \db -> do g <- C.newRandom Right (_, sq) <- createSndConn db g cData1 sndQueue1 - setSndQueueStatus db sq Confirmed Right _ <- createNewConn db g cData1 {connId = "conn2"} SCMInvitation updateNewConnSnd db "conn2" sndQueue1 `shouldReturn` Left SESndQueueExists @@ -489,7 +488,7 @@ testSndQueueOfAnotherConn = addConnSndQueue db "conn2" sndQueue1 `shouldReturn` Left SESndQueueExists getConn db "conn1" - `shouldReturn` Right (SomeConn SCSnd (SndConnection cData1 (sq {status = Confirmed} :: SndQueue))) + `shouldReturn` Right (SomeConn SCSnd (SndConnection cData1 sq)) testUpgradeSndConnToDuplex :: SpecWith DBStore testUpgradeSndConnToDuplex = From 8fd2a6220c6c8260084431a784e52dde4ed25468 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:55:20 +0000 Subject: [PATCH 046/159] simplify createSndConn --- src/Simplex/Messaging/Agent/Store/AgentStore.hs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index aa8b9c9dd..e421d88ad 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -573,11 +573,12 @@ updateNewConnSnd db connId sq = createSndConn :: DB.Connection -> TVar ChaChaDRG -> ConnData -> NewSndQueue -> IO (Either StoreError (ConnId, SndQueue)) createSndConn db gVar cData q@SndQueue {server} = -- check confirmed snd queue doesn't already exist, to prevent it being deleted by REPLACE in insertSndQueue_ - ifM (liftIO $ checkConfirmedSndQueueExists_ db q) (pure $ Left SESndQueueExists) $ - fmap (>>= sequence) . createConn_ db gVar cData $ \connId -> do + ifM (liftIO $ checkConfirmedSndQueueExists_ db q) (pure $ Left SESndQueueExists) . runExceptT $ do + (connId, sq) <- ExceptT . createConn_ db gVar cData $ \connId -> do serverKeyHash_ <- createServer db server createConnRecord db connId cData SCMInvitation insertSndQueue_ db connId q serverKeyHash_ + (connId,) <$> except sq createConnRecord :: DB.Connection -> ConnId -> ConnData -> SConnectionMode c -> IO () createConnRecord db connId ConnData {userId, connAgentVersion, enableNtfs, pqSupport, serviceRequestExpiresAt} cMode = do From 7d64f29ad836df7fe6a7d9458227fd29672f28f4 Mon Sep 17 00:00:00 2001 From: Spencer Michaels Date: Fri, 11 Sep 2026 23:48:16 -0700 Subject: [PATCH 047/159] Fix IPv6 host and port formatting in addresses and links --- src/Simplex/FileTransfer/Client/Main.hs | 5 +++-- src/Simplex/Messaging/Agent/Protocol.hs | 2 +- src/Simplex/Messaging/Protocol.hs | 11 ++++++----- src/Simplex/Messaging/ServiceScheme.hs | 2 +- src/Simplex/RemoteControl/Invitation.hs | 3 ++- xftp-web/src/protocol/address.ts | 6 +++++- 6 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Simplex/FileTransfer/Client/Main.hs b/src/Simplex/FileTransfer/Client/Main.hs index 6421d5b80..2bec1a6d8 100644 --- a/src/Simplex/FileTransfer/Client/Main.hs +++ b/src/Simplex/FileTransfer/Client/Main.hs @@ -72,6 +72,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (StrEncoding (..)) import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Protocol (ProtoServerWithAuth (..), ProtocolServer (..), SenderId, SndPrivateAuthKey, XFTPServer, XFTPServerWithAuth) +import Simplex.Messaging.ServiceScheme (SrvLoc (..)) import Simplex.Messaging.Util (groupAllOn, ifM, stateTVar', tshow, whenM) import System.Exit (exitFailure) import System.FilePath (splitFileName, ()) @@ -602,9 +603,9 @@ decodeWebURI fragment = do strDecode yaml >>= validateFileDescription -- | Extract web link host and URI fragment from a file description. --- Returns (hostname, uriFragment) for https://hostname/#uriFragment. +-- Returns (authority, uriFragment) for https://authority/#uriFragment. fileWebLink :: FileDescription 'FRecipient -> Maybe (B.ByteString, B.ByteString) fileWebLink fd@FileDescription {chunks} = case chunks of (FileChunk {replicas = FileChunkReplica {server = ProtocolServer {host}} : _} : _) -> - Just (strEncode (L.head host), encodeWebURI fd) + Just (strEncode (SrvLoc (L.head host) ""), encodeWebURI fd) _ -> Nothing diff --git a/src/Simplex/Messaging/Agent/Protocol.hs b/src/Simplex/Messaging/Agent/Protocol.hs index 91949aba0..93438e471 100644 --- a/src/Simplex/Messaging/Agent/Protocol.hs +++ b/src/Simplex/Messaging/Agent/Protocol.hs @@ -1740,7 +1740,7 @@ instance ConnectionModeI m => StrEncoding (ConnShortLink m) where where (authority, paramHosts) = case sch of SLSSimplex -> ("simplex:", h : hs) - SLSServer -> ("https://" <> strEncode h, hs) + SLSServer -> ("https://" <> strEncode (SrvLoc h ""), hs) lnkIdStr = if B.null lnkId then "" else B64.encodeUnpadded lnkId <> "/" queryStr = if B.null query then "" else "?" <> query query = diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index ef9eac7bf..f571ed133 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -1341,7 +1341,7 @@ instance ProtocolTypeI p => Encoding (ProtocolServer p) where instance ProtocolTypeI p => StrEncoding (ProtocolServer p) where strEncode ProtocolServer {scheme, host, port, keyHash} = - strEncodeServer scheme (strEncode host) port keyHash Nothing + strEncodeServer scheme host port keyHash Nothing strP = serverStrP >>= \case (AProtocolServer _ srv, Nothing) -> either fail pure $ checkProtocolType srv @@ -1394,7 +1394,7 @@ deriving instance Show AProtoServerWithAuth instance ProtocolTypeI p => StrEncoding (ProtoServerWithAuth p) where strEncode (ProtoServerWithAuth ProtocolServer {scheme, host, port, keyHash} auth_) = - strEncodeServer scheme (strEncode host) port keyHash auth_ + strEncodeServer scheme host port keyHash auth_ strP = (\(AProtoServerWithAuth _ srv) -> checkProtocolType srv) <$?> strP instance StrEncoding AProtoServerWithAuth where @@ -1431,12 +1431,13 @@ legacyServerP = requireKeyHash <$?> do legacyStrEncodeServer :: ProtocolTypeI p => ProtocolServer p -> ByteString legacyStrEncodeServer ProtocolServer {scheme, host, port, keyHash} = - strEncodeServer scheme (strEncode $ L.head host) port keyHash Nothing + strEncodeServer scheme [L.head host] port keyHash Nothing -strEncodeServer :: ProtocolTypeI p => SProtocolType p -> ByteString -> ServiceName -> C.KeyHash -> Maybe BasicAuth -> ByteString +strEncodeServer :: ProtocolTypeI p => SProtocolType p -> NonEmpty TransportHost -> ServiceName -> C.KeyHash -> Maybe BasicAuth -> ByteString strEncodeServer scheme host port keyHash auth_ = - strEncode scheme <> "://" <> strEncode keyHash <> maybe "" ((":" <>) . strEncode) auth_ <> "@" <> host <> portStr + strEncode scheme <> "://" <> strEncode keyHash <> maybe "" ((":" <>) . strEncode) auth_ <> "@" <> hostStr <> portStr where + hostStr = B.intercalate "," $ map (strEncode . (`SrvLoc` "")) $ L.toList host portStr = B.pack $ if null port then "" else ':' : port serverStrP :: Parser (AProtocolServer, Maybe BasicAuth) diff --git a/src/Simplex/Messaging/ServiceScheme.hs b/src/Simplex/Messaging/ServiceScheme.hs index 904ab971e..08e5512ed 100644 --- a/src/Simplex/Messaging/ServiceScheme.hs +++ b/src/Simplex/Messaging/ServiceScheme.hs @@ -31,7 +31,7 @@ data SrvLoc = SrvLoc TransportHost ServiceName instance StrEncoding SrvLoc where strEncode (SrvLoc host port) - | null port = strEncode host + | null port = h | otherwise = h <> B.pack (':' : port) where h = case host of diff --git a/src/Simplex/RemoteControl/Invitation.hs b/src/Simplex/RemoteControl/Invitation.hs index 480838c31..e12786235 100644 --- a/src/Simplex/RemoteControl/Invitation.hs +++ b/src/Simplex/RemoteControl/Invitation.hs @@ -26,6 +26,7 @@ import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) +import Simplex.Messaging.ServiceScheme (SrvLoc (..)) import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.RemoteControl.Types (VersionRangeRCP) @@ -61,7 +62,7 @@ instance StrEncoding RCInvitation where [ "xrcp:/", strEncode ca, "@", - strEncode host, + strEncode (SrvLoc host ""), ":", strEncode port, "#/?", diff --git a/xftp-web/src/protocol/address.ts b/xftp-web/src/protocol/address.ts index c2897a63e..a2526fbbf 100644 --- a/xftp-web/src/protocol/address.ts +++ b/xftp-web/src/protocol/address.ts @@ -33,9 +33,13 @@ export function parseXFTPServer(address: string): XFTPServer { const keyHash = base64urlDecode(m[1]) if (keyHash.length !== 32) throw new Error("parseXFTPServer: keyHash must be 32 bytes") const hostPart = m[2] + const listPort = hostPart.includes(',') && /\[[0-9a-f:]*:[0-9a-f:]*\]/i.test(hostPart) + ? hostPart.match(/:(\d+)$/)?.[1] + : undefined // Take the first host (before any comma), then split port from that const firstHost = hostPart.split(',')[0] - return {keyHash, ...parseHostPort(firstHost)} + const hostPort = parseHostPort(firstHost) + return {keyHash, ...hostPort, port: listPort ?? hostPort.port} } function parseHostPort(firstHost: string): Pick { From 13dc07532fae786a1cb54be2c9270fe1f381cb7e Mon Sep 17 00:00:00 2001 From: Spencer Michaels Date: Fri, 11 Sep 2026 23:48:16 -0700 Subject: [PATCH 048/159] Test IPv6 address and link encoding --- tests/AgentTests/ConnectionRequestTests.hs | 26 ++++++++++++++ tests/CoreTests/EncodingTests.hs | 42 ++++++++++++++++++---- tests/FileDescriptionTests.hs | 29 ++++++++++++++- tests/RemoteControl.hs | 40 +++++++++++++++++---- tests/XFTPWebTests.hs | 23 ++++++++++++ xftp-web/test/address.node.test.ts | 16 +++++++++ 6 files changed, 161 insertions(+), 15 deletions(-) diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index b61f589ad..89488c653 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -30,6 +30,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (EntityId (..), ProtocolServer (..), QueueMode (..), currentSMPClientVersion, supportedSMPClientVRange, pattern VersionSMPC) import Simplex.Messaging.ServiceScheme (ServiceScheme (..)) +import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.Messaging.Version import Test.Hspec hiding (fit, it) import Util @@ -295,6 +296,22 @@ connectionRequestTests = invalidE2EParamsStrUri = "v%3D3%26x3dh%3DMEIwBQYDK2VvAzk9mKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D%2CMEIwBQYDK2VvAzkAmKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D" strDecode @AConnectionRequestUri ("simplex:/contact#/?v=6-8&smp=" <> url invalidDhKeyQueueStr) `shouldSatisfy` isLeft strDecode @AConnectionRequestUri ("simplex:/invitation#/?v=6-8&smp=" <> url queueStr <> "&e2e=" <> invalidE2EParamsStrUri) `shouldSatisfy` isLeft + connectionRequestClientDataEmpty #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri <> "&data=" <> url "{}") + contactAddress #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr) + contactAddress #== ("https://simplex.chat/contact#/?v=2-7&smp=" <> url queueStr) + contactAddress2queues #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueStr <> ";" <> queueStr)) + contactAddressNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueNewStr) + contactAddress2queuesNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueNewStr <> ";" <> queueNewStr)) + contactAddressV2 #==# ("simplex:/contact#/?v=2&smp=" <> url queueStr) + contactAddressV2 #== ("https://simplex.chat/contact#/?v=1&smp=" <> url queueStr) -- adjusted to v2 + contactAddressV2 #== ("https://simplex.chat/contact#/?v=1-2&smp=" <> url queueStr) -- adjusted to v2 + contactAddressV2 #== ("https://simplex.chat/contact#/?v=2-2&smp=" <> url queueStr) + contactAddressClientData #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr <> "&data=" <> url "{\"type\":\"group_link\", \"group_link_id\":\"abc\"}") + it "should generate a bracketed IPv6 application-server authority" $ do + let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + request = CRInvitationUri (connReqData {crScheme = SSAppServer $ SrvLoc ipv6Host ""}) testE2ERatchetParams + encoded = strEncode request + encoded `shouldSatisfy` B.isPrefixOf "https://[2001:db8::1]/invitation#/?" it "should serialize / parse queue address, connection invitations and contact addresses as binary" $ do smpEncodingTest queue smpEncodingTest queueNoQM -- this passes, no queue mode patch in SMPQueueUri encoding @@ -328,6 +345,11 @@ connectionRequestTests = smpEncodingTest $ ACSL SCMContact $ CSLContact SLSServer CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") smpEncodingTest $ ACSL SCMInvitation $ CSLInvitation SLSServer shortSrv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") it "should serialize / parse short links" $ do + let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + ipv6Srv = srv {host = [ipv6Host, "jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion"]} + linkKey = LinkKey "0123456789abcdef0123456789abcdef" + ipv6Contact = CSLContact SLSServer CCTContact ipv6Srv linkKey + ipv6Invitation = CSLInvitation SLSServer ipv6Srv (EntityId "0123456789abcdef01234567") linkKey CSLContact SLSServer CCTContact srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLContact SLSServer CCTGroup srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/g#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLContact SLSServer CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY" @@ -338,6 +360,10 @@ connectionRequestTests = CSLContact SLSSimplex CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im" CSLInvitation SLSSimplex srv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im%2Cjjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLInvitation SLSSimplex shortSrv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im" + ipv6Contact #==# "https://[2001:db8::1]/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" + ipv6Invitation #==# "https://[2001:db8::1]/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" + smpEncodingTest ipv6Contact + smpEncodingTest ipv6Invitation it "should shorten / restore short links" $ do let contact = CSLContact SLSServer CCTContact shortenShortLink [srv] (contact srv (LinkKey "0123456789abcdef0123456789abcdef")) diff --git a/tests/CoreTests/EncodingTests.hs b/tests/CoreTests/EncodingTests.hs index 4108bef2a..fbc3cdfb3 100644 --- a/tests/CoreTests/EncodingTests.hs +++ b/tests/CoreTests/EncodingTests.hs @@ -16,7 +16,7 @@ import Data.Time.ISO8601 (parseISO8601) import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) -import Simplex.Messaging.Protocol (ProtocolServer (..), XFTPServer) +import Simplex.Messaging.Protocol (NtfServer, ProtoServerWithAuth (..), ProtocolServer (..), SMPServer, XFTPServer, legacyStrEncodeServer) import Simplex.Messaging.ServiceScheme (ServiceScheme (..), SrvLoc (..)) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Test.Hspec hiding (fit, it) @@ -81,6 +81,8 @@ encodingTests = modifyMaxSuccess (const 1000) $ do shouldReject @TransportHost "[simplex.chat]" shouldReject @TransportHost "[smp.simplex.im]" describe "Encoding service locations" $ do + it "should encode and decode bracketed IPv6 host with implicit HTTPS port" $ + (SSAppServer $ SrvLoc ipv6Host "") #==# "https://[2001:db8::1]" it "should parse bracketed IPv6 host with port" $ do strDecode @ServiceScheme "https://[2001:db8::1]:8443" `shouldBe` Right (SSAppServer $ SrvLoc "2001:db8::1" "8443") @@ -89,12 +91,38 @@ encodingTests = modifyMaxSuccess (const 1000) $ do it "should reject bracketed non-IPv6 host" $ shouldReject @ServiceScheme "https://[simplex.chat]:8443" describe "Encoding protocol servers" $ do - it "should parse bracketed IPv6 server host with port" $ - case strDecode @XFTPServer "xftp://1234-w==@[2001:db8::1]:443" of - Left err -> expectationFailure err - Right (ProtocolServer _ parsedHost parsedPort _) -> do - parsedHost `shouldBe` (ipv6Host :| []) - parsedPort `shouldBe` "443" + it "should canonically round-trip IPv6 server hosts and ports" $ do + let xftp = either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer + ipv6Server = xftp {host = ipv6Host :| [], port = "5223"} + defaultPortServer = ipv6Server {port = ""} + ipv6First = ipv6Server {host = ipv6Host :| ["example.com"]} + ipv6Last = ipv6Server {host = "example.com" :| [ipv6Host]} + ipv6Server #==# "xftp://1234-w==@[2001:db8::1]:5223" + defaultPortServer #==# "xftp://1234-w==@[2001:db8::1]" + ipv6First #==# "xftp://1234-w==@[2001:db8::1],example.com:5223" + ipv6Last #==# "xftp://1234-w==@example.com,[2001:db8::1]:5223" + ipv6First {port = ""} #==# "xftp://1234-w==@[2001:db8::1],example.com" + ipv6Last {port = ""} #==# "xftp://1234-w==@example.com,[2001:db8::1]" + it "should bracket IPv6 for each protocol and authenticated and legacy encoders" $ do + let smp = (either error id (strDecode "smp://1234-w==@example.com:5223") :: SMPServer) {host = ipv6Host :| []} + ntf = (either error id (strDecode "ntf://1234-w==@example.com:5223") :: NtfServer) {host = ipv6Host :| []} + xftp = (either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer) {host = ipv6Host :| ["example.com"]} + strEncode smp `shouldBe` "smp://1234-w==@[2001:db8::1]:5223" + strDecode (strEncode smp) `shouldBe` Right smp + strEncode ntf `shouldBe` "ntf://1234-w==@[2001:db8::1]:5223" + strDecode (strEncode ntf) `shouldBe` Right ntf + let authenticated = ProtoServerWithAuth xftp (Just "user") + legacy = legacyStrEncodeServer xftp + strEncode authenticated `shouldBe` "xftp://1234-w==:user@[2001:db8::1],example.com:5223" + strDecode (strEncode authenticated) `shouldBe` Right authenticated + legacy `shouldBe` "xftp://1234-w==@[2001:db8::1]:5223" + strDecode legacy `shouldBe` Right xftp {host = ipv6Host :| []} + it "should preserve non-IPv6 server encodings" $ do + let xftp = either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer + strEncode xftp {host = THIPv4 (192, 0, 2, 1) :| []} `shouldBe` "xftp://1234-w==@192.0.2.1:5223" + strEncode xftp `shouldBe` "xftp://1234-w==@example.com:5223" + strEncode xftp {host = "beccx4yfxxbvyhqypaavemqurytl6hozr47wfc7uuecacjqdvwpw2xid.onion" :| []} + `shouldBe` "xftp://1234-w==@beccx4yfxxbvyhqypaavemqurytl6hozr47wfc7uuecacjqdvwpw2xid.onion:5223" it "should reject bracketed non-IPv6 server host" $ shouldReject @XFTPServer "xftp://1234-w==@[simplex.chat]:443" where diff --git a/tests/FileDescriptionTests.hs b/tests/FileDescriptionTests.hs index a1f55afd7..4ac12dd42 100644 --- a/tests/FileDescriptionTests.hs +++ b/tests/FileDescriptionTests.hs @@ -15,6 +15,7 @@ import Data.Either (isRight) import qualified Data.Yaml as Y import Simplex.FileTransfer.Chunks (chunkSize0, chunkSize3, serverChunkSizes) import Simplex.FileTransfer.Client (prepareChunkSizes) +import Simplex.FileTransfer.Client.Main (decodeWebURI, fileWebLink) import Simplex.FileTransfer.Crypto (decryptChunks, encryptFile, sha512HashChunks) import Simplex.FileTransfer.Description import Simplex.FileTransfer.Protocol @@ -24,7 +25,7 @@ import qualified Simplex.Messaging.Crypto.File as CF import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding (smpEncode) import Simplex.Messaging.Encoding.String (StrEncoding (..)) -import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Protocol (EntityId (..), XFTPServer) import Simplex.Messaging.ServiceScheme (ServiceScheme (..)) import System.Directory (getFileSize, removeFile) import System.IO (IOMode (..), withFile) @@ -47,6 +48,7 @@ fileDescriptionTests = do describe "file description URIs" $ do it "round trip file description URI" testFileDescriptionURI it "round trip file description URI with extra JSON" testFileDescriptionURIExtras + it "encode IPv6 post-upload web link authority and preserve its fragment" testFileWebLinkIPv6 fileDescPath :: FilePath fileDescPath = "tests/fixtures/file_description.yaml" @@ -282,6 +284,31 @@ testDecryptChunks = dstPath = testPath "decrypted" withRemoveTmpFile :: HasTestEnv => IO () -> IO () +testFileWebLinkIPv6 :: IO () +testFileWebLinkIPv6 = do + let ipv6Server = either error id (strDecode "xftp://abc=@[2001:db8::1]:5223") :: XFTPServer + ipv6FileDesc = withPrimaryServer ipv6Server fileDesc + case fileWebLink ipv6FileDesc of + Nothing -> expectationFailure "expected an IPv6 web link" + Just (authority, fragment) -> do + let webLink = "https://" <> authority <> "/#" <> fragment + authority `shouldBe` "[2001:db8::1]" + webLink `shouldBe` "https://[2001:db8::1]/#" <> fragment + expected <- either fail pure $ validateFileDescription ipv6FileDesc + decodeWebURI fragment `shouldBe` Right expected + (fst <$> fileWebLink fileDesc) `shouldBe` Just "example1.com" + where + withPrimaryServer :: XFTPServer -> FileDescription 'FRecipient -> FileDescription 'FRecipient + withPrimaryServer server (FileDescription party fdSize fdDigest key nonce fdChunkSize (chunk : chunks) redirect) = + FileDescription party fdSize fdDigest key nonce fdChunkSize (replaceChunk chunk : chunks) redirect + where + replaceChunk :: FileChunk -> FileChunk + replaceChunk (FileChunk chunkNo size digest (FileChunkReplica _ replicaId replicaKey : replicas)) = + FileChunk chunkNo size digest (FileChunkReplica server replicaId replicaKey : replicas) + replaceChunk c = c + withPrimaryServer _ fd = fd + +withRemoveTmpFile :: IO () -> IO () withRemoveTmpFile = bracket_ (pure ()) diff --git a/tests/RemoteControl.hs b/tests/RemoteControl.hs index fa36ae6c0..bb8731aad 100644 --- a/tests/RemoteControl.hs +++ b/tests/RemoteControl.hs @@ -30,6 +30,7 @@ import Simplex.RemoteControl.Invitation ( RCEncInvitation (..), RCInvitation (..), RCSignedInvitation, + RCVerifiedInvitation (..), signInvitation, verifySignedInvitation, ) @@ -43,7 +44,8 @@ remoteControlTests :: Spec remoteControlTests = do describe "preferred bindings should go first" testPreferAddress describe "Invitation parsing" $ do - it "should parse bracketed IPv6 host with port" testInvitationBracketedIPv6Host + it "should encode and parse bracketed IPv6 host with port" testInvitationBracketedIPv6Host + it "should encode, parse and verify signed IPv6 invitation" testSignedInvitationBracketedIPv6Host it "should reject bracketed non-IPv6 host" testInvitationBracketedNonIPv6HostRejected describe "New controller/host pairing" $ do it "should connect to new pairing" testNewPairing @@ -88,10 +90,9 @@ testPreferAddress = do testInvitationBracketedIPv6Host :: IO () testInvitationBracketedIPv6Host = do invitation <- testIPv6Invitation - let bracketedUri = - B.pack . replaceFirst "@2001:db8::1:" "@[2001:db8::1]:" . B.unpack $ - strEncode invitation + let bracketedUri = strEncode invitation expectedHost = either error id (strDecode "2001:db8::1") :: TransportHost + bracketedUri `shouldSatisfy` B.isInfixOf "@[2001:db8::1]:5223" case strDecode bracketedUri of Left err -> expectationFailure err Right RCInvitation {host, port} -> do @@ -101,9 +102,7 @@ testInvitationBracketedIPv6Host = do testInvitationBracketedNonIPv6HostRejected :: IO () testInvitationBracketedNonIPv6HostRejected = do invitation <- testIPv6Invitation - let bracketedUri = - B.pack . replaceFirst "@2001:db8::1:" "@[simplex.chat]:" . B.unpack $ - strEncode invitation + let bracketedUri = B.pack . replaceFirst "@[2001:db8::1]:" "@[simplex.chat]:" . B.unpack $ strEncode invitation case strDecode bracketedUri :: Either String RCInvitation of Left _ -> pure () Right _ -> expectationFailure "expected parse failure for bracketed non-IPv6 host" @@ -117,6 +116,33 @@ replaceFirst needle replacement = go Just rest -> replacement <> rest Nothing -> c : go cs +testSignedInvitationBracketedIPv6Host :: IO () +testSignedInvitationBracketedIPv6Host = do + drg <- C.newRandom + (skey, sKey) <- atomically $ C.generateKeyPair @'C.Ed25519 drg + (idkey, idKey) <- atomically $ C.generateKeyPair @'C.Ed25519 drg + (dh, _) <- atomically $ C.generateKeyPair @'C.X25519 drg + let invitation = + RCInvitation + (C.KeyHash "test-ca") + (either error id $ strDecode "2001:db8::1") + 5223 + supportedRCPVRange + (J.String "app") + (MkSystemTime 0 0) + skey + idkey + dh + encoded = strEncode $ signInvitation sKey idKey invitation + encoded `shouldSatisfy` B.isInfixOf "@[2001:db8::1]:5223" + case strDecode encoded :: Either String RCSignedInvitation of + Left err -> expectationFailure err + Right signed -> case verifySignedInvitation signed of + Just (RCVerifiedInvitation RCInvitation {host, port}) -> do + host `shouldBe` either error id (strDecode "2001:db8::1") + port `shouldBe` 5223 + Nothing -> expectationFailure "expected valid signed IPv6 invitation" + testIPv6Invitation :: IO RCInvitation testIPv6Invitation = do drg <- C.newRandom diff --git a/tests/XFTPWebTests.hs b/tests/XFTPWebTests.hs index 4d1275f26..60942418a 100644 --- a/tests/XFTPWebTests.hs +++ b/tests/XFTPWebTests.hs @@ -38,6 +38,8 @@ import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (strDecode, strEncode) +import Simplex.Messaging.Protocol (XFTPServer, pattern XFTPServer) +import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.Messaging.Transport.Server (loadFileFingerprint) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, removeDirectoryRecursive) import System.Environment (getEnvironment) @@ -2903,6 +2905,27 @@ tsAddressTests = describe "protocol/address" $ do <> jsOut "new TextEncoder().encode(s.host + ':' + s.port)" result `shouldBe` "host1.com:5000" + it "preserves Haskell-produced IPv6 list ports with IPv6 first and last" $ do + let base = either error id (strDecode "xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@example.com") :: XFTPServer + XFTPServer _ _ keyHash = base + ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + vectors = + [ (ipv6Host NE.:| ["example.com"], "[2001:db8::1]", "5223"), + ("example.com" NE.:| [ipv6Host], "example.com", "5223"), + (ipv6Host NE.:| [], "[2001:db8::1]", "443") + ] + forM_ vectors $ \(hosts, expectedHost, expectedPort) -> do + let addressPort = if expectedPort == "443" then "" else expectedPort + address = strEncode $ XFTPServer hosts addressPort keyHash + result <- + callNode $ + impAddr + <> "const address = new TextDecoder().decode(" + <> jsUint8 address + <> ");const s = Addr.parseXFTPServer(address);" + <> jsOut "new TextEncoder().encode(s.host + '|' + s.port + '|' + Addr.formatXFTPServer(s))" + result `shouldBe` expectedHost <> "|" <> BC.pack expectedPort <> "|xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@" <> expectedHost <> ":" <> BC.pack expectedPort + -- ── integration ─────────────────────────────────────────────────── tsIntegrationTests :: Spec diff --git a/xftp-web/test/address.node.test.ts b/xftp-web/test/address.node.test.ts index b9738b334..e0fae482f 100644 --- a/xftp-web/test/address.node.test.ts +++ b/xftp-web/test/address.node.test.ts @@ -19,3 +19,19 @@ test('parseXFTPServer uses the default port for bracketed IPv6 hosts', () => { expect(server.port).toBe('443') expect(serverOrigin(server)).toBe('https://[2001:db8::1]') }) + +test('parseXFTPServer preserves a list-level port with IPv6 first', () => { + const server = parseXFTPServer(`xftp://${keyHash}@[2001:db8::1],example.com:5223`) + + expect(server.host).toBe('[2001:db8::1]') + expect(server.port).toBe('5223') + expect(formatXFTPServer(server)).toBe(`xftp://${keyHash}@[2001:db8::1]:5223`) +}) + +test('parseXFTPServer preserves a list-level port with IPv6 last', () => { + const server = parseXFTPServer(`xftp://${keyHash}@example.com,[2001:db8::1]:5223`) + + expect(server.host).toBe('example.com') + expect(server.port).toBe('5223') + expect(formatXFTPServer(server)).toBe(`xftp://${keyHash}@example.com:5223`) +}) From 3c888348c6a58971a3e01476b36623d92ce704d9 Mon Sep 17 00:00:00 2001 From: Evgeny Poberezkin Date: Mon, 10 Aug 2026 16:59:20 +0100 Subject: [PATCH 049/159] ntf server: use multiple APNS clients for each provider --- src/Simplex/Messaging/Notifications/Server.hs | 23 ++++++++----------- .../Messaging/Notifications/Server/Env.hs | 17 ++++++-------- 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index 1b2dfa86f..d474e075c 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -643,19 +643,15 @@ showServer' :: SMPServer -> Text showServer' = decodeLatin1 . strEncode . host pushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () -pushNotification = pushNotification_ $ \q -> atomically . writeTBQueue q - -tryPushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () -tryPushNotification = pushNotification_ $ \q x -> unlessM (atomically $ tryWriteTBQueue q x) $ incNtfStat ntfDropped - -pushNotification_ :: (TBQueue (NtfTknRec, PushNotification) -> (NtfTknRec, PushNotification) -> M ()) -> NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () -pushNotification_ enqueue s srvHost_ isOwn tkn@NtfTknRec {ntfTknId, token = token@(DeviceToken pp _)} ntf = +pushNotification s srvHost_ isOwn tkn@NtfTknRec {token = token@(DeviceToken pp _)} ntf = ifM (pushProviderAllowed token) - (getOrCreatePushWorker s (srvHost_, pp, hash (unEntityId ntfTknId) `mod` pushWorkersPerServer) isOwn >>= (`enqueue` (tkn, ntf))) + (getOrCreatePushWorker s (srvHost_, pp, pushTokenShardId 8 tkn) isOwn >>= atomically . (`writeTBQueue` (tkn, ntf))) (logWarn "skipping disabled APNS test push provider") - where - pushWorkersPerServer = 8 + +pushTokenShardId :: Int -> NtfTknRec -> Int +pushTokenShardId pushWorkersPerServer NtfTknRec {ntfTknId} = + hash (unEntityId ntfTknId) `mod` pushWorkersPerServer pushProviderAllowed :: DeviceToken -> M Bool pushProviderAllowed (DeviceToken PPApnsTest _) = asks (allowTestPushProvider . config) @@ -718,7 +714,7 @@ runPushWorker s srvHost_ isOwn q = forever $ do | otherwise = liftIO $ logError "bad notification token status" deliverNotification :: NtfPostgresStore -> PushProvider -> NtfTknRec -> PushNotification -> IO (Either PushProviderError ()) deliverNotification st pp tkn@NtfTknRec {ntfTknId} ntf' = do - (deliver, clientVar) <- getPushClient s pp + (deliver, clientVar) <- getPushClient s pp tokenShardId runExceptT (deliver tkn ntf') >>= \case Right _ -> pure $ Right () Left e -> case e of @@ -731,11 +727,12 @@ runPushWorker s srvHost_ isOwn q = forever $ do err e PPPermanentError -> err e where + tokenShardId = pushTokenShardId 8 tkn retryDeliver :: PushClientVar -> Text -> IO (Either PushProviderError ()) retryDeliver oldVar reason = do logWarn $ "retrying push (" <> tshow pp <> ", " <> tshow ntfTknId <> "): " <> reason - atomically $ removeSessVar oldVar pp (pushClients s) - (deliver, _) <- getPushClient s pp + atomically $ removeSessVar oldVar (pp, tokenShardId) (pushClients s) + (deliver, _) <- getPushClient s pp tokenShardId runExceptT (deliver tkn ntf') >>= \case Right _ -> pure $ Right () Left e -> case e of diff --git a/src/Simplex/Messaging/Notifications/Server/Env.hs b/src/Simplex/Messaging/Notifications/Server/Env.hs index 2f5761d1a..04a0774ad 100644 --- a/src/Simplex/Messaging/Notifications/Server/Env.hs +++ b/src/Simplex/Messaging/Notifications/Server/Env.hs @@ -30,11 +30,9 @@ module Simplex.Messaging.Notifications.Server.Env import Control.Concurrent (ThreadId) import qualified Control.Exception as E import Control.Logger.Simple -import Control.Monad import Control.Monad.Except import Control.Monad.Trans.Except import Crypto.Random -import Data.Functor (($>)) import Data.Int (Int64) import Simplex.Messaging.Agent.RetryInterval import Data.List.NonEmpty (NonEmpty) @@ -66,7 +64,6 @@ import Simplex.Messaging.Transport.Credentials (genCredentials, tlsCredentials) import Simplex.Messaging.Transport.Server (AddHTTP, ServerCredentials, TransportServerConfig, loadFingerprint, loadServerCredential) import Simplex.Messaging.Util (isAsyncCancellation, liftEitherWith, tshow) import Simplex.Messaging.Util () -import System.Exit (exitFailure) import System.Mem.Weak (Weak) import UnliftIO.STM @@ -175,7 +172,7 @@ data NtfPushServer = NtfPushServer { pushWorkers :: TMap (Maybe T.Text, PushProvider, Int) PushWorkerVar, -- Int is the worker shard pushWorkerSeq :: TVar Int, pushQSize :: Natural, - pushClients :: TMap PushProvider PushClientVar, + pushClients :: TMap (PushProvider, Int) PushClientVar, pushClientSeq :: TVar Int, apnsConfig :: APNSPushClientConfig } @@ -201,11 +198,11 @@ newNtfPushServer pushQSize apnsConfig = do -- | Single-flight access to the per-provider push client with bounded retry. -- The returned PushClientVar is the handle retryDeliver passes to removeSessVar to evict -- this specific instance before re-fetching. -getPushClient :: NtfPushServer -> PushProvider -> IO (PushProviderClient, PushClientVar) -getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInterval}} pp = +getPushClient :: NtfPushServer -> PushProvider -> Int -> IO (PushProviderClient, PushClientVar) +getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInterval}} pp tokenShardId = withRetryIntervalCount reconnectInterval $ \n _delay loop -> do ts <- getCurrentTime - E.try (getSessVarIO (pushClientSeq s) pp (pushClients s) ts >>= either (newPushClient s pp) waitForPushClient) >>= \case + E.try (atomically (getSessVar (pushClientSeq s) (pp, tokenShardId) (pushClients s) ts) >>= either (newPushClient s pp tokenShardId) waitForPushClient) >>= \case Right result -> pure result Left e | isAsyncCancellation e -> E.throwIO e @@ -214,15 +211,15 @@ getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInter loop | otherwise -> E.throwIO e -newPushClient :: NtfPushServer -> PushProvider -> PushClientVar -> IO (PushProviderClient, PushClientVar) -newPushClient NtfPushServer {pushClients, apnsConfig} pp v = do +newPushClient :: NtfPushServer -> PushProvider -> Int -> PushClientVar -> IO (PushProviderClient, PushClientVar) +newPushClient NtfPushServer {pushClients, apnsConfig} pp tokenShardId v = do r <- E.try $ case apnsProviderHost pp of Nothing -> pure $ \_ _ -> pure () Just host -> apnsPushProviderClient <$> createAPNSPushClient host apnsConfig atomically $ do putTMVar (sessionVar v) r case r of - Left _ -> removeSessVar v pp pushClients + Left _ -> removeSessVar v (pp, tokenShardId) pushClients Right _ -> pure () either E.throwIO (\c -> pure (c, v)) r From e48ef261568dcc3dc1cc15b43b3e7961c61f5ea5 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 04:09:57 -0500 Subject: [PATCH 050/159] ntf server: batch SMP subscriptions Consolidated from PR #1995. --- tests/NtfServerTests.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index db49434de..1c96ce23f 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -15,7 +15,7 @@ module NtfServerTests where import Control.Concurrent (threadDelay) import Control.Exception (bracket) -import Control.Monad (forM, replicateM, unless, void) +import Control.Monad (forM, replicateM, replicateM_, unless, void) import qualified Data.Aeson as J import qualified Data.Aeson.Types as JT import Data.Bifunctor (first) From 8a843c9c9db23c244d50f08bc5d3e5725b6900e7 Mon Sep 17 00:00:00 2001 From: spacedandy-agents-simplex <342056592+spacedandy-agents-simplex@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:30:50 +0000 Subject: [PATCH 051/159] tests: check every recipient key restored after link swaps --- tests/ServerTests.hs | 176 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index cf0003da8..550bbce71 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -2551,6 +2551,182 @@ testDuplicateQueueLinkData = victimSId2 `shouldBe` victimSId victimLD2 `shouldBe` victimLD +testLargeCommand :: SpecWith (ASrvTransport, AStoreType) +testLargeCommand = + it "refuses a command larger than an encrypted block and keeps the session" $ \(at, msType) -> + withSmpServer (at, msType) $ do + g <- C.newRandom + ts <- getCurrentTime + c <- getProtocolClient g NRMInteractive (1, SMPServer testHost testPort testKeyHash, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) >>= either (fail . show) pure + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + fd <- atomically $ C.randomBytes 2048 g + Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing + let largestUserData = 14165 + linkData n = (EncDataBytes fd, EncDataBytes $ B.replicate n 'a') + setLink n = runExceptT $ addSMPQueueLink c NRMInteractive rKey rId lnkId (linkData n) + setLink largestUserData `shouldReturn` Right () + setLink (largestUserData + 1) `shouldReturn` Left (PCETransportError TELargeMsg) + (fmap snd <$> runExceptT (getSMPQueueLink c NRMInteractive lnkId)) `shouldReturn` Right (linkData largestUserData) + +testSwapQueueLink :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLink = + it "swaps short link user data when the stored data hash matches" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r s -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + otherLnkId <- EntityId <$> atomically (C.randomBytes 24 g) + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + Resp "1" _ (LCUR ud) <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld1) Nothing ld1) + (ud, snd ld) #== "returns stored user data when the hash differs" + Resp "2" _ (LNK _ ld') <- sendRecv s ("", "2", lnkId, LGET) + (ld', ld) #== "link data unchanged after the hash differs" + + Resp "3" _ err1 <- signSendRecv r rKey ("3", rId, LSWP otherLnkId (userDataHash ld) Nothing ld1) + (err1, ERR AUTH) #== "rejects another link ID" + Resp "4" _ err2 <- signSendRecv r rKey ("4", rId, LSWP lnkId (userDataHash ld) Nothing (EncDataBytes "other fixed data", snd ld1)) + (err2, ERR AUTH) #== "rejects other fixed data" + + Resp "5" rId' OK <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld) Nothing ld1) + rId' `shouldBe` rId + Resp "6" _ (LNK _ ld1') <- sendRecv s ("", "6", lnkId, LGET) + (ld1', ld1) #== "replaces user data and keeps fixed data" + + (noLinkRId, noLinkKey, Nothing) <- createLinkQueue g r $ \_ -> QRContact Nothing + Resp "7" _ err3 <- signSendRecv r noLinkKey ("7", noLinkRId, LSWP lnkId (userDataHash ld1) Nothing ld1) + (err3, ERR AUTH) #== "rejects queue without link" + + (msgRId, msgKey, Just msgLnkId) <- createLinkQueue g r $ \sId -> QRMessaging $ Just (sId, ld) + Resp "8" _ err4 <- signSendRecv r msgKey ("8", msgRId, LSWP msgLnkId (userDataHash ld) Nothing ld1) + (err4, ERR AUTH) #== "rejects messaging queue" + +testSwapQueueLinkKeys :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkKeys = + it "swaps short link user data with recipient keys" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r s -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + (rPub', rKey') <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + Resp "1" _ OK <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld) (Just [C.toPublic rKey, rPub']) ld1) + Resp "2" _ err1 <- signSendRecv r rKey ("2", rId, LSET lnkId ld2) + (err1, ERR AUTH) #== "rejects LSET on a queue with two keys" + Resp "3" _ err2 <- signSendRecv r rKey' ("3", rId, LSET lnkId ld2) + (err2, ERR AUTH) #== "rejects LSET with the added key" + + Resp "4" _ OK <- signSendRecv r rKey' ("4", rId, LSWP lnkId (userDataHash ld1) (Just [rPub']) ld2) + Resp "5" _ err3 <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld2) Nothing ld1) + (err3, ERR AUTH) #== "rejects the removed key" + Resp "6" _ (LNK _ ld') <- sendRecv s ("", "6", lnkId, LGET) + (ld', ld2) #== "stores data written with the added key" + +testConcurrentSwapQueueLink :: SpecWith (ASrvTransport, AStoreType) +testConcurrentSwapQueueLink = + it "accepts one of concurrent swaps from the same data" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r1 r2 -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + ld3 = (fst ld, EncDataBytes "user data 3") + (rId, rKey, _) <- createLinkQueue g r1 $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + rs <- + concurrently + (signSendRecv r1 rKey ("1", rId, LSWP lnkId (userDataHash ld) Nothing ld1)) + (signSendRecv r2 rKey ("2", rId, LSWP lnkId (userDataHash ld) Nothing ld2)) + storedLD <- case rs of + (Resp "1" _ OK, Resp "2" _ (LCUR ud)) -> ld1 <$ (ud `shouldBe` snd ld1) + (Resp "1" _ (LCUR ud), Resp "2" _ OK) -> ld2 <$ (ud `shouldBe` snd ld2) + _ -> error $ "expected OK and LCUR, got " <> show rs + + Resp "3" _ OK <- signSendRecv r2 rKey ("3", rId, LSWP lnkId (userDataHash storedLD) Nothing ld3) + Resp "4" _ (LNK _ ld') <- sendRecv r1 ("", "4", lnkId, LGET) + (ld', ld3) #== "stores data swapped from the current data" + +testSwapQueueLinkClient :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkClient = + it "sends swaps only in v24 sessions, with up to 6 recipient keys" $ \(at, msType) -> + withSmpServer (at, msType) $ do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + connect vr = getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) >>= either (fail . show) pure + c <- connect supportedClientSMPRelayVRange + cPrev <- connect $ prevRange supportedClientSMPRelayVRange + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + fd <- atomically $ C.randomBytes 2048 g + let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13824 'a') + ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13824 'b') + otherKeys <- replicateM 5 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) + (rPub7, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing + Right () <- runExceptT $ addSMPQueueLink c NRMInteractive rKey rId lnkId ld + let keys6 = rPub :| otherKeys + keys7 = keys6 <> [rPub7] + swap c' keys = runExceptT $ swapSMPQueueLink c' NRMInteractive rKey rId lnkId (userDataHash ld) keys ld' + storedLD = fmap snd <$> runExceptT (getSMPQueueLink c NRMInteractive lnkId) + + swap cPrev Nothing `shouldReturn` Left (PCETransportError TEVersion) + swap c (Just keys7) `shouldReturn` Left (PCETransportError TELargeMsg) + storedLD `shouldReturn` Right ld + swap c (Just keys6) `shouldReturn` Right Nothing + storedLD `shouldReturn` Right ld' + +testSwapQueueLinkStoreLog :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkStoreLog = + it "restores swapped short link data and recipient keys after restart" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + (rPub1, rKey1) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rPub2, rKey2) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + ld3 = (fst ld, EncDataBytes "user data 3") + ld4 = (fst ld, EncDataBytes "user data 4") + (cfg', _) = serverStoreLogCfg msType + (rId, rKey) <- withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \r -> do + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + Resp "1" _ OK <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld) (Just [C.toPublic rKey, rPub1]) ld1) + Resp "2" _ OK <- signSendRecv r rKey1 ("2", rId, LSWP lnkId (userDataHash ld1) (Just [rPub1, rPub2]) ld2) + Resp "3" _ OK <- signSendRecv r rKey2 ("3", rId, LSWP lnkId (userDataHash ld2) Nothing ld3) + pure (rId, rKey) + withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \r -> do + Resp "4" _ (LNK _ ld') <- sendRecv r ("", "4", lnkId, LGET) + (ld', ld3) #== "restores data of the last swap" + Resp "5" _ err1 <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld3) Nothing ld4) + (err1, ERR AUTH) #== "restores removed key as removed" + Resp "6" _ (LCUR ud) <- signSendRecv r rKey1 ("6", rId, LSWP lnkId (userDataHash ld2) Nothing ld4) + (ud, snd ld3) #== "restores the first key" + Resp "7" _ OK <- signSendRecv r rKey2 ("7", rId, LSWP lnkId (userDataHash ld3) Nothing ld4) + Resp "8" _ (LNK _ ld4') <- sendRecv r ("", "8", lnkId, LGET) + (ld4', ld4) #== "swaps restored data" + +createLinkQueue :: Transport c => TVar ChaChaDRG -> THandleSMP c 'TClient -> (SenderId -> QueueReqData) -> IO (RecipientId, C.APrivateAuthKey, Maybe LinkId) +createLinkQueue g r queueReqData = do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + C.CbNonce corrId <- atomically $ C.randomCbNonce g + let sId = EntityId $ B.take 24 $ C.sha3_384 corrId + Resp _ NoEntity (IDS QIK {rcvId, linkId}) <- + signSendRecv r rKey (corrId, NoEntity, NEW (NewQueueReq rPub dhPub Nothing SMSubscribe (Just $ queueReqData sId) Nothing)) + pure (rcvId, rKey, linkId) + +userDataHash :: QueueLinkData -> LinkDataHash +userDataHash = linkDataHash . snd + samplePubKey :: C.APublicVerifyKey samplePubKey = C.APublicVerifyKey C.SEd25519 "MCowBQYDK2VwAyEAfAOflyvbJv1fszgzkQ6buiZJVgSpQWsucXq7U6zjMgY=" From 1ea80e874f48ee495a4100188fe9b975b9fae13d Mon Sep 17 00:00:00 2001 From: spacedandy-agents-simplex <342056592+spacedandy-agents-simplex@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:45:24 +0000 Subject: [PATCH 052/159] tests: check the forwarded correlation ID below the nonce version --- tests/SMPProxyTests.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index b0890202d..48ee6486e 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -522,9 +522,9 @@ testChangedFwdVersion = et <- encrypt $ SMP.encTransmissionNonce v nonce _ <- runExceptT' $ forward corrId v et runExceptT (forward corrId (prevVersion v) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) - runExceptT (forward (C.unCbNonce $ SMP.encTransmissionNonce v nonce) (prevVersion v) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) - (_, SMP.EncResponse resp) <- runExceptT' . forward corrId (prevVersion v) =<< encrypt nonce - runExceptT (forward (C.unCbNonce $ C.reverseNonce nonce) (prevVersion v) $ SMP.EncTransmission resp) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + runExceptT (forward (C.unCbNonce $ SMP.encTransmissionNonce v nonce) (prevVersion fwdNoncesSMPVersion) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + (_, SMP.EncResponse resp) <- runExceptT' . forward corrId (prevVersion fwdNoncesSMPVersion) =<< encrypt nonce + runExceptT (forward (C.unCbNonce $ C.reverseNonce nonce) (prevVersion fwdNoncesSMPVersion) $ SMP.EncTransmission resp) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) testFwdCorrIdSize :: HasTestEnv => IO () testFwdCorrIdSize = From a09845d5a1fb6b253512650de7ebb1c284219886 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:07:31 +0000 Subject: [PATCH 053/159] docs: server stats persistence plan --- ...r-stats-persistence-implementation-plan.md | 1594 +++++++++++++++++ 1 file changed, 1594 insertions(+) create mode 100644 plans/2026-10-23-server-stats-persistence-implementation-plan.md diff --git a/plans/2026-10-23-server-stats-persistence-implementation-plan.md b/plans/2026-10-23-server-stats-persistence-implementation-plan.md new file mode 100644 index 000000000..f071efc7a --- /dev/null +++ b/plans/2026-10-23-server-stats-persistence-implementation-plan.md @@ -0,0 +1,1594 @@ +# SMP Server Stats Persistence Implementation Plan + +**Goal:** SMP server stats survive crashes: periodic saves to Postgres (Postgres mode) or an atomically written file (memory mode), with active-queue sets saved incrementally. + +**Architecture:** A new `Simplex.Messaging.Server.StatsStore` module loads and saves `ServerStatsData` through a file or a database backend. `PeriodStats` tracks hashes added since the last save so the database receives only new hashes. `Server.hs` restores on start, recomputes store counts, saves on a timer, around the daily rollover, and on shutdown, all under `savingLock`. + +**Tech Stack:** Haskell (GHC 9.6.3), postgresql-simple, hspec, cabal with `-fserver_postgres`. + +**Spec:** `plans/2026-10-23-server-stats-persistence-design.md` + +## Global Constraints + +- Build and test with `-fserver_postgres`; PostgreSQL must run on `localhost:5432` (see `contributing/PROJECT.md`). Use the same flags for every command so cabal does not rebuild between steps: `cabal build -fserver_postgres --ghc-options=-O0`, `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="..."`. +- Never wait with `sleep`/polling loops; run commands in the foreground with a timeout. +- Format changed Haskell with fourmolu (`fourmolu -i `); files with CPP (`Server.hs`, `Env/STM.hs`, `StatsStore.hs`, test files with CPP) are formatted by fragment, matching surrounding style. +- No new compiler warnings (library uses `-Weverything`); imports used only under `dbServerPostgres` go inside the `#if defined(dbServerPostgres)` block. +- Comments only where code cannot state it (ordering, invariants); no plan/spec references in code. +- Commit messages: `: `, max 50 chars, imperative, no body, no co-author. +- `server_stats_queues.period_set` values are fixed: 1 msg day, 2 msg week, 3 msg month, 4 ntf day, 5 ntf week, 6 ntf month. +- Column order of `server_stats` in the migration, `statsFields`, and the `FromRow StatsRow` instance must be identical. +- Default save interval 300 seconds, INI key `[STORE_LOG] stats_save_interval`. + +**User decisions (already made):** +- Postgres-mode servers store stats in a Postgres table; the existing file is imported once when the database has no stats row, then renamed to `.bak`; afterwards the database is the only source and corrections are done with SQL. +- One `BIGINT` column per persisted metric (not a text blob or JSONB). +- Active-queue sets are stored incrementally in a hash table (`server_stats_queues`), only new hashes inserted per save, rows of reset sets deleted. +- Memory-mode servers save the file periodically with temp file + rename and no longer rename it to `.bak` at startup. +- Scope: the metrics persisted in the file today, plus recomputing `qCount`/`msgCount`/`ntfCount` from the store on every start. +- Save interval is an INI option with default 300 seconds, active only when `log_stats = on`. + +--- + +## File Structure + +| File | Responsibility | +|---|---| +| `src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs` | New migration `20261023_server_stats` | +| `src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql` | Regenerated schema dump | +| `src/Simplex/Messaging/Server/Env/STM.hs` | `statsSaveInterval` config, `defStatsSaveInterval`, pending tracking switch in `newEnv` | +| `src/Simplex/Messaging/Server/Main.hs`, `Main/Init.hs` | INI option read and generated ini comment | +| `src/Simplex/Messaging/Server/Stats.hs` | Pending hashes in `PeriodStats`, `newServerStats` switch | +| `src/Simplex/Messaging/Server/StatsStore.hs` (new) | Load/save stats via file or database | +| `src/Simplex/Messaging/Server.hs` | Restore, periodic save thread, rollover and shutdown saves | +| `simplexmq.cabal` | New library module and test module | +| `tests/CoreTests/ServerStatsTests.hs` (new) | Pending tracking, file and database store tests | +| `tests/ServerTests.hs`, `tests/SMPClient.hs`, `tests/Test.hs` | Server-level tests, test config, registration | + +--- + +### Task 1: Add server_stats schema migration + +**Goal:** Postgres tables for persisted stats exist and the schema dump matches. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs` (migration list at the top; definitions appended at the end of the file) +- Modify: `src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql` (regenerated by the schema dump test) + +**Acceptance Criteria:** +- [ ] `server_stats` has `server_stats_id SMALLINT PRIMARY KEY CHECK (server_stats_id = 1)`, `saved_at`, `from_time` and 84 counter columns, all `BIGINT NOT NULL` +- [ ] `server_stats_queues(period_set SMALLINT, queue_hash BIGINT, PRIMARY KEY (period_set, queue_hash))` +- [ ] Down migration drops both tables +- [ ] `/SMP server schema dump/` tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server schema dump/"` → 2 examples, 0 failures (second run, after the first run rewrote the dump) + +**Steps:** + +- [ ] **Step 1: Register the migration** + +In `serverSchemaMigrations`, after the `20260918_expire_messages` entry: + +```haskell + ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), + ("20261023_server_stats", m20261023_server_stats, Just down_m20261023_server_stats) + ] +``` + +- [ ] **Step 2: Append migration definitions at the end of the file** + +```haskell +m20261023_server_stats :: Text +m20261023_server_stats = + [r| +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); + |] + +down_m20261023_server_stats :: Text +down_m20261023_server_stats = + [r| +DROP TABLE server_stats_queues; + +DROP TABLE server_stats; + |] +``` + +- [ ] **Step 3: Run the schema dump test to regenerate the dump** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server schema dump/"` +Expected: "verify and overwrite schema dump" FAILS once (dump differs) and rewrites `server_schema.sql`; "verify schema down migrations" passes. + +- [ ] **Step 4: Run it again** + +Run the same command. +Expected: 2 examples, 0 failures. `git diff --stat` shows `server_schema.sql` with the two new tables and their primary keys only. + +- [ ] **Step 5: Commit** + +```bash +git add src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +git commit -m "smp server: add server_stats tables" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs", "src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/SMP server schema dump/\"", "acceptanceCriteria": ["server_stats singleton row with 84 counter columns", "server_stats_queues with composite PK", "down migration drops both tables", "schema dump tests pass"], "modelTier": "mechanical"} +``` + +--- + +### Task 2: Add stats_save_interval config option + +**Goal:** `ServerConfig.statsSaveInterval` is read from `[STORE_LOG] stats_save_interval` (default 300) and documented in the generated ini. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/Env/STM.hs` (export list near `defNtfExpirationHours`; constants after `defaultNtfExpiration`; `ServerConfig` after `serverStatsBackupFile`) +- Modify: `src/Simplex/Messaging/Server/Main.hs:497` (config record) +- Modify: `src/Simplex/Messaging/Server/Main/Init.hs:106-108` (ini text) +- Modify: `tests/SMPClient.hs:266` (test config) + +**Acceptance Criteria:** +- [ ] `defStatsSaveInterval = 300` exported from `Env.STM` +- [ ] `statsSaveInterval` read with `readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval"` +- [ ] Generated ini contains `# stats_save_interval = 300` after `# prometheus_interval = 60` +- [ ] `/Server CLIs/` tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Server CLIs/"` → 0 failures + +**Steps:** + +- [ ] **Step 1: Config field and default in `Env/STM.hs`** + +Export list, after `defNtfExpirationHours,`: + +```haskell + defNtfExpirationHours, + defStatsSaveInterval, +``` + +After the `defaultNtfExpiration` definition: + +```haskell +defStatsSaveInterval :: Int64 +defStatsSaveInterval = 300 +``` + +In `ServerConfig`, after `serverStatsBackupFile`: + +```haskell + -- | file to save and restore stats + serverStatsBackupFile :: Maybe FilePath, + -- | interval to save stats, seconds + statsSaveInterval :: Int64, +``` + +- [ ] **Step 2: Read the option in `Main.hs`** + +After `serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log",`: + +```haskell + serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log", + statsSaveInterval = readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini, +``` + +- [ ] **Step 3: Document it in the generated ini (`Main/Init.hs`)** + +Replace: + +```haskell + <> "# Log interval for real-time Prometheus metrics\n\ + \# prometheus_interval = 60\n\n\ + \[AUTH]\n\ +``` + +with: + +```haskell + <> "# Log interval for real-time Prometheus metrics\n\ + \# prometheus_interval = 60\n\n" + <> "# Interval to save server statistics, seconds (requires log_stats)\n" + <> ("# stats_save_interval = " <> tshow defStatsSaveInterval <> "\n\n") + <> "[AUTH]\n\ +``` + +The rest of the `[AUTH]` literal stays unchanged. + +- [ ] **Step 4: Test config (`tests/SMPClient.hs`, `cfgMS`)** + +After `serverStatsBackupFile = Nothing,`: + +```haskell + serverStatsBackupFile = Nothing, + statsSaveInterval = defStatsSaveInterval, +``` + +`SMPClient.hs` already imports `Simplex.Messaging.Server.Env.STM` unqualified. + +- [ ] **Step 5: Build and run CLI tests** + +Run: `cabal build -fserver_postgres --ghc-options=-O0 all` +Expected: builds with no new warnings. +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Server CLIs/"` +Expected: 0 failures. + +- [ ] **Step 6: Commit** + +```bash +git add src/Simplex/Messaging/Server/Env/STM.hs src/Simplex/Messaging/Server/Main.hs src/Simplex/Messaging/Server/Main/Init.hs tests/SMPClient.hs +git commit -m "smp server: add stats_save_interval option" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/Env/STM.hs", "src/Simplex/Messaging/Server/Main.hs", "src/Simplex/Messaging/Server/Main/Init.hs", "tests/SMPClient.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Server CLIs/\"", "acceptanceCriteria": ["defStatsSaveInterval = 300 exported", "statsSaveInterval read from STORE_LOG", "generated ini documents the option", "CLI tests pass"], "modelTier": "mechanical"} +``` + +--- + +### Task 3: Track pending active-queue hashes + +**Goal:** `PeriodStats` optionally records hashes added and sets reset since the last save; SMP `ServerStats` enables it only for Postgres-mode servers with stats persistence. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/Stats.hs` (export list; `newServerStats`; `PeriodStats`; `newPeriodStats`; `periodStatCounts`; `updatePeriodStats`) +- Modify: `src/Simplex/Messaging/Server/Env/STM.hs:548,574` (`newEnv`) +- Create: `tests/CoreTests/ServerStatsTests.hs` +- Modify: `tests/Test.hs` (import and `describe` in "Core tests"), `simplexmq.cabal` (test `other-modules`, after `CoreTests.SOCKSSettings`) + +**Acceptance Criteria:** +- [ ] `newPeriodStats` has no pending tracking (XFTP and NTF servers unchanged) +- [ ] `newPendingPeriodStats` records each hash once per period until taken +- [ ] Day reset always, week reset on Monday, month reset on the 1st set `pendingReset = True` and clear `pendingAdded` +- [ ] `restorePendingHashes` merges taken hashes back (union, reset flags OR-ed) +- [ ] `newEnv` enables tracking only when `serverStatsBackupFile` is set and the store is Postgres +- [ ] `/Core tests/Server stats tests/pending period stats/` pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` → 4 examples, 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing tests** + +Create `tests/CoreTests/ServerStatsTests.hs`: + +```haskell +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +module CoreTests.ServerStatsTests where + +import Data.Hashable (hash) +import Data.IORef +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.Maybe (isNothing) +import Data.Time.Calendar (fromGregorian) +import Data.Time.Clock (UTCTime (..)) +import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Server.Stats +import Test.Hspec hiding (fit, it) +import Util + +serverStatsTests :: Spec +serverStatsTests = + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + +q1, q2, q3, q4, q5 :: EntityId +q1 = EntityId "queue1" +q2 = EntityId "queue2" +q3 = EntityId "queue3" +q4 = EntityId "queue4" +q5 = EntityId "queue5" + +hashes :: [EntityId] -> IntSet +hashes = IS.fromList . map (hash . unEntityId) + +utcDay :: Integer -> Int -> Int -> UTCTime +utcDay y m d = UTCTime (fromGregorian y m d) 3600 + +-- 2026-06-10 is Wednesday, 2026-06-08 is Monday, 2026-06-01 is Monday and the 1st +wednesday, monday, monday1st :: UTCTime +wednesday = utcDay 2026 6 10 +monday = utcDay 2026 6 8 +monday1st = utcDay 2026 6 1 + +noPending :: PendingHashes +noPending = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +resetPending :: PendingHashes +resetPending = PendingHashes {pendingReset = True, pendingAdded = IS.empty} + +added :: [EntityId] -> PendingHashes +added qs = PendingHashes {pendingReset = False, pendingAdded = hashes qs} + +testNoPending :: IO () +testNoPending = do + ps <- newPeriodStats + isNothing (pendingPeriods ps) `shouldBe` True + updatePeriodStats ps q1 + readIORef (day ps) `shouldReturn` hashes [q1] + ServerStats {activeQueues, activeQueuesNtf} <- newServerStats False wednesday + isNothing (pendingPeriods activeQueues) `shouldBe` True + isNothing (pendingPeriods activeQueuesNtf) `shouldBe` True + +testPendingAdded :: IO () +testPendingAdded = do + ServerStats {activeQueues = ps} <- newServerStats True wednesday + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + mapM_ (updatePeriodStats ps) [q1, q2, q1] + takePendingHashes pendingDay `shouldReturn` added [q1, q2] + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q1 + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q3 + takePendingHashes pendingDay `shouldReturn` added [q3] + takePendingHashes pendingWeek `shouldReturn` added [q1, q2, q3] + takePendingHashes pendingMonth `shouldReturn` added [q1, q2, q3] + readIORef (day ps) `shouldReturn` hashes [q1, q2, q3] + +testPendingReset :: IO () +testPendingReset = do + ps <- newPendingPeriodStats + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + updatePeriodStats ps q1 + PeriodStatCounts {dayCount, weekCount, monthCount} <- periodStatCounts ps wednesday + (dayCount, weekCount, monthCount) `shouldBe` ("1", "", "") + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` added [q1] + takePendingHashes pendingMonth `shouldReturn` added [q1] + updatePeriodStats ps q2 + _ <- periodStatCounts ps monday + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` resetPending + takePendingHashes pendingMonth `shouldReturn` added [q2] + readIORef (month ps) `shouldReturn` hashes [q1, q2] + updatePeriodStats ps q3 + _ <- periodStatCounts ps monday1st + mapM takePendingHashes [pendingDay, pendingWeek, pendingMonth] `shouldReturn` [resetPending, resetPending, resetPending] + mapM readIORef [day ps, week ps, month ps] `shouldReturn` [IS.empty, IS.empty, IS.empty] + updatePeriodStats ps q4 + takePendingHashes pendingMonth `shouldReturn` added [q4] + +testMergePending :: IO () +testMergePending = do + mergePendingHashes (added [q1]) (added [q2]) `shouldBe` added [q1, q2] + mergePendingHashes resetPending (added [q2]) `shouldBe` PendingHashes {pendingReset = True, pendingAdded = hashes [q2]} + ref <- newIORef $ added [q5] + restorePendingHashes ref PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4]} + readIORef ref `shouldReturn` PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4, q5]} +``` + +Register it. In `tests/Test.hs` imports, after `import CoreTests.SOCKSSettings`: + +```haskell +import CoreTests.SOCKSSettings +import CoreTests.ServerStatsTests +``` + +In "Core tests", after `describe "Message store tests" msgStoreTests`: + +```haskell + describe "Message store tests" msgStoreTests + describe "Server stats tests" serverStatsTests +``` + +In `simplexmq.cabal` test-suite `other-modules`, after `CoreTests.SOCKSSettings`: + +``` + CoreTests.SOCKSSettings + CoreTests.ServerStatsTests +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: compile error — `pendingPeriods`, `PendingPeriods`, `PendingHashes`, `takePendingHashes`, `newPendingPeriodStats`, `mergePendingHashes`, `restorePendingHashes` not in scope; `newServerStats` applied to too many arguments. + +- [ ] **Step 3: Implement pending tracking in `Stats.hs`** + +Export list, replace `newPeriodStats,` with: + +```haskell + newPeriodStats, + newPendingPeriodStats, + PendingPeriods (..), + PendingHashes (..), + takePendingHashes, + restorePendingHashes, + mergePendingHashes, +``` + +`newServerStats`: change the signature and the two `PeriodStats` allocations, and add a `where`: + +```haskell +newServerStats :: Bool -> UTCTime -> IO ServerStats +newServerStats trackPending ts = do +``` + +```haskell + activeQueues <- newActiveQueues +``` + +```haskell + activeQueuesNtf <- newActiveQueues +``` + +and after the final `pure ServerStats {...}` expression of `newServerStats`: + +```haskell + rslvStats + } + where + newActiveQueues = if trackPending then newPendingPeriodStats else newPeriodStats +``` + +Replace the `PeriodStats` type and `newPeriodStats`: + +```haskell +data PeriodStats = PeriodStats + { day :: IORef IntSet, + week :: IORef IntSet, + month :: IORef IntSet, + pendingPeriods :: Maybe PendingPeriods + } + +-- hashes added and sets reset since the last successful save +data PendingPeriods = PendingPeriods + { pendingDay :: IORef PendingHashes, + pendingWeek :: IORef PendingHashes, + pendingMonth :: IORef PendingHashes + } + +data PendingHashes = PendingHashes + { pendingReset :: Bool, + pendingAdded :: IntSet + } + deriving (Eq, Show) + +newPeriodStats :: IO PeriodStats +newPeriodStats = newPeriodStats_ Nothing + +newPendingPeriodStats :: IO PeriodStats +newPendingPeriodStats = do + pendingDay <- newIORef noPendingHashes + pendingWeek <- newIORef noPendingHashes + pendingMonth <- newIORef noPendingHashes + newPeriodStats_ $ Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} + +newPeriodStats_ :: Maybe PendingPeriods -> IO PeriodStats +newPeriodStats_ pendingPeriods = do + day <- newIORef IS.empty + week <- newIORef IS.empty + month <- newIORef IS.empty + pure PeriodStats {day, week, month, pendingPeriods} + +noPendingHashes :: PendingHashes +noPendingHashes = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +takePendingHashes :: IORef PendingHashes -> IO PendingHashes +takePendingHashes ref = atomicModifyIORef' ref (noPendingHashes,) + +restorePendingHashes :: IORef PendingHashes -> PendingHashes -> IO () +restorePendingHashes ref taken = atomicModifyIORef'_ ref $ mergePendingHashes taken + +mergePendingHashes :: PendingHashes -> PendingHashes -> PendingHashes +mergePendingHashes (PendingHashes r hs) (PendingHashes r' hs') = PendingHashes (r || r') (IS.union hs hs') +``` + +Replace `periodStatCounts`: + +```haskell +periodStatCounts :: PeriodStats -> UTCTime -> IO PeriodStatCounts +periodStatCounts ps ts = do + let d = utctDay ts + (_, wDay) = mondayStartWeek d + MonthDay _ mDay = d + pending_ = pendingPeriods ps + dayCount <- periodCount 1 (day ps) (pendingDay <$> pending_) + weekCount <- periodCount wDay (week ps) (pendingWeek <$> pending_) + monthCount <- periodCount mDay (month ps) (pendingMonth <$> pending_) + pure PeriodStatCounts {dayCount, weekCount, monthCount} + where + periodCount :: Int -> IORef IntSet -> Maybe (IORef PendingHashes) -> IO Text + periodCount 1 ref pRef_ = do + -- pending is reset before the set, so a hash added concurrently can only be persisted for the new period + mapM_ (`atomicWriteIORef` PendingHashes {pendingReset = True, pendingAdded = IS.empty}) pRef_ + tshow . IS.size <$> atomicSwapIORef ref IS.empty + periodCount _ _ _ = pure "" +``` + +Replace `updatePeriodStats`: + +```haskell +updatePeriodStats :: PeriodStats -> EntityId -> IO () +updatePeriodStats ps (EntityId pId) = do + updatePeriod (day ps) (pendingDay <$> pendingPeriods ps) + updatePeriod (week ps) (pendingWeek <$> pendingPeriods ps) + updatePeriod (month ps) (pendingMonth <$> pendingPeriods ps) + where + ph = hash pId + updatePeriod ref pRef_ = unlessM (IS.member ph <$> readIORef ref) $ do + atomicModifyIORef'_ ref $ IS.insert ph + mapM_ (\pRef -> atomicModifyIORef'_ pRef $ \p -> p {pendingAdded = IS.insert ph $ pendingAdded p}) pRef_ +``` + +- [ ] **Step 4: Enable tracking in `newEnv` (`Env/STM.hs`)** + +Add `serverStatsBackupFile` to the `newEnv` pattern: + +```haskell +newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes, serverStatsBackupFile} = do +``` + +Replace `serverStats <- newServerStats =<< getCurrentTime`: + +```haskell + serverStats <- newServerStats (isJust serverStatsBackupFile && isJust (dbStoreCfg serverStoreCfg)) =<< getCurrentTime +``` + +- [ ] **Step 5: Run tests to verify they pass** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 4 examples, 0 failures. `cabal build -fserver_postgres --ghc-options=-O0 all` shows no new warnings (XFTP and NTF servers compile unchanged). + +- [ ] **Step 6: Commit** + +```bash +git add src/Simplex/Messaging/Server/Stats.hs src/Simplex/Messaging/Server/Env/STM.hs tests/CoreTests/ServerStatsTests.hs tests/Test.hs simplexmq.cabal +git commit -m "smp server: track pending active queue hashes" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/Stats.hs", "src/Simplex/Messaging/Server/Env/STM.hs", "tests/CoreTests/ServerStatsTests.hs", "tests/Test.hs", "simplexmq.cabal"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Core tests/Server stats tests/\"", "acceptanceCriteria": ["newPeriodStats without pending", "pending hashes recorded once per period", "reset flags per day/Monday/1st", "restore merges taken hashes", "newEnv tracks pending only for Postgres with persistence", "4 tests pass"], "modelTier": "standard"} +``` + +--- + +### Task 4: Add StatsStore module + +**Goal:** `loadStats`/`saveStats` persist `ServerStatsData` to a file (atomic replace) or to Postgres (row upsert, incremental hashes, one-time file import). + +**Files:** +- Create: `src/Simplex/Messaging/Server/StatsStore.hs` +- Modify: `simplexmq.cabal` (library `exposed-modules` in the `!flag(client_library)` block, after `Simplex.Messaging.Server.Stats`) +- Modify: `tests/CoreTests/ServerStatsTests.hs` + +**Acceptance Criteria:** +- [ ] File save writes `.tmp` then renames; load does not rename; missing file gives `Nothing`; invalid file throws; write errors are logged, not thrown +- [ ] DB save deletes rows of flagged sets, inserts pending hashes (batches of 10000, `ON CONFLICT DO NOTHING`), upserts the row, in one transaction +- [ ] DB save failure logs and restores taken pending hashes +- [ ] DB load returns the row and all six sets; unknown `period_set` throws +- [ ] DB load with no row imports the file in one transaction and renames it to `.bak`; with a row, the file is left in place with a warning +- [ ] Round trip preserves every persisted field (distinct values per field) + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` → 13 examples, 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing tests** + +In `tests/CoreTests/ServerStatsTests.hs` add `{-# LANGUAGE CPP #-}` to the pragmas, extend imports: + +```haskell +import qualified Data.ByteString.Char8 as B +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.StatsStore +import System.Directory (doesFileExist) +#if defined(dbServerPostgres) +import Control.Exception (bracket) +import Control.Monad (void) +import CoreTests.MsgStoreTests (testPostgresStoreConfig) +import qualified Database.PostgreSQL.Simple as DB +import Data.String (fromString) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) +import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) +import Simplex.Messaging.Server.QueueStore.Postgres (PostgresQueueStore (..)) +#endif +``` + +Replace `serverStatsTests`: + +```haskell +serverStatsTests :: Spec +serverStatsTests = do + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + describe "stats file" $ do + it "should save and load stats" testFileSaveLoad + it "should return no stats without file" testFileMissing + it "should log and continue when file cannot be written" testFileSaveError + it "should fail on invalid file" testFileParseError +#if defined(dbServerPostgres) + describe "stats database" $ do + it "should save and load stats with period sets" testDBSaveLoad + it "should save added hashes and delete reset sets" testDBResetAndAdded + it "should keep pending hashes when save fails" testDBSaveFailure + it "should import stats file when database has no stats" testDBImportFile + it "should ignore stats file when database has stats" testDBIgnoreFile +#endif +``` + +Append the helpers and tests: + +```haskell +statsFile :: HasTestEnv => FilePath +statsFile = testPath "smp-server-stats.log" + +-- every zero counter line of the file encoding gets a distinct value, so a column order mistake changes the result +distinctCounters :: ServerStatsData -> ServerStatsData +distinctCounters d = either error id $ strDecode $ B.unlines $ zipWith setValue [1 :: Int ..] $ B.lines $ strEncode d + where + setValue i l = case B.breakSubstring "=" l of + (k, "=0") -> k <> "=" <> B.pack (show i) + _ -> l + +newDistinctStats :: Bool -> IO ServerStats +newDistinctStats trackPending = do + ss <- newServerStats trackPending wednesday + setServerStats ss . distinctCounters =<< getServerStatsData ss + pure ss + +testFileSaveLoad :: HasTestEnv => IO () +testFileSaveLoad = do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + updatePeriodStats (activeQueuesNtf ss) q2 + saveStats (StatsFile statsFile) ss + doesFileExist (statsFile <> ".tmp") `shouldReturn` False + expected <- getServerStatsData ss + Just d <- loadStats (StatsFile statsFile) + strEncode d `shouldBe` strEncode expected + doesFileExist statsFile `shouldReturn` True + +testFileMissing :: HasTestEnv => IO () +testFileMissing = (isNothing <$> loadStats (StatsFile statsFile)) `shouldReturn` True + +testFileSaveError :: HasTestEnv => IO () +testFileSaveError = do + let f = testPath "missing/smp-server-stats.log" + saveStats (StatsFile f) =<< newServerStats False wednesday + doesFileExist f `shouldReturn` False + +testFileParseError :: HasTestEnv => IO () +testFileParseError = do + B.writeFile statsFile "invalid" + loadStats (StatsFile statsFile) `shouldThrow` anyIOException + +#if defined(dbServerPostgres) +withStatsDB :: HasTestEnv => (DBStore -> IO a) -> IO a +withStatsDB action = bracket (newMsgStore testPostgresStoreConfig :: IO PostgresMsgStore) closeMsgStore $ action . dbStore . queueStore + +testDBSaveLoad :: HasTestEnv => IO () +testDBSaveLoad = withStatsDB $ \st -> do + ss <- newDistinctStats True + mapM_ (updatePeriodStats $ activeQueues ss) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + expected <- getServerStatsData ss + Just d <- getDBStats st + strEncode d `shouldBe` strEncode expected {_qCount = 0} + _day (_activeQueues d) `shouldBe` hashes [q1, q2] + _month (_activeQueuesNtf d) `shouldBe` hashes [q3] + +testDBResetAndAdded :: HasTestEnv => IO () +testDBResetAndAdded = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + mapM_ (updatePeriodStats msgQueues) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + updatePeriodStats msgQueues q4 + _ <- periodStatCounts msgQueues wednesday + updatePeriodStats msgQueues q5 + saveStats (StatsDB st statsFile) ss + Just ServerStatsData {_activeQueues, _activeQueuesNtf} <- getDBStats st + _day _activeQueues `shouldBe` hashes [q5] + _week _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _month _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _day _activeQueuesNtf `shouldBe` hashes [q3] + +testDBSaveFailure :: HasTestEnv => IO () +testDBSaveFailure = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + updatePeriodStats (activeQueues ss) q2 + renameTable st "server_stats_queues" "server_stats_queues_moved" + saveStats (StatsDB st statsFile) ss + renameTable st "server_stats_queues_moved" "server_stats_queues" + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + saveStats (StatsDB st statsFile) ss + Just d' <- getDBStats st + _day (_activeQueues d') `shouldBe` hashes [q1, q2] + where + renameTable st from to = withTransaction st $ \db -> void $ DB.execute_ db $ fromString $ "ALTER TABLE " <> from <> " RENAME TO " <> to + +testDBImportFile :: HasTestEnv => IO () +testDBImportFile = withStatsDB $ \st -> do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + d <- getServerStatsData ss + B.writeFile statsFile $ strEncode d + Just imported <- loadStats (StatsDB st statsFile) + strEncode imported `shouldBe` strEncode d + doesFileExist statsFile `shouldReturn` False + doesFileExist (statsFile <> ".bak") `shouldReturn` True + Just saved <- getDBStats st + strEncode saved `shouldBe` strEncode d {_qCount = 0} + +testDBIgnoreFile :: HasTestEnv => IO () +testDBIgnoreFile = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + saved <- getServerStatsData ss + B.writeFile statsFile . strEncode =<< getServerStatsData =<< newDistinctStats False + Just loaded <- loadStats (StatsDB st statsFile) + strEncode loaded `shouldBe` strEncode saved {_qCount = 0} + doesFileExist statsFile `shouldReturn` True +#endif +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: compile error — module `Simplex.Messaging.Server.StatsStore` not found. + +- [ ] **Step 3: Create `src/Simplex/Messaging/Server/StatsStore.hs`** + +```haskell +{-# LANGUAGE CPP #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} + +module Simplex.Messaging.Server.StatsStore + ( StatsStore (..), + loadStats, + saveStats, +#if defined(dbServerPostgres) + PeriodSet (..), + getDBStats, +#endif + ) +where + +import qualified Control.Exception as E +import Control.Logger.Simple +import Control.Monad +import qualified Data.ByteString.Char8 as B +import qualified Data.Text as T +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Util (ifM, tshow) +import System.Directory (doesFileExist, removeFile, renameFile) +import UnliftIO.Exception (tryAny) +#if defined(dbServerPostgres) +import Data.Bifunctor (bimap) +import Data.IORef (IORef) +import Data.Int (Int16, Int64) +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.List (find, intersperse) +import qualified Data.List.NonEmpty as L +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import Database.PostgreSQL.Simple (Only (..), Query) +import qualified Database.PostgreSQL.Simple as DB +import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) +import Database.PostgreSQL.Simple.ToField (ToField (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Util (toChunks, whenM) +#endif + +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath +#endif + +loadStats :: StatsStore -> IO (Maybe ServerStatsData) +loadStats = \case + StatsFile f -> ifM (doesFileExist f) (Just <$> readStatsFile f) (pure Nothing) +#if defined(dbServerPostgres) + StatsDB st f -> + getDBStats st >>= \case + Just d -> do + whenM (doesFileExist f) $ logWarn $ "server stats file " <> T.pack f <> " is ignored, stats are restored from the database" + pure $ Just d + Nothing -> ifM (doesFileExist f) (Just <$> importStatsFile st f) (pure Nothing) +#endif + +saveStats :: StatsStore -> ServerStats -> IO () +saveStats = \case + StatsFile f -> saveStatsFile f +#if defined(dbServerPostgres) + StatsDB st _ -> saveDBStats st +#endif + +readStatsFile :: FilePath -> IO ServerStatsData +readStatsFile f = do + logNote $ "restoring server stats from file " <> T.pack f + strDecode <$> B.readFile f >>= \case + Right d -> pure d + Left e -> E.throwIO $ userError $ "error parsing server stats file " <> f <> ": " <> e + +saveStatsFile :: FilePath -> ServerStats -> IO () +saveStatsFile f ss = do + d <- getServerStatsData ss + tryAny (B.writeFile tmp (strEncode d) >> renameFile tmp f) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to file " <> T.pack f <> ": " <> tshow e + void $ tryAny $ removeFile tmp + where + tmp = f <> ".tmp" + +#if defined(dbServerPostgres) +data PeriodSet = PSMsgDay | PSMsgWeek | PSMsgMonth | PSNtfDay | PSNtfWeek | PSNtfMonth + deriving (Bounded, Enum, Eq, Ord, Show) + +-- stored in server_stats_queues.period_set, the values must not change +periodSetId :: PeriodSet -> Int16 +periodSetId = \case + PSMsgDay -> 1 + PSMsgWeek -> 2 + PSMsgMonth -> 3 + PSNtfDay -> 4 + PSNtfWeek -> 5 + PSNtfMonth -> 6 + +instance ToField PeriodSet where + toField = toField . periodSetId + +periodSetFromId :: Int16 -> Maybe PeriodSet +periodSetFromId i = find ((i ==) . periodSetId) [minBound .. maxBound] + +periodSetHashes :: ServerStatsData -> PeriodSet -> IntSet +periodSetHashes ServerStatsData {_activeQueues = q, _activeQueuesNtf = n} = \case + PSMsgDay -> _day q + PSMsgWeek -> _week q + PSMsgMonth -> _month q + PSNtfDay -> _day n + PSNtfWeek -> _week n + PSNtfMonth -> _month n + +periodSetPending :: ServerStats -> PeriodSet -> Maybe (IORef PendingHashes) +periodSetPending ServerStats {activeQueues, activeQueuesNtf} = \case + PSMsgDay -> pendingDay <$> pendingPeriods activeQueues + PSMsgWeek -> pendingWeek <$> pendingPeriods activeQueues + PSMsgMonth -> pendingMonth <$> pendingPeriods activeQueues + PSNtfDay -> pendingDay <$> pendingPeriods activeQueuesNtf + PSNtfWeek -> pendingWeek <$> pendingPeriods activeQueuesNtf + PSNtfMonth -> pendingMonth <$> pendingPeriods activeQueuesNtf + +getDBStats :: DBStore -> IO (Maybe ServerStatsData) +getDBStats st = + withTransaction st $ \db -> + DB.query_ db selectStatsQuery >>= \case + StatsRow d : _ -> Just . withPeriodSets d <$> DB.fold_ db "SELECT period_set, queue_hash FROM server_stats_queues" M.empty addHash + [] -> pure Nothing + where + addHash sets (psId :: Int16, h :: Int64) = case periodSetFromId psId of + Just ps -> pure $! M.alter (Just . maybe (IS.singleton h') (IS.insert h')) ps sets + Nothing -> E.throwIO $ userError $ "unknown period_set " <> show psId + where + h' = fromIntegral h + withPeriodSets d sets = + d + { _activeQueues = periodData PSMsgDay PSMsgWeek PSMsgMonth, + _activeQueuesNtf = periodData PSNtfDay PSNtfWeek PSNtfMonth + } + where + periodData dp wp mp = PeriodStatsData {_day = get dp, _week = get wp, _month = get mp} + get p = M.findWithDefault IS.empty p sets + +importStatsFile :: DBStore -> FilePath -> IO ServerStatsData +importStatsFile st f = do + d <- readStatsFile f + withTransaction st $ \db -> do + void $ DB.execute_ db "DELETE FROM server_stats_queues" + forM_ [minBound .. maxBound] $ \ps -> insertHashes db ps $ periodSetHashes d ps + upsertStats db d + renameFile f $ f <> ".bak" + logNote "server stats imported to the database" + pure d + +saveDBStats :: DBStore -> ServerStats -> IO () +saveDBStats st ss = do + taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> + forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref + d <- getServerStatsData ss + tryAny (withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to the database: " <> tshow e + forM_ taken $ \(_, ref, p) -> restorePendingHashes ref p + where + savePending db (ps, _, PendingHashes {pendingReset, pendingAdded}) = do + when pendingReset $ void $ DB.execute db "DELETE FROM server_stats_queues WHERE period_set = ?" (Only ps) + insertHashes db ps pendingAdded + +insertHashes :: DB.Connection -> PeriodSet -> IntSet -> IO () +insertHashes db ps hs = + forM_ (toChunks hashInsertBatch $ IS.toList hs) $ \hs' -> + void $ + DB.executeMany + db + "INSERT INTO server_stats_queues (period_set, queue_hash) VALUES (?, ?) ON CONFLICT DO NOTHING" + (map (\h -> (ps, fromIntegral h :: Int64)) $ L.toList hs') + +-- rows per INSERT statement, bounds the query size of the one-time file import +hashInsertBatch :: Int +hashInsertBatch = 10000 + +upsertStats :: DB.Connection -> ServerStatsData -> IO () +upsertStats db d = do + savedAt <- systemSeconds <$> getSystemTime + void $ DB.execute db upsertStatsQuery $ savedAt : map (($ d) . snd) statsFields + +selectStatsQuery :: Query +selectStatsQuery = "SELECT " <> commaSep (map fst statsFields) <> " FROM server_stats WHERE server_stats_id = 1" + +upsertStatsQuery :: Query +upsertStatsQuery = + "INSERT INTO server_stats (server_stats_id, saved_at, " + <> commaSep cols + <> ") VALUES (1, ?, " + <> commaSep (map (const "?") cols) + <> ") ON CONFLICT (server_stats_id) DO UPDATE SET " + <> commaSep (map (\c -> c <> " = EXCLUDED." <> c) ("saved_at" : cols)) + where + cols = map fst statsFields + +commaSep :: [Query] -> Query +commaSep = mconcat . intersperse ", " + +-- the order must match the FromRow StatsRow instance +statsFields :: [(Query, ServerStatsData -> Int64)] +statsFields = + ("from_time", round . utcTimeToPOSIXSeconds . _fromTime) + : map + (fmap (fromIntegral .)) + ( [ ("q_created", _qCreated), + ("q_secured", _qSecured), + ("q_deleted_all", _qDeletedAll), + ("q_deleted_new", _qDeletedNew), + ("q_deleted_secured", _qDeletedSecured), + ("q_deleted_all_b", _qDeletedAllB), + ("q_blocked", _qBlocked), + ("q_sub", _qSub), + ("q_sub_all_b", _qSubAllB), + ("q_sub_auth", _qSubAuth), + ("q_sub_duplicate", _qSubDuplicate), + ("q_sub_prohibited", _qSubProhibited), + ("q_sub_end", _qSubEnd), + ("q_sub_end_b", _qSubEndB), + ("ntf_created", _ntfCreated), + ("ntf_new_created", _ntfNewCreated), + ("ntf_deleted", _ntfDeleted), + ("ntf_deleted_b", _ntfDeletedB), + ("ntf_sub", _ntfSub), + ("ntf_sub_b", _ntfSubB), + ("ntf_sub_auth", _ntfSubAuth), + ("ntf_sub_duplicate", _ntfSubDuplicate), + ("msg_sent", _msgSent), + ("msg_sent_auth", _msgSentAuth), + ("msg_sent_quota", _msgSentQuota), + ("msg_sent_large", _msgSentLarge), + ("msg_sent_block", _msgSentBlock), + ("msg_recv", _msgRecv), + ("msg_recv_get", _msgRecvGet), + ("msg_get", _msgGet), + ("msg_get_no_msg", _msgGetNoMsg), + ("msg_get_auth", _msgGetAuth), + ("msg_get_duplicate", _msgGetDuplicate), + ("msg_get_prohibited", _msgGetProhibited), + ("msg_expired", _msgExpired), + ("msg_sent_ntf", _msgSentNtf), + ("msg_recv_ntf", _msgRecvNtf), + ("msg_ntfs", _msgNtfs), + ("msg_ntfs_b", _msgNtfsB), + ("msg_ntf_no_sub", _msgNtfNoSub), + ("msg_ntf_lost", _msgNtfLost), + ("msg_ntf_expired", _msgNtfExpired) + ] + <> proxyFields "p_relays" _pRelays + <> proxyFields "p_relays_own" _pRelaysOwn + <> proxyFields "p_msg_fwds" _pMsgFwds + <> proxyFields "p_msg_fwds_own" _pMsgFwdsOwn + <> [("p_msg_fwds_recv", _pMsgFwdsRecv)] + <> serviceFields "rcv_services" _rcvServices + <> serviceFields "ntf_services" _ntfServices + <> map + (fmap (. _rslvStats)) + [ ("rslv_reqs", _rslvReqs), + ("rslv_succ", _rslvSucc), + ("rslv_not_found", _rslvNotFound), + ("rslv_resolver_errs", _rslvResolverErrs), + ("rslv_disabled", _rslvDisabled) + ] + ) + where + proxyFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("requests", _pRequests), + ("successes", _pSuccesses), + ("errors_connect", _pErrorsConnect), + ("errors_compat", _pErrorsCompat), + ("errors_other", _pErrorsOther) + ] + serviceFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("assoc_new", _srvAssocNew), + ("assoc_duplicate", _srvAssocDuplicate), + ("assoc_updated", _srvAssocUpdated), + ("assoc_removed", _srvAssocRemoved), + ("sub_count", _srvSubCount), + ("sub_duplicate", _srvSubDuplicate), + ("sub_queues", _srvSubQueues), + ("sub_end", _srvSubEnd) + ] + +newtype StatsRow = StatsRow ServerStatsData + +instance FromRow StatsRow where + fromRow = do + _fromTime <- posixSecondsToUTCTime . fromIntegral <$> field @Int64 + _qCreated <- field + _qSecured <- field + _qDeletedAll <- field + _qDeletedNew <- field + _qDeletedSecured <- field + _qDeletedAllB <- field + _qBlocked <- field + _qSub <- field + _qSubAllB <- field + _qSubAuth <- field + _qSubDuplicate <- field + _qSubProhibited <- field + _qSubEnd <- field + _qSubEndB <- field + _ntfCreated <- field + _ntfNewCreated <- field + _ntfDeleted <- field + _ntfDeletedB <- field + _ntfSub <- field + _ntfSubB <- field + _ntfSubAuth <- field + _ntfSubDuplicate <- field + _msgSent <- field + _msgSentAuth <- field + _msgSentQuota <- field + _msgSentLarge <- field + _msgSentBlock <- field + _msgRecv <- field + _msgRecvGet <- field + _msgGet <- field + _msgGetNoMsg <- field + _msgGetAuth <- field + _msgGetDuplicate <- field + _msgGetProhibited <- field + _msgExpired <- field + _msgSentNtf <- field + _msgRecvNtf <- field + _msgNtfs <- field + _msgNtfsB <- field + _msgNtfNoSub <- field + _msgNtfLost <- field + _msgNtfExpired <- field + _pRelays <- proxyStatsP + _pRelaysOwn <- proxyStatsP + _pMsgFwds <- proxyStatsP + _pMsgFwdsOwn <- proxyStatsP + _pMsgFwdsRecv <- field + _rcvServices <- serviceStatsP + _ntfServices <- serviceStatsP + _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field + pure $ + StatsRow + ServerStatsData + { _fromTime, + _qCreated, + _qSecured, + _qDeletedAll, + _qDeletedAllB, + _qDeletedNew, + _qDeletedSecured, + _qBlocked, + _qSub, + _qSubAllB, + _qSubAuth, + _qSubDuplicate, + _qSubProhibited, + _qSubEnd, + _qSubEndB, + _ntfCreated, + _ntfNewCreated, + _ntfDeleted, + _ntfDeletedB, + _ntfSub, + _ntfSubB, + _ntfSubAuth, + _ntfSubDuplicate, + _msgSent, + _msgSentAuth, + _msgSentQuota, + _msgSentLarge, + _msgSentBlock, + _msgRecv, + _msgRecvAckTimes = emptyTimeBuckets, + _msgRecvGet, + _msgGet, + _msgGetNoMsg, + _msgGetAuth, + _msgGetDuplicate, + _msgGetProhibited, + _msgExpired, + _activeQueues = newPeriodStatsData, + _msgSentNtf, + _msgRecvNtf, + _activeQueuesNtf = newPeriodStatsData, + _msgNtfs, + _msgNtfsB, + _msgNtfNoSub, + _msgNtfLost, + _msgNtfExpired, + _pRelays, + _pRelaysOwn, + _pMsgFwds, + _pMsgFwdsOwn, + _pMsgFwdsRecv, + _ntfServices, + _rcvServices, + _rcvServicesSubMsg = 0, + _rcvServicesSubDuplicate = 0, + _authDelayExceeded = 0, + _cmdSlotWaits = 0, + _cmdSlotWaitMs = 0, + _cmdSlotWaitMaxMs = 0, + _cmdSlotWaitTimeouts = 0, + _qCount = 0, + _msgCount = 0, + _ntfCount = 0, + _rslvStats + } + where + proxyStatsP = ProxyStatsData <$> field <*> field <*> field <*> field <*> field + serviceStatsP = do + _srvAssocNew <- field + _srvAssocDuplicate <- field + _srvAssocUpdated <- field + _srvAssocRemoved <- field + _srvSubCount <- field + _srvSubDuplicate <- field + _srvSubQueues <- field + _srvSubEnd <- field + pure newServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} +#endif +``` + +In `simplexmq.cabal`, library `exposed-modules` (the `!flag(client_library)` block), after `Simplex.Messaging.Server.Stats`: + +``` + Simplex.Messaging.Server.Stats + Simplex.Messaging.Server.StatsStore +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 13 examples, 0 failures (the failing-save test logs one "error saving server stats to the database" line). +Run: `cabal build --ghc-options=-O0 lib:simplexmq` (without `-fserver_postgres`) +Expected: builds with no warnings from `StatsStore.hs`. + +- [ ] **Step 5: Commit** + +```bash +git add src/Simplex/Messaging/Server/StatsStore.hs simplexmq.cabal tests/CoreTests/ServerStatsTests.hs +git commit -m "smp server: add stats store" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/StatsStore.hs", "simplexmq.cabal", "tests/CoreTests/ServerStatsTests.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Core tests/Server stats tests/\"", "acceptanceCriteria": ["atomic file save, no rename on load", "DB save deletes reset sets, inserts pending, upserts row in one tx", "failed DB save restores pending", "DB load with sets; unknown period_set throws", "import once with .bak; row wins over file", "round trip with distinct values", "13 tests pass", "builds without server_postgres"], "modelTier": "frontier"} +``` + +--- + +### Task 5: Save stats periodically in the server + +**Goal:** The SMP server restores stats through `StatsStore`, recomputes store counts on every start, and saves stats on a timer, around the daily rollover and on shutdown under `savingLock`. + +**Files:** +- Modify: `src/Simplex/Messaging/Server.hs` (imports; `raceAny_` thread list ~:186; `saveServer` ~:239; `serverStatsThread_`/`logServerStats` ~:510-530; `saveServerStats`/`restoreServerStats` ~:2515-2549) +- Modify: `tests/ServerTests.hs` (imports; `serverTests` list; `testRestoreMessages`; `testRestoreExpireMessages`; new tests) + +**Acceptance Criteria:** +- [ ] Postgres mode loads from `server_stats` (or imports the file once); memory mode loads the file without renaming +- [ ] Load errors log and exit +- [ ] `qCount`, `msgCount`, `ntfCount` are set from the store on every start; startup expiration counts are added to `msgExpired`/`msgNtfExpired` +- [ ] `saveStatsThread` saves every `statsSaveInterval` seconds under `savingLock` when `serverStatsBackupFile` is set +- [ ] Daily rollover saves before and after writing the daily line, holding `savingLock` +- [ ] Shutdown and control `save` save stats before the message store is closed +- [ ] Existing restore tests pass for memory and Postgres stores; new tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/"` → 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing server tests (`tests/ServerTests.hs`)** + +Imports: change `import Data.Maybe (catMaybes)` to `import Data.Maybe (catMaybes, fromMaybe)`. In the `#if defined(dbServerPostgres)` import block add: + +```haskell +import CoreTests.ServerStatsTests (withStatsDB) +import Simplex.Messaging.Server.StatsStore (getDBStats) +``` + +In `serverTests`, after `describe "Restore messages (old / v2)" testRestoreExpireMessages`: + +```haskell + describe "Restore messages (old / v2)" testRestoreExpireMessages + describe "Save server stats" $ do + testSaveStatsPeriodically + testStartupStoreCounts +``` + +Add after `checkStats`: + +```haskell +readSavedStats :: HasTestEnv => AStoreType -> IO ServerStatsData +readSavedStats = \case + ASType _ SMSMemory -> do + logSize testServerStatsBackupFile `shouldReturn` 101 + either error id . strDecode <$> B.readFile testServerStatsBackupFile +#if defined(dbServerPostgres) + ASType _ SMSPostgres -> withStatsDB $ fmap (fromMaybe $ error "no saved stats") . getDBStats +#else + ASType _ SMSPostgres -> error "compiled without server_postgres flag" +#endif + +testSaveStatsPeriodically :: SpecWith (ASrvTransport, AStoreType) +testSaveStatsPeriodically = + it "should save stats while running and restore them on start" $ \(at@(ATransport t), msType) -> do + removeFileIfExists testServerStatsBackupFile + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, statsSaveInterval = 1} + (rId, stats1, snapshot) <- withSmpServerConfigOn at cfg' testPort $ \_ -> do + rId <- runClient t $ \h -> runClient t $ \rh -> do + (sId, rId, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello") + pure rId + threadDelay 1500000 + stats1 <- readSavedStats msType + snapshot <- case msType of + ASType _ SMSMemory -> Just <$> B.readFile testServerStatsBackupFile + _ -> pure Nothing + pure (rId, stats1, snapshot) + checkStats stats1 [rId] 1 0 + -- a crash leaves the last periodic save, not the save on shutdown + mapM_ (B.writeFile testServerStatsBackupFile) snapshot + stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 1500000 >> readSavedStats msType + checkStats stats2 [rId] 1 0 + removeFileIfExists testServerStatsBackupFile + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + +testStartupStoreCounts :: SpecWith (ASrvTransport, AStoreType) +testStartupStoreCounts = + it "should count stored queues and messages on start without saved stats" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = cfgMS msType + withSmpServerConfigOn at cfg' testPort $ \_ -> runClient t $ \h -> runClient t $ \rh -> do + (sId, _, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello 1") + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () + let cfg2 = updateCfg cfg' $ \cfg_ -> cfg_ {prometheusInterval = Just 1} + metrics <- withSmpServerConfigOn at cfg2 testPort $ \_ -> threadDelay 1500000 >> B.readFile testPrometheusMetricsFile + let expected = case msType of + ASType SQSMemory _ -> ["simplex_smp_messages_total 2", "simplex_smp_queues_total1 1"] + -- Postgres queue count is a reltuples estimate + _ -> ["simplex_smp_messages_total 2"] + forM_ expected $ \l -> B.lines metrics `shouldContain` [l] + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient +``` + +Update the existing restore tests to read stats through `readSavedStats`: + +In `testRestoreMessages`, replace each of the three pairs + +```haskell + logSize testServerStatsBackupFile `shouldReturn` 101 + Right stats1 <- strDecode <$> B.readFile testServerStatsBackupFile +``` + +(and the same for `stats2`, `stats3`) with + +```haskell + stats1 <- readSavedStats msType +``` + +(`stats2`, `stats3` respectively), and replace `removeFile testServerStatsBackupFile` with `removeFileIfExists testServerStatsBackupFile`. + +In `testRestoreExpireMessages`, replace + +```haskell + Right ServerStatsData {_msgExpired} <- strDecode <$> B.readFile testServerStatsBackupFile +``` + +with + +```haskell + ServerStatsData {_msgExpired} <- readSavedStats msType +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/Save server stats/"` +Expected: FAIL — memory: "should save stats while running" fails (`logSize` finds no file while running); both stores: "should count stored queues and messages" fails (`simplex_smp_messages_total 0` or `simplex_smp_queues_total1 0`); Postgres: `readSavedStats` gets "no saved stats". + +- [ ] **Step 3: Server imports (`Server.hs`)** + +After `import Simplex.Messaging.Server.Stats`: + +```haskell +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore +``` + +Remove `renameFile` from `import UnliftIO.Directory (doesFileExist, renameFile)` if no other use remains (check with `rg -n "renameFile" src/Simplex/Messaging/Server.hs` after Step 7). + +In the existing `#if defined(dbServerPostgres)` import block: + +```haskell +#if defined(dbServerPostgres) +import Simplex.Messaging.Server.MsgStore.Postgres (getDbMessageStats) +import qualified Simplex.Messaging.Server.QueueStore.Postgres as PQ +#endif +``` + +- [ ] **Step 4: Start the save thread** + +In the `raceAny_` list: + +```haskell + <> serverStatsThread_ cfg + <> saveStatsThread_ cfg + <> prometheusMetricsThread_ cfg +``` + +After `serverStatsThread_` definition (before `logServerStats`): + +```haskell + saveStatsThread_ :: ServerConfig s -> [M s ()] + saveStatsThread_ ServerConfig {serverStatsBackupFile = Just _, statsSaveInterval} = [saveStatsThread statsSaveInterval] + saveStatsThread_ _ = [] + + saveStatsThread :: Int64 -> M s () + saveStatsThread interval = do + labelMyThread "saveStatsThread" + lock <- asks $ savingLock . server + forever $ do + liftIO $ threadDelay' $ 1000000 * interval + withLock' lock "saveStats" saveServerStats +``` + +- [ ] **Step 5: Save around the daily rollover (`logServerStats`)** + +Before `let interval = 1000000 * logInterval`: + +```haskell + lock <- asks $ savingLock . server + u <- askUnliftIO + let interval = 1000000 * logInterval +``` + +Replace `withFile statsFilePath AppendMode $ \h -> liftIO $ do` with + +```haskell + withFile statsFilePath AppendMode $ \h -> withLock' lock "logStats" $ liftIO $ do + unliftIO u saveServerStats + hSetBuffering h LineBuffering +``` + +(`hSetBuffering h LineBuffering` is the existing first line.) After the last statement of that block, the multi-line `T.hPutStrLn h $ T.intercalate "," (...)`, add at the same indentation: + +```haskell + unliftIO u saveServerStats +``` + +- [ ] **Step 6: Save stats before closing the store (`saveServer`)** + +```haskell + saveServer :: Bool -> M s () + saveServer drainMsgs = do + -- the database stats store is closed together with the message store + saveServerStats + ms <- asks msgStore_ + liftIO $ saveServerMessages drainMsgs ms >> closeMsgStore (fromMsgStore ms) + saveServerNtfs +``` + +- [ ] **Step 7: Replace `saveServerStats` and `restoreServerStats`** + +Replace both definitions with: + +```haskell +serverStatsStore :: M s (Maybe StatsStore) +serverStatsStore = do + ms <- asks msgStore_ + fmap (statsStore ms) <$> asks (serverStatsBackupFile . config) + where + statsStore :: MsgStore s -> FilePath -> StatsStore + statsStore = \case + StoreMemory _ -> StatsFile +#if defined(dbServerPostgres) + StoreDatabase ms -> StatsDB (PQ.dbStore $ queueStore ms) +#endif + +saveServerStats :: M s () +saveServerStats = do + ss <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . (`saveStats` ss)) + +restoreServerStats :: forall s. MsgStoreClass s => Maybe MessageStats -> MessageStats -> M s () +restoreServerStats msgStats_ ntfStats = do + s <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . tryAny . loadStats >=> restore s) + st <- asks msgStore + EntityCounts {queueCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + liftIO $ do + writeIORef (qCount s) queueCount + writeIORef (msgCount s) $ maybe 0 storedMsgsCount msgStats_ + writeIORef (ntfCount s) $ storedMsgsCount ntfStats + atomicModifyIORef'_ (msgExpired s) (+ maybe 0 expiredMsgsCount msgStats_) + atomicModifyIORef'_ (msgNtfExpired s) (+ expiredMsgsCount ntfStats) + where + restore s = \case + Right (Just d) -> liftIO (setServerStats s d) >> logNote "server stats restored" + Right Nothing -> pure () + Left e -> do + logError $ "error restoring server stats: " <> tshow e + liftIO exitFailure +``` + +`restoreServerStats` keeps its call site (`restoreServerStats msgStats_ ntfStats`, ~:182). Check that `renameFile` and `B.readFile`/`strDecode` imports are still used elsewhere in `Server.hs`; remove only unused ones. + +- [ ] **Step 8: Build without warnings** + +Run: `cabal build -fserver_postgres --ghc-options=-O0 all` and `cabal build --ghc-options=-O0 lib:simplexmq` +Expected: no warnings in changed files. + +- [ ] **Step 9: Run server tests** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/"` +Expected: 0 failures for memory and postgres-only stores, including "Save server stats", "Restore messages", "Restore messages (old / v2)". +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 13 examples, 0 failures. +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Notifications server/"` +Expected: 0 failures (uses `withSmpServerStoreLogOn` with stats persistence). + +- [ ] **Step 10: Commit** + +```bash +git add src/Simplex/Messaging/Server.hs tests/ServerTests.hs +git commit -m "smp server: save stats periodically" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server.hs", "tests/ServerTests.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/SMP server via TLS/\"", "acceptanceCriteria": ["restore via StatsStore per mode", "load errors exit", "store counts recomputed every start", "periodic save under savingLock", "rollover saves before and after daily line", "shutdown saves before closing store", "existing and new server tests pass"], "modelTier": "frontier"} +``` From 333ccb020d6a2cbbc8b9087b0bdb928dd5b24a41 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 09:50:23 +0000 Subject: [PATCH 054/159] docs: server stats persistence design --- ...6-10-23-server-stats-persistence-design.md | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 plans/2026-10-23-server-stats-persistence-design.md diff --git a/plans/2026-10-23-server-stats-persistence-design.md b/plans/2026-10-23-server-stats-persistence-design.md new file mode 100644 index 000000000..d30290714 --- /dev/null +++ b/plans/2026-10-23-server-stats-persistence-design.md @@ -0,0 +1,227 @@ +# SMP server stats persistence + +## Problem + +SMP server stats live in `IORef`s and are written to `smp-server-stats.log` only on clean shutdown or the control port `save` command (`saveServer`, `Server.hs:240`, `Server.hs:1036`). At startup the file is restored and renamed to `.bak` (`Server.hs:2540`), so no stats file exists while the server runs. A crash loses all stats since start, including lifetime counters (`*_services_assoc_*`, `*_services_sub_*`, `ntfNewCreated`, `msgSentBlock`) and the active-queue period sets. Without the file, `qCount` and `ntfCount` start from 0 and drift, and `msgCount` stays wrong until the first expiration run (`Server.hs:491`). + +## Goals + +- Crash loses at most one save interval of stats. +- Postgres-mode servers keep stats in the database, covered by database backups. +- Memory-mode servers keep stats in the file, written atomically. +- `qCount`, `msgCount`, `ntfCount` are correct after every start. + +## Non-goals + +- Persisting counters that the file does not persist today (`srvSubOk/More/Fewer/Diff/*Total`, `rcvServicesSubMsg`, `rcvServicesSubDuplicate`, `authDelayExceeded`, `cmdSlotWait*`, `msgRecvAckTimes`). +- XFTP and notification server stats. +- Resetting week/month sets when the server is down on a Monday or the 1st (existing behaviour). + +## Configuration + +- `ServerConfig.statsSaveInterval :: Int64`, seconds. +- INI `[STORE_LOG] stats_save_interval`, default 300. Generated ini gets `# stats_save_interval = 300` next to `prometheus_interval` (`Main/Init.hs:107`). +- Persistence is active only when `serverStatsBackupFile` is set (`log_stats = on`), as today. The same path is the memory-mode stats file and the Postgres-mode import source. + +## Architecture + +New module `Simplex.Messaging.Server.StatsStore`: + +```haskell +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath -- import source +#endif +``` + +`Env` selects the backend from `ServerStoreCfg`: `SSCMemory` gives `StatsFile`, `SSCDatabase` gives `StatsDB` with the queue store's `DBStore`. Queue and message store classes are unchanged. The module exposes load and save functions; `Server.hs` does not branch on the backend. + +### PeriodStats + +Each of `day`, `week`, `month` in `PeriodStats` gets a pending `IORef IntSet` of hashes added since the last successful save, and a pending-reset flag. `updatePeriodStats` inserts into the pending set when it inserts into the main set. A reset (rollover) empties the main and pending sets and sets the flag. + +The six persisted sets are identified by `PeriodSet`: + +| `PeriodSet` | value | source | +|---|---|---| +| `PSMsgDay` | 1 | `activeQueues.day` | +| `PSMsgWeek` | 2 | `activeQueues.week` | +| `PSMsgMonth` | 3 | `activeQueues.month` | +| `PSNtfDay` | 4 | `activeQueuesNtf.day` | +| `PSNtfWeek` | 5 | `activeQueuesNtf.week` | +| `PSNtfMonth` | 6 | `activeQueuesNtf.month` | + +## Data flow + +### Startup (replaces `restoreServerStats`) + +Postgres mode: +1. If the `server_stats` row exists, load it and load `server_stats_queues` into the six sets. A load error logs and exits. +2. Else if the file exists, parse it (parse error logs and exits), write the row and all set hashes in one transaction, rename the file to `.bak`. +3. Else start with empty stats. + +A file present together with an existing row is ignored and left in place, with a warning in the log. + +Memory mode: if the file exists, load it without renaming; else start with empty stats. + +In all cases, after loading: +- `qCount` is set from `getEntityCounts`, `msgCount` from the message restore stats, `ntfCount` from the notification restore stats. +- `msgExpired` and `msgNtfExpired` add the counts expired during startup, as `restoreServerStats` does today. + +### Save + +`saveStatsThread` runs every `statsSaveInterval` seconds. Shutdown (`saveServer`) and control port `save` run the same save. Every save and the rollover hold `savingLock`. The save function does not take the lock itself: `stopServer` and control `save` already hold it around `saveServer`, and the rollover calls save twice inside one lock. + +Postgres mode, one transaction: +1. For each set with the pending-reset flag: `DELETE FROM server_stats_queues WHERE period_set = ?`. +2. For each set: `INSERT INTO server_stats_queues (period_set, queue_hash) SELECT ?, unnest(?::BIGINT[]) ON CONFLICT DO NOTHING` with the swapped-out pending hashes. +3. `INSERT ... ON CONFLICT (server_stats_id) DO UPDATE` of all counter columns and `saved_at`. + +On commit the pending-reset flags are cleared. On failure the swapped-out pending hashes are merged back into the pending sets, flags stay set, the error is logged, and the next save retries. + +Memory mode: write `strEncode` of `ServerStatsData` to `.tmp`, then rename over ``. On failure, log, remove the temp file, keep the old file. + +### Daily rollover (`logServerStats`) + +Under `savingLock`: +1. Save, flushing pending hashes of the ending period. +2. Swap counters and write the daily line as today; reset the day sets, the week sets on Monday, the month sets on the 1st, setting their pending-reset flags. +3. Save, deleting the reset sets' rows and storing the zeroed counters. + +A crash between steps 2 and 3 restores pre-rollover counters, and the next daily line counts them twice; the window is one save. + +## Schema + +Migration `20261023_server_stats` in `QueueStore/Postgres/Migrations.hs`; down migration drops both tables; `server_schema.sql` regenerated. + +```sql +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); +``` + +Times are epoch seconds, as in existing tables. `qCount`, `msgCount`, `ntfCount` are not stored; they are recomputed at startup. + +Expected size at month end on current servers (1.5M monthly and 1.3M notification monthly queues mid-month, Oct 14): 4–6M hash rows, 300–400MB with the primary key index. Each save inserts only new hashes. + +Manual correction, with the server stopped: + +```sql +UPDATE server_stats SET rcv_services_assoc_new = rcv_services_assoc_new + 835795; +``` + +## Error handling + +| Failure | Behaviour | +|---|---| +| DB load at startup | Log, exit. Starting with zeros would overwrite the row on the first save. | +| File parse at startup or import | Log, exit (as today). | +| Periodic DB save | Log, merge pending hashes back, keep reset flags, retry next interval. | +| Memory file write | Log, remove temp file, keep old file. | +| Shutdown save | Log. | + +## Testing + +In `tests/ServerTests.hs`, next to the existing stats tests (`:1049`, `:1196`): + +1. Memory mode, 1s interval: after activity, the file read while the server runs has matching counters; a restart from a copy of that mid-run file restores them; the file is not renamed. +2. Postgres: while the server runs, the `server_stats` row and `server_stats_queues` counts per set match the activity. +3. Postgres import: file and no row produce the row with file values and a `.bak` file; file and existing row keep the row and leave the file in place. +4. No stats source with existing queues and messages: `qCount`, `msgCount`, `ntfCount` equal store counts. +5. `StatsStore` against Postgres: save/load round trip; pending hashes merged back after a failed save; reset flags delete only the flagged sets; load after rollover returns only new-period hashes. +6. Pure functions: pending-hash merge and pending-reset flag handling. + +Postgres tests run with `-fserver_postgres`, as existing ones do. From 9ffd900ab6c084a22fb0b3d3c128997168e914fd Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:13:00 +0000 Subject: [PATCH 055/159] smp server: add server_stats tables --- .../Server/QueueStore/Postgres/Migrations.hs | 107 +++++++++++++++++ .../QueueStore/Postgres/server_schema.sql | 110 ++++++++++++++++++ 2 files changed, 217 insertions(+) diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs index 9b3d3bdd2..7c3a4640b 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs @@ -24,6 +24,7 @@ serverSchemaMigrations = ("20260916_prometheus_indexes", m20260916_prometheus_indexes, Just down_m20260916_prometheus_indexes), ("20260917_msg_queues_hot", m20260917_msg_queues_hot, Just down_m20260917_msg_queues_hot), ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), + ("20261023_server_stats", m20261023_server_stats, Just down_m20261023_server_stats), ("20261108_rcv_service_queues", m20261108_rcv_service_queues, Just down_m20261108_rcv_service_queues) ] @@ -1248,4 +1249,110 @@ down_m20261108_rcv_service_queues :: Text down_m20261108_rcv_service_queues = [r| DROP INDEX idx_msg_queues_rcv_service_active; +m20261023_server_stats :: Text +m20261023_server_stats = + [r| +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); + |] + +down_m20261023_server_stats :: Text +down_m20261023_server_stats = + [r| +DROP TABLE server_stats_queues; + +DROP TABLE server_stats; |] diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql index 74ede79f6..fddfe7530 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql @@ -447,6 +447,106 @@ WITH (fillfactor='80', autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze +CREATE TABLE smp_server.server_stats ( + server_stats_id smallint NOT NULL, + saved_at bigint NOT NULL, + from_time bigint NOT NULL, + q_created bigint NOT NULL, + q_secured bigint NOT NULL, + q_deleted_all bigint NOT NULL, + q_deleted_new bigint NOT NULL, + q_deleted_secured bigint NOT NULL, + q_deleted_all_b bigint NOT NULL, + q_blocked bigint NOT NULL, + q_sub bigint NOT NULL, + q_sub_all_b bigint NOT NULL, + q_sub_auth bigint NOT NULL, + q_sub_duplicate bigint NOT NULL, + q_sub_prohibited bigint NOT NULL, + q_sub_end bigint NOT NULL, + q_sub_end_b bigint NOT NULL, + ntf_created bigint NOT NULL, + ntf_new_created bigint NOT NULL, + ntf_deleted bigint NOT NULL, + ntf_deleted_b bigint NOT NULL, + ntf_sub bigint NOT NULL, + ntf_sub_b bigint NOT NULL, + ntf_sub_auth bigint NOT NULL, + ntf_sub_duplicate bigint NOT NULL, + msg_sent bigint NOT NULL, + msg_sent_auth bigint NOT NULL, + msg_sent_quota bigint NOT NULL, + msg_sent_large bigint NOT NULL, + msg_sent_block bigint NOT NULL, + msg_recv bigint NOT NULL, + msg_recv_get bigint NOT NULL, + msg_get bigint NOT NULL, + msg_get_no_msg bigint NOT NULL, + msg_get_auth bigint NOT NULL, + msg_get_duplicate bigint NOT NULL, + msg_get_prohibited bigint NOT NULL, + msg_expired bigint NOT NULL, + msg_sent_ntf bigint NOT NULL, + msg_recv_ntf bigint NOT NULL, + msg_ntfs bigint NOT NULL, + msg_ntfs_b bigint NOT NULL, + msg_ntf_no_sub bigint NOT NULL, + msg_ntf_lost bigint NOT NULL, + msg_ntf_expired bigint NOT NULL, + p_relays_requests bigint NOT NULL, + p_relays_successes bigint NOT NULL, + p_relays_errors_connect bigint NOT NULL, + p_relays_errors_compat bigint NOT NULL, + p_relays_errors_other bigint NOT NULL, + p_relays_own_requests bigint NOT NULL, + p_relays_own_successes bigint NOT NULL, + p_relays_own_errors_connect bigint NOT NULL, + p_relays_own_errors_compat bigint NOT NULL, + p_relays_own_errors_other bigint NOT NULL, + p_msg_fwds_requests bigint NOT NULL, + p_msg_fwds_successes bigint NOT NULL, + p_msg_fwds_errors_connect bigint NOT NULL, + p_msg_fwds_errors_compat bigint NOT NULL, + p_msg_fwds_errors_other bigint NOT NULL, + p_msg_fwds_own_requests bigint NOT NULL, + p_msg_fwds_own_successes bigint NOT NULL, + p_msg_fwds_own_errors_connect bigint NOT NULL, + p_msg_fwds_own_errors_compat bigint NOT NULL, + p_msg_fwds_own_errors_other bigint NOT NULL, + p_msg_fwds_recv bigint NOT NULL, + rcv_services_assoc_new bigint NOT NULL, + rcv_services_assoc_duplicate bigint NOT NULL, + rcv_services_assoc_updated bigint NOT NULL, + rcv_services_assoc_removed bigint NOT NULL, + rcv_services_sub_count bigint NOT NULL, + rcv_services_sub_duplicate bigint NOT NULL, + rcv_services_sub_queues bigint NOT NULL, + rcv_services_sub_end bigint NOT NULL, + ntf_services_assoc_new bigint NOT NULL, + ntf_services_assoc_duplicate bigint NOT NULL, + ntf_services_assoc_updated bigint NOT NULL, + ntf_services_assoc_removed bigint NOT NULL, + ntf_services_sub_count bigint NOT NULL, + ntf_services_sub_duplicate bigint NOT NULL, + ntf_services_sub_queues bigint NOT NULL, + ntf_services_sub_end bigint NOT NULL, + rslv_reqs bigint NOT NULL, + rslv_succ bigint NOT NULL, + rslv_not_found bigint NOT NULL, + rslv_resolver_errs bigint NOT NULL, + rslv_disabled bigint NOT NULL, + CONSTRAINT server_stats_server_stats_id_check CHECK ((server_stats_id = 1)) +); + + + +CREATE TABLE smp_server.server_stats_queues ( + period_set smallint NOT NULL, + queue_hash bigint NOT NULL +); + + + CREATE TABLE smp_server.services ( service_id bytea NOT NULL, service_role text NOT NULL, @@ -475,6 +575,16 @@ ALTER TABLE ONLY smp_server.msg_queues +ALTER TABLE ONLY smp_server.server_stats + ADD CONSTRAINT server_stats_pkey PRIMARY KEY (server_stats_id); + + + +ALTER TABLE ONLY smp_server.server_stats_queues + ADD CONSTRAINT server_stats_queues_pkey PRIMARY KEY (period_set, queue_hash); + + + ALTER TABLE ONLY smp_server.services ADD CONSTRAINT services_pkey PRIMARY KEY (service_id); From 1a266b2e8e2db07ef77b64d98639920006ce33d6 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:17:11 +0000 Subject: [PATCH 056/159] smp server: add stats_save_interval option --- src/Simplex/Messaging/Server/Env/STM.hs | 6 ++++++ src/Simplex/Messaging/Server/Main.hs | 1 + src/Simplex/Messaging/Server/Main/Init.hs | 6 ++++-- tests/SMPClient.hs | 1 + 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 1fc73b0a9..ec523d0d4 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -64,6 +64,7 @@ module Simplex.Messaging.Server.Env.STM defaultMsgQueueQuota, defMsgExpirationDays, defNtfExpirationHours, + defStatsSaveInterval, defaultMessageExpiration, defaultNtfExpiration, defaultInactiveClientExpiration, @@ -176,6 +177,8 @@ data ServerConfig s = ServerConfig serverStatsLogFile :: FilePath, -- | file to save and restore stats serverStatsBackupFile :: Maybe FilePath, + -- | interval to save stats, seconds + statsSaveInterval :: Int64, -- | interval and file to save prometheus metrics prometheusInterval :: Maybe Int, prometheusMetricsFile :: FilePath, @@ -239,6 +242,9 @@ defaultNtfExpiration = checkInterval = 3600 -- seconds, 1 hour } +defStatsSaveInterval :: Int64 +defStatsSaveInterval = 300 + defaultInactiveClientExpiration :: ExpirationConfig defaultInactiveClientExpiration = ExpirationConfig diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 7c68ab836..397ee1247 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -495,6 +495,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = logStatsStartTime = 0, -- seconds from 00:00 UTC serverStatsLogFile = combine logPath "smp-server-stats.daily.log", serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log", + statsSaveInterval = readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini, prometheusInterval = eitherToMaybe (lookupValue "STORE_LOG" "prometheus_interval" ini) >>= readMaybe . T.unpack, prometheusMetricsFile = combine logPath "smp-server-metrics.txt", pendingENDInterval = 15000000, -- 15 seconds diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index 7762ec609..e215de140 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -104,8 +104,10 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> "# Log daily server statistics to CSV file\n" <> ("log_stats = " <> onOff logStats <> "\n\n") <> "# Log interval for real-time Prometheus metrics\n\ - \# prometheus_interval = 60\n\n\ - \[AUTH]\n\ + \# prometheus_interval = 60\n\n" + <> "# Interval to save server statistics, seconds (requires log_stats)\n" + <> ("# stats_save_interval = " <> tshow defStatsSaveInterval <> "\n\n") + <> "[AUTH]\n\ \# Set new_queues option to off to completely prohibit creating new messaging queues.\n\ \# This can be useful when you want to decommission the server, but not all connections are switched yet.\n\ \new_queues = on\n\n\ diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 74576031e..391f99023 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -265,6 +265,7 @@ cfgMS msType = withStoreCfg (testServerStoreConfig msType) $ \serverStoreCfg -> logStatsStartTime = 0, serverStatsLogFile = testPath "smp-server-stats.daily.log", serverStatsBackupFile = Nothing, + statsSaveInterval = defStatsSaveInterval, prometheusInterval = Nothing, prometheusMetricsFile = testPrometheusMetricsFile, pendingENDInterval = 500000, From e2c9f03c69c4d644a19c43469a4a39be11afa51c Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:20:35 +0000 Subject: [PATCH 057/159] smp server: track pending active queue hashes --- simplexmq.cabal | 1 + src/Simplex/Messaging/Server/Env/STM.hs | 4 +- src/Simplex/Messaging/Server/Stats.hs | 84 ++++++++++++++---- tests/CoreTests/ServerStatsTests.hs | 108 ++++++++++++++++++++++++ tests/Test.hs | 2 + 5 files changed, 180 insertions(+), 19 deletions(-) create mode 100644 tests/CoreTests/ServerStatsTests.hs diff --git a/simplexmq.cabal b/simplexmq.cabal index 1fb2272cd..0e54c3a8d 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -591,6 +591,7 @@ test-suite simplexmq-test CoreTests.MsgStoreTests CoreTests.RetryIntervalTests CoreTests.SOCKSSettings + CoreTests.ServerStatsTests CoreTests.StoreLogTests CoreTests.TSessionSubs CoreTests.TransportTests diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index ec523d0d4..066f30013 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -564,7 +564,7 @@ newProhibitedSub = do return Sub {subThread = ProhibitSub, delivered} newEnv :: ServerConfig s -> IO (Env s) -newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes} = do +newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes, serverStatsBackupFile} = do when (msgIdBytes < 24) $ do logError "Error: msgIdBytes must be at least 24" exitFailure @@ -592,7 +592,7 @@ newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smp newReloadableCredential checkHTTPSCredentials creds cred Fingerprint fp <- loadFingerprint smpCredentials let serverIdentity = KeyHash fp - serverStats <- newServerStats =<< getCurrentTime + serverStats <- newServerStats (isJust serverStatsBackupFile && isJust (dbStoreCfg serverStoreCfg)) =<< getCurrentTime sockets <- newTVarIO [] clientSeq <- newTVarIO 0 proxyAgent <- newSMPProxyAgent smpAgentCfg random diff --git a/src/Simplex/Messaging/Server/Stats.hs b/src/Simplex/Messaging/Server/Stats.hs index a3e57d1cd..4b3c8707d 100644 --- a/src/Simplex/Messaging/Server/Stats.hs +++ b/src/Simplex/Messaging/Server/Stats.hs @@ -21,6 +21,12 @@ module Simplex.Messaging.Server.Stats getServerStatsData, setServerStats, newPeriodStats, + newPendingPeriodStats, + PendingPeriods (..), + PendingHashes (..), + takePendingHashes, + restorePendingHashes, + mergePendingHashes, newPeriodStatsData, getPeriodStatsData, setPeriodStats, @@ -214,8 +220,8 @@ data ServerStatsData = ServerStatsData } deriving (Show) -newServerStats :: UTCTime -> IO ServerStats -newServerStats ts = do +newServerStats :: Bool -> UTCTime -> IO ServerStats +newServerStats trackPending ts = do fromTime <- newIORef ts qCreated <- newIORef 0 qSecured <- newIORef 0 @@ -253,10 +259,10 @@ newServerStats ts = do msgGetDuplicate <- newIORef 0 msgGetProhibited <- newIORef 0 msgExpired <- newIORef 0 - activeQueues <- newPeriodStats + activeQueues <- newActiveQueues msgSentNtf <- newIORef 0 msgRecvNtf <- newIORef 0 - activeQueuesNtf <- newPeriodStats + activeQueuesNtf <- newActiveQueues msgNtfs <- newIORef 0 msgNtfsB <- newIORef 0 msgNtfNoSub <- newIORef 0 @@ -353,6 +359,8 @@ newServerStats ts = do ntfCount, rslvStats } + where + newActiveQueues = if trackPending then newPendingPeriodStats else newPeriodStats getServerStatsData :: ServerStats -> IO ServerStatsData getServerStatsData s = do @@ -790,15 +798,51 @@ instance StrEncoding ServerStatsData where data PeriodStats = PeriodStats { day :: IORef IntSet, week :: IORef IntSet, - month :: IORef IntSet + month :: IORef IntSet, + pendingPeriods :: Maybe PendingPeriods + } + +-- hashes added and sets reset since the last successful save +data PendingPeriods = PendingPeriods + { pendingDay :: IORef PendingHashes, + pendingWeek :: IORef PendingHashes, + pendingMonth :: IORef PendingHashes } +data PendingHashes = PendingHashes + { pendingReset :: Bool, + pendingAdded :: IntSet + } + deriving (Eq, Show) + newPeriodStats :: IO PeriodStats -newPeriodStats = do +newPeriodStats = newPeriodStats_ Nothing + +newPendingPeriodStats :: IO PeriodStats +newPendingPeriodStats = do + pendingDay <- newIORef noPendingHashes + pendingWeek <- newIORef noPendingHashes + pendingMonth <- newIORef noPendingHashes + newPeriodStats_ $ Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} + +newPeriodStats_ :: Maybe PendingPeriods -> IO PeriodStats +newPeriodStats_ pendingPeriods = do day <- newIORef IS.empty week <- newIORef IS.empty month <- newIORef IS.empty - pure PeriodStats {day, week, month} + pure PeriodStats {day, week, month, pendingPeriods} + +noPendingHashes :: PendingHashes +noPendingHashes = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +takePendingHashes :: IORef PendingHashes -> IO PendingHashes +takePendingHashes ref = atomicModifyIORef' ref (noPendingHashes,) + +restorePendingHashes :: IORef PendingHashes -> PendingHashes -> IO () +restorePendingHashes ref taken = atomicModifyIORef'_ ref $ mergePendingHashes taken + +mergePendingHashes :: PendingHashes -> PendingHashes -> PendingHashes +mergePendingHashes (PendingHashes r hs) (PendingHashes r' hs') = PendingHashes (r || r') (IS.union hs hs') data PeriodStatsData = PeriodStatsData { _day :: IntSet, @@ -854,23 +898,29 @@ periodStatCounts ps ts = do let d = utctDay ts (_, wDay) = mondayStartWeek d MonthDay _ mDay = d - dayCount <- periodCount 1 $ day ps - weekCount <- periodCount wDay $ week ps - monthCount <- periodCount mDay $ month ps + pending_ = pendingPeriods ps + dayCount <- periodCount 1 (day ps) (pendingDay <$> pending_) + weekCount <- periodCount wDay (week ps) (pendingWeek <$> pending_) + monthCount <- periodCount mDay (month ps) (pendingMonth <$> pending_) pure PeriodStatCounts {dayCount, weekCount, monthCount} where - periodCount :: Int -> IORef IntSet -> IO Text - periodCount 1 ref = tshow . IS.size <$> atomicSwapIORef ref IS.empty - periodCount _ _ = pure "" + periodCount :: Int -> IORef IntSet -> Maybe (IORef PendingHashes) -> IO Text + periodCount 1 ref pRef_ = do + -- pending is reset before the set, so a hash added concurrently can only be persisted for the new period + mapM_ (`atomicWriteIORef` PendingHashes {pendingReset = True, pendingAdded = IS.empty}) pRef_ + tshow . IS.size <$> atomicSwapIORef ref IS.empty + periodCount _ _ _ = pure "" updatePeriodStats :: PeriodStats -> EntityId -> IO () updatePeriodStats ps (EntityId pId) = do - updatePeriod $ day ps - updatePeriod $ week ps - updatePeriod $ month ps + updatePeriod (day ps) (pendingDay <$> pendingPeriods ps) + updatePeriod (week ps) (pendingWeek <$> pendingPeriods ps) + updatePeriod (month ps) (pendingMonth <$> pendingPeriods ps) where ph = hash pId - updatePeriod ref = unlessM (IS.member ph <$> readIORef ref) $ atomicModifyIORef'_ ref $ IS.insert ph + updatePeriod ref pRef_ = unlessM (IS.member ph <$> readIORef ref) $ do + atomicModifyIORef'_ ref $ IS.insert ph + mapM_ (\pRef -> atomicModifyIORef'_ pRef $ \p -> p {pendingAdded = IS.insert ph $ pendingAdded p}) pRef_ data ProxyStats = ProxyStats { pRequests :: IORef Int, diff --git a/tests/CoreTests/ServerStatsTests.hs b/tests/CoreTests/ServerStatsTests.hs new file mode 100644 index 000000000..b99d98376 --- /dev/null +++ b/tests/CoreTests/ServerStatsTests.hs @@ -0,0 +1,108 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +module CoreTests.ServerStatsTests where + +import Data.Hashable (hash) +import Data.IORef +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.Maybe (isNothing) +import Data.Time.Calendar (fromGregorian) +import Data.Time.Clock (UTCTime (..)) +import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Server.Stats +import Test.Hspec hiding (fit, it) +import Util + +serverStatsTests :: Spec +serverStatsTests = + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + +q1, q2, q3, q4, q5 :: EntityId +q1 = EntityId "queue1" +q2 = EntityId "queue2" +q3 = EntityId "queue3" +q4 = EntityId "queue4" +q5 = EntityId "queue5" + +hashes :: [EntityId] -> IntSet +hashes = IS.fromList . map (hash . unEntityId) + +utcDay :: Integer -> Int -> Int -> UTCTime +utcDay y m d = UTCTime (fromGregorian y m d) 3600 + +-- 2026-06-10 is Wednesday, 2026-06-08 is Monday, 2026-06-01 is Monday and the 1st +wednesday, monday, monday1st :: UTCTime +wednesday = utcDay 2026 6 10 +monday = utcDay 2026 6 8 +monday1st = utcDay 2026 6 1 + +noPending :: PendingHashes +noPending = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +resetPending :: PendingHashes +resetPending = PendingHashes {pendingReset = True, pendingAdded = IS.empty} + +added :: [EntityId] -> PendingHashes +added qs = PendingHashes {pendingReset = False, pendingAdded = hashes qs} + +testNoPending :: IO () +testNoPending = do + ps <- newPeriodStats + isNothing (pendingPeriods ps) `shouldBe` True + updatePeriodStats ps q1 + readIORef (day ps) `shouldReturn` hashes [q1] + ServerStats {activeQueues, activeQueuesNtf} <- newServerStats False wednesday + isNothing (pendingPeriods activeQueues) `shouldBe` True + isNothing (pendingPeriods activeQueuesNtf) `shouldBe` True + +testPendingAdded :: IO () +testPendingAdded = do + ServerStats {activeQueues = ps} <- newServerStats True wednesday + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + mapM_ (updatePeriodStats ps) [q1, q2, q1] + takePendingHashes pendingDay `shouldReturn` added [q1, q2] + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q1 + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q3 + takePendingHashes pendingDay `shouldReturn` added [q3] + takePendingHashes pendingWeek `shouldReturn` added [q1, q2, q3] + takePendingHashes pendingMonth `shouldReturn` added [q1, q2, q3] + readIORef (day ps) `shouldReturn` hashes [q1, q2, q3] + +testPendingReset :: IO () +testPendingReset = do + ps <- newPendingPeriodStats + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + updatePeriodStats ps q1 + PeriodStatCounts {dayCount, weekCount, monthCount} <- periodStatCounts ps wednesday + (dayCount, weekCount, monthCount) `shouldBe` ("1", "", "") + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` added [q1] + takePendingHashes pendingMonth `shouldReturn` added [q1] + updatePeriodStats ps q2 + _ <- periodStatCounts ps monday + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` resetPending + takePendingHashes pendingMonth `shouldReturn` added [q2] + readIORef (month ps) `shouldReturn` hashes [q1, q2] + updatePeriodStats ps q3 + _ <- periodStatCounts ps monday1st + mapM takePendingHashes [pendingDay, pendingWeek, pendingMonth] `shouldReturn` [resetPending, resetPending, resetPending] + mapM readIORef [day ps, week ps, month ps] `shouldReturn` [IS.empty, IS.empty, IS.empty] + updatePeriodStats ps q4 + takePendingHashes pendingMonth `shouldReturn` added [q4] + +testMergePending :: IO () +testMergePending = do + mergePendingHashes (added [q1]) (added [q2]) `shouldBe` added [q1, q2] + mergePendingHashes resetPending (added [q2]) `shouldBe` PendingHashes {pendingReset = True, pendingAdded = hashes [q2]} + ref <- newIORef $ added [q5] + restorePendingHashes ref PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4]} + readIORef ref `shouldReturn` PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4, q5]} diff --git a/tests/Test.hs b/tests/Test.hs index 346c24e82..39e9c7830 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -15,6 +15,7 @@ import CoreTests.LockTests import CoreTests.MsgStoreTests import CoreTests.RetryIntervalTests import CoreTests.SOCKSSettings +import CoreTests.ServerStatsTests import CoreTests.StoreLogTests import CoreTests.TSessionSubs import CoreTests.TransportTests @@ -96,6 +97,7 @@ main = do describe "Ethereum crypto tests" ethCryptoTests describe "Encrypted files tests" cryptoFileTests describe "Message store tests" msgStoreTests + describe "Server stats tests" serverStatsTests describe "SOCKS settings tests" socksSettingsTests describe "Store log tests" storeLogTests describe "XFTP store log tests" fileStoreLogTests From 6b6a3b0bf1b3a2104b47a51ca8fead9b76f8c736 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:29:54 +0000 Subject: [PATCH 058/159] smp server: add stats store --- simplexmq.cabal | 1 + src/Simplex/Messaging/Server/StatsStore.hs | 436 +++++++++++++++++++++ tests/CoreTests/ServerStatsTests.hs | 149 ++++++- 3 files changed, 585 insertions(+), 1 deletion(-) create mode 100644 src/Simplex/Messaging/Server/StatsStore.hs diff --git a/simplexmq.cabal b/simplexmq.cabal index 0e54c3a8d..6ba15d1cb 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -319,6 +319,7 @@ library Simplex.Messaging.Server.QueueStore.STM Simplex.Messaging.Server.QueueStore.Types Simplex.Messaging.Server.Stats + Simplex.Messaging.Server.StatsStore Simplex.Messaging.Server.StoreLog Simplex.Messaging.Server.StoreLog.ReadWrite Simplex.Messaging.Server.StoreLog.Types diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs new file mode 100644 index 000000000..d8bd46cae --- /dev/null +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -0,0 +1,436 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} + +module Simplex.Messaging.Server.StatsStore + ( StatsStore (..), + loadStats, + saveStats, +#if defined(dbServerPostgres) + PeriodSet (..), + getDBStats, +#endif + ) +where + +import qualified Control.Exception as E +import Control.Logger.Simple +import Control.Monad +import qualified Data.ByteString.Char8 as B +import qualified Data.Text as T +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Util (ifM, tshow) +import System.Directory (doesFileExist, removeFile, renameFile) +import UnliftIO.Exception (tryAny) +#if defined(dbServerPostgres) +import Data.Bifunctor (bimap) +import Data.IORef (IORef) +import Data.Int (Int16, Int64) +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.List (find, intersperse) +import qualified Data.List.NonEmpty as L +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import Database.PostgreSQL.Simple (Only (..), Query) +import qualified Database.PostgreSQL.Simple as DB +import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) +import Database.PostgreSQL.Simple.ToField (ToField (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Util (toChunks, whenM) +#endif + +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath +#endif + +loadStats :: StatsStore -> IO (Maybe ServerStatsData) +loadStats = \case + StatsFile f -> ifM (doesFileExist f) (Just <$> readStatsFile f) (pure Nothing) +#if defined(dbServerPostgres) + StatsDB st f -> + getDBStats st >>= \case + Just d -> do + whenM (doesFileExist f) $ logWarn $ "server stats file " <> T.pack f <> " is ignored, stats are restored from the database" + pure $ Just d + Nothing -> ifM (doesFileExist f) (Just <$> importStatsFile st f) (pure Nothing) +#endif + +saveStats :: StatsStore -> ServerStats -> IO () +saveStats = \case + StatsFile f -> saveStatsFile f +#if defined(dbServerPostgres) + StatsDB st _ -> saveDBStats st +#endif + +readStatsFile :: FilePath -> IO ServerStatsData +readStatsFile f = do + logNote $ "restoring server stats from file " <> T.pack f + strDecode <$> B.readFile f >>= \case + Right d -> pure d + Left e -> E.throwIO $ userError $ "error parsing server stats file " <> f <> ": " <> e + +saveStatsFile :: FilePath -> ServerStats -> IO () +saveStatsFile f ss = do + d <- getServerStatsData ss + tryAny (B.writeFile tmp (strEncode d) >> renameFile tmp f) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to file " <> T.pack f <> ": " <> tshow e + void $ tryAny $ removeFile tmp + where + tmp = f <> ".tmp" + +#if defined(dbServerPostgres) +data PeriodSet = PSMsgDay | PSMsgWeek | PSMsgMonth | PSNtfDay | PSNtfWeek | PSNtfMonth + deriving (Bounded, Enum, Eq, Ord, Show) + +-- stored in server_stats_queues.period_set, the values must not change +periodSetId :: PeriodSet -> Int16 +periodSetId = \case + PSMsgDay -> 1 + PSMsgWeek -> 2 + PSMsgMonth -> 3 + PSNtfDay -> 4 + PSNtfWeek -> 5 + PSNtfMonth -> 6 + +instance ToField PeriodSet where + toField = toField . periodSetId + +periodSetFromId :: Int16 -> Maybe PeriodSet +periodSetFromId i = find ((i ==) . periodSetId) [minBound .. maxBound] + +periodSetHashes :: ServerStatsData -> PeriodSet -> IntSet +periodSetHashes ServerStatsData {_activeQueues = q, _activeQueuesNtf = n} = \case + PSMsgDay -> _day q + PSMsgWeek -> _week q + PSMsgMonth -> _month q + PSNtfDay -> _day n + PSNtfWeek -> _week n + PSNtfMonth -> _month n + +periodSetPending :: ServerStats -> PeriodSet -> Maybe (IORef PendingHashes) +periodSetPending ServerStats {activeQueues, activeQueuesNtf} = \case + PSMsgDay -> pendingDay <$> pendingPeriods activeQueues + PSMsgWeek -> pendingWeek <$> pendingPeriods activeQueues + PSMsgMonth -> pendingMonth <$> pendingPeriods activeQueues + PSNtfDay -> pendingDay <$> pendingPeriods activeQueuesNtf + PSNtfWeek -> pendingWeek <$> pendingPeriods activeQueuesNtf + PSNtfMonth -> pendingMonth <$> pendingPeriods activeQueuesNtf + +getDBStats :: DBStore -> IO (Maybe ServerStatsData) +getDBStats st = + withTransaction st $ \db -> + DB.query_ db selectStatsQuery >>= \case + StatsRow d : _ -> Just . withPeriodSets d <$> DB.fold_ db "SELECT period_set, queue_hash FROM server_stats_queues" M.empty addHash + [] -> pure Nothing + where + addHash sets (psId :: Int16, h :: Int64) = case periodSetFromId psId of + Just ps -> pure $! M.alter (Just . maybe (IS.singleton h') (IS.insert h')) ps sets + Nothing -> E.throwIO $ userError $ "unknown period_set " <> show psId + where + h' = fromIntegral h + withPeriodSets d sets = + d + { _activeQueues = periodData PSMsgDay PSMsgWeek PSMsgMonth, + _activeQueuesNtf = periodData PSNtfDay PSNtfWeek PSNtfMonth + } + where + periodData dp wp mp = PeriodStatsData {_day = get dp, _week = get wp, _month = get mp} + get p = M.findWithDefault IS.empty p sets + +importStatsFile :: DBStore -> FilePath -> IO ServerStatsData +importStatsFile st f = do + d <- readStatsFile f + withTransaction st $ \db -> do + void $ DB.execute_ db "DELETE FROM server_stats_queues" + forM_ [minBound .. maxBound] $ \ps -> insertHashes db ps $ periodSetHashes d ps + upsertStats db d + renameFile f $ f <> ".bak" + logNote "server stats imported to the database" + pure d + +saveDBStats :: DBStore -> ServerStats -> IO () +saveDBStats st ss = do + taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> + forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref + d <- getServerStatsData ss + tryAny (withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to the database: " <> tshow e + forM_ taken $ \(_, ref, p) -> restorePendingHashes ref p + where + savePending db (ps, _, PendingHashes {pendingReset, pendingAdded}) = do + when pendingReset $ void $ DB.execute db "DELETE FROM server_stats_queues WHERE period_set = ?" (Only ps) + insertHashes db ps pendingAdded + +insertHashes :: DB.Connection -> PeriodSet -> IntSet -> IO () +insertHashes db ps hs = + forM_ (toChunks hashInsertBatch $ IS.toList hs) $ \hs' -> + void $ + DB.executeMany + db + "INSERT INTO server_stats_queues (period_set, queue_hash) VALUES (?, ?) ON CONFLICT DO NOTHING" + (map (\h -> (ps, fromIntegral h :: Int64)) $ L.toList hs') + +-- rows per INSERT statement, bounds the query size of the one-time file import +hashInsertBatch :: Int +hashInsertBatch = 10000 + +upsertStats :: DB.Connection -> ServerStatsData -> IO () +upsertStats db d = do + savedAt <- systemSeconds <$> getSystemTime + void $ DB.execute db upsertStatsQuery $ savedAt : map (($ d) . snd) statsFields + +selectStatsQuery :: Query +selectStatsQuery = "SELECT " <> commaSep (map fst statsFields) <> " FROM server_stats WHERE server_stats_id = 1" + +upsertStatsQuery :: Query +upsertStatsQuery = + "INSERT INTO server_stats (server_stats_id, saved_at, " + <> commaSep cols + <> ") VALUES (1, ?, " + <> commaSep (map (const "?") cols) + <> ") ON CONFLICT (server_stats_id) DO UPDATE SET " + <> commaSep (map (\c -> c <> " = EXCLUDED." <> c) ("saved_at" : cols)) + where + cols = map fst statsFields + +commaSep :: [Query] -> Query +commaSep = mconcat . intersperse ", " + +-- the order must match the FromRow StatsRow instance +statsFields :: [(Query, ServerStatsData -> Int64)] +statsFields = + ("from_time", round . utcTimeToPOSIXSeconds . _fromTime) + : map + (fmap (fromIntegral .)) + ( [ ("q_created", _qCreated), + ("q_secured", _qSecured), + ("q_deleted_all", _qDeletedAll), + ("q_deleted_new", _qDeletedNew), + ("q_deleted_secured", _qDeletedSecured), + ("q_deleted_all_b", _qDeletedAllB), + ("q_blocked", _qBlocked), + ("q_sub", _qSub), + ("q_sub_all_b", _qSubAllB), + ("q_sub_auth", _qSubAuth), + ("q_sub_duplicate", _qSubDuplicate), + ("q_sub_prohibited", _qSubProhibited), + ("q_sub_end", _qSubEnd), + ("q_sub_end_b", _qSubEndB), + ("ntf_created", _ntfCreated), + ("ntf_new_created", _ntfNewCreated), + ("ntf_deleted", _ntfDeleted), + ("ntf_deleted_b", _ntfDeletedB), + ("ntf_sub", _ntfSub), + ("ntf_sub_b", _ntfSubB), + ("ntf_sub_auth", _ntfSubAuth), + ("ntf_sub_duplicate", _ntfSubDuplicate), + ("msg_sent", _msgSent), + ("msg_sent_auth", _msgSentAuth), + ("msg_sent_quota", _msgSentQuota), + ("msg_sent_large", _msgSentLarge), + ("msg_sent_block", _msgSentBlock), + ("msg_recv", _msgRecv), + ("msg_recv_get", _msgRecvGet), + ("msg_get", _msgGet), + ("msg_get_no_msg", _msgGetNoMsg), + ("msg_get_auth", _msgGetAuth), + ("msg_get_duplicate", _msgGetDuplicate), + ("msg_get_prohibited", _msgGetProhibited), + ("msg_expired", _msgExpired), + ("msg_sent_ntf", _msgSentNtf), + ("msg_recv_ntf", _msgRecvNtf), + ("msg_ntfs", _msgNtfs), + ("msg_ntfs_b", _msgNtfsB), + ("msg_ntf_no_sub", _msgNtfNoSub), + ("msg_ntf_lost", _msgNtfLost), + ("msg_ntf_expired", _msgNtfExpired) + ] + <> proxyFields "p_relays" _pRelays + <> proxyFields "p_relays_own" _pRelaysOwn + <> proxyFields "p_msg_fwds" _pMsgFwds + <> proxyFields "p_msg_fwds_own" _pMsgFwdsOwn + <> [("p_msg_fwds_recv", _pMsgFwdsRecv)] + <> serviceFields "rcv_services" _rcvServices + <> serviceFields "ntf_services" _ntfServices + <> map + (fmap (. _rslvStats)) + [ ("rslv_reqs", _rslvReqs), + ("rslv_succ", _rslvSucc), + ("rslv_not_found", _rslvNotFound), + ("rslv_resolver_errs", _rslvResolverErrs), + ("rslv_disabled", _rslvDisabled) + ] + ) + where + proxyFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("requests", _pRequests), + ("successes", _pSuccesses), + ("errors_connect", _pErrorsConnect), + ("errors_compat", _pErrorsCompat), + ("errors_other", _pErrorsOther) + ] + serviceFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("assoc_new", _srvAssocNew), + ("assoc_duplicate", _srvAssocDuplicate), + ("assoc_updated", _srvAssocUpdated), + ("assoc_removed", _srvAssocRemoved), + ("sub_count", _srvSubCount), + ("sub_duplicate", _srvSubDuplicate), + ("sub_queues", _srvSubQueues), + ("sub_end", _srvSubEnd) + ] + +newtype StatsRow = StatsRow ServerStatsData + +instance FromRow StatsRow where + fromRow = do + _fromTime <- posixSecondsToUTCTime . fromIntegral <$> field @Int64 + _qCreated <- field + _qSecured <- field + _qDeletedAll <- field + _qDeletedNew <- field + _qDeletedSecured <- field + _qDeletedAllB <- field + _qBlocked <- field + _qSub <- field + _qSubAllB <- field + _qSubAuth <- field + _qSubDuplicate <- field + _qSubProhibited <- field + _qSubEnd <- field + _qSubEndB <- field + _ntfCreated <- field + _ntfNewCreated <- field + _ntfDeleted <- field + _ntfDeletedB <- field + _ntfSub <- field + _ntfSubB <- field + _ntfSubAuth <- field + _ntfSubDuplicate <- field + _msgSent <- field + _msgSentAuth <- field + _msgSentQuota <- field + _msgSentLarge <- field + _msgSentBlock <- field + _msgRecv <- field + _msgRecvGet <- field + _msgGet <- field + _msgGetNoMsg <- field + _msgGetAuth <- field + _msgGetDuplicate <- field + _msgGetProhibited <- field + _msgExpired <- field + _msgSentNtf <- field + _msgRecvNtf <- field + _msgNtfs <- field + _msgNtfsB <- field + _msgNtfNoSub <- field + _msgNtfLost <- field + _msgNtfExpired <- field + _pRelays <- proxyStatsP + _pRelaysOwn <- proxyStatsP + _pMsgFwds <- proxyStatsP + _pMsgFwdsOwn <- proxyStatsP + _pMsgFwdsRecv <- field + _rcvServices <- serviceStatsP + _ntfServices <- serviceStatsP + _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field + pure $ + StatsRow + ServerStatsData + { _fromTime, + _qCreated, + _qSecured, + _qDeletedAll, + _qDeletedAllB, + _qDeletedNew, + _qDeletedSecured, + _qBlocked, + _qSub, + _qSubAllB, + _qSubAuth, + _qSubDuplicate, + _qSubProhibited, + _qSubEnd, + _qSubEndB, + _ntfCreated, + _ntfNewCreated, + _ntfDeleted, + _ntfDeletedB, + _ntfSub, + _ntfSubB, + _ntfSubAuth, + _ntfSubDuplicate, + _msgSent, + _msgSentAuth, + _msgSentQuota, + _msgSentLarge, + _msgSentBlock, + _msgRecv, + _msgRecvAckTimes = emptyTimeBuckets, + _msgRecvGet, + _msgGet, + _msgGetNoMsg, + _msgGetAuth, + _msgGetDuplicate, + _msgGetProhibited, + _msgExpired, + _activeQueues = newPeriodStatsData, + _msgSentNtf, + _msgRecvNtf, + _activeQueuesNtf = newPeriodStatsData, + _msgNtfs, + _msgNtfsB, + _msgNtfNoSub, + _msgNtfLost, + _msgNtfExpired, + _pRelays, + _pRelaysOwn, + _pMsgFwds, + _pMsgFwdsOwn, + _pMsgFwdsRecv, + _ntfServices, + _rcvServices, + _rcvServicesSubMsg = 0, + _rcvServicesSubDuplicate = 0, + _authDelayExceeded = 0, + _cmdSlotWaits = 0, + _cmdSlotWaitMs = 0, + _cmdSlotWaitMaxMs = 0, + _cmdSlotWaitTimeouts = 0, + _qCount = 0, + _msgCount = 0, + _ntfCount = 0, + _rslvStats + } + where + proxyStatsP = ProxyStatsData <$> field <*> field <*> field <*> field <*> field + serviceStatsP = do + _srvAssocNew <- field + _srvAssocDuplicate <- field + _srvAssocUpdated <- field + _srvAssocRemoved <- field + _srvSubCount <- field + _srvSubDuplicate <- field + _srvSubQueues <- field + _srvSubEnd <- field + pure newServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} +#endif diff --git a/tests/CoreTests/ServerStatsTests.hs b/tests/CoreTests/ServerStatsTests.hs index b99d98376..0d9a2ad01 100644 --- a/tests/CoreTests/ServerStatsTests.hs +++ b/tests/CoreTests/ServerStatsTests.hs @@ -1,8 +1,10 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module CoreTests.ServerStatsTests where +import qualified Data.ByteString.Char8 as B import Data.Hashable (hash) import Data.IORef import Data.IntSet (IntSet) @@ -10,18 +12,45 @@ import qualified Data.IntSet as IS import Data.Maybe (isNothing) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime (..)) +import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (EntityId (..)) import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore +import System.Directory (doesFileExist) import Test.Hspec hiding (fit, it) import Util +#if defined(dbServerPostgres) +import Control.Exception (bracket) +import Control.Monad (void) +import CoreTests.MsgStoreTests (testPostgresStoreConfig) +import qualified Database.PostgreSQL.Simple as DB +import Data.String (fromString) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) +import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) +import Simplex.Messaging.Server.QueueStore.Postgres (PostgresQueueStore (..)) +#endif serverStatsTests :: Spec -serverStatsTests = +serverStatsTests = do describe "pending period stats" $ do it "should not track pending hashes when disabled" testNoPending it "should track hashes added since the last take" testPendingAdded it "should reset pending hashes with period sets" testPendingReset it "should merge restored pending hashes" testMergePending + describe "stats file" $ do + it "should save and load stats" testFileSaveLoad + it "should return no stats without file" testFileMissing + it "should log and continue when file cannot be written" testFileSaveError + it "should fail on invalid file" testFileParseError +#if defined(dbServerPostgres) + describe "stats database" $ do + it "should save and load stats with period sets" testDBSaveLoad + it "should save added hashes and delete reset sets" testDBResetAndAdded + it "should keep pending hashes when save fails" testDBSaveFailure + it "should import stats file when database has no stats" testDBImportFile + it "should ignore stats file when database has stats" testDBIgnoreFile +#endif q1, q2, q3, q4, q5 :: EntityId q1 = EntityId "queue1" @@ -106,3 +135,121 @@ testMergePending = do ref <- newIORef $ added [q5] restorePendingHashes ref PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4]} readIORef ref `shouldReturn` PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4, q5]} + +statsFile :: HasTestEnv => FilePath +statsFile = testPath "smp-server-stats.log" + +-- every zero counter line of the file encoding gets a distinct value, so a column order mistake changes the result +distinctCounters :: ServerStatsData -> ServerStatsData +distinctCounters d = either error id $ strDecode $ B.unlines $ zipWith setValue [1 :: Int ..] $ B.lines $ strEncode d + where + setValue i l = case B.breakSubstring "=" l of + (k, "=0") -> k <> "=" <> B.pack (show i) + _ -> l + +newDistinctStats :: Bool -> IO ServerStats +newDistinctStats trackPending = do + ss <- newServerStats trackPending wednesday + setServerStats ss . distinctCounters =<< getServerStatsData ss + pure ss + +testFileSaveLoad :: HasTestEnv => IO () +testFileSaveLoad = do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + updatePeriodStats (activeQueuesNtf ss) q2 + saveStats (StatsFile statsFile) ss + doesFileExist (statsFile <> ".tmp") `shouldReturn` False + expected <- getServerStatsData ss + Just d <- loadStats (StatsFile statsFile) + strEncode d `shouldBe` strEncode expected + doesFileExist statsFile `shouldReturn` True + +testFileMissing :: HasTestEnv => IO () +testFileMissing = (isNothing <$> loadStats (StatsFile statsFile)) `shouldReturn` True + +testFileSaveError :: HasTestEnv => IO () +testFileSaveError = do + let f = testPath "missing/smp-server-stats.log" + saveStats (StatsFile f) =<< newServerStats False wednesday + doesFileExist f `shouldReturn` False + +testFileParseError :: HasTestEnv => IO () +testFileParseError = do + B.writeFile statsFile "invalid" + loadStats (StatsFile statsFile) `shouldThrow` anyIOException + +#if defined(dbServerPostgres) +withStatsDB :: HasTestEnv => (DBStore -> IO a) -> IO a +withStatsDB action = bracket (newMsgStore testPostgresStoreConfig :: IO PostgresMsgStore) closeMsgStore $ action . dbStore . queueStore + +testDBSaveLoad :: HasTestEnv => IO () +testDBSaveLoad = withStatsDB $ \st -> do + ss <- newDistinctStats True + mapM_ (updatePeriodStats $ activeQueues ss) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + expected <- getServerStatsData ss + Just d <- getDBStats st + strEncode d `shouldBe` strEncode expected {_qCount = 0} + _day (_activeQueues d) `shouldBe` hashes [q1, q2] + _month (_activeQueuesNtf d) `shouldBe` hashes [q3] + +testDBResetAndAdded :: HasTestEnv => IO () +testDBResetAndAdded = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + mapM_ (updatePeriodStats msgQueues) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + updatePeriodStats msgQueues q4 + _ <- periodStatCounts msgQueues wednesday + updatePeriodStats msgQueues q5 + saveStats (StatsDB st statsFile) ss + Just ServerStatsData {_activeQueues, _activeQueuesNtf} <- getDBStats st + _day _activeQueues `shouldBe` hashes [q5] + _week _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _month _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _day _activeQueuesNtf `shouldBe` hashes [q3] + +testDBSaveFailure :: HasTestEnv => IO () +testDBSaveFailure = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + updatePeriodStats (activeQueues ss) q2 + renameTable st "server_stats_queues" "server_stats_queues_moved" + saveStats (StatsDB st statsFile) ss + renameTable st "server_stats_queues_moved" "server_stats_queues" + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + saveStats (StatsDB st statsFile) ss + Just d' <- getDBStats st + _day (_activeQueues d') `shouldBe` hashes [q1, q2] + where + renameTable st from to = withTransaction st $ \db -> void $ DB.execute_ db $ fromString $ "ALTER TABLE " <> from <> " RENAME TO " <> to + +testDBImportFile :: HasTestEnv => IO () +testDBImportFile = withStatsDB $ \st -> do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + d <- getServerStatsData ss + B.writeFile statsFile $ strEncode d + Just imported <- loadStats (StatsDB st statsFile) + strEncode imported `shouldBe` strEncode d + doesFileExist statsFile `shouldReturn` False + doesFileExist (statsFile <> ".bak") `shouldReturn` True + Just saved <- getDBStats st + strEncode saved `shouldBe` strEncode d {_qCount = 0} + +testDBIgnoreFile :: HasTestEnv => IO () +testDBIgnoreFile = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + saved <- getServerStatsData ss + B.writeFile statsFile . strEncode =<< getServerStatsData =<< newDistinctStats False + Just loaded <- loadStats (StatsDB st statsFile) + strEncode loaded `shouldBe` strEncode saved {_qCount = 0} + doesFileExist statsFile `shouldReturn` True +#endif From 38dbf23f372b4c3b8897cbac02b187193653720f Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 10:43:14 +0000 Subject: [PATCH 059/159] smp server: save stats periodically --- src/Simplex/Messaging/Server.hs | 89 +++++++++++++++++++++------------ tests/ServerTests.hs | 82 ++++++++++++++++++++++++++---- 2 files changed, 129 insertions(+), 42 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 7b8a635d2..828722ccb 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -116,6 +116,7 @@ import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.QueueStore.STM (withLoadedQueues) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore import Simplex.Messaging.Server.StoreLog (foldLogLines) import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) @@ -144,6 +145,7 @@ import GHC.Conc.Sync (threadLabel) #if defined(dbServerPostgres) import Simplex.Messaging.Server.MsgStore.Postgres (getDbMessageStats) +import qualified Simplex.Messaging.Server.QueueStore.Postgres as PQ #endif -- | Runs an SMP server using passed configuration. @@ -193,6 +195,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt : map runServer transports <> expireMessagesThread_ cfg <> serverStatsThread_ cfg + <> saveStatsThread_ cfg <> prometheusMetricsThread_ cfg <> controlPortThread_ cfg ) @@ -236,10 +239,11 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt saveServer :: Bool -> M s () saveServer drainMsgs = do + -- the database stats store is closed together with the message store + saveServerStats ms <- asks msgStore_ liftIO $ saveServerMessages drainMsgs ms >> closeMsgStore (fromMsgStore ms) saveServerNtfs - saveServerStats closeServer :: M s () closeServer = do @@ -499,6 +503,18 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt [logServerStats logStatsStartTime interval serverStatsLogFile] serverStatsThread_ _ = [] + saveStatsThread_ :: ServerConfig s -> [M s ()] + saveStatsThread_ ServerConfig {serverStatsBackupFile = Just _, statsSaveInterval} = [saveStatsThread statsSaveInterval] + saveStatsThread_ _ = [] + + saveStatsThread :: Int64 -> M s () + saveStatsThread interval = do + labelMyThread "saveStatsThread" + lock <- asks $ savingLock . server + forever $ do + liftIO $ threadDelay' $ 1000000 * interval + withLock' lock "saveStats" saveServerStats + logServerStats :: Int64 -> Int64 -> FilePath -> M s () logServerStats startAt logInterval statsFilePath = do labelMyThread "logServerStats" @@ -508,9 +524,14 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, rcvServices, ntfServices, rslvStats} <- asks serverStats st <- asks msgStore + EntityCounts {queueCount, notifierCount, rcvServiceCount, ntfServiceCount, rcvServiceQueuesCount, ntfServiceQueuesCount} <- + liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + lock <- asks $ savingLock . server + u <- askUnliftIO let interval = 1000000 * logInterval forever $ do - handleAny (\e -> logError $ "Server stats log error: " <> tshow e) $ withFile statsFilePath AppendMode $ \h -> liftIO $ do + handleAny (\e -> logError $ "Server stats log error: " <> tshow e) $ withFile statsFilePath AppendMode $ \h -> withLock' lock "logStats" $ liftIO $ do + unliftIO u saveServerStats hSetBuffering h LineBuffering EntityCounts {queueCount, notifierCount, rcvServiceCount, ntfServiceCount, rcvServiceQueuesCount, ntfServiceQueuesCount} <- getEntityCounts @(StoreQueue s) $ queueStore st @@ -644,6 +665,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt <> showServiceStats ntfServices' <> showNameResolverStats rslvStats' ) + unliftIO u saveServerStats liftIO $ threadDelay' interval where showProxyStats ProxyStatsData {_pRequests, _pSuccesses, _pErrorsConnect, _pErrorsCompat, _pErrorsOther} = @@ -2551,38 +2573,39 @@ restoreServerNtfs = ntfErr :: Show e => String -> e -> String ntfErr op e = op <> " error (" <> show e <> "): " <> B.unpack (B.take 100 s) -saveServerStats :: M s () -saveServerStats = - asks (serverStatsBackupFile . config) - >>= mapM_ (\f -> asks serverStats >>= liftIO . getServerStatsData >>= liftIO . saveStats f) +serverStatsStore :: M s (Maybe StatsStore) +serverStatsStore = do + ms <- asks msgStore_ + fmap (statsStore ms) <$> asks (serverStatsBackupFile . config) where - saveStats f stats = do - logNote $ "saving server stats to file " <> T.pack f - B.writeFile f $ strEncode stats - logNote "server stats saved" + statsStore :: MsgStore s -> FilePath -> StatsStore + statsStore = \case + StoreMemory _ -> StatsFile +#if defined(dbServerPostgres) + StoreDatabase ms -> StatsDB (PQ.dbStore $ queueStore ms) +#endif + +saveServerStats :: M s () +saveServerStats = do + ss <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . (`saveStats` ss)) restoreServerStats :: forall s. MsgStoreClass s => Maybe MessageStats -> MessageStats -> M s () -restoreServerStats msgStats_ ntfStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStats +restoreServerStats msgStats_ ntfStats = do + s <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . tryAny . loadStats >=> restore s) + st <- asks msgStore + EntityCounts {queueCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + liftIO $ do + writeIORef (qCount s) queueCount + writeIORef (msgCount s) $ maybe 0 storedMsgsCount msgStats_ + writeIORef (ntfCount s) $ storedMsgsCount ntfStats + atomicModifyIORef'_ (msgExpired s) (+ maybe 0 expiredMsgsCount msgStats_) + atomicModifyIORef'_ (msgNtfExpired s) (+ expiredMsgsCount ntfStats) where - restoreStats f = whenM (doesFileExist f) $ do - logNote $ "restoring server stats from file " <> T.pack f - liftIO (strDecode <$> B.readFile f) >>= \case - Right d@ServerStatsData {_qCount = statsQCount, _msgCount = statsMsgCount, _ntfCount = statsNtfCount} -> do - s <- asks serverStats - st <- asks msgStore - EntityCounts {queueCount = _qCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st - let _msgCount = maybe statsMsgCount storedMsgsCount msgStats_ - _ntfCount = storedMsgsCount ntfStats - _msgExpired' = _msgExpired d + maybe 0 expiredMsgsCount msgStats_ - _msgNtfExpired' = _msgNtfExpired d + expiredMsgsCount ntfStats - liftIO $ setServerStats s d {_qCount, _msgCount, _ntfCount, _msgExpired = _msgExpired', _msgNtfExpired = _msgNtfExpired'} - renameFile f $ f <> ".bak" - logNote "server stats restored" - compareCounts "Queue" statsQCount _qCount - compareCounts "Message" statsMsgCount _msgCount - compareCounts "Notification" statsNtfCount _ntfCount - Left e -> do - logNote $ "error restoring server stats: " <> T.pack e - liftIO exitFailure - compareCounts name statsCnt storeCnt = - when (statsCnt /= storeCnt) $ logWarn $ name <> " count differs: stats: " <> tshow statsCnt <> ", store: " <> tshow storeCnt + restore s = \case + Right (Just d) -> liftIO (setServerStats s d) >> logNote "server stats restored" + Right Nothing -> pure () + Left e -> do + logError $ "error restoring server stats: " <> tshow e + liftIO exitFailure diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 550bbce71..8c983c462 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -34,7 +34,7 @@ import Data.Hashable (hash) import qualified Data.IntSet as IS import Data.List.NonEmpty (NonEmpty (..)) import Data.List (isPrefixOf) -import Data.Maybe (catMaybes, isJust) +import Data.Maybe (catMaybes, fromMaybe, isJust) import qualified Data.Set as S import Data.String (IsString (..)) import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime) @@ -72,6 +72,8 @@ import Simplex.Messaging.Server.Env.STM (readWriteQueueStore) import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStoreCfg (..), exportDbMessages) import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..), newMsgStore) import Simplex.Messaging.Server.StoreLog (closeStoreLog) +import CoreTests.ServerStatsTests (withStatsDB) +import Simplex.Messaging.Server.StatsStore (getDBStats) #endif serverTests :: SpecWith (ASrvTransport, AStoreType) @@ -117,6 +119,9 @@ serverTests = do describe "Store log" testWithStoreLog describe "Restore messages" testRestoreMessages describe "Restore messages (old / v2)" testRestoreExpireMessages + describe "Save server stats" $ do + testSaveStatsPeriodically + testStartupStoreCounts describe "Save prometheus metrics" testPrometheusMetrics describe "Delay of AUTH error" testAuthErrorDelay describe "Message notifications" $ do @@ -1641,8 +1646,7 @@ testRestoreMessages = pure () rId <- readTVarIO recipientId logSize testStoreLogFile `shouldReturn` 2 - logSize testServerStatsBackupFile `shouldReturn` 102 - Right stats1 <- strDecode <$> B.readFile testServerStatsBackupFile + stats1 <- readSavedStats msType checkStats stats1 [rId] 5 1 withSmpServerConfigOn at cfg' testPort . runTest t $ \h -> do Just rKey <- readTVarIO recipientKey @@ -1657,8 +1661,7 @@ testRestoreMessages = logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) -- the last message is not removed because it was not ACK'd -- logSize testStoreMsgsFile `shouldReturn` 3 - logSize testServerStatsBackupFile `shouldReturn` 102 - Right stats2 <- strDecode <$> B.readFile testServerStatsBackupFile + stats2 <- readSavedStats msType checkStats stats2 [rId] 5 3 withSmpServerConfigOn at cfg' testPort . runTest t $ \h -> do @@ -1675,11 +1678,10 @@ testRestoreMessages = pure () logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) removeFile testStoreLogFile - logSize testServerStatsBackupFile `shouldReturn` 102 - Right stats3 <- strDecode <$> B.readFile testServerStatsBackupFile + stats3 <- readSavedStats msType checkStats stats3 [rId] 5 5 removeFileIfExists testStoreMsgsFile - removeFile testServerStatsBackupFile + removeFileIfExists testServerStatsBackupFile where runTest :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO ()) -> ThreadId -> Expectation runTest _ test' server = do @@ -1705,6 +1707,68 @@ checkStats s qs sent received = do IS.toList _week `shouldBe` map (hash . unEntityId) qs IS.toList _month `shouldBe` map (hash . unEntityId) qs +readSavedStats :: HasTestEnv => AStoreType -> IO ServerStatsData +readSavedStats = \case + ASType _ SMSMemory -> do + logSize testServerStatsBackupFile `shouldReturn` 101 + either error id . strDecode <$> B.readFile testServerStatsBackupFile +#if defined(dbServerPostgres) + ASType _ SMSPostgres -> withStatsDB $ fmap (fromMaybe $ error "no saved stats") . getDBStats +#else + ASType _ SMSPostgres -> error "compiled without server_postgres flag" +#endif + +testSaveStatsPeriodically :: SpecWith (ASrvTransport, AStoreType) +testSaveStatsPeriodically = + it "should save stats while running and restore them on start" $ \(at@(ATransport t), msType) -> do + removeFileIfExists testServerStatsBackupFile + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, statsSaveInterval = 1} + (rId, stats1, snapshot) <- withSmpServerConfigOn at cfg' testPort $ \_ -> do + rId <- runClient t $ \h -> runClient t $ \rh -> do + (sId, rId, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello") + pure rId + threadDelay 1500000 + stats1 <- readSavedStats msType + snapshot <- case msType of + ASType _ SMSMemory -> Just <$> B.readFile testServerStatsBackupFile + _ -> pure Nothing + pure (rId, stats1, snapshot) + checkStats stats1 [rId] 1 0 + -- a crash leaves the last periodic save, not the save on shutdown + mapM_ (B.writeFile testServerStatsBackupFile) snapshot + stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 1500000 >> readSavedStats msType + checkStats stats2 [rId] 1 0 + removeFileIfExists testServerStatsBackupFile + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + +testStartupStoreCounts :: SpecWith (ASrvTransport, AStoreType) +testStartupStoreCounts = + it "should count stored queues and messages on start without saved stats" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = cfgMS msType + withSmpServerConfigOn at cfg' testPort $ \_ -> runClient t $ \h -> runClient t $ \rh -> do + (sId, _, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello 1") + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () + let cfg2 = updateCfg cfg' $ \cfg_ -> cfg_ {prometheusInterval = Just 1} + metrics <- withSmpServerConfigOn at cfg2 testPort $ \_ -> threadDelay 1500000 >> B.readFile testPrometheusMetricsFile + let expected :: [ByteString] + expected = case msType of + ASType SQSMemory _ -> ["simplex_smp_messages_total 2", "simplex_smp_queues_total1 1"] + -- Postgres queue count is a reltuples estimate + _ -> ["simplex_smp_messages_total 2"] + forM_ expected $ \l -> map (B.unwords . take 2 . B.words) (B.lines metrics) `shouldContain` [l] + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + testRestoreExpireMessages :: SpecWith (ASrvTransport, AStoreType) testRestoreExpireMessages = it "should store messages on exit and restore on start (old / v2)" $ \(at@(ATransport t), msType) -> do @@ -1753,7 +1817,7 @@ testRestoreExpireMessages = msgs'' <- B.readFile testStoreMsgsFile length (B.lines msgs'') `shouldBe` 2 B.lines msgs'' `shouldBe` drop 2 (B.lines msgs) - Right ServerStatsData {_msgExpired} <- strDecode <$> B.readFile testServerStatsBackupFile + ServerStatsData {_msgExpired} <- readSavedStats msType _msgExpired `shouldBe` 2 where exportStoreMessages :: HasTestEnv => AStoreType -> IO () From 05535ce824fd10c766fdbecb9cc5b846761228d8 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 11:02:43 +0000 Subject: [PATCH 060/159] smp server: restore pending hashes on cancel --- src/Simplex/Messaging/Server/StatsStore.hs | 9 +++++--- tests/CoreTests/ServerStatsTests.hs | 24 +++++++++++++++++++++- tests/ServerTests.hs | 18 +++++++++++----- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs index d8bd46cae..0290c5501 100644 --- a/src/Simplex/Messaging/Server/StatsStore.hs +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -45,6 +45,7 @@ import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) import Database.PostgreSQL.Simple.ToField (ToField (..)) import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) import Simplex.Messaging.Util (toChunks, whenM) +import UnliftIO.Exception (isSyncException) #endif data StatsStore @@ -161,15 +162,17 @@ importStatsFile st f = do pure d saveDBStats :: DBStore -> ServerStats -> IO () -saveDBStats st ss = do +saveDBStats st ss = E.mask $ \unmask -> do taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref d <- getServerStatsData ss - tryAny (withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case + E.try @E.SomeException (unmask $ withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case Right () -> pure () Left e -> do - logError $ "error saving server stats to the database: " <> tshow e forM_ taken $ \(_, ref, p) -> restorePendingHashes ref p + if isSyncException e + then logError $ "error saving server stats to the database: " <> tshow e + else E.throwIO e where savePending db (ps, _, PendingHashes {pendingReset, pendingAdded}) = do when pendingReset $ void $ DB.execute db "DELETE FROM server_stats_queues WHERE period_set = ?" (Only ps) diff --git a/tests/CoreTests/ServerStatsTests.hs b/tests/CoreTests/ServerStatsTests.hs index 0d9a2ad01..13072afaf 100644 --- a/tests/CoreTests/ServerStatsTests.hs +++ b/tests/CoreTests/ServerStatsTests.hs @@ -20,7 +20,9 @@ import System.Directory (doesFileExist) import Test.Hspec hiding (fit, it) import Util #if defined(dbServerPostgres) -import Control.Exception (bracket) +import Control.Concurrent (threadDelay, throwTo) +import Control.Concurrent.Async (AsyncCancelled (..), async, asyncThreadId, poll, waitCatch) +import Control.Exception (bracket, fromException) import Control.Monad (void) import CoreTests.MsgStoreTests (testPostgresStoreConfig) import qualified Database.PostgreSQL.Simple as DB @@ -29,6 +31,7 @@ import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) import Simplex.Messaging.Server.QueueStore.Postgres (PostgresQueueStore (..)) +import System.Timeout (timeout) #endif serverStatsTests :: Spec @@ -48,6 +51,7 @@ serverStatsTests = do it "should save and load stats with period sets" testDBSaveLoad it "should save added hashes and delete reset sets" testDBResetAndAdded it "should keep pending hashes when save fails" testDBSaveFailure + it "should keep pending hashes when save is cancelled" testDBSaveCancelled it "should import stats file when database has no stats" testDBImportFile it "should ignore stats file when database has stats" testDBIgnoreFile #endif @@ -229,6 +233,24 @@ testDBSaveFailure = withStatsDB $ \st -> do where renameTable st from to = withTransaction st $ \db -> void $ DB.execute_ db $ fromString $ "ALTER TABLE " <> from <> " RENAME TO " <> to +testDBSaveCancelled :: HasTestEnv => IO () +testDBSaveCancelled = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + Just (Left e) <- timeout 5000000 $ do + a <- withTransaction st $ \db -> do + void $ DB.execute_ db "LOCK TABLE server_stats_queues IN EXCLUSIVE MODE" + a <- async $ saveStats (StatsDB st statsFile) ss + threadDelay 200000 + isNothing <$> poll a `shouldReturn` True + throwTo (asyncThreadId a) AsyncCancelled + pure a + waitCatch a + fromException e `shouldBe` Just AsyncCancelled + saveStats (StatsDB st statsFile) ss + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + testDBImportFile :: HasTestEnv => IO () testDBImportFile = withStatsDB $ \st -> do ss <- newDistinctStats False diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 8c983c462..634b2e472 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -1726,21 +1726,28 @@ testSaveStatsPeriodically = (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, statsSaveInterval = 1} (rId, stats1, snapshot) <- withSmpServerConfigOn at cfg' testPort $ \_ -> do - rId <- runClient t $ \h -> runClient t $ \rh -> do + (sId, rId) <- runClient t $ \h -> runClient t $ \rh -> do (sId, rId, _, _) <- createAndSecureQueue rh sPub Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello") - pure rId - threadDelay 1500000 + pure (sId, rId) + threadDelay 2500000 stats1 <- readSavedStats msType snapshot <- case msType of ASType _ SMSMemory -> Just <$> B.readFile testServerStatsBackupFile _ -> pure Nothing + runClient t $ \h -> do + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () pure (rId, stats1, snapshot) checkStats stats1 [rId] 1 0 -- a crash leaves the last periodic save, not the save on shutdown mapM_ (B.writeFile testServerStatsBackupFile) snapshot - stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 1500000 >> readSavedStats msType - checkStats stats2 [rId] 1 0 + stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 2500000 >> readSavedStats msType + let restoredSent = case msType of + ASType _ SMSMemory -> 1 + _ -> 2 + checkStats stats2 [rId] restoredSent 0 + doesFileExist (testServerStatsBackupFile <> ".bak") `shouldReturn` False removeFileIfExists testServerStatsBackupFile where runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a @@ -1758,6 +1765,7 @@ testStartupStoreCounts = Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") pure () let cfg2 = updateCfg cfg' $ \cfg_ -> cfg_ {prometheusInterval = Just 1} + removeFileIfExists testPrometheusMetricsFile metrics <- withSmpServerConfigOn at cfg2 testPort $ \_ -> threadDelay 1500000 >> B.readFile testPrometheusMetricsFile let expected :: [ByteString] expected = case msType of From d007985f1ee3e05ceeb7c34818ba8a19c223af89 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 11:14:30 +0000 Subject: [PATCH 061/159] smp server: skip stats save on closed store --- src/Simplex/Messaging/Server/StatsStore.hs | 5 +++-- tests/CoreTests/ServerStatsTests.hs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs index 0290c5501..c3bf27f7b 100644 --- a/src/Simplex/Messaging/Server/StatsStore.hs +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -28,6 +28,7 @@ import Simplex.Messaging.Util (ifM, tshow) import System.Directory (doesFileExist, removeFile, renameFile) import UnliftIO.Exception (tryAny) #if defined(dbServerPostgres) +import Control.Concurrent.STM (readTVarIO) import Data.Bifunctor (bimap) import Data.IORef (IORef) import Data.Int (Int16, Int64) @@ -43,7 +44,7 @@ import Database.PostgreSQL.Simple (Only (..), Query) import qualified Database.PostgreSQL.Simple as DB import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) import Database.PostgreSQL.Simple.ToField (ToField (..)) -import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore (..), withTransaction) import Simplex.Messaging.Util (toChunks, whenM) import UnliftIO.Exception (isSyncException) #endif @@ -162,7 +163,7 @@ importStatsFile st f = do pure d saveDBStats :: DBStore -> ServerStats -> IO () -saveDBStats st ss = E.mask $ \unmask -> do +saveDBStats st ss = ifM (readTVarIO $ dbClosed st) (logWarn "server stats are not saved: database store is closed") $ E.mask $ \unmask -> do taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref d <- getServerStatsData ss diff --git a/tests/CoreTests/ServerStatsTests.hs b/tests/CoreTests/ServerStatsTests.hs index 13072afaf..6efaedbee 100644 --- a/tests/CoreTests/ServerStatsTests.hs +++ b/tests/CoreTests/ServerStatsTests.hs @@ -27,6 +27,7 @@ import Control.Monad (void) import CoreTests.MsgStoreTests (testPostgresStoreConfig) import qualified Database.PostgreSQL.Simple as DB import Data.String (fromString) +import Simplex.Messaging.Agent.Store.Postgres (closeDBStore) import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) @@ -52,6 +53,7 @@ serverStatsTests = do it "should save added hashes and delete reset sets" testDBResetAndAdded it "should keep pending hashes when save fails" testDBSaveFailure it "should keep pending hashes when save is cancelled" testDBSaveCancelled + it "should not save when database store is closed" testDBSaveClosed it "should import stats file when database has no stats" testDBImportFile it "should ignore stats file when database has stats" testDBIgnoreFile #endif @@ -251,6 +253,16 @@ testDBSaveCancelled = withStatsDB $ \st -> do Just d <- getDBStats st _day (_activeQueues d) `shouldBe` hashes [q1] +testDBSaveClosed :: HasTestEnv => IO () +testDBSaveClosed = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + updatePeriodStats msgQueues q1 + closeDBStore st + timeout 5000000 (saveStats (StatsDB st statsFile) ss) `shouldReturn` Just () + Just PendingPeriods {pendingDay} <- pure $ pendingPeriods msgQueues + takePendingHashes pendingDay `shouldReturn` added [q1] + testDBImportFile :: HasTestEnv => IO () testDBImportFile = withStatsDB $ \st -> do ss <- newDistinctStats False From 63edf9589b1e06b3fdee086c0f225891eaa8d1ff Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 11:15:58 +0000 Subject: [PATCH 062/159] smp server: validate stats_save_interval --- src/Simplex/Messaging/Server/Main.hs | 5 ++++- tests/CLITests.hs | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 397ee1247..605f490cd 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -440,6 +440,9 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = transports = iniTransports ini sharedHTTP = any (\(_, _, addHTTP) -> addHTTP) transports iniStoreType = either error id $! readStoreType ini + iniStatsSaveInterval = case readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini of + n | n < 1 -> error $ "invalid INI setting stats_save_interval: " <> show n + n -> n iniStoreCfg :: SupportedStore qs ms => SQSType qs -> SMSType ms -> ServerStoreCfg (MsgStoreType qs ms) iniStoreCfg SQSMemory SMSMemory = SSCMemory $ enableStoreLog' ini $> StorePaths {storeLogFile = storeLogFilePath, storeMsgsFile = restoreMessagesFile storeMsgsFilePath} #if defined(dbServerPostgres) @@ -495,7 +498,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = logStatsStartTime = 0, -- seconds from 00:00 UTC serverStatsLogFile = combine logPath "smp-server-stats.daily.log", serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log", - statsSaveInterval = readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini, + statsSaveInterval = iniStatsSaveInterval, prometheusInterval = eitherToMaybe (lookupValue "STORE_LOG" "prometheus_interval" ini) >>= readMaybe . T.unpack, prometheusMetricsFile = combine logPath "smp-server-metrics.txt", pendingENDInterval = 15000000, -- 15 seconds diff --git a/tests/CLITests.hs b/tests/CLITests.hs index 8cd711bfe..fa76b947b 100644 --- a/tests/CLITests.hs +++ b/tests/CLITests.hs @@ -93,6 +93,7 @@ cliTests = do it "with store log, no password" $ smpServerTest True False it "static files" smpServerTestStatic it "cloud scripts disable embedded web without certificates" smpCloudScriptsDisableWeb + it "should not start with invalid stats_save_interval" smpServerInvalidStatsSaveInterval #if defined(dbServerPostgres) around_ (postgressBracket ntfTestServerDBConnectInfo) $ before_ (createNtfSchema ntfTestServerDBConnectInfo ntfTestServerDBOpts) $ describe "Ntf server CLI" $ do @@ -285,6 +286,16 @@ testStartInvalidCredential = do (prExitCode, show <$> prException) `shouldBe` (ExitFailure 1, Nothing) prStdout `shouldBe` "invalid credential: no private key\n" +smpServerInvalidStatsSaveInterval :: HasTestEnv => IO () +smpServerInvalidStatsSaveInterval = do + let iniFile = cfgPath <> "/smp-server.ini" + capture_ (withArgs ["init", "-y", "--no-password"] $ smpServerCLI cfgPath logPath) + >>= (`shouldSatisfy` (("Server initialized, please provide additional server information in " <> iniFile) `isPrefixOf`)) + Right ini <- readIniFile iniFile + writeIniFile iniFile ini {iniSections = HM.adjust (("stats_save_interval", "0") :) "STORE_LOG" (iniSections ini)} + capture_ (withArgs ["start"] $ 5000000 `timeout` smpServerCLI cfgPath logPath) + `shouldThrow` errorCall "invalid INI setting stats_save_interval: 0" + smpCloudScriptsDisableWeb :: HasCallStack => IO () smpCloudScriptsDisableWeb = do linode <- readFile "scripts/smp-server-linode.sh" From 981701336dca83821256da1ef754f2b33f1c78a0 Mon Sep 17 00:00:00 2001 From: sh Date: Fri, 23 Oct 2026 11:16:36 +0000 Subject: [PATCH 063/159] smp server: tidy stats store exports --- src/Simplex/Messaging/Server/StatsStore.hs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs index c3bf27f7b..80321d358 100644 --- a/src/Simplex/Messaging/Server/StatsStore.hs +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -11,7 +11,6 @@ module Simplex.Messaging.Server.StatsStore loadStats, saveStats, #if defined(dbServerPostgres) - PeriodSet (..), getDBStats, #endif ) @@ -188,7 +187,7 @@ insertHashes db ps hs = "INSERT INTO server_stats_queues (period_set, queue_hash) VALUES (?, ?) ON CONFLICT DO NOTHING" (map (\h -> (ps, fromIntegral h :: Int64)) $ L.toList hs') --- rows per INSERT statement, bounds the query size of the one-time file import +-- rows per INSERT statement, bounds the query size hashInsertBatch :: Int hashInsertBatch = 10000 From 521a44163a1edb8844b9d9d89cbc0970554f3239 Mon Sep 17 00:00:00 2001 From: shum Date: Fri, 2 Oct 2026 11:15:20 +0000 Subject: [PATCH 064/159] agent: reject low-order DH keys in double ratchet --- src/Simplex/Messaging/Agent.hs | 5 +- src/Simplex/Messaging/Crypto/Ratchet.hs | 80 ++++++++++++++----------- tests/AgentTests/DoubleRatchetTests.hs | 70 +++++++++++++++++++--- 3 files changed, 111 insertions(+), 44 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 00f418ded..ea227c32c 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1585,7 +1585,7 @@ createRatchet_ db g connId maxSupported pqSupport e2eRcvParams@(CR.E2ERatchetPar (_, rcDHRs) <- atomically $ C.generateKeyPair g rcParams <- liftEitherWith (SEAgentError . cryptoError) $ CR.pqX3dhSnd pks e2eRcvParams let rcVs = CR.RatchetVersions {current = v, maxSupported} - rc = CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams + rc <- liftEitherWith (SEAgentError . cryptoError) $ CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams liftIO $ createSndRatchet db connId rc e2eSndParams pure (rc, e2eSndParams) @@ -4443,7 +4443,8 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr | otherwise = do (_, rcDHRs) <- atomically . C.generateKeyPair =<< asks random rcParams <- liftEitherWith cryptoError $ CR.pqX3dhSnd (pk1, pk2, CR.APRKP CR.SRKSProposed <$> pKem) e2eOtherPartyParams - recreateRatchet replyKey_ (Just $ EREADY lastExternalSndId) $ CR.initSndRatchet rcVs k2Rcv rcDHRs rcParams + rcRatchet <- liftEitherWith cryptoError $ CR.initSndRatchet rcVs k2Rcv rcDHRs rcParams + recreateRatchet replyKey_ (Just $ EREADY lastExternalSndId) rcRatchet checkMsgIntegrity :: PrevExternalSndId -> ExternalSndId -> PrevRcvMsgHash -> ByteString -> MsgIntegrity checkMsgIntegrity prevExtSndId extSndId internalPrevMsgHash receivedPrevMsgHash diff --git a/src/Simplex/Messaging/Crypto/Ratchet.hs b/src/Simplex/Messaging/Crypto/Ratchet.hs index d09dd5b17..056d36372 100644 --- a/src/Simplex/Messaging/Crypto/Ratchet.hs +++ b/src/Simplex/Messaging/Crypto/Ratchet.hs @@ -84,13 +84,16 @@ module Simplex.Messaging.Crypto.Ratchet RatchetKEM (..), RatchetKEMAccepted (..), RatchetKey (..), + EncMessageHeader (..), + EncRatchetMessage (..), + paddedHeaderLen, fullHeaderLen, applySMDiff, ) where import Control.Applicative ((<|>)) -import Control.Monad (unless) +import Control.Monad (unless, when) import Control.Monad.Except import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except @@ -470,7 +473,7 @@ pqX3dhSnd :: DhAlgorithm a => AE2EPrivRatchetParams a -> E2ERatchetParams 'RKSPr -- 3. replied 2. received pqX3dhSnd (spk1, spk2, spKem_) (E2ERatchetParams _ rk1 rk2 rKem_) = do (ks_, kem_) <- sndPq - let initParams = pqX3dh (publicKey spk1, rk1) (dh' rk1 spk2) (dh' rk2 spk1) (dh' rk2 spk2) kem_ + initParams <- pqX3dh (publicKey spk1, rk1) (dh' rk1 spk2) (dh' rk2 spk1) (dh' rk2 spk2) kem_ pure (initParams, ks_) where sndPq :: Either CryptoError (Maybe KEMKeyPair, Maybe RatchetKEMAccepted) @@ -486,7 +489,7 @@ pqX3dhRcv :: forall s a. (RatchetKEMStateI s, DhAlgorithm a) => RcvE2EPrivRatche -- 1. sent 4. received in reply pqX3dhRcv (rpk1, rpk2, rpKem_) (E2ERatchetParams _ sk1 sk2 sKem_) = do kem_ <- rcvPq - let initParams = pqX3dh (sk1, publicKey rpk1) (dh' sk2 rpk1) (dh' sk1 rpk2) (dh' sk2 rpk2) (snd <$> kem_) + initParams <- liftEither $ pqX3dh (sk1, publicKey rpk1) (dh' sk2 rpk1) (dh' sk1 rpk2) (dh' sk2 rpk2) (snd <$> kem_) pure (initParams, fst <$> kem_) where rcvPq :: ExceptT CryptoError IO (Maybe (KEMKeyPair, RatchetKEMAccepted)) @@ -498,9 +501,10 @@ pqX3dhRcv (rpk1, rpk2, rpKem_) (E2ERatchetParams _ sk1 sk2 sKem_) = do Nothing -> throwE CERatchetKEMState _ -> pure Nothing -- both parties can send "proposal" in case of ratchet renegotiation -pqX3dh :: DhAlgorithm a => (PublicKey a, PublicKey a) -> DhSecret a -> DhSecret a -> DhSecret a -> Maybe RatchetKEMAccepted -> RatchetInitParams +pqX3dh :: DhAlgorithm a => (PublicKey a, PublicKey a) -> DhSecret a -> DhSecret a -> DhSecret a -> Maybe RatchetKEMAccepted -> Either CryptoError RatchetInitParams pqX3dh (sk1, rk1) dh1 dh2 dh3 kemAccepted = - RatchetInitParams {assocData, rcVerifyCodePQ = Str vcPQ, ratchetKey = RatchetKey sk, sndHK = Key hk, rcvNextHK = Key nhk, kemAccepted} + mapM_ checkDhSecret [dh1, dh2, dh3] + $> RatchetInitParams {assocData, rcVerifyCodePQ = Str vcPQ, ratchetKey = RatchetKey sk, sndHK = Key hk, rcvNextHK = Key nhk, kemAccepted} where assocData = Str $ pubKeyBytes sk1 <> pubKeyBytes rk1 dhs = dhBytes' dh1 <> dhBytes' dh2 <> dhBytes' dh3 <> pq @@ -645,30 +649,31 @@ instance FromField MessageKey where fromField = blobFieldDecoder smpDecode -- // above added for KEM -- @ initSndRatchet :: - forall a. (AlgorithmI a, DhAlgorithm a) => RatchetVersions -> PublicKey a -> PrivateKey a -> (RatchetInitParams, Maybe KEMKeyPair) -> Ratchet a + forall a. (AlgorithmI a, DhAlgorithm a) => RatchetVersions -> PublicKey a -> PrivateKey a -> (RatchetInitParams, Maybe KEMKeyPair) -> Either CryptoError (Ratchet a) initSndRatchet rcVersion rcDHRr rcDHRs (RatchetInitParams {assocData, rcVerifyCodePQ, ratchetKey, sndHK, rcvNextHK, kemAccepted}, rcPQRs_) = do -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(SK, DH(state.DHRs, state.DHRr) || state.PQRss) - let (rcRK, rcCKs, rcNHKs) = rootKdf ratchetKey rcDHRr rcDHRs (rcPQRss <$> kemAccepted) - pqOn = isJust rcPQRs_ - in Ratchet - { rcVersion, - rcAD = assocData, - rcVCPQ = Just rcVerifyCodePQ, - rcDHRs, - rcKEM = (`RatchetKEM` kemAccepted) <$> rcPQRs_, - rcSupportKEM = PQSupport pqOn, - rcEnableKEM = PQEncryption pqOn, - rcSndKEM = PQEncryption $ isJust kemAccepted, - rcRcvKEM = PQEncOff, - rcRK, - rcSnd = Just SndRatchet {rcDHRr, rcCKs, rcHKs = sndHK}, - rcRcv = Nothing, - rcPN = 0, - rcNs = 0, - rcNr = 0, - rcNHKs, - rcNHKr = rcvNextHK - } + (rcRK, rcCKs, rcNHKs) <- rootKdf ratchetKey rcDHRr rcDHRs (rcPQRss <$> kemAccepted) + let pqOn = isJust rcPQRs_ + pure + Ratchet + { rcVersion, + rcAD = assocData, + rcVCPQ = Just rcVerifyCodePQ, + rcDHRs, + rcKEM = (`RatchetKEM` kemAccepted) <$> rcPQRs_, + rcSupportKEM = PQSupport pqOn, + rcEnableKEM = PQEncryption pqOn, + rcSndKEM = PQEncryption $ isJust kemAccepted, + rcRcvKEM = PQEncOff, + rcRK, + rcSnd = Just SndRatchet {rcDHRr, rcCKs, rcHKs = sndHK}, + rcRcv = Nothing, + rcPN = 0, + rcNs = 0, + rcNr = 0, + rcNHKs, + rcNHKr = rcvNextHK + } -- | Receiving ratchet initialization, equivalent to RatchetInitBobPQ2HE in double ratchet spec -- @@ -1039,10 +1044,10 @@ rcDecrypt g rc@Ratchet {rcRcv, rcAD = Str rcAD, rcVersion} rcMKSkipped msg' = do -- state.DHRs = GENERATE_DH() (_, rcDHRs') <- atomically $ generateKeyPair @a g -- state.RK, state.CKr, state.NHKr = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || ss) - let (rcRK', rcCKr', rcNHKr') = rootKdf rcRK msgDHRs rcDHRs kemSS - -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || state.PQRss) - (rcRK'', rcCKs', rcNHKs') = rootKdf rcRK' msgDHRs rcDHRs' kemSS' - sndKEM = isJust kemSS' + (rcRK', rcCKr', rcNHKr') <- liftEither $ rootKdf rcRK msgDHRs rcDHRs kemSS + -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || state.PQRss) + (rcRK'', rcCKs', rcNHKs') <- liftEither $ rootKdf rcRK' msgDHRs rcDHRs' kemSS' + let sndKEM = isJust kemSS' rcvKEM = isJust kemSS rcEnableKEM' = PQEncryption $ sndKEM || rcvKEM || isJust rcKEM' pure @@ -1149,14 +1154,21 @@ rcDecrypt g rc@Ratchet {rcRcv, rcAD = Str rcAD, rcVersion} rcMKSkipped msg' = do -- DECRYPT(mk, cipher-text, CONCAT(AD, enc_header)) tryE $ decryptAEAD mk iv (rcAD <> emHeader) emBody emAuthTag -rootKdf :: (AlgorithmI a, DhAlgorithm a) => RatchetKey -> PublicKey a -> PrivateKey a -> Maybe KEMSharedKey -> (RatchetKey, RatchetKey, Key) +rootKdf :: (AlgorithmI a, DhAlgorithm a) => RatchetKey -> PublicKey a -> PrivateKey a -> Maybe KEMSharedKey -> Either CryptoError (RatchetKey, RatchetKey, Key) rootKdf (RatchetKey rk) k pk kemSecret_ = - let dhOut = dhBytes' (dh' k pk) + let dhSecret = dh' k pk + dhOut = dhBytes' dhSecret ss = case kemSecret_ of Just (KEMSharedKey s) -> dhOut <> BA.convert s Nothing -> dhOut (rk', ck, nhk) = hkdf3 rk ss "SimpleXRootRatchet" - in (RatchetKey rk', RatchetKey ck, Key nhk) + in checkDhSecret dhSecret $> (RatchetKey rk', RatchetKey ck, Key nhk) + +-- RFC 7748 section 6.2: X25519 and X448 produce the all-zero secret for low-order public keys +checkDhSecret :: DhSecret a -> Either CryptoError () +checkDhSecret s = when (BA.constEq dhOut $ B.replicate (B.length dhOut) '\0') $ Left $ CryptoHeaderError "all-zero DH secret" + where + dhOut = dhBytes' s chainKdf :: RatchetKey -> (RatchetKey, Key, IV, IV) chainKdf (RatchetKey ck) = diff --git a/tests/AgentTests/DoubleRatchetTests.hs b/tests/AgentTests/DoubleRatchetTests.hs index 7a7b05f75..005df8aad 100644 --- a/tests/AgentTests/DoubleRatchetTests.hs +++ b/tests/AgentTests/DoubleRatchetTests.hs @@ -10,6 +10,8 @@ {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -Wno-orphans #-} {-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-} +-- DhAlgorithm makes non-DH key constructors unreachable in lowOrderKeys, but GHC reports it as redundant +{-# OPTIONS_GHC -fno-warn-redundant-constraints #-} module AgentTests.DoubleRatchetTests where @@ -17,9 +19,14 @@ import Control.Concurrent.STM import Control.Monad (forM_, when) import Control.Monad.Except import Control.Monad.IO.Class +import Crypto.Cipher.AES (AES256) +import qualified Crypto.Error as CE +import qualified Crypto.PubKey.Curve25519 as X25519 +import qualified Crypto.PubKey.Curve448 as X448 import Crypto.Random (ChaChaDRG) import Data.Aeson (FromJSON, ToJSON, (.=)) import qualified Data.Aeson as J +import qualified Data.ByteArray as BA import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.Map.Strict as M @@ -52,6 +59,8 @@ doubleRatchetTests = do it "should decode v2 Ratchet with default field values" $ testDecodeV2RatchetJSON it "should agree the same ratchet parameters" $ testAlgs testX3dh it "should agree the same ratchet parameters with version 1" $ testAlgs testX3dhV1 + it "should reject low-order DH keys in key agreement" $ testAlgs testX3dhLowOrderKeys + it "should reject low-order DH key in message header" $ testAlgs testRatchetStepLowOrderKey describe "post-quantum hybrid KEM double-ratchet algorithm" $ do describe "hybrid KEM key agreement" $ do it "should propose KEM during agreement, but no shared secret" $ testAlgs testPqX3dhProposeInReply @@ -398,6 +407,51 @@ testX3dhV1 _ = do paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob paramsAlice `shouldBe` paramsBob +testX3dhLowOrderKeys :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () +testX3dhLowOrderKeys _ = do + g <- C.newRandom + let v = currentE2EEncryptVersion + (pksBob, AE2ERatchetParams _ e2eBob@(E2ERatchetParams _ bk1 bk2 _)) <- liftIO $ generateSndE2EParams @a g v Nothing + (pksAlice, e2eAlice@(E2ERatchetParams _ ak1 ak2 _)) <- liftIO $ generateRcvE2EParams @a g v PQSupportOff + Right _ <- pure $ pqX3dhSnd pksBob e2eAlice + Right _ <- runExceptT $ pqX3dhRcv pksAlice e2eBob + let params k1 k2 = E2ERatchetParams v k1 k2 Nothing :: E2ERatchetParams 'RKSProposed a + forM_ (lowOrderKeys ak1) $ \k -> do + pqX3dhSnd pksBob (params k ak2) `shouldBe` Left allZeroDhError + pqX3dhSnd pksBob (params ak1 k) `shouldBe` Left allZeroDhError + runExceptT (pqX3dhRcv pksAlice $ params k bk2) `shouldReturn` Left allZeroDhError + runExceptT (pqX3dhRcv pksAlice $ params bk1 k) `shouldReturn` Left allZeroDhError + +testRatchetStepLowOrderKey :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () +testRatchetStepLowOrderKey _ = do + g <- C.newRandom + (alice, Ratchet {rcSnd = Just SndRatchet {rcHKs}, rcAD = Str ad}, _, _, _) <- initRatchets @a + let decryptWithKey k = do + let hdr = MsgHeader {msgMaxVersion = currentE2EEncryptVersion, msgDHRs = k, msgKEM = Nothing, msgPN = 0, msgNs = 0} + ehIV = C.IV $ B.replicate (C.ivSize @AES256) '\0' + Right (ehAuthTag, ehBody) <- runExceptT $ C.encryptAEAD rcHKs ehIV (paddedHeaderLen PQSupportOff) ad (smpEncode hdr) + let emHeader = smpEncode EncMessageHeader {ehVersion = currentE2EEncryptVersion, ehIV, ehAuthTag, ehBody} + runExceptT $ rcDecrypt g alice M.empty $ smpEncode EncRatchetMessage {emHeader, emAuthTag = ehAuthTag, emBody = "message"} + (validKey, _) <- atomically $ C.generateKeyPair @a g + decryptWithKey validKey >>= \case + Right (Left C.AESDecryptError, _, _) -> pure () + _ -> expectationFailure "header with valid key should be decrypted and ratchet advanced" + forM_ (lowOrderKeys validKey) $ \k -> + decryptWithKey k >>= \case + Left e -> e `shouldBe` allZeroDhError + Right _ -> expectationFailure "ratchet should not advance with low-order key" + +-- RFC 7748 section 6.2: u = 0 and u = 1 are low-order points on both curves and their twists +lowOrderKeys :: DhAlgorithm a => C.PublicKey a -> [C.PublicKey a] +lowOrderKeys = \case + C.PublicKeyX25519 k -> C.PublicKeyX25519 . CE.throwCryptoError . X25519.publicKey <$> lowOrderPoints (BA.length k) + C.PublicKeyX448 k -> C.PublicKeyX448 . CE.throwCryptoError . X448.publicKey <$> lowOrderPoints (BA.length k) + where + lowOrderPoints n = [B.replicate n '\0', B.cons '\1' $ B.replicate (n - 1) '\0'] + +allZeroDhError :: CryptoError +allZeroDhError = C.CryptoHeaderError "all-zero DH secret" + testPqX3dhProposeInReply :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () testPqX3dhProposeInReply _ = do g <- C.newRandom @@ -535,8 +589,8 @@ initRatchets = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOff + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOff pure (alice, bob, encrypt' noSndKEM, decrypt' noRcvKEM, (\#>)) initRatchetsKEMProposed :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -552,8 +606,8 @@ initRatchetsKEMProposed = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsKEMAccepted :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -570,8 +624,8 @@ initRatchetsKEMAccepted = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsKEMProposedAgain :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -587,8 +641,8 @@ initRatchetsKEMProposedAgain = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsV2 :: (AlgorithmI a, DhAlgorithm a) => Encrypt a -> Decrypt a -> IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) From 2f0ff2108eb90ada25f3fbc5070f7574719acb0b Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 13:51:06 +0000 Subject: [PATCH 065/159] smp-server: merge send and sendMsg threads --- src/Simplex/Messaging/Server.hs | 48 +++++++++++++++++---------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 828722ccb..cfed6f457 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -42,6 +42,7 @@ module Simplex.Messaging.Server ) where +import Control.Applicative ((<|>)) import Control.Concurrent.STM (throwSTM) import qualified Control.Exception as E import Control.Logger.Simple @@ -1092,9 +1093,8 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do expCfg <- asks $ inactiveClientExpiration . config - th <- newMVar h -- put TH under a fair lock to interleave messages and command responses labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ $ [liftIO $ send th c, liftIO $ sendMsg th c, client processSubs s ms c, receive h ms c] <> disconnectThread_ c s expCfg + raceAny_ $ [liftIO $ send h c, client s ms c, receive h ms c] <> disconnectThread_ c s expCfg disconnectThread_ :: Client s -> Server s -> Maybe ExpirationConfig -> [M s ()] disconnectThread_ c s (Just expCfg) = [liftIO $ disconnectTransport h (rcvActiveAt c) (sndActiveAt c) expCfg (noSubscriptions c s)] disconnectThread_ _ _ _ = [] @@ -1262,36 +1262,38 @@ forwardedCmdWait = (`netTimeoutInt` NRMBackground) . tcpTimeout . networkConfig microseconds :: SystemTime -> Int64 microseconds (MkSystemTime s ns) = s * 1000000 + fromIntegral (ns `div` 1000) -send :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> IO () -send th c@Client {sndQ, msgQ, clientTHParams = THandleParams {sessionId}} = do +-- Messages are sent one per transmission, interleaved with command responses. +send :: Transport c => THandleSMP c 'TServer -> Client s -> IO () +send h c@Client {sndQ, msgQ, clientTHParams = THandleParams {sessionId}} = do labelMyThread . B.unpack $ "client $" <> encode sessionId <> " send" - forever $ atomically (readTBQueue sndQ) >>= sendTransmissions + sendLoop [] where + sendLoop :: [Transmission BrokerMsg] -> IO () + sendLoop = \case + [] -> + atomically (Left <$> readTBQueue sndQ <|> Right <$> readTBQueue msgQ) >>= \case + Left ts -> sendTransmissions ts >>= sendLoop + Right msgs -> sendLoop $ L.toList msgs + msg : msgs -> do + tSend h c [msg] + atomically (tryReadTBQueue sndQ) >>= \case + Just ts -> sendTransmissions ts >>= sendLoop . (msgs <>) + Nothing -> sendLoop msgs -- If the request had batched subscriptions -- this will reply SOKs to all SUBs in the first batched transmission, -- to reduce client timeouts. -- After that all messages will be sent in separate transmissions, -- without any client response timeouts, and allowing them to interleave -- with other requests responses. - sendTransmissions :: (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO () - sendTransmissions (ts, []) = tSend th c ts + sendTransmissions :: (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO [Transmission BrokerMsg] + sendTransmissions (ts, []) = [] <$ tSend h c ts sendTransmissions (ts, msg : msgs) - | length ts <= 4 = do -- up to 4 SOKs can be in one block with MSG (see testBatchSubResponses test) - tSend th c $ ts <> [msg] - mapM_ (atomically . writeTBQueue msgQ) $ L.nonEmpty msgs - | otherwise = do - tSend th c ts - atomically $ writeTBQueue msgQ (msg :| msgs) - -sendMsg :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> IO () -sendMsg th c@Client {msgQ, clientTHParams = THandleParams {sessionId}} = do - labelMyThread . B.unpack $ "client $" <> encode sessionId <> " sendMsg" - forever $ atomically (readTBQueue msgQ) >>= mapM_ (\t -> tSend th c [t]) - -tSend :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> NonEmpty (Transmission BrokerMsg) -> IO () -tSend th Client {sndActiveAt} ts = do - withMVar th $ \h@THandle {params} -> - void . tPut h $ L.map (\t -> Right (Nothing, encodeTransmission params t)) ts + | length ts <= 4 = msgs <$ tSend h c (ts <> [msg]) -- up to 4 SOKs can be in one block with MSG (see testBatchSubResponses test) + | otherwise = (msg : msgs) <$ tSend h c ts + +tSend :: Transport c => THandleSMP c 'TServer -> Client s -> NonEmpty (Transmission BrokerMsg) -> IO () +tSend h@THandle {params} Client {sndActiveAt} ts = do + void . tPut h $ L.map (\t -> Right (Nothing, encodeTransmission params t)) ts atomically . (writeTVar sndActiveAt $!) =<< liftIO getSystemTime disconnectTransport :: THandle v c 'TServer -> TVar SystemTime -> TVar SystemTime -> ExpirationConfig -> IO Bool -> IO () From 13732c5ac725dd2b53eedb13678179fc5e9bbf8d Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 14:00:48 +0000 Subject: [PATCH 066/159] smp-server: expire inactive clients in one thread --- src/Simplex/Messaging/Server.hs | 34 +++++++++++++++++-------- src/Simplex/Messaging/Server/Env/STM.hs | 10 +++++--- tests/ServerTests.hs | 18 +++++++++++++ 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index cfed6f457..3a477c251 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -195,6 +195,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt : sigIntHandlerThread : map runServer transports <> expireMessagesThread_ cfg + <> expireClientsThread_ cfg <> serverStatsThread_ cfg <> saveStatsThread_ cfg <> prometheusMetricsThread_ cfg @@ -463,6 +464,27 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt expireMessagesThread_ ServerConfig {messageExpiration = Just msgExp} = [expireMessagesThread msgExp] expireMessagesThread_ _ = [] + expireClientsThread_ :: ServerConfig s -> [M s ()] + expireClientsThread_ ServerConfig {inactiveClientExpiration = Just expCfg} = [expireClientsThread expCfg] + expireClientsThread_ _ = [] + + expireClientsThread :: ExpirationConfig -> M s () + expireClientsThread expCfg = do + labelMyThread "expireClients" + srv <- asks server + liftIO $ forever $ do + threadDelay' $ checkInterval expCfg * 1000000 + old <- expireBeforeEpoch expCfg + getServerClients srv >>= mapM_ (expireClient srv old) + where + expireClient srv old c@Client {rcvActiveAt, sndActiveAt, closeTransport} = do + ts <- max <$> readTVarIO rcvActiveAt <*> readTVarIO sndActiveAt + when (systemSeconds ts < old) $ whenM (noSubscriptions srv c) closeTransport + noSubscriptions srv Client {clientId} = + not <$> anyM [hasSubs (subscribers srv), hasSubs (ntfSubscribers srv)] + where + hasSubs ServerSubscribers {subClients} = IS.member clientId <$> readTVarIO subClients + expireMessagesThread :: ExpirationConfig -> M s () expireMessagesThread ExpirationConfig {checkInterval, ttl} = do ms <- asks msgStore @@ -1084,7 +1106,7 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi ts <- liftIO getSystemTime nextClientId <- asks clientSeq clientId <- atomically $ stateTVar' nextClientId $ \next -> (next, next + 1) - c <- liftIO $ newClient clientId q thParams ts + c <- liftIO $ newClient clientId q thParams ts (closeConnection $ connection h) runClientThreads c `finally` clientDisconnected c where runClientThreads :: Client s -> M s () @@ -1092,16 +1114,8 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi s <- asks server ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do - expCfg <- asks $ inactiveClientExpiration . config labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ $ [liftIO $ send h c, client s ms c, receive h ms c] <> disconnectThread_ c s expCfg - disconnectThread_ :: Client s -> Server s -> Maybe ExpirationConfig -> [M s ()] - disconnectThread_ c s (Just expCfg) = [liftIO $ disconnectTransport h (rcvActiveAt c) (sndActiveAt c) expCfg (noSubscriptions c s)] - disconnectThread_ _ _ _ = [] - noSubscriptions Client {clientId} s = - not <$> anyM [hasSubs (subscribers s), hasSubs (ntfSubscribers s)] - where - hasSubs ServerSubscribers {subClients} = IS.member clientId <$> readTVarIO subClients + raceAny_ [liftIO $ send h c, client s ms c, receive h ms c] controlPortAuth :: Handle -> Maybe BasicAuth -> Maybe BasicAuth -> TVar CPClientRole -> BasicAuth -> IO () controlPortAuth h user admin role auth = do diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 066f30013..1de40dce0 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -457,7 +457,8 @@ data Client s = Client connected :: TVar Bool, createdAt :: SystemTime, rcvActiveAt :: TVar SystemTime, - sndActiveAt :: TVar SystemTime + sndActiveAt :: TVar SystemTime, + closeTransport :: IO () } type VerifiedTransmission s = (Maybe (StoreQueue s, QueueRec), Transmission Cmd) @@ -511,8 +512,8 @@ newServerSubscribers = do pendingEvents <- newTVarIO IM.empty pure ServerSubscribers {queueSubscribers, serviceSubscribers, totalServiceSubs, subClients, pendingEvents} -newClient :: ClientId -> Natural -> THandleParams SMPVersion 'TServer -> SystemTime -> IO (Client s) -newClient clientId qSize clientTHParams createdAt = do +newClient :: ClientId -> Natural -> THandleParams SMPVersion 'TServer -> SystemTime -> IO () -> IO (Client s) +newClient clientId qSize clientTHParams createdAt closeTransport = do subscriptions <- TM.emptyIO ntfSubscriptions <- TM.emptyIO serviceSubscribed <- newTVarIO False @@ -549,7 +550,8 @@ newClient clientId qSize clientTHParams createdAt = do connected, createdAt, rcvActiveAt, - sndActiveAt + sndActiveAt, + closeTransport } newSubscription :: SubscriptionThread -> STM Sub diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 634b2e472..68eb311fd 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -138,6 +138,7 @@ serverTests = do testMsgExpireOnInterval testMsgNOTExpireOnInterval describe "Blocking queues" $ testBlockMessageQueue + describe "Inactive clients" testInactiveClientExpiration describe "Short links" $ do testInvQueueLinkData testContactQueueLinkData @@ -2416,6 +2417,23 @@ testMsgExpireOnInterval = Nothing -> return () Just _ -> error "nothing should be delivered" +testInactiveClientExpiration :: SpecWith (ASrvTransport, AStoreType) +testInactiveClientExpiration = + it "should disconnect inactive clients without subscriptions" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do + g <- C.newRandom + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1}} + withSmpServerConfigOn (ATransport t) cfg' testPort $ \_ -> + testSMPClient @c $ \rh -> testSMPClient @c $ \h -> do + Resp "1" NoEntity (Ids _ _ _) <- signSendRecv rh rKey ("1", NoEntity, New rPub dhPub) + threadDelay 2500000 + try (timeout 2000000 $ tGet1 h) >>= \case + Left (_ :: SomeException) -> pure () + Right r -> unexpected (r :: Maybe (Transmission (Either ErrorType BrokerMsg))) + Resp "2" NoEntity PONG <- sendRecv rh (Nothing, "2", NoEntity, PING) + pure () + testMsgNOTExpireOnInterval :: SpecWith (ASrvTransport, AStoreType) testMsgNOTExpireOnInterval = it "should block and unblock message queues" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do From 153d1c5feaedad4a89999a6e61ee3f0ecd0e47eb Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 14:05:35 +0000 Subject: [PATCH 067/159] transport: do not retain last received TLS record --- src/Simplex/Messaging/Transport.hs | 10 ++++++++-- src/Simplex/Messaging/Transport/WebSockets.hs | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 4fcf9ead4..aa20b0cf7 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -77,6 +77,7 @@ module Simplex.Messaging.Transport ALPN, connectTLS, closeTLS, + recvTLS, defaultSupportedParams, defaultSupportedParamsHTTPS, withTlsUnique, @@ -376,6 +377,11 @@ withTlsUnique cxt f = STServer -> T.getPeerFinished STClient -> T.getFinished +-- tls stores the receive record state lazily, so until the next record arrives it retains the last one (up to 16KB). +-- Reading the negotiated cipher forces it. +recvTLS :: T.Context -> IO ByteString +recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt + closeTLS :: T.Context -> IO () closeTLS ctx = T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here @@ -438,7 +444,7 @@ instance Transport TLS where -- this function may return less than requested number of bytes cGet :: TLS p -> Int -> IO ByteString cGet TLS {tlsContext, tlsBuffer, tlsTransportConfig = TransportConfig {transportTimeout = t_}} n = - getBuffered tlsBuffer n t_ (T.recvData tlsContext) + getBuffered tlsBuffer n t_ (recvTLS tlsContext) cPut :: TLS p -> ByteString -> IO () cPut TLS {tlsContext, tlsTransportConfig = TransportConfig {transportTimeout = t_}} = @@ -446,7 +452,7 @@ instance Transport TLS where getLn :: TLS p -> IO ByteString getLn TLS {tlsContext, tlsBuffer} = do - getLnBuffered tlsBuffer (T.recvData tlsContext) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] + getLnBuffered tlsBuffer (recvTLS tlsContext) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] where handleTlsEOF = \case T.PostHandshake T.Error_EOF -> E.throwIO TEBadBlock diff --git a/src/Simplex/Messaging/Transport/WebSockets.hs b/src/Simplex/Messaging/Transport/WebSockets.hs index 3ab213dcd..700e449b4 100644 --- a/src/Simplex/Messaging/Transport/WebSockets.hs +++ b/src/Simplex/Messaging/Transport/WebSockets.hs @@ -27,6 +27,7 @@ import Simplex.Messaging.Transport STransportPeer (..), TransportPeerI (..), closeTLS, + recvTLS, smpBlockSize, withTlsUnique, ) @@ -106,7 +107,7 @@ makeTLSContextStream cxt = S.makeStream readStream writeStream where readStream :: IO (Maybe ByteString) - readStream = (Just <$> T.recvData cxt) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] + readStream = (Just <$> recvTLS cxt) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] where handleTlsEOF = \case T.PostHandshake T.Error_EOF -> pure Nothing From 4356be1948e824106db371cc61a330285d7ef4e7 Mon Sep 17 00:00:00 2001 From: shum Date: Fri, 16 Oct 2026 16:08:05 +0000 Subject: [PATCH 068/159] tests: run proxy leak tests with test environment --- tests/SMPProxyTests.hs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 48ee6486e..8e9e67d67 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -677,6 +677,18 @@ testProxyClosesRelayConnectionAfterDisconnect = withStallingServerOn' testPort2 $ \accepted closed -> do race_ (atomically $ takeTMVar accepted) requestRelaySession timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testProxyForwardTimeoutStuckSession :: HasTestEnv => IO () +testProxyForwardTimeoutStuckSession = + withSmpServerConfigOn (transport @TLS) proxyCfgForwardTimeout testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") + sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") + rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) testForwardOversizedNotKept :: HasTestEnv => IO () testForwardOversizedNotKept = From 6c4b97b1129e3780e9432286df7618e3fafcacef Mon Sep 17 00:00:00 2001 From: shum Date: Fri, 16 Oct 2026 16:08:22 +0000 Subject: [PATCH 069/159] tests: run relay limit test with test environment --- tests/SMPProxyTests.hs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 8e9e67d67..ae641246f 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -690,6 +690,27 @@ testProxyForwardTimeoutStuckSession = rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) +testProxyRelayConcurrencyLimit :: HasTestEnv => IO () +testProxyRelayConcurrencyLimit = + withSmpServerConfigOn (transport @TLS) cfg' testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") + sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + rs <- forConcurrently ([1 .. 20] :: [Int]) $ \_ -> runExceptT (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") + let rejected = length $ filter (== Right (Left (ProxyProtocolError (SMP.PROXY (SMP.BROKER SMP.TIMEOUT))))) rs + rejected `shouldSatisfy` (> 0) + threadDelay 1500000 + readRelayLimitMetric <$> readFile testPrometheusMetricsFile `shouldReturn` Just rejected + where + cfg' = updateCfg proxyCfg $ \cfg_ -> cfg_ {proxyRelayConcurrency = 1, prometheusInterval = Just 1} + readRelayLimitMetric m = case [v | "simplex_smp_relay_messages_concurrency_limit" : v : _ <- map words (lines m)] of + v : _ -> readMaybe v + [] -> Nothing + testForwardOversizedNotKept :: HasTestEnv => IO () testForwardOversizedNotKept = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do From 1e48b4c34cd6d6c7052c9384c60583e8536d45c1 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 01:03:23 -0500 Subject: [PATCH 070/159] fix: close TLS contexts without waiting for peer --- src/Simplex/Messaging/Transport.hs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index aa20b0cf7..335efae5f 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -383,10 +383,7 @@ recvTLS :: T.Context -> IO ByteString recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt closeTLS :: T.Context -> IO () -closeTLS ctx = - T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here - `E.finally` T.contextClose ctx - `catchOwn_` pure () +closeTLS ctx = T.contextClose ctx `catchAll_` pure () defaultSupportedParams :: T.Supported defaultSupportedParams = From e3942bf6008cdbc7cc54d7dd1965680f43868c59 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:27:48 +0000 Subject: [PATCH 071/159] tests: time out store log write, database operation, TLS handshake and file receive --- tests/CoreTests/MsgStoreTests.hs | 2 +- tests/XFTPServerTests.hs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index f892ed162..d31276d6c 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -50,7 +50,7 @@ import Util #if defined(dbServerPostgres) import AgentTests.FunctionalAPITests (runRight) -import Control.Concurrent (forkIO, threadDelay) +import Control.Concurrent (forkIO) import qualified Control.Exception as E import Data.List (sortOn) import Database.PostgreSQL.Simple (Only (..)) diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index b3afe4192..fb7d9873d 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -352,6 +352,18 @@ testReceiveFileTimeout :: HasTestEnv => Expectation testReceiveFileTimeout = timeout 100000 (runExceptT $ receiveFile (\_ -> "" <$ threadDelay maxBound) $ XFTPRcvChunkSpec testChunkPath chSize "") `shouldReturn` Nothing +testTLSHandshakeTimeout :: HasTestEnv => Expectation +testTLSHandshakeTimeout = + withStallingServerOn xftpTestPort $ + timeout 1000000 (runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort Nothing $ \(_ :: TLS 'TClient) -> pure ()) + `shouldReturn` Nothing + where + cfg = defaultTransportClientConfig {logTLSErrors = True} + +testReceiveFileTimeout :: HasTestEnv => Expectation +testReceiveFileTimeout = + timeout 100000 (runExceptT $ receiveFile (\_ -> "" <$ threadDelay maxBound) $ XFTPRcvChunkSpec testChunkPath chSize "") `shouldReturn` Nothing + testFileStorageQuota :: HasTestEnv => AFStoreType -> Expectation testFileStorageQuota fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileSizeQuota = Just $ chSize * 2}) $ \_ -> testXFTPClient $ \c -> runRight_ $ do From 751e686ef4496d21e1150af364f5af64584376ed Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:31:29 +0000 Subject: [PATCH 072/159] agent, servers, transport: stop cancelled and timed-out operations --- src/Simplex/FileTransfer/Transport.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index 1878dc7d2..0254dc296 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -206,8 +206,8 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receive write sz = receiveFileBlocks getBody write sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, - E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO - + E.Handler $ \(e :: E.SomeAsyncException) -> E.throwIO e, + E.Handler $ \(e :: E.SomeException) -> logError (err e) $> Left FILE_IO ] err e = "receiveFile error: " <> tshow e From b796885523daf4cc4c33c25e5549bb7ac888f8db Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:44:56 +0000 Subject: [PATCH 073/159] tests: set the type of the TLS client config in the handshake timeout test --- tests/XFTPServerTests.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index fb7d9873d..42360e978 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -358,6 +358,7 @@ testTLSHandshakeTimeout = timeout 1000000 (runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort Nothing $ \(_ :: TLS 'TClient) -> pure ()) `shouldReturn` Nothing where + cfg :: TransportClientConfig cfg = defaultTransportClientConfig {logTLSErrors = True} testReceiveFileTimeout :: HasTestEnv => Expectation From 28142b27230f62cb175fc743ec03dd0e986ee163 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:45:09 +0000 Subject: [PATCH 074/159] xftp server: handle overflow and allocation limit in a file receive as before, rethrow only cancellations --- src/Simplex/FileTransfer/Transport.hs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index 0254dc296..e6aa0bb27 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -206,8 +206,7 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receive write sz = receiveFileBlocks getBody write sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, - E.Handler $ \(e :: E.SomeAsyncException) -> E.throwIO e, - E.Handler $ \(e :: E.SomeException) -> logError (err e) $> Left FILE_IO + E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO ] err e = "receiveFile error: " <> tshow e From 3a6f1ae6d49c2d53fb48f46da0d9520e5c988f84 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:30:35 +0000 Subject: [PATCH 075/159] xftp: remove chunk files without records when the server starts --- src/Simplex/FileTransfer/Server.hs | 17 +++++++++++++++++ tests/XFTPServerTests.hs | 1 + 2 files changed, 18 insertions(+) diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index 72e10d502..c3ccd82b6 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -139,6 +139,7 @@ xftpServer :: forall s. FileStoreClass s => XFTPServerConfig s -> TMVar Bool -> xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpiration, fileExpiration, xftpServerVRange, information} started = do expireServerFiles Nothing fileExpiration removeTmpUploads + removeUnstoredFiles restoreServerStats expireServerFiles Nothing fileExpiration `onException` stopServer raceAny_ @@ -759,6 +760,22 @@ expireServerFiles itemDelay expCfg = do periodStatsInterval :: Int64 periodStatsInterval = 86400 +removeUnstoredFiles :: FileStoreClass s => M s () +removeUnstoredFiles = do + dir <- asks $ filesPath . config + st <- asks fileStore + whenM ((> 0) <$> liftIO (getFileCount st)) $ do + removed <- filterM (unstored st) =<< listDirectory dir + forM_ removed $ \f -> removeFile (dir f) `catchAny` \_ -> pure () + unless (null removed) $ logNote $ "Removed " <> tshow (length removed) <> " files without records" + where + unstored st name = case B64.decode $ B.pack name of + Right sId -> + liftIO (getFile st SFSender $ EntityId sId) >>= \case + Right (FileRec {filePath}, _) -> isNothing <$> readTVarIO filePath + Left e -> pure $ e == AUTH + Left _ -> pure False + randomId :: Int -> M s ByteString randomId n = atomically . C.randomBytes n =<< asks random diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 42360e978..16b12bc4d 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -104,6 +104,7 @@ xftpServerTests = do it "should count stored files after restart without stats backup" $ testFileStatsRestart False it "should count stored files after restart with stats backup" $ testFileStatsRestart True it "should count stored files after deletion" testFileStatsDelete + it "should remove files without stored chunks when the server starts" testRemoveUnstoredFiles describe "XFTP basic auth" $ do -- allow FNEW | server auth | clnt auth | success it "prohibited without basic auth" $ testFileBasicAuth True (Just "pwd") Nothing False From 30d64a694c9ecd1479bbefeb444ea7cdbce92adf Mon Sep 17 00:00:00 2001 From: Michael-Zebratrix <339181523+Michael-Zebratrix@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:38:38 +0100 Subject: [PATCH 076/159] Report remote-control listener startup failures without blocking --- src/Simplex/Messaging/Transport/Server.hs | 3 +-- src/Simplex/RemoteControl/Discovery.hs | 10 ++++------ src/Simplex/RemoteControl/Types.hs | 8 +++++++- tests/RemoteControl.hs | 20 ++++++++++++++++++++ 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/Simplex/Messaging/Transport/Server.hs b/src/Simplex/Messaging/Transport/Server.hs index 29586cd92..c45724e7a 100644 --- a/src/Simplex/Messaging/Transport/Server.hs +++ b/src/Simplex/Messaging/Transport/Server.hs @@ -311,8 +311,7 @@ startTCPServer started host port = withSocketsDo $ resolve >>= open >>= setStart select as = fromJust $ family AF_INET6 <|> family AF_INET where family f = find ((== f) . addrFamily) as - open addr = do - sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) + open addr = E.bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close $ \sock -> do setSocketOption sock ReuseAddr 1 withFdSocket sock setCloseOnExecIfNeeded logNote $ "binding to " <> tshow (addrAddress addr) diff --git a/src/Simplex/RemoteControl/Discovery.hs b/src/Simplex/RemoteControl/Discovery.hs index baff4adaa..ae11dd7f3 100644 --- a/src/Simplex/RemoteControl/Discovery.hs +++ b/src/Simplex/RemoteControl/Discovery.hs @@ -36,7 +36,7 @@ import Simplex.Messaging.Transport (TransportPeer (..), defaultSupportedParams) import qualified Simplex.Messaging.Transport as Transport import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Server (mkTransportServerConfig, runTransportServerSocket, startTCPServer) -import Simplex.Messaging.Util (ifM, tshow) +import Simplex.Messaging.Util (tshow) import Simplex.RemoteControl.Discovery.Multicast (setMembership) import Simplex.RemoteControl.Types import UnliftIO @@ -80,11 +80,9 @@ preferAddress RCCtrlAddress {address, interface} addrs = startTLSServer :: Maybe Word16 -> TMVar (Maybe N.PortNumber) -> TLS.Credential -> TLS.ServerHooks -> (Transport.TLS 'TServer -> IO ()) -> IO (Async ()) startTLSServer port_ startedOnPort credentials hooks server = async . liftIO $ do started <- newEmptyTMVarIO - bracketOnError (startTCPServer started Nothing $ maybe "0" show port_) (\_e -> setPort Nothing) $ \socket -> - ifM - (atomically $ readTMVar started) - (runServer started socket) - (setPort Nothing) + -- Acquisition can fail before the listener has a port to report. + (bracketOnError (startTCPServer started Nothing $ maybe "0" show port_) N.close $ runServer started) + `finally` setPort Nothing where runServer started socket = do port <- N.socketPort socket diff --git a/src/Simplex/RemoteControl/Types.hs b/src/Simplex/RemoteControl/Types.hs index 48c623e7c..2f9fe31fd 100644 --- a/src/Simplex/RemoteControl/Types.hs +++ b/src/Simplex/RemoteControl/Types.hs @@ -256,6 +256,12 @@ type SessionCode = ByteString type RCStepTMVar a = TMVar (Either RCErrorType a) -$(JQ.deriveJSON (sumTypeJSON $ dropPrefix "RCE") ''RCErrorType) +$( JQ.deriveJSON + ( sumTypeJSON $ \case + "RCETLSStartFailed" -> "tlsStartFailed" + name -> dropPrefix "RCE" name + ) + ''RCErrorType + ) $(JQ.deriveJSON defaultJSON ''RCCtrlAddress) diff --git a/tests/RemoteControl.hs b/tests/RemoteControl.hs index bb8731aad..09177372d 100644 --- a/tests/RemoteControl.hs +++ b/tests/RemoteControl.hs @@ -19,10 +19,12 @@ import qualified Data.ByteString.Lazy.Char8 as LB import Data.List (stripPrefix) import Data.List.NonEmpty (NonEmpty (..)) import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import qualified Network.Socket as N import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (StrEncoding (..)) import Simplex.Messaging.Transport (TSbChainKeys (..)) import Simplex.Messaging.Transport.Client (TransportHost) +import Simplex.Messaging.Transport.Server (startTCPServer) import qualified Simplex.RemoteControl.Client as HC (RCHostClient (action)) import qualified Simplex.RemoteControl.Client as RC import Simplex.RemoteControl.Discovery (mkLastLocalHost, preferAddress) @@ -51,6 +53,7 @@ remoteControlTests = do it "should connect to new pairing" testNewPairing it "should connect to existing pairing" testExistingPairing it "should reject host certificate not signed by CA of known host" testHostCertNotSignedByCA + it "returns a TLS startup error when the listening port is occupied" testOccupiedPort describe "Multicast discovery" $ do it "should find paired host and connect" testMulticast it "should accept announcement only within timestamp window" testAnnouncementTimestamp @@ -162,6 +165,23 @@ testIPv6Invitation = do dh } +testOccupiedPort :: IO () +testOccupiedPort = do + drg <- C.newRandom + hp <- RC.newRCHostPairing drg + started <- newEmptyTMVarIO + bracket (startTCPServer started Nothing "0") N.close $ \listener -> do + port <- N.socketPort listener + result <- timeout 5000000 $ runExceptT $ RC.connectRCHost drg hp (J.String "app") False Nothing (Just $ fromIntegral port) + case result of + Just (Left e) -> do + e `shouldBe` RCETLSStartFailed + LB.unpack (J.encode e) `shouldContain` "\"tlsStartFailed\"" + Just (Right (_, _, client, _)) -> do + uninterruptibleCancel $ HC.action client + expectationFailure "Started a second listener on an occupied port" + Nothing -> expectationFailure "Remote control did not report the listener startup failure" + testNewPairing :: IO () testNewPairing = do drg <- C.newRandom From 2850f05499f5257649445f4be63351a71d4cc463 Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 11:30:17 +0000 Subject: [PATCH 077/159] tests: reproduce proxy request leak, stuck relay --- src/Simplex/Messaging/Client.hs | 1 + tests/SMPClient.hs | 7 +++++++ tests/SMPProxyTests.hs | 26 ++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 750c3c39a..5cefa4c4d 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -35,6 +35,7 @@ module Simplex.Messaging.Client ProxiedRelay (..), getProtocolClient, closeProtocolClient, + pClientSentCommandsCount, protocolClientServer, protocolClientServer', transportHost', diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 391f99023..f7d19ad2d 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -368,6 +368,13 @@ proxyCfgShortPingInterval = let aCfg = smpAgentCfg cfg' cCfg = smpCfg aCfg in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {smpPingInterval = 1_000000}}}} +proxyCfgForwardTimeout :: HasTestEnv => AServerConfig +proxyCfgForwardTimeout = + updateCfg proxyCfg $ \cfg' -> + let aCfg = smpAgentCfg cfg' + cCfg = smpCfg aCfg + nt = NetworkTimeout {backgroundTimeout = 1, interactiveTimeout = 1} + in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {tcpTimeout = nt}}}} proxyCfgVPrev :: HasTestEnv => AStoreType -> AServerConfig proxyCfgVPrev msType = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index ae641246f..57c4a1574 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -756,6 +756,32 @@ testLateResponseCommandReleased = (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () +testProxyForwardTimeoutStuckSession :: IO () +testProxyForwardTimeoutStuckSession = + withSmpServerConfigOn (transport @TLS) proxyCfgForwardTimeout testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") + sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") + rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) + +testForwardOversizedNotKept :: IO () +testForwardOversizedNotKept = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let proxyClientCfg = defaultSMPClientConfig {serverVRange = supportedProxyClientSMPRelayVRange, agreeSecret = True, proxyServer = True} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) proxyClientCfg [] Nothing ts (\_ -> pure ()) + (k, _) <- atomically $ C.generateKeyPair @'C.X25519 g + let et = SMP.EncTransmission $ B.replicate smpBlockSize 'a' + runExceptT (forwardSMPTransmission c (SMP.CorrId "123456789012345678901234") currentClientSMPRelayVersion k et) + `shouldReturn` Left (PCETransportError TELargeMsg) + pClientSentCommandsCount c `shouldReturn` 0 + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From a3448c9d74068cdd3168f30d9efc0481a6469b11 Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 11:30:42 +0000 Subject: [PATCH 078/159] smp: remove unsent and timed-out proxy requests --- src/Simplex/Messaging/Client.hs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 5cefa4c4d..0d41f4263 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1381,17 +1381,19 @@ sendProtocolCommand c nm = sendProtocolCommand_ c nm Nothing Nothing -- -- Please note: if nonce is passed it is also used as a correlation ID sendProtocolCommand_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.CbNonce -> Maybe Int -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg -sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = +sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ, sentCommands}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = ExceptT $ uncurry sendRecv =<< mkTransmission_ c nonce_ (entId, pKey, cmd) where sendRecv :: Either TransportError SentRawTransmission -> Request err msg -> IO (Either (ProtocolClientError err) msg) - sendRecv t_ r = case t_ of - Left e -> pure . Left $ PCETransportError e + sendRecv t_ r@Request {corrId} = case t_ of + Left e -> notSent e Right t | B.length s > blockSize - 2 -> pure . Left $ PCETransportError TELargeMsg | otherwise -> response <$> sendBlock c [r] (Just r, s) (getResponse c nm tOut r) where s = tEncodeBatch1 serviceAuth t + where + notSent e = Left (PCETransportError e) <$ atomically (TM.delete corrId sentCommands) sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do @@ -1426,6 +1428,7 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, se Just r' -> writeTVar timeoutErrorCount 0 $> r' Nothing -> do modifyTVar' timeoutErrorCount (+ 1) + -- a late response is delivered to msgQ, without msgQ it is only logged when (isNothing msgQ) $ TM.delete corrId sentCommands pure $ Left PCEResponseTimeout pure Response {entityId, response} From d474a3cb58e163cf9ed38e65b79bda8fdd488d6e Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 14 Oct 2026 16:23:28 +0000 Subject: [PATCH 079/159] tests: pass CorrCbNonce to forwardSMPTransmission --- tests/SMPProxyTests.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 57c4a1574..0293e95fc 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -778,7 +778,7 @@ testForwardOversizedNotKept = c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) proxyClientCfg [] Nothing ts (\_ -> pure ()) (k, _) <- atomically $ C.generateKeyPair @'C.X25519 g let et = SMP.EncTransmission $ B.replicate smpBlockSize 'a' - runExceptT (forwardSMPTransmission c (SMP.CorrId "123456789012345678901234") currentClientSMPRelayVersion k et) + runExceptT (forwardSMPTransmission c (either error id $ C.corrCbNonce "123456789012345678901234") currentClientSMPRelayVersion k et) `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 From bf350bba037f9d16a44bce2fb54af94ccc52ebb7 Mon Sep 17 00:00:00 2001 From: shum Date: Fri, 16 Oct 2026 16:08:05 +0000 Subject: [PATCH 080/159] tests: run proxy leak tests with test environment --- tests/SMPProxyTests.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 0293e95fc..d41f26948 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -756,7 +756,7 @@ testLateResponseCommandReleased = (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () -testProxyForwardTimeoutStuckSession :: IO () +testProxyForwardTimeoutStuckSession :: HasTestEnv => IO () testProxyForwardTimeoutStuckSession = withSmpServerConfigOn (transport @TLS) proxyCfgForwardTimeout testPort $ \_ -> do g <- C.newRandom @@ -769,7 +769,7 @@ testProxyForwardTimeoutStuckSession = rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) -testForwardOversizedNotKept :: IO () +testForwardOversizedNotKept :: HasTestEnv => IO () testForwardOversizedNotKept = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do g <- C.newRandom From 871a85d44a1faee8f5b77f0edd0e049fb49cabb3 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:51:35 +0000 Subject: [PATCH 081/159] tests: commands without response after timeout or cancel --- tests/SMPProxyTests.hs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index d41f26948..535eb602a 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -78,6 +78,10 @@ smpProxyTests = do testClosedClientCommandsFail it "releases command kept for late response" $ \_ -> testLateResponseCommandReleased + it "does not keep timed out command" $ \_ -> + testTimedOutCommandNotKept + it "does not keep command of cancelled thread" $ \_ -> + testCancelledCommandNotKept describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -782,6 +786,24 @@ testForwardOversizedNotKept = `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 +testTimedOutCommandNotKept :: IO () +testTimedOutCommandNotKept = do + g <- C.newRandom + c <- smpClientStub g "session" currentClientSMPRelayVersion Nothing + runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) Nothing NoEntity (SMP.Cmd SMP.SIdleClient SMP.PING)) + `shouldReturn` Left PCEResponseTimeout + pClientSentCommandsCount c `shouldReturn` 0 + +testCancelledCommandNotKept :: IO () +testCancelledCommandNotKept = do + g <- C.newRandom + c <- smpClientStub g "session" currentClientSMPRelayVersion Nothing + a <- async $ runExceptT $ sendProtocolCommand c NRMBackground Nothing NoEntity (SMP.Cmd SMP.SIdleClient SMP.PING) + threadDelay 100000 + pClientSentCommandsCount c `shouldReturn` 1 + cancel a + pClientSentCommandsCount c `shouldReturn` 0 + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From c7a228250518942f9fad97a5af9d7f9a94d6697d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:55:35 +0000 Subject: [PATCH 082/159] smp server: release forwarded commands when their sender disconnects --- src/Simplex/Messaging/Client.hs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 0d41f4263..b3729e2cd 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1381,8 +1381,12 @@ sendProtocolCommand c nm = sendProtocolCommand_ c nm Nothing Nothing -- -- Please note: if nonce is passed it is also used as a correlation ID sendProtocolCommand_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.CbNonce -> Maybe Int -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg -sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ, sentCommands}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = - ExceptT $ uncurry sendRecv =<< mkTransmission_ c nonce_ (entId, pKey, cmd) +sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ, sentCommands, msgQ}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = + ExceptT $ + E.bracketOnError + (mkTransmission_ c nonce_ (entId, pKey, cmd)) + (\(_, Request {corrId}) -> when (isNothing msgQ) $ atomically $ TM.delete corrId sentCommands) + (uncurry sendRecv) where sendRecv :: Either TransportError SentRawTransmission -> Request err msg -> IO (Either (ProtocolClientError err) msg) sendRecv t_ r@Request {corrId} = case t_ of From c7033171ad2cd25f4b5dcd8a33f19cfae6f20233 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:55:26 +0000 Subject: [PATCH 083/159] clients: stop waiting for send queue space when a command ends --- src/Simplex/Messaging/Client.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index b3729e2cd..91d349114 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1396,6 +1396,7 @@ sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ, sentCommands, ms | otherwise -> response <$> sendBlock c [r] (Just r, s) (getResponse c nm tOut r) where s = tEncodeBatch1 serviceAuth t + getResp = getResponse c nm tOut r where notSent e = Left (PCETransportError e) <$ atomically (TM.delete corrId sentCommands) From 0a181c307642fbd473abc7cbf0569e925adde510 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:52:07 +0000 Subject: [PATCH 084/159] tests: command release tests next to the send queue test --- src/Simplex/Messaging/Client.hs | 1 - tests/SMPProxyTests.hs | 26 -------------------------- 2 files changed, 27 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 91d349114..d975833b5 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -35,7 +35,6 @@ module Simplex.Messaging.Client ProxiedRelay (..), getProtocolClient, closeProtocolClient, - pClientSentCommandsCount, protocolClientServer, protocolClientServer', transportHost', diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 535eb602a..09a01bbbf 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -74,14 +74,6 @@ smpProxyTests = do testProxyClosesRelayConnectionAfterDisconnect it "does not keep oversized forwarded command" $ \_ -> testForwardOversizedNotKept - it "fails commands of closed client at once" $ \_ -> - testClosedClientCommandsFail - it "releases command kept for late response" $ \_ -> - testLateResponseCommandReleased - it "does not keep timed out command" $ \_ -> - testTimedOutCommandNotKept - it "does not keep command of cancelled thread" $ \_ -> - testCancelledCommandNotKept describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -786,24 +778,6 @@ testForwardOversizedNotKept = `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 -testTimedOutCommandNotKept :: IO () -testTimedOutCommandNotKept = do - g <- C.newRandom - c <- smpClientStub g "session" currentClientSMPRelayVersion Nothing - runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) Nothing NoEntity (SMP.Cmd SMP.SIdleClient SMP.PING)) - `shouldReturn` Left PCEResponseTimeout - pClientSentCommandsCount c `shouldReturn` 0 - -testCancelledCommandNotKept :: IO () -testCancelledCommandNotKept = do - g <- C.newRandom - c <- smpClientStub g "session" currentClientSMPRelayVersion Nothing - a <- async $ runExceptT $ sendProtocolCommand c NRMBackground Nothing NoEntity (SMP.Cmd SMP.SIdleClient SMP.PING) - threadDelay 100000 - pClientSentCommandsCount c `shouldReturn` 1 - cancel a - pClientSentCommandsCount c `shouldReturn` 0 - -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From 1f2851a607775bf524f905a53b53f922d0028436 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:07:45 +0000 Subject: [PATCH 085/159] tests: remove the pending stuck relay session test --- tests/SMPClient.hs | 8 +------- tests/SMPProxyTests.hs | 25 ------------------------- 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index f7d19ad2d..7deb65c43 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -368,13 +368,7 @@ proxyCfgShortPingInterval = let aCfg = smpAgentCfg cfg' cCfg = smpCfg aCfg in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {smpPingInterval = 1_000000}}}} -proxyCfgForwardTimeout :: HasTestEnv => AServerConfig -proxyCfgForwardTimeout = - updateCfg proxyCfg $ \cfg' -> - let aCfg = smpAgentCfg cfg' - cCfg = smpCfg aCfg - nt = NetworkTimeout {backgroundTimeout = 1, interactiveTimeout = 1} - in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {tcpTimeout = nt}}}} + proxyCfgVPrev :: HasTestEnv => AStoreType -> AServerConfig proxyCfgVPrev msType = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 09a01bbbf..48ae00eec 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -673,18 +673,6 @@ testProxyClosesRelayConnectionAfterDisconnect = withStallingServerOn' testPort2 $ \accepted closed -> do race_ (atomically $ takeTMVar accepted) requestRelaySession timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () -testProxyForwardTimeoutStuckSession :: HasTestEnv => IO () -testProxyForwardTimeoutStuckSession = - withSmpServerConfigOn (transport @TLS) proxyCfgForwardTimeout testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - let srv = SMPServer testHost testPort testKeyHash - vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion - pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) - sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") - sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g - rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") - rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) testProxyRelayConcurrencyLimit :: HasTestEnv => IO () testProxyRelayConcurrencyLimit = @@ -752,19 +740,6 @@ testLateResponseCommandReleased = (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () -testProxyForwardTimeoutStuckSession :: HasTestEnv => IO () -testProxyForwardTimeoutStuckSession = - withSmpServerConfigOn (transport @TLS) proxyCfgForwardTimeout testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - let srv = SMPServer testHost testPort testKeyHash - vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion - pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) - sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") - sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g - rs <- forM ([1 .. 10] :: [Int]) $ \_ -> runExceptT' (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") - rs `shouldSatisfy` elem (Left (ProxyProtocolError (SMP.PROXY SMP.NO_SESSION))) - testForwardOversizedNotKept :: HasTestEnv => IO () testForwardOversizedNotKept = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do From 0b61833d269167dcd50da44d8b678fcb2525a814 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:07:45 +0000 Subject: [PATCH 086/159] clients: remove code comment --- src/Simplex/Messaging/Client.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index d975833b5..054a12cb8 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1432,7 +1432,6 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, se Just r' -> writeTVar timeoutErrorCount 0 $> r' Nothing -> do modifyTVar' timeoutErrorCount (+ 1) - -- a late response is delivered to msgQ, without msgQ it is only logged when (isNothing msgQ) $ TM.delete corrId sentCommands pure $ Left PCEResponseTimeout pure Response {entityId, response} From 8b8c545163f4708a342740889d354ffa56322dfc Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:28:28 +0000 Subject: [PATCH 087/159] tests: batched commands without response, commands of closed client --- tests/SMPProxyTests.hs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 48ae00eec..b631ced88 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -74,6 +74,8 @@ smpProxyTests = do testProxyClosesRelayConnectionAfterDisconnect it "does not keep oversized forwarded command" $ \_ -> testForwardOversizedNotKept + it "fails commands of closed client at once" $ \_ -> + testClosedClientCommandsFail describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -753,6 +755,18 @@ testForwardOversizedNotKept = `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 +testClosedClientCommandsFail :: HasTestEnv => IO () +testClosedClientCommandsFail = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + closed <- newEmptyTMVarIO + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) + closeProtocolClient c + atomically $ takeTMVar closed + Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) + forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From 8c535e970b08b6bf61d2df04e80ac71aa9d9b998 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:33:11 +0000 Subject: [PATCH 088/159] clients: release batched commands that end without a response --- src/Simplex/Messaging/Client.hs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 054a12cb8..995e759b9 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1380,24 +1380,31 @@ sendProtocolCommand c nm = sendProtocolCommand_ c nm Nothing Nothing -- -- Please note: if nonce is passed it is also used as a correlation ID sendProtocolCommand_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.CbNonce -> Maybe Int -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg -sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ, sentCommands, msgQ}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = - ExceptT $ - E.bracketOnError - (mkTransmission_ c nonce_ (entId, pKey, cmd)) - (\(_, Request {corrId}) -> when (isNothing msgQ) $ atomically $ TM.delete corrId sentCommands) - (uncurry sendRecv) +sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = + ExceptT $ uncurry sendRecv =<< mkTransmission_ c nonce_ (entId, pKey, cmd) where sendRecv :: Either TransportError SentRawTransmission -> Request err msg -> IO (Either (ProtocolClientError err) msg) - sendRecv t_ r@Request {corrId} = case t_ of - Left e -> notSent e + sendRecv t_ r = case t_ of + Left e -> pure . Left $ PCETransportError e Right t | B.length s > blockSize - 2 -> pure . Left $ PCETransportError TELargeMsg | otherwise -> response <$> sendBlock c [r] (Just r, s) (getResponse c nm tOut r) where s = tEncodeBatch1 serviceAuth t - getResp = getResponse c nm tOut r - where - notSent e = Left (PCETransportError e) <$ atomically (TM.delete corrId sentCommands) + +sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = + E.bracketOnError + (atomically $ ifM (readTVar connected) (mapM_ addRequest rs) (mapM_ failRequest rs) >> tryWriteTBQueue sndQ t) + (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) + (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) + where + addRequest r@Request {corrId} = TM.insert corrId r sentCommands + removeRequest Request {corrId} = TM.delete corrId sentCommands + +failRequest :: Request err msg -> STM () +failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do From 98f664238ee4cfa00bfe144790d4ebe4b81d5f2e Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:42:52 +0000 Subject: [PATCH 089/159] tests: command kept for late response after its lifetime --- tests/SMPProxyTests.hs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index b631ced88..7ab59bd27 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -76,6 +76,8 @@ smpProxyTests = do testForwardOversizedNotKept it "fails commands of closed client at once" $ \_ -> testClosedClientCommandsFail + it "releases command kept for late response" $ \_ -> + testLateResponseCommandReleased describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -767,6 +769,24 @@ testClosedClientCommandsFail = Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) +testLateResponseCommandReleased :: HasTestEnv => IO () +testLateResponseCommandReleased = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + msgQ <- newTBQueueIO 4 + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) + rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) + `shouldReturn` Left PCEResponseTimeout + pClientSentCommandsCount c `shouldReturn` 1 + threadDelay 1000000 + pClientSentCommandsCount c `shouldReturn` 0 + (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ + pure () + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is From 924d3edf96b3f1213b5c3ec1e38ea08416cf595d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:25:52 +0000 Subject: [PATCH 090/159] clients: start command lifetime when queued, skip queue when closed --- src/Simplex/Messaging/Client.hs | 8 +++++--- tests/SMPProxyTests.hs | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 995e759b9..2b3db2398 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1393,13 +1393,15 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv s = tEncodeBatch1 serviceAuth t sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a -sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do + ts <- getCurrentTime + -- two separate "atomically" needed to avoid blocking E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ addRequest rs) (mapM_ failRequest rs) >> tryWriteTBQueue sndQ t) + (atomically $ ifM (readTVar connected) (mapM_ (addRequest ts) rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) where - addRequest r@Request {corrId} = TM.insert corrId r sentCommands + addRequest ts r@Request {corrId} = TM.insert corrId r {createdAt = ts} sentCommands removeRequest Request {corrId} = TM.delete corrId sentCommands failRequest :: Request err msg -> STM () diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 7ab59bd27..7a9637d44 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -768,6 +768,8 @@ testClosedClientCommandsFail = atomically $ takeTMVar closed Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) + pClientSentCommandsCount c `shouldReturn` 0 + atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = From 142545bfad2f34c7d2a00e8d21a504ddf205a7ad Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:07:57 +0000 Subject: [PATCH 091/159] clients: keep the address of the connected server --- src/Simplex/Messaging/Client.hs | 15 ++++++++----- src/Simplex/Messaging/Transport/Client.hs | 27 ++++++++++++++++++----- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 2b3db2398..2558448f4 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -30,7 +30,7 @@ module Simplex.Messaging.Client ( -- * Connect (disconnect) client to (from) SMP server TransportSession, SMPTransportSession, - ProtocolClient (thParams, sessionTs), + ProtocolClient (thParams, sessionTs, connectedServer), SMPClient, ProxiedRelay (..), getProtocolClient, @@ -175,7 +175,7 @@ import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport -import Simplex.Messaging.Transport.Client (SocksAuth (..), SocksProxyWithAuth (..), TransportClientConfig (..), TransportHost (..), defaultSMPPort, runTransportClient) +import Simplex.Messaging.Transport.Client (SocksAuth (..), SocksProxyWithAuth (..), TransportClientConfig (..), TransportHost (..), defaultSMPPort, runTLSTransportClient') import Simplex.Messaging.Transport.HTTP2 (httpALPN11) import Simplex.Messaging.Transport.KeepAlive import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts, x509validate) @@ -191,6 +191,7 @@ data ProtocolClient v err msg = ProtocolClient { action :: Maybe (Weak ThreadId), thParams :: THandleParams v 'TClient, sessionTs :: UTCTime, + connectedServer :: ProtoServer msg, client_ :: PClient v err msg } @@ -214,6 +215,7 @@ data PClient v err msg = PClient smpClientStub :: TVar ChaChaDRG -> ByteString -> VersionSMP -> Maybe (THandleAuth 'TClient) -> IO SMPClient smpClientStub g sessionId thVersion thAuth = do let ts = UTCTime (read "2024-03-31") 0 + let srv = "smp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@localhost:5001" connected <- newTVarIO True clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO @@ -239,10 +241,11 @@ smpClientStub g sessionId thVersion thAuth = do serverInfo = Nothing }, sessionTs = ts, + connectedServer = srv, client_ = PClient { connected, - transportSession = (1, "smp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@localhost:5001", Nothing), + transportSession = (1, srv, Nothing), transportHost = "localhost", tcpConnectTimeout, tcpTimeout, @@ -626,7 +629,7 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS let tcConfig = (transportClientConfig networkConfig nm useHost useSNI useALPN) {clientCredentials = serviceCreds <$> serviceCredentials} socksCreds = clientSocksCredentials networkConfig proxySessTs transportSession tId <- - restore (runTransportClient tcConfig socksCreds useHost port' (Just $ keyHash srv) (client t c cVar)) + restore (runTLSTransportClient' defaultSupportedParams Nothing tcConfig socksCreds useHost port' (Just $ keyHash srv) (client t c cVar)) `forkFinally` \r -> let err = either toNetworkError (const NEFailedError) r in void $ atomically $ tryPutTMVar cVar $ Left $ PCENetworkError err @@ -648,8 +651,8 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS web = useWebPort networkConfig presetDomains srv - client :: forall c. Transport c => TProxy c 'TClient -> PClient v err msg -> TMVar (Either (ProtocolClientError err) (ProtocolClient v err msg)) -> c 'TClient -> IO () - client _ c cVar h = do + client :: forall c. Transport c => TProxy c 'TClient -> PClient v err msg -> TMVar (Either (ProtocolClientError err) (ProtocolClient v err msg)) -> IO (TransportHost, ServiceName) -> c 'TClient -> IO () + client _ c cVar connectedAddress h = do ks <- if agreeSecret then Just <$> atomically (C.generateKeyPair g) else pure Nothing serviceKeys_ <- mapM (\creds -> (creds,) <$> atomically (C.generateKeyPair g)) serviceCredentials runExceptT (protocolClientHandshake @v @err @msg h ks (keyHash srv) serverVRange proxyServer serviceKeys_) >>= \case diff --git a/src/Simplex/Messaging/Transport/Client.hs b/src/Simplex/Messaging/Transport/Client.hs index 7472b35e6..3e328e08c 100644 --- a/src/Simplex/Messaging/Transport/Client.hs +++ b/src/Simplex/Messaging/Transport/Client.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Transport.Client ( runTransportClient, runTLSTransportClient, + runTLSTransportClient', smpClientHandshake, defaultSMPPort, defaultTcpConnectTimeout, @@ -164,14 +165,17 @@ data ConnectionHandle c | CHTransport (c 'TClient) runTLSTransportClient :: Transport c => T.Supported -> Maybe XS.CertificateStore -> TransportClientConfig -> Maybe SocksCredentials -> TransportHost -> ServiceName -> Maybe C.KeyHash -> (c 'TClient -> IO a) -> IO a -runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tcpKeepAlive, clientCredentials, clientALPN, useSNI} socksCreds host port keyHash client = do +runTLSTransportClient tlsParams caStore_ cfg socksCreds host port keyHash = runTLSTransportClient' tlsParams caStore_ cfg socksCreds host port keyHash . const + +runTLSTransportClient' :: Transport c => T.Supported -> Maybe XS.CertificateStore -> TransportClientConfig -> Maybe SocksCredentials -> TransportHost -> ServiceName -> Maybe C.KeyHash -> (IO (TransportHost, ServiceName) -> c 'TClient -> IO a) -> IO a +runTLSTransportClient' tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tcpKeepAlive, clientCredentials, clientALPN, useSNI} socksCreds host port keyHash client = do serverCert <- newEmptyTMVarIO clientCredsSent <- newIORef False let hostName = B.unpack $ strEncode host clientParams = mkTLSClientParams tlsParams caStore_ hostName port keyHash clientCredentials clientCredsSent clientALPN useSNI serverCert - connectTCP = case socksProxy of - Just proxy -> connectSocksClient proxy socksCreds (hostAddr host) - _ -> connectTCPClient hostName + (connectTCP, connectedAddress) = case socksProxy of + Just proxy -> (connectSocksClient proxy socksCreds (hostAddr host), \_ -> pure (host, show $ socksPort port)) + _ -> (connectTCPClient hostName, fmap peerAddress . getPeerName) h <- newIORef Nothing let set hc = (>>= \c -> writeIORef h (Just $ hc c) $> c) E.bracket (set CHSocket $ connectTCP port) (\_ -> closeConn h) $ \sock -> do @@ -181,7 +185,7 @@ runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tls <- set CHContext $ connectTLS (Just hostName) tCfg clientParams sock chain <- takePeerCertChain serverCert sent <- readIORef clientCredsSent - client =<< set CHTransport (getTransportConnection tCfg sent chain tls) + client (connectedAddress sock) =<< set CHTransport (getTransportConnection tCfg sent chain tls) where closeConn = readIORef >=> mapM_ (\c -> closeConn_ c `catchAll_` pure ()) closeConn_ = \case @@ -193,6 +197,14 @@ runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, THIPv6 addr -> SocksAddrIPV6 addr THOnionHost h -> SocksAddrDomainName h THDomainName h -> SocksAddrDomainName $ B.pack h + peerAddress = \case + SockAddrInet p addr -> (THIPv4 $ unifyLoopback $ hostAddressToTuple addr, show p) + SockAddrInet6 p _ (0, 0, 0xffff, addr) _ -> peerAddress $ SockAddrInet p $ toHostAddress $ toIPv4w addr + SockAddrInet6 p _ addr _ -> (THIPv6 addr, show p) + _ -> (host, port) + unifyLoopback = \case + (127, _, _, _) -> (127, 0, 0, 1) + addr -> addr connectTCPClient :: HostName -> ServiceName -> IO Socket connectTCPClient host port = withSocketsDo $ resolve >>= tryOpen err @@ -222,11 +234,14 @@ defaultSMPPort = 5223 connectSocksClient :: SocksProxy -> Maybe SocksCredentials -> SocksHostAddress -> ServiceName -> IO Socket connectSocksClient (SocksProxy addr) socksCreds hostAddr _port = do - let port = if null _port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe _port + let port = socksPort _port fst <$> case socksCreds of Just creds -> socksConnectAuth (defaultSocksConf addr) (SocksAddress hostAddr port) creds _ -> socksConnect (defaultSocksConf addr) (SocksAddress hostAddr port) +socksPort :: ServiceName -> PortNumber +socksPort port = if null port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe port + defaultSocksHost :: (Word8, Word8, Word8, Word8) defaultSocksHost = (127, 0, 0, 1) From 32355606f155c77f0b45777acf8faf0792be5702 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:08:10 +0000 Subject: [PATCH 092/159] smp server: one proxy session per relay, limit pending relay connections --- src/Simplex/Messaging/Client/Agent.hs | 32 ++++++++++++++++++----- src/Simplex/Messaging/Server.hs | 19 +++++++++----- src/Simplex/Messaging/Server/Env/STM.hs | 4 +++ src/Simplex/Messaging/Server/Main.hs | 2 ++ src/Simplex/Messaging/Server/Main/Init.hs | 2 ++ tests/SMPClient.hs | 7 ++++- tests/SMPProxyTests.hs | 1 + 7 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index c20ae768e..aef075119 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -52,7 +52,7 @@ import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as L import Data.Map.Strict (Map) import qualified Data.Map.Strict as M -import Data.Maybe (isJust, isNothing) +import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Set as S import Data.Text.Encoding import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime) @@ -82,7 +82,7 @@ import Simplex.Messaging.Session import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport -import Simplex.Messaging.Util (catchAll_, ifM, safeDecodeUtf8, stateTVar', toChunks, tshow, whenM, ($>>=), (<$$>)) +import Simplex.Messaging.Util (catchAll_, diffToMicroseconds, ifM, safeDecodeUtf8, stateTVar', threadDelay', toChunks, tshow, whenM, ($>>=), (<$$>)) import System.Timeout (timeout) import UnliftIO (async) import UnliftIO.STM @@ -107,6 +107,9 @@ data SMPClientAgentConfig = SMPClientAgentConfig { smpCfg :: ProtocolClientConfig SMPVersion, reconnectInterval :: RetryInterval, persistErrorInterval :: NominalDiffTime, + maxPersistedErrors :: Int, + maxConnectingClients :: Maybe Int, + sessionPerConnectedServer :: Bool, msgQSize :: Maybe Natural, agentQSize :: Natural, agentSubsBatchSize :: Int, @@ -124,6 +127,9 @@ defaultSMPClientAgentConfig = maxInterval = 10 * second }, persistErrorInterval = 30, -- seconds + maxPersistedErrors = 1000, + maxConnectingClients = Nothing, + sessionPerConnectedServer = False, msgQSize = Just 2048, agentQSize = 2048, agentSubsBatchSize = 1360, @@ -143,6 +149,9 @@ data SMPClientAgent p = SMPClientAgent randomDrg :: TVar ChaChaDRG, smpClients :: TMap SMPServer SMPClientVar, smpSessions :: TMap SessionId (OwnServer, SMPClient), + connectedServerSessions :: Maybe (TMap SMPServer SessionId), + connectingClients :: TVar Int, + persistedErrors :: TVar Int, -- Only one service subscription can exist per server with this agent. -- With correctly functioning SMP server, queue and service subscriptions can't be -- active at the same time. @@ -159,7 +168,7 @@ data SMPClientAgent p = SMPClientAgent type OwnServer = Bool newSMPClientAgent :: SParty p -> SMPClientAgentConfig -> Maybe DBService -> TVar ChaChaDRG -> IO (SMPClientAgent p) -newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize} dbService randomDrg = do +newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize, sessionPerConnectedServer} dbService randomDrg = do active <- newTVarIO True startedAt <- getCurrentTime -- Only subscribing agents receive server transmissions, should not be created until processed to prevent deadlock. @@ -167,6 +176,9 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize agentQ <- newTBQueueIO agentQSize smpClients <- TM.emptyIO smpSessions <- TM.emptyIO + connectedServerSessions <- if sessionPerConnectedServer then Just <$> TM.emptyIO else pure Nothing + connectingClients <- newTVarIO 0 + persistedErrors <- newTVarIO 0 activeServiceSubs <- TM.emptyIO activeQueueSubs <- TM.emptyIO pendingServiceSubs <- TM.emptyIO @@ -185,6 +197,9 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize randomDrg, smpClients, smpSessions, + connectedServerSessions, + connectingClients, + persistedErrors, activeServiceSubs, activeQueueSubs, pendingServiceSubs, @@ -203,7 +218,7 @@ getSMPServerClient' ca srv = snd <$> getSMPServerClient'' ca srv {-# INLINE getSMPServerClient' #-} getSMPServerClient'' :: SMPClientAgent p -> SMPServer -> ExceptT SMPClientError IO (OwnServer, SMPClient) -getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, workerSeq} srv = do +getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, connectedServerSessions, connectingClients, persistedErrors, workerSeq} srv = do ts <- liftIO getCurrentTime withGetSessVar workerSeq srv smpClients ts (ExceptT . newSMPClient) waitForSMPClient where @@ -223,8 +238,8 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke Nothing -> throwE PCEResponseTimeout newSMPClient :: SMPClientVar -> IO (Either SMPClientError (OwnServer, SMPClient)) - newSMPClient v = do - r <- connectClient ca srv v `E.catches` clientHandlers + newSMPClient v = withConnectSlot $ \slot -> do + r <- if slot then connectClient ca srv v `E.catches` clientHandlers else pure $ Left PCEResponseTimeout case r of Right smp -> do logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv @@ -237,7 +252,8 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke pure $ Right c Left e -> do let ei = persistErrorInterval agentCfg - if ei == 0 + persisted <- if slot && ei > 0 then atomically $ takeSlot persistedErrors $ maxPersistedErrors agentCfg else pure False + if not persisted then atomically $ do putTMVar (sessionVar v) (Left (e, Nothing)) removeSessVar v srv smpClients @@ -300,6 +316,8 @@ connectClient ca@SMPClientAgent {agentCfg, dbService, smpClients, smpSessions, m qVar_ <- TM.lookupIO srv $ activeQueueSubs ca atomically $ do TM.delete sessId smpSessions + forM_ (connectedServerSessions ca) $ \ss -> + whenM ((Just sessId ==) <$> TM.lookup (connectedServer smp) ss) $ TM.delete (connectedServer smp) ss removeSessVar v srv smpClients sSub <- pure sVar_ $>>= updateServiceSub qSubs <- pure qVar_ $>>= updateQueueSubs diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 3a477c251..c43d07758 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -97,7 +97,7 @@ import Network.Socket (ServiceName, Socket, socketToHandle) import qualified Network.TLS as TLS import Numeric.Natural (Natural) import Simplex.Messaging.Agent.Lock -import Simplex.Messaging.Client (NetworkConfig (..), NetworkRequestMode (..), ProtocolClient (thParams), ProtocolClientConfig (..), ProtocolClientError (..), SMPClient, SMPClientError, clientHandlers, forwardSMPTransmission, netTimeoutInt, smpProxyError, temporaryClientError) +import Simplex.Messaging.Client (NetworkConfig (..), NetworkRequestMode (..), ProtocolClient (thParams), ProtocolClientConfig (..), ProtocolClientError (..), SMPClient, SMPClientError, chooseTransportHost, clientHandlers, forwardSMPTransmission, netTimeoutInt, smpProxyError, temporaryClientError) import Simplex.Messaging.Client.Agent (OwnServer, SMPClientAgent (..), SMPClientAgentConfig (..), SMPClientAgentEvent (..), closeSMPClientAgent, getSMPServerClient'', isOwnServer, lookupSMPServerClient, getConnectedSMPServerClient) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding @@ -1583,12 +1583,17 @@ client pure $ allowSMPProxy && maybe True ((== auth) . Just) newQueueBasicAuth getRelay = do ProxyAgent {smpAgent = a} <- asks proxyAgent - liftIO (getConnectedSMPServerClient a srv) >>= \case - Just r -> Just <$> proxyServerResponse a r - Nothing -> - forkProxiedCmd $ - liftIO (runExceptT (getSMPServerClient'' a srv) `E.catches` clientHandlers) - >>= proxyServerResponse a + let ProtocolClientConfig {networkConfig, defaultTransport} = smpCfg $ agentCfg a + relaySrv h = srv {host = [h], port = if null (port srv) then fst defaultTransport else port srv} + case relaySrv <$> chooseTransportHost networkConfig (host srv) of + Left e -> Just <$> proxyServerResponse a (Left e) + Right srv' -> + liftIO (getConnectedSMPServerClient a srv') >>= \case + Just r -> Just <$> proxyServerResponse a r + Nothing -> + forkProxiedCmd $ + liftIO (runExceptT (getSMPServerClient'' a srv') `E.catches` clientHandlers) + >>= proxyServerResponse a proxyServerResponse :: SMPClientAgent 'Sender -> Either SMPClientError (OwnServer, SMPClient) -> M s BrokerMsg proxyServerResponse a smp_ = do ServerStats {pRelays, pRelaysOwn} <- asks serverStats diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 1de40dce0..8f0b01966 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -69,6 +69,7 @@ module Simplex.Messaging.Server.Env.STM defaultNtfExpiration, defaultInactiveClientExpiration, defaultProxyClientConcurrency, + defaultProxyConnectConcurrency, defaultNameResolverConcurrency, defaultForwardWorkers, defaultMaxClientCmdWait, @@ -255,6 +256,9 @@ defaultInactiveClientExpiration = defaultProxyClientConcurrency :: Int defaultProxyClientConcurrency = 500 +defaultProxyConnectConcurrency :: Int +defaultProxyConnectConcurrency = 1000 + defaultNameResolverConcurrency :: Int defaultNameResolverConcurrency = 5000 diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 605f490cd..2d94e4e67 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -529,6 +529,8 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = } }, ownServerDomains = either (const []) textToOwnServers $ lookupValue "PROXY" "own_server_domains" ini, + maxConnectingClients = Just $ readIniDefault defaultProxyConnectConcurrency "PROXY" "connect_concurrency" ini, + sessionPerConnectedServer = True, msgQSize = Nothing, -- to prevent accumulation of late responses, and deadlocks in SMP proxy persistErrorInterval = 30 -- seconds }, diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index e215de140..d0bfd4fd4 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -162,6 +162,8 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = \# Number of workers processing messages that one proxy server forwards to this server.\n\ \# Messages to one queue are processed by one worker, in the order they are received.\n" <> ("# forward_workers = " <> tshow defaultForwardWorkers) + \# Limit number of connections to destination servers being established at once.\n" + <> ("# connect_concurrency = " <> tshow defaultProxyConnectConcurrency) <> "\n\n\ \[NAMES]\n\ \# Public-namespace resolution via the snrc-resolve.py REST resolver.\n\ diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 7deb65c43..9b71a232f 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -341,7 +341,12 @@ proxyCfgMS msType = let smpAgentCfg' = smpAgentCfg cfg' in cfg' { allowSMPProxy = True, - smpAgentCfg = smpAgentCfg' {smpCfg = (smpCfg smpAgentCfg') {agreeSecret = True, proxyServer = True, serverVRange = supportedProxyClientSMPRelayVRange}} + smpAgentCfg = + smpAgentCfg' + { smpCfg = (smpCfg smpAgentCfg') {agreeSecret = True, proxyServer = True, serverVRange = supportedProxyClientSMPRelayVRange}, + maxConnectingClients = Just defaultProxyConnectConcurrency, + sessionPerConnectedServer = True + } } proxyCfgS2 :: HasTestEnv => AServerConfig diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 7a9637d44..44f56a7b2 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -34,6 +34,7 @@ import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), InitialAgentServers import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, REQ) import qualified Simplex.Messaging.Agent.Protocol as A import Simplex.Messaging.Client +import qualified Simplex.Messaging.Client.Agent as CA import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Ratchet (pattern PQSupportOn) import qualified Simplex.Messaging.Crypto.Ratchet as CR From 36ec9411cbdc78efd302358ef0318ee8b18adf9f Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:12:34 +0000 Subject: [PATCH 093/159] smp server: complete relay session setup when the sender disconnects --- src/Simplex/Messaging/Client/Agent.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index aef075119..20710e3a7 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -238,8 +238,8 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, conne Nothing -> throwE PCEResponseTimeout newSMPClient :: SMPClientVar -> IO (Either SMPClientError (OwnServer, SMPClient)) - newSMPClient v = withConnectSlot $ \slot -> do - r <- if slot then connectClient ca srv v `E.catches` clientHandlers else pure $ Left PCEResponseTimeout + newSMPClient v = withConnectSlot $ \slot -> E.mask $ \restore -> do + r <- if slot then restore (connectClient ca srv v) `E.catches` clientHandlers else pure $ Left PCEResponseTimeout case r of Right smp -> do logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv From 5a10e135b3fb81203f2542651a8208723f720f8a Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:12:09 +0000 Subject: [PATCH 094/159] smp server: reject repeated forwarded commands below version 23 --- protocol/simplex-messaging.md | 2 +- src/Simplex/Messaging/Server.hs | 3 +- src/Simplex/Messaging/Server/Env/STM.hs | 10 ++++++ src/Simplex/Messaging/Server/Main.hs | 1 + tests/SMPClient.hs | 1 + tests/SMPProxyTests.hs | 41 +++++++++++++++++++++++++ 6 files changed, 56 insertions(+), 2 deletions(-) diff --git a/protocol/simplex-messaging.md b/protocol/simplex-messaging.md index 109c43cb8..bd68d457d 100644 --- a/protocol/simplex-messaging.md +++ b/protocol/simplex-messaging.md @@ -1168,7 +1168,7 @@ fwdCommandKey = length x509encoded transmission = *OCTET ; note that it is not prefixed with the length ``` -The destination router having received this command decrypts both encryption layers (proxy and client), rejects it with `ERR CRYPTO` if the correlation ID of the decrypted transmission differs from `fwdCorrId`, verifies client authorization as usual, processes it, and send the double encrypted `RRES` response to proxy. +The destination router having received this command decrypts both encryption layers (proxy and client), rejects it with `ERR CRYPTO` if the correlation ID of the decrypted transmission differs from `fwdCorrId` or, when `fwdSmpVersion` is below 23, if `fwdCorrId` was already used in this session, verifies client authorization as usual, processes it, and send the double encrypted `RRES` response to proxy. The number of such correlation IDs in one session is limited, and the destination router closes the session when the limit is exceeded. The shared secret for encrypting transmission bodies between proxy router and destination router is agreed from proxy and destination router keys exchanged in handshake headers - proxy and router use the same shared secret during the session for the encryption between them. diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index c43d07758..1997e25f9 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -60,6 +60,7 @@ import qualified Data.ByteString.Builder as BLD import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB +import qualified Data.ByteString.Short as SBS import Data.Constraint (Dict (..)) import Data.Dynamic (toDyn) import Data.Either (fromRight, isRight, partitionEithers) @@ -1460,7 +1461,7 @@ client (processSub, processNtfSub) Server {subscribers} ms - clnt@Client {rcvQ, sndQ, msgQ, clientTHParams = thParams'@THandleParams {sessionId}, procThreads, fwdWorkers} = do + clnt@Client {clientId, rcvQ, sndQ, msgQ, clientTHParams = thParams'@THandleParams {sessionId}, procThreads, fwdWorkers, fwdCorrIds} = do labelMyThread . B.unpack $ "client $" <> encode sessionId <> " commands" stats <- asks serverStats authDelay <- asks $ authErrorDelay . config diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 8f0b01966..4aa4cb542 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -73,6 +73,7 @@ module Simplex.Messaging.Server.Env.STM defaultNameResolverConcurrency, defaultForwardWorkers, defaultMaxClientCmdWait, + defaultMaxFwdCorrIds, defaultAuthErrorDelayMs, readWriteQueueStore, noPostgresExitStr, @@ -88,6 +89,7 @@ import Control.Monad import Control.Monad.Reader (ReaderT) import qualified Crypto.PubKey.RSA as RSA import Crypto.Random +import Data.ByteString.Short (ShortByteString) import Data.Int (Int64) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IM @@ -98,6 +100,7 @@ import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty) import Data.Map.Strict (Map) import Data.Maybe (isJust) +import Data.Set (Set) import qualified Data.Text as T import Data.Time.Clock (getCurrentTime) import Data.Time.Clock.System (SystemTime) @@ -208,6 +211,7 @@ data ServerConfig s = ServerConfig serverResolverConcurrency :: Int, serverForwardWorkers :: Int, maxClientCmdWait :: Int, + maxFwdCorrIds :: Int, -- | public-namespace resolver config; Nothing disables the names role namesConfig :: Maybe NamesConfig, -- | server public information @@ -268,6 +272,9 @@ defaultForwardWorkers = 8 defaultMaxClientCmdWait :: Int defaultMaxClientCmdWait = 60000000 -- microseconds +defaultMaxFwdCorrIds :: Int +defaultMaxFwdCorrIds = 65536 + defaultAuthErrorDelayMs :: Int64 defaultAuthErrorDelayMs = 50 @@ -457,6 +464,7 @@ data Client s = Client fwdWorkers :: TVar (IntMap (TBQueue (M s ()))), endThreads :: TVar (IntMap (Weak ThreadId)), endThreadSeq :: TVar Int, + fwdCorrIds :: TVar (Set ShortByteString), clientTHParams :: THandleParams SMPVersion 'TServer, connected :: TVar Bool, createdAt :: SystemTime, @@ -531,6 +539,7 @@ newClient clientId qSize clientTHParams createdAt closeTransport = do fwdWorkers <- newTVarIO IM.empty endThreads <- newTVarIO IM.empty endThreadSeq <- newTVarIO 0 + fwdCorrIds <- newTVarIO mempty connected <- newTVarIO True rcvActiveAt <- newTVarIO createdAt sndActiveAt <- newTVarIO createdAt @@ -550,6 +559,7 @@ newClient clientId qSize clientTHParams createdAt closeTransport = do fwdWorkers, endThreads, endThreadSeq, + fwdCorrIds, clientTHParams, connected, createdAt, diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 2d94e4e67..67fcacc4c 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -539,6 +539,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = serverResolverConcurrency = readIniDefault defaultNameResolverConcurrency "NAMES" "resolver_concurrency" ini, serverForwardWorkers = readIniDefault defaultForwardWorkers "PROXY" "forward_workers" ini, maxClientCmdWait = defaultMaxClientCmdWait, + maxFwdCorrIds = defaultMaxFwdCorrIds, namesConfig = readNamesConfig ini, information = serverPublicInfo ini, startOptions diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 9b71a232f..dff0b3973 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -288,6 +288,7 @@ cfgMS msType = withStoreCfg (testServerStoreConfig msType) $ \serverStoreCfg -> serverResolverConcurrency = defaultNameResolverConcurrency, serverForwardWorkers = defaultForwardWorkers, maxClientCmdWait = defaultMaxClientCmdWait, + maxFwdCorrIds = defaultMaxFwdCorrIds, namesConfig = Nothing, information = Nothing, startOptions = defaultStartOptions diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 44f56a7b2..1b94cfa47 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -101,6 +101,10 @@ smpProxyTests = do xit "batching proxy requests" todo it "relay rejects forwarded command with changed version" $ \_ -> testChangedFwdVersion + it "relay rejects repeated forwarded command below version 23" $ \_ -> + testRepeatedFwdCommand + it "relay closes connection after limit of forwarded commands below version 23" $ \_ -> + testFwdCorrIdsLimit it "proxy rejects forwarded correlation ID that is not 24 bytes" $ \_ -> testFwdCorrIdSize it "relay delays AUTH errors to forwarded commands" $ \_ -> @@ -527,6 +531,43 @@ testChangedFwdVersion = (_, SMP.EncResponse resp) <- runExceptT' . forward corrId (prevVersion fwdNoncesSMPVersion) =<< encrypt nonce runExceptT (forward (C.unCbNonce $ C.reverseNonce nonce) (prevVersion fwdNoncesSMPVersion) $ SMP.EncTransmission resp) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) +testRepeatedFwdCommand :: HasTestEnv => IO () +testRepeatedFwdCommand = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + forward <- newForwardedPing rc + let v = prevVersion fwdNoncesSMPVersion + Right (Just _, _) <- forward fwdNoncesSMPVersion + Right (Just _, _) <- forward fwdNoncesSMPVersion + Right (Nothing, _) <- forward v + forward v `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + forward (prevVersion v) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + +testFwdCorrIdsLimit :: HasTestEnv => IO () +testFwdCorrIdsLimit = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {maxFwdCorrIds = 2}) testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + let v = prevVersion fwdNoncesSMPVersion + forwardNew = newForwardedPing rc >>= \forward -> forward v + Right _ <- forwardNew + Right _ <- forwardNew + forwardNew `shouldReturn` Left (PCENetworkError SMP.NEFailedError) + +newForwardedPing :: SMPClient -> IO (VersionSMP -> IO (Either SMPClientError (Maybe C.CbNonce, SMP.EncResponse))) +newForwardedPing rc = do + g <- C.newRandom + THAuthClient {peerServerPubKey} <- maybe (fail "getProtocolClient returned no thAuth") pure $ thAuth $ thParams rc + (cmdPubKey, cmdPrivKey) <- atomically $ C.generateKeyPair g + nonce@(C.CbNonce corrId) <- atomically $ C.randomCbNonce g + let t = SMP.tEncodeBatch1 False (Nothing, SMP.encodeTransmission (thParams rc) (SMP.CorrId corrId, SMP.NoEntity, SMP.Cmd SMP.SIdleClient SMP.PING)) + pure $ \v -> do + et <- either (fail . show) (pure . SMP.EncTransmission) $ C.cbEncrypt (C.dh' peerServerPubKey cmdPrivKey) (SMP.encTransmissionNonce v nonce) t SMP.paddedProxiedTLength + runExceptT $ forwardSMPTransmission rc (either error id $ C.corrCbNonce corrId) v cmdPubKey et + testFwdCorrIdSize :: HasTestEnv => IO () testFwdCorrIdSize = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> From 9eecbd62e06b108e7670d652a8b592024c3e9407 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:11:53 +0000 Subject: [PATCH 095/159] smp server: count forwarded commands below and from version 23 --- src/Simplex/Messaging/Server.hs | 17 +++++++-- src/Simplex/Messaging/Server/Prometheus.hs | 4 +++ src/Simplex/Messaging/Server/Stats.hs | 40 ++++++++++++++++++++++ tests/SMPProxyTests.hs | 29 ++++++++++++++++ 4 files changed, 87 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 1997e25f9..ddc02adfe 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -545,7 +545,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime liftIO $ putStrLn $ "server stats log enabled: " <> statsFilePath liftIO $ threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) - ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, rcvServices, ntfServices, rslvStats} + ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, pMsgFwdsBelow23, pMsgFwdsFrom23, pMsgFwdsRecvBelow23, pMsgFwdsRecvFrom23, rcvServices, ntfServices, rslvStats} <- asks serverStats st <- asks msgStore EntityCounts {queueCount, notifierCount, rcvServiceCount, ntfServiceCount, rcvServiceQueuesCount, ntfServiceQueuesCount} <- @@ -608,6 +608,10 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt pMsgFwds' <- getResetProxyStatsData pMsgFwds pMsgFwdsOwn' <- getResetProxyStatsData pMsgFwdsOwn pMsgFwdsRecv' <- atomicSwapIORef pMsgFwdsRecv 0 + pMsgFwdsBelow23' <- atomicSwapIORef pMsgFwdsBelow23 0 + pMsgFwdsFrom23' <- atomicSwapIORef pMsgFwdsFrom23 0 + pMsgFwdsRecvBelow23' <- atomicSwapIORef pMsgFwdsRecvBelow23 0 + pMsgFwdsRecvFrom23' <- atomicSwapIORef pMsgFwdsRecvFrom23 0 rcvServices' <- getServiceStatsData rcvServices ntfServices' <- getServiceStatsData ntfServices qCount' <- readIORef qCount @@ -688,6 +692,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt <> showServiceStats rcvServices' <> showServiceStats ntfServices' <> showNameResolverStats rslvStats' + <> map tshow [pMsgFwdsBelow23', pMsgFwdsFrom23', pMsgFwdsRecvBelow23', pMsgFwdsRecvFrom23'] ) unliftIO u saveServerStats liftIO $ threadDelay' interval @@ -1623,11 +1628,12 @@ client _ -> ERR $ transportErr TEVersion PFWD fwdV pubKey encBlock -> do ProxyAgent {smpAgent = a} <- asks proxyAgent - ServerStats {pMsgFwds, pMsgFwdsOwn} <- asks serverStats + ServerStats {pMsgFwds, pMsgFwdsOwn, pMsgFwdsBelow23, pMsgFwdsFrom23} <- asks serverStats let inc = mkIncProxyStats pMsgFwds pMsgFwdsOwn liftIO (lookupSMPServerClient a sessId) >>= \case Just (own, smp) | Right fwdCorrId <- C.corrCbNonce (bs corrId) -> do inc own pRequests + incStat $ if fwdV < fwdNoncesSMPVersion then pMsgFwdsBelow23 else pMsgFwdsFrom23 forkProxiedCmd $ do liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses @@ -2318,7 +2324,12 @@ client Nothing -> pure $ Just (corrId', entId', ERR $ CMD PROHIBITED) stats <- asks serverStats incStat $ pMsgFwdsRecv stats - traverse encodeResp r_ + incStat $ (if fwdVersion < fwdNoncesSMPVersion then pMsgFwdsRecvBelow23 else pMsgFwdsRecvFrom23) stats + traverse encodeResp r_ >>= \case + Just rres | any isAuthError r_ -> do + authDelay <- asks $ authErrorDelay . config + Nothing <$ liftIO (sendAfterDelay clnt stats authDelay startedAt ([(corrId, NoEntity, rres)], [])) + rres_ -> pure rres_ where forwardWorker :: EntityId -> M s (TBQueue (M s ())) forwardWorker (EntityId eId) = do diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index 1934a4cd5..360142630 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -131,6 +131,10 @@ prometheusMetrics sm rtm ts = _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, _rcvServices, _ntfServices, _rcvServicesSubMsg, diff --git a/src/Simplex/Messaging/Server/Stats.hs b/src/Simplex/Messaging/Server/Stats.hs index 4b3c8707d..141e1c279 100644 --- a/src/Simplex/Messaging/Server/Stats.hs +++ b/src/Simplex/Messaging/Server/Stats.hs @@ -130,6 +130,10 @@ data ServerStats = ServerStats pMsgFwds :: ProxyStats, pMsgFwdsOwn :: ProxyStats, pMsgFwdsRecv :: IORef Int, + pMsgFwdsBelow23 :: IORef Int, + pMsgFwdsFrom23 :: IORef Int, + pMsgFwdsRecvBelow23 :: IORef Int, + pMsgFwdsRecvFrom23 :: IORef Int, rcvServices :: ServiceStats, ntfServices :: ServiceStats, rcvServicesSubMsg :: IORef Int, @@ -201,6 +205,10 @@ data ServerStatsData = ServerStatsData _pMsgFwds :: ProxyStatsData, _pMsgFwdsOwn :: ProxyStatsData, _pMsgFwdsRecv :: Int, + _pMsgFwdsBelow23 :: Int, + _pMsgFwdsFrom23 :: Int, + _pMsgFwdsRecvBelow23 :: Int, + _pMsgFwdsRecvFrom23 :: Int, _ntfServices :: ServiceStatsData, _rcvServices :: ServiceStatsData, _rcvServicesSubMsg :: Int, @@ -273,6 +281,10 @@ newServerStats trackPending ts = do pMsgFwds <- newProxyStats pMsgFwdsOwn <- newProxyStats pMsgFwdsRecv <- newIORef 0 + pMsgFwdsBelow23 <- newIORef 0 + pMsgFwdsFrom23 <- newIORef 0 + pMsgFwdsRecvBelow23 <- newIORef 0 + pMsgFwdsRecvFrom23 <- newIORef 0 rcvServices <- newServiceStats ntfServices <- newServiceStats rcvServicesSubMsg <- newIORef 0 @@ -342,6 +354,10 @@ newServerStats trackPending ts = do pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, + pMsgFwdsBelow23, + pMsgFwdsFrom23, + pMsgFwdsRecvBelow23, + pMsgFwdsRecvFrom23, rcvServices, ntfServices, rcvServicesSubMsg, @@ -415,6 +431,10 @@ getServerStatsData s = do _pMsgFwds <- getProxyStatsData $ pMsgFwds s _pMsgFwdsOwn <- getProxyStatsData $ pMsgFwdsOwn s _pMsgFwdsRecv <- readIORef $ pMsgFwdsRecv s + _pMsgFwdsBelow23 <- readIORef $ pMsgFwdsBelow23 s + _pMsgFwdsFrom23 <- readIORef $ pMsgFwdsFrom23 s + _pMsgFwdsRecvBelow23 <- readIORef $ pMsgFwdsRecvBelow23 s + _pMsgFwdsRecvFrom23 <- readIORef $ pMsgFwdsRecvFrom23 s _rcvServices <- getServiceStatsData $ rcvServices s _ntfServices <- getServiceStatsData $ ntfServices s _rcvServicesSubMsg <- readIORef $ rcvServicesSubMsg s @@ -484,6 +504,10 @@ getServerStatsData s = do _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, _rcvServices, _ntfServices, _rcvServicesSubMsg, @@ -556,6 +580,10 @@ setServerStats s d = do setProxyStats (pMsgFwds s) $! _pMsgFwds d setProxyStats (pMsgFwdsOwn s) $! _pMsgFwdsOwn d writeIORef (pMsgFwdsRecv s) $! _pMsgFwdsRecv d + writeIORef (pMsgFwdsBelow23 s) $! _pMsgFwdsBelow23 d + writeIORef (pMsgFwdsFrom23 s) $! _pMsgFwdsFrom23 d + writeIORef (pMsgFwdsRecvBelow23 s) $! _pMsgFwdsRecvBelow23 d + writeIORef (pMsgFwdsRecvFrom23 s) $! _pMsgFwdsRecvFrom23 d setServiceStats (rcvServices s) $! _rcvServices d setServiceStats (ntfServices s) $! _ntfServices d writeIORef (rcvServicesSubMsg s) $! _rcvServicesSubMsg d @@ -633,6 +661,10 @@ instance StrEncoding ServerStatsData where "pMsgFwdsOwn:", strEncode (_pMsgFwdsOwn d), "pMsgFwdsRecv=" <> strEncode (_pMsgFwdsRecv d), + "pMsgFwdsBelow23=" <> strEncode (_pMsgFwdsBelow23 d), + "pMsgFwdsFrom23=" <> strEncode (_pMsgFwdsFrom23 d), + "pMsgFwdsRecvBelow23=" <> strEncode (_pMsgFwdsRecvBelow23 d), + "pMsgFwdsRecvFrom23=" <> strEncode (_pMsgFwdsRecvFrom23 d), "rcvServices:", strEncode (_rcvServices d), "ntfServices:", @@ -707,6 +739,10 @@ instance StrEncoding ServerStatsData where _pMsgFwds <- proxyStatsP "pMsgFwds:" _pMsgFwdsOwn <- proxyStatsP "pMsgFwdsOwn:" _pMsgFwdsRecv <- opt "pMsgFwdsRecv=" + _pMsgFwdsBelow23 <- opt "pMsgFwdsBelow23=" + _pMsgFwdsFrom23 <- opt "pMsgFwdsFrom23=" + _pMsgFwdsRecvBelow23 <- opt "pMsgFwdsRecvBelow23=" + _pMsgFwdsRecvFrom23 <- opt "pMsgFwdsRecvFrom23=" _rcvServices <- serviceStatsP "rcvServices:" _ntfServices <- serviceStatsP "ntfServices:" _rslvStats <- @@ -766,6 +802,10 @@ instance StrEncoding ServerStatsData where _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, _rcvServices, _ntfServices, _rcvServicesSubMsg = 0, diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 1b94cfa47..56460717c 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -38,10 +38,12 @@ import qualified Simplex.Messaging.Client.Agent as CA import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Ratchet (pattern PQSupportOn) import qualified Simplex.Messaging.Crypto.Ratchet as CR +import Simplex.Messaging.Encoding.String (strDecode) import Simplex.Messaging.Protocol (EncRcvMsgBody (..), MsgBody, QueueReqData (..), RcvMessage (..), SubscriptionMode (..), maxMessageLength, noMsgFlags) import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Server.Env.STM (AStoreType (..), ServerConfig (..)) import Simplex.Messaging.Server.MsgStore.Types (SQSType (..)) +import Simplex.Messaging.Server.Stats (ServerStatsData (..)) import Simplex.Messaging.Transport import Simplex.Messaging.Util (bshow, tshow) import Simplex.Messaging.Version (mkVersionRange) @@ -105,6 +107,8 @@ smpProxyTests = do testRepeatedFwdCommand it "relay closes connection after limit of forwarded commands below version 23" $ \_ -> testFwdCorrIdsLimit + it "proxy and relay count forwarded commands by version" $ \_ -> + testFwdVersionStats it "proxy rejects forwarded correlation ID that is not 24 bytes" $ \_ -> testFwdCorrIdSize it "relay delays AUTH errors to forwarded commands" $ \_ -> @@ -557,6 +561,31 @@ testFwdCorrIdsLimit = Right _ <- forwardNew forwardNew `shouldReturn` Left (PCENetworkError SMP.NEFailedError) +testFwdVersionStats :: HasTestEnv => IO () +testFwdVersionStats = do + withSmpServerConfigOn (transport @TLS) statsCfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive testSMPServer Nothing + forM_ [fwdNoncesSMPVersion, fwdNoncesSMPVersion, prevVersion fwdNoncesSMPVersion] $ \v -> + runExceptT (proxySMPMessage pc NRMInteractive sess {prVersion = v} Nothing (SMP.EntityId "1234") noMsgFlags "hello") `shouldReturn` Left (PCEProtocolError SMP.AUTH) + threadDelay 1500000 + ms <- map B.words . B.lines <$> B.readFile testPrometheusMetricsFile + let metric name = [v | n : v : _ <- ms, n == name] + map + metric + [ "simplex_smp_relay_messages_requests_version{version=\"below_23\"}", + "simplex_smp_relay_messages_requests_version{version=\"from_23\"}", + "simplex_smp_relay_messages_received_version{version=\"below_23\"}", + "simplex_smp_relay_messages_received_version{version=\"from_23\"}" + ] + `shouldBe` [["1"], ["2"], ["1"], ["2"]] + Right ServerStatsData {_pMsgFwdsBelow23, _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23} <- strDecode <$> B.readFile testServerStatsBackupFile + (_pMsgFwdsBelow23, _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23) `shouldBe` (1, 2, 1, 2) + where + statsCfg = updateCfg proxyCfg $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, prometheusInterval = Just 1} + newForwardedPing :: SMPClient -> IO (VersionSMP -> IO (Either SMPClientError (Maybe C.CbNonce, SMP.EncResponse))) newForwardedPing rc = do g <- C.newRandom From a0ee44043d9b9cd96687518e615b380cdbd3f652 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:15:03 +0000 Subject: [PATCH 096/159] smp server: announce minimum client version and latest app releases --- src/Simplex/Messaging/Server/Information.hs | 28 ++++++++++++++++++--- src/Simplex/Messaging/Server/Main.hs | 15 +++++++++-- src/Simplex/Messaging/Server/Main/Init.hs | 7 ++++++ tests/AgentTests/FunctionalAPITests.hs | 3 ++- tests/CLITests.hs | 12 +++++++-- 5 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/Simplex/Messaging/Server/Information.hs b/src/Simplex/Messaging/Server/Information.hs index 2f1f046e7..11057063b 100644 --- a/src/Simplex/Messaging/Server/Information.hs +++ b/src/Simplex/Messaging/Server/Information.hs @@ -10,6 +10,8 @@ module Simplex.Messaging.Server.Information ( ServerInformation (..), ServerPublicConfig (..), ServerPublicInfo (..), + ClientSupport (..), + MinClientVersion (..), ServerPersistenceMode (..), ServerConditions (..), HostingType (..), @@ -26,6 +28,8 @@ import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Int (Int64) import Data.Maybe (isJust) import Data.Text (Text) +import Data.Time.Calendar (Day) +import Data.Word (Word16) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (defaultJSON, dropPrefix, enumJSON) @@ -55,7 +59,8 @@ data ServerPublicInfo = ServerPublicInfo complaintsContacts :: Maybe ServerContactAddress, hosting :: Maybe Entity, hostingType :: Maybe HostingType, - serverCountry :: Maybe Text + serverCountry :: Maybe Text, + clientSupport :: Maybe ClientSupport } deriving (Show) @@ -70,12 +75,13 @@ emptyServerInfo sourceCode = complaintsContacts = Nothing, hosting = Nothing, hostingType = Nothing, - serverCountry = Nothing + serverCountry = Nothing, + clientSupport = Nothing } hasServerInfo :: ServerPublicInfo -> Bool -hasServerInfo ServerPublicInfo {usageConditions, operator, website, adminContacts, complaintsContacts, hosting, hostingType, serverCountry} = - isJust usageConditions || isJust operator || isJust website || isJust adminContacts || isJust complaintsContacts || isJust hosting || isJust hostingType || isJust serverCountry +hasServerInfo ServerPublicInfo {usageConditions, operator, website, adminContacts, complaintsContacts, hosting, hostingType, serverCountry, clientSupport} = + isJust usageConditions || isJust operator || isJust website || isJust adminContacts || isJust complaintsContacts || isJust hosting || isJust hostingType || isJust serverCountry || isJust clientSupport data ServerPersistenceMode = SPMMemoryOnly | SPMQueues | SPMMessages deriving (Show) @@ -120,6 +126,16 @@ data ServerContactAddress = ServerContactAddress data PGPKey = PGPKey {pkURI :: Text, pkFingerprint :: Text} deriving (Show) +data ClientSupport = ClientSupport + { minClientVersion :: Maybe MinClientVersion, + stableRelease :: Maybe Text, + betaRelease :: Maybe Text + } + deriving (Eq, Show) + +data MinClientVersion = MinClientVersion {protocolVersion :: Word16, fromDate :: Day} + deriving (Eq, Show) + $(J.deriveJSON (enumJSON $ dropPrefix "SPM") ''ServerPersistenceMode) $(J.deriveJSON defaultJSON ''ServerConditions) @@ -132,6 +148,10 @@ $(J.deriveJSON defaultJSON ''ServerContactAddress) $(J.deriveJSON defaultJSON ''ServerPublicConfig) +$(J.deriveJSON defaultJSON ''MinClientVersion) + +$(J.deriveJSON defaultJSON ''ClientSupport) + $(J.deriveJSON defaultJSON ''ServerPublicInfo) $(J.deriveJSON defaultJSON ''ServerInformation) diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 67fcacc4c..63ea31edd 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -56,6 +56,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1, encodeUtf8) import qualified Data.Text.IO as T +import Data.Time.Format.ISO8601 (iso8601ParseM) import Options.Applicative import Simplex.Messaging.Agent.Protocol (ConnectionLink (..), ConnectionMode (..), connReqUriP') import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) @@ -698,9 +699,18 @@ serverPublicInfo ini = serverInfo <$!> infoValue "source_code" adminContacts = iniContacts "admin_simplex" "admin_email" "admin_pgp" "admin_pgp_fingerprint", complaintsContacts = iniContacts "complaints_simplex" "complaints_email" "complaints_pgp" "complaints_pgp_fingerprint", hosting = iniEntity "hosting" "hosting_country", - hostingType = either error id <$!> strDecodeIni "INFORMATION" "hosting_type" ini + hostingType = either error id <$!> strDecodeIni "INFORMATION" "hosting_type" ini, + clientSupport = iniClientSupport } infoValue name = eitherToMaybe $ lookupValue "INFORMATION" name ini + iniClientSupport = + let minClientVersion = MinClientVersion <$> (either error id <$!> strDecodeIni "INFORMATION" "client_min_version" ini) <*> (dateValue <$!> infoValue "client_min_version_date") + stableRelease = infoValue "client_stable_release" + betaRelease = infoValue "client_beta_release" + in case (minClientVersion, stableRelease, betaRelease) of + (Nothing, Nothing, Nothing) -> Nothing + _ -> Just ClientSupport {minClientVersion, stableRelease, betaRelease} + dateValue = fromMaybe (error "Use YYYY-MM-DD for client_min_version_date") . iso8601ParseM . T.unpack iniEntity nameField countryField = (\name -> Entity {name, country = countryValue countryField}) <$!> infoValue nameField @@ -955,7 +965,8 @@ cliCommandP cfgPath logPath iniFile = complaintsContacts = Nothing, hosting = fst hosting_, hostingType, - serverCountry + serverCountry, + clientSupport = Nothing }, operatorCountry = snd operator_, hostingCountry = snd hosting_, diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index d0bfd4fd4..82dcd8bf6 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -246,6 +246,13 @@ informationIniContent InitOptions {sourceCode, serverInfo} = <> "\n\ \# Hosting type can be `virtual`, `dedicated`, `colocation`, `owned`\n" <> ("hosting_type = " <> maybe "virtual" (decodeLatin1 . strEncode) hostingType <> "\n\n") + <> "# Client support announced to the apps.\n\ + \# Clients with protocol version below client_min_version are not supported from client_min_version_date.\n\ + \# client_min_version = 23\n\ + \# client_min_version_date = YYYY-MM-DD\n\ + \# The latest app releases.\n\ + \# client_stable_release = 7.1.2\n\ + \# client_beta_release = 7.2.0-beta.1\n\n" where ServerPublicInfo {operator, website, hosting, hostingType, serverCountry} = serverInfo countryStr optName country = optDisabled country <> optName <> "_country = " <> fromMaybe "ISO-3166 2-letter code" country <> "\n" diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index eb7983177..862d5ebf0 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4936,7 +4936,8 @@ testServerInformation = complaintsContacts = Nothing, hosting = Nothing, hostingType = Nothing, - serverCountry = Nothing + serverCountry = Nothing, + clientSupport = Nothing } testClientSupport :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () diff --git a/tests/CLITests.hs b/tests/CLITests.hs index fa76b947b..33e9b5cb0 100644 --- a/tests/CLITests.hs +++ b/tests/CLITests.hs @@ -13,10 +13,11 @@ import qualified Crypto.PubKey.RSA as RSA import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as BL import qualified Data.HashMap.Strict as HM -import Data.Ini (Ini (..), lookupValue, readIniFile, writeIniFile) +import Data.Ini (Ini (..), lookupValue, parseIni, readIniFile, writeIniFile) import Data.List (isInfixOf, isPrefixOf) import Data.Maybe (mapMaybe) import qualified Data.Text as T +import Data.Time.Calendar (fromGregorian) import qualified Data.X509 as X import qualified Data.X509.File as XF import Data.X509.Validation (Fingerprint (..)) @@ -30,7 +31,8 @@ import Simplex.FileTransfer.Server.Main (xftpServerCLI) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Server.CLI (simplexmqVersionCommit) import Simplex.Messaging.Server.Env.STM (ServerConfig (serverStoreCfg), ServerStoreCfg (SSCMemory), checkHTTPSCredentials, newEnv) -import Simplex.Messaging.Server.Main (smpServerCLI, smpServerCLI_) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (clientSupport)) +import Simplex.Messaging.Server.Main (serverPublicInfo, smpServerCLI, smpServerCLI_) import Simplex.Messaging.Transport (TLS (..), Transport (cGet, cPut, getLn), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS, supportedClientSMPRelayVRange) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), defaultTransportClientConfig, runTLSTransportClient, smpClientHandshake) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC @@ -94,6 +96,7 @@ cliTests = do it "static files" smpServerTestStatic it "cloud scripts disable embedded web without certificates" smpCloudScriptsDisableWeb it "should not start with invalid stats_save_interval" smpServerInvalidStatsSaveInterval + it "reads client support information" smpServerClientSupport #if defined(dbServerPostgres) around_ (postgressBracket ntfTestServerDBConnectInfo) $ before_ (createNtfSchema ntfTestServerDBConnectInfo ntfTestServerDBOpts) $ describe "Ntf server CLI" $ do @@ -295,6 +298,11 @@ smpServerInvalidStatsSaveInterval = do writeIniFile iniFile ini {iniSections = HM.adjust (("stats_save_interval", "0") :) "STORE_LOG" (iniSections ini)} capture_ (withArgs ["start"] $ 5000000 `timeout` smpServerCLI cfgPath logPath) `shouldThrow` errorCall "invalid INI setting stats_save_interval: 0" +smpServerClientSupport :: HasCallStack => IO () +smpServerClientSupport = do + Right ini <- pure $ parseIni "[INFORMATION]\nsource_code = https://github.com/simplex-chat/simplexmq\nclient_min_version = 24\nclient_min_version_date = 2027-05-01\nclient_stable_release = 7.2.0\n" + (clientSupport =<< serverPublicInfo ini) + `shouldBe` Just ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = 24, fromDate = fromGregorian 2027 5 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} smpCloudScriptsDisableWeb :: HasCallStack => IO () smpCloudScriptsDisableWeb = do From c666c713df5fccecb77741efbd4b921ad3322883 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:19:24 +0000 Subject: [PATCH 097/159] agent: notify about client support announced by preset servers --- src/Simplex/Messaging/Agent/Client.hs | 9 ++++++--- src/Simplex/Messaging/Agent/Protocol.hs | 4 ++++ src/Simplex/Messaging/Transport.hs | 1 + tests/AgentTests/FunctionalAPITests.hs | 8 ++++++-- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 2b32a806d..e87f227ad 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -318,12 +318,12 @@ import Simplex.Messaging.Protocol import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo -import Simplex.Messaging.Server.Information (ServerPublicInfo) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (clientSupport)) import Simplex.Messaging.Session import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, newNtfCredsSMPVersion, pattern VersionSMP) +import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, fwdNoncesSMPVersion, newNtfCredsSMPVersion, pattern VersionSMP) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Credentials import Simplex.Messaging.Util @@ -379,6 +379,7 @@ data AgentClient = AgentClient useNetworkConfig :: TVar (NetworkConfig, NetworkConfig), -- (slow, fast) networks presetDomains :: [HostName], presetServers :: [SMPServer], + presetClientSupport :: TVar ClientSupport, userNetworkInfo :: TVar UserNetworkInfo, userNetworkUpdated :: TVar (Maybe UTCTime), subscrConns :: TVar (Set ConnId), @@ -555,6 +556,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf xftpDownloadSessions <- newQSem $ xftpMaxDownloadSessions cfg userEntitlements <- newTVarIO entitlements useNetworkConfig <- newTVarIO (slowNetworkConfig netCfg, netCfg) + presetClientSupport <- newTVarIO $ ClientSupport Nothing Nothing Nothing userNetworkInfo <- newTVarIO $ UserNetworkInfo UNOther True userNetworkUpdated <- newTVarIO Nothing subscrConns <- newTVarIO S.empty @@ -606,6 +608,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf useNetworkConfig, presetDomains, presetServers, + presetClientSupport, userNetworkInfo, userNetworkUpdated, subscrConns, @@ -790,7 +793,7 @@ getSMPProxyClient c@AgentClient {active, smpClients, smpProxiedRelays, workerSeq Nothing -> Left $ BROKER (B.unpack $ strEncode srv) TIMEOUT smpConnectClient :: AgentClient -> NetworkRequestMode -> SMPTransportSession -> TMap SMPServer ProxiedRelayVar -> SMPClientVar -> AM SMPConnectedClient -smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm tSess@(userId, srv, _) prs v = +smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains, presetServers} nm tSess@(userId, srv, _) prs v = newProtocolClient c tSess smpClients connectClient v `catchAllErrors` \e -> lift (resubscribeSMPSession c tSess) >> throwE e where diff --git a/src/Simplex/Messaging/Agent/Protocol.hs b/src/Simplex/Messaging/Agent/Protocol.hs index 93438e471..319e318f2 100644 --- a/src/Simplex/Messaging/Agent/Protocol.hs +++ b/src/Simplex/Messaging/Agent/Protocol.hs @@ -287,6 +287,7 @@ import Simplex.Messaging.Protocol pattern SMPServer, ) import qualified Simplex.Messaging.Protocol as SMP +import Simplex.Messaging.Server.Information (ClientSupport) import Simplex.Messaging.ServiceScheme import Simplex.Messaging.Transport.Client (TransportHost, TransportHosts_ (..)) import Simplex.Messaging.Util @@ -449,6 +450,7 @@ data AEvent (e :: AEntity) where ERR :: AgentErrorType -> AEvent AEConn ERRS :: NonEmpty (ConnId, AgentErrorType) -> AEvent AENone SUSPENDED :: AEvent AENone + CLIENT_SUPPORT :: ClientSupport -> AEvent AENone RFPROG :: Int64 -> Int64 -> AEvent AERcvFile RFDONE :: FilePath -> AEvent AERcvFile RFERR :: AgentErrorType -> AEvent AERcvFile @@ -534,6 +536,7 @@ data AEventTag (e :: AEntity) where ERR_ :: AEventTag AEConn ERRS_ :: AEventTag AENone SUSPENDED_ :: AEventTag AENone + CLIENT_SUPPORT_ :: AEventTag AENone -- XFTP commands and responses RFDONE_ :: AEventTag AERcvFile RFPROG_ :: AEventTag AERcvFile @@ -601,6 +604,7 @@ aEventTag = \case ERR _ -> ERR_ ERRS _ -> ERRS_ SUSPENDED -> SUSPENDED_ + CLIENT_SUPPORT _ -> CLIENT_SUPPORT_ RFPROG {} -> RFPROG_ RFDONE {} -> RFDONE_ RFERR {} -> RFERR_ diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 335efae5f..1e7c42274 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -35,6 +35,7 @@ module Simplex.Messaging.Transport ( -- * SMP transport parameters SMPVersion, VersionSMP, + pattern VersionSMP, VersionRangeSMP, THandleSMP, alpnSupportedSMPHandshakes, diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 862d5ebf0..6b2f8066e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -87,6 +87,7 @@ import qualified Data.Set as S import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1) import qualified Data.Text.IO as T +import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (diffUTCTime, getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Tuple (swap) @@ -119,11 +120,11 @@ import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.Env.STM (AStoreType (..), ServerConfig (..), ServerStoreCfg (..), StorePaths (..)) import Simplex.Messaging.Server.Expiration -import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (..)) import Simplex.Messaging.Server.MsgStore.Types (SMSType (..), SQSType (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..)) -import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, VersionSMP, currentServerSMPRelayVersion, minClientSMPRelayVersion, minServerSMPRelayVersion, alpnSupportedSMPHandshakes) +import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, VersionSMP, currentClientSMPRelayVersion, currentServerSMPRelayVersion, minClientSMPRelayVersion, minServerSMPRelayVersion, alpnSupportedSMPHandshakes) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) import Simplex.Messaging.Util (bshow, diffToMicroseconds, unlessM) import Simplex.Messaging.Version (VersionRange (..)) @@ -687,6 +688,9 @@ functionalAPITests ps = do it "should pass with correct password" $ testSMPServerConnectionTest ps auth (srv auth) `shouldReturn` Right (Just (Right testServerInformation)) it "should fail without password" $ testSMPServerConnectionTest ps auth (srv Nothing) `shouldReturn` Left authErr it "should fail with incorrect password" $ testSMPServerConnectionTest ps auth (srv $ Just "wrong") `shouldReturn` Left authErr + describe "Client support from preset servers" $ do + it "should notify about unsupported version and app releases" $ testClientSupport ps + it "should not notify about supported version or servers that are not preset" $ testClientSupportNoEvent ps describe "getConnectionVerifyCodes" $ it "should return the same codes for both peers" $ withSmpServer ps testConnectionVerifyCodes From 57aae322d50ef22d01e9694d66de32c8a0ba0cd6 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:35:55 +0000 Subject: [PATCH 098/159] tests: type the version list in the forwarding stats test --- tests/SMPProxyTests.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 56460717c..6473d01b9 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -568,7 +568,7 @@ testFwdVersionStats = do ts <- getCurrentTime pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive testSMPServer Nothing - forM_ [fwdNoncesSMPVersion, fwdNoncesSMPVersion, prevVersion fwdNoncesSMPVersion] $ \v -> + forM_ ([fwdNoncesSMPVersion, fwdNoncesSMPVersion, prevVersion fwdNoncesSMPVersion] :: [VersionSMP]) $ \v -> runExceptT (proxySMPMessage pc NRMInteractive sess {prVersion = v} Nothing (SMP.EntityId "1234") noMsgFlags "hello") `shouldReturn` Left (PCEProtocolError SMP.AUTH) threadDelay 1500000 ms <- map B.words . B.lines <$> B.readFile testPrometheusMetricsFile From d65c677b381b54e6a81fcf3b47e56c3910859e6c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:22:28 +0000 Subject: [PATCH 099/159] Revert "agent: require version 23 for private routing to preset servers" This reverts commit beca5081b99f34253cc8d94cb3b17b3f8ef1bc4e, keeping the test of private routing to a server below version 23. --- src/Simplex/Messaging/Agent/Client.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index e87f227ad..2ad50723a 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -323,7 +323,7 @@ import Simplex.Messaging.Session import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, fwdNoncesSMPVersion, newNtfCredsSMPVersion, pattern VersionSMP) +import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, newNtfCredsSMPVersion, pattern VersionSMP) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Credentials import Simplex.Messaging.Util From 2e819b03499deb0c1bdda0c21f01328c6ff617a9 Mon Sep 17 00:00:00 2001 From: Narasimha-sc <166327228+Narasimha-sc@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:43:44 +0000 Subject: [PATCH 100/159] transport: option to detect dead connections with data in flight --- plans/2026-11-03-unacked-data-timeout.md | 35 ++++++++++++++++ simplexmq.cabal | 1 + src/Simplex/Messaging/Client.hs | 6 ++- src/Simplex/Messaging/Transport/KeepAlive.hs | 23 +++++++++-- tests/CoreTests/KeepAliveTests.hs | 42 ++++++++++++++++++++ tests/CoreTests/SOCKSSettings.hs | 10 +++++ tests/Test.hs | 2 + 7 files changed, 114 insertions(+), 5 deletions(-) create mode 100644 plans/2026-11-03-unacked-data-timeout.md create mode 100644 tests/CoreTests/KeepAliveTests.hs diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md new file mode 100644 index 000000000..aef26f16b --- /dev/null +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -0,0 +1,35 @@ +# Unacknowledged-data timeout + +## Problem + +A client connection to a server that becomes unreachable while data is unacknowledged is reported as failed after about 15 minutes on Linux and Android. Until then, the client sends into the dead connection. + +## Cause + +TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed by the OS only after the retransmission limit: `tcp_retries2` = 15, about 15 minutes. + +## Fix + +- `KeepAliveOpts.unackedDataTimeout :: Maybe Bool`: + - `Just True`: on. + - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. +- `setSocketKeepAlive`, option on: the socket timeout for unacknowledged data is set to `keepIdle + keepIntvl * keepCnt` seconds (90 s with `defaultKeepAliveOpts`): + + | OS | Socket option | Unit | + |---|---|---| + | Linux, Android | `TCP_USER_TIMEOUT` | ms | + | macOS, iOS | `TCP_RXT_CONNDROPTIME` | s | + | Windows | not set | | + +- `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. + +## Scope + +- Client connections with keep-alive: SMP, NTF and XFTP clients (`transportClientConfig`). +- Unchanged: + - connections without the option; + - outgoing connections of servers (`defaultNetworkConfig`) and remote control (`defaultTransportClientConfig`): `unackedDataTimeout = Nothing`; + - `defaultHTTP2ClientConfig`: keep-alive not set. +- Tests: + - `tests/CoreTests/SOCKSSettings.hs`: the option is removed only with a SOCKS proxy for the host. + - `tests/CoreTests/KeepAliveTests.hs`, Linux only: a client writing to a peer that does not read fails with `ETIMEDOUT` within 8 s with the option and keep-alive time 2 s, and does not fail within 8 s without it. diff --git a/simplexmq.cabal b/simplexmq.cabal index 6ba15d1cb..090d13af4 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -588,6 +588,7 @@ test-suite simplexmq-test CoreTests.CryptoTests CoreTests.EncodingTests CoreTests.EthCryptoTests + CoreTests.KeepAliveTests CoreTests.LockTests CoreTests.MsgStoreTests CoreTests.RetryIntervalTests diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 2558448f4..7059a358b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -155,7 +155,7 @@ import Data.List (find, isSuffixOf) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M -import Data.Maybe (catMaybes, fromMaybe, isNothing) +import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing) import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) @@ -453,9 +453,11 @@ defaultNetworkConfig = transportClientConfig :: NetworkConfig -> NetworkRequestMode -> TransportHost -> Bool -> Maybe [ALPN] -> TransportClientConfig transportClientConfig NetworkConfig {socksProxy, socksMode, tcpConnectTimeout, tcpKeepAlive, logTLSErrors} nm host useSNI clientALPN = - TransportClientConfig {socksProxy = useSocksProxy socksMode, tcpConnectTimeout = tOut, tcpKeepAlive, logTLSErrors, clientCredentials = Nothing, clientALPN, useSNI} + TransportClientConfig {socksProxy = socks, tcpConnectTimeout = tOut, tcpKeepAlive = keepAlive, logTLSErrors, clientCredentials = Nothing, clientALPN, useSNI} where tOut = netTimeoutInt tcpConnectTimeout nm + socks = useSocksProxy socksMode + keepAlive = (\ka -> if isJust socks then ka {unackedDataTimeout = Nothing} else ka) <$> tcpKeepAlive socksProxy' = (\(SocksProxyWithAuth _ proxy) -> proxy) <$> socksProxy useSocksProxy SMAlways = socksProxy' useSocksProxy SMOnion = case host of diff --git a/src/Simplex/Messaging/Transport/KeepAlive.hs b/src/Simplex/Messaging/Transport/KeepAlive.hs index 1d34a27f0..1ebb2a35f 100644 --- a/src/Simplex/Messaging/Transport/KeepAlive.hs +++ b/src/Simplex/Messaging/Transport/KeepAlive.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Transport.KeepAlive setSocketKeepAlive, ) where +import Control.Monad (when) import qualified Data.Aeson.TH as J import Foreign.C (CInt (..)) import Network.Socket @@ -18,7 +19,8 @@ import Simplex.Messaging.Parsers (defaultJSON) data KeepAliveOpts = KeepAliveOpts { keepIdle :: Int, keepIntvl :: Int, - keepCnt :: Int + keepCnt :: Int, + unackedDataTimeout :: Maybe Bool } deriving (Eq, Show) @@ -27,7 +29,8 @@ defaultKeepAliveOpts = KeepAliveOpts { keepIdle = 30, keepIntvl = 15, - keepCnt = 4 + keepCnt = 4, + unackedDataTimeout = Nothing } _SOL_TCP :: CInt @@ -53,8 +56,12 @@ _TCP_KEEPCNT = 16 #if defined(darwin_HOST_OS) foreign import capi "netinet/tcp.h value TCP_KEEPALIVE" _TCP_KEEPIDLE :: CInt + +foreign import capi "netinet/tcp.h value TCP_RXT_CONNDROPTIME" _TCP_RXT_CONNDROPTIME :: CInt #else foreign import capi "netinet/tcp.h value TCP_KEEPIDLE" _TCP_KEEPIDLE :: CInt + +foreign import capi "netinet/tcp.h value TCP_USER_TIMEOUT" _TCP_USER_TIMEOUT :: CInt #endif foreign import capi "netinet/tcp.h value TCP_KEEPINTVL" _TCP_KEEPINTVL :: CInt @@ -63,11 +70,21 @@ foreign import capi "netinet/tcp.h value TCP_KEEPCNT" _TCP_KEEPCNT :: CInt #endif +setSocketUnackedDataTimeout :: Socket -> Int -> IO () +#if defined(mingw32_HOST_OS) +setSocketUnackedDataTimeout _ _ = pure () +#elif defined(darwin_HOST_OS) +setSocketUnackedDataTimeout sock = setSocketOption sock (SockOpt _SOL_TCP _TCP_RXT_CONNDROPTIME) +#else +setSocketUnackedDataTimeout sock seconds = setSocketOption sock (SockOpt _SOL_TCP _TCP_USER_TIMEOUT) (seconds * 1000) +#endif + setSocketKeepAlive :: Socket -> KeepAliveOpts -> IO () -setSocketKeepAlive sock KeepAliveOpts {keepCnt, keepIdle, keepIntvl} = do +setSocketKeepAlive sock KeepAliveOpts {keepCnt, keepIdle, keepIntvl, unackedDataTimeout} = do setSocketOption sock KeepAlive 1 setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPIDLE) keepIdle setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPINTVL) keepIntvl setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPCNT) keepCnt + when (unackedDataTimeout == Just True) $ setSocketUnackedDataTimeout sock $ keepIdle + keepIntvl * keepCnt $(J.deriveJSON defaultJSON ''KeepAliveOpts) diff --git a/tests/CoreTests/KeepAliveTests.hs b/tests/CoreTests/KeepAliveTests.hs new file mode 100644 index 000000000..b8d0c58bc --- /dev/null +++ b/tests/CoreTests/KeepAliveTests.hs @@ -0,0 +1,42 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE NumericUnderscores #-} + +module CoreTests.KeepAliveTests where + +import Control.Exception (bracket, handle) +import Control.Monad (forever) +import qualified Data.ByteString.Char8 as B +import Foreign.C (CInt) +import Foreign.C.Error (Errno (..), eTIMEDOUT) +import GHC.IO.Exception (IOException (..)) +import Network.Socket +import Network.Socket.ByteString (sendAll) +import Simplex.Messaging.Transport.KeepAlive +import System.Info (os) +import System.Timeout (timeout) +import Test.Hspec hiding (fit, it) +import Util + +keepAliveTests :: Spec +keepAliveTests = linuxOnly $ it "should fail connection with data not accepted by peer only with unackedDataTimeout" testUnackedDataTimeout + where + linuxOnly t = if os == "linux" then t else skip "Linux only" t + +testUnackedDataTimeout :: IO () +testUnackedDataTimeout = do + sendToPeerNotReading (Just True) `shouldReturn` Just (Just timedOut) + sendToPeerNotReading Nothing `shouldReturn` Nothing + where + Errno timedOut = eTIMEDOUT + +sendToPeerNotReading :: Maybe Bool -> IO (Maybe (Maybe CInt)) +sendToPeerNotReading unackedDataTimeout = + bracket (socket AF_INET Stream defaultProtocol) close $ \srv -> do + bind srv $ SockAddrInet 0 $ tupleToHostAddress (127, 0, 0, 1) + listen srv 1 + addr <- getSocketName srv + bracket (socket AF_INET Stream defaultProtocol) close $ \c -> do + setSocketKeepAlive c KeepAliveOpts {keepIdle = 1, keepIntvl = 1, keepCnt = 1, unackedDataTimeout} + connect c addr + bracket (fst <$> accept srv) close $ \_ -> + timeout 8_000000 $ handle (pure . ioe_errno) $ forever $ sendAll c $ B.replicate 65536 'x' diff --git a/tests/CoreTests/SOCKSSettings.hs b/tests/CoreTests/SOCKSSettings.hs index a56be966e..64bbb6ea8 100644 --- a/tests/CoreTests/SOCKSSettings.hs +++ b/tests/CoreTests/SOCKSSettings.hs @@ -15,6 +15,7 @@ import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ErrorType, pattern SMPServer) import Simplex.Messaging.Transport.Client +import Simplex.Messaging.Transport.KeepAlive import Test.Hspec hiding (fit, it) import Util @@ -92,11 +93,20 @@ testSocksMode = do transportSocks (Just defaultSocksProxyWithAuth) SMAlways testOnionHost `shouldBe` Just defaultSocksProxy transportSocks (Just defaultSocksProxyWithAuth) SMOnion testPublicHost `shouldBe` Nothing transportSocks (Just defaultSocksProxyWithAuth) SMOnion testOnionHost `shouldBe` Just defaultSocksProxy + it "should remove unackedDataTimeout only if SOCKS proxy is used" $ do + transportUnackedTimeout Nothing SMAlways testPublicHost `shouldBe` Just True + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMOnion testPublicHost `shouldBe` Just True + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMAlways testPublicHost `shouldBe` Nothing + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMOnion testOnionHost `shouldBe` Nothing where transportSocks proxy socksMode = transportSocksCfg defaultNetworkConfig {socksProxy = proxy, socksMode} transportSocksCfg cfg host = let TransportClientConfig {socksProxy} = transportClientConfig cfg NRMInteractive host False Nothing in socksProxy + transportUnackedTimeout proxy socksMode host = + let keepAlive = Just defaultKeepAliveOpts {unackedDataTimeout = Just True} + TransportClientConfig {tcpKeepAlive} = transportClientConfig defaultNetworkConfig {socksProxy = proxy, socksMode, tcpKeepAlive = keepAlive} NRMInteractive host False Nothing + in tcpKeepAlive >>= unackedDataTimeout testIPAddressProtected :: Spec testIPAddressProtected = do diff --git a/tests/Test.hs b/tests/Test.hs index 39e9c7830..cf3184d62 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -11,6 +11,7 @@ import CoreTests.CryptoFileTests import CoreTests.CryptoTests import CoreTests.EncodingTests import CoreTests.EthCryptoTests +import CoreTests.KeepAliveTests import CoreTests.LockTests import CoreTests.MsgStoreTests import CoreTests.RetryIntervalTests @@ -99,6 +100,7 @@ main = do describe "Message store tests" msgStoreTests describe "Server stats tests" serverStatsTests describe "SOCKS settings tests" socksSettingsTests + describe "TCP keep-alive tests" keepAliveTests describe "Store log tests" storeLogTests describe "XFTP store log tests" fileStoreLogTests fileExpirationTests From 83df1454e4928077a9f7e60838678b3e1fa4c5b1 Mon Sep 17 00:00:00 2001 From: Narasimha-sc <166327228+Narasimha-sc@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:16:37 +0000 Subject: [PATCH 101/159] transport: set the unacked-data timeout only on Linux and Android --- plans/2026-11-03-unacked-data-timeout.md | 14 ++------------ src/Simplex/Messaging/Transport/KeepAlive.hs | 6 +----- tests/CoreTests/KeepAliveTests.hs | 3 +++ 3 files changed, 6 insertions(+), 17 deletions(-) diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md index aef26f16b..3b3a9d734 100644 --- a/plans/2026-11-03-unacked-data-timeout.md +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -6,20 +6,14 @@ A client connection to a server that becomes unreachable while data is unacknowl ## Cause -TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed by the OS only after the retransmission limit: `tcp_retries2` = 15, about 15 minutes. +On Linux, TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed by the OS only after the retransmission limit: `tcp_retries2` = 15, about 15 minutes. macOS and iOS keep-alive closes it after the keep-alive time regardless of unacknowledged data. ## Fix - `KeepAliveOpts.unackedDataTimeout :: Maybe Bool`: - `Just True`: on. - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. -- `setSocketKeepAlive`, option on: the socket timeout for unacknowledged data is set to `keepIdle + keepIntvl * keepCnt` seconds (90 s with `defaultKeepAliveOpts`): - - | OS | Socket option | Unit | - |---|---|---| - | Linux, Android | `TCP_USER_TIMEOUT` | ms | - | macOS, iOS | `TCP_RXT_CONNDROPTIME` | s | - | Windows | not set | | +- `setSocketKeepAlive`, option on, Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with `defaultKeepAliveOpts`). macOS, iOS and Windows: not set. - `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. @@ -27,9 +21,5 @@ TCP keep-alive probes are not sent while the connection has unacknowledged or un - Client connections with keep-alive: SMP, NTF and XFTP clients (`transportClientConfig`). - Unchanged: - - connections without the option; - outgoing connections of servers (`defaultNetworkConfig`) and remote control (`defaultTransportClientConfig`): `unackedDataTimeout = Nothing`; - `defaultHTTP2ClientConfig`: keep-alive not set. -- Tests: - - `tests/CoreTests/SOCKSSettings.hs`: the option is removed only with a SOCKS proxy for the host. - - `tests/CoreTests/KeepAliveTests.hs`, Linux only: a client writing to a peer that does not read fails with `ETIMEDOUT` within 8 s with the option and keep-alive time 2 s, and does not fail within 8 s without it. diff --git a/src/Simplex/Messaging/Transport/KeepAlive.hs b/src/Simplex/Messaging/Transport/KeepAlive.hs index 1ebb2a35f..af6e6067c 100644 --- a/src/Simplex/Messaging/Transport/KeepAlive.hs +++ b/src/Simplex/Messaging/Transport/KeepAlive.hs @@ -56,8 +56,6 @@ _TCP_KEEPCNT = 16 #if defined(darwin_HOST_OS) foreign import capi "netinet/tcp.h value TCP_KEEPALIVE" _TCP_KEEPIDLE :: CInt - -foreign import capi "netinet/tcp.h value TCP_RXT_CONNDROPTIME" _TCP_RXT_CONNDROPTIME :: CInt #else foreign import capi "netinet/tcp.h value TCP_KEEPIDLE" _TCP_KEEPIDLE :: CInt @@ -71,10 +69,8 @@ foreign import capi "netinet/tcp.h value TCP_KEEPCNT" _TCP_KEEPCNT :: CInt #endif setSocketUnackedDataTimeout :: Socket -> Int -> IO () -#if defined(mingw32_HOST_OS) +#if defined(mingw32_HOST_OS) || defined(darwin_HOST_OS) setSocketUnackedDataTimeout _ _ = pure () -#elif defined(darwin_HOST_OS) -setSocketUnackedDataTimeout sock = setSocketOption sock (SockOpt _SOL_TCP _TCP_RXT_CONNDROPTIME) #else setSocketUnackedDataTimeout sock seconds = setSocketOption sock (SockOpt _SOL_TCP _TCP_USER_TIMEOUT) (seconds * 1000) #endif diff --git a/tests/CoreTests/KeepAliveTests.hs b/tests/CoreTests/KeepAliveTests.hs index b8d0c58bc..45d7f6c6a 100644 --- a/tests/CoreTests/KeepAliveTests.hs +++ b/tests/CoreTests/KeepAliveTests.hs @@ -6,6 +6,7 @@ module CoreTests.KeepAliveTests where import Control.Exception (bracket, handle) import Control.Monad (forever) import qualified Data.ByteString.Char8 as B +import Data.Time.Clock (diffUTCTime, getCurrentTime) import Foreign.C (CInt) import Foreign.C.Error (Errno (..), eTIMEDOUT) import GHC.IO.Exception (IOException (..)) @@ -24,7 +25,9 @@ keepAliveTests = linuxOnly $ it "should fail connection with data not accepted b testUnackedDataTimeout :: IO () testUnackedDataTimeout = do + start <- getCurrentTime sendToPeerNotReading (Just True) `shouldReturn` Just (Just timedOut) + (`diffUTCTime` start) <$> getCurrentTime >>= (`shouldSatisfy` (>= 2)) sendToPeerNotReading Nothing `shouldReturn` Nothing where Errno timedOut = eTIMEDOUT From 927197eafa8151b299345de53f3ebb4fc9b19a1a Mon Sep 17 00:00:00 2001 From: Narasimha-sc <166327228+Narasimha-sc@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:24:52 +0000 Subject: [PATCH 102/159] transport: move the TCP_USER_TIMEOUT import next to its use --- plans/2026-11-03-unacked-data-timeout.md | 1 - src/Simplex/Messaging/Transport/KeepAlive.hs | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md index 3b3a9d734..1c94a23d2 100644 --- a/plans/2026-11-03-unacked-data-timeout.md +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -14,7 +14,6 @@ On Linux, TCP keep-alive probes are not sent while the connection has unacknowle - `Just True`: on. - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. - `setSocketKeepAlive`, option on, Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with `defaultKeepAliveOpts`). macOS, iOS and Windows: not set. - - `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. ## Scope diff --git a/src/Simplex/Messaging/Transport/KeepAlive.hs b/src/Simplex/Messaging/Transport/KeepAlive.hs index af6e6067c..c6e6d461a 100644 --- a/src/Simplex/Messaging/Transport/KeepAlive.hs +++ b/src/Simplex/Messaging/Transport/KeepAlive.hs @@ -58,8 +58,6 @@ _TCP_KEEPCNT = 16 foreign import capi "netinet/tcp.h value TCP_KEEPALIVE" _TCP_KEEPIDLE :: CInt #else foreign import capi "netinet/tcp.h value TCP_KEEPIDLE" _TCP_KEEPIDLE :: CInt - -foreign import capi "netinet/tcp.h value TCP_USER_TIMEOUT" _TCP_USER_TIMEOUT :: CInt #endif foreign import capi "netinet/tcp.h value TCP_KEEPINTVL" _TCP_KEEPINTVL :: CInt @@ -72,6 +70,8 @@ setSocketUnackedDataTimeout :: Socket -> Int -> IO () #if defined(mingw32_HOST_OS) || defined(darwin_HOST_OS) setSocketUnackedDataTimeout _ _ = pure () #else +foreign import capi "netinet/tcp.h value TCP_USER_TIMEOUT" _TCP_USER_TIMEOUT :: CInt + setSocketUnackedDataTimeout sock seconds = setSocketOption sock (SockOpt _SOL_TCP _TCP_USER_TIMEOUT) (seconds * 1000) #endif From 259438244d374adf84909eb102240eb51ad4732b Mon Sep 17 00:00:00 2001 From: Narasimha-sc <166327228+Narasimha-sc@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:28:25 +0000 Subject: [PATCH 103/159] docs: correct the timeout example in the unacked-data timeout plan --- plans/2026-11-03-unacked-data-timeout.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md index 1c94a23d2..71a563167 100644 --- a/plans/2026-11-03-unacked-data-timeout.md +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -13,7 +13,7 @@ On Linux, TCP keep-alive probes are not sent while the connection has unacknowle - `KeepAliveOpts.unackedDataTimeout :: Maybe Bool`: - `Just True`: on. - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. -- `setSocketKeepAlive`, option on, Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with `defaultKeepAliveOpts`). macOS, iOS and Windows: not set. +- `setSocketKeepAlive`, option on, Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with the default keep-alive values). macOS, iOS and Windows: not set. - `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. ## Scope From 16e7ac37ba3df1b831bf2bd9193e8a735275e930 Mon Sep 17 00:00:00 2001 From: Narasimha-sc <166327228+Narasimha-sc@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:30:29 +0000 Subject: [PATCH 104/159] docs: reword the unacked-data timeout plan --- plans/2026-11-03-unacked-data-timeout.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md index 71a563167..7264b72b5 100644 --- a/plans/2026-11-03-unacked-data-timeout.md +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -2,18 +2,20 @@ ## Problem -A client connection to a server that becomes unreachable while data is unacknowledged is reported as failed after about 15 minutes on Linux and Android. Until then, the client sends into the dead connection. +On Linux and Android, a client connection to a server that becomes unreachable while data is unacknowledged fails only after about 15 minutes. Until then, the client sends into the dead connection. ## Cause -On Linux, TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed by the OS only after the retransmission limit: `tcp_retries2` = 15, about 15 minutes. macOS and iOS keep-alive closes it after the keep-alive time regardless of unacknowledged data. +On Linux and Android, TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed only at the retransmission limit (`tcp_retries2` = 15, about 15 minutes). On macOS and iOS, a connection is closed by keep-alive `keepIdle + keepIntvl * keepCnt` after the last received segment, with or without unacknowledged data. ## Fix - `KeepAliveOpts.unackedDataTimeout :: Maybe Bool`: - `Just True`: on. - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. -- `setSocketKeepAlive`, option on, Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with the default keep-alive values). macOS, iOS and Windows: not set. +- `setSocketKeepAlive`, option on: + - Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with the default keep-alive values). + - macOS, iOS and Windows: not set. - `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. ## Scope From 2eed1964028c0a203acffcf172539354f615f9af Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Sat, 17 Oct 2026 08:25:02 +0900 Subject: [PATCH 105/159] Remove XFTP receive chunks before reporting completion --- src/Simplex/FileTransfer/Agent.hs | 5 ++- tests/XFTPAgent.hs | 65 ++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index 7aeb2f627..be100e3d4 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -321,9 +321,10 @@ runXFTPRcvLocalWorker c Worker {doWork} = do void $ liftError (FILE . FILE_IO . show) $ decryptChunks encSize chunkPaths key nonce $ \_ -> pure destFile case redirect of Nothing -> do + -- RFDONE lets the consumer delete the shared receive prefix. + -- Finish chunk cleanup before publishing completion. + lift $ forM_ tmpPath (removePath <=< toFSFilePath) notify c rcvFileEntityId $ RFDONE fsSavePath - flip catchAllErrors (\e -> logError $ "XFTP rcv worker error: " <> tshow e) $ - lift $ forM_ tmpPath (removePath <=< toFSFilePath) liftIO $ waitUntilForeground c withStore' c (`updateRcvFileComplete` rcvFileId) Just RcvFileRedirect {redirectFileInfo, redirectDbId} -> do diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index 026dfe9de..84d917a16 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -13,6 +13,7 @@ module XFTPAgent where import AgentTests.FunctionalAPITests (get, nGet, pGet, rfGet, runRight, runRight_, sfGet, withAgent, testServerInformation) +import Control.Concurrent.STM (retry) import Control.Logger.Simple import Control.Monad import Control.Monad.Except @@ -28,6 +29,7 @@ import Data.Maybe (fromJust, isJust) import qualified Data.Set as S import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay) import Data.Time.Clock.System (getSystemTime, systemSeconds) +import GHC.Conc (BlockReason (BlockedOnSTM), ThreadStatus (ThreadBlocked), threadStatus) import SMPAgentClient (agentCfg, initAgentServers, noAuthSrvCfg, testDB, testDB2, testDB3, userServers) import SMPClient (testHost2, withStallingServerOn', xit'') import Simplex.FileTransfer.Client (XFTPClientConfig (..)) @@ -40,6 +42,7 @@ import Simplex.FileTransfer.Types (FileErrorType (NO_FILE), RcvFileId, SndFileId import Simplex.Messaging.Agent (AgentClient, testProtocolServer, xftpDeleteRcvFile, xftpDeleteSndFileInternal, xftpDeleteSndFileRemote, xftpPrepareReceiveFile, xftpPrepareSendFile, xftpReceiveFile, xftpSendDescription, xftpStartReceiveFile, xftpStartSendFile, xftpStartWorkers) import qualified Simplex.Messaging.Agent as XA import Simplex.Messaging.Agent.Client (AgentClient (subQ, xftpClients, xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) +import qualified Simplex.Messaging.Agent.Client as AC import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, InitialAgentServers, xftpCfg) import qualified Simplex.Messaging.Agent.Env.SQLite as AEnv import Simplex.Messaging.Agent.Protocol hiding (SFDONE) @@ -59,9 +62,11 @@ import Simplex.Messaging.Protocol (AProtocolType (..), BasicAuth, EntityId (..), import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) import Simplex.Messaging.Server.Information (ServerPublicInfo) import Simplex.Messaging.Transport (EntitlementConfig (..)) -import Simplex.Messaging.Util (tshow, unlessM) +import qualified Simplex.Messaging.TMap as TM +import Simplex.Messaging.Util (ifM, tshow, unlessM) import System.Directory (Permissions (writable), createDirectory, doesDirectoryExist, doesFileExist, getFileSize, getPermissions, listDirectory, removeFile, setPermissions) import System.FilePath (()) +import System.Mem.Weak (deRefWeak) import Test.Hspec hiding (fit, it, xit) import UnliftIO import UnliftIO.Concurrent @@ -85,6 +90,7 @@ xftpAgentTests = it "should send and receive with encrypted local files" testXFTPAgentSendReceiveEncrypted it "should send and receive large file with a redirect" testXFTPAgentSendReceiveRedirect it "should send and receive small file without a redirect" testXFTPAgentSendReceiveNoRedirect + it "should remove received chunks before publishing completion" testXFTPAgentCompletionCleanup it "should receive prepared file only after it is started" testXFTPAgentPrepareReceive it "should send prepared file only after it is started" testXFTPAgentPrepareSend it "should prepare files concurrently in distinct work directories" $ \_ -> testXFTPAgentPrepareSendConcurrently @@ -337,6 +343,63 @@ testXFTPAgentSendReceiveNoRedirect = withXFTPServer $ do inBytes <- B.readFile filePathIn B.readFile out `shouldReturn` inBytes +-- A full event queue is a barrier at RFDONE, after real download/decryption. +-- Holding the not-yet-started local worker lets us install that barrier after +-- draining RFPROG, without sleeps or changing the transfer implementation. +testXFTPAgentCompletionCleanup :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () +testXFTPAgentCompletionCleanup = withXFTPServer $ do + filePathIn <- createRandomFile_ (kb 64) "completion-order" + sentBytes <- B.readFile filePathIn + withAgent 1 agentCfg initAgentServers testDB $ \sndr -> do + runRight_ $ xftpStartWorkers sndr (Just senderFiles) + _ <- runRight $ xftpSendFile sndr 1 (CryptoFile filePathIn Nothing) 1 + sfProgress sndr (kb 128) + (_, _, SFDONE _ (description : _)) <- sfGet sndr + withAgent 2 agentCfg {AEnv.tbqSize = 1} initAgentServers testDB2 $ \rcp -> do + let AEnv.XFTPAgent {AEnv.xftpWorkDir, AEnv.xftpRcvWorkers} = AEnv.xftpAgent $ AC.agentEnv rcp + AEnv.Worker {AEnv.action, AEnv.doWork, AEnv.restarts} <- atomically $ do + writeTVar xftpWorkDir $ Just recipientFiles + workerId <- stateTVar (AC.workerSeq rcp) $ \next -> (next, next + 1) + w <- AEnv.Worker workerId <$> newTMVar () <*> newEmptyTMVar <*> newTVar (AEnv.RestartCount 0 0) + TM.insert Nothing w xftpRcvWorkers + pure w + let releaseWorker = atomically $ void $ tryPutTMVar action Nothing + flip finally releaseWorker $ do + rfId <- runRight $ xftpReceiveFile rcp 1 description Nothing True + rfProgress rcp (kb 128) + [prefixDir] <- listDirectory recipientFiles + let prefixPath = recipientFiles prefixDir + tmpPath = prefixPath "xftp.encrypted" + outputPath = prefixPath "xftp.decrypted" + doesDirectoryExist tmpPath `shouldReturn` True + -- No producer can publish completion until this sentinel is consumed. + atomically $ writeTBQueue (AC.subQ rcp) ("barrier", rfId, AEvt SAERcvFile $ RFPROG 0 (kb 128)) + releaseWorker + weak <- atomically $ readTMVar action >>= maybe retry pure + Just tid <- deRefWeak weak + let awaitPublish = do + blocked <- (== ThreadBlocked BlockedOnSTM) <$> threadStatus tid + decrypted <- + if blocked + then ifM (doesFileExist outputPath) ((== sentBytes) <$> B.readFile outputPath) (pure False) + else pure False + unless (blocked && decrypted) $ yield >> awaitPublish + timeout 10000000 awaitPublish `shouldReturn` Just () + -- This fails on the old order: its worker is blocked in notify while + -- the encrypted chunk directory still exists. + doesDirectoryExist tmpPath `shouldReturn` False + rfGet rcp `shouldReturn` ("barrier", rfId, RFPROG 0 (kb 128)) + rfGet rcp `shouldReturn` ("", rfId, RFDONE outputPath) + -- Model the consumer immediately deleting its completed receive. + xftpDeleteRcvFile rcp rfId + let awaitIdle = do + idle <- atomically $ isEmptyTMVar doWork + blocked <- (== ThreadBlocked BlockedOnSTM) <$> threadStatus tid + unless (idle && blocked) $ yield >> awaitIdle + timeout 10000000 awaitIdle `shouldReturn` Just () + AEnv.restartCount <$> readTVarIO restarts `shouldReturn` 0 + atomically (tryReadTBQueue $ AC.subQ rcp) `shouldReturn` Nothing + testXFTPAgentPrepareReceive :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () testXFTPAgentPrepareReceive = withXFTPServer $ do filePath <- createRandomFile From 17fbbd8731ceb2c3366b092e0feddb4d7860aa07 Mon Sep 17 00:00:00 2001 From: earmark-halt <82045246+earmark-halt@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:26:28 +0000 Subject: [PATCH 106/159] transport: support domain names for SOCKS proxy, fix IPv6 proxy addresses SOCKS proxy only accepted IP addresses, so smp-server failed to start with `socks_proxy = tor:9050`, or with `localhost:9050` suggested in the generated config. IPv6 proxy addresses were accepted, but connection failed, because socksConnect always opens IPv4 socket. Fixes #1828 Co-Authored-By: Claude Opus 5.5 --- src/Simplex/Messaging/Transport/Client.hs | 44 ++++++++--- tests/CoreTests/SOCKSSettings.hs | 91 ++++++++++++++++++++++- 2 files changed, 122 insertions(+), 13 deletions(-) diff --git a/src/Simplex/Messaging/Transport/Client.hs b/src/Simplex/Messaging/Transport/Client.hs index 3e328e08c..f3febf2e0 100644 --- a/src/Simplex/Messaging/Transport/Client.hs +++ b/src/Simplex/Messaging/Transport/Client.hs @@ -233,11 +233,25 @@ defaultSMPPort :: PortNumber defaultSMPPort = 5223 connectSocksClient :: SocksProxy -> Maybe SocksCredentials -> SocksHostAddress -> ServiceName -> IO Socket -connectSocksClient (SocksProxy addr) socksCreds hostAddr _port = do - let port = socksPort _port - fst <$> case socksCreds of - Just creds -> socksConnectAuth (defaultSocksConf addr) (SocksAddress hostAddr port) creds - _ -> socksConnect (defaultSocksConf addr) (SocksAddress hostAddr port) +connectSocksClient proxy socksCreds hostAddr _port = do + let port = if null _port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe _port + destAddr = SocksAddress hostAddr port + E.bracketOnError connectProxy close $ \sock -> do + conf <- defaultSocksConf <$> getPeerName sock + sock <$ case socksCreds of + Just creds -> socksConnectWithSocketAuth sock conf destAddr creds + _ -> socksConnectWithSocket sock conf destAddr + where + -- socksConnect from Network.Socks5 always opens IPv4 socket + connectProxy = case proxy of + SocksProxy addr -> + E.bracketOnError (socket (sockFamily addr) Stream defaultProtocol) close $ \sock -> + connect sock addr $> sock + SocksProxyDomain host port -> connectTCPClient host (show port) + sockFamily = \case + SockAddrInet {} -> AF_INET + SockAddrInet6 {} -> AF_INET6 + SockAddrUnix {} -> AF_UNIX socksPort :: ServiceName -> PortNumber socksPort port = if null port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe port @@ -251,7 +265,9 @@ defaultSocksProxyWithAuth = SocksProxyWithAuth SocksIsolateByAuth defaultSocksPr defaultSocksProxy :: SocksProxy defaultSocksProxy = SocksProxy $ SockAddrInet 9050 $ tupleToHostAddress defaultSocksHost -newtype SocksProxy = SocksProxy SockAddr +data SocksProxy + = SocksProxy SockAddr + | SocksProxyDomain HostName PortNumber deriving (Eq) data SocksProxyWithAuth = SocksProxyWithAuth SocksAuth SocksProxy @@ -263,19 +279,23 @@ data SocksAuth | SocksIsolateByAuth -- this is default deriving (Eq, Show) -instance Show SocksProxy where show (SocksProxy addr) = show addr +instance Show SocksProxy where + show = \case + SocksProxy addr -> show addr + SocksProxyDomain host port -> host <> ":" <> show port instance StrEncoding SocksProxy where strEncode = B.pack . show strP = do host <- fromMaybe (THIPv4 defaultSocksHost) <$> optional strP port <- fromMaybe 9050 <$> optional (A.char ':' *> (fromInteger <$> A.decimal)) - SocksProxy <$> socksAddr port host + socksProxyP port host where - socksAddr port = \case - THIPv4 addr -> pure $ SockAddrInet port $ tupleToHostAddress addr - THIPv6 addr -> pure $ SockAddrInet6 port 0 addr 0 - _ -> fail "SOCKS5 host should be IPv4 or IPv6 address" + socksProxyP port = \case + THIPv4 addr -> pure $ SocksProxy $ SockAddrInet port $ tupleToHostAddress addr + THIPv6 addr -> pure $ SocksProxy $ SockAddrInet6 port 0 addr 0 + THDomainName host -> pure $ SocksProxyDomain host port + THOnionHost _ -> fail "SOCKS5 host cannot be onion address" instance StrEncoding SocksProxyWithAuth where strEncode (SocksProxyWithAuth auth proxy) = strEncode auth <> strEncode proxy diff --git a/tests/CoreTests/SOCKSSettings.hs b/tests/CoreTests/SOCKSSettings.hs index 64bbb6ea8..2ee06d221 100644 --- a/tests/CoreTests/SOCKSSettings.hs +++ b/tests/CoreTests/SOCKSSettings.hs @@ -3,19 +3,35 @@ {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} module CoreTests.SOCKSSettings where -import Network.Socket (SockAddr (..), tupleToHostAddress) +import Control.Concurrent (forkIO) +import Control.Concurrent.Async (race_, withAsync) +import Control.Concurrent.STM +import qualified Control.Exception as E +import Control.Monad +import qualified Data.ByteString as BS +import Data.ByteString.Char8 (ByteString) +import qualified Data.ByteString.Char8 as B +import Data.Time.Clock (getCurrentTime) +import Data.Word (Word8) +import Network.Socket +import Network.Socket.ByteString (recv, sendAll) +import SMPClient (testKeyHash, testPort, withSmpServerConfigOn) +import qualified SMPClient import Simplex.Messaging.Agent.Client (ipAddressProtected) import Simplex.Messaging.Client import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ErrorType, pattern SMPServer) +import Simplex.Messaging.Transport (TLS, transport) import Simplex.Messaging.Transport.Client import Simplex.Messaging.Transport.KeepAlive +import Simplex.Messaging.Transport.Server (startTCPServer) import Test.Hspec hiding (fit, it) import Util @@ -25,6 +41,7 @@ socksSettingsTests = do describe "socksMode setting, independent of hostMode setting" testSocksMode describe "ipAddressProtected, consistent with chosen host and socksMode" testIPAddressProtected describe "socks proxy address encoding" testSocksProxyEncoding + describe "socks proxy connection" testSocksProxyConnection testPublicHost :: TransportHost testPublicHost = "smp.example.com" @@ -137,7 +154,11 @@ testSocksProxyEncoding = do strDecode "[::1]:9050" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0) strDecode "[::1]:8080" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 8080 0 (0, 0, 0, 1) 0) strDecode "[fd12:3456:789a:1::1]:8080" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "localhost" `shouldBe` authIsolate (SocksProxyDomain "localhost" 9050) + strDecode "localhost:9050" `shouldBe` authIsolate (SocksProxyDomain "localhost" 9050) + strDecode "tor:9150" `shouldBe` authIsolate (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth SocksIsolateByAuth defaultSocksProxy) `shouldBe` "127.0.0.1:9050" + strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxyDomain "tor" 9150)) `shouldBe` "tor:9150" strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "[::1]:9050" strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "[fd12:3456:789a:1::1]:8080" it "should decode SOCKS proxy without credentials" $ do @@ -148,7 +169,9 @@ testSocksProxyEncoding = do strDecode "@1.1.1.1" `shouldBe` authNull (SocksProxy $ SockAddrInet 9050 $ tupleToHostAddress (1, 1, 1, 1)) strDecode "@127.0.0.1:9050" `shouldBe` authNull defaultSocksProxy strDecode "@[fd12:3456:789a:1::1]:8080" `shouldBe` authNull (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "@tor:9150" `shouldBe` authNull (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth SocksAuthNull defaultSocksProxy) `shouldBe` "@127.0.0.1:9050" + strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxyDomain "tor" 9150)) `shouldBe` "@tor:9150" strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "@[::1]:9050" strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "@[fd12:3456:789a:1::1]:8080" it "should decode SOCKS proxy with credentials" $ do @@ -160,6 +183,72 @@ testSocksProxyEncoding = do strDecode "user:pass@127.0.0.1:9050" `shouldBe` authUser defaultSocksProxy strDecode "user:pass@fd12:3456:789a:1::1" `shouldBe` authUser (SocksProxy $ SockAddrInet6 9050 0 (0xfd123456, 0x789a0001, 0, 1) 0) strDecode "user:pass@[fd12:3456:789a:1::1]:8080" `shouldBe` authUser (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "user:pass@tor:9150" `shouldBe` authUser (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth auth defaultSocksProxy) `shouldBe` "user:pass@127.0.0.1:9050" + strEncode (SocksProxyWithAuth auth (SocksProxyDomain "tor" 9150)) `shouldBe` "user:pass@tor:9150" strEncode (SocksProxyWithAuth auth (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "user:pass@[::1]:9050" strEncode (SocksProxyWithAuth auth (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "user:pass@[fd12:3456:789a:1::1]:8080" + +testSocksProxyConnection :: Spec +testSocksProxyConnection = do + it "should connect via SOCKS proxy with IPv4 address" $ socksConnectionTest "127.0.0.1" "127.0.0.1:5050" + it "should connect via SOCKS proxy with IPv6 address" $ socksConnectionTest "::1" "[::1]:5050" + it "should connect via SOCKS proxy with domain name" $ socksConnectionTest "127.0.0.1" "localhost:5050" + it "should connect via SOCKS proxy with domain name without credentials" $ socksConnectionTest "127.0.0.1" "@localhost:5050" + +socksConnectionTest :: HostName -> ByteString -> IO () +socksConnectionTest proxyHost proxy = + withSmpServerConfigOn (transport @TLS) SMPClient.cfg testPort $ \_ -> + withSocksProxy proxyHost "5050" $ \destinations -> do + g <- C.newRandom + ts <- getCurrentTime + let networkConfig = defaultNetworkConfig {socksProxy = either error Just $ strDecode proxy, socksMode = SMAlways} + srv = SMPServer ["localhost"] testPort testKeyHash + (c :: SMPClient) <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {networkConfig} [] Nothing ts (\_ -> pure ()) + closeProtocolClient c + readTVarIO destinations `shouldReturn` ["localhost:5001"] + +-- | Minimal SOCKS5 proxy (RFC 1928) for CONNECT command to domain names, +-- with optional username/password authentication (RFC 1929), that records requested destinations. +withSocksProxy :: HostName -> ServiceName -> (TVar [ByteString] -> IO a) -> IO a +withSocksProxy host port action = do + destinations <- newTVarIO [] + started <- newEmptyTMVarIO + E.bracket (startTCPServer started (Just host) port) close $ \sock -> + withAsync (forever $ accept sock >>= \(conn, _) -> forkIO $ socksConnection destinations conn `E.finally` close conn) $ \_ -> + action destinations + +socksConnection :: TVar [ByteString] -> Socket -> IO () +socksConnection destinations conn = do + [5, nMethods] <- recvBytes 2 + methods <- recvBytes nMethods + if 2 `elem` methods + then do + sendAll conn "\5\2" + [1, uLen] <- recvBytes 2 + [pLen] <- recvBytes uLen >> recvBytes 1 + void $ recvBytes pLen + sendAll conn "\1\0" + else sendAll conn "\5\0" + [5, 1, 0, 3, hLen] <- recvBytes 5 + host <- B.unpack . BS.pack <$> recvBytes hLen + [p1, p2] <- recvBytes 2 + let port = show (fromIntegral p1 * 256 + fromIntegral p2 :: Int) + atomically $ modifyTVar' destinations (<> [B.pack $ host <> ":" <> port]) + addr : _ <- getAddrInfo (Just defaultHints {addrSocketType = Stream}) (Just host) (Just port) + E.bracket (socket (addrFamily addr) Stream defaultProtocol) close $ \dst -> do + connect dst $ addrAddress addr + sendAll conn "\5\0\0\1\0\0\0\0\0\0" + race_ (relay conn dst) (relay dst conn) + where + recvBytes :: Word8 -> IO [Word8] + recvBytes n = BS.unpack <$> recvAll (fromIntegral n) + recvAll n + | n <= 0 = pure "" + | otherwise = do + s <- recv conn n + when (BS.null s) $ E.throwIO $ userError "connection closed" + (s <>) <$> recvAll (n - BS.length s) + relay from to = do + s <- recv from 16384 + unless (BS.null s) $ sendAll to s >> relay from to From be21c722a26c1a584bb57a8578c33a6db8f218bd Mon Sep 17 00:00:00 2001 From: earmark-halt <82045246+earmark-halt@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:26:22 +0000 Subject: [PATCH 107/159] build: check out git submodules when building from source blst and libbbs sources are git submodules since #1794, but the build instructions and the reproduce script cloned the repository without them, so the build failed with "does not exist: cbits/blst/src/server.c". Fixes #1855 Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 3 +++ README.md | 2 ++ scripts/simplexmq-reproduce-builds.sh | 3 ++- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 06b59e6e1..89310f553 100644 --- a/Dockerfile +++ b/Dockerfile @@ -45,6 +45,9 @@ WORKDIR /project ARG APP RUN if [ -z "$APP" ]; then printf "Please spcify \$APP build-arg.\n"; exit 1; fi +# Check that git submodules are checked out +RUN if [ ! -f cbits/blst/src/server.c ] || [ ! -f cbits/libbbs/src/bbs.c ]; then printf "Git submodules are missing, run: git submodule update --init --recursive\n"; exit 1; fi + # Compile app RUN cabal update RUN cabal build exe:$APP diff --git a/README.md b/README.md index 3ece2a4c2..3258bb0a9 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ On Linux, you can build smp server using Docker. git clone https://github.com/simplex-chat/simplexmq cd simplexmq git checkout stable + git submodule update --init --recursive DOCKER_BUILDKIT=1 docker build -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For xmp-server DOCKER_BUILDKIT=1 docker build -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server ``` @@ -234,6 +235,7 @@ On Linux, you can build smp server using Docker. git clone https://github.com/simplex-chat/simplexmq cd simplexmq git checkout stable + git submodule update --init --recursive cabal update cabal build exe:smp-server exe:xftp-server ``` diff --git a/scripts/simplexmq-reproduce-builds.sh b/scripts/simplexmq-reproduce-builds.sh index ec480b369..38638afd3 100755 --- a/scripts/simplexmq-reproduce-builds.sh +++ b/scripts/simplexmq-reproduce-builds.sh @@ -23,7 +23,8 @@ mkdir -p "$init_dir/$TAG-$repo_name/from-source" "$init_dir/$TAG-$repo_name/preb git -C "$tempdir" clone "$repo.git" &&\ cd "$tempdir/${repo_name}" &&\ - git checkout "$TAG" + git checkout "$TAG" &&\ + git submodule update --init --recursive for os in 22.04 24.04; do os_url="$(printf '%s' "$os" | tr '.' '_')" From 8fdcb08008f72653024ca56a762731f7c6707380 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 29 Sep 2026 20:48:36 +0000 Subject: [PATCH 108/159] agent: decrypt messages out of order after disabling KEM --- src/Simplex/Messaging/Crypto/Ratchet.hs | 3 +-- tests/AgentTests/DoubleRatchetTests.hs | 9 +++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Crypto/Ratchet.hs b/src/Simplex/Messaging/Crypto/Ratchet.hs index 056d36372..2a60cec7e 100644 --- a/src/Simplex/Messaging/Crypto/Ratchet.hs +++ b/src/Simplex/Messaging/Crypto/Ratchet.hs @@ -928,8 +928,7 @@ rcEncryptHeader rc@Ratchet {rcSnd = Just sr@SndRatchet {rcCKs, rcHKs}, rcDHRs, r rcNs = rcNs + 1, rcSupportKEM = rcSupportKEM', rcEnableKEM = rcEnableKEM', - rcVersion = rcVersion', - rcKEM = if pqEnc_ == Just PQEncOff then (\rck -> rck {rcKEMs = Nothing}) <$> rcKEM else rcKEM + rcVersion = rcVersion' } pure (msgEncryptKey, rc') where diff --git a/tests/AgentTests/DoubleRatchetTests.hs b/tests/AgentTests/DoubleRatchetTests.hs index 005df8aad..512a9c972 100644 --- a/tests/AgentTests/DoubleRatchetTests.hs +++ b/tests/AgentTests/DoubleRatchetTests.hs @@ -78,6 +78,7 @@ doubleRatchetTests = do describe "message tests, KEM proposed again in reply" $ runMessageTests initRatchetsKEMProposedAgain True it "should disable and re-enable KEM" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableEnableKEM it "should disable and re-enable KEM (always set PQEncryption)" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableEnableKEMStrict + it "should decrypt messages out of order after disabling KEM" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableKEMOutOfOrder it "should enable KEM when it was not enabled in handshake" $ withRatchets_ @X25519 initRatchets testEnableKEM it "should enable KEM when it was not enabled in handshake (always set PQEncryption)" $ withRatchets_ @X25519 initRatchets testEnableKEMStrict @@ -304,6 +305,14 @@ testDisableEnableKEMStrict alice bob _ _ _ = do (alice, "now KEM is enabled") !#>! bob (bob, "KEM is enabled for both sides") !#>! alice +testDisableKEMOutOfOrder :: forall a. (AlgorithmI a, DhAlgorithm a) => TestRatchets a +testDisableKEMOutOfOrder alice bob encrypt decrypt _ = do + Right b1 <- withTVar (encrypt_ (Just PQEncOff)) hasSndKEM bob "disabling KEM" + Right b2 <- encrypt bob "KEM disabled" + Decrypted "KEM disabled" <- decrypt alice b2 + Decrypted "disabling KEM" <- decrypt alice b1 + pure () + testEnableKEM :: forall a. (AlgorithmI a, DhAlgorithm a) => TestRatchets a testEnableKEM alice bob _ _ _ = do (bob, "hello alice") \#> alice From ec837c7025deea94848f6eae1d5101898d6d565c Mon Sep 17 00:00:00 2001 From: Passw Date: Wed, 19 Aug 2026 09:47:47 +0800 Subject: [PATCH 109/159] fix executableName from 'file-server' to 'xftp-server' after execute `xftp-server init ...` the pop-out indicates ``` ... Run `file-server start` to start server. ``` should be ``` ... Run `xftp-server start` to start server. ``` --- src/Simplex/FileTransfer/Server/Main.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Simplex/FileTransfer/Server/Main.hs b/src/Simplex/FileTransfer/Server/Main.hs index d1d78d12d..dd5f65d61 100644 --- a/src/Simplex/FileTransfer/Server/Main.hs +++ b/src/Simplex/FileTransfer/Server/Main.hs @@ -93,7 +93,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do iniFile = combine cfgPath "file-server.ini" serverVersion = "SimpleX XFTP server v" <> simplexmqVersionCommit defaultServerPort = "443" - executableName = "file-server" + executableName = "xftp-server" storeLogFilePath = combine logPath "file-server-store.log" defaultStaticPath = combine logPath "www" runDatabaseCmd cmd ini = case cmd of From 9736a1d1a30a1fef7ab84f7ef66a4f2c686b4a55 Mon Sep 17 00:00:00 2001 From: Ap4sh Date: Fri, 3 Jul 2026 20:21:48 +0200 Subject: [PATCH 110/159] docker: show smp-server init errors --- README.md | 4 ++-- scripts/docker/entrypoint-smp-server | 2 +- src/Simplex/Messaging/Server/Main.hs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3258bb0a9..4419489f1 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im - `smp-server` - You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`: ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -189,7 +189,7 @@ On Linux, you can build smp server using Docker. - `smp-server` - You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`: ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ diff --git a/scripts/docker/entrypoint-smp-server b/scripts/docker/entrypoint-smp-server index 7b1aaac2d..51ba1db94 100755 --- a/scripts/docker/entrypoint-smp-server +++ b/scripts/docker/entrypoint-smp-server @@ -63,7 +63,7 @@ if [ ! -f "${confd}/smp-server.ini" ]; then --store-log \ --daily-stats \ --source-code \ - "$@" > /dev/null 2>&1 + "$@" > /dev/null # Fix path to certificates if [ -n "${WEB_MANUAL}" ]; then diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 63ea31edd..c3e67d1cf 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -341,7 +341,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = s -> case strDecode $ encodeUtf8 $ T.pack s of Right auth -> pure . Just $ ServerPassword auth - _ -> putStrLn "Invalid password. Only latin letters, digits and symbols other than '@' and ':' are allowed" >> serverPassword + _ -> putStrLn "Invalid password. Passwords can contain printable ASCII characters except whitespace, '@', ':' and '/'" >> serverPassword checkInitOptions InitOptions {sourceCode, serverInfo, operatorCountry, hostingCountry} = do let err_ | isNothing sourceCode && hasServerInfo serverInfo = From db5c00194ffac0e405a405045aa506dc3085bc67 Mon Sep 17 00:00:00 2001 From: Hmm Date: Mon, 16 Jun 2025 16:58:20 +0000 Subject: [PATCH 111/159] Fix typo in Init.hs --- src/Simplex/Messaging/Server/Main/Init.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index 82dcd8bf6..fad3a042b 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -83,7 +83,7 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> ("enable = " <> onOff enableStoreLog <> "\n\n") <> "# Queue storage mode: `memory` or `database` (to store queue records in PostgreSQL database).\n\ \# `memory` - in-memory persistence, with optional append-only log (`enable = on`).\n\ - \# `database`- PostgreSQL databass (requires `store_messages = database`).\n\ + \# `database`- PostgreSQL database (requires `store_messages = database`).\n\ \store_queues = memory\n\n\ \# Database connection settings for PostgreSQL database (`store_queues = database`).\n" <> iniDbOpts dbOptions defaultDBOpts From ef5f232f7b337d728640c39f47ee3608d481dc51 Mon Sep 17 00:00:00 2001 From: sh-agents <350651734+sh-agents@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:32:03 +0000 Subject: [PATCH 112/159] resolver: read .simplex addresses from .env --- scripts/resolver/.env.example | 6 ++++++ scripts/resolver/README.md | 7 ++++--- scripts/resolver/docker-compose.yml | 6 +++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/scripts/resolver/.env.example b/scripts/resolver/.env.example index f3bcdcc00..880983d32 100644 --- a/scripts/resolver/.env.example +++ b/scripts/resolver/.env.example @@ -30,3 +30,9 @@ TRUSTED_NODE_URL=https://mainnet-checkpoint-sync.attestant.io # SNRC_LOG_COLOR=always # coloured `docker compose logs` # SNRC_LOG_LEVEL=debug # also log health checks and idle connections # SNRC_TRUSTED_PROXIES=172.16.0.0/12 # behind a reverse proxy on the host; see README + +# .simplex contracts on mainnet; unset, .simplex names answer 400. See README, +# "Configuring addresses". +# SNRC_REGISTRY_SIMPLEX=0xa7f6497be2f1aa41aa2db55aba8a6e0145dff0d2 +# SNRC_REGISTRAR_SIMPLEX=0x44052f7dc9c1cef20b0319a6b75288988dbb12a1 +# SNRC_CONTROLLER_SIMPLEX=0x8005011c6e966656cdb9a222e9a4792600a37219 # proxy diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index adc0745d8..923808b06 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -377,8 +377,8 @@ the client will reject. Its `subnameHook()` names the subname registrar, whose `reservedNames`, which is where `reasonCode` comes from. With no controller a held-back name reads as not reserved, and no name can be priced. -All three default to the mainnet `.testing` deployment. `.simplex` is unset -until it is deployed. +All three default to the mainnet `.testing` deployment. `.simplex` has no +default; `.env.example` lists its mainnet addresses. Newer contracts, which `.simplex` will run, keep `reservedNames` in a **name policy** (`SimplexNamePolicy`), with the same `Reason`, and their controller @@ -403,7 +403,8 @@ here. To override any of them, set `SNRC_REGISTRY_`, `SNRC_REGISTRAR_` or `SNRC_CONTROLLER_` on the `resolver` service in `docker-compose.yml`, or -as env vars when you run the script directly. +as env vars when you run the script directly. With docker compose, the +`.simplex` ones can be set in `.env`. ### Load and scaling diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index a0978b6b6..b285a47db 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -154,14 +154,14 @@ services: # (mainnet `.testing`; `.simplex` unconfigured). Set explicitly here # only if you're deploying against a different network or contract. # SNRC_REGISTRY_TESTING: 0x... - # SNRC_REGISTRY_SIMPLEX: 0x... # Registrar and controller, same cascade. Without the registrar `status` # is "unknown"; without the controller a reserved name is "unregistered". # SNRC_REGISTRAR_TESTING: 0x... - # SNRC_REGISTRAR_SIMPLEX: 0x... # SNRC_CONTROLLER_TESTING: 0x... - # SNRC_CONTROLLER_SIMPLEX: 0x... # Set in .env (see .env.example); unset or empty means the resolver's default. + SNRC_REGISTRY_SIMPLEX: ${SNRC_REGISTRY_SIMPLEX:-} + SNRC_REGISTRAR_SIMPLEX: ${SNRC_REGISTRAR_SIMPLEX:-} + SNRC_CONTROLLER_SIMPLEX: ${SNRC_CONTROLLER_SIMPLEX:-} SNRC_WORKERS: ${SNRC_WORKERS:-} SNRC_RPC_TIMEOUT: ${SNRC_RPC_TIMEOUT:-} SNRC_LOG_FORMAT: ${SNRC_LOG_FORMAT:-} From 144a5b16682e5aeb127198e27f31c195b2c593ce Mon Sep 17 00:00:00 2001 From: sh-agents <350651734+sh-agents@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:11:22 +0000 Subject: [PATCH 113/159] resolver: wait for the node instead of exiting --- scripts/resolver/README.md | 9 +-- scripts/resolver/docker-compose.yml | 6 +- scripts/resolver/service/snrc-resolve.py | 26 +++++-- scripts/resolver/service/test_snrc_resolve.py | 70 +++++++++++++++++-- 4 files changed, 92 insertions(+), 19 deletions(-) diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index 923808b06..0a344face 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -389,9 +389,10 @@ so the read reverts. A read that reverts, answers nothing, names no policy or fails with an RPC error is logged as `no_name_policy`, and reservations are read from the controller. For a controller that has a name policy, every lookup under its TLD then answers 502 until a restart: after an RPC error, or when the node -has not yet reached the controller or its `setNamePolicy`. A node that -does not answer stops the resolver, and the container restarts. After the -controller's owner calls `setNamePolicy`, restart the resolver. +has not yet reached the controller or its `setNamePolicy`. While the node +does not answer, the resolver does not listen and reads again, waiting 1 s, +then twice as long each time, up to 30 s. After the controller's owner calls +`setNamePolicy`, restart the resolver. The controller default is the **proxy**, not `SimplexControllerImpl`. Storage lives in the proxy, so the implementation address answers nothing. The two @@ -449,7 +450,7 @@ Each event is one line: UTC time, level, event name, then `key=value` fields. | `client_gone` | warn | the caller hung up before the answer, usually an smp-server past its timeout | | `http_error` | warn | a malformed request; idle keep-alive timeouts only at debug | | `request_failed` | error | a request failed unexpectedly, with its traceback | -| `startup_failed` | error | the node did not answer the startup read of the name policies; the container restarts | +| `node_unavailable` | warn | the node did not answer the startup read of the name policies; read again after `retry_s` | | `worker_exited`, `worker_failed` | error | a worker stopped; the others stop too, so the container restarts | | `stopping` | info | stopped by a signal | diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index b285a47db..aa526f34a 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -141,9 +141,9 @@ services: # starting before reth has finished snapshot replay just yields a few # 502s until the chain is queryable. The upstream reth image doesn't # ship a HEALTHCHECK, so we can't gate on healthy. - # The startup read of the name policies is the exception: until reth - # answers, the resolver exits and restarts, and a TLD whose name policy - # reth has not yet reached answers 502 until the resolver restarts + # The startup read of the name policies is the exception: the resolver + # listens only once reth answers it, and a TLD whose name policy reth has + # not yet reached answers 502 until the resolver restarts # (README, "Configuring addresses"). reth: condition: service_started diff --git a/scripts/resolver/service/snrc-resolve.py b/scripts/resolver/service/snrc-resolve.py index b017f196e..ae545fcaf 100755 --- a/scripts/resolver/service/snrc-resolve.py +++ b/scripts/resolver/service/snrc-resolve.py @@ -99,6 +99,9 @@ PORT = int(os.environ.get("SNRC_PORT", "8000")) # The smp-server gives up after 3 s, so a slower call only holds a thread. RPC_TIMEOUT_S = float(os.environ.get("SNRC_RPC_TIMEOUT", "") or 5) +# Waits between startup reads while the node is not answering, doubling up to the maximum. +STARTUP_RETRY_MIN_S = 1 +STARTUP_RETRY_MAX_S = 30 # The node and the beacon client usually share the host, so not every core. MAX_DEFAULT_WORKERS = 4 WORKERS = int(os.environ.get("SNRC_WORKERS", "") or min(MAX_DEFAULT_WORKERS, os.cpu_count() or 1)) @@ -548,6 +551,18 @@ def name_policies() -> dict: return policies +def wait_for_name_policies() -> dict: + """name_policies(), read again until the node answers, as it starts with the resolver.""" + delay = STARTUP_RETRY_MIN_S + while True: + try: + return name_policies() + except Exception as e: + log_event(logging.WARNING, "node_unavailable", error=type(e).__name__, message=str(e), retry_s=delay) + time.sleep(delay) + delay = min(delay * 2, STARTUP_RETRY_MAX_S) + + def pricing_params(tld: str): """What it costs to register a name under this TLD, in US cents, or None when no controller or price oracle is configured.""" @@ -1551,11 +1566,10 @@ def stop_and_exit(signum, frame): def main(): setup_logging() - try: - NAME_POLICIES.update(name_policies()) - except Exception: - log_event(logging.ERROR, "startup_failed", exc_info=True) - sys.exit(1) + # as PID 1 in the container, the process ignores SIGTERM without a handler + signal.signal(signal.SIGTERM, stop_on) + signal.signal(signal.SIGINT, stop_on) + NAME_POLICIES.update(wait_for_name_policies()) log_event( logging.INFO, "listening", @@ -1570,8 +1584,6 @@ def main(): if WORKERS > 1: supervise(WORKERS) else: - signal.signal(signal.SIGTERM, stop_on) - signal.signal(signal.SIGINT, stop_on) serve(reuse_port=False) diff --git a/scripts/resolver/service/test_snrc_resolve.py b/scripts/resolver/service/test_snrc_resolve.py index 46d756769..9bf85e9c0 100644 --- a/scripts/resolver/service/test_snrc_resolve.py +++ b/scripts/resolver/service/test_snrc_resolve.py @@ -22,7 +22,8 @@ import time import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from urllib.error import HTTPError +from unittest import mock +from urllib.error import HTTPError, URLError from urllib.parse import urlparse from urllib.request import Request, urlopen @@ -1503,6 +1504,22 @@ def test_a_node_that_does_not_answer_stops_the_read(self): with self.assertRaises(HTTPError): snrc.name_policies() + def test_a_node_that_does_not_answer_is_read_again_with_doubling_waits(self): + self.node.status = 502 + self.node.chain.answers[snrc.name_policy_call(FakeChain.CONTROLLER)] = "0x" + snrc.encode_uint(int(FakeChain.NAME_POLICY, 16)) + waits = [] + + def sleep(seconds): + waits.append(seconds) + if len(waits) == 7: + self.node.status = 200 + + with mock.patch.object(time, "sleep", sleep), self.assertLogs("snrc_resolve", "WARNING") as logs: + self.assertEqual(snrc.wait_for_name_policies(), {"testing": FakeChain.NAME_POLICY}) + self.assertEqual(waits, [1, 2, 4, 8, 16, 30, 30]) + self.assertEqual([(r.getMessage(), r.fields["error"], r.fields["retry_s"]) for r in logs.records], + [("node_unavailable", "HTTPError", wait) for wait in waits]) + class Aggregate3Tests(unittest.TestCase): def test_calls_are_encoded_as_multicall3_reads_them(self): @@ -1774,14 +1791,57 @@ def test_an_idle_connection_is_closed(self): class StartupTests(unittest.TestCase): - def test_a_node_that_does_not_answer_stops_the_service(self): + def test_the_service_waits_for_the_node_and_then_listens(self): + node = FakeNode() + self.addCleanup(node.stop) + node.status = 502 + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + env = dict(os.environ, SNRC_RPC=node.url, SNRC_BIND="127.0.0.1", SNRC_PORT=str(port), SNRC_WORKERS="1") + service = subprocess.Popen([sys.executable, os.path.join(_HERE, "snrc-resolve.py")], env=env, stderr=subprocess.PIPE, text=True) + self.addCleanup(service.stderr.close) + self.addCleanup(service.wait) + self.addCleanup(service.kill) + # the stderr reads below end at EOF if the service hangs + watchdog = threading.Timer(10, service.kill) + watchdog.start() + self.addCleanup(watchdog.cancel) + + self.assertRegex(service.stderr.readline(), r"WARN node_unavailable error=HTTPError .* retry_s=1$") + node.status = 200 + lines = iter(service.stderr.readline, "") + self.assertTrue(any("INFO listening" in line for line in lines), "the service did not start listening") + self.assertIsNone(service.poll()) + # `listening` is logged before the socket is bound + deadline = time.monotonic() + 5 + while True: + try: + with urlopen(f"http://127.0.0.1:{port}/health", timeout=5) as res: + self.assertTrue(json.loads(res.read())["ok"]) + break + except URLError: + if time.monotonic() > deadline: + raise + time.sleep(0.05) + + def test_stopping_the_service_while_it_waits_for_the_node(self): node = FakeNode() self.addCleanup(node.stop) node.status = 502 env = dict(os.environ, SNRC_RPC=node.url, SNRC_WORKERS="1") - service = subprocess.run([sys.executable, os.path.join(_HERE, "snrc-resolve.py")], env=env, stderr=subprocess.PIPE, text=True, timeout=10) - self.assertEqual(service.returncode, 1) - self.assertRegex(service.stderr, r"ERROR startup_failed") + service = subprocess.Popen([sys.executable, os.path.join(_HERE, "snrc-resolve.py")], env=env, stderr=subprocess.PIPE, text=True) + self.addCleanup(service.stderr.close) + self.addCleanup(service.wait) + self.addCleanup(service.kill) + watchdog = threading.Timer(10, service.kill) + watchdog.start() + self.addCleanup(watchdog.cancel) + + self.assertIn("node_unavailable", service.stderr.readline()) + service.send_signal(signal.SIGTERM) + self.assertEqual(service.wait(timeout=5), 0) + self.assertRegex(service.stderr.read(), r"INFO stopping signal=SIGTERM") @unittest.skipUnless(sys.platform.startswith("linux"), "reads worker processes from /proc") From bf9698ac03a290986a967068d38ac18523dc88cb Mon Sep 17 00:00:00 2001 From: sh-agents <350651734+sh-agents@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:15:25 +0000 Subject: [PATCH 114/159] resolver: give reth 2 minutes to stop --- scripts/resolver/docker-compose.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index aa526f34a..55c84f739 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -102,6 +102,9 @@ services: --rpc.gascap 50000000 --port 30303 --discovery.port 30303 + # Docker's default 10 s can kill reth before it flushes its database, and it + # then unwinds its last blocks on the next start. + stop_grace_period: 2m restart: unless-stopped nimbus: From 2395938acaa42445deb6933a868de495e482789e Mon Sep 17 00:00:00 2001 From: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:39:26 +0000 Subject: [PATCH 115/159] resolver: resolve .simplex names on mainnet by default --- scripts/resolver/.env.example | 2 +- scripts/resolver/README.md | 9 ++++----- scripts/resolver/docker-compose.yml | 2 +- scripts/resolver/service/snrc-resolve.py | 16 ++++++++++------ 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/scripts/resolver/.env.example b/scripts/resolver/.env.example index 880983d32..58dd029b4 100644 --- a/scripts/resolver/.env.example +++ b/scripts/resolver/.env.example @@ -5,7 +5,7 @@ # Chain settings. # ============================================================================ -# Ethereum network: mainnet (the SNRC `.testing` contracts live on mainnet) +# Ethereum network: mainnet (the SNRC `.testing` and `.simplex` contracts are on mainnet) # or holesky (test). Mainnet full sync needs ~1 day and ~1.2 TB NVMe. NETWORK=mainnet diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index 0a344face..14464e65c 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -1,7 +1,7 @@ # Self-hosted SNRC stack One `docker compose up` runs the self-hosted SimpleX Namespace (SNRC) backend -against **Ethereum mainnet** (where the `.testing` contracts live): +against **Ethereum mainnet** (where the `.testing` and `.simplex` contracts are deployed): | # | Component | What it does | |---|---|---| @@ -63,7 +63,7 @@ curl -s -X POST http://127.0.0.1:8545 \ **2. resolver is healthy:** ```sh curl -s http://127.0.0.1:8000/health | jq -# → {"ok": true, "rpc": "http://reth:8545", "registries": {"testing": "0x…", "simplex": ""}, +# → {"ok": true, "rpc": "http://reth:8545", "registries": {"testing": "0x…", "simplex": "0x…"}, # "blockNumber": 23400000, "chainLagSeconds": 12} ``` @@ -377,10 +377,9 @@ the client will reject. Its `subnameHook()` names the subname registrar, whose `reservedNames`, which is where `reasonCode` comes from. With no controller a held-back name reads as not reserved, and no name can be priced. -All three default to the mainnet `.testing` deployment. `.simplex` has no -default; `.env.example` lists its mainnet addresses. +All three default to the mainnet deployments of `.testing` and `.simplex`. -Newer contracts, which `.simplex` will run, keep `reservedNames` in a **name +Newer contracts, which `.simplex` runs, keep `reservedNames` in a **name policy** (`SimplexNamePolicy`), with the same `Reason`, and their controller answers no `reservedNames` call. The resolver reads each controller's `namePolicy()` once at startup, before its workers start, and reads reservations diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index 55c84f739..1cf8e8053 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -154,7 +154,7 @@ services: SNRC_RPC: http://reth:8545 SNRC_BIND: 0.0.0.0 # Registry addresses cascade through the script's own defaults - # (mainnet `.testing`; `.simplex` unconfigured). Set explicitly here + # (mainnet `.testing` and `.simplex`). Set explicitly here # only if you're deploying against a different network or contract. # SNRC_REGISTRY_TESTING: 0x... # Registrar and controller, same cascade. Without the registrar `status` diff --git a/scripts/resolver/service/snrc-resolve.py b/scripts/resolver/service/snrc-resolve.py index ae545fcaf..934c507ad 100755 --- a/scripts/resolver/service/snrc-resolve.py +++ b/scripts/resolver/service/snrc-resolve.py @@ -38,13 +38,14 @@ (default: mainnet, 0x58fc46996d975c57883564648bda5206d1a0102b) SNRC_REGISTRY_SIMPLEX ENSRegistry for the .simplex deployment - (default: empty — TLD not yet deployed) + (default: mainnet, + 0x3ce23ef6a00d89105299b52aadd72b92681414be) SNRC_REGISTRAR_ BaseRegistrar (ERC-721) for the TLD; expiry and status - (default: mainnet for .testing, empty for .simplex) + (default: mainnet) SNRC_CONTROLLER_ SimplexController (proxy) for the TLD; reservations, read from the policy its `namePolicy()` names, if any, and through its `prices()` oracle what registering costs - (default: mainnet for .testing, empty for .simplex) + (default: mainnet) SNRC_PORT Listen port (default: 8000) SNRC_BIND Bind address (default: 0.0.0.0) SNRC_WORKERS Worker processes sharing the port (default: CPU count, at most 4) @@ -127,13 +128,15 @@ REGISTRIES = { "testing": os.environ.get("SNRC_REGISTRY_TESTING", "") or "0x58fc46996d975c57883564648bda5206d1a0102b", # mainnet .testing - "simplex": os.environ.get("SNRC_REGISTRY_SIMPLEX", ""), # not deployed yet + "simplex": os.environ.get("SNRC_REGISTRY_SIMPLEX", "") + or "0x3ce23ef6a00d89105299b52aadd72b92681414be", # mainnet .simplex } REGISTRARS = { "testing": os.environ.get("SNRC_REGISTRAR_TESTING", "") or "0xef47eb4384b46c89e4482a677c2cbcbd2a6fd85a", # mainnet .testing - "simplex": os.environ.get("SNRC_REGISTRAR_SIMPLEX", ""), # not deployed yet + "simplex": os.environ.get("SNRC_REGISTRAR_SIMPLEX", "") + or "0x4c0589dbc22862babb25eb72d11bba49d84aabe8", # mainnet .simplex } CONTROLLERS = { @@ -141,7 +144,8 @@ # Proxy address, not SimplexControllerImpl: storage is held by the proxy. # Recorded in deployments.json as ETHRegistrarController. or "0xeeb9b6bf5fb68fb726005f7ba549c2f4b32f2dad", # mainnet .testing - "simplex": os.environ.get("SNRC_CONTROLLER_SIMPLEX", ""), # not deployed yet + "simplex": os.environ.get("SNRC_CONTROLLER_SIMPLEX", "") + or "0x68fab655a0204865a2f3ab3a607037e09648c92b", # mainnet .simplex } # The name policy each TLD's controller names, which holds its reservations in From 83e55e7eae78a5249ccbc3e73da5c37bf60536a3 Mon Sep 17 00:00:00 2001 From: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:44:57 +0000 Subject: [PATCH 116/159] resolver: test an unconfigured TLD with one that has no defaults --- scripts/resolver/service/test_snrc_resolve.py | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/scripts/resolver/service/test_snrc_resolve.py b/scripts/resolver/service/test_snrc_resolve.py index 9bf85e9c0..71ae21ce8 100644 --- a/scripts/resolver/service/test_snrc_resolve.py +++ b/scripts/resolver/service/test_snrc_resolve.py @@ -1568,36 +1568,36 @@ def request(self, path, headers=None, level="INFO"): return record def test_a_request_is_logged_with_its_outcome(self): - record = self.request("/v2/resolve/x.simplex") + record = self.request("/v2/resolve/x.nosuchtld") fields = record.fields self.assertEqual(record.levelname, "INFO") self.assertEqual( (fields["client"], fields["method"], fields["path"], fields["status"], fields["worker"]), - ("127.0.0.1", "GET", "/v2/resolve/x.simplex", 400, os.getpid()), + ("127.0.0.1", "GET", "/v2/resolve/x.nosuchtld", 400, os.getpid()), ) self.assertGreater(fields["bytes"], 0) self.assertGreaterEqual(fields["ms"], 0) def test_a_trusted_proxy_names_the_client(self): snrc.TRUSTED_PROXIES = (ipaddress.ip_network("127.0.0.1/32"),) - record = self.request("/v2/resolve/x.simplex", {"X-Forwarded-For": "203.0.113.7"}) + record = self.request("/v2/resolve/x.nosuchtld", {"X-Forwarded-For": "203.0.113.7"}) self.assertEqual(record.fields["client"], "203.0.113.7") def test_any_other_peer_cannot_name_itself(self): - record = self.request("/v2/resolve/x.simplex", {"X-Forwarded-For": "203.0.113.7"}) + record = self.request("/v2/resolve/x.nosuchtld", {"X-Forwarded-For": "203.0.113.7"}) self.assertEqual(record.fields["client"], "127.0.0.1") def test_a_bad_request_is_not_logged_with_the_previous_ones_fields(self): """On a kept-alive connection the handler still held the last request's path and size.""" with self.assertLogs("snrc_resolve", "INFO") as logs: with socket.create_connection(self.server.server_address, timeout=5) as sock: - sock.sendall(b"GET /v2/resolve/x.simplex HTTP/1.1\r\nHost: x\r\n\r\n") + sock.sendall(b"GET /v2/resolve/x.nosuchtld HTTP/1.1\r\nHost: x\r\n\r\n") sock.recv(65536) sock.sendall(b"BOGUS\r\n\r\n") while sock.recv(65536): pass first, second = [r for r in logs.records if r.getMessage() == "request"] - self.assertEqual(first.fields["path"], "/v2/resolve/x.simplex") + self.assertEqual(first.fields["path"], "/v2/resolve/x.nosuchtld") self.assertEqual((second.fields["status"], second.fields["path"], second.fields["bytes"], second.fields["ms"]), (400, None, None, None)) def test_health_checks_are_logged_only_at_debug(self): @@ -1631,33 +1631,33 @@ def exchange(self, head: bytes, body: bytes = b"") -> bytes: break return data - SMUGGLED = b"GET /v2/resolve/y.simplex HTTP/1.1\r\nHost: x\r\n\r\n" + SMUGGLED = b"GET /v2/resolve/y.nosuchtld HTTP/1.1\r\nHost: x\r\n\r\n" def test_a_body_is_refused_and_the_connection_closed(self): - data = self.exchange(b"GET /v2/resolve/x.simplex HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(self.SMUGGLED), self.SMUGGLED) + data = self.exchange(b"GET /v2/resolve/x.nosuchtld HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(self.SMUGGLED), self.SMUGGLED) self.assertEqual(data.count(b"HTTP/1.1 "), 1) self.assertIn(b"HTTP/1.1 400 ", data) self.assertIn(b"Connection: close", data) - self.assertNotIn(b"y.simplex", data) + self.assertNotIn(b"y.nosuchtld", data) def test_a_length_after_a_malformed_header_line_is_still_seen(self): """Python stops parsing headers at a malformed line and keeps the rest as payload.""" - data = self.exchange(b"GET /v2/resolve/x.simplex HTTP/1.1\r\nX-Junk : 1\r\nContent-Length: %d\r\n\r\n" % len(self.SMUGGLED), self.SMUGGLED) + data = self.exchange(b"GET /v2/resolve/x.nosuchtld HTTP/1.1\r\nX-Junk : 1\r\nContent-Length: %d\r\n\r\n" % len(self.SMUGGLED), self.SMUGGLED) self.assertEqual(data.count(b"HTTP/1.1 "), 1) self.assertIn(b"unexpectedBody", data) - self.assertNotIn(b"y.simplex", data) + self.assertNotIn(b"y.nosuchtld", data) def test_a_chunked_body_is_refused_and_the_connection_closed(self): chunked = b"%x\r\n" % len(self.SMUGGLED) + self.SMUGGLED + b"\r\n0\r\n\r\n" - data = self.exchange(b"GET /v2/resolve/x.simplex HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n", chunked) + data = self.exchange(b"GET /v2/resolve/x.nosuchtld HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n", chunked) self.assertEqual(data.count(b"HTTP/1.1 "), 1) - self.assertNotIn(b"y.simplex", data) + self.assertNotIn(b"y.nosuchtld", data) def test_an_empty_body_keeps_the_connection(self): conn = http.client.HTTPConnection(*self.server.server_address, timeout=5) answers = [] for _ in range(2): - conn.request("GET", "/v2/resolve/x.simplex", headers={"Content-Length": "0"}) + conn.request("GET", "/v2/resolve/x.nosuchtld", headers={"Content-Length": "0"}) res = conn.getresponse() answers.append((res.status, json.loads(res.read())["error"], conn.sock)) conn.close() @@ -1765,7 +1765,7 @@ def test_requests_share_one_connection_without_delay(self): conn = http.client.HTTPConnection(*self.server.server_address, timeout=5) start = time.monotonic() for i in range(20): - conn.request("GET", "/v2/resolve/x.simplex") + conn.request("GET", "/v2/resolve/x.nosuchtld") res = conn.getresponse() res.read() self.assertEqual((res.version, res.status), (11, 400)) From 39f3359119aa1cd5112870abfb8fffd10a0b036c Mon Sep 17 00:00:00 2001 From: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:51:14 +0000 Subject: [PATCH 117/159] resolver: document the .simplex proxies and the name policy check --- scripts/resolver/README.md | 31 ++++++++++++++++-------- scripts/resolver/service/snrc-resolve.py | 4 +-- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index 14464e65c..f0420e2ad 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -46,8 +46,8 @@ docker compose logs --tail=20 reth ``` This is the long pole (~1 day on mainnet). Until reth is synced the resolver -returns `502`. A TLD whose controller has a name policy then still answers `502` -until `docker compose restart resolver` (see Configuring addresses). +returns `502`. `.simplex`, whose controller has a name policy, then still answers +`502` until `docker compose restart resolver` (see Configuring addresses). ## Verify @@ -83,6 +83,14 @@ curl -s http://127.0.0.1:8000/v2/resolve/foobar.testing | jq # → {"type":"registered","expires":1780000000,"graceUntil":…,"nameRecord":{…}} ``` +**5. a reservation read from `.simplex`'s name policy:** +```sh +curl -s http://127.0.0.1:8000/v2/resolve/simplex.simplex | jq +# → {"lastBlockTs":…,"registration":{"type":"reserved","reservedReason":"internal"}} +``` + +A `502` here while check 4 passes requires `docker compose restart resolver`. + **Wire your smp-server:** in its `[NAMES]` section set `resolver_endpoint: http://127.0.0.1:8000` (no auth needed for loopback). @@ -119,7 +127,7 @@ The resolver (`snrc-resolve.py`, host `127.0.0.1:8000`) is also runnable standalone for local dev (no Docker), via [`uv`](https://docs.astral.sh/uv/): ```sh -uv run scripts/resolver/service/snrc-resolve.py # defaults to local reth + mainnet .testing +uv run scripts/resolver/service/snrc-resolve.py # defaults to local reth + mainnet .testing and .simplex ``` Tests and lint run from `scripts/resolver/service`: @@ -393,13 +401,16 @@ does not answer, the resolver does not listen and reads again, waiting 1 s, then twice as long each time, up to 30 s. After the controller's owner calls `setNamePolicy`, restart the resolver. -The controller default is the **proxy**, not `SimplexControllerImpl`. Storage -lives in the proxy, so the implementation address answers nothing. The two -deployment files use different names for that proxy: -`deployments.mainnet.testing.json` records it under the ENS role name -`ETHRegistrarController`, and `verification.mainnet.testing.json` calls it -`SimplexControllerProxy`. Both are the same address, and it is the one used -here. +Each default is the address `deployments.mainnet..json` records, which is +the **proxy** of an upgradeable contract: the controller for `.testing`, all +three for `.simplex`. Storage lives in the proxy, so an implementation address +holds no names: a registrar implementation reports every name as never +registered. The two deployment files use different names for a proxy: +`deployments.mainnet..json` records the controller under the ENS role name +`ETHRegistrarController`, and `verification.mainnet..json` calls it +`SimplexControllerProxy`; for `.simplex` the registry and the registrar are +`ENSRegistryProxy` and `BaseRegistrarImplementationProxy` there. Each pair is +one address, and it is the one used here. To override any of them, set `SNRC_REGISTRY_`, `SNRC_REGISTRAR_` or `SNRC_CONTROLLER_` on the `resolver` service in `docker-compose.yml`, or diff --git a/scripts/resolver/service/snrc-resolve.py b/scripts/resolver/service/snrc-resolve.py index 934c507ad..3186ef75b 100755 --- a/scripts/resolver/service/snrc-resolve.py +++ b/scripts/resolver/service/snrc-resolve.py @@ -119,8 +119,8 @@ ) # Each TLD is its own SNRC deployment with its own ENSRegistry. Dispatch -# happens on the rightmost label of the queried name. Empty / unset means -# "not deployed" — requests for that TLD return 400 with a clear error. +# happens on the rightmost label of the queried name. A TLD without an entry +# answers 400 tldNotConfigured. # `... or "..."` makes the script's defaults the single source of truth: # unset AND empty-string both fall through to the literal. docker-compose # can therefore pass `SNRC_REGISTRY_TESTING=${SNRC_REGISTRY_TESTING:-}` From 36ec0b7e307b13d15eef745253c6a6a3fe5da9d8 Mon Sep 17 00:00:00 2001 From: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:05:02 +0000 Subject: [PATCH 118/159] resolver: test the .simplex defaults; document the image rebuild --- scripts/resolver/README.md | 29 ++++++++++--------- scripts/resolver/docker-compose.yml | 5 ++-- scripts/resolver/service/test_snrc_resolve.py | 8 +++++ 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index f0420e2ad..d26c0675c 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -46,8 +46,8 @@ docker compose logs --tail=20 reth ``` This is the long pole (~1 day on mainnet). Until reth is synced the resolver -returns `502`. `.simplex`, whose controller has a name policy, then still answers -`502` until `docker compose restart resolver` (see Configuring addresses). +returns `502`. `.simplex`, whose controller has a name policy, can then still +answer `502` until `docker compose restart resolver` (see Configuring addresses). ## Verify @@ -80,7 +80,7 @@ curl -s http://127.0.0.1:8000/resolve/foobar.testing | jq **4. the route your router will call** (check 3 passes on an older resolver too): ```sh curl -s http://127.0.0.1:8000/v2/resolve/foobar.testing | jq -# → {"type":"registered","expires":1780000000,"graceUntil":…,"nameRecord":{…}} +# → {"lastBlockTs":…,"registration":{"type":"registered","expires":1780000000,"graceUntil":…,"nameRecord":{…}}} ``` **5. a reservation read from `.simplex`'s name policy:** @@ -108,6 +108,8 @@ A `502` here while check 4 passes requires `docker compose restart resolver`. - **All images track `:latest`** (reth, nimbus) — you get upstream fixes on each `docker compose pull`; re-run the verify checks after pulling. +- The resolver image contains the script: after updating this directory, run + `docker compose up -d --build resolver`, then checks 2 and 5. - All ports bind to loopback; expose only what you put behind a TLS reverse proxy. ## Teardown @@ -401,21 +403,20 @@ does not answer, the resolver does not listen and reads again, waiting 1 s, then twice as long each time, up to 30 s. After the controller's owner calls `setNamePolicy`, restart the resolver. -Each default is the address `deployments.mainnet..json` records, which is -the **proxy** of an upgradeable contract: the controller for `.testing`, all -three for `.simplex`. Storage lives in the proxy, so an implementation address -holds no names: a registrar implementation reports every name as never -registered. The two deployment files use different names for a proxy: -`deployments.mainnet..json` records the controller under the ENS role name -`ETHRegistrarController`, and `verification.mainnet..json` calls it -`SimplexControllerProxy`; for `.simplex` the registry and the registrar are -`ENSRegistryProxy` and `BaseRegistrarImplementationProxy` there. Each pair is -one address, and it is the one used here. +Each default is the address that `deployments.mainnet..json` records. For +an upgradeable contract that address is the **proxy**: the controller of +`.testing` and all three of `.simplex`. Storage lives in the proxy, so an +implementation address holds no names: a registrar implementation reports every +name as never registered. `verification.mainnet..json` names the proxies +differently: `ETHRegistrarController` is `SimplexControllerProxy` there, and for +`.simplex`, `ENSRegistry` and `BaseRegistrarImplementation` are `ENSRegistryProxy` +and `BaseRegistrarImplementationProxy`. Its entries `ENSRegistry@…` and +`BaseRegistrarImplementation@…` are the implementations. To override any of them, set `SNRC_REGISTRY_`, `SNRC_REGISTRAR_` or `SNRC_CONTROLLER_` on the `resolver` service in `docker-compose.yml`, or as env vars when you run the script directly. With docker compose, the -`.simplex` ones can be set in `.env`. +`.simplex` ones can be set in `.env`. An empty value means the default. ### Load and scaling diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index 1cf8e8053..84f844b0c 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -157,8 +157,9 @@ services: # (mainnet `.testing` and `.simplex`). Set explicitly here # only if you're deploying against a different network or contract. # SNRC_REGISTRY_TESTING: 0x... - # Registrar and controller, same cascade. Without the registrar `status` - # is "unknown"; without the controller a reserved name is "unregistered". + # SNRC_REGISTRY_SIMPLEX: 0x... + # Registrar and controller, same cascade. Unset or empty means the default, + # so every TLD has all three; override the three of a TLD together. # SNRC_REGISTRAR_TESTING: 0x... # SNRC_CONTROLLER_TESTING: 0x... # Set in .env (see .env.example); unset or empty means the resolver's default. diff --git a/scripts/resolver/service/test_snrc_resolve.py b/scripts/resolver/service/test_snrc_resolve.py index 71ae21ce8..6810a1cb5 100644 --- a/scripts/resolver/service/test_snrc_resolve.py +++ b/scripts/resolver/service/test_snrc_resolve.py @@ -2013,3 +2013,11 @@ def test_unknown_settings_are_refused_at_start(self): snrc.setup_logging(self.out) finally: setattr(snrc, setting, saved) + + +class DefaultsTests(unittest.TestCase): + def test_both_tlds_resolve_on_mainnet_by_default(self): + fresh = importlib.util.module_from_spec(_SPEC) + _SPEC.loader.exec_module(fresh) + for table in (fresh.REGISTRIES, fresh.REGISTRARS, fresh.CONTROLLERS): + self.assertEqual(sorted(tld for tld, address in table.items() if address), ["simplex", "testing"]) From b2155be0691a2d3117772987cd534ba4d16d49fb Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:25:40 +0000 Subject: [PATCH 119/159] core: keep receiving from other servers while one is slow to reply --- src/Simplex/Messaging/Agent.hs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index ea227c32c..7940cf7df 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2924,6 +2924,10 @@ ackMessage' c cmdId_ connId msgId rcptInfo_ = Left e -> throwE $ storeError e del :: AM () del = withStore' c $ \db -> deleteMsg db connId (InternalId msgId) >> mapM_ (deleteCommand db) cmdId_ + duplexConn :: Connection cType -> Maybe (Connection 'CDuplex) + duplexConn = \case + conn@DuplexConnection {} -> Just conn + _ -> Nothing sendRcpt :: Connection 'CDuplex -> AM () sendRcpt (DuplexConnection cData _ sqs) = do msg@RcvMsg {msgType, msgReceipt} <- withStore c $ \db -> getRcvMsg db connId $ InternalId msgId From 0734f82dacd944001ec4dfcb588531a3af1542a1 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:50:09 +0000 Subject: [PATCH 120/159] agent: drop redundant lock in service join error and Maybe in ack --- src/Simplex/Messaging/Agent.hs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 7940cf7df..ea227c32c 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2924,10 +2924,6 @@ ackMessage' c cmdId_ connId msgId rcptInfo_ = Left e -> throwE $ storeError e del :: AM () del = withStore' c $ \db -> deleteMsg db connId (InternalId msgId) >> mapM_ (deleteCommand db) cmdId_ - duplexConn :: Connection cType -> Maybe (Connection 'CDuplex) - duplexConn = \case - conn@DuplexConnection {} -> Just conn - _ -> Nothing sendRcpt :: Connection 'CDuplex -> AM () sendRcpt (DuplexConnection cData _ sqs) = do msg@RcvMsg {msgType, msgReceipt} <- withStore c $ \db -> getRcvMsg db connId $ InternalId msgId From dd905adf15c4836e5e2771f1828c73714d60da22 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:29:23 +0000 Subject: [PATCH 121/159] agent: detect server requests made in connection locks --- src/Simplex/Messaging/Agent.hs | 2 +- src/Simplex/Messaging/Agent/Client.hs | 3 ++- src/Simplex/Messaging/Agent/Env/SQLite.hs | 2 ++ tests/SMPAgentClient.hs | 1 + 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index ea227c32c..b32f11685 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -356,7 +356,7 @@ disconnectAgentClient c@AgentClient {agentEnv = Env {ntfSupervisor = ns, xftpAge -- only used in the tests disposeAgentClient :: AgentClient -> IO () -disposeAgentClient c@AgentClient {acThread, agentEnv = Env {store}} = do +disposeAgentClient c@AgentClient {acThread, connLockViolations, agentEnv = Env {store}} = do t_ <- atomically (swapTVar acThread Nothing) $>>= (liftIO . deRefWeak) disconnectAgentClient c mapM_ killThread t_ diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 2ad50723a..0f8b50c6a 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -236,6 +236,7 @@ import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) +import qualified Data.Text as T import Data.Text.Encoding import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) @@ -332,7 +333,7 @@ import System.Mem.Weak (Weak, deRefWeak) import System.Random (randomR) import UnliftIO (QSem, mapConcurrently, newQSem, signalQSem, timeout, waitQSem) import UnliftIO.Async (async) -import UnliftIO.Concurrent (forkIO, mkWeakThreadId) +import UnliftIO.Concurrent (forkIO, mkWeakThreadId, myThreadId) import UnliftIO.Directory (doesFileExist, getTemporaryDirectory, removeFile) import qualified UnliftIO.Exception as E import UnliftIO.STM diff --git a/src/Simplex/Messaging/Agent/Env/SQLite.hs b/src/Simplex/Messaging/Agent/Env/SQLite.hs index 47b4da520..0a8bd9f29 100644 --- a/src/Simplex/Messaging/Agent/Env/SQLite.hs +++ b/src/Simplex/Messaging/Agent/Env/SQLite.hs @@ -171,6 +171,7 @@ data AgentConfig = AgentConfig logStatsInterval :: Int64, cleanupStepInterval :: Int, maxWorkerRestartsPerMin :: Int, + prohibitRequestsInConnLock :: Bool, storedMsgDataTTL :: NominalDiffTime, rcvFilesTTL :: NominalDiffTime, sndFilesTTL :: NominalDiffTime, @@ -250,6 +251,7 @@ defaultAgentConfig = logStatsInterval = 10 * 1000000, -- 10 seconds cleanupStepInterval = 200000, -- 200ms maxWorkerRestartsPerMin = 5, + prohibitRequestsInConnLock = False, storedMsgDataTTL = 21 * nominalDay, rcvFilesTTL = 2 * nominalDay, sndFilesTTL = nominalDay, diff --git a/tests/SMPAgentClient.hs b/tests/SMPAgentClient.hs index feb43387e..0e4b2cacc 100644 --- a/tests/SMPAgentClient.hs +++ b/tests/SMPAgentClient.hs @@ -99,6 +99,7 @@ agentCfg = ntfCfg = defaultNTFClientConfig {qSize = 1, defaultTransport = (ntfTestPort, transport @TLS), networkConfig}, reconnectInterval = fastRetryInterval, persistErrorInterval = 1, + prohibitRequestsInConnLock = True, caCertificateFile = "tests/fixtures/ca.crt", privateKeyFile = "tests/fixtures/server.key", certificateFile = "tests/fixtures/server.crt" From 7210a76b048573b6ae1f48d163c8fa7081726a6e Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:19:52 +0000 Subject: [PATCH 122/159] agent: delete new queue when switch is aborted while it is created --- tests/AgentTests/FunctionalAPITests.hs | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 6b2f8066e..37db897e7 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4489,6 +4489,35 @@ testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer p (timeout 20_000000 (runRight_ $ drainSwitchCompleted a' bId QDRcv) `shouldReturn` Just ()) (timeout 20_000000 (runRight_ $ drainSwitchCompleted b aId QDSnd) `shouldReturn` Just ()) +testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () +testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ changeSwitch b aId + atomically $ putTMVar opened () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitQueueDeleted testStoreLogFile2 + +waitQueueDeleted :: HasCallStack => FilePath -> IO () +waitQueueDeleted storeLogFile = go (50 :: Int) + where + go n = do + records <- B.lines <$> B.readFile storeLogFile + case (count "CREATE " records, count "DELETE " records) of + (1, 1) -> pure () + counts + | n > 0 -> threadDelay 100000 >> go (n - 1) + | otherwise -> expectationFailure $ "the created queue was not deleted: " <> show counts + count tag = length . filter (tag `B.isPrefixOf`) + endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b From bbfb284e79aa3fd2864a2b6bf8570ce5134af6e9 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:25:33 +0000 Subject: [PATCH 123/159] agent: refuse switch start, postpone rotation during ratchet sync --- tests/AgentTests/FunctionalAPITests.hs | 48 +++++++++++++++++++------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 37db897e7..2e5c098db 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4492,19 +4492,18 @@ testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer p testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = withSmpServer ps $ - withAgent 1 agentCfg initAgentServers testDB $ \a -> - withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do - (aId, _) <- runRight $ makeConnection a b - setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] - withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> - withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do - timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () - void . runRight $ changeSwitch b aId - atomically $ putTMVar opened () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) - runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' - waitQueueDeleted testStoreLogFile2 + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withGatedServerOn testPort2 testPort3 $ \accepted opened -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ changeSwitch b aId + atomically $ putTMVar opened () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitQueueDeleted testStoreLogFile2 waitQueueDeleted :: HasCallStack => FilePath -> IO () waitQueueDeleted storeLogFile = go (50 :: Int) @@ -4518,6 +4517,29 @@ waitQueueDeleted storeLogFile = go (50 :: Int) | otherwise -> expectationFailure $ "the created queue was not deleted: " <> show counts count tag = length . filter (tag `B.isPrefixOf`) +testFastSwitchRatchetSyncWhileSecuring :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer ps $ do + a <- getSMPAgentClient' 1 agentCfg initAgentServers testDB + (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ makeConnection a b + setProtocolServers a 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do + _ <- switchConnectionAsync a "" bId + phaseRcv a bId SPStarted [Just RSSendingQADD, Nothing] + withAgent 3 agentCfg initAgentServers testDB2 $ \b -> do + runRight_ $ do + subscribeConnection b aId + phaseSnd b aId SPStarted [Just SSSecuringQueue, Nothing] + disposeAgentClient a + ConnectionStats {ratchetSyncState} <- runRight $ synchronizeRatchet b aId PQSupportOn True + ratchetSyncState `shouldBe` RSStarted + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> do + threadDelay 3000000 + withAgent 4 agentCfg initAgentServers testDB $ \a' -> do + runRight_ $ subscribeConnection a' bId + concurrently_ + (timeout 20_000000 (runRight_ $ drainSwitchCompleted a' bId QDRcv) `shouldReturn` Just ()) + (timeout 20_000000 (runRight_ $ drainSwitchCompleted b aId QDSnd) `shouldReturn` Just ()) + endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b From 686269c641e14598a19539c0c93bb9676f8c2e41 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:27:48 +0000 Subject: [PATCH 124/159] agent: delete reply queue when service request expires while created --- src/Simplex/Messaging/Agent.hs | 14 ++++++++------ src/Simplex/Messaging/Agent/Client.hs | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index b32f11685..f580d75e2 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1873,7 +1873,8 @@ serviceRequest_ c userId cReqUri@(CRContactUri _ addrKeys_) timeout_ doSend = do expiresAt <- addUTCTime reqTimeout <$> liftIO getCurrentTime (connId, _) <- newConnToJoin c userId "" False (Just expiresAt) cReqUri PQSupportOn var <- atomically newEmptyTMVar - atomically $ TM.insert connId var (serviceRequests c) + joining <- newTVarIO False + atomically $ TM.insert connId (var, joining) (serviceRequests c) r <- tryAllErrors $ do doSend connId liftIO $ do @@ -2308,16 +2309,17 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do JOIN (JRServiceReq cReq@(CRContactUri ConnReqUriData {crSmpQueues = q :| _} _) pqEnc signKey_) subMode connInfo -> noServer $ do triedHosts <- newTVarIO S.empty tryCommand . withNextSrv c userId storageSrvs triedHosts [qServer q] $ \srv -> - atomically (TM.lookup connId (serviceRequests c)) >>= \case + atomically (TM.lookup connId (serviceRequests c) >>= mapM (\r@(_, joining) -> r <$ writeTVar joining True)) >>= \case Nothing -> pure () - Just v -> do + Just (v, joining) -> do let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) - `catchAllErrors` \e -> + `catchAllErrors` (\e -> whenM (atomically $ TM.member connId (serviceRequests c)) $ if temporaryOrHostError e then throwE e - else atomically $ void $ tryPutTMVar v $ Left e -- will not overwrite existing result + else atomically $ void $ tryPutTMVar v $ Left e) -- will not overwrite existing result + `allFinally` withConnLock c connId "JOIN service request" (unlessM (atomically $ writeTVar joining False >> TM.member connId (serviceRequests c)) $ deleteConnectionAsync' c True connId) LET confId ownCInfo -> withServer' . tryAtomicCommand $ allowConnection' c (Just cmdId) connId confId ownCInfo >> notify OK ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >>= mapM_ (atomically . writeTBQueue subQ) >> notify OK SWCH -> @@ -4071,7 +4073,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr where dispatchServiceReply result = do found <- atomically $ TM.lookup connId (serviceRequests c) >>= \case - Just var -> tryPutTMVar var result + Just (var, _) -> tryPutTMVar var result Nothing -> pure False unless found $ notify $ ERR $ AGENT $ A_SERVICE ASENoPendingRequest processConf rc' connInfo senderConf = do diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 0f8b50c6a..04079cce5 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -415,7 +415,7 @@ data AgentClient = AgentClient clientId :: Int, agentEnv :: Env, proxySessTs :: TVar UTCTime, - serviceRequests :: TMap ConnId (TMVar (Either AgentErrorType SMP.MsgBody)), + serviceRequests :: TMap ConnId (TMVar (Either AgentErrorType SMP.MsgBody), TVar Bool), smpServersStats :: TMap (UserId, SMPServer) AgentSMPServerStats, xftpServersStats :: TMap (UserId, XFTPServer) AgentXFTPServerStats, ntfServersStats :: TMap (UserId, NtfServer) AgentNtfServerStats, From 176c752d1c6a149b504349f38577c1f2778f782a Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:04:32 +0000 Subject: [PATCH 125/159] tests: check deleted queues in the store log after the server stops --- tests/AgentTests/FunctionalAPITests.hs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 2e5c098db..e4ae7ba9e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4503,18 +4503,24 @@ testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = atomically $ putTMVar opened () timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' - waitQueueDeleted testStoreLogFile2 + waitRcvQueueRecords b 1 + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) -waitQueueDeleted :: HasCallStack => FilePath -> IO () -waitQueueDeleted storeLogFile = go (50 :: Int) +waitRcvQueueRecords :: HasCallStack => AgentClient -> Int -> IO () +waitRcvQueueRecords c n = go (50 :: Int) + where + go i = do + qs :: [(ConnId, Int64)] <- withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, rcv_queue_id FROM rcv_queues") + unless (length qs == n) $ + if i > 0 + then threadDelay 100000 >> go (i - 1) + else expectationFailure $ "receive queue records: " <> show qs + +storeLogQueues :: FilePath -> IO (Int, Int) +storeLogQueues storeLogFile = do + records <- B.lines <$> B.readFile storeLogFile + pure (count "CREATE " records, count "DELETE " records) where - go n = do - records <- B.lines <$> B.readFile storeLogFile - case (count "CREATE " records, count "DELETE " records) of - (1, 1) -> pure () - counts - | n > 0 -> threadDelay 100000 >> go (n - 1) - | otherwise -> expectationFailure $ "the created queue was not deleted: " <> show counts count tag = length . filter (tag `B.isPrefixOf`) testFastSwitchRatchetSyncWhileSecuring :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () From ee66b3d5e3cc78a6956a73536789074329dae1fc Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:04:57 +0000 Subject: [PATCH 126/159] agent: delete expired request connection at once, its late queue on creation --- src/Simplex/Messaging/Agent.hs | 14 ++++++-------- src/Simplex/Messaging/Agent/Client.hs | 2 +- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index f580d75e2..b32f11685 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1873,8 +1873,7 @@ serviceRequest_ c userId cReqUri@(CRContactUri _ addrKeys_) timeout_ doSend = do expiresAt <- addUTCTime reqTimeout <$> liftIO getCurrentTime (connId, _) <- newConnToJoin c userId "" False (Just expiresAt) cReqUri PQSupportOn var <- atomically newEmptyTMVar - joining <- newTVarIO False - atomically $ TM.insert connId (var, joining) (serviceRequests c) + atomically $ TM.insert connId var (serviceRequests c) r <- tryAllErrors $ do doSend connId liftIO $ do @@ -2309,17 +2308,16 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do JOIN (JRServiceReq cReq@(CRContactUri ConnReqUriData {crSmpQueues = q :| _} _) pqEnc signKey_) subMode connInfo -> noServer $ do triedHosts <- newTVarIO S.empty tryCommand . withNextSrv c userId storageSrvs triedHosts [qServer q] $ \srv -> - atomically (TM.lookup connId (serviceRequests c) >>= mapM (\r@(_, joining) -> r <$ writeTVar joining True)) >>= \case + atomically (TM.lookup connId (serviceRequests c)) >>= \case Nothing -> pure () - Just (v, joining) -> do + Just v -> do let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) - `catchAllErrors` (\e -> + `catchAllErrors` \e -> whenM (atomically $ TM.member connId (serviceRequests c)) $ if temporaryOrHostError e then throwE e - else atomically $ void $ tryPutTMVar v $ Left e) -- will not overwrite existing result - `allFinally` withConnLock c connId "JOIN service request" (unlessM (atomically $ writeTVar joining False >> TM.member connId (serviceRequests c)) $ deleteConnectionAsync' c True connId) + else atomically $ void $ tryPutTMVar v $ Left e -- will not overwrite existing result LET confId ownCInfo -> withServer' . tryAtomicCommand $ allowConnection' c (Just cmdId) connId confId ownCInfo >> notify OK ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >>= mapM_ (atomically . writeTBQueue subQ) >> notify OK SWCH -> @@ -4073,7 +4071,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr where dispatchServiceReply result = do found <- atomically $ TM.lookup connId (serviceRequests c) >>= \case - Just (var, _) -> tryPutTMVar var result + Just var -> tryPutTMVar var result Nothing -> pure False unless found $ notify $ ERR $ AGENT $ A_SERVICE ASENoPendingRequest processConf rc' connInfo senderConf = do diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 04079cce5..0f8b50c6a 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -415,7 +415,7 @@ data AgentClient = AgentClient clientId :: Int, agentEnv :: Env, proxySessTs :: TVar UTCTime, - serviceRequests :: TMap ConnId (TMVar (Either AgentErrorType SMP.MsgBody), TVar Bool), + serviceRequests :: TMap ConnId (TMVar (Either AgentErrorType SMP.MsgBody)), smpServersStats :: TMap (UserId, SMPServer) AgentSMPServerStats, xftpServersStats :: TMap (UserId, XFTPServer) AgentXFTPServerStats, ntfServersStats :: TMap (UserId, NtfServer) AgentNtfServerStats, From 9cd9d6714321c3478e82643cd5181e50235fd7d1 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:42:19 +0000 Subject: [PATCH 127/159] agent: refuse switch before its new queue during ratchet sync --- tests/AgentTests/FunctionalAPITests.hs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index e4ae7ba9e..e8e9d8b75 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4506,6 +4506,22 @@ testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = waitRcvQueueRecords b 1 storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testSwitchRatchetSyncBeforeNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchRatchetSyncBeforeNewQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort2 $ \_ -> do + setUserNetworkInfo b $ UserNetworkInfo UNNone False + runRight_ $ do + void $ switchConnectionAsync b "" aId + void $ synchronizeRatchet b aId PQSupportOn True + setUserNetworkInfo b $ UserNetworkInfo UNWifi True + get b =##> \case ("", c, ERR (A.CMD PROHIBITED "switchConnection: send prohibited")) -> c == aId; _ -> False + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + storeLogQueues testStoreLogFile2 `shouldReturn` (0, 0) + waitRcvQueueRecords :: HasCallStack => AgentClient -> Int -> IO () waitRcvQueueRecords c n = go (50 :: Int) where From d677fdd924d821e16c16601d7adb9e7a2ce4fa1f Mon Sep 17 00:00:00 2001 From: brenzi-agent Date: Wed, 4 Nov 2026 07:19:23 +0000 Subject: [PATCH 128/159] ci: lint and test the resolver in the Linux build job when it changes --- .github/workflows/build.yml | 70 +++++++++++++++++++++++-------------- scripts/ci/README.md | 8 ++++- 2 files changed, 51 insertions(+), 27 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0df0a8875..8226a1cec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -33,6 +33,7 @@ jobs: runs-on: ubuntu-latest outputs: reduced: ${{ github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == true || (github.event_name == 'push' && github.ref_type == 'branch' && github.repository != 'simplex-chat/simplexmq') }} + resolver: ${{ steps.changes.outputs.resolver }} steps: - name: Reject a manual run on a tag if: github.event_name == 'workflow_dispatch' && github.ref_type == 'tag' @@ -40,6 +41,33 @@ jobs: echo "::error::A manual run starts on a branch; to retry a release, re-run the jobs of its tag push." exit 1 + - name: Clone project to check changes + if: github.event_name != 'push' + uses: actions/checkout@v3 + with: + fetch-depth: 2 + + - name: Check changes + id: changes + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + case "$GITHUB_EVENT_NAME" in + pull_request) + base=HEAD^1 + ;; + workflow_dispatch) + base=$(gh api "repos/$GITHUB_REPOSITORY/compare/master...$GITHUB_REF_NAME" --jq .merge_base_commit.sha) + git fetch -q --depth=1 origin "$base" + ;; + *) + echo "resolver=true" >> "$GITHUB_OUTPUT" + exit 0 + ;; + esac + git diff --quiet "$base" HEAD -- scripts/resolver/service .github/workflows/build.yml || echo "resolver=true" >> "$GITHUB_OUTPUT" + - name: Clone project if: startsWith(github.ref, 'refs/tags/v') uses: actions/checkout@v3 @@ -95,6 +123,7 @@ jobs: cache_o0: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/stable') }} image_cache: ghcr.io/${{ github.repository_owner }}/simplexmq-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }} source_hashes: dist-newstyle/sources.sha256 + resolver: ${{ needs.maybe-release.outputs.resolver == 'true' && matrix.os == '24.04' && matrix.arch == 'x86-64' }} runs-on: ${{ matrix.runner }} services: &build-services postgres: @@ -152,6 +181,21 @@ jobs: with: submodules: recursive + - name: Set up uv + if: env.resolver == 'true' + # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Lint resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + run: uv run --frozen ruff check . + + - name: Test resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + run: uv run --frozen pytest -v + - name: Set up Docker Buildx if: matrix.should_run == true uses: simplex-chat/docker-setup-buildx-action@v3 @@ -534,29 +578,3 @@ jobs: should_run: true client_postgres: true steps: *build-steps - -# ============================= -# Resolver test job -# ============================= - -# The SNRC resolver is Python, so this job needs none of the Haskell toolchain -# above and runs independently of it. - - resolver-test: - name: "resolver (python)" - runs-on: ubuntu-latest - steps: - - name: Clone project - uses: actions/checkout@v3 - - - name: Set up uv - # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - - - name: Lint - working-directory: scripts/resolver/service - run: uv run --frozen ruff check . - - - name: Test - working-directory: scripts/resolver/service - run: uv run --frozen pytest -v diff --git a/scripts/ci/README.md b/scripts/ci/README.md index e19dd5523..99e3a6967 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -9,7 +9,13 @@ | a push to a draft pull request
a manual run (workflow_dispatch)
a push to master or stable in a fork | reduced | build-reduced: ubuntu-24.04 x86-64, GHC 9.6.3, at -O0 (-O2 on pushes), without the standard build | | a pull request marked ready for review, and later pushes to it
a push to master or stable in simplex-chat/simplexmq
a push of a v* tag | full | build: 5 entries (GHC 8.10.7 and 9.6.3, x86-64 and aarch64), at -O0 on pull requests and -O2 on pushes | -Both builds also run maybe-release and resolver (python). Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. The ubuntu-24.04 x86-64 entry also runs the tests built with `-fclient_postgres -fslow_servers -fconn_lock_checks` (agent with the PostgreSQL store, XFTP servers that delay responses for the slow-server test, and an agent that fails server requests made inside a connection lock, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store". After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. +Both builds also run maybe-release and resolver (python). Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. The ubuntu-24.04 x86-64 entry also runs the tests built with `-fclient_postgres -fslow_servers -fconn_lock_checks` (agent with the PostgreSQL store, XFTP servers that delay responses for the slow-server test, and an agent that fails server requests made inside a connection lock, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store". After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. + +The ubuntu-24.04 x86-64 entry also lints and tests the resolver (scripts/resolver/service, steps "Lint resolver" and "Test resolver"): +- on a push; +- on a pull request or a manual run that changes scripts/resolver/service or build.yml. A manual run is compared with its merge base with master. + +Local resolver run: scripts/resolver/README.md, "Resolver API reference". The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. ## Test selection From a2be97f00cba4d47bbaa6e8b0243ccc2cb93a506 Mon Sep 17 00:00:00 2001 From: brenzi-agent Date: Wed, 4 Nov 2026 08:56:47 +0000 Subject: [PATCH 129/159] ci: test the resolver against a seeded chain and known mainnet names --- .github/workflows/build.yml | 26 +++ .github/workflows/resolver-mainnet.yml | 26 +++ scripts/ci/README.md | 6 +- scripts/resolver/README.md | 7 + scripts/resolver/service/test_ground_truth.py | 156 ++++++++++++++++++ 5 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/resolver-mainnet.yml create mode 100644 scripts/resolver/service/test_ground_truth.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8226a1cec..d77549ee6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -191,9 +191,35 @@ jobs: working-directory: scripts/resolver/service run: uv run --frozen ruff check . + - name: Set up Node + if: env.resolver == 'true' + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Build SNRC contracts + if: env.resolver == 'true' + env: + SNRC_CONTRACTS: ${{ runner.temp }}/snrc + SNRC_CONTRACTS_REPO: https://github.com/brenzi-agent/simplex-namespace-contract + SNRC_CONTRACTS_COMMIT: 6db35cddead2330845262baa7d5ddd2e92ce5a63 + COREPACK_ENABLE_DOWNLOAD_PROMPT: 0 + run: | + git clone -q --filter=blob:none "$SNRC_CONTRACTS_REPO" "$SNRC_CONTRACTS" + cd "$SNRC_CONTRACTS" + git checkout -q "$SNRC_CONTRACTS_COMMIT" + git submodule -q update --init --filter=blob:none ens-contracts + corepack enable + pnpm install --frozen-lockfile + cd ens-contracts + pnpm install --frozen-lockfile + pnpm exec hardhat compile + - name: Test resolver if: env.resolver == 'true' working-directory: scripts/resolver/service + env: + SNRC_CONTRACTS: ${{ runner.temp }}/snrc run: uv run --frozen pytest -v - name: Set up Docker Buildx diff --git a/.github/workflows/resolver-mainnet.yml b/.github/workflows/resolver-mainnet.yml new file mode 100644 index 000000000..e4411a733 --- /dev/null +++ b/.github/workflows/resolver-mainnet.yml @@ -0,0 +1,26 @@ +name: resolver mainnet + +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + pull_request: + paths: + - .github/workflows/resolver-mainnet.yml + +jobs: + mainnet: + name: "resolver on mainnet" + runs-on: ubuntu-latest + steps: + - name: Clone project + uses: actions/checkout@v3 + + - name: Set up uv + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Test known names + working-directory: scripts/resolver/service + env: + SNRC_MAINNET_RPC: ${{ secrets.SNRC_MAINNET_RPC || 'https://ethereum-rpc.publicnode.com' }} + run: uv run --frozen pytest -v test_ground_truth.py -k MainnetTests diff --git a/scripts/ci/README.md b/scripts/ci/README.md index 99e3a6967..7faa50d2d 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -15,7 +15,11 @@ The ubuntu-24.04 x86-64 entry also lints and tests the resolver (scripts/resolve - on a push; - on a pull request or a manual run that changes scripts/resolver/service or build.yml. A manual run is compared with its merge base with master. -Local resolver run: scripts/resolver/README.md, "Resolver API reference". The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. +"Build SNRC contracts" builds the simplex-namespace-contract commit set in the step; test_ground_truth.py deploys it to a Hardhat node, seeds it with scripts/seed-lookup-states.mjs and checks the resolver's answer for each seeded name. + +`resolver-mainnet.yml` checks the resolver's answers for known mainnet names daily, on a manual run and on a pull request that changes it. The RPC is the secret `SNRC_MAINNET_RPC`, or a public endpoint without it. + +Local run: scripts/resolver/README.md, "Resolver API reference". The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. ## Test selection diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index d26c0675c..1ef2cd19b 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -139,6 +139,13 @@ uv run pytest uv run ruff check . ``` +`test_ground_truth.py` runs only with its variables set: `SNRC_CONTRACTS`, a simplex-namespace-contract checkout with `ens-contracts` compiled (the CI step "Build SNRC contracts"), and `SNRC_MAINNET_RPC`, a mainnet JSON-RPC endpoint: + +```sh +SNRC_CONTRACTS=../snrc uv run pytest test_ground_truth.py +SNRC_MAINNET_RPC=https://ethereum-rpc.publicnode.com uv run pytest test_ground_truth.py -k MainnetTests +``` + Dependencies are locked in `uv.lock`; the Docker image installs exactly those. Three routes, versioned separately from the protocol so each only changes when diff --git a/scripts/resolver/service/test_ground_truth.py b/scripts/resolver/service/test_ground_truth.py new file mode 100644 index 000000000..028343c8e --- /dev/null +++ b/scripts/resolver/service/test_ground_truth.py @@ -0,0 +1,156 @@ +import json +import os +import socket +import subprocess +import sys +import time +import unittest +from datetime import datetime, timedelta, timezone +from urllib.error import HTTPError +from urllib.request import urlopen + +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTRACTS = os.environ.get("SNRC_CONTRACTS", "") +MAINNET_RPC = os.environ.get("SNRC_MAINNET_RPC", "") +LOCAL_RPC = "http://127.0.0.1:8545" +LOCAL_OWNER = "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266" +CONTACT = "https://localhost/a#ground-truth" +SIMPLEX_MAINNET = { + "SNRC_REGISTRY_SIMPLEX": "0xa7f6497be2f1aa41aa2db55aba8a6e0145dff0d2", + "SNRC_REGISTRAR_SIMPLEX": "0x44052f7dc9c1cef20b0319a6b75288988dbb12a1", + "SNRC_CONTROLLER_SIMPLEX": "0x8005011c6e966656cdb9a222e9a4792600a37219", +} + + +def get(url): + try: + with urlopen(url, timeout=30) as r: + return r.status, json.load(r) + except HTTPError as e: + return e.code, json.load(e) + + +def wait_for(url, process): + for _ in range(600): + if process.poll() is not None: + raise RuntimeError(f"{process.args[0]} exited with {process.returncode}") + try: + urlopen(url, timeout=1).close() + return + except HTTPError: + return + except OSError: + time.sleep(0.5) + raise TimeoutError(url) + + +def start_resolver(test_class, env): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + process = subprocess.Popen( + [sys.executable, os.path.join(HERE, "snrc-resolve.py")], + env={**os.environ, **env, "SNRC_BIND": "127.0.0.1", "SNRC_PORT": str(port), "SNRC_WORKERS": "1"}, + ) + test_class.addClassCleanup(process.terminate) + url = f"http://127.0.0.1:{port}" + wait_for(url + "/health", process) + return url + + +class GroundTruthTestCase(unittest.TestCase): + def registration(self, name): + status, body = get(f"{self.url}/v2/resolve/{name}") + self.assertEqual(status, 200, body) + return body["lastBlockTs"], body["registration"] + + def assert_registered(self, name, contact=None): + now, reg = self.registration(name) + self.assertEqual(reg["type"], "registered", name) + self.assertGreater(reg["graceUntil"], now) + if contact is not None: + self.assertEqual(reg["nameRecord"]["simplexContact"], contact) + return now, reg + + def assert_type(self, name, type_, **fields): + reg = self.registration(name)[1] + self.assertEqual(reg["type"], type_, name) + for key, value in fields.items(): + self.assertEqual(reg[key], value, name) + + +@unittest.skipUnless(CONTRACTS, "SNRC_CONTRACTS is not set") +class LocalChainTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + start = datetime.now(timezone.utc) - timedelta(days=900) + node = subprocess.Popen( + [os.path.join("node_modules", ".bin", "hardhat"), "--network", "hardhat", "node"], + cwd=os.path.join(CONTRACTS, "ens-contracts"), + env={**os.environ, "HARDHAT_INITIAL_DATE": start.isoformat()}, + stdout=subprocess.DEVNULL, + ) + cls.addClassCleanup(node.terminate) + wait_for(LOCAL_RPC, node) + env = {**os.environ, "SIMPLEX_TLD": "simplex", "RPC_URL": LOCAL_RPC, "CONTACT_LINK": CONTACT} + subprocess.run(["node", "scripts/deploy-local.mjs"], cwd=CONTRACTS, env=env, check=True) + with open(os.path.join(CONTRACTS, "deployments.local.json")) as f: + cls.addrs = json.load(f) + subprocess.run(["node", "scripts/seed-lookup-states.mjs"], cwd=CONTRACTS, env={**env, "ADDRS": json.dumps(cls.addrs)}, check=True) + cls.url = start_resolver(cls, { + "SNRC_RPC": LOCAL_RPC, + "SNRC_MULTICALL": cls.addrs["Multicall"], + "SNRC_REGISTRY_SIMPLEX": cls.addrs["ENSRegistry"], + "SNRC_REGISTRAR_SIMPLEX": cls.addrs["BaseRegistrarImplementation"], + "SNRC_CONTROLLER_SIMPLEX": cls.addrs["ETHRegistrarController"], + }) + + def test_a_live_name_is_registered_with_its_records(self): + now, reg = self.assert_registered("bakery.simplex", [CONTACT]) + self.assertGreater(reg["expires"], now) + self.assertEqual(reg["nameRecord"]["owner"], LOCAL_OWNER) + self.assert_registered("nolink.simplex", []) + + def test_a_name_in_grace_is_registered(self): + now, reg = self.assert_registered("expiring.simplex", [CONTACT]) + self.assertLess(reg["expires"], now) + + def test_a_held_subname_is_registered(self): + reg = self.assert_registered("menu.bakery.simplex")[1] + self.assertEqual(reg["nameRecord"]["name"], "menu.bakery.simplex") + self.assertEqual(reg["nameRecord"]["owner"], self.addrs["SubnameRegistrar"].lower()) + + def test_names_nobody_holds_are_available_at_the_launch_price(self): + pricing = {"registrationPrices": {}, "basePrice": 5000, "minLabelLength": 6} + for name in ("sunflower.simplex", "lapsed.simplex", "menu.expiring.simplex"): + self.assert_type(name, "available", pricing=pricing) + + def test_reserved_names_carry_their_reason(self): + for name, reason in (("simplex.simplex", "internal"), ("brandname.simplex", "trademark"), ("privacy.simplex", "community")): + self.assert_type(name, "reserved", reservedReason=reason) + + def test_v1_answers_each_state_by_its_status(self): + status, body = get(f"{self.url}/resolve/bakery.simplex") + self.assertEqual((status, body["simplexContact"]), (200, [CONTACT])) + for name, code in (("sunflower.simplex", 404), ("lapsed.simplex", 410), ("menu.expiring.simplex", 404)): + self.assertEqual(get(f"{self.url}/resolve/{name}")[0], code, name) + + +@unittest.skipUnless(MAINNET_RPC, "SNRC_MAINNET_RPC is not set") +class MainnetTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + cls.url = start_resolver(cls, {"SNRC_RPC": MAINNET_RPC, **SIMPLEX_MAINNET}) + + def test_known_names_are_registered(self): + self.assert_registered("foobar.testing", ["https://smp16.simplex.im/a#Q_F00BA7"]) + self.assert_registered("bitcoin.testing") + self.assert_registered("evgenypoberezkin.simplex") + + def test_reserved_names_carry_their_reason(self): + for name in ("simplex.testing", "simplex.simplex"): + self.assert_type(name, "reserved", reservedReason="internal") + + def test_a_name_nobody_registered_is_available(self): + for name in ("groundtruthcheck.testing", "groundtruthcheck.simplex"): + self.assert_type(name, "available") From 5c32b31ee6e0523fe41e8388264fc4c0ed83f9c9 Mon Sep 17 00:00:00 2001 From: brenzi-agent Date: Wed, 4 Nov 2026 08:59:27 +0000 Subject: [PATCH 130/159] ci: seed with the subname registrar approved --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d77549ee6..c0fb441bb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -202,7 +202,7 @@ jobs: env: SNRC_CONTRACTS: ${{ runner.temp }}/snrc SNRC_CONTRACTS_REPO: https://github.com/brenzi-agent/simplex-namespace-contract - SNRC_CONTRACTS_COMMIT: 6db35cddead2330845262baa7d5ddd2e92ce5a63 + SNRC_CONTRACTS_COMMIT: ac7c68789b129de925a876b1eafa320c6a095693 COREPACK_ENABLE_DOWNLOAD_PROMPT: 0 run: | git clone -q --filter=blob:none "$SNRC_CONTRACTS_REPO" "$SNRC_CONTRACTS" From 60d5e61fe30a95465cfae9c3fe39981d0311c05c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:20:45 +0000 Subject: [PATCH 131/159] debug --- tests/Test.hs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/Test.hs b/tests/Test.hs index cf3184d62..3cccee4d6 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -69,11 +69,18 @@ import PostgresSchemaDump (postgresSchemaDumpTest) import SMPClient (postgressBracket) #endif +#if MIN_VERSION_base(4,18,0) +import Control.Concurrent (forkIO, threadDelay) +import Control.Monad (forM_, void) +import GHC.Conc.Sync (listThreads, threadLabel, threadStatus) +#endif + logCfg :: LogConfig logCfg = LogConfig {lc_file = Nothing, lc_stderr = True} main :: IO () main = do + dumpThreadsAfter 25 setLogLevel testLogLevel withGlobalLogging logCfg $ do setEnv "APNS_KEY_ID" "H82WD9K9AQ" @@ -212,6 +219,20 @@ main = do describe "Agent SQLite schema dump" schemaDumpTest #endif +dumpThreadsAfter :: Int -> IO () +#if MIN_VERSION_base(4,18,0) +dumpThreadsAfter minutes = void . forkIO $ do + threadDelay $ minutes * 60000000 + ts <- listThreads + putStrLn $ "=== " <> show (length ts) <> " threads after " <> show minutes <> " minutes" + forM_ ts $ \t -> do + s <- threadStatus t + l <- threadLabel t + putStrLn $ show t <> " " <> show s <> " " <> maybe "" id l +#else +dumpThreadsAfter _ = pure () +#endif + hspecInTmpDir :: Spec -> IO () hspecInTmpDir spec = do (config, forest) <- evalSpec defaultConfig spec From 1fbb4b951de7442bd0c02a4dd08cd5d0dad571a9 Mon Sep 17 00:00:00 2001 From: Alexander Bondarenko <486682+dpwiz@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:19:00 +0300 Subject: [PATCH 132/159] tests: detect and mark hung tests as failed --- tests/Test.hs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/Test.hs b/tests/Test.hs index 3cccee4d6..a73025d80 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -22,6 +22,7 @@ import CoreTests.TSessionSubs import CoreTests.TransportTests import CoreTests.UtilTests import CoreTests.VersionRangeTests +import Data.Maybe (fromMaybe) import FileDescriptionTests (fileDescriptionTests) import RSLVTests (rslvTests) import RemoteControl (remoteControlTests) @@ -35,8 +36,11 @@ import Simplex.Messaging.Transport (TLS, Transport (..)) import System.Directory (createDirectoryIfMissing, listDirectory, removePathForcibly) import System.Environment (getArgs, setEnv, withArgs) import System.FilePath (()) +import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Test.Hspec.Core.Runner (defaultConfig, evalSpec, evaluateResult, readConfig, runSpecForest) +import Test.Hspec.Core.Spec +import Test.Hspec.Runner (configPrintSlowItems) import Util import XFTPAgent import XFTPCLI (xftpCLIConcurrentTests, xftpCLIFileTests) @@ -95,6 +99,7 @@ main = do . aroundAll_ (postgressBracket ntfTestServerDBConnectInfo) . aroundAll_ (postgressBracket testXFTPDBConnectInfo) #endif + . deadline (120 * 1000000) $ do parallel $ do describe "Core tests" $ do @@ -235,7 +240,7 @@ dumpThreadsAfter _ = pure () hspecInTmpDir :: Spec -> IO () hspecInTmpDir spec = do - (config, forest) <- evalSpec defaultConfig spec + (config, forest) <- evalSpec defaultConfig {configPrintSlowItems = Just 10} spec config' <- getArgs >>= readConfig config withTmpDir (withArgs [] $ runSpecForest forest config') >>= evaluateResult @@ -243,3 +248,11 @@ withTmpDir :: IO a -> IO a withTmpDir = bracket_ (createDirectoryIfMissing False tmpDir >> clearTmpDir) clearTmpDir where clearTmpDir = listDirectory tmpDir >>= mapM_ (removePathForcibly . (tmpDir )) + +-- | Abort tests after a reasonable deadline. +deadline :: Int -> SpecWith b -> SpecWith b +deadline limit = mapSpecItem_ $ \item@Item {itemLocation, itemExample} -> + item + { itemExample = \params aw pc -> + fromMaybe (Result "timed out" . Failure itemLocation $ Reason "time limit") <$> timeout limit (itemExample params aw pc) + } From a8b86cabb1b3ca35e72acff0ae44fe40b5255179 Mon Sep 17 00:00:00 2001 From: Bjarne Laumann Date: Sat, 12 Apr 2025 00:22:52 +0200 Subject: [PATCH 133/159] Added user flag to docker run command --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4419489f1..add9c94b0 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im - `smp-server` - You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -125,12 +125,13 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im -p 5223:5223 \ -v $HOME/simplex/smp/config:/etc/opt/simplex:z \ -v $HOME/simplex/smp/logs:/var/opt/simplex:z \ + -u "non_root_user_id" simplexchat/smp-server:latest ``` - `xftp-server` - You must change **your_ip_or_domain** and **maximum_storage**. + You must change **your_ip_or_domain** and **maximum_storage**. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -139,6 +140,7 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im -v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/files:/srv/xftp:z \ + -u "non_root_user_id" simplexchat/xftp-server:latest ``` @@ -189,7 +191,7 @@ On Linux, you can build smp server using Docker. - `smp-server` - You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -197,12 +199,13 @@ On Linux, you can build smp server using Docker. -p 5223:5223 \ -v $HOME/simplex/smp/config:/etc/opt/simplex:z \ -v $HOME/simplex/smp/logs:/var/opt/simplex:z \ + -u "non_root_user_id" simplexchat/smp-server:latest ``` - `xftp-server` - You must change **your_ip_or_domain** and **maximum_storage**. + You must change **your_ip_or_domain** and **maximum_storage**. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -211,6 +214,7 @@ On Linux, you can build smp server using Docker. -v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/files:/srv/xftp:z \ + -u "non_root_user_id" simplexchat/xftp-server:latest ``` From 099d05520c8e26ef400d9d5c407a372e8124cd7e Mon Sep 17 00:00:00 2001 From: Happy_Shrimp Date: Thu, 8 Aug 2024 02:27:25 -0400 Subject: [PATCH 134/159] Added '--network=host' to build commands for smp-server and xftp-server to fix issue with no network available. See issue logged here: https://github.com/simplex-chat/simplexmq/issues/1253 Fixed a typo from '# For xmp-server' to '# For smp-server' --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index add9c94b0..3d4116a57 100644 --- a/README.md +++ b/README.md @@ -177,8 +177,8 @@ On Linux, you can build smp server using Docker. cd simplexmq git checkout stable git submodule update --init --recursive - DOCKER_BUILDKIT=1 docker build -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For xmp-server - DOCKER_BUILDKIT=1 docker build -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server + DOCKER_BUILDKIT=1 docker build --network=host -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For smp-server + DOCKER_BUILDKIT=1 docker build --network=host -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server ``` 2. Create directories for persistent Docker configuration: From 47fadb640b9fe44958c0ca94f669fec785bcab38 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:01:06 -0500 Subject: [PATCH 135/159] transport: import exception handler for nonblocking TLS close --- src/Simplex/Messaging/Transport.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 1e7c42274..12c8d19d2 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -145,7 +145,7 @@ import Simplex.Messaging.Server.Information import Simplex.Messaging.SystemTime (SystemSeconds) import Simplex.Messaging.Transport.Buffer import Simplex.Messaging.Transport.Shared -import Simplex.Messaging.Util (bshow, catchOwn', catchOwn_, liftEitherWith, stateTVar', (<$$>)) +import Simplex.Messaging.Util (bshow, catchAll_, catchOwn', catchOwn_, liftEitherWith, stateTVar', (<$$>)) import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal import System.IO.Error (isEOFError) From 90a7fdf4a37cb395c6b5e56d7498354293ff3850 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:08:44 -0500 Subject: [PATCH 136/159] server: reconcile consolidated build errors Restore notification grouping and batched subscription results. Initialize delayed AUTH and unacked-data settings. Remove duplicate client send block definitions. --- src/Simplex/FileTransfer/Server.hs | 2 +- src/Simplex/FileTransfer/Server/Env.hs | 3 +- src/Simplex/Messaging/Agent.hs | 2 +- src/Simplex/Messaging/Client.hs | 16 -------- src/Simplex/Messaging/Server.hs | 37 ++++++------------- src/Simplex/Messaging/Server/Env/STM.hs | 2 + src/Simplex/Messaging/Server/Main/Init.hs | 1 + .../Messaging/Server/QueueStore/STM.hs | 4 ++ 8 files changed, 23 insertions(+), 44 deletions(-) diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index c3ccd82b6..d9a1f3496 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -613,7 +613,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case ifM (isJust <$> readTVarIO filePath) (pure Nothing) $ Just <$> mask (\restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA)) Left e -> pure $ Just $ FRErr e - skipCommitted = ifM (isJust <$> readTVarIO filePath) drainCommitted + skipCommitted = drainCommitted where drainCommitted = do t <- asks $ fileTimeout . config diff --git a/src/Simplex/FileTransfer/Server/Env.hs b/src/Simplex/FileTransfer/Server/Env.hs index 1f95fd0e7..8e7bbc7ba 100644 --- a/src/Simplex/FileTransfer/Server/Env.hs +++ b/src/Simplex/FileTransfer/Server/Env.hs @@ -139,7 +139,8 @@ defaultXFTPKeepAlive = KeepAliveOpts { keepIdle = 60, keepIntvl = 10, - keepCnt = 6 + keepCnt = 6, + unackedDataTimeout = Nothing } defaultXFTPUserTimeout :: Int diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index b32f11685..ea227c32c 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -356,7 +356,7 @@ disconnectAgentClient c@AgentClient {agentEnv = Env {ntfSupervisor = ns, xftpAge -- only used in the tests disposeAgentClient :: AgentClient -> IO () -disposeAgentClient c@AgentClient {acThread, connLockViolations, agentEnv = Env {store}} = do +disposeAgentClient c@AgentClient {acThread, agentEnv = Env {store}} = do t_ <- atomically (swapTVar acThread Nothing) $>>= (liftIO . deRefWeak) disconnectAgentClient c mapM_ killThread t_ diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 7059a358b..94b0dce78 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1413,22 +1413,6 @@ failRequest :: Request err msg -> STM () failRequest Request {pending, responseVar} = whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError -sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a -sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do - ts <- getCurrentTime - -- two separate "atomically" needed to avoid blocking - E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ (addRequest ts) rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) - (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) - (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) - where - addRequest ts r@Request {corrId} = TM.insert corrId r {createdAt = ts} sentCommands - removeRequest Request {corrId} = TM.delete corrId sentCommands - -failRequest :: Request err msg -> STM () -failRequest Request {pending, responseVar} = - whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError - nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do sent <- atomically $ tryWriteTBQueue q x diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index ddc02adfe..d2ada83aa 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1121,7 +1121,7 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ [liftIO $ send h c, client s ms c, receive h ms c] + raceAny_ [liftIO $ send h c, client processSubs s ms c, receive h ms c] controlPortAuth :: Handle -> Maybe BasicAuth -> Maybe BasicAuth -> TVar CPClientRole -> BasicAuth -> IO () controlPortAuth h user admin role auth = do @@ -1240,7 +1240,7 @@ sendResponses c@Client {sndQ} stats authDelay since rs@(ts, _) | otherwise = atomically $ writeTBQueue sndQ rs sendAfterDelay :: Client s -> ServerStats -> Int64 -> SystemTime -> (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO () -sendAfterDelay c@Client {sndQ, clientTHParams = THandleParams {sessionId}} stats delay since rs +sendAfterDelay c@Client {sndQ, delayedQ, clientTHParams = THandleParams {sessionId}} stats delay since rs | delay > 0 = do elapsed <- subtract (microseconds since) . microseconds <$> getSystemTime when (elapsed >= delay) $ incStat $ authDelayExceeded stats @@ -1490,10 +1490,10 @@ client partitionSubs t (msgQs, rcvQs, ntfQs) = case t of (Just (_, QueueRec {status = EntityBlocked _}), (_, _, Cmd SRecipient SUB)) -> (msgQs, rcvQs, ntfQs) (Just (q, qr), (_, entId, Cmd SRecipient SUB)) - | isJust clntServiceId_ || isJust (rcvServiceId qr) -> (q : msgQs, M.insert entId q rcvQs, ntfQs) - | otherwise -> (q : msgQs, rcvQs, ntfQs) + | isJust clntServiceId_ || isJust (rcvServiceId qr) -> ((q, qr) : msgQs, q : rcvQs, ntfQs) + | otherwise -> ((q, qr) : msgQs, rcvQs, ntfQs) (Just (q, qr), (_, entId, Cmd SNotifier NSUB)) - | isJust clntServiceId_ || isJust (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, M.insert entId q ntfQs) + | isJust clntServiceId_ || isJust (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, q : ntfQs) _ -> (msgQs, rcvQs, ntfQs) runExceptT $ do rcvAssocs <- ifNotNull rcvAssocQs $ setService SRecipientService clntServiceId_ @@ -1745,7 +1745,7 @@ client case command of SUB -> case batchSubs >>= \(msgs, rcvAssocs, _, subs) -> sequence (M.lookup entId rcvAssocs) $> (msgs, subs) of Left e -> pure $ Just (err e, Nothing) - Right (msgs, rcvAssoc_) -> withQueue' $ \_ -> subscribeQueueAndDeliver (M.lookup entId msgs) rcvAssoc_ + Right (msgs, subs) -> withQueue' $ \_ -> subscribeQueueAndDeliver (M.lookup entId msgs) (fromMaybe (Left INTERNAL) $ M.lookup entId subs) GET -> withQueue getMessage ACK msgId -> withQueue $ acknowledgeMsg msgId KEY sKey -> withQueue $ \q _ -> either err (corrId,entId,) <$> secureQueue_ q sKey @@ -1886,25 +1886,12 @@ client suspendQueue_ :: (StoreQueue s, QueueRec) -> M s (Transmission BrokerMsg) suspendQueue_ (q, _) = liftIO $ either err (const ok) <$> suspendQueue (queueStore ms) q - subscribeQueueAndDeliver :: Maybe Message -> Maybe (TVar (Maybe ServiceId)) -> QueueRec -> M s ResponseAndMessage - subscribeQueueAndDeliver msg_ rcvAssoc_ qr = - liftIO (TM.lookupIO entId $ subscriptions clnt) >>= \case - Nothing -> - deliver =<< subscribeQueue - Just s@Sub {subThread} -> do - stats <- asks serverStats - case subThread of - ProhibitSub -> do - -- cannot use SUB in the same connection where GET was used - incStat $ qSubProhibited stats - pure (err (CMD PROHIBITED), Nothing) - _ -> do - incStat $ qSubDuplicate stats - atomically (writeTVar (delivered s) Nothing) >> subscribeQueue >> deliver (True, Just s) + subscribeQueueAndDeliver :: Maybe Message -> Either ErrorType (Bool, Maybe Sub) -> QueueRec -> M s ResponseAndMessage + subscribeQueueAndDeliver msg_ subResult qr = + case subResult of + Left e -> pure (err e, Nothing) + Right (hasSub, sub_) -> deliver (hasSub, sub_) where - subscribeQueue = do - rcvServiceId <- replacedServiceId rcvAssoc_ - sharedSubscribeQueue rcvServiceId subscribers subscriptions serviceSubsCount (newSubscription NoSub) rcvServices deliver :: (Bool, Maybe Sub) -> M s ResponseAndMessage deliver (hasSub, sub_) = do stats <- asks serverStats @@ -2374,7 +2361,7 @@ client sub <- atomically $ TM.lookupDelete entId $ subscriptions clnt liftIO $ mapM_ cancelSub sub when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) - atomically $ writeTQueue (subQ subscribers) (CSDeleted entId rcvServiceId, clientId) + liftIO $ processSub clnt $ CSDeleted entId rcvServiceId forM_ (notifier qr) $ \NtfCreds {notifierId = nId, ntfServiceId} -> do -- queue is deleted by a different client from the one subscribed to notifications, -- so we don't need to remove subscription from the current client. diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 4aa4cb542..10c47d90b 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -535,6 +535,7 @@ newClient clientId qSize clientTHParams createdAt closeTransport = do rcvQ <- newTBQueueIO qSize sndQ <- newTBQueueIO qSize msgQ <- newTBQueueIO qSize + delayedQ <- newTBQueueIO qSize procThreads <- newTVarIO 0 fwdWorkers <- newTVarIO IM.empty endThreads <- newTVarIO IM.empty @@ -555,6 +556,7 @@ newClient clientId qSize clientTHParams createdAt closeTransport = do rcvQ, sndQ, msgQ, + delayedQ, procThreads, fwdWorkers, endThreads, diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index fad3a042b..c45acd981 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -162,6 +162,7 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = \# Number of workers processing messages that one proxy server forwards to this server.\n\ \# Messages to one queue are processed by one worker, in the order they are received.\n" <> ("# forward_workers = " <> tshow defaultForwardWorkers) + <> "\n\n\ \# Limit number of connections to destination servers being established at once.\n" <> ("# connect_concurrency = " <> tshow defaultProxyConnectConcurrency) <> "\n\n\ diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index 8edc3b975..a5f892ed6 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -357,6 +357,10 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where ssNtfs' = (Nothing, ntfs') : ssNtfs pure $ Right (ssNtfs', deleteNtfs) where + addService (ssNtfs, deleteNtfs) (serviceId, s) = do + (sNIds, _) <- readTVarIO $ serviceNtfQueues s + let (sNtfs, otherNtfs) = partition (\(nId, _) -> S.member nId sNIds) deleteNtfs + pure ((Just serviceId, sNtfs) : ssNtfs, otherNtfs) addNtf ns qs ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId ns >>= (`M.lookup` qs) of Just q -> do qr <- readTVarIO (queueRec q) From e66d64419dffc320c350df8ae860889686de5e31 Mon Sep 17 00:00:00 2001 From: sh-agents <350651734+sh-agents@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:39:04 +0000 Subject: [PATCH 137/159] servers: share the delay until the daily stats time --- src/Simplex/Messaging/Notifications/Server.hs | 5 ++--- src/Simplex/Messaging/Server.hs | 5 ++--- src/Simplex/Messaging/Util.hs | 8 +++++++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index d474e075c..bc7d9fe22 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -47,7 +47,7 @@ import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Text.Encoding (decodeLatin1) -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import GHC.IORef (atomicSwapIORef) @@ -169,9 +169,8 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} logServerStats :: Int64 -> Int64 -> FilePath -> M () logServerStats startAt logInterval statsFilePath = do - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime logNote $ "server stats log enabled: " <> T.pack statsFilePath - liftIO $ threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) + liftIO $ delayUntilDayTime startAt NtfServerStats {fromTime, tknCreated, tknVerified, tknDeleted, tknReplaced, subCreated, subDeleted, ntfReceived, ntfDelivered, ntfFailed, ntfCronDelivered, ntfCronFailed, ntfVrfQueued, ntfVrfDelivered, ntfVrfFailed, ntfVrfInvalidTkn, activeTokens, activeSubs} <- asks serverStats let interval = 1000000 * logInterval diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index d2ada83aa..f50dea394 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -83,7 +83,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1) import qualified Data.Text.IO as T -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import Data.Type.Equality @@ -542,9 +542,8 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt logServerStats :: Int64 -> Int64 -> FilePath -> M s () logServerStats startAt logInterval statsFilePath = do labelMyThread "logServerStats" - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime liftIO $ putStrLn $ "server stats log enabled: " <> statsFilePath - liftIO $ threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) + liftIO $ delayUntilDayTime startAt ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, pMsgFwdsBelow23, pMsgFwdsFrom23, pMsgFwdsRecvBelow23, pMsgFwdsRecvFrom23, rcvServices, ntfServices, rslvStats} <- asks serverStats st <- asks msgStore diff --git a/src/Simplex/Messaging/Util.hs b/src/Simplex/Messaging/Util.hs index 8c384f596..7b2f2cd5d 100644 --- a/src/Simplex/Messaging/Util.hs +++ b/src/Simplex/Messaging/Util.hs @@ -61,6 +61,7 @@ module Simplex.Messaging.Util safeDecodeUtf8, timeoutThrow, threadDelay', + delayUntilDayTime, diffToMicroseconds, diffToMilliseconds, labelMyThread, @@ -97,7 +98,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import qualified Data.Text.IO as T -import Data.Time (NominalDiffTime) +import Data.Time (NominalDiffTime, diffTimeToPicoseconds, getCurrentTime, utctDayTime) import Data.Tuple (swap) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) @@ -424,6 +425,11 @@ threadDelay' = loop threadDelay $ fromIntegral maxWait loop $ time - maxWait +delayUntilDayTime :: Int64 -> IO () +delayUntilDayTime startAt = do + initialDelay <- (startAt -) . fromIntegral . (`div` 1000000000000) . diffTimeToPicoseconds . utctDayTime <$> getCurrentTime + threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) + diffToMicroseconds :: NominalDiffTime -> Int64 diffToMicroseconds diff = truncate $ diff * 1000000 {-# INLINE diffToMicroseconds #-} From b54da06e23f03051faecdbbc5b1d41f703c647f3 Mon Sep 17 00:00:00 2001 From: spacedandy-agents-simplex <342056592+spacedandy-agents-simplex@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:34:58 +0000 Subject: [PATCH 138/159] smp protocol: LSWP swaps link data and keys only over the known data --- protocol/simplex-messaging.md | 40 +++++++++++++++++++++++++++--- src/Simplex/Messaging/Client.hs | 11 ++++++++ src/Simplex/Messaging/Protocol.hs | 19 ++++++++++++++ src/Simplex/Messaging/Server.hs | 1 + src/Simplex/Messaging/Transport.hs | 9 +++++-- tests/SMPProxyTests.hs | 21 ++++++++++++++++ tests/ServerTests.hs | 11 ++++++-- 7 files changed, 105 insertions(+), 7 deletions(-) diff --git a/protocol/simplex-messaging.md b/protocol/simplex-messaging.md index bd68d457d..1ded3fd1a 100644 --- a/protocol/simplex-messaging.md +++ b/protocol/simplex-messaging.md @@ -34,6 +34,7 @@ Version 21, 2026-07-05 - [Secure queue by recipient](#secure-queue-by-recipient) - [Set queue recipient keys](#set-queue-recipient-keys) - [Set short link](#set-short-link) + - [Swap short link data](#swap-short-link-data) - [Delete short link](#delete-short-link) - [Enable notifications command](#enable-notifications-command) - [Disable notifications command](#disable-notifications-command) @@ -57,6 +58,7 @@ Version 21, 2026-07-05 - [Subscribe to multiple queue notifications](#subscribe-to-multiple-queue-notifications) - [Router messages](#router-messages) - [Link response](#link-response) + - [Current link data response](#current-link-data-response) - [Queue subscription response](#queue-subscription-response) - [Service subscription response](#service-subscription-response) - [All service messages received](#all-service-messages-received) @@ -86,7 +88,7 @@ It's designed with the focus on communication security and integrity, under the It is designed as a low level protocol for other application protocols to solve the problem of secure and private message transmission, making [MITM attack][1] very difficult at any part of the message transmission system. -This document describes SMP protocol version 23. Versions 1-5 are discontinued. The version history: +This document describes SMP protocol version 24. Versions 1-5 are discontinued. The version history: - v1: binary protocol encoding - v2: message flags (used to control notifications) @@ -110,6 +112,7 @@ This document describes SMP protocol version 23. Versions 1-5 are discontinued. - v21: server public information in handshake - v22: `RNAME` says whether a name can be registered, not only what it resolves to - v23: version in nonces of forwarded commands, random nonces for forwarded responses +- v24: LSWP command to swap short link data and recipient keys (LCUR response); LSET is refused on queues with several recipient keys ## Introduction @@ -547,12 +550,13 @@ smpCommand = ping / recipientCmd / senderCommand / proxyCommand / notifierCommand / linkCommand / routerMsg recipientCmd = create / subscribe / subscribeMultiple / rcvSecure / recipientKeys / enableNotifications / disableNotifications / getMessage / - acknowledge / suspend / delete / getQueueInfo / setShortLink / deleteShortLink + acknowledge / suspend / delete / getQueueInfo / setShortLink / swapShortLink / + deleteShortLink senderCommand = send / sndSecure linkCommand = setLinkKey / getLinkData proxyCommand = proxySession / proxyForward / relayForward notifierCommand = subscribeNotifications / subscribeNotificationsMultiple -routerMsg = queueIds / linkResponse / serviceOk / serviceOkMultiple / +routerMsg = queueIds / linkResponse / currentLinkData / serviceOk / serviceOkMultiple / message / allReceived / notifierIdResponse / messageNotification / proxySessionKey / proxyResponse / relayResponse / unsubscribed / serviceUnsubscribed / deleted / @@ -725,6 +729,27 @@ length2 = 2*2 OCTET ; Word16, network byte order (big-endian) The router responds with `OK` response if successful. +From v24 the router responds with `ERR AUTH` when the queue has more than one recipient key: the link data of such a queue can only be changed with `LSWP`. + +#### Swap short link data + +This command is used by the owners of a contact address short link to replace its user data and, optionally, the queue recipient keys, only when the stored user data has the hash the owner sends (added in v24): + +```abnf +swapShortLink = %s"LSWP " linkId userDataHash optRecipientKeys encFixedData encUserData +linkId = shortString +userDataHash = shortString ; SHA-256 hash of the stored encrypted user data (without length prefix) +optRecipientKeys = %s"0" / (%s"1" recipientKeysList) ; the new recipient keys of the queue +encFixedData = largeString ; encrypted fixed link data, must be the same as stored +encUserData = largeString ; new encrypted user data +``` + +The router responds with `ERR AUTH` if the queue is not a contact queue, has no short link, or if the link ID or fixed data differ from the stored ones. + +If the hash of the stored user data differs from `userDataHash`, the router responds with [current link data response](#current-link-data-response) (`LCUR`) with the stored user data, and changes nothing. + +Otherwise the router stores the user data and, when present, the recipient keys in one atomic step, and responds with `OK`. + #### Delete short link This command is used to remove a short link association from the queue: @@ -1251,6 +1276,15 @@ encFixedData = largeString ; encrypted fixed link data encUserData = largeString ; encrypted user data ``` +#### Current link data response + +Sent in response to `LSWP` command when the hash of the stored user data differs from the hash in the command: + +```abnf +currentLinkData = %s"LCUR " encUserData +encUserData = largeString ; the stored encrypted user data +``` + #### Queue subscription response Sent in response to `SUB` and `NSUB` commands: diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 94b0dce78..656cf463b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -57,6 +57,7 @@ module Simplex.Messaging.Client secureSndSMPQueue, proxySecureSndSMPQueue, addSMPQueueLink, + swapSMPQueueLink, deleteSMPQueueLink, secureGetSMPQueueLink, proxySecureGetSMPQueueLink, @@ -74,6 +75,7 @@ module Simplex.Messaging.Client deleteSMPQueues, connectSMPProxiedRelay, proxySMPMessage, + proxySMPCommand, proxyResolveName, directResolveName, forwardSMPTransmission, @@ -1002,6 +1004,15 @@ addSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> Recip addSMPQueueLink c nm rpKey rId lnkId d = okSMPCommand (LSET lnkId d) c nm rpKey rId {-# INLINE addSMPQueueLink #-} +swapSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> RecipientId -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> ExceptT SMPClientError IO (Maybe EncUserDataBytes) +swapSMPQueueLink c nm rpKey rId lnkId h ks_ d + | thVersion (thParams c) >= linkSwapSMPVersion = + sendSMPCommand c nm (Just rpKey) rId (LSWP lnkId h ks_ d) >>= \case + OK -> pure Nothing + LCUR ud -> pure $ Just ud + r -> throwE $ unexpectedResponse r + | otherwise = throwE $ PCETransportError TEVersion + -- | Delete queue link deleteSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPClientError IO () deleteSMPQueueLink = okSMPCommand LDEL diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index f571ed133..bcc734809 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -603,6 +603,7 @@ data Command (p :: Party) where KEY :: SndPublicAuthKey -> Command Recipient RKEY :: NonEmpty RcvPublicAuthKey -> Command Recipient LSET :: LinkId -> QueueLinkData -> Command Recipient + LSWP :: LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> Command Recipient LDEL :: Command Recipient NKEY :: NtfPublicAuthKey -> RcvNtfPublicDhKey -> Command Recipient NDEL :: Command Recipient @@ -690,6 +691,13 @@ instance ToField EncDataBytes where toField (EncDataBytes s) = toField (Binary s) {-# INLINE toField #-} +newtype LinkDataHash = LinkDataHash ByteString + deriving (Eq, Show) + deriving newtype (Encoding) + +linkDataHash :: EncUserDataBytes -> LinkDataHash +linkDataHash (EncDataBytes s) = LinkDataHash $ C.sha256Hash s + data NewNtfCreds = NewNtfCreds NtfPublicAuthKey RcvNtfPublicDhKey deriving (Show) instance StrEncoding SubscriptionMode where @@ -754,6 +762,7 @@ data BrokerMsg where -- SMP broker messages (responses, client messages, notifications) IDS :: QueueIdsKeys -> BrokerMsg LNK :: SenderId -> QueueLinkData -> BrokerMsg + LCUR :: EncUserDataBytes -> BrokerMsg -- | Service subscription success - confirms when queue was associated with the service SOK :: Maybe ServiceId -> BrokerMsg -- | The number of queues and XOR-hash of their IDs subscribed with SUBS command @@ -971,6 +980,7 @@ data CommandTag (p :: Party) where KEY_ :: CommandTag Recipient RKEY_ :: CommandTag Recipient LSET_ :: CommandTag Recipient + LSWP_ :: CommandTag Recipient LDEL_ :: CommandTag Recipient NKEY_ :: CommandTag Recipient NDEL_ :: CommandTag Recipient @@ -1000,6 +1010,7 @@ deriving instance Show CmdTag data BrokerMsgTag = IDS_ | LNK_ + | LCUR_ | SOK_ | SOKS_ | MSG_ @@ -1035,6 +1046,7 @@ instance PartyI p => Encoding (CommandTag p) where KEY_ -> "KEY" RKEY_ -> "RKEY" LSET_ -> "LSET" + LSWP_ -> "LSWP" LDEL_ -> "LDEL" NKEY_ -> "NKEY" NDEL_ -> "NDEL" @@ -1064,6 +1076,7 @@ instance ProtocolMsgTag CmdTag where "KEY" -> Just $ CT SRecipient KEY_ "RKEY" -> Just $ CT SRecipient RKEY_ "LSET" -> Just $ CT SRecipient LSET_ + "LSWP" -> Just $ CT SRecipient LSWP_ "LDEL" -> Just $ CT SRecipient LDEL_ "NKEY" -> Just $ CT SRecipient NKEY_ "NDEL" -> Just $ CT SRecipient NDEL_ @@ -1096,6 +1109,7 @@ instance Encoding BrokerMsgTag where smpEncode = \case IDS_ -> "IDS" LNK_ -> "LNK" + LCUR_ -> "LCUR" SOK_ -> "SOK" SOKS_ -> "SOKS" MSG_ -> "MSG" @@ -1119,6 +1133,7 @@ instance ProtocolMsgTag BrokerMsgTag where decodeTag = \case "IDS" -> Just IDS_ "LNK" -> Just LNK_ + "LCUR" -> Just LCUR_ "SOK" -> Just SOK_ "SOKS" -> Just SOKS_ "MSG" -> Just MSG_ @@ -1892,6 +1907,7 @@ instance PartyI p => ProtocolEncoding SMPVersion ErrorType (Command p) where KEY k -> e (KEY_, ' ', k) RKEY ks -> e (RKEY_, ' ', ks) LSET lnkId d -> e (LSET_, ' ', lnkId, d) + LSWP lnkId h keys_ d -> e (LSWP_, ' ', lnkId, h, keys_, d) LDEL -> e LDEL_ NKEY k dhKey -> e (NKEY_, ' ', k, dhKey) NDEL -> e NDEL_ @@ -1987,6 +2003,7 @@ instance ProtocolEncoding SMPVersion ErrorType Cmd where KEY_ -> KEY <$> _smpP RKEY_ -> RKEY <$> _smpP LSET_ -> LSET <$> _smpP <*> smpP + LSWP_ -> LSWP <$> _smpP <*> smpP <*> smpP <*> smpP LDEL_ -> pure LDEL NKEY_ -> NKEY <$> _smpP <*> smpP NDEL_ -> pure NDEL @@ -2035,6 +2052,7 @@ instance ProtocolEncoding SMPVersion ErrorType BrokerMsg where where ids = e (IDS_, ' ', rcvId, sndId, srvDh) LNK sId d -> e (LNK_, ' ', sId, d) + LCUR d -> e (LCUR_, ' ', d) SOK serviceId_ | v >= serviceCertsSMPVersion -> e (SOK_, ' ', serviceId_) | otherwise -> e OK_ -- won't happen, the association with the service requires v >= serviceCertsSMPVersion @@ -2097,6 +2115,7 @@ instance ProtocolEncoding SMPVersion ErrorType BrokerMsg where serverNtfCreds <- p4 pure $ IDS QIK {rcvId, sndId, rcvPublicDhKey, queueMode, linkId, serviceId, serverNtfCreds} LNK_ -> LNK <$> _smpP <*> smpP + LCUR_ -> LCUR <$> _smpP SOK_ -> SOK <$> _smpP SOKS_ -> serviceRespP SOKS NID_ -> NID <$> _smpP <*> smpP diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index f50dea394..8d7914964 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1754,6 +1754,7 @@ client _ | isSecuredMsgQueue qr -> pure $ err AUTH Just (lnkId', _) | lnkId' /= lnkId -> pure $ err AUTH -- can't change link ID _ -> liftIO $ either err (const ok) <$> addQueueLinkData (queueStore ms) q lnkId d + LSWP lnkId h ks_ d -> withQueue $ \q qr -> checkMode QMContact qr $ maybe OK LCUR <$$> liftIO (swapQueueLinkData (queueStore ms) q lnkId h ks_ d) LDEL -> withQueue $ \q qr -> case queueData qr of Just _ -> liftIO $ either err (const ok) <$> deleteQueueLinkData (queueStore ms) q diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 12c8d19d2..69fe8d5ec 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -55,6 +55,7 @@ module Simplex.Messaging.Transport serverInfoSMPVersion, nameAvailSMPVersion, fwdNoncesSMPVersion, + linkSwapSMPVersion, simplexMQVersion, smpBlockSize, TransportConfig (..), @@ -180,6 +181,7 @@ smpBlockSize = 16384 -- 21 - server public information in handshake (7/5/2026) -- 22 - RNAME answers name availability as well as the record (7/25/2026) -- 23 - version in forwarded command nonce, random nonce in forwarded responses (10/2/2026) +-- 24 - LSWP command to swap short link data and recipient keys, LCUR response, LSET refused with many recipient keys (10/28/2026) data SMPVersion @@ -221,6 +223,9 @@ nameAvailSMPVersion = VersionSMP 22 fwdNoncesSMPVersion :: VersionSMP fwdNoncesSMPVersion = VersionSMP 23 +linkSwapSMPVersion :: VersionSMP +linkSwapSMPVersion = VersionSMP 24 + minClientSMPRelayVersion :: VersionSMP minClientSMPRelayVersion = VersionSMP 15 @@ -228,10 +233,10 @@ minServerSMPRelayVersion :: VersionSMP minServerSMPRelayVersion = VersionSMP 15 currentClientSMPRelayVersion :: VersionSMP -currentClientSMPRelayVersion = VersionSMP 23 +currentClientSMPRelayVersion = VersionSMP 24 currentServerSMPRelayVersion :: VersionSMP -currentServerSMPRelayVersion = VersionSMP 23 +currentServerSMPRelayVersion = VersionSMP 24 -- Max SMP protocol version to be used in e2e encrypted connection between -- client and server, as defined by SMP proxy. Normally set below the current diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 6473d01b9..035f653fb 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -115,6 +115,8 @@ smpProxyTests = do testForwardedAuthErrorDelay it "proxy closes idle relay connection" $ \_ -> testProxyClosesIdleRelay + it "relay refuses forwarded short link data swap" $ \_ -> + testForwardedSwapQueueLink describe "deliver message via SMP proxy" $ do let srv1, srv2 :: HasTestEnv => SMPServer srv1 = SMPServer testHost testPort testKeyHash @@ -693,6 +695,25 @@ testForwardedQueueLocked = _ <- PSQL.execute_ db $ Query $ "SET search_path TO " <> schema testStoreDBOpts2 pure db #endif +testForwardedSwapQueueLink :: HasTestEnv => IO () +testForwardedSwapQueueLink = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> + withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (2, testSMPServer2, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + lnkId <- SMP.EntityId <$> atomically (C.randomBytes 24 g) + let ld = (SMP.EncDataBytes "fixed data", SMP.EncDataBytes "user data") + ld' = (fst ld, SMP.EncDataBytes "new user data") + SMP.QIK {rcvId} <- runExceptT' $ createSMPQueue rc NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing + runExceptT' $ addSMPQueueLink rc NRMInteractive rKey rcvId lnkId ld + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive testSMPServer2 Nothing + runExceptT (proxySMPCommand pc NRMInteractive sess (Just rKey) rcvId (SMP.LSWP lnkId (SMP.linkDataHash $ snd ld) Nothing ld')) + `shouldReturn` Left (PCEProtocolError $ SMP.CMD SMP.PROHIBITED) + (snd <$> runExceptT' (getSMPQueueLink rc NRMInteractive lnkId)) `shouldReturn` ld -- Shared "phase 2" of the reconnection tests: start a healthy relay, confirm it is reachable -- directly (PING, not via the proxy) so a proxy failure can only mean the proxy didn't reconnect, diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 68eb311fd..a8c80371f 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -19,12 +19,14 @@ module ServerTests where import Control.Concurrent (ThreadId, killThread, threadDelay) -import Control.Concurrent.Async (concurrently_) +import Control.Concurrent.Async (concurrently, concurrently_) import Control.Concurrent.STM import Control.Exception (SomeException, finally, throwIO, try) import Control.Monad import Control.Monad.IO.Class +import Control.Monad.Trans.Except (runExceptT) import qualified Crypto.PubKey.ECC.Types as ECC +import Crypto.Random (ChaChaDRG) import Data.Bifunctor (first) import qualified Data.ByteString.Base64 as B64 import Data.ByteString.Char8 (ByteString) @@ -44,7 +46,7 @@ import qualified Data.X509 as X import qualified Data.X509.Validation as XV import GHC.Stack (withFrozenCallStack) import SMPClient -import Simplex.Messaging.Client (authTransmission) +import Simplex.Messaging.Client (ProtocolClientConfig (..), pattern NRMInteractive, ProtocolClientError (..), addSMPQueueLink, authTransmission, createSMPQueue, defaultSMPClientConfig, getProtocolClient, getSMPQueueLink, swapSMPQueueLink) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String @@ -143,6 +145,11 @@ serverTests = do testInvQueueLinkData testContactQueueLinkData testDuplicateQueueLinkData + testSwapQueueLink + testSwapQueueLinkKeys + testConcurrentSwapQueueLink + testSwapQueueLinkClient + testSwapQueueLinkStoreLog pattern Resp :: CorrId -> QueueId -> BrokerMsg -> Transmission (Either ErrorType BrokerMsg) pattern Resp corrId queueId command <- (corrId, queueId, Right command) From a15b832a0e20bf1f0e8759c4010f02df92e93f62 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:20:23 -0500 Subject: [PATCH 139/159] protocol: expose short-link swap API and fix regression tests --- src/Simplex/Messaging/Protocol.hs | 2 ++ tests/AgentTests/ConnectionRequestTests.hs | 8 ++++---- tests/AgentTests/DoubleRatchetTests.hs | 2 +- tests/CoreTests/KeepAliveTests.hs | 2 +- tests/CoreTests/SOCKSSettings.hs | 2 +- tests/FileDescriptionTests.hs | 1 - 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index bcc734809..f5a932096 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -61,6 +61,8 @@ module Simplex.Messaging.Protocol QueueReqData (..), QueueMode (..), QueueLinkData, + LinkDataHash, + linkDataHash, EncFixedDataBytes, EncUserDataBytes, EncDataBytes (..), diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index 89488c653..b39008875 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -302,10 +302,10 @@ connectionRequestTests = contactAddress2queues #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueStr <> ";" <> queueStr)) contactAddressNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueNewStr) contactAddress2queuesNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueNewStr <> ";" <> queueNewStr)) - contactAddressV2 #==# ("simplex:/contact#/?v=2&smp=" <> url queueStr) - contactAddressV2 #== ("https://simplex.chat/contact#/?v=1&smp=" <> url queueStr) -- adjusted to v2 - contactAddressV2 #== ("https://simplex.chat/contact#/?v=1-2&smp=" <> url queueStr) -- adjusted to v2 - contactAddressV2 #== ("https://simplex.chat/contact#/?v=2-2&smp=" <> url queueStr) + contactAddress #==# ("simplex:/contact#/?v=2&smp=" <> url queueStr) + contactAddress #== ("https://simplex.chat/contact#/?v=1&smp=" <> url queueStr) -- adjusted to v2 + contactAddress #== ("https://simplex.chat/contact#/?v=1-2&smp=" <> url queueStr) -- adjusted to v2 + contactAddress #== ("https://simplex.chat/contact#/?v=2-2&smp=" <> url queueStr) contactAddressClientData #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr <> "&data=" <> url "{\"type\":\"group_link\", \"group_link_id\":\"abc\"}") it "should generate a bracketed IPv6 application-server authority" $ do let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost diff --git a/tests/AgentTests/DoubleRatchetTests.hs b/tests/AgentTests/DoubleRatchetTests.hs index 512a9c972..0fbdffe9b 100644 --- a/tests/AgentTests/DoubleRatchetTests.hs +++ b/tests/AgentTests/DoubleRatchetTests.hs @@ -439,7 +439,7 @@ testRatchetStepLowOrderKey _ = do let hdr = MsgHeader {msgMaxVersion = currentE2EEncryptVersion, msgDHRs = k, msgKEM = Nothing, msgPN = 0, msgNs = 0} ehIV = C.IV $ B.replicate (C.ivSize @AES256) '\0' Right (ehAuthTag, ehBody) <- runExceptT $ C.encryptAEAD rcHKs ehIV (paddedHeaderLen PQSupportOff) ad (smpEncode hdr) - let emHeader = smpEncode EncMessageHeader {ehVersion = currentE2EEncryptVersion, ehIV, ehAuthTag, ehBody} + let emHeader = smpEncode EncMessageHeader {ehVersion = currentE2EEncryptVersion, ehIV, ehAuthTag, ehBody, ehLegacy = False} runExceptT $ rcDecrypt g alice M.empty $ smpEncode EncRatchetMessage {emHeader, emAuthTag = ehAuthTag, emBody = "message"} (validKey, _) <- atomically $ C.generateKeyPair @a g decryptWithKey validKey >>= \case diff --git a/tests/CoreTests/KeepAliveTests.hs b/tests/CoreTests/KeepAliveTests.hs index 45d7f6c6a..aa70bddad 100644 --- a/tests/CoreTests/KeepAliveTests.hs +++ b/tests/CoreTests/KeepAliveTests.hs @@ -21,7 +21,7 @@ import Util keepAliveTests :: Spec keepAliveTests = linuxOnly $ it "should fail connection with data not accepted by peer only with unackedDataTimeout" testUnackedDataTimeout where - linuxOnly t = if os == "linux" then t else skip "Linux only" t + linuxOnly t = if os == "linux" then t else before_ (pendingWith "Linux only") t testUnackedDataTimeout :: IO () testUnackedDataTimeout = do diff --git a/tests/CoreTests/SOCKSSettings.hs b/tests/CoreTests/SOCKSSettings.hs index 2ee06d221..63d9fd3c4 100644 --- a/tests/CoreTests/SOCKSSettings.hs +++ b/tests/CoreTests/SOCKSSettings.hs @@ -196,7 +196,7 @@ testSocksProxyConnection = do it "should connect via SOCKS proxy with domain name" $ socksConnectionTest "127.0.0.1" "localhost:5050" it "should connect via SOCKS proxy with domain name without credentials" $ socksConnectionTest "127.0.0.1" "@localhost:5050" -socksConnectionTest :: HostName -> ByteString -> IO () +socksConnectionTest :: HasTestEnv => HostName -> ByteString -> IO () socksConnectionTest proxyHost proxy = withSmpServerConfigOn (transport @TLS) SMPClient.cfg testPort $ \_ -> withSocksProxy proxyHost "5050" $ \destinations -> do diff --git a/tests/FileDescriptionTests.hs b/tests/FileDescriptionTests.hs index 4ac12dd42..ce9c7c1a5 100644 --- a/tests/FileDescriptionTests.hs +++ b/tests/FileDescriptionTests.hs @@ -283,7 +283,6 @@ testDecryptChunks = encPath = testPath "encrypted" dstPath = testPath "decrypted" -withRemoveTmpFile :: HasTestEnv => IO () -> IO () testFileWebLinkIPv6 :: IO () testFileWebLinkIPv6 = do let ipv6Server = either error id (strDecode "xftp://abc=@[2001:db8::1]:5223") :: XFTPServer From 176d75e3fd149af4ab6ea22f3f94ed4e2ac8e7da Mon Sep 17 00:00:00 2001 From: spacedandy-agents-simplex <342056592+spacedandy-agents-simplex@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:50:21 +0000 Subject: [PATCH 140/159] smp server: swap link data and keys atomically, refuse LSET on many keys --- src/Simplex/Messaging/Protocol.hs | 2 + .../Messaging/Server/QueueStore/Postgres.hs | 26 ++++++++- .../Messaging/Server/QueueStore/STM.hs | 56 ++++++++++++++----- .../Messaging/Server/QueueStore/Types.hs | 1 + src/Simplex/Messaging/Server/StoreLog.hs | 14 +++++ .../Messaging/Server/StoreLog/ReadWrite.hs | 7 ++- tests/CoreTests/MsgStoreTests.hs | 45 ++++++++++++++- tests/CoreTests/StoreLogTests.hs | 44 ++++++++++++++- 8 files changed, 173 insertions(+), 22 deletions(-) diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index f5a932096..d502f68da 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -66,6 +66,8 @@ module Simplex.Messaging.Protocol EncFixedDataBytes, EncUserDataBytes, EncDataBytes (..), + LinkDataHash (..), + linkDataHash, NewNtfCreds (..), ServerNtfCreds (..), Party (..), diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 4357cea63..46eb7ecbb 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -217,7 +217,31 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where atomically $ writeTVar (queueRec sq) $ Just q {queueData = Just (lnkId, d)} withLog "addQueueLinkData" st $ \s -> logCreateLink s rId lnkId d -- the sender key condition is checked in SQL because without cache each command reads its own copy of the queue record - qry = "UPDATE msg_queues SET fixed_data = ?, user_data = ?, link_id = ? WHERE recipient_id = ? AND deleted_at IS NULL AND (sender_key IS NULL OR queue_mode = ?)" + qry = "UPDATE msg_queues SET fixed_data = ?, user_data = ?, link_id = ? WHERE recipient_id = ? AND deleted_at IS NULL AND (sender_key IS NULL OR queue_mode = ?) AND get_byte(recipient_keys, 0) = 1" + + swapQueueLinkData :: PostgresQueueStore q -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) + swapQueueLinkData st sq lnkId h rKeys_ d = + withQueueRec sq $ \q -> + withDB "swapQueueLinkData" st swap >>= \case + Just ud -> pure $ Just ud + Nothing -> do + let !q' = q {recipientKeys = fromMaybe (recipientKeys q) rKeys_, queueData = Just (lnkId, d)} + atomically $ writeTVar (queueRec sq) $ Just q' + withLog "swapQueueLinkData" st $ \s -> logSwapLink s rId lnkId d rKeys_ + pure Nothing + where + rId = recipientId sq + swap db = + firstRow id AUTH (DB.query db "SELECT link_id, fixed_data, user_data FROM msg_queues WHERE recipient_id = ? AND deleted_at IS NULL FOR UPDATE" (Only rId)) + $>>= \case + (Just lnkId', Just fd', Just ud') + | lnkId' /= lnkId || fd' /= fst d -> pure $ Left AUTH + | linkDataHash ud' /= h -> pure $ Right $ Just ud' + | otherwise -> Right Nothing <$ updateLink db + _ -> pure $ Left AUTH + updateLink db = case rKeys_ of + Just rKeys -> DB.execute db "UPDATE msg_queues SET user_data = ?, recipient_keys = ? WHERE recipient_id = ?" (snd d, rKeys, rId) + Nothing -> DB.execute db "UPDATE msg_queues SET user_data = ? WHERE recipient_id = ?" (snd d, rId) deleteQueueLinkData :: PostgresQueueStore q -> q -> IO (Either ErrorType ()) deleteQueueLinkData st sq = diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index a5f892ed6..53d79afff 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -19,6 +19,7 @@ module Simplex.Messaging.Server.QueueStore.STM STMService (..), foldRcvServiceQueues, withLoadedQueues, + restoreQueueLinkData, setStoreLog, withLog', readQueueRecIO, @@ -34,8 +35,9 @@ import Data.Bitraversable (bimapM) import Data.Functor (($>)) import Data.Int (Int64) import Data.List (partition) -import Data.List.NonEmpty (NonEmpty) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M +import Data.Maybe (fromMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) @@ -171,20 +173,25 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where where rId = recipientId sq qr = queueRec sq - add q = case queueData q of - _ | isSecuredMsgQueue q -> pure $ Left AUTH - Nothing -> addLink - Just (lnkId', d') | lnkId' == lnkId && fst d' == fst d -> addLink + add q = case recipientKeys q of + _ :| [] -> addLinkData st sq lnkId d q _ -> pure $ Left AUTH - where - addLink = do - TM.lookup lnkId (links st) >>= \case - Just rId' | rId' /= rId -> pure $ Left AUTH - _ -> do - let !q' = q {queueData = Just (lnkId, d)} - writeTVar qr $ Just q' - TM.insert lnkId rId $ links st - pure $ Right () + + swapQueueLinkData :: STMQueueStore q -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) + swapQueueLinkData st sq lnkId h rKeys_ d = + atomically (readQueueRec qr $>>= swap) $>>= \case + Just ud -> pure $ Right $ Just ud + Nothing -> Nothing <$$ withLog "swapQueueLinkData" st (\s -> logSwapLink s (recipientId sq) lnkId d rKeys_) + where + qr = queueRec sq + swap q = case queueData q of + Just (lnkId', (fd', ud')) + | lnkId' /= lnkId || fd' /= fst d -> pure $ Left AUTH + | linkDataHash ud' /= h -> pure $ Right $ Just ud' + | otherwise -> do + let !q' = q {recipientKeys = fromMaybe (recipientKeys q) rKeys_, queueData = Just (lnkId, d)} + writeTVar qr (Just q') $> Right Nothing + Nothing -> pure $ Left AUTH deleteQueueLinkData :: STMQueueStore q -> q -> IO (Either ErrorType ()) deleteQueueLinkData st sq = E.uninterruptibleMask_ $ @@ -425,6 +432,27 @@ withLoadedQueues st f = readTVarIO (queues st) >>= foldM run mempty where run !acc = fmap (acc <>) . f +restoreQueueLinkData :: StoreQueueClass q => STMQueueStore q -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) +restoreQueueLinkData st sq lnkId d = atomically $ readQueueRec (queueRec sq) $>>= addLinkData st sq lnkId d + +addLinkData :: StoreQueueClass q => STMQueueStore q -> q -> LinkId -> QueueLinkData -> QueueRec -> STM (Either ErrorType ()) +addLinkData st sq lnkId d q = case queueData q of + _ | isSecuredMsgQueue q -> pure $ Left AUTH + Nothing -> addLink + Just (lnkId', d') | lnkId' == lnkId && fst d' == fst d -> addLink + _ -> pure $ Left AUTH + where + rId = recipientId sq + qr = queueRec sq + addLink = do + TM.lookup lnkId (links st) >>= \case + Just rId' | rId' /= rId -> pure $ Left AUTH + _ -> do + let !q' = q {queueData = Just (lnkId, d)} + writeTVar qr $ Just q' + TM.insert lnkId rId $ links st + pure $ Right () + withQueueRec :: TVar (Maybe QueueRec) -> (QueueRec -> STM a) -> IO (Either ErrorType a) withQueueRec qr a = atomically $ readQueueRec qr >>= mapM a diff --git a/src/Simplex/Messaging/Server/QueueStore/Types.hs b/src/Simplex/Messaging/Server/QueueStore/Types.hs index 372c411a1..28e60f388 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Types.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Types.hs @@ -33,6 +33,7 @@ class StoreQueueClass q => QueueStoreClass q s where getQueues_ :: BatchParty p => s -> (RecipientId -> QueueRec -> IO q) -> SParty p -> [QueueId] -> IO [Either ErrorType q] getQueueLinkData :: s -> q -> LinkId -> IO (Either ErrorType QueueLinkData) addQueueLinkData :: s -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) + swapQueueLinkData :: s -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) deleteQueueLinkData :: s -> q -> IO (Either ErrorType ()) secureQueue :: s -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) updateKeys :: s -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) diff --git a/src/Simplex/Messaging/Server/StoreLog.hs b/src/Simplex/Messaging/Server/StoreLog.hs index 4ceb3cddd..d12701ffc 100644 --- a/src/Simplex/Messaging/Server/StoreLog.hs +++ b/src/Simplex/Messaging/Server/StoreLog.hs @@ -19,6 +19,7 @@ module Simplex.Messaging.Server.StoreLog writeStoreLogRecord, logCreateQueue, logCreateLink, + logSwapLink, logDeleteLink, logSecureQueue, logUpdateKeys, @@ -66,6 +67,7 @@ import System.FilePath (takeDirectory, takeFileName) data StoreLogRecord = CreateQueue RecipientId QueueRec | CreateLink RecipientId LinkId QueueLinkData + | CreateLinkKeys RecipientId LinkId QueueLinkData (NonEmpty RcvPublicAuthKey) | DeleteLink RecipientId | SecureQueue QueueId SndPublicAuthKey | UpdateKeys RecipientId (NonEmpty RcvPublicAuthKey) @@ -83,6 +85,7 @@ data StoreLogRecord data SLRTag = CreateQueue_ | CreateLink_ + | CreateLinkKeys_ | DeleteLink_ | SecureQueue_ | UpdateKeys_ @@ -154,6 +157,7 @@ instance StrEncoding SLRTag where strEncode = \case CreateQueue_ -> "CREATE" CreateLink_ -> "LINK" + CreateLinkKeys_ -> "LKEYS" DeleteLink_ -> "LDELETE" SecureQueue_ -> "SECURE" UpdateKeys_ -> "KEYS" @@ -171,6 +175,7 @@ instance StrEncoding SLRTag where A.choice [ "CREATE" $> CreateQueue_, "LINK" $> CreateLink_, + "LKEYS" $> CreateLinkKeys_, "LDELETE" $> DeleteLink_, "SECURE" $> SecureQueue_, "KEYS" $> UpdateKeys_, @@ -189,6 +194,7 @@ instance StrEncoding StoreLogRecord where strEncode = \case CreateQueue rId q -> B.unwords [strEncode CreateQueue_, "rid=" <> strEncode rId, strEncode q] CreateLink rId lnkId d -> strEncode (CreateLink_, rId, lnkId, d) + CreateLinkKeys rId lnkId d rKeys -> strEncode (CreateLinkKeys_, rId, lnkId, d, rKeys) DeleteLink rId -> strEncode (DeleteLink_, rId) SecureQueue rId sKey -> strEncode (SecureQueue_, rId, sKey) UpdateKeys rId rKeys -> strEncode (UpdateKeys_, rId, rKeys) @@ -206,6 +212,7 @@ instance StrEncoding StoreLogRecord where strP_ >>= \case CreateQueue_ -> CreateQueue <$> ("rid=" *> strP_) <*> strP CreateLink_ -> CreateLink <$> strP_ <*> strP_ <*> strP + CreateLinkKeys_ -> CreateLinkKeys <$> strP_ <*> strP_ <*> strP_ <*> strP DeleteLink_ -> DeleteLink <$> strP SecureQueue_ -> SecureQueue <$> strP_ <*> strP UpdateKeys_ -> UpdateKeys <$> strP_ <*> strP @@ -253,6 +260,13 @@ logCreateQueue s rId q = writeStoreLogRecord s $ CreateQueue rId q logCreateLink :: StoreLog 'WriteMode -> RecipientId -> LinkId -> QueueLinkData -> IO () logCreateLink s rId lnkId d = writeStoreLogRecord s $ CreateLink rId lnkId d +logSwapLink :: StoreLog 'WriteMode -> RecipientId -> LinkId -> QueueLinkData -> Maybe (NonEmpty RcvPublicAuthKey) -> IO () +logSwapLink s rId lnkId d = \case + Just rKeys -> do + writeStoreLogRecord s $ CreateLinkKeys rId lnkId d rKeys + logUpdateKeys s rId rKeys + Nothing -> logCreateLink s rId lnkId d + logDeleteLink :: StoreLog 'WriteMode -> RecipientId -> IO () logDeleteLink s = writeStoreLogRecord s . DeleteLink diff --git a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs index 14e0461ad..e3af87fd4 100644 --- a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs +++ b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs @@ -20,10 +20,10 @@ import Data.Text.Encoding (decodeLatin1) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ASubscriberParty (..), ErrorType, RecipientId, SParty (..)) import Simplex.Messaging.Server.QueueStore (QueueRec, ServiceRec (..)) -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), STMService (..), withLoadedQueues) +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), STMService (..), restoreQueueLinkData, withLoadedQueues) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.StoreLog -import Simplex.Messaging.Util (tshow, ($>>=)) +import Simplex.Messaging.Util (tshow, ($>>), ($>>=)) import System.IO writeQueueStore :: forall q. StoreQueueClass q => StoreLog 'WriteMode -> STMQueueStore q -> IO () @@ -43,7 +43,8 @@ readQueueStore tty mkQ f st = readLogLines tty f $ \_ -> processLine procLogRecord :: StoreLogRecord -> IO () procLogRecord = \case CreateQueue rId qr -> addQueue_ st mkQ rId qr >>= qError rId "CreateQueue" - CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> addQueueLinkData st q lnkId d + CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> restoreQueueLinkData st q lnkId d + CreateLinkKeys rId lnkId d rKeys -> withQueue rId "CreateLinkKeys" $ \q -> restoreQueueLinkData st q lnkId d $>> updateKeys st q rKeys DeleteLink rId -> withQueue rId "DeleteLink" $ \q -> deleteQueueLinkData st q SecureQueue qId sKey -> withQueue qId "SecureQueue" $ \q -> secureQueue st q sKey UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q Nothing rKeys diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index d31276d6c..2a99ff7ac 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -31,17 +31,18 @@ import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Simplex.Messaging.Crypto (pattern MaxLenBS) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (strEncode) -import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), noMsgFlags, randomMsgId) +import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), linkDataHash, noMsgFlags, randomMsgId) import Simplex.Messaging.Server.MsgStore.STM import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.NtfStore import Simplex.Messaging.Server.QueueStore import Simplex.Messaging.Server.QueueStore.QueueInfo -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), withLog') +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), readQueueRecIO, withLog') import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..), closeStoreLog, openWriteStoreLog) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM +import Simplex.Messaging.Util (($>>=)) import SMPClient (testStoreLogFile) import System.IO.Unsafe (unsafeInterleaveIO) import System.Timeout (timeout) @@ -95,6 +96,7 @@ msgStoreTests = do it "should peek the first message of each queue in a batch" $ withMsgStore cfg testPeekMsgs it "should not add link data to secured messaging queue" $ withMsgStore cfg testLinkDataSecuredQueue it "should not update recipient keys changed after the command was verified" $ withMsgStore cfg testUpdateChangedKeys + it "should swap link data and recipient keys" $ withMsgStore cfg testSwapQueueLinkData -- TODO constrain to STM stores? withMsgStore :: MsgStoreClass s => MsgStoreConfig s -> (s -> IO ()) -> IO () @@ -308,6 +310,45 @@ testUpdateChangedKeys ms = do (_, QueueRec {recipientKeys}) <- ExceptT $ getQueueRec ms SRecipient rId liftIO $ recipientKeys `shouldBe` [k1] void $ ExceptT $ deleteQueue ms q +testSwapQueueLinkData :: MsgStoreClass s => s -> IO () +testSwapQueueLinkData ms = do + g <- C.newRandom + (rKey2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let st = queueStore ms + rndId = atomically $ EntityId <$> C.randomBytes 24 g + (fd, ud) = testLinkData + d1 = (fd, EncDataBytes "user data 1") + d2 = (fd, EncDataBytes "user data 2") + lnkId <- rndId + otherLnkId <- rndId + (rId, qr) <- testNewQueueRecData g QMContact (Just (lnkId, testLinkData)) + (noLinkRId, noLinkQr) <- testNewQueueRec g QMContact + let rKeys = recipientKeys qr <> [rKey2] + storedKeys = fmap recipientKeys <$> (getQueue ms SRecipient rId $>>= readQueueRecIO . queueRec) + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + noLinkQ <- ExceptT $ addQueue ms noLinkRId noLinkQr + liftIO $ do + swapQueueLinkData st noLinkQ lnkId (linkDataHash ud) Nothing d1 `shouldReturn` Left AUTH + swapQueueLinkData st q otherLnkId (linkDataHash ud) Nothing d1 `shouldReturn` Left AUTH + swapQueueLinkData st q lnkId (linkDataHash ud) Nothing (EncDataBytes "other fixed data", snd d1) `shouldReturn` Left AUTH + swapQueueLinkData st q lnkId (linkDataHash $ snd d1) (Just rKeys) d1 `shouldReturn` Right (Just ud) + getQueueLinkData st q lnkId `shouldReturn` Right testLinkData + storedKeys `shouldReturn` Right (recipientKeys qr) + swapQueueLinkData st q lnkId (linkDataHash ud) Nothing d1 `shouldReturn` Right Nothing + getQueueLinkData st q lnkId `shouldReturn` Right d1 + staleQ <- ExceptT $ getQueue ms SRecipient rId + liftIO $ do + swapQueueLinkData st q lnkId (linkDataHash $ snd d1) (Just rKeys) d2 `shouldReturn` Right Nothing + getQueueLinkData st q lnkId `shouldReturn` Right d2 + storedKeys `shouldReturn` Right rKeys + addQueueLinkData st staleQ lnkId d1 `shouldReturn` Left AUTH + freshQ <- ExceptT $ getQueue ms SRecipient rId + liftIO $ do + addQueueLinkData st freshQ lnkId d1 `shouldReturn` Left AUTH + getQueueLinkData st freshQ lnkId `shouldReturn` Right d2 + void $ ExceptT $ deleteQueue ms q + void $ ExceptT $ deleteQueue ms noLinkQ -- sizes of queues, senders, links and notifiers maps type QueueMapSizes = (Int, Int, Int, Int) diff --git a/tests/CoreTests/StoreLogTests.hs b/tests/CoreTests/StoreLogTests.hs index 45116d4a5..fb615551c 100644 --- a/tests/CoreTests/StoreLogTests.hs +++ b/tests/CoreTests/StoreLogTests.hs @@ -31,7 +31,7 @@ import Simplex.Messaging.Server.Env.STM (readWriteQueueStore) import Simplex.Messaging.Server.MsgStore.STM (STMMsgStore (..)) import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.QueueStore -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..)) +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), setStoreLog) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.StoreLog import Simplex.Messaging.SystemTime @@ -61,7 +61,8 @@ deriving instance Eq StoreLogRecord deriving instance Eq NtfCreds storeLogTests :: Spec -storeLogTests = +storeLogTests = do + it "should log link data swaps and restore them" testSwapLinkStoreLog forM_ [QMMessaging, QMContact] $ \qm -> do g <- runIO C.newRandom ((rId, qr), ntfCreds, date, sr@ServiceRec {serviceId}) <- runIO $ @@ -75,6 +76,9 @@ storeLogTests = rcvSr = sr {serviceRole = SRMessaging} blockedWithNotice = BlockingInfo {reason = BRContent, notice = Just ClientNotice {ttl = Just 86400}} newKeys <- runIO $ L.fromList <$> sequence [pubKey, pubKey] + newKeys' <- runIO $ L.fromList <$> sequence [pubKey, pubKey, pubKey] + let qd' = (fst qd, EncDataBytes "user data 1") + qd'' = (fst qd, EncDataBytes "user data 2") testSMPStoreLog ("SMP server store log, queueMode = " <> show qm) [ SLTC @@ -148,6 +152,18 @@ storeLogTests = saved = [CreateQueue rId qr, UpdateKeys rId newKeys], compacted = [CreateQueue rId qr {recipientKeys = newKeys}], state = M.fromList [(rId, qr {recipientKeys = newKeys})] + }, + SLTC + { name = "swap link data and recipient keys twice", + saved = [CreateQueue rId' qr', CreateLinkKeys rId' lnkId qd' newKeys, UpdateKeys rId' newKeys, CreateLinkKeys rId' lnkId qd'' newKeys', UpdateKeys rId' newKeys'], + compacted = [CreateQueue rId' qr' {recipientKeys = newKeys', queueData = Just (lnkId, qd'')}], + state = M.fromList [(rId', qr' {recipientKeys = newKeys', queueData = Just (lnkId, qd'')})] + }, + SLTC + { name = "swap link data and recipient keys, then swap link data", + saved = [CreateQueue rId' qr', CreateLinkKeys rId' lnkId qd' newKeys, UpdateKeys rId' newKeys, CreateLink rId' lnkId qd''], + compacted = [CreateQueue rId' qr' {recipientKeys = newKeys, queueData = Just (lnkId, qd'')}], + state = M.fromList [(rId', qr' {recipientKeys = newKeys, queueData = Just (lnkId, qd'')})] } ] @@ -193,6 +209,30 @@ testSMPStoreLog testSuite tests = storeState :: STMMsgStore -> IO (M.Map RecipientId QueueRec) storeState st = M.mapMaybe id <$> (readTVarIO (queues $ queueStore st) >>= mapM (readTVarIO . queueRec)) +testSwapLinkStoreLog :: HasTestEnv => IO () +testSwapLinkStoreLog = do + g <- C.newRandom + lnkId <- atomically $ EntityId <$> C.randomBytes 24 g + (rId, qr) <- testNewQueueRecData g QMContact (Just (lnkId, testLinkData)) + (rKey2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let (fd, ud) = testLinkData + d1 = (fd, EncDataBytes "user data 1") + d2 = (fd, EncDataBytes "user data 2") + rKeys = rKey2 L.<| recipientKeys qr + ms <- newMsgStore testSMTStoreConfig + setStoreLog (queueStore ms) =<< openWriteStoreLog False testStoreLogFile + Right q <- addQueue ms rId qr + swapQueueLinkData (queueStore ms) q lnkId (linkDataHash ud) (Just rKeys) d1 `shouldReturn` Right Nothing + swapQueueLinkData (queueStore ms) q lnkId (linkDataHash $ snd d1) Nothing d2 `shouldReturn` Right Nothing + closeMsgStore ms + ([], logged) <- partitionEithers . map strDecode . B.lines <$> B.readFile testStoreLogFile + logged `shouldBe` [CreateQueue rId qr, CreateLinkKeys rId lnkId d1 rKeys, UpdateKeys rId rKeys, CreateLink rId lnkId d2] + ms' <- newMsgStore testSMTStoreConfig + sl <- readWriteQueueStore True (mkQueue ms') testStoreLogFile $ queueStore ms' + Right q' <- getQueue ms' SRecipient rId + readTVarIO (queueRec q') `shouldReturn` Just qr {recipientKeys = rKeys, queueData = Just (lnkId, d2)} + closeStoreLog sl + type FileRecState = (FileInfo, RoundedFileTime, Maybe RoundedFileTime, ServerEntityStatus) type XFTPStoreLogTestCase = StoreLogTestCase FileStoreLogRecord (M.Map SenderId FileRecState) From 16c9a126f462d16701773daec5991679f34111bd Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:24:32 -0500 Subject: [PATCH 141/159] server: restore short-link keys with concurrency-aware API --- src/Simplex/Messaging/Protocol.hs | 2 -- src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index d502f68da..aa66a2a68 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -61,8 +61,6 @@ module Simplex.Messaging.Protocol QueueReqData (..), QueueMode (..), QueueLinkData, - LinkDataHash, - linkDataHash, EncFixedDataBytes, EncUserDataBytes, EncDataBytes (..), diff --git a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs index e3af87fd4..1bb279882 100644 --- a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs +++ b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs @@ -44,7 +44,7 @@ readQueueStore tty mkQ f st = readLogLines tty f $ \_ -> processLine procLogRecord = \case CreateQueue rId qr -> addQueue_ st mkQ rId qr >>= qError rId "CreateQueue" CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> restoreQueueLinkData st q lnkId d - CreateLinkKeys rId lnkId d rKeys -> withQueue rId "CreateLinkKeys" $ \q -> restoreQueueLinkData st q lnkId d $>> updateKeys st q rKeys + CreateLinkKeys rId lnkId d rKeys -> withQueue rId "CreateLinkKeys" $ \q -> restoreQueueLinkData st q lnkId d $>> updateKeys st q Nothing rKeys DeleteLink rId -> withQueue rId "DeleteLink" $ \q -> deleteQueueLinkData st q SecureQueue qId sKey -> withQueue qId "SecureQueue" $ \q -> secureQueue st q sKey UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q Nothing rKeys From dbbe5c7e9ea0def554e34863c4e2d010ef5e879d Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:27:31 -0500 Subject: [PATCH 142/159] tests: restore service notification and switch regressions --- tests/AgentTests/FunctionalAPITests.hs | 73 -------------------------- tests/FileDescriptionTests.hs | 2 +- tests/ServerTests.hs | 37 +++++++++++++ 3 files changed, 38 insertions(+), 74 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index e8e9d8b75..6b2f8066e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4489,79 +4489,6 @@ testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer p (timeout 20_000000 (runRight_ $ drainSwitchCompleted a' bId QDRcv) `shouldReturn` Just ()) (timeout 20_000000 (runRight_ $ drainSwitchCompleted b aId QDSnd) `shouldReturn` Just ()) -testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () -testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = - withSmpServer ps $ - withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do - (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b - setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] - withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withGatedServerOn testPort2 testPort3 $ \accepted opened -> - withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do - timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () - void . runRight $ changeSwitch b aId - atomically $ putTMVar opened () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) - runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' - waitRcvQueueRecords b 1 - storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) - -testSwitchRatchetSyncBeforeNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () -testSwitchRatchetSyncBeforeNewQueue ps@(t, _) = - withSmpServer ps $ - withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do - (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b - setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] - withSmpServerConfigOn t cfgS2 testPort2 $ \_ -> do - setUserNetworkInfo b $ UserNetworkInfo UNNone False - runRight_ $ do - void $ switchConnectionAsync b "" aId - void $ synchronizeRatchet b aId PQSupportOn True - setUserNetworkInfo b $ UserNetworkInfo UNWifi True - get b =##> \case ("", c, ERR (A.CMD PROHIBITED "switchConnection: send prohibited")) -> c == aId; _ -> False - runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' - storeLogQueues testStoreLogFile2 `shouldReturn` (0, 0) - -waitRcvQueueRecords :: HasCallStack => AgentClient -> Int -> IO () -waitRcvQueueRecords c n = go (50 :: Int) - where - go i = do - qs :: [(ConnId, Int64)] <- withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, rcv_queue_id FROM rcv_queues") - unless (length qs == n) $ - if i > 0 - then threadDelay 100000 >> go (i - 1) - else expectationFailure $ "receive queue records: " <> show qs - -storeLogQueues :: FilePath -> IO (Int, Int) -storeLogQueues storeLogFile = do - records <- B.lines <$> B.readFile storeLogFile - pure (count "CREATE " records, count "DELETE " records) - where - count tag = length . filter (tag `B.isPrefixOf`) - -testFastSwitchRatchetSyncWhileSecuring :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () -testFastSwitchRatchetSyncWhileSecuring ps@(t, ASType qsType _) = withSmpServer ps $ do - a <- getSMPAgentClient' 1 agentCfg initAgentServers testDB - (aId, bId) <- withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight $ makeConnection a b - setProtocolServers a 1 [noAuthSrvCfg testSMPServer2] - withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do - _ <- switchConnectionAsync a "" bId - phaseRcv a bId SPStarted [Just RSSendingQADD, Nothing] - withAgent 3 agentCfg initAgentServers testDB2 $ \b -> do - runRight_ $ do - subscribeConnection b aId - phaseSnd b aId SPStarted [Just SSSecuringQueue, Nothing] - disposeAgentClient a - ConnectionStats {ratchetSyncState} <- runRight $ synchronizeRatchet b aId PQSupportOn True - ratchetSyncState `shouldBe` RSStarted - withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> do - threadDelay 3000000 - withAgent 4 agentCfg initAgentServers testDB $ \a' -> do - runRight_ $ subscribeConnection a' bId - concurrently_ - (timeout 20_000000 (runRight_ $ drainSwitchCompleted a' bId QDRcv) `shouldReturn` Just ()) - (timeout 20_000000 (runRight_ $ drainSwitchCompleted b aId QDSnd) `shouldReturn` Just ()) - endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b diff --git a/tests/FileDescriptionTests.hs b/tests/FileDescriptionTests.hs index ce9c7c1a5..89424091b 100644 --- a/tests/FileDescriptionTests.hs +++ b/tests/FileDescriptionTests.hs @@ -307,7 +307,7 @@ testFileWebLinkIPv6 = do replaceChunk c = c withPrimaryServer _ fd = fd -withRemoveTmpFile :: IO () -> IO () +withRemoveTmpFile :: HasTestEnv => IO () -> IO () withRemoveTmpFile = bracket_ (pure ()) diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index a8c80371f..2a65e3cfb 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -2385,6 +2385,43 @@ testServiceNotificationsReturnToConnection = Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg nh2 pure () +testServiceNotificationsRepeatedNSUB :: SpecWith (ASrvTransport, AStoreType) +testServiceNotificationsRepeatedNSUB = + it "should end the service subscription to a notifier once when NSUB is repeated in one block" $ \(ATransport t, msType) -> do + g <- C.newRandom + smpTest3 t msType $ \rh sh nh@THandle {params} -> do + let createNtfQueue = do + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (sId, rId, rKey, _) <- createAndSecureQueue rh sPub + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvNtfPubDhKey, _) <- atomically $ C.generateKeyPair g + Resp "1" _ (NID nId _) <- signSendRecv rh rKey ("1", rId, NKEY nPub rcvNtfPubDhKey) + pure (sId, sKey, rId, rKey, nId, nKey) + (sId1, sKey1, rId1, rKey1, nId1, nKey1) <- createNtfQueue + (_, _, _, _, nId2, nKey2) <- createNtfQueue + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + testNtfServiceClient t serviceKeys $ \snh -> do + Resp "2" _ (SOK (Just serviceId)) <- serviceSignSendRecv snh nKey1 servicePK ("2", nId1, NSUB) + Resp "3" _ (SOK (Just _)) <- serviceSignSendRecv snh nKey2 servicePK ("3", nId2, NSUB) + let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth params (CorrId "4", nId2, NSUB) + Right auth <- pure $ authTransmission (thAuth params) False (Just nKey2) Nothing tForAuth + let nsub = Right (auth, tToSend) + [Right (), Right (), Right ()] <- tPut nh [nsub, nsub, nsub] + [Resp "4" _ (SOK Nothing), Resp "4" _ (SOK Nothing), Resp "4" _ (SOK Nothing)] <- tGetClient nh + Resp "" nId2' END <- tGet1 snh + nId2' `shouldBe` nId2 + Resp "5" _ OK <- signSendRecv sh sKey1 ("5", sId1, _SEND' "hello") + Resp "" _ (Msg mId _) <- tGet1 rh + Resp "6" _ OK <- signSendRecv rh rKey1 ("6", rId1, ACK mId) + Resp "" nId1' (NMSG _ _) <- tGet1 snh + nId1' `shouldBe` nId1 + testNtfServiceClient t serviceKeys $ \snh' -> do + let idsHash = queueIdsHash [nId1] + Resp "7" _ (SOKS 1 idsHash') <- signSendRecv snh' (C.APrivateAuthKey C.SEd25519 servicePK) ("7", serviceId, NSUBS 1 idsHash) + idsHash' `shouldBe` idsHash + Resp "" _ (ENDS n idsHash'') <- tGet1 snh + (n, idsHash'') `shouldBe` (1, idsHash) + testMsgExpireOnSend :: SpecWith (ASrvTransport, AStoreType) testMsgExpireOnSend = it "should expire messages that are not received before messageTTL on SEND" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do From ae4b294f9e9bd00fb13e35e0f54d6b667e5ee1e2 Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 30 Sep 2026 14:04:34 +0000 Subject: [PATCH 143/159] smp-server: limit forwards in flight per relay --- src/Simplex/Messaging/Server.hs | 22 +++++++---- src/Simplex/Messaging/Server/Env/STM.hs | 17 +++++++-- src/Simplex/Messaging/Server/Main.hs | 1 + src/Simplex/Messaging/Server/Main/Init.hs | 2 + tests/SMPClient.hs | 1 + tests/SMPProxyTests.hs | 45 ----------------------- tests/XFTPAgent.hs | 2 +- tests/XFTPServerTests.hs | 17 +-------- 8 files changed, 35 insertions(+), 72 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 8d7914964..0ef3d7441 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1626,24 +1626,32 @@ client Nothing -> ERR $ transportErr TENoServerAuth _ -> ERR $ transportErr TEVersion PFWD fwdV pubKey encBlock -> do - ProxyAgent {smpAgent = a} <- asks proxyAgent + ProxyAgent {smpAgent = a, relayForwards} <- asks proxyAgent ServerStats {pMsgFwds, pMsgFwdsOwn, pMsgFwdsBelow23, pMsgFwdsFrom23} <- asks serverStats let inc = mkIncProxyStats pMsgFwds pMsgFwdsOwn liftIO (lookupSMPServerClient a sessId) >>= \case Just (own, smp) | Right fwdCorrId <- C.corrCbNonce (bs corrId) -> do inc own pRequests incStat $ if fwdV < fwdNoncesSMPVersion then pMsgFwdsBelow23 else pMsgFwdsFrom23 - forkProxiedCmd $ do - liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case - Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses - Left e -> ERR (smpProxyError e) <$ case e of - PCEProtocolError {} -> inc own pSuccesses - _ -> inc own pErrorsOther + maxFwds <- asks $ proxyRelayConcurrency . config + forkProxiedCmd $ + bracket (atomically $ reserve maxFwds relayForwards) (\r -> when r $ atomically $ release relayForwards) $ \case + False -> ERR (smpProxyError PCEResponseTimeout) <$ inc own pErrorsOther + True -> + liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case + Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses + Left e -> ERR (smpProxyError e) <$ case e of + PCEProtocolError {} -> inc own pSuccesses + _ -> inc own pErrorsOther Just _ -> pure $ Just $ ERR $ CMD SYNTAX Nothing -> inc False pRequests >> inc False pErrorsConnect $> Just (ERR $ PROXY NO_SESSION) where forkProxiedCmd :: M s BrokerMsg -> M s (Maybe BrokerMsg) forkProxiedCmd = forkCmd serverClientConcurrency corrId (EntityId sessId) (ERR $ smpProxyError PCEResponseTimeout) + reserve maxFwds v = stateTVar' v $ \fwds -> case M.lookup sessId fwds of + Just n | n >= maxFwds -> (False, fwds) + n_ -> (True, M.insert sessId (maybe 1 (+ 1) n_) fwds) + release v = modifyTVar' v $ M.update (\n -> if n > 1 then Just (n - 1) else Nothing) sessId -- Run a slow command on a thread, responding with timeoutErr if it was not started before the client timeout forkCmd :: (ServerConfig s -> Int) -> CorrId -> EntityId -> BrokerMsg -> M s BrokerMsg -> M s (Maybe a) forkCmd concurrency corrId entId timeoutErr cmdAction = diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 10c47d90b..80a760e14 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -70,6 +70,7 @@ module Simplex.Messaging.Server.Env.STM defaultInactiveClientExpiration, defaultProxyClientConcurrency, defaultProxyConnectConcurrency, + defaultProxyRelayConcurrency, defaultNameResolverConcurrency, defaultForwardWorkers, defaultMaxClientCmdWait, @@ -133,7 +134,7 @@ import Simplex.Messaging.Server.StoreLog.ReadWrite import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, THandleParams, TransportPeer (..), VersionRangeSMP) +import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, SessionId, THandleParams, TransportPeer (..), VersionRangeSMP) import Simplex.Messaging.Transport.Server import Simplex.Messaging.Util (ifM, tshow, whenM, ($>>=)) import System.Directory (doesFileExist) @@ -204,6 +205,8 @@ data ServerConfig s = ServerConfig smpAgentCfg :: SMPClientAgentConfig, allowSMPProxy :: Bool, -- auth is the same with `newQueueBasicAuth` serverClientConcurrency :: Int, + -- | max forwarded commands awaiting a response from one destination relay + proxyRelayConcurrency :: Int, -- | max concurrent forwarded name resolutions per proxy connection, enforced in forkCmd. -- Much higher than serverClientConcurrency: forwarded RSLVs from many clients -- aggregate over a single proxy->relay connection (only servers send proxied @@ -263,6 +266,9 @@ defaultProxyClientConcurrency = 500 defaultProxyConnectConcurrency :: Int defaultProxyConnectConcurrency = 1000 +defaultProxyRelayConcurrency :: Int +defaultProxyRelayConcurrency = 512 + defaultNameResolverConcurrency :: Int defaultNameResolverConcurrency = 5000 @@ -442,8 +448,10 @@ data ClientSub | CSDeleted QueueId (Maybe ServiceId) -- includes previously associated service IDs | CSService ServiceId (Int64, IdsHash) -- only send END to idividual client subs on message delivery, not of SSUB/NSSUB -newtype ProxyAgent = ProxyAgent - { smpAgent :: SMPClientAgent 'Sender +data ProxyAgent = ProxyAgent + { smpAgent :: SMPClientAgent 'Sender, + -- forwarded commands awaiting a response, per relay session + relayForwards :: TVar (Map SessionId Int) } type ClientId = Int @@ -717,7 +725,8 @@ noPostgresExitStr = newSMPProxyAgent :: SMPClientAgentConfig -> TVar ChaChaDRG -> IO ProxyAgent newSMPProxyAgent smpAgentCfg random = do smpAgent <- newSMPClientAgent SSender smpAgentCfg Nothing random - pure ProxyAgent {smpAgent} + relayForwards <- newTVarIO mempty + pure ProxyAgent {smpAgent, relayForwards} readWriteQueueStore :: forall q. StoreQueueClass q => Bool -> (RecipientId -> QueueRec -> IO q) -> FilePath -> STMQueueStore q -> IO (StoreLog 'WriteMode) readWriteQueueStore tty mkQ = readWriteStoreLog (readQueueStore tty mkQ) (writeQueueStore @q) diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index c3e67d1cf..ba7506ef9 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -537,6 +537,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = }, allowSMPProxy = True, serverClientConcurrency = readIniDefault defaultProxyClientConcurrency "PROXY" "client_concurrency" ini, + proxyRelayConcurrency = readIniDefault defaultProxyRelayConcurrency "PROXY" "relay_concurrency" ini, serverResolverConcurrency = readIniDefault defaultNameResolverConcurrency "NAMES" "resolver_concurrency" ini, serverForwardWorkers = readIniDefault defaultForwardWorkers "PROXY" "forward_workers" ini, maxClientCmdWait = defaultMaxClientCmdWait, diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index c45acd981..c30be4087 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -165,6 +165,8 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> "\n\n\ \# Limit number of connections to destination servers being established at once.\n" <> ("# connect_concurrency = " <> tshow defaultProxyConnectConcurrency) + \# Limit number of messages forwarded to one destination server and awaiting its response.\n" + <> ("# relay_concurrency = " <> tshow defaultProxyRelayConcurrency) <> "\n\n\ \[NAMES]\n\ \# Public-namespace resolution via the snrc-resolve.py REST resolver.\n\ diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index dff0b3973..9b2be6f97 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -285,6 +285,7 @@ cfgMS msType = withStoreCfg (testServerStoreConfig msType) $ \serverStoreCfg -> smpAgentCfg = defaultSMPClientAgentConfig {persistErrorInterval = 1, msgQSize = Nothing}, -- seconds allowSMPProxy = False, serverClientConcurrency = 2, + proxyRelayConcurrency = defaultProxyRelayConcurrency, serverResolverConcurrency = defaultNameResolverConcurrency, serverForwardWorkers = defaultForwardWorkers, maxClientCmdWait = defaultMaxClientCmdWait, diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 035f653fb..de3819d50 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -836,51 +836,6 @@ testLateResponseCommandReleased = (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () -testForwardOversizedNotKept :: HasTestEnv => IO () -testForwardOversizedNotKept = - withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - let proxyClientCfg = defaultSMPClientConfig {serverVRange = supportedProxyClientSMPRelayVRange, agreeSecret = True, proxyServer = True} - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) proxyClientCfg [] Nothing ts (\_ -> pure ()) - (k, _) <- atomically $ C.generateKeyPair @'C.X25519 g - let et = SMP.EncTransmission $ B.replicate smpBlockSize 'a' - runExceptT (forwardSMPTransmission c (either error id $ C.corrCbNonce "123456789012345678901234") currentClientSMPRelayVersion k et) - `shouldReturn` Left (PCETransportError TELargeMsg) - pClientSentCommandsCount c `shouldReturn` 0 - -testClosedClientCommandsFail :: HasTestEnv => IO () -testClosedClientCommandsFail = - withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - closed <- newEmptyTMVarIO - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) - closeProtocolClient c - atomically $ takeTMVar closed - Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) - forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) - pClientSentCommandsCount c `shouldReturn` 0 - atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 - -testLateResponseCommandReleased :: HasTestEnv => IO () -testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) - rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g - (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) - `shouldReturn` Left PCEResponseTimeout - pClientSentCommandsCount c `shouldReturn` 1 - threadDelay 1000000 - pClientSentCommandsCount c `shouldReturn` 0 - (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ - pure () - -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index 84d917a16..50548a34c 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -31,7 +31,7 @@ import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay) import Data.Time.Clock.System (getSystemTime, systemSeconds) import GHC.Conc (BlockReason (BlockedOnSTM), ThreadStatus (ThreadBlocked), threadStatus) import SMPAgentClient (agentCfg, initAgentServers, noAuthSrvCfg, testDB, testDB2, testDB3, userServers) -import SMPClient (testHost2, withStallingServerOn', xit'') +import SMPClient (testHost2, withStallingServerOn') import Simplex.FileTransfer.Client (XFTPClientConfig (..)) import Simplex.FileTransfer.Description (ChunkReplicaId (..), FileChunk (..), FileChunkReplica (..), FileDescription (..), FileDescriptionURI (..), FileDigest (..), FileSize (..), ValidFileDescription, fileDescriptionURI, kb, mb, qrSizeLimit, validateFileDescription, pattern ValidFileDescription) import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..), SFileParty (..)) diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 16b12bc4d..648a35b4e 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -63,7 +63,7 @@ import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..), defaultHTTP2BufferSize import Simplex.Messaging.Transport.HTTP2.File (fileBlockSize) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) -import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential) +import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential, newSocketState) import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts) import Simplex.Messaging.Util (bshow, unlessM, whenM) import Simplex.Messaging.Version (mkVersionRange) @@ -353,19 +353,6 @@ testReceiveFileTimeout :: HasTestEnv => Expectation testReceiveFileTimeout = timeout 100000 (runExceptT $ receiveFile (\_ -> "" <$ threadDelay maxBound) $ XFTPRcvChunkSpec testChunkPath chSize "") `shouldReturn` Nothing -testTLSHandshakeTimeout :: HasTestEnv => Expectation -testTLSHandshakeTimeout = - withStallingServerOn xftpTestPort $ - timeout 1000000 (runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort Nothing $ \(_ :: TLS 'TClient) -> pure ()) - `shouldReturn` Nothing - where - cfg :: TransportClientConfig - cfg = defaultTransportClientConfig {logTLSErrors = True} - -testReceiveFileTimeout :: HasTestEnv => Expectation -testReceiveFileTimeout = - timeout 100000 (runExceptT $ receiveFile (\_ -> "" <$ threadDelay maxBound) $ XFTPRcvChunkSpec testChunkPath chSize "") `shouldReturn` Nothing - testFileStorageQuota :: HasTestEnv => AFStoreType -> Expectation testFileStorageQuota fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileSizeQuota = Just $ chSize * 2}) $ \_ -> testXFTPClient $ \c -> runRight_ $ do @@ -967,7 +954,7 @@ withHeldHTTP2Requests action = do cfg = HC.defaultHTTP2ClientConfig {HC.qSize = 1, HC.connTimeout = 1000000, HC.suportedTLSParams = defaultSupportedParams} connect = either (error . show) pure =<< HC.getVerifiedHTTP2Client Nothing (THDomainName "localhost") xftpTestPort (Just $ C.KeyHash fp) Nothing cfg (pure ()) serverBracket - (\started -> runHTTP2Server started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> pure ()) hold) + (\started -> newSocketState >>= \ss -> runHTTP2Server ss started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> pure ()) hold) (pure ()) $ \_ -> bracket connect HC.closeHTTP2Client $ \c -> action (HC.sendRequest c $ H2.requestNoBody "POST" "/" []) received release From 3181f3e1fb7744ef0c9f4c8db87332a83f8ca6e7 Mon Sep 17 00:00:00 2001 From: shum Date: Wed, 14 Oct 2026 15:20:43 +0000 Subject: [PATCH 144/159] smp-server: count forwards above relay limit --- src/Simplex/Messaging/Server.hs | 4 ++-- src/Simplex/Messaging/Server/Prometheus.hs | 5 +++++ src/Simplex/Messaging/Server/Stats.hs | 8 ++++++++ tests/SMPProxyTests.hs | 3 +++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 0ef3d7441..57dea9eb4 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1627,7 +1627,7 @@ client _ -> ERR $ transportErr TEVersion PFWD fwdV pubKey encBlock -> do ProxyAgent {smpAgent = a, relayForwards} <- asks proxyAgent - ServerStats {pMsgFwds, pMsgFwdsOwn, pMsgFwdsBelow23, pMsgFwdsFrom23} <- asks serverStats + ServerStats {pMsgFwds, pMsgFwdsOwn, pMsgFwdsBelow23, pMsgFwdsFrom23, pMsgFwdsRelayLimit} <- asks serverStats let inc = mkIncProxyStats pMsgFwds pMsgFwdsOwn liftIO (lookupSMPServerClient a sessId) >>= \case Just (own, smp) | Right fwdCorrId <- C.corrCbNonce (bs corrId) -> do @@ -1636,7 +1636,7 @@ client maxFwds <- asks $ proxyRelayConcurrency . config forkProxiedCmd $ bracket (atomically $ reserve maxFwds relayForwards) (\r -> when r $ atomically $ release relayForwards) $ \case - False -> ERR (smpProxyError PCEResponseTimeout) <$ inc own pErrorsOther + False -> ERR (smpProxyError PCEResponseTimeout) <$ (inc own pErrorsOther >> incStat pMsgFwdsRelayLimit) True -> liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index 360142630..945f864d2 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -135,6 +135,7 @@ prometheusMetrics sm rtm ts = _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, _rcvServices, _ntfServices, _rcvServicesSubMsg, @@ -413,6 +414,10 @@ prometheusMetrics sm rtm ts = \simplex_smp_relay_messages_errors{source=\"own\",type=\"compat\"} " <> mshow (_pErrorsCompat _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pErrorsCompat\n\ \simplex_smp_relay_messages_errors{source=\"own\",type=\"other\"} " <> mshow (_pErrorsOther _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pErrorsOther\n\ \\n\ + \# HELP simplex_smp_relay_messages_concurrency_limit Messages not sent through relay, as the limit of messages in flight to relay was reached.\n\ + \# TYPE simplex_smp_relay_messages_concurrency_limit counter\n\ + \simplex_smp_relay_messages_concurrency_limit " <> mshow _pMsgFwdsRelayLimit <> "\n# pMsgFwdsRelayLimit\n\ + \\n\ \# HELP simplex_smp_relay_messages_received Relay messages statistics.\n\ \# TYPE simplex_smp_relay_messages_received counter\n\ \simplex_smp_relay_messages_received " <> mshow _pMsgFwdsRecv <> "\n# pMsgFwdsRecv\n\ diff --git a/src/Simplex/Messaging/Server/Stats.hs b/src/Simplex/Messaging/Server/Stats.hs index 141e1c279..d27649557 100644 --- a/src/Simplex/Messaging/Server/Stats.hs +++ b/src/Simplex/Messaging/Server/Stats.hs @@ -134,6 +134,7 @@ data ServerStats = ServerStats pMsgFwdsFrom23 :: IORef Int, pMsgFwdsRecvBelow23 :: IORef Int, pMsgFwdsRecvFrom23 :: IORef Int, + pMsgFwdsRelayLimit :: IORef Int, rcvServices :: ServiceStats, ntfServices :: ServiceStats, rcvServicesSubMsg :: IORef Int, @@ -209,6 +210,7 @@ data ServerStatsData = ServerStatsData _pMsgFwdsFrom23 :: Int, _pMsgFwdsRecvBelow23 :: Int, _pMsgFwdsRecvFrom23 :: Int, + _pMsgFwdsRelayLimit :: Int, _ntfServices :: ServiceStatsData, _rcvServices :: ServiceStatsData, _rcvServicesSubMsg :: Int, @@ -285,6 +287,7 @@ newServerStats trackPending ts = do pMsgFwdsFrom23 <- newIORef 0 pMsgFwdsRecvBelow23 <- newIORef 0 pMsgFwdsRecvFrom23 <- newIORef 0 + pMsgFwdsRelayLimit <- newIORef 0 rcvServices <- newServiceStats ntfServices <- newServiceStats rcvServicesSubMsg <- newIORef 0 @@ -358,6 +361,7 @@ newServerStats trackPending ts = do pMsgFwdsFrom23, pMsgFwdsRecvBelow23, pMsgFwdsRecvFrom23, + pMsgFwdsRelayLimit, rcvServices, ntfServices, rcvServicesSubMsg, @@ -435,6 +439,7 @@ getServerStatsData s = do _pMsgFwdsFrom23 <- readIORef $ pMsgFwdsFrom23 s _pMsgFwdsRecvBelow23 <- readIORef $ pMsgFwdsRecvBelow23 s _pMsgFwdsRecvFrom23 <- readIORef $ pMsgFwdsRecvFrom23 s + _pMsgFwdsRelayLimit <- readIORef $ pMsgFwdsRelayLimit s _rcvServices <- getServiceStatsData $ rcvServices s _ntfServices <- getServiceStatsData $ ntfServices s _rcvServicesSubMsg <- readIORef $ rcvServicesSubMsg s @@ -508,6 +513,7 @@ getServerStatsData s = do _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, _rcvServices, _ntfServices, _rcvServicesSubMsg, @@ -584,6 +590,7 @@ setServerStats s d = do writeIORef (pMsgFwdsFrom23 s) $! _pMsgFwdsFrom23 d writeIORef (pMsgFwdsRecvBelow23 s) $! _pMsgFwdsRecvBelow23 d writeIORef (pMsgFwdsRecvFrom23 s) $! _pMsgFwdsRecvFrom23 d + writeIORef (pMsgFwdsRelayLimit s) $! _pMsgFwdsRelayLimit d setServiceStats (rcvServices s) $! _rcvServices d setServiceStats (ntfServices s) $! _ntfServices d writeIORef (rcvServicesSubMsg s) $! _rcvServicesSubMsg d @@ -806,6 +813,7 @@ instance StrEncoding ServerStatsData where _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit = 0, _rcvServices, _ntfServices, _rcvServicesSubMsg = 0, diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index de3819d50..8a6d25f29 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -49,6 +49,7 @@ import Simplex.Messaging.Util (bshow, tshow) import Simplex.Messaging.Version (mkVersionRange) import System.FilePath (splitExtensions) import System.Random (randomRIO) +import Text.Read (readMaybe) import Test.Hspec hiding (fit, it, xit) import UnliftIO import Util @@ -81,6 +82,8 @@ smpProxyTests = do testClosedClientCommandsFail it "releases command kept for late response" $ \_ -> testLateResponseCommandReleased + it "rejects forwards above the relay concurrency limit" $ \_ -> + testProxyRelayConcurrencyLimit describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel From 56a30d8fee17cfc5f137395f1a6bd746dc3354d8 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 05:34:01 -0500 Subject: [PATCH 145/159] server: finish relay concurrency metrics and HTTP2 test setup --- src/Simplex/Messaging/Server/Main/Init.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index c30be4087..4893429b4 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -165,6 +165,7 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> "\n\n\ \# Limit number of connections to destination servers being established at once.\n" <> ("# connect_concurrency = " <> tshow defaultProxyConnectConcurrency) + <> "\n\n\ \# Limit number of messages forwarded to one destination server and awaiting its response.\n" <> ("# relay_concurrency = " <> tshow defaultProxyRelayConcurrency) <> "\n\n\ From 33ddd13e09d1cfbc21b98bdf57c989fd7b26a500 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 06:13:38 -0500 Subject: [PATCH 146/159] server: make service subscription replacement counts consistent Reset replacement subscription state. Deduplicate unsubscription events. Recompute service END counts from the store. Use dynamic SOCKS ports and current stats fixtures. --- src/Simplex/Messaging/Server.hs | 34 +++++++++++++++++----- tests/AgentTests/ConnectionRequestTests.hs | 11 ------- tests/CoreTests/SOCKSSettings.hs | 15 ++++++---- tests/SMPProxyTests.hs | 21 ------------- tests/ServerTests.hs | 2 +- tests/Test.hs | 1 + tests/XFTPServerTests.hs | 2 +- 7 files changed, 38 insertions(+), 48 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 57dea9eb4..dc3e7158e 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -254,14 +254,18 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt asks namesEnv >>= liftIO . mapM_ closeNamesEnv processClientSub :: - forall sub. + forall sub p. + (PartyI p, ServiceParty p) => + s -> + SParty p -> Server s -> (Server s -> ServerSubscribers s) -> (Client s -> TMap QueueId sub) -> + (Client s -> TVar Bool) -> (Client s -> TVar (Int64, IdsHash)) -> Maybe (sub -> IO ()) -> Client s -> ClientSub -> IO () - processClientSub srv srvSubscribers clientSubs clientServiceSubs unsub_ clnt sub = + processClientSub ms party srv srvSubscribers clientSubs clientServiceSubscribed clientServiceSubs unsub_ clnt sub = uninterruptibleMask_ $ atomically (updateSubscribers clnt sub) >>= endPreviousSubscriptions @@ -303,6 +307,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt cancelServiceSubs serviceId = checkAnotherClient $ \c -> do changedSubs@(n, idsHash) <- swapTVar (clientServiceSubs c) (0, mempty) + writeTVar (clientServiceSubscribed c) False pure [(c, CSADecreaseSubs changedSubs, (serviceId, ENDS n idsHash))] checkAnotherClient :: (Client s -> STM [PrevClientSub s]) -> Maybe (Client s) -> STM [PrevClientSub s] checkAnotherClient mkSub = \case @@ -312,7 +317,12 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt endPreviousSubscriptions :: [PrevClientSub s] -> IO () endPreviousSubscriptions = mapM_ $ \(c, subAction, evt) -> do - atomically $ modifyTVar' pendingEvents $ IM.alter (Just . maybe [evt] (evt <|)) (clientId c) + evt' <- case subAction of + CSADecreaseSubs _ -> do + current <- liftIO $ getServiceQueueCountHash @(StoreQueue s) (queueStore ms) party (fst evt) + pure $ either (const evt) ((fst evt,) . uncurry ENDS) current + _ -> pure evt + atomically $ modifyTVar' pendingEvents $ IM.alter (Just . maybe [evt'] (evt' <|)) (clientId c) case subAction of CSAEndSub qId -> atomically (endSub c qId) >>= unsubPrev -- like endSub, also removes the delivery subscription from the service client's subscriptions map, @@ -785,10 +795,10 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt let serverInfo = LB.toStrict . J.encode <$> information labelMyThread $ "smp handshake for " <> transportName tp liftIO (timeout smpHandshakeTimeout . runExceptT $ smpServerHandshake srvCert srvSignKey h ks kh smpServerVRange serverInfo $ getClientService ms g idSize) >>= \case - Just (Right th) -> runClientTransport (processSubs srv) th + Just (Right th) -> runClientTransport (processSubs srv ms) th _ -> pure () where - processSubs srv = (processClientSub srv subscribers subscriptions serviceSubsCount (Just cancelSub), processClientSub srv ntfSubscribers ntfSubscriptions ntfServiceSubsCount Nothing) + processSubs srv ms = (processClientSub ms SRecipientService srv subscribers subscriptions serviceSubscribed serviceSubsCount (Just cancelSub), processClientSub ms SNotifierService srv ntfSubscribers ntfSubscriptions ntfServiceSubscribed ntfServiceSubsCount Nothing) getClientService :: s -> TVar ChaChaDRG -> Int -> SMPServiceRole -> X.CertificateChain -> XV.Fingerprint -> ExceptT TransportError IO ServiceId getClientService ms g idSize role cert fp = do @@ -1569,8 +1579,9 @@ client incSrvStat srvAssocRemoved -- getSubscription may find a subscription for receiving service, where clientSubs also hold active deliveries for service subscriptions. -- For notification service it can only find one if storage and session states diverge. - r <- getSubscription - writeSub + r@(hasSub, _) <- getSubscription + atomically $ modifyTVar' (clientServiceSubs clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) + unless hasSub writeSub pure r Nothing -> do r@(hasSub, _) <- getSubscription @@ -2368,7 +2379,9 @@ client -- we delete subscription here, so the client with no subscriptions can be disconnected. sub <- atomically $ TM.lookupDelete entId $ subscriptions clnt liftIO $ mapM_ cancelSub sub - when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) + when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ do + modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) + modifyTVar' (totalServiceSubs subscribers) $ subtractServiceSubs (1, queueIdHash (recipientId q)) liftIO $ processSub clnt $ CSDeleted entId rcvServiceId forM_ (notifier qr) $ \NtfCreds {notifierId = nId, ntfServiceId} -> do -- queue is deleted by a different client from the one subscribed to notifications, @@ -2376,6 +2389,11 @@ client stats <- asks serverStats deleted <- asks ntfStore >>= liftIO . (`deleteNtfs` nId) when (deleted > 0) $ liftIO $ atomicModifyIORef'_ (ntfCount stats) (subtract deleted) + when (isJust ntfServiceId && ntfServiceId == clntServiceId) $ do + ntfSubscribers <- asks (ntfSubscribers . server) + atomically $ do + modifyTVar' (ntfServiceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash nId) + modifyTVar' (totalServiceSubs ntfSubscribers) $ subtractServiceSubs (1, queueIdHash nId) liftIO $ processNtfSub clnt $ CSDeleted nId ntfServiceId updateDeletedStats qr pure ok diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index b39008875..b20831b84 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -296,17 +296,6 @@ connectionRequestTests = invalidE2EParamsStrUri = "v%3D3%26x3dh%3DMEIwBQYDK2VvAzk9mKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D%2CMEIwBQYDK2VvAzkAmKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D" strDecode @AConnectionRequestUri ("simplex:/contact#/?v=6-8&smp=" <> url invalidDhKeyQueueStr) `shouldSatisfy` isLeft strDecode @AConnectionRequestUri ("simplex:/invitation#/?v=6-8&smp=" <> url queueStr <> "&e2e=" <> invalidE2EParamsStrUri) `shouldSatisfy` isLeft - connectionRequestClientDataEmpty #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri <> "&data=" <> url "{}") - contactAddress #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr) - contactAddress #== ("https://simplex.chat/contact#/?v=2-7&smp=" <> url queueStr) - contactAddress2queues #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueStr <> ";" <> queueStr)) - contactAddressNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueNewStr) - contactAddress2queuesNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueNewStr <> ";" <> queueNewStr)) - contactAddress #==# ("simplex:/contact#/?v=2&smp=" <> url queueStr) - contactAddress #== ("https://simplex.chat/contact#/?v=1&smp=" <> url queueStr) -- adjusted to v2 - contactAddress #== ("https://simplex.chat/contact#/?v=1-2&smp=" <> url queueStr) -- adjusted to v2 - contactAddress #== ("https://simplex.chat/contact#/?v=2-2&smp=" <> url queueStr) - contactAddressClientData #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr <> "&data=" <> url "{\"type\":\"group_link\", \"group_link_id\":\"abc\"}") it "should generate a bracketed IPv6 application-server authority" $ do let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost request = CRInvitationUri (connReqData {crScheme = SSAppServer $ SrvLoc ipv6Host ""}) testE2ERatchetParams diff --git a/tests/CoreTests/SOCKSSettings.hs b/tests/CoreTests/SOCKSSettings.hs index 63d9fd3c4..d46a87015 100644 --- a/tests/CoreTests/SOCKSSettings.hs +++ b/tests/CoreTests/SOCKSSettings.hs @@ -199,24 +199,27 @@ testSocksProxyConnection = do socksConnectionTest :: HasTestEnv => HostName -> ByteString -> IO () socksConnectionTest proxyHost proxy = withSmpServerConfigOn (transport @TLS) SMPClient.cfg testPort $ \_ -> - withSocksProxy proxyHost "5050" $ \destinations -> do + withSocksProxy proxyHost "0" $ \destinations proxyPort -> do g <- C.newRandom ts <- getCurrentTime - let networkConfig = defaultNetworkConfig {socksProxy = either error Just $ strDecode proxy, socksMode = SMAlways} + let (proxyPrefix, proxySuffix) = B.breakSubstring "5050" proxy + proxy' = proxyPrefix <> B.pack proxyPort <> B.drop 4 proxySuffix + networkConfig = defaultNetworkConfig {socksProxy = either error Just $ strDecode proxy', socksMode = SMAlways} srv = SMPServer ["localhost"] testPort testKeyHash (c :: SMPClient) <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {networkConfig} [] Nothing ts (\_ -> pure ()) closeProtocolClient c - readTVarIO destinations `shouldReturn` ["localhost:5001"] + readTVarIO destinations `shouldReturn` [B.pack $ "localhost:" <> testPort] -- | Minimal SOCKS5 proxy (RFC 1928) for CONNECT command to domain names, -- with optional username/password authentication (RFC 1929), that records requested destinations. -withSocksProxy :: HostName -> ServiceName -> (TVar [ByteString] -> IO a) -> IO a +withSocksProxy :: HostName -> ServiceName -> (TVar [ByteString] -> ServiceName -> IO a) -> IO a withSocksProxy host port action = do destinations <- newTVarIO [] started <- newEmptyTMVarIO E.bracket (startTCPServer started (Just host) port) close $ \sock -> - withAsync (forever $ accept sock >>= \(conn, _) -> forkIO $ socksConnection destinations conn `E.finally` close conn) $ \_ -> - action destinations + withAsync (forever $ accept sock >>= \(conn, _) -> forkIO $ socksConnection destinations conn `E.finally` close conn) $ \_ -> do + proxyPort <- show <$> socketPort sock + action destinations proxyPort socksConnection :: TVar [ByteString] -> Socket -> IO () socksConnection destinations conn = do diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 8a6d25f29..5ecc27a64 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -118,8 +118,6 @@ smpProxyTests = do testForwardedAuthErrorDelay it "proxy closes idle relay connection" $ \_ -> testProxyClosesIdleRelay - it "relay refuses forwarded short link data swap" $ \_ -> - testForwardedSwapQueueLink describe "deliver message via SMP proxy" $ do let srv1, srv2 :: HasTestEnv => SMPServer srv1 = SMPServer testHost testPort testKeyHash @@ -698,25 +696,6 @@ testForwardedQueueLocked = _ <- PSQL.execute_ db $ Query $ "SET search_path TO " <> schema testStoreDBOpts2 pure db #endif -testForwardedSwapQueueLink :: HasTestEnv => IO () -testForwardedSwapQueueLink = - withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> - withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) - rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (2, testSMPServer2, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) - (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g - lnkId <- SMP.EntityId <$> atomically (C.randomBytes 24 g) - let ld = (SMP.EncDataBytes "fixed data", SMP.EncDataBytes "user data") - ld' = (fst ld, SMP.EncDataBytes "new user data") - SMP.QIK {rcvId} <- runExceptT' $ createSMPQueue rc NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing - runExceptT' $ addSMPQueueLink rc NRMInteractive rKey rcvId lnkId ld - sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive testSMPServer2 Nothing - runExceptT (proxySMPCommand pc NRMInteractive sess (Just rKey) rcvId (SMP.LSWP lnkId (SMP.linkDataHash $ snd ld) Nothing ld')) - `shouldReturn` Left (PCEProtocolError $ SMP.CMD SMP.PROHIBITED) - (snd <$> runExceptT' (getSMPQueueLink rc NRMInteractive lnkId)) `shouldReturn` ld -- Shared "phase 2" of the reconnection tests: start a healthy relay, confirm it is reachable -- directly (PING, not via the proxy) so a proxy failure can only mean the proxy didn't reconnect, diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 2a65e3cfb..63596b730 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -1718,7 +1718,7 @@ checkStats s qs sent received = do readSavedStats :: HasTestEnv => AStoreType -> IO ServerStatsData readSavedStats = \case ASType _ SMSMemory -> do - logSize testServerStatsBackupFile `shouldReturn` 101 + logSize testServerStatsBackupFile `shouldReturn` 106 either error id . strDecode <$> B.readFile testServerStatsBackupFile #if defined(dbServerPostgres) ASType _ SMSPostgres -> withStatsDB $ fmap (fromMaybe $ error "no saved stats") . getDBStats diff --git a/tests/Test.hs b/tests/Test.hs index a73025d80..6c6601c56 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} +{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeApplications #-} import AgentTests (agentCoreTests, agentTests) diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 648a35b4e..184df4e09 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -947,7 +947,7 @@ withHeldHTTP2Requests action = do release <- newEmptyTMVarIO creds <- loadServerCredential xftpCredentials Fingerprint fp <- loadFileFingerprint "tests/fixtures/ca.crt" - let hold _ _ _ _ respond = do + let hold _ _ _ _ _ respond = do atomically $ modifyTVar' received (+ 1) atomically $ readTMVar release respond $ responseNoBody ok200 [] From cc87fec98ac57e2fb024b9d38dd15c89d83875ca Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 06:23:30 -0500 Subject: [PATCH 147/159] tests: keep short-link responses within block size --- tests/ServerTests.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index 63596b730..f205e60e4 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -2801,8 +2801,8 @@ testSwapQueueLinkClient = (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g lnkId <- EntityId <$> atomically (C.randomBytes 24 g) fd <- atomically $ C.randomBytes 2048 g - let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13824 'a') - ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13824 'b') + let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13800 'a') + ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13800 'b') otherKeys <- replicateM 5 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) (rPub7, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing From 117afec831ac165b263a89bb550f48efb4389a06 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 10:51:42 -0500 Subject: [PATCH 148/159] fix SMP AUTH delayed response delivery Start sendDelayed alongside send, command processing and receive threads. Without this thread, AUTH responses remain in delayedQ indefinitely when authErrorDelay is enabled. Verified: queue key SEd25519 / used key SEd25519 passes in 1.6138s. --- src/Simplex/Messaging/Server.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index dc3e7158e..130623dad 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1130,7 +1130,7 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ [liftIO $ send h c, client processSubs s ms c, receive h ms c] + raceAny_ [liftIO $ send h c, liftIO $ sendDelayed c, client processSubs s ms c, receive h ms c] controlPortAuth :: Handle -> Maybe BasicAuth -> Maybe BasicAuth -> TVar CPClientRole -> BasicAuth -> IO () controlPortAuth h user admin role auth = do From 2b3c8bb3661b481143072b7b07172267e1cb2ea5 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 11:44:48 -0500 Subject: [PATCH 149/159] fix consolidated server and PostgreSQL regressions Complete PostgreSQL migration, stats and service-association integration. Cancel replaced XFTP uploads without self-cancel deadlocks; drain unstarted uploads after commit. Delete expired files using paths returned at record deletion and cancel active uploads. Allow retrying unconfirmed sender queues and restore notification push call. Update test fixtures for temporary uploads, encoded frame size and deterministic expiration timing. Focused AUTH, short-link, async retry, SQLite schema, static-file and all 45 XFTP chunk tests pass. --- src/Simplex/FileTransfer/Server.hs | 45 +++++++++++-------- .../Messaging/Agent/Store/AgentStore.hs | 2 +- src/Simplex/Messaging/Notifications/Server.hs | 2 +- .../Messaging/Server/QueueStore/Postgres.hs | 29 +++++++----- .../Server/QueueStore/Postgres/Migrations.hs | 35 ++++++++++++++- src/Simplex/Messaging/Server/StatsStore.hs | 30 ++++++++++++- tests/CoreTests/XFTPStoreTests.hs | 1 + tests/NtfServerTests.hs | 4 +- tests/ServerTests.hs | 4 +- tests/XFTPServerTests.hs | 10 ++--- 10 files changed, 117 insertions(+), 45 deletions(-) diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index d9a1f3496..9605b0fdc 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -137,11 +137,10 @@ data EntitlementChecked = EntNotChecked | EntChecked (Maybe SessionEntitlement) xftpServer :: forall s. FileStoreClass s => XFTPServerConfig s -> TMVar Bool -> M s () xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpiration, fileExpiration, xftpServerVRange, information} started = do - expireServerFiles Nothing fileExpiration - removeTmpUploads - removeUnstoredFiles restoreServerStats expireServerFiles Nothing fileExpiration `onException` stopServer + removeTmpUploads + removeUnstoredFiles raceAny_ ( runServer : expireFiles fileExpiration @@ -595,23 +594,30 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case receiveServerFile FileRec {senderId, fileInfo = FileInfo {size, digest}} = case bodyPart of Nothing -> pure $ FRErr SIZE -- TODO validate body size from request before downloading, once it's populated - Just getBody -> replaceUpload $ receiveUncommitted >>= maybe skipCommitted pure + Just getBody -> do + receivedBody <- newTVarIO False + let getBody' n = getBody n >>= \bs -> bs <$ when (not $ B.null bs) (atomically $ writeTVar receivedBody True) + replaceUpload receivedBody $ receiveUncommitted getBody' >>= maybe skipCommitted pure where - replaceUpload upload = do + replaceUpload receivedBody upload = do uploads <- asks uploadingFiles prevUpload <- newEmptyTMVarIO let startUpload = do - a <- asyncWithUnmask $ \unmask -> uninterruptibleMask_ (atomically $ readTMVar prevUpload) >>= mapM_ uninterruptibleCancel >> unmask upload + a <- asyncWithUnmask $ \unmask -> uninterruptibleMask_ (atomically $ readTMVar prevUpload) >>= mapM_ cancel >> unmask upload a <$ atomically (TM.lookupInsert senderId a uploads >>= putTMVar prevUpload) - removeUpload a = uninterruptibleCancel a >> atomically (TM.alter (mfilter (/= a)) senderId uploads) - fromRight (FRErr TIMEOUT) <$> bracket startUpload removeUpload waitCatch + removeUpload a = atomically (TM.alter (mfilter (/= a)) senderId uploads) + bracket startUpload removeUpload waitCatch >>= \case + Right r -> pure r + Left e + | isAsyncCancellation e -> ifM (readTVarIO receivedBody) (pure $ FRErr TIMEOUT) skipCommitted + | otherwise -> pure $ FRErr TIMEOUT -- having a filePath means the file is already uploaded and committed, must not change anything - receiveUncommitted = do + receiveUncommitted getBody' = do st <- asks fileStore liftIO (getFile st SFSender senderId) >>= \case Right (FileRec {filePath}, _) -> ifM (isJust <$> readTVarIO filePath) (pure Nothing) $ - Just <$> mask (\restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA)) + Just <$> mask (\restore -> ifM reserve (receive getBody' restore) (pure $ FRErr QUOTA)) Left e -> pure $ Just $ FRErr e skipCommitted = drainCommitted where @@ -631,12 +637,12 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case quota <- asks $ fromMaybe maxBound . fileSizeQuota . config atomically . stateTVar' us $ \used -> let used' = used + fromIntegral size in if used' <= quota then (True, used') else (False, used) - receive restore = do + receive getBody' restore = do path <- asks $ filesPath . config tmpId <- randomId 12 let fPath = path serverFileName senderId tmpPath = fPath <> "." <> B.unpack (strEncode tmpId) <> tmpUploadExtension - (restore (receiveChunk $ XFTPRcvChunkSpec tmpPath size digest) `onException` release tmpPath) >>= \case + (restore (receiveChunk getBody' $ XFTPRcvChunkSpec tmpPath size digest) `onException` release tmpPath) >>= \case Right () -> do renameFile tmpPath fPath stats <- asks serverStats @@ -665,9 +671,9 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case us <- asks usedStorage atomically $ modifyTVar' us $ subtract (fromIntegral size) removeUpload fPath = liftIO $ whenM (doesFileExist fPath) (removeFile fPath) `catch` logFileError - receiveChunk spec = do + receiveChunk getBody' spec = do t <- asks $ fileTimeout . config - liftIO $ fromMaybe (Left TIMEOUT) <$> timeout t (runExceptT $ receiveFile getBody spec) + liftIO $ fromMaybe (Left TIMEOUT) <$> timeout t (runExceptT $ receiveFile getBody' spec) sendServerFile :: FileRec -> RcvPublicDhKey -> M s (FileResponse, Maybe ServerFile) sendServerFile FileRec {senderId, filePath, fileInfo = FileInfo {size}} rDhKey = do readTVarIO filePath >>= \case @@ -744,16 +750,17 @@ expireServerFiles itemDelay expCfg = do mbs bs = tshow (bs `div` 1048576) <> "mb" expireLoop st now old = do expired <- liftIO $ expiredFiles st now old 10000 - forM_ expired $ \(_, filePath_, _) -> - forM_ filePath_ $ \fp -> - whenM (doesFileExist fp) $ - (removeFile fp >> mapM_ threadDelay itemDelay) `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e let sIds = map (\(sId, _, _) -> sId) expired unless (null sIds) $ do + uploads <- asks uploadingFiles + forM_ sIds $ \sId -> atomically (TM.lookupDelete sId uploads) >>= mapM_ cancel withFileLog $ \sl -> mapM_ (logDeleteFile sl) sIds deleted <- liftIO $ deleteFiles st sIds forM_ deleted $ \(_, filePath_, fileSize) -> do - forM_ filePath_ $ \_ -> subtractStoredFile fileSize + forM_ filePath_ $ \fp -> do + whenM (doesFileExist fp) $ + (removeFile fp >> mapM_ threadDelay itemDelay) `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e + subtractStoredFile fileSize incFileStat filesExpired expireLoop st now old diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index e421d88ad..85e00ebc1 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -2449,7 +2449,7 @@ insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do replace_snd_queue_id=EXCLUDED.replace_snd_queue_id, smp_client_version=EXCLUDED.smp_client_version, server_key_hash=EXCLUDED.server_key_hash - WHERE snd_queues.conn_id = EXCLUDED.conn_id + WHERE snd_queues.conn_id = EXCLUDED.conn_id OR snd_queues.status = 'new' RETURNING 1 |] ((host server, port server, sndId, queueMode, connId', sndPrivateKey, e2ePubKey, e2eDhSecret) diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index bc7d9fe22..d1cd89afe 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -551,7 +551,7 @@ ntfSubscriber NtfSubscriber {smpAgent = ca@SMPClientAgent {msgQ = msgQ_, agentQ} isOwn = isOwnServer ca srv liftIO (addTokenLastNtf st newNtf) >>= \case Right (tkn, lastNtfs) -> do - tryPushNotification ps (Just srvHost) isOwn tkn $ PNMessage lastNtfs + pushNotification ps (Just srvHost) isOwn tkn $ PNMessage lastNtfs liftIO $ incNtfStat_ stats ntfReceived when isOwn $ liftIO $ incServerStat srvHost (ntfReceivedOwn stats) Left AUTH -> liftIO $ do diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 46eb7ecbb..a91cec889 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -409,22 +409,28 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where map fromOnly <$> DB.query db updateQuery (serviceId, In (map recipientId qs))) results <- liftIO $ forM qs $ \sq -> do let rId = recipientId sq - (rId,) <$> if S.member rId updated - then readQueueRecIO (queueRec sq) $>>= \q -> do + let updateRec q = + case party of + SRecipientService -> q {rcvServiceId = serviceId} + SNotifierService -> case notifier q of + Just nc -> q {notifier = Just nc {ntfServiceId = serviceId}} + Nothing -> q + (rId,) <$> (if S.member rId updated + then readQueueRecIO (queueRec sq) $>>= (\q -> do + let prevSrvId = case party of + SRecipientService -> rcvServiceId q + SNotifierService -> notifier q >>= ntfServiceId atomically $ writeTVar (queueRec sq) $ Just $ updateRec q when (prevSrvId /= serviceId) $ withLog "setQueueServices" st $ \sl -> logQueueService sl (recipientId sq) party serviceId - pure $ Right prevSrvId - Nothing -> pure $ Left AUTH + pure $ Right ()) + else pure $ Left AUTH) + pure $ M.fromList results + where updateQuery = case party of SRecipientService -> "UPDATE msg_queues SET rcv_service_id = ? WHERE recipient_id IN ? AND deleted_at IS NULL RETURNING recipient_id" SNotifierService -> "UPDATE msg_queues SET ntf_service_id = ? WHERE recipient_id IN ? AND notifier_id IS NOT NULL AND deleted_at IS NULL RETURNING recipient_id" - updateRec q = case party of - SRecipientService -> q {rcvServiceId = serviceId} - SNotifierService -> case notifier q of - Just nc -> q {notifier = Just nc {ntfServiceId = serviceId}} - Nothing -> q getQueueNtfServices :: PostgresQueueStore q -> [(NotifierId, a)] -> IO (Either ErrorType ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)])) getQueueNtfServices st ntfs = E.uninterruptibleMask_ $ runExceptT $ do @@ -435,8 +441,9 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where if null snIds then ([], ntfs) else - let snIds' = foldl' (\m (sId, nId) -> M.alter (Just . maybe (S.singleton nId) (S.insert nId)) sId m) M.empty snIds - in foldr addService ([], ntfs) (M.assocs snIds') + let nsIds = M.fromList [(nId, sId) | (sId, nId) <- snIds] + (ssNtfs, deleteNtfs) = foldr (addNtf nsIds) (M.empty, []) ntfs + in (M.assocs ssNtfs, deleteNtfs) where addNtf nsIds ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId nsIds of Just serviceId -> (M.alter (Just . maybe [ntf] (ntf :)) serviceId ssNtfs, deleteNtfs) diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs index 7c3a4640b..6e71c65fa 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs @@ -25,7 +25,8 @@ serverSchemaMigrations = ("20260917_msg_queues_hot", m20260917_msg_queues_hot, Just down_m20260917_msg_queues_hot), ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), ("20261023_server_stats", m20261023_server_stats, Just down_m20261023_server_stats), - ("20261108_rcv_service_queues", m20261108_rcv_service_queues, Just down_m20261108_rcv_service_queues) + ("20261108_rcv_service_queues", m20261108_rcv_service_queues, Just down_m20261108_rcv_service_queues), + ("20261121_server_stats_v2", m20261121_server_stats_v2, Just down_m20261121_server_stats_v2) ] -- | The list of migrations in ascending order by date @@ -1249,6 +1250,8 @@ down_m20261108_rcv_service_queues :: Text down_m20261108_rcv_service_queues = [r| DROP INDEX idx_msg_queues_rcv_service_active; + |] + m20261023_server_stats :: Text m20261023_server_stats = [r| @@ -1356,3 +1359,33 @@ DROP TABLE server_stats_queues; DROP TABLE server_stats; |] + +m20261121_server_stats_v2 :: Text +m20261121_server_stats_v2 = + [r| +ALTER TABLE server_stats + ADD COLUMN rslv_rejected BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_below23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_from23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_recv_below23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_recv_from23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_relay_limit BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmds BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmd_ms BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmd_max_ms BIGINT NOT NULL DEFAULT 0; + |] + +down_m20261121_server_stats_v2 :: Text +down_m20261121_server_stats_v2 = + [r| +ALTER TABLE server_stats + DROP COLUMN rslv_rejected, + DROP COLUMN p_msg_fwds_below23, + DROP COLUMN p_msg_fwds_from23, + DROP COLUMN p_msg_fwds_recv_below23, + DROP COLUMN p_msg_fwds_recv_from23, + DROP COLUMN p_msg_fwds_relay_limit, + DROP COLUMN fwd_worker_cmds, + DROP COLUMN fwd_worker_cmd_ms, + DROP COLUMN fwd_worker_cmd_max_ms; + |] diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs index 80321d358..cecf1394c 100644 --- a/src/Simplex/Messaging/Server/StatsStore.hs +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -275,8 +275,18 @@ statsFields = ("rslv_succ", _rslvSucc), ("rslv_not_found", _rslvNotFound), ("rslv_resolver_errs", _rslvResolverErrs), - ("rslv_disabled", _rslvDisabled) + ("rslv_disabled", _rslvDisabled), + ("rslv_rejected", _rslvRejected) ] + <> [ ("p_msg_fwds_below23", _pMsgFwdsBelow23), + ("p_msg_fwds_from23", _pMsgFwdsFrom23), + ("p_msg_fwds_recv_below23", _pMsgFwdsRecvBelow23), + ("p_msg_fwds_recv_from23", _pMsgFwdsRecvFrom23), + ("p_msg_fwds_relay_limit", _pMsgFwdsRelayLimit), + ("fwd_worker_cmds", _fwdWorkerCmds), + ("fwd_worker_cmd_ms", _fwdWorkerCmdMs), + ("fwd_worker_cmd_max_ms", _fwdWorkerCmdMaxMs) + ] ) where proxyFields pfx sel = @@ -355,7 +365,15 @@ instance FromRow StatsRow where _pMsgFwdsRecv <- field _rcvServices <- serviceStatsP _ntfServices <- serviceStatsP - _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field + _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field <*> field + _pMsgFwdsBelow23 <- field + _pMsgFwdsFrom23 <- field + _pMsgFwdsRecvBelow23 <- field + _pMsgFwdsRecvFrom23 <- field + _pMsgFwdsRelayLimit <- field + _fwdWorkerCmds <- field + _fwdWorkerCmdMs <- field + _fwdWorkerCmdMaxMs <- field pure $ StatsRow ServerStatsData @@ -410,6 +428,11 @@ instance FromRow StatsRow where _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, _ntfServices, _rcvServices, _rcvServicesSubMsg = 0, @@ -419,6 +442,9 @@ instance FromRow StatsRow where _cmdSlotWaitMs = 0, _cmdSlotWaitMaxMs = 0, _cmdSlotWaitTimeouts = 0, + _fwdWorkerCmds, + _fwdWorkerCmdMs, + _fwdWorkerCmdMaxMs, _qCount = 0, _msgCount = 0, _ntfCount = 0, diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index 914c22725..d6b3fd0cb 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -14,6 +14,7 @@ import qualified Database.PostgreSQL.Simple as DB import SMPClient (deadlockOnce) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store +import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..)) import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore, withDB') import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, readWriteFileStore, serverFileName, writeFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (..)) diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index 1c96ce23f..ef8ede3a3 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -51,7 +51,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Env (NtfServerConfig (..)) import Simplex.Messaging.Notifications.Server.Push.APNS -import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfPostgresStore (dbStore), closeNtfDbStore, getEntityCounts, newNtfDbStore, withClientDB, withDB') +import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfEntityCounts (..), NtfPostgresStore (dbStore), closeNtfDbStore, getEntityCounts, newNtfDbStore, withClientDB, withDB') import Simplex.Messaging.Notifications.Transport (THandleNTF) import Simplex.Messaging.Parsers (parse, parseAll) import Simplex.Messaging.Protocol hiding (notification) @@ -189,7 +189,7 @@ testFullPushQueue (ATransport t, msType) = do Resp "4" _ OK <- signSendRecv sh sKey ("4", sId, _SEND' "hello") pure () checkLastNtfs n = do - (_, _, cnt) <- getEntityCounts st + NtfEntityCounts {lastNtfCount = cnt} <- getEntityCounts st unless (cnt == n) $ threadDelay 100000 >> checkLastNtfs n waitLastNtfs n = timeout 5000000 (checkLastNtfs n) `shouldReturn` Just () sIds <- replicateM 6 $ subscribe tknKey tId $ SMPServer SMP.testHost SMP.testPort SMP.testKeyHash diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index f205e60e4..ea51aa0b0 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -2801,8 +2801,8 @@ testSwapQueueLinkClient = (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g lnkId <- EntityId <$> atomically (C.randomBytes 24 g) fd <- atomically $ C.randomBytes 2048 g - let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13800 'a') - ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13800 'b') + let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13832 'a') + ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13832 'b') otherKeys <- replicateM 5 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) (rPub7, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 184df4e09..6c0b78400 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -26,7 +26,7 @@ import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import qualified Data.CaseInsensitive as CI import Data.Either (isLeft) -import Data.List (find, isInfixOf) +import Data.List (find, isInfixOf, isPrefixOf) import Data.List.NonEmpty (NonEmpty) import Data.Maybe (listToMaybe) import qualified Data.Text as T @@ -426,8 +426,7 @@ testConcurrentChunkUpload = xftpTest2 $ \c@XFTPClient {http2Client, thParams} c' atomically $ takeTMVar resume send $ byteString part2 flush - serverFile = xftpServerFiles serverFileName sId - waitServerFile = unlessM (doesFileExist serverFile) $ threadDelay 10000 >> waitServerFile + waitServerFile = unlessM (any (serverFileName sId `isPrefixOf`) <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitServerFile upload1 <- async $ HC.sendRequest http2Client req Nothing timeout 5000000 waitServerFile `shouldReturn` Just () timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) @@ -457,8 +456,7 @@ testCancelStalledChunkUpload fsType = withXFTPServerConfigOn (updateXFTPCfg (cfg send $ byteString $ B.replicate 1024 'x' flush threadDelay maxBound - serverFile = xftpServerFiles serverFileName sId - waitServerFile = unlessM (doesFileExist serverFile) $ threadDelay 10000 >> waitServerFile + waitServerFile = unlessM (any (serverFileName sId `isPrefixOf`) <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitServerFile upload1 <- async $ HC.sendRequest http2Client req Nothing timeout 5000000 waitServerFile `shouldReturn` Just () timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) @@ -486,8 +484,8 @@ testUploadDuringExpiration fsType = do withXFTPServerConfigOn (updateXFTPCfg (cfgFSTestFiles fsType) $ \c -> c {fileExpiration}) $ \_ -> do testXFTPClient $ \c -> do runRight_ $ forM_ uploadedIds $ \fId -> uploadXFTPChunk c spKey fId chunkSpec - timeout 10000000 waitExpiration `shouldReturn` Just () runRight_ $ uploadXFTPChunk c spKey sId chunkSpec + timeout 20000000 waitExpiration `shouldReturn` Just () timeout 10000000 waitRemoved `shouldReturn` Just () where fileExpiration = ExpirationConfig {ttl = 3600, checkInterval = 1} From b9f3979c8cb59b6ce79bbef41ecc8ff3f4bef837 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 11:58:22 -0500 Subject: [PATCH 150/159] clean up failed invitation joins Delete only the newly created connection when securing it fails, so a later invitation retry does not conflict with the stale sender queue. Keep cross-connection sender queue protection intact. Verified async second-attempt connection and should-not-add-SndQueue-of-another-connection tests. --- src/Simplex/Messaging/Agent.hs | 4 +++- src/Simplex/Messaging/Agent/Store/AgentStore.hs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index ea227c32c..67a304ecb 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1647,7 +1647,9 @@ joinConnSrv' c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo pqSup su doJoin :: Maybe RcvQueue -> Maybe SndQueue -> AM SndQueueSecured doJoin rq_ sq_ = do ((cData, sq), (e2eSndParams, lnkId_)) <- startJoinInvitation c userId connId sq_ enableNtfs inv pqSup - secureConfirmQueue c nm cData rq_ sq srv cInfo e2eSndParams subMode + (secureConfirmQueue c nm cData rq_ sq srv cInfo e2eSndParams subMode `catchError` \e -> do + unless (isJust sq_) $ void $ withStore' c $ \db -> deleteConn db Nothing connId + throwError e) >>= (mapM_ (delInvSL c connId srv) lnkId_ $>) joinConnSrv' c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo pqSupport subMode srv mkInner = lift (compatibleContactUri cReqUri) >>= \case diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 85e00ebc1..e421d88ad 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -2449,7 +2449,7 @@ insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do replace_snd_queue_id=EXCLUDED.replace_snd_queue_id, smp_client_version=EXCLUDED.smp_client_version, server_key_hash=EXCLUDED.server_key_hash - WHERE snd_queues.conn_id = EXCLUDED.conn_id OR snd_queues.status = 'new' + WHERE snd_queues.conn_id = EXCLUDED.conn_id RETURNING 1 |] ((host server, port server, sndId, queueMode, connId', sndPrivateKey, e2ePubKey, e2eDhSecret) From 9d6918da7ae5c0f3a1197a37b72bc72c9ae4b4af Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 12:37:22 -0500 Subject: [PATCH 151/159] restore fair SMP message delivery Use separate response and message senders under the fair transport lock, preventing sustained command traffic from starving message delivery. Share the test deadline helper and raise the integration-suite limit to 180 seconds for multi-restart workloads. Verified the 200-subscription batching test and all focused connection regressions. --- src/Simplex/Messaging/Server.hs | 47 ++++++++++++++++----------------- tests/Test.hs | 9 +------ tests/Util.hs | 11 +++++++- 3 files changed, 34 insertions(+), 33 deletions(-) diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 130623dad..846fd9fa8 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -1129,8 +1129,9 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi s <- asks server ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do + th <- newMVar h labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ [liftIO $ send h c, liftIO $ sendDelayed c, client processSubs s ms c, receive h ms c] + raceAny_ [liftIO $ send th c, liftIO $ sendMsg th c, liftIO $ sendDelayed c, client processSubs s ms c, receive h ms c] controlPortAuth :: Handle -> Maybe BasicAuth -> Maybe BasicAuth -> TVar CPClientRole -> BasicAuth -> IO () controlPortAuth h user admin role auth = do @@ -1291,38 +1292,36 @@ forwardedCmdWait = (`netTimeoutInt` NRMBackground) . tcpTimeout . networkConfig microseconds :: SystemTime -> Int64 microseconds (MkSystemTime s ns) = s * 1000000 + fromIntegral (ns `div` 1000) --- Messages are sent one per transmission, interleaved with command responses. -send :: Transport c => THandleSMP c 'TServer -> Client s -> IO () -send h c@Client {sndQ, msgQ, clientTHParams = THandleParams {sessionId}} = do +send :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> IO () +send th c@Client {sndQ, msgQ, clientTHParams = THandleParams {sessionId}} = do labelMyThread . B.unpack $ "client $" <> encode sessionId <> " send" - sendLoop [] + forever $ atomically (readTBQueue sndQ) >>= sendTransmissions where - sendLoop :: [Transmission BrokerMsg] -> IO () - sendLoop = \case - [] -> - atomically (Left <$> readTBQueue sndQ <|> Right <$> readTBQueue msgQ) >>= \case - Left ts -> sendTransmissions ts >>= sendLoop - Right msgs -> sendLoop $ L.toList msgs - msg : msgs -> do - tSend h c [msg] - atomically (tryReadTBQueue sndQ) >>= \case - Just ts -> sendTransmissions ts >>= sendLoop . (msgs <>) - Nothing -> sendLoop msgs -- If the request had batched subscriptions -- this will reply SOKs to all SUBs in the first batched transmission, -- to reduce client timeouts. -- After that all messages will be sent in separate transmissions, -- without any client response timeouts, and allowing them to interleave -- with other requests responses. - sendTransmissions :: (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO [Transmission BrokerMsg] - sendTransmissions (ts, []) = [] <$ tSend h c ts + sendTransmissions :: (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO () + sendTransmissions (ts, []) = tSend th c ts sendTransmissions (ts, msg : msgs) - | length ts <= 4 = msgs <$ tSend h c (ts <> [msg]) -- up to 4 SOKs can be in one block with MSG (see testBatchSubResponses test) - | otherwise = (msg : msgs) <$ tSend h c ts - -tSend :: Transport c => THandleSMP c 'TServer -> Client s -> NonEmpty (Transmission BrokerMsg) -> IO () -tSend h@THandle {params} Client {sndActiveAt} ts = do - void . tPut h $ L.map (\t -> Right (Nothing, encodeTransmission params t)) ts + | length ts <= 4 = do -- up to 4 SOKs can be in one block with MSG (see testBatchSubResponses test) + tSend th c $ ts <> [msg] + mapM_ (atomically . writeTBQueue msgQ) $ L.nonEmpty msgs + | otherwise = do + tSend th c ts + atomically $ writeTBQueue msgQ (msg :| msgs) + +sendMsg :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> IO () +sendMsg th c@Client {msgQ, clientTHParams = THandleParams {sessionId}} = do + labelMyThread . B.unpack $ "client $" <> encode sessionId <> " sendMsg" + forever $ atomically (readTBQueue msgQ) >>= mapM_ (\t -> tSend th c [t]) + +tSend :: Transport c => MVar (THandleSMP c 'TServer) -> Client s -> NonEmpty (Transmission BrokerMsg) -> IO () +tSend th Client {sndActiveAt} ts = do + withMVar th $ \h@THandle {params} -> + void . tPut h $ L.map (\t -> Right (Nothing, encodeTransmission params t)) ts atomically . (writeTVar sndActiveAt $!) =<< liftIO getSystemTime disconnectTransport :: THandle v c 'TServer -> TVar SystemTime -> TVar SystemTime -> ExpirationConfig -> IO Bool -> IO () diff --git a/tests/Test.hs b/tests/Test.hs index 6c6601c56..9cdd954af 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -100,7 +100,7 @@ main = do . aroundAll_ (postgressBracket ntfTestServerDBConnectInfo) . aroundAll_ (postgressBracket testXFTPDBConnectInfo) #endif - . deadline (120 * 1000000) + . deadline (180 * 1000000) $ do parallel $ do describe "Core tests" $ do @@ -250,10 +250,3 @@ withTmpDir = bracket_ (createDirectoryIfMissing False tmpDir >> clearTmpDir) cle where clearTmpDir = listDirectory tmpDir >>= mapM_ (removePathForcibly . (tmpDir )) --- | Abort tests after a reasonable deadline. -deadline :: Int -> SpecWith b -> SpecWith b -deadline limit = mapSpecItem_ $ \item@Item {itemLocation, itemExample} -> - item - { itemExample = \params aw pc -> - fromMaybe (Result "timed out" . Failure itemLocation $ Reason "time limit") <$> timeout limit (itemExample params aw pc) - } diff --git a/tests/Util.hs b/tests/Util.hs index 8e266a024..39083e1c2 100644 --- a/tests/Util.hs +++ b/tests/Util.hs @@ -16,6 +16,7 @@ import Control.Logger.Simple import Control.Monad (replicateM, unless, when) import Data.Either (partitionEithers) import Data.List (tails) +import Data.Maybe (fromMaybe) import Data.String (IsString (..)) import GHC.Conc (BlockReason (..), ThreadStatus (..), getNumCapabilities, getNumProcessors, setNumCapabilities, threadStatus) import GHC.IO.Exception (IOException (..)) @@ -29,7 +30,7 @@ import System.Process (callCommand) import System.Timeout (timeout) import Test.Hspec hiding (fit, it, xit) import qualified Test.Hspec as Hspec -import Test.Hspec.Core.Spec (Example (..), Result (..), ResultStatus (..)) +import Test.Hspec.Core.Spec (Example (..), FailureReason (..), Item (..), Result (..), ResultStatus (..), mapSpecItem_) withNumCapabilities :: Int -> IO a -> IO a withNumCapabilities new a = getNumCapabilities >>= \old -> bracket_ (setNumCapabilities new) (setNumCapabilities old) a @@ -140,6 +141,14 @@ eventuallyRemove path retries = case retries of data TestWrapper a = TestWrapper String (HasTestEnv => a) +-- | Abort a test after the specified number of microseconds. +deadline :: Int -> SpecWith b -> SpecWith b +deadline limit = mapSpecItem_ $ \item@Item {itemLocation, itemExample} -> + item + { itemExample = \params aw pc -> + fromMaybe (Result "timed out" . Failure itemLocation $ Reason "time limit") <$> timeout limit (itemExample params aw pc) + } + -- TODO [ntfdb] running wiht LogWarn level shows potential issue "Queue count differs" testLogLevel :: LogLevel testLogLevel = LogError From 6d6baedc6e7b53c7b737d59f84bb3f566fd3a02b Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 13:29:10 -0500 Subject: [PATCH 152/159] preserve connection state on failed joins Delete only the new sender queue after secureConfirmQueue fails, preserving the connection and ratchet for retries. Verified all invitation/contact user-retry tests, async second attempt and cross-connection sender queue protection. --- src/Simplex/Messaging/Agent.hs | 2 +- src/Simplex/Messaging/Agent/Store/AgentStore.hs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 67a304ecb..e6a4a0985 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1648,7 +1648,7 @@ joinConnSrv' c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo pqSup su doJoin rq_ sq_ = do ((cData, sq), (e2eSndParams, lnkId_)) <- startJoinInvitation c userId connId sq_ enableNtfs inv pqSup (secureConfirmQueue c nm cData rq_ sq srv cInfo e2eSndParams subMode `catchError` \e -> do - unless (isJust sq_) $ void $ withStore' c $ \db -> deleteConn db Nothing connId + unless (isJust sq_) $ void $ withStore' c $ \db -> deleteNewConnSnd db connId throwError e) >>= (mapM_ (delInvSL c connId srv) lnkId_ $>) joinConnSrv' c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo pqSupport subMode srv mkInner = diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index e421d88ad..308be288c 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -49,6 +49,7 @@ module Simplex.Messaging.Agent.Store.AgentStore createNewConn, updateNewConnRcv, updateNewConnSnd, + deleteNewConnSnd, createSndConn, getClientNotices, updateClientNotices, @@ -570,6 +571,9 @@ updateNewConnSnd db connId sq = updateConn :: IO (Either StoreError SndQueue) updateConn = addConnSndQueue_ db connId sq +deleteNewConnSnd :: DB.Connection -> ConnId -> IO () +deleteNewConnSnd db connId = DB.execute db "DELETE FROM snd_queues WHERE conn_id = ? AND status = 'new'" (Only connId) + createSndConn :: DB.Connection -> TVar ChaChaDRG -> ConnData -> NewSndQueue -> IO (Either StoreError (ConnId, SndQueue)) createSndConn db gVar cData q@SndQueue {server} = -- check confirmed snd queue doesn't already exist, to prevent it being deleted by REPLACE in insertSndQueue_ From 53d2b1400f69b3600c1d2cfd1916750750c00dec Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 13:50:39 -0500 Subject: [PATCH 153/159] prevent notification queue head-of-line blocking Use non-blocking writes for push workers so one full queue cannot delay notifications from other servers. Accept NMSG responses from service subscriptions and correct second-token test entity matching. Verified both memory and PostgreSQL full-push-queue tests. --- src/Simplex/Messaging/Notifications/Server.hs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index d1cd89afe..3fb3cb4a4 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -54,7 +54,7 @@ import GHC.IORef (atomicSwapIORef) import GHC.Stats (getRTSStats) import Network.Socket (ServiceName, Socket, socketToHandle) import Numeric.Natural (Natural) -import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError, ServerTransmission (..)) +import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError, ServerTransmission (..), nonBlockingWriteTBQueue) import Simplex.Messaging.Client.Agent import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String @@ -536,18 +536,21 @@ ntfSubscriber NtfSubscriber {smpAgent = ca@SMPClientAgent {msgQ = msgQ_, agentQ} ps <- asks pushServer stats <- asks serverStats forever $ do - ((_, srv@(SMPServer (h :| _) _ _), _), THandleParams {sessionId}, ts) <- atomically $ readTBQueue msgQ + ((_, srv, _), THandleParams {sessionId}, ts) <- atomically $ readTBQueue msgQ forM_ ts $ \(ntfId, t) -> case t of STUnexpectedError e -> logError $ "SMP client unexpected error: " <> tshow e -- uncorrelated response, should not happen + STResponse _ r@(Right (SMP.NMSG _ _)) -> processNtf st ps stats srv sessionId ntfId r STResponse {} -> pure () -- it was already reported as timeout error - STEvent msgOrErr -> do + STEvent r -> processNtf st ps stats srv sessionId ntfId r + where + processNtf st ps stats srv sessionId ntfId msgOrErr = do let smpQueue = SMPQueueNtf srv ntfId case msgOrErr of Right (SMP.NMSG nmsgNonce encNMsgMeta) -> do ntfTs <- liftIO getSystemTime liftIO $ updatePeriodStats (activeSubs stats) ntfId let newNtf = PNMessageData {smpQueue, ntfTs, nmsgNonce, encNMsgMeta} - srvHost = safeDecodeUtf8 $ strEncode h + srvHost = safeDecodeUtf8 $ strEncode $ L.head $ host srv isOwn = isOwnServer ca srv liftIO (addTokenLastNtf st newNtf) >>= \case Right (tkn, lastNtfs) -> do @@ -645,7 +648,7 @@ pushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> P pushNotification s srvHost_ isOwn tkn@NtfTknRec {token = token@(DeviceToken pp _)} ntf = ifM (pushProviderAllowed token) - (getOrCreatePushWorker s (srvHost_, pp, pushTokenShardId 8 tkn) isOwn >>= atomically . (`writeTBQueue` (tkn, ntf))) + (getOrCreatePushWorker s (srvHost_, pp, pushTokenShardId 8 tkn) isOwn >>= liftIO . (`nonBlockingWriteTBQueue` (tkn, ntf))) (logWarn "skipping disabled APNS test push provider") pushTokenShardId :: Int -> NtfTknRec -> Int From 1d9482225e52f7f4e6a832af7e3b2475249f346e Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 15:13:41 -0500 Subject: [PATCH 154/159] update PostgreSQL schemas and integration timeout Include generated schema updates from the completed migration set. Allow up to 360 seconds for heavily contended multi-restart integration tests. Verified: default suite 1449 examples, 0 failures, 7 pending. --- tests/Test.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Test.hs b/tests/Test.hs index 9cdd954af..99dd844be 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -100,7 +100,7 @@ main = do . aroundAll_ (postgressBracket ntfTestServerDBConnectInfo) . aroundAll_ (postgressBracket testXFTPDBConnectInfo) #endif - . deadline (180 * 1000000) + . deadline (360 * 1000000) $ do parallel $ do describe "Core tests" $ do From cbfb1f4b35653c83c1779dd788c7fb5e83eb8556 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Sat, 21 Nov 2026 15:14:05 -0500 Subject: [PATCH 155/159] record generated PostgreSQL schemas Schema dumps produced and verified by the PostgreSQL schema tests. --- .../Postgres/Migrations/agent_postgres_schema.sql | 15 ++++++++------- .../Server/Store/ntf_server_schema.sql | 1 + .../Server/QueueStore/Postgres/server_schema.sql | 12 +++++++++++- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql index 33de2a8de..c1a14a830 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); @@ -177,7 +178,7 @@ CREATE TABLE smp_agent_test_protocol_schema.commands ( command bytea NOT NULL, agent_version integer DEFAULT 1 NOT NULL, server_key_hash bytea, - created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00-05'::timestamp with time zone NOT NULL, failed smallint DEFAULT 0 ); @@ -240,14 +241,14 @@ CREATE TABLE smp_agent_test_protocol_schema.connections ( ratchet_sync_state text DEFAULT 'ok'::text NOT NULL, deleted_at_wait_delivery timestamp with time zone, pq_support smallint DEFAULT 0 NOT NULL, - created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00-05'::timestamp with time zone NOT NULL, service_request_expires_at timestamp with time zone ); CREATE TABLE smp_agent_test_protocol_schema.deleted_snd_chunk_replicas ( - deleted_snd_chunk_replica_id bigint NOT NULL, + deleted_snd_chunk_replica_id bigint CONSTRAINT deleted_snd_chunk_replicas_deleted_snd_chunk_replica_i_not_null NOT NULL, user_id bigint NOT NULL, xftp_server_id bigint NOT NULL, replica_id bytea NOT NULL, @@ -274,7 +275,7 @@ ALTER TABLE smp_agent_test_protocol_schema.deleted_snd_chunk_replicas ALTER COLU CREATE TABLE smp_agent_test_protocol_schema.encrypted_rcv_message_hashes ( - encrypted_rcv_message_hash_id bigint NOT NULL, + encrypted_rcv_message_hash_id bigint CONSTRAINT encrypted_rcv_message_hashe_encrypted_rcv_message_hash_not_null NOT NULL, conn_id bytea NOT NULL, hash bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -417,7 +418,7 @@ ALTER TABLE smp_agent_test_protocol_schema.ntf_tokens_to_delete ALTER COLUMN ntf CREATE TABLE smp_agent_test_protocol_schema.processed_ratchet_key_hashes ( - processed_ratchet_key_hash_id bigint NOT NULL, + processed_ratchet_key_hash_id bigint CONSTRAINT processed_ratchet_key_hashe_processed_ratchet_key_hash_not_null NOT NULL, conn_id bytea NOT NULL, hash bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -650,8 +651,8 @@ ALTER TABLE smp_agent_test_protocol_schema.skipped_messages ALTER COLUMN skipped CREATE TABLE smp_agent_test_protocol_schema.snd_file_chunk_replica_recipients ( - snd_file_chunk_replica_recipient_id bigint NOT NULL, - snd_file_chunk_replica_id bigint NOT NULL, + snd_file_chunk_replica_recipient_id bigint CONSTRAINT snd_file_chunk_replica_reci_snd_file_chunk_replica_rec_not_null NOT NULL, + snd_file_chunk_replica_id bigint CONSTRAINT snd_file_chunk_replica_recip_snd_file_chunk_replica_id_not_null NOT NULL, rcv_replica_id bytea NOT NULL, rcv_replica_key bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, diff --git a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql index c68b59668..218f13cd7 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql +++ b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql index fddfe7530..f67a1c9d2 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); @@ -424,7 +425,7 @@ CREATE TABLE smp_server.migrations ( CREATE TABLE smp_server.msg_queues ( recipient_id bytea NOT NULL, - recipient_keys bytea NOT NULL, + recipient_keys bytea CONSTRAINT msg_queues_recipient_key_not_null NOT NULL, rcv_dh_secret bytea NOT NULL, sender_id bytea NOT NULL, sender_key bytea, @@ -535,6 +536,15 @@ CREATE TABLE smp_server.server_stats ( rslv_not_found bigint NOT NULL, rslv_resolver_errs bigint NOT NULL, rslv_disabled bigint NOT NULL, + rslv_rejected bigint DEFAULT 0 NOT NULL, + p_msg_fwds_below23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_from23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_recv_below23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_recv_from23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_relay_limit bigint DEFAULT 0 NOT NULL, + fwd_worker_cmds bigint DEFAULT 0 NOT NULL, + fwd_worker_cmd_ms bigint DEFAULT 0 NOT NULL, + fwd_worker_cmd_max_ms bigint DEFAULT 0 NOT NULL, CONSTRAINT server_stats_server_stats_id_check CHECK ((server_stats_id = 1)) ); From 32becddc0142cb8aee008a32438e8d2996b86ab4 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Mon, 23 Nov 2026 12:22:29 -0500 Subject: [PATCH 156/159] fix TLS shutdown and full-queue ACK handling Attempt TLS bye before closing the context without uninterruptible masking. Use non-blocking notification writes for ACK events when the agent event queue is full. Both focused regression tests pass. --- src/Simplex/Messaging/Agent.hs | 2 +- src/Simplex/Messaging/Transport.hs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 4c82f5055..8694013d3 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2901,7 +2901,7 @@ retrySndOp c loop = do withConnLockNotify :: AgentClient -> ConnId -> Text -> AM (Maybe ATransmission) -> AM () withConnLockNotify c connId name action = do t_ <- withConnLock c connId name action - forM_ t_ $ atomically . writeTBQueue (subQ c) + forM_ t_ $ liftIO . nonBlockingWriteTBQueue (subQ c) ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM () ackMessage' c cmdId_ connId msgId rcptInfo_ = withConnLockNotify c connId "ackMessage" $ do diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 69fe8d5ec..5428f5767 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -389,7 +389,10 @@ recvTLS :: T.Context -> IO ByteString recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt closeTLS :: T.Context -> IO () -closeTLS ctx = T.contextClose ctx `catchAll_` pure () +closeTLS ctx = + T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here + `E.finally` T.contextClose ctx + `catchOwn'` \_ -> pure () defaultSupportedParams :: T.Supported defaultSupportedParams = From d7d5ebd2a0a79358afa53b4d71a2869d6238beaf Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Mon, 23 Nov 2026 12:52:54 -0500 Subject: [PATCH 157/159] bound TLS close without waiting for peer Race TLS bye with a one-second timeout and close the context directly afterward. Avoid nested timeout and withAsync cleanup deadlocks under uninterruptible masks. Both TLS close regression tests pass. --- src/Simplex/Messaging/Transport.hs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index 5428f5767..cf55e3fe4 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -110,6 +110,8 @@ module Simplex.Messaging.Transport where import Control.Applicative (optional) +import Control.Concurrent (threadDelay) +import Control.Concurrent.Async (async, cancel, waitEither) import Control.Concurrent.STM import Control.Monad import Control.Monad.Except @@ -389,9 +391,11 @@ recvTLS :: T.Context -> IO ByteString recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt closeTLS :: T.Context -> IO () -closeTLS ctx = - T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here - `E.finally` T.contextClose ctx +closeTLS ctx = do + byeThread <- async $ T.bye ctx + timeoutThread <- async $ threadDelay 1000000 + (void $ waitEither byeThread timeoutThread) + `E.finally` (T.contextClose ctx >> cancel byeThread >> cancel timeoutThread) `catchOwn'` \_ -> pure () defaultSupportedParams :: T.Supported From b60f101e0047433bb194fc1d0fcbbb8c99ec3ad3 Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Mon, 23 Nov 2026 13:50:44 -0500 Subject: [PATCH 158/159] make TLS close bounded and cancellation-safe Close TLS context after 50ms and finish cancellation after another 150ms. This preserves timeout semantics while ensuring the context is already closed when the outer timeout fires. TLS close, blocked-peer close and 1000-cancellation tests pass. --- src/Simplex/Messaging/Transport.hs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index cf55e3fe4..d6de161e4 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -111,7 +111,7 @@ where import Control.Applicative (optional) import Control.Concurrent (threadDelay) -import Control.Concurrent.Async (async, cancel, waitEither) +import Control.Concurrent.Async (async, cancel) import Control.Concurrent.STM import Control.Monad import Control.Monad.Except @@ -393,10 +393,10 @@ recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt closeTLS :: T.Context -> IO () closeTLS ctx = do byeThread <- async $ T.bye ctx - timeoutThread <- async $ threadDelay 1000000 - (void $ waitEither byeThread timeoutThread) - `E.finally` (T.contextClose ctx >> cancel byeThread >> cancel timeoutThread) - `catchOwn'` \_ -> pure () + threadDelay 50000 + T.contextClose ctx + threadDelay 150000 + cancel byeThread defaultSupportedParams :: T.Supported defaultSupportedParams = From 24f29d6285b6b010bd4ceac9bfd8c40b2868225a Mon Sep 17 00:00:00 2001 From: adayhans8-debug Date: Mon, 23 Nov 2026 14:01:03 -0500 Subject: [PATCH 159/159] update push client tests for sharded workers Pass shard ID 0 to getPushClient and look up pushClients by (provider, shard). Push worker kill and periodic-server-stop tests pass with PostgreSQL enabled. --- tests/NtfServerTests.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index 7e6feb1ac..ba73d62f1 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -208,11 +208,11 @@ testPushClientKilled :: HasTestEnv => Expectation testPushClientKilled = withStallingServerOn' apnsTestPort $ \accepted _ -> do s <- newNtfPushServer 1 apnsConfig - a <- async $ getPushClient s PPApnsTest + a <- async $ getPushClient s PPApnsTest 0 atomically $ takeTMVar accepted killThread $ asyncThreadId a timeout 1000000 (either fromException (const Nothing) <$> waitCatch a) `shouldReturn` Just (Just ThreadKilled) - isNothing <$> TM.lookupIO PPApnsTest (pushClients s) `shouldReturn` True + isNothing <$> TM.lookupIO (PPApnsTest, 0) (pushClients s) `shouldReturn` True where NtfServerConfig {apnsConfig} = ntfServerCfg