diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index 9855fb313..9165d01b3 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, liftError, tshow, unlessM, whenM) +import Simplex.Messaging.Util (allFinally, catchAll_, catchAllErrors, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) import System.FilePath (takeFileName, ()) import UnliftIO import UnliftIO.Directory @@ -235,7 +235,7 @@ runXFTPRcvWorker c srv Worker {doWork} = do relChunkPath = fileTmpPath takeFileName chunkPath agentXFTPDownloadChunk c userId digest replica chunkSpec liftIO $ waitUntilForeground c - (entityId, complete, progress) <- withStore c $ \db -> runExceptT $ do + (entityId, complete, progress) <- handleAllErrors (rcvFileError c rcvFileId) . withStore c $ \db -> runExceptT $ do liftIO $ lockRcvFileForUpdate db rcvFileId liftIO $ updateRcvFileChunkReceived db (rcvChunkReplicaId replica) rcvChunkId relChunkPath RcvFile {size = FileSize currentSize, chunks, redirect} <- ExceptT $ getRcvFile db rcvFileId @@ -284,6 +284,9 @@ rcvWorkerInternalError c rcvFileId rcvFileEntityId redirectEntityId_ tmpPath err withStore' c $ \db -> updateRcvFileError db rcvFileId (show err) notify c (fromMaybe rcvFileEntityId redirectEntityId_) (RFERR err) +rcvFileError :: AgentClient -> DBRcvFileId -> AgentErrorType -> AM a +rcvFileError c rcvFileId e = ifM (withStore' c (`getRcvFileDeleted` rcvFileId)) (throwE $ FILE NO_FILE) (throwE e) + runXFTPRcvLocalWorker :: AgentClient -> Worker -> AM () runXFTPRcvLocalWorker c Worker {doWork} = do cfg <- asks config @@ -331,7 +334,7 @@ runXFTPRcvLocalWorker c Worker {doWork} = do | otherwise -> pure fd liftIO $ waitUntilForeground c -- register and download chunks from the actual file - withStore c $ \db -> updateRcvFileComplete db rcvFileId >> updateRcvFileRedirect db redirectDbId next + withStore c (\db -> updateRcvFileComplete db rcvFileId >> updateRcvFileRedirect db redirectDbId next) `catchAllErrors` rcvFileError c redirectDbId forM_ nextChunks (downloadChunk c) flip catchAllErrors (\e -> logError $ "XFTP rcv worker error: " <> tshow e) $ lift $ forM_ tmpPath (removePath <=< toFSFilePath) @@ -439,7 +442,7 @@ runXFTPSndPrepareWorker c Worker {doWork} = do removeFile fsEncPath withStore' c $ \db -> updateSndFileStatus db sndFileId SFSEncrypting (digest, chunkSpecsDigests) <- encryptFileForUpload sndFile fsEncPath - withStore c $ \db -> do + handleAllErrors (sndFileError c sndFileId) . withStore c $ \db -> do lockSndFileForUpdate db sndFileId updateSndFileEncrypted db sndFileId digest chunkSpecsDigests getSndFile db sndFileId @@ -484,7 +487,7 @@ runXFTPSndPrepareWorker c Worker {doWork} = do createChunk numRecipients' storageHours ch = do liftIO $ assertUploadsAllowed c (replica, ProtoServerWithAuth srv _) <- tryCreate - withStore' c $ \db -> createSndFileReplica db ch replica + withStore' c (\db -> createSndFileReplica db ch replica) `catchAllErrors` sndFileError c sndFileId pure srv where tryCreate = do @@ -518,6 +521,9 @@ sndWorkerInternalError c sndFileId sndFileEntityId prefixPath err = do withStore' c $ \db -> updateSndFileError db sndFileId (show err) notify c sndFileEntityId $ SFERR err +sndFileError :: AgentClient -> DBSndFileId -> AgentErrorType -> AM a +sndFileError c sndFileId e = ifM (withStore' c (`getSndFileDeleted` sndFileId)) (throwE $ FILE NO_FILE) (throwE e) + runXFTPSndWorker :: AgentClient -> XFTPServer -> Worker -> AM () runXFTPSndWorker c srv Worker {doWork} = do cfg <- asks config @@ -558,7 +564,7 @@ runXFTPSndWorker c srv Worker {doWork} = do liftIO $ assertUploadsAllowed c agentXFTPUploadChunk c userId chunkDigest replica' chunkSpec' liftIO $ waitUntilUploadsAllowed c - sf@SndFile {sndFileEntityId, prefixPath, chunks} <- withStore c $ \db -> do + sf@SndFile {sndFileEntityId, prefixPath, chunks} <- handleAllErrors (sndFileError c sndFileId) . withStore c $ \db -> do lockSndFileForUpdate db sndFileId updateSndChunkReplicaStatus db sndChunkReplicaId SFRSUploaded getSndFile db sndFileId @@ -582,7 +588,7 @@ runXFTPSndWorker c srv Worker {doWork} = do | otherwise = do let numRecipients' = min (numRecipients - length rcvIdsKeys) maxRecipients rcvIdsKeys' <- agentXFTPAddRecipients c userId chunkDigest cr numRecipients' - cr' <- withStore' c $ \db -> addSndChunkReplicaRecipients db cr $ L.toList rcvIdsKeys' + cr' <- withStore' c (\db -> addSndChunkReplicaRecipients db cr $ L.toList rcvIdsKeys') `catchAllErrors` sndFileError c sndFileId addRecipients ch cr' sndFileToDescrs :: SndFile -> AM (ValidFileDescription 'FSender, [ValidFileDescription 'FRecipient]) sndFileToDescrs SndFile {digest = Nothing} = throwE $ INTERNAL "snd file has no digest" diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index 98a4ab549..6712075b6 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -166,6 +166,7 @@ module Simplex.Messaging.Agent.Client waitUntilUploadsAllowed, withStore, withStore', + withStoreIsolation', withStoreBatch, withStoreBatch', unsafeWithStore, @@ -249,7 +250,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) +import Simplex.Messaging.Agent.Store.Common (DBStore, IsolationLevel (..), withTransactionIsolation) import Simplex.Messaging.Agent.Store.DB (SQLError) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Entity @@ -2305,7 +2306,7 @@ waitForWork = void . atomically . readTMVar {-# INLINE waitForWork #-} withWork :: AgentClient -> TMVar () -> (DB.Connection -> IO (Either StoreError (Maybe a))) -> (a -> AM ()) -> AM () -withWork c doWork = withWork_ c doWork . withStore' c +withWork c doWork = withWork_ c doWork . withStoreIsolation' c RepeatableRead {-# INLINE withWork #-} -- setting doWork flag to "no work" before getWork rather than after prevents race condition when flag is set to "has work" by another thread after getWork call. @@ -2487,10 +2488,20 @@ withStore' c action = withStore c $ fmap Right . action {-# INLINE withStore' #-} withStore :: AgentClient -> (DB.Connection -> IO (Either StoreError a)) -> AM a -withStore c action = do +withStore c action = withStore_ c (`withTransaction` action) + +withStoreIsolation' :: AgentClient -> IsolationLevel -> (DB.Connection -> IO a) -> AM a +withStoreIsolation' c isolation action = withStoreIsolation c isolation $ fmap Right . action +{-# INLINE withStoreIsolation' #-} + +withStoreIsolation :: AgentClient -> IsolationLevel -> (DB.Connection -> IO (Either StoreError a)) -> AM a +withStoreIsolation c isolation action = withStore_ c $ \st -> withTransactionIsolation st isolation action + +withStore_ :: AgentClient -> (DBStore -> IO (Either StoreError a)) -> AM a +withStore_ c transaction = do st <- asks store withExceptT storeError . ExceptT . liftIO . agentOperationBracket c AODatabase (\_ -> pure ()) $ - withTransaction st action `E.catch` handleDBErrors + transaction st `E.catch` handleDBErrors where handleDBErrors :: E.SomeException -> IO (Either StoreError a) handleDBErrors e = pure $ Left $ case E.fromException e of diff --git a/src/Simplex/Messaging/Agent/NtfSubSupervisor.hs b/src/Simplex/Messaging/Agent/NtfSubSupervisor.hs index 39b9d6600..de8713ec5 100644 --- a/src/Simplex/Messaging/Agent/NtfSubSupervisor.hs +++ b/src/Simplex/Messaging/Agent/NtfSubSupervisor.hs @@ -46,6 +46,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 (IsolationLevel (..)) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Client (NetworkRequestMode (..), nonBlockingWriteTBQueue) import qualified Simplex.Messaging.Crypto as C @@ -214,7 +215,7 @@ runNtfWorker c srv Worker {doWork} = runNtfOperation :: AM () runNtfOperation = do ntfBatchSize <- asks $ ntfBatchSize . config - withWorkItems c doWork (withStore' c $ \db -> getNextNtfSubNTFActions db srv ntfBatchSize) $ \nextSubs -> do + withWorkItems c doWork (withStoreIsolation' c RepeatableRead $ \db -> getNextNtfSubNTFActions db srv ntfBatchSize) $ \nextSubs -> do logInfo $ "runNtfWorker - length nextSubs = " <> tshow (length nextSubs) currTs <- liftIO getCurrentTime let (creates, checks, deletes, rotates) = splitActions currTs nextSubs @@ -382,7 +383,7 @@ runNtfSMPWorker c srv Worker {doWork} = forever $ do runNtfSMPOperation :: AM () runNtfSMPOperation = do ntfBatchSize <- asks $ ntfBatchSize . config - withWorkItems c doWork (withStore' c $ \db -> getNextNtfSubSMPActions db srv ntfBatchSize) $ \nextSubs -> do + withWorkItems c doWork (withStoreIsolation' c RepeatableRead $ \db -> getNextNtfSubSMPActions db srv ntfBatchSize) $ \nextSubs -> do logInfo $ "runNtfSMPWorker - length nextSubs = " <> tshow (length nextSubs) let (creates, deletes) = splitActions nextSubs retrySubActions c creates createNotifierKeys diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 9f350aaa0..f77434bf6 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -230,6 +230,7 @@ module Simplex.Messaging.Agent.Store.AgentStore updateRcvFileRedirect, updateRcvFileNoTmpPath, updateRcvFileDeleted, + getRcvFileDeleted, deleteRcvFile', getNextRcvChunkToDownload, getNextRcvFileToDecrypt, @@ -1169,17 +1170,21 @@ getWorkItems itemName getIds getItem markFailed = runExceptT $ handleWrkErr itemName "getIds" getIds >>= mapM (tryE . tryGetItem itemName 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 itemId) `catchAllErrors` \e -> mark >> throwE e +tryGetItem itemName getItem markFailed itemId = ExceptT getItem' `catchE` \e -> mark >> throwE e where + getItem' = E.handleJust workItemError (pure . Left . fromSomeException) $ getItem itemId mark = handleWrkErr itemName ("markFailed ID " <> show itemId) $ markFailed itemId -- Errors caught by this function will suspend worker as if there is no more work, handleWrkErr :: forall e a. AnyStoreError e => String -> String -> IO a -> ExceptT e IO a -handleWrkErr itemName opName action = ExceptT $ first mkError <$> E.try action +handleWrkErr itemName opName action = ExceptT $ first mkError <$> E.tryJust workItemError action where 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 + updatePendingMsgRIState :: DB.Connection -> ConnId -> InternalId -> RI2State -> IO () updatePendingMsgRIState db connId msgId RI2State {slowInterval, fastInterval} = DB.execute db "UPDATE snd_messages SET retry_int_slow = ?, retry_int_fast = ? WHERE conn_id = ? AND internal_id = ?" (slowInterval, fastInterval, connId, msgId) @@ -2062,7 +2067,8 @@ getNextNtfSubNTFActions db ntfServer@(NtfServer ntfHost ntfPort _) ntfBatchSize db [sql| SELECT conn_id - FROM ntf_subscriptions + FROM ntf_subscriptions ns + JOIN connections c USING (conn_id) WHERE ntf_host = ? AND ntf_port = ? AND ntf_sub_action IS NOT NULL AND (ntf_failed = 0 OR updated_by_supervisor = 1) ORDER BY ntf_sub_action_ts ASC @@ -2107,6 +2113,7 @@ getNextNtfSubSMPActions db smpServer@(SMPServer smpHost smpPort _) ntfBatchSize [sql| SELECT conn_id FROM ntf_subscriptions ns + JOIN connections c USING (conn_id) WHERE smp_host = ? AND smp_port = ? AND ntf_sub_smp_action IS NOT NULL AND ntf_sub_action_ts IS NOT NULL AND (smp_failed = 0 OR updated_by_supervisor = 1) ORDER BY ntf_sub_action_ts ASC @@ -3403,6 +3410,11 @@ updateRcvFileDeleted db rcvFileId = do updatedAt <- getCurrentTime DB.execute db "UPDATE rcv_files SET deleted = 1, updated_at = ? WHERE rcv_file_id = ?" (updatedAt, rcvFileId) +getRcvFileDeleted :: DB.Connection -> DBRcvFileId -> IO Bool +getRcvFileDeleted db rcvFileId = + maybeFirstRow' True fromOnlyBI $ + DB.query db "SELECT deleted FROM rcv_files WHERE rcv_file_id = ?" (Only rcvFileId) + deleteRcvFile' :: DB.Connection -> DBRcvFileId -> IO () deleteRcvFile' db rcvFileId = DB.execute db "DELETE FROM rcv_files WHERE rcv_file_id = ?" (Only rcvFileId) diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs index 267e4e8a9..ca470912f 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs @@ -9,16 +9,20 @@ module Simplex.Messaging.Agent.Store.Postgres.Common ( DBStore (..), DBStorePool (..), DBOpts (..), + IsolationLevel (..), newDBStorePool, withConnection, withConnection', withTransaction, withTransaction', withTransactionPriority, + withTransactionIsolation, + isTransactionConflict, withSavepoint, ) where +import Control.Logger.Simple (logWarn) import Control.Monad (void) import Control.Concurrent.MVar import Control.Concurrent.STM @@ -27,9 +31,10 @@ import Data.Bitraversable (bimapM) import Data.ByteString (ByteString) import Data.Functor (($>)) 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) +import Simplex.Messaging.Util (ifM, tshow) -- TODO [postgres] use log_min_duration_statement instead of custom slow queries (SQLite's Connection type) data DBStore = DBStore @@ -97,6 +102,32 @@ withTransactionPriority st priority action = withConnectionPriority st priority where transaction conn = PSQL.withTransaction conn $ action conn +-- isolation for agent transactions; postgresql-simple is not a dependency of SQLite builds +data IsolationLevel = RepeatableRead + +withTransactionIsolation :: DBStore -> IsolationLevel -> (PSQL.Connection -> IO a) -> IO a +withTransactionIsolation st isolation action = withConnection st transaction + where + transaction conn = retryTransaction 3 $ PSQL.withTransactionLevel level conn $ action conn + level = case isolation of + RepeatableRead -> PSQL.RepeatableRead + +retryTransaction :: Int -> IO a -> IO a +retryTransaction n transaction + | n > 0 = E.tryJust conflict transaction >>= either retryAfter pure + | otherwise = transaction + where + conflict e = if conflictState e then Just e else Nothing + retryAfter e = do + logWarn $ "transaction retried after " <> tshow e + retryTransaction (n - 1) transaction + +isTransactionConflict :: E.SomeException -> Bool +isTransactionConflict = maybe False conflictState . E.fromException + +conflictState :: PSQL.SqlError -> Bool +conflictState = (`elem` ["40001", "40P01"]) . PSQL.sqlState + -- Execute an action within a savepoint. -- On success, releases the savepoint. On error, rolls back to the savepoint -- to restore the transaction to a usable state before returning the error. diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs index 087d84eb1..46ea836dc 100644 --- a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs @@ -6,6 +6,7 @@ module Simplex.Messaging.Agent.Store.SQLite.Common ( DBStore (..), DBOpts (..), + IsolationLevel (..), SQLiteFuncDef (..), SQLiteFuncPtrs (..), withConnection, @@ -13,6 +14,8 @@ module Simplex.Messaging.Agent.Store.SQLite.Common withTransaction, withTransaction', withTransactionPriority, + withTransactionIsolation, + isTransactionConflict, withSavepoint, dbBusyLoop, storeKey, @@ -105,6 +108,15 @@ withTransactionPriority st@DBStore {dbClosed} priority action = withConnectionPr where 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 + +withTransactionIsolation :: DBStore -> IsolationLevel -> (DB.Connection -> IO a) -> IO a +withTransactionIsolation st _ = withTransaction st + +isTransactionConflict :: E.SomeException -> Bool +isTransactionConflict _ = 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/Util.hs b/src/Simplex/Messaging/Util.hs index 132270618..de7ba9236 100644 --- a/src/Simplex/Messaging/Util.hs +++ b/src/Simplex/Messaging/Util.hs @@ -33,6 +33,7 @@ module Simplex.Messaging.Util tryAllErrors, tryAllErrors', catchAllErrors, + handleAllErrors, catchAllErrors', catchThrow, allFinally, @@ -293,6 +294,10 @@ catchAllErrors :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> (e -> Except catchAllErrors action handler = tryAllErrors action >>= either handler pure {-# INLINE catchAllErrors #-} +handleAllErrors :: (AnyError e, MonadUnliftIO m) => (e -> ExceptT e m a) -> ExceptT e m a -> ExceptT e m a +handleAllErrors handler action = action `catchAllErrors` handler +{-# INLINE handleAllErrors #-} + catchAllErrors' :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> (e -> m a) -> m a catchAllErrors' action handler = tryAllErrors' action >>= either handler pure {-# INLINE catchAllErrors' #-} diff --git a/tests/AgentTests.hs b/tests/AgentTests.hs index 80539aa49..cb14f5fff 100644 --- a/tests/AgentTests.hs +++ b/tests/AgentTests.hs @@ -19,7 +19,9 @@ import Simplex.Messaging.Server.Env.STM (AStoreType (..)) import Simplex.Messaging.Transport (ASrvTransport) import Test.Hspec hiding (fit, it) -#if !defined(dbPostgres) +#if defined(dbPostgres) +import AgentTests.FunctionalAPITests (workItemReadTests) +#else import AgentTests.SQLiteTests (storeTests) #endif @@ -34,6 +36,9 @@ agentCoreTests = do describe "Double ratchet tests" doubleRatchetTests describe "Short link tests" shortLinkTests describe "resolve names" resolveNameTests +#if defined(dbPostgres) + describe "Work item reads" workItemReadTests +#endif agentTests :: (ASrvTransport, AStoreType) -> Spec agentTests ps = do diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index dc0037da5..41a3e9ae1 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -57,6 +57,9 @@ module AgentTests.FunctionalAPITests agentCfgVPrevPQ, agentCfgV7, testServerInformation, +#if defined(dbPostgres) + workItemReadTests, +#endif ) where @@ -132,9 +135,14 @@ import Util import XFTPClient (testXFTPServer, withXFTPServerThreadOn) #if defined(dbPostgres) +import Database.PostgreSQL.Simple (Only (..), Query) import Fixtures -import Simplex.Messaging.Agent.Store (RcvQueue, RcvQueueSub (..), ServiceAssoc) -import Simplex.Messaging.Agent.Store.AgentStore (deleteClientService, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs) +import Simplex.Messaging.Agent.Client (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.Common (IsolationLevel (..)) +import Simplex.Messaging.Notifications.Types (NtfAgentSubStatus (NASNew), NtfSubAction (NSANtf, NSASMP), NtfSubNTFAction (NSACreate), NtfSubSMPAction (NSASmpKey), newNtfSubscription) #endif #if defined(dbServerPostgres) import qualified Database.PostgreSQL.Simple as PSQL @@ -4861,6 +4869,129 @@ testTwoUsers = withAgentClients2 $ \a b -> do up :: ConnId -> ATransmission -> Bool up cId = \case ("", "", AEvt SAENone (UP _ [cId'])) -> cId' == cId; _ -> False +#if defined(dbPostgres) +workItemReadTests :: Spec +workItemReadTests = do + it "should read a command deleted after its ID query" $ + readWhileDeleting createCmd (lockTable "connections") "JOIN connections cs USING (conn_id)" "DELETE FROM commands" readCommand + `shouldReturn` True + it "should read a ntf subscription whose connection is deleted after its ID query" $ + readWhileDeleting (createNtfSub $ NSANtf NSACreate) (lockTable "servers") "JOIN servers s ON s.host = ns.smp_host" "DELETE FROM connections" (readNtfActions testNtfServer) + `shouldReturn` True + it "should read a ntf SMP action whose connection is deleted after its ID query" $ + readWhileDeleting (createNtfSub $ NSASMP NSASmpKey) (lockTable "ntf_servers") "JOIN ntf_servers s USING (ntf_host, ntf_port)" "DELETE FROM connections" (readSMPActions testSMPServer) + `shouldReturn` True + it "should retry the read when a file is deleted while its lock is awaited" $ + readWhileDeleting createSndFile' (lockRows "snd_files") "redirect_size, redirect_digest, storage_time" "DELETE FROM snd_files" readSndFile + `shouldReturn` False + it "should retry the read when a ntf subscription is deleted while its update waits" $ + readWhileDeleting (createNtfSub $ NSANtf NSACreate) (lockRows "ntf_subscriptions") "SET updated_by_supervisor = 0" "DELETE FROM ntf_subscriptions" (readNtfActions testNtfServer) + `shouldReturn` False + it "should retry the read aborted by deadlock with ntf subscription deletion" $ + readWhileDeleting (createNtfSub $ NSANtf NSACreate) (lockTable "servers") "JOIN servers s ON s.host = ns.smp_host" "DELETE FROM ntf_subscriptions" (readNtfActions testNtfServer) + `shouldReturn` False + it "should mark a command failed when its read fails" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> 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 () + 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 retry the read 3 times on the same connection after serialization failures" $ do + (r, pids) <- readWithErrors 3 "40001" + r `shouldBe` Right () + attemptsOn pids `shouldBe` (4, 1) + it "should retry the read after deadlocks" $ do + (r, pids) <- readWithErrors 2 "40P01" + r `shouldBe` Right () + attemptsOn pids `shouldBe` (3, 1) + it "should report INTERNAL when serialization failures continue after 3 retries" $ do + (Left (A.INTERNAL e), pids) <- readWithErrors 4 "40001" + e `shouldContain` "sqlState = \\\"40001\\\"" + attemptsOn pids `shouldBe` (4, 1) + it "should not retry the read after other database errors" $ do + (Left (A.INTERNAL e), pids) <- readWithErrors 1 "23505" + e `shouldContain` "sqlState = \\\"23505\\\"" + attemptsOn pids `shouldBe` (1, 1) + where + attemptsOn :: [Int] -> (Int, Int) + attemptsOn pids = (length pids, S.size $ S.fromList pids) + createCmd :: DB.Connection -> IO () + createCmd db = do + createConn db + createCommand db "1" "conn1" Nothing (AClientCommand $ NEW True (ACM SCMInvitation) IKPQOn SMSubscribe False) `shouldReturn` Right () + readCommand a doWork = withWork a doWork $ \db -> getPendingServerCommand db "conn1" Nothing + createNtfSub :: HasTestEnv => NtfSubAction -> DB.Connection -> IO () + createNtfSub action db = do + let ProtocolServer {host = ntfHost, port = ntfPort, keyHash = ntfKeyHash} = testNtfServer + createConn db + void $ createServer db testSMPServer + DB.execute db "INSERT INTO ntf_servers (ntf_host, ntf_port, ntf_key_hash) VALUES (?,?,?)" (ntfHost, ntfPort, ntfKeyHash) + 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 + createSndFile' :: DB.Connection -> IO () + createSndFile' db = do + g <- C.newRandom + key <- atomically $ C.randomSbKey g + nonce <- atomically $ C.randomCbNonce g + Right sfId <- createSndFile db g 1 (CryptoFile "testfile" Nothing) 1 "test.xftp" key nonce Nothing Nothing + startPreparedSndFile db sfId `shouldReturn` Right () + readSndFile a doWork = withWork a doWork (`getNextSndFileToPrepare` 86400) + createConn :: DB.Connection -> IO () + createConn db = DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (?,?,?)" (1 :: Int64, "conn1" :: ConnId, SCMInvitation) + lockTable :: Query -> DB.Connection -> IO () + lockTable table db = DB.execute_ db $ "LOCK TABLE " <> table <> " IN ACCESS EXCLUSIVE MODE" + lockRows :: Query -> DB.Connection -> IO () + lockRows table db = void (DB.query_ db ("SELECT 1 FROM " <> table <> " FOR UPDATE") :: IO [Only Int]) + +readWhileDeleting :: HasTestEnv => (DB.Connection -> IO ()) -> (DB.Connection -> IO ()) -> String -> Query -> (AgentClient -> TMVar () -> (a -> AM ()) -> AM ()) -> IO Bool +readWhileDeleting createItem lockItem waitingQuery deleteItem readItem = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st createItem + doWork <- newTMVarIO () + itemRead <- newTVarIO False + 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) + waitForLock st holder waitingQuery + DB.execute_ db deleteItem + pure r + wait reading `shouldReturn` Right () + events <- atomically $ flushTBQueue $ subQ a + filter workerError events `shouldBe` [] + readTVarIO itemRead + +workerError :: ATransmission -> Bool +workerError (_, _, AEvt _ e) = case e of + ERR _ -> True + ERRS _ -> True + _ -> False + +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,) <$> readIORef pids + where + readItem pids db = do + [Only pid] <- DB.query_ db "SELECT pg_backend_pid()" + n <- atomicModifyIORef' pids $ \ps -> (pid : ps, length ps) + when (n < failures) $ DB.execute_ db $ "DO $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = '" <> errCode <> "'; END $$" + +waitForLock :: DBStore -> Int -> String -> IO () +waitForLock st holder waitingQuery = timeout 5000000 waitLoop `shouldReturn` Just () + where + waitLoop = do + [Only waiting] <- + 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 +#endif + testClientServiceConnection :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testClientServiceConnection ps = do ((sId, uId), qIdHash) <- withSmpServerStoreLogOn ps testPort $ \_ -> do diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index d76d6ad1b..5c7d50ce1 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -35,14 +35,15 @@ import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..)) import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..), defaultFileExpiration) import Simplex.FileTransfer.Server.Store (STMFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (AUTH)) -import Simplex.FileTransfer.Types (RcvFileId, SndFileId) +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 (AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) +import Simplex.Messaging.Agent.Client (AgentClient (xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, 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 +import Simplex.Messaging.Agent.Stats (AgentXFTPServerStats (downloadAttempts, uploadAttempts)) import Simplex.Messaging.Agent.Store.Common (withTransaction) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Interface (closeDBStore) @@ -95,6 +96,10 @@ xftpAgentTests = -- TODO when server is fixed to correctly send AUTH error, this test has to be modified to expect AUTH error it "if file is deleted on server, should limit retries and continue receiving next file" testXFTPAgentDeleteOnServer it "if file is expired on server, should report error and continue receiving next file" testXFTPAgentExpiredOnServer + it "should report NO_FILE when file is deleted from database during upload" $ \_ -> testXFTPAgentDeleteDuringUpload agentCfg 1 + it "should report NO_FILE when file is deleted from database while adding recipients" $ \_ -> + testXFTPAgentDeleteDuringUpload agentCfg {AEnv.xftpMaxRecipientsPerRequest = 1} 2 + it "should report NO_FILE when file is deleted from database during download" $ \_ -> testXFTPAgentDeleteDuringDownload it "should request additional recipient IDs when number of recipients exceeds maximum per request" testXFTPAgentRequestAdditionalRecipientIDs it "should complete sending file while agent is suspending" testXFTPAgentSuspendSending it "should suspend on timeout when file is not sent" $ \_ -> testXFTPAgentSuspendTimeout @@ -1060,6 +1065,50 @@ testXFTPAgentExpiredOnServer fsType = withGlobalLogging logCfgNoLogs $ where fastExpiration = ExpirationConfig {ttl = 2, checkInterval = 1} +testXFTPAgentDeleteDuringUpload :: (HasCallStack, HasTestEnv) => AgentConfig -> Int -> IO () +testXFTPAgentDeleteDuringUpload cfg numRecipients = do + filePath <- createRandomFile + sfId <- withXFTPServerStoreLogOn $ \_ -> + withAgent 1 cfg initAgentServers testDB $ \sndr -> runRight $ do + xftpStartWorkers sndr (Just senderFiles) + sfId <- xftpSendFile sndr 1 (CF.plain filePath) numRecipients + ("", sfId', SFPROG _ _) <- sfGet sndr + liftIO $ sfId' `shouldBe` sfId + pure sfId + withAgent 2 cfg {AEnv.xftpConsecutiveRetries = 100} initAgentServers testDB $ \sndr -> do + runRight_ $ xftpStartWorkers sndr (Just senderFiles) + waitForAttempt sndr uploadAttempts + withTransaction (agentClientStore sndr) (`DB.execute_` "DELETE FROM snd_files") + withXFTPServerStoreLogOn $ \_ -> + timeout 30000000 (sfGet sndr) >>= \case + Just ("", sfId', SFERR e) -> (sfId', e) `shouldBe` (sfId, FILE NO_FILE) + r -> expectationFailure $ "unexpected event " <> show r + +testXFTPAgentDeleteDuringDownload :: (HasCallStack, HasTestEnv) => IO () +testXFTPAgentDeleteDuringDownload = do + filePath <- createRandomFile + rfd <- withXFTPServerStoreLogOn $ \_ -> + withAgent 1 agentCfg initAgentServers testDB $ \sndr -> do + (_, _, rfd, _) <- runRight $ testSend sndr filePath + pure rfd + withAgent 2 agentCfg {AEnv.xftpConsecutiveRetries = 100} initAgentServers testDB2 $ \rcp -> do + rfId <- runRight $ do + xftpStartWorkers rcp (Just recipientFiles) + xftpReceiveFile rcp 1 rfd Nothing True + waitForAttempt rcp downloadAttempts + withTransaction (agentClientStore rcp) (`DB.execute_` "DELETE FROM rcv_files") + withXFTPServerStoreLogOn $ \_ -> + timeout 30000000 (rfGet rcp) >>= \case + Just ("", rfId', RFERR e) -> (rfId', e) `shouldBe` (rfId, FILE NO_FILE) + r -> expectationFailure $ "unexpected event " <> show r + +waitForAttempt :: HasCallStack => AgentClient -> (AgentXFTPServerStats -> TVar Int) -> IO () +waitForAttempt c attempts = do + n <- atomically count + timeout 10000000 (atomically $ count >>= checkSTM . (> n)) `shouldReturn` Just () + where + count = readTVar (xftpServersStats c) >>= fmap sum . mapM (readTVar . attempts) . M.elems + testXFTPAgentRequestAdditionalRecipientIDs :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () testXFTPAgentRequestAdditionalRecipientIDs = withXFTPServer $ do filePath <- createRandomFile