From dbb9f264c850d73dbfeb693fa5a2dd56e2a6d2a8 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 01/44] agent, clients: prevent hangs while a server or event processing is slow --- src/Simplex/FileTransfer/Agent.hs | 2 +- src/Simplex/Messaging/Agent.hs | 393 +++++++++++++--------- 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, 826 insertions(+), 206 deletions(-) diff --git a/src/Simplex/FileTransfer/Agent.hs b/src/Simplex/FileTransfer/Agent.hs index 9165d01b3..bc5c9ff5c 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 a17f79019..efc59f03e 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 @@ -1181,8 +1183,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) @@ -1245,15 +1250,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 @@ -1312,13 +1317,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 @@ -1743,7 +1749,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 @@ -1912,7 +1918,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 @@ -1986,8 +1992,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 @@ -2034,7 +2040,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 @@ -2226,10 +2232,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 @@ -2295,36 +2301,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 @@ -2346,95 +2362,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 @@ -2449,11 +2490,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 @@ -2472,11 +2513,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) @@ -2841,26 +2886,32 @@ 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 {} -> ack $ sendRcpt conn - RcvConnection {} -> ack $ pure () - 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 () -> AM (Maybe ATransmission) - ack afterAck = - -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged + -- 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 (rq, srvMsgId) -> do - t_ <- ackQueueMessage c rq srvMsgId - afterAck - t_ <$ del + Right r -> pure $ Just r Left (SEMsgNotFound _) -> Nothing <$ del Left e -> throwE $ storeError e del :: AM () @@ -2891,19 +2942,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 @@ -2913,12 +2965,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 = @@ -2968,12 +3031,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 @@ -2993,14 +3056,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 @@ -3063,7 +3128,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 @@ -3133,8 +3198,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 @@ -3458,6 +3523,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 @@ -3579,7 +3645,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 @@ -3779,6 +3845,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 @@ -3821,6 +3888,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 @@ -4408,11 +4476,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 6712075b6..da9911cbf 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 0c9fd8521..3dbb86611 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 @@ -517,6 +525,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 @@ -533,6 +543,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 @@ -541,6 +553,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 @@ -557,6 +573,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 @@ -575,6 +593,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" $ @@ -585,6 +607,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" $ @@ -595,6 +618,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" $ @@ -648,6 +683,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 "should deliver receipt again after client restart without acknowledgement" $ testDuplicateReceipt ps False False @@ -1162,6 +1200,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 @@ -1647,6 +1704,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 @@ -3250,6 +3343,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 @@ -3416,6 +3524,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 @@ -3517,6 +3634,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 @@ -3760,6 +3906,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 @@ -4051,6 +4211,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 @@ -4187,6 +4367,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 @@ -4659,6 +4953,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 @@ -5361,6 +5668,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 1dd2b3636..11b6b76a8 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -23,7 +23,7 @@ import Data.List.NonEmpty (NonEmpty) import qualified Data.X509 as X 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 (..)) @@ -43,6 +43,7 @@ import Simplex.Messaging.Util (unlessM) import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal 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) @@ -79,6 +80,9 @@ testPort = testServerPort 1 testPort2 :: HasTestEnv => ServiceName testPort2 = testServerPort 2 +testPort3 :: HasTestEnv => ServiceName +testPort3 = testServerPort 8 + ntfTestPort :: HasTestEnv => ServiceName ntfTestPort = testServerPort 3 @@ -427,6 +431,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 e930913352291a4a48ca5caf6dd452fe7c573872 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 02/44] 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 efc59f03e..9cf046015 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 @@ -2312,7 +2312,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 @@ -2886,27 +2886,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 7632a07a4c8f40f00e1a01a429630a6a75719ead 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 03/44] 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 3dbb86611..07dec1ae8 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -3660,7 +3660,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 () @@ -4229,7 +4229,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 76079eeb0a991f3b1d1fb33637b47c1e0a6fe744 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 04/44] 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 07dec1ae8..20232e381 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -553,8 +553,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 @@ -3634,18 +3634,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 39a30e17d9660accf9ce4593fee6ebd0332d0ea7 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 05/44] 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 20232e381..7ac09d48f 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -3346,12 +3346,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 259167a89633671cffb3d20bfd812372d4990a29 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 06/44] 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 9cf046015..25748798d 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3516,15 +3516,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 284a4d782abaa84ab6b5e25569f4a8aceaf0757f 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 07/44] 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 59b1e229b..276b310f8 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -89,6 +89,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 @@ -409,6 +414,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.* @@ -662,6 +669,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 25748798d..26cc2684a 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 @@ -1036,8 +1039,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) @@ -1730,8 +1735,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 @@ -1871,9 +1879,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) @@ -3189,7 +3196,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' @@ -3646,7 +3653,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 da9911cbf..3df783afa 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 170e8740f..61b7043a8 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_ uninterruptibleCancel . 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 7ac09d48f..157f8da77 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 @@ -683,9 +685,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 "should deliver receipt again after client restart without acknowledgement" $ testDuplicateReceipt ps False False @@ -4433,6 +4439,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 $ @@ -4961,6 +4985,7 @@ testConnectionVerifyCodes = codes1'' <- getConnectionVerifyCodes a bId liftIO $ codes1'' `shouldBe` codes1 +#if defined(conn_lock_checks) testServerRequestInConnLock :: (HasCallStack, HasTestEnv) => IO () testServerRequestInConnLock = withAgentClients2 $ \a b -> do @@ -4973,6 +4998,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 6b67a5d00..e90565d06 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 (withStallingServerOn') +import SMPClient (serverBracket, 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 (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 @@ -87,6 +90,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 @@ -439,6 +444,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 1b3798d0e4fba03642cbb0deda3f4fa646f6bc2b 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 08/44] 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 157f8da77..60e204f91 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -1732,14 +1732,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) @@ -4414,11 +4414,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 @@ -4431,11 +4431,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) @@ -4447,11 +4447,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 11b6b76a8..c3c9aa7a5 100644 --- a/tests/SMPClient.hs +++ b/tests/SMPClient.hs @@ -431,21 +431,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 277c0f426b4476dce0b0bc7441f6d16dfdcb8d6d 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 09/44] 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 3df783afa..ed4b02d83 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 5658cbd8910ae51034456214858d6ac6b19a5d41 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:28:53 +0000 Subject: [PATCH 10/44] docs: plan for the agent without waits on slow servers --- plans/2026-11-21-agent-no-blocking.md | 70 +++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 plans/2026-11-21-agent-no-blocking.md diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md new file mode 100644 index 000000000..ec6bc5da3 --- /dev/null +++ b/plans/2026-11-21-agent-no-blocking.md @@ -0,0 +1,70 @@ +# Agent without waits on slow servers and full queues + +## Problem + +- One subscriber thread processes received messages, each under the lock of its connection. +- Worker and API threads held that lock across server requests, up to 75 seconds per attempt, so one slow server stopped the messages of all connections. +- An acknowledgement held the lock while it waited for space in msgQ, which only the subscriber drains, after it takes the same lock. +- API calls waited for space in subQ, which the app drains while it holds its own locks. + +## Rules + +1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails. +2. The second locked step reads the connection again; when its state changed, the step is dropped, postponed during ratchet synchronization, or undone. +3. A queue created on a server is recorded under the connection lock or deleted from the server; connection deletion takes the same locks. +4. API threads and lock holders never wait for space in subQ or msgQ. + +## Helpers + +- `requestAndCommit`: validates the connection under the lock, makes the request, validates again and commits under the lock. +- `recordNewQueue`: records a queue created on a server under the lock, or deletes it from the server. + +## Sequence + +```mermaid +sequenceDiagram + participant W as Worker of connection X + participant L as Lock of X + participant S as Slow server + participant Sub as Subscriber + participant P as Protocol clients + rect rgb(255,228,228) + Note over W,P: Before + W->>L: take + W->>S: SKEY, confirmation + Sub--xL: MSG for X waits up to 75 s + P--xSub: MSG for Y, Z: msgQ full, writers wait + end + rect rgb(226,244,226) + Note over W,P: After + W->>L: read, validate, release + W->>S: SKEY, confirmation, without the lock + Sub->>L: MSG for X waits for database work only + P->>Sub: MSG for Y, Z processed + W->>L: read again, validate, write + end +``` + +## Changes + +- agent, connection locks: + - `requestAndCommit` in ICDuplexSecure, ICQSecure, ICQSndSecure, ICQDelete and `ackMessage`; + - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; + - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; + - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; + - deletion under the locks of its connections; + - the record step of an acknowledgement reads the queue again; + - a concurrent acknowledgement of a deleted message is dropped; + - each switch start has an identifier; an abort removes it, and the switch whose identifier was removed is aborted after its queue is created; + - the receive queue status is set to Secured under the lock, only from Confirmed; + - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, resumed after synchronization; + - SWCH is refused while the ratchet is not synchronized. +- agent, events written without waiting: + - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; + - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; + - the notification command of connection deletion. +- clients: + - a message in the response to ACK, SUB or GET is written to msgQ without waiting; + - a command waits for send-queue space only until its response timeout, and is not sent after it ends; + - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. +- moved to separate pull requests: the HTTP/2 request timeout, the SUSPENDED event written without waiting. From a411c2852723c38e4ee92ad4ed0aec4f34014491 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:32:39 +0000 Subject: [PATCH 11/44] agent, xftp: move SUSPENDED and HTTP/2 changes to separate pull requests --- src/Simplex/Messaging/Agent.hs | 7 ++- src/Simplex/Messaging/Agent/Client.hs | 20 +++----- .../Messaging/Transport/HTTP2/Client.hs | 13 +++-- tests/AgentTests/FunctionalAPITests.hs | 11 ---- tests/XFTPServerTests.hs | 51 ++----------------- 5 files changed, 20 insertions(+), 82 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 26cc2684a..2e65df384 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3523,15 +3523,14 @@ suspendAgent c 0 = do where suspend opSel = atomically $ modifyTVar' (opSel c) $ \s -> s {opSuspended = True} suspendAgent c@AgentClient {agentState = as} maxDelay = do - (prevState, state) <- + state <- atomically $ do - prevState <- swapTVar as ASSuspending + writeTVar as ASSuspending suspendOperation c AONtfNetwork $ pure () suspendOperation c AORcvNetwork $ suspendOperation c AOSndFiles $ suspendMsgDelivery c - (prevState,) <$> readTVar as - unless (prevState == ASSuspending) . void . forkIO $ notifySuspended c + readTVar as when (state == ASSuspending) $ do void . forkIO $ removeDeletedOrFailedSndFilesInProgress c void . forkIO $ do diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index ed4b02d83..a5779ff0b 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -2435,9 +2435,9 @@ endAgentOperation c op = endOperation c op $ case op of suspendSendingAndDatabase c AOSndNetwork -> suspendOperation c AODatabase $ - setSuspended c + notifySuspended c AODatabase -> - setSuspended c + notifySuspended c suspendMsgDelivery :: AgentClient -> STM () suspendMsgDelivery c = @@ -2448,7 +2448,7 @@ suspendSendingAndDatabase :: AgentClient -> STM () suspendSendingAndDatabase c = suspendOperation c AOSndNetwork $ suspendOperation c AODatabase $ - setSuspended c + notifySuspended c suspendOperation :: AgentClient -> AgentOperation -> STM () -> STM () suspendOperation c op endedAction = do @@ -2456,15 +2456,11 @@ suspendOperation c op endedAction = do -- unsafeIOToSTM $ putStrLn $ "suspendOperation_ " <> show op <> " " <> show n when (n == 0) $ whenSuspending c endedAction -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) +notifySuspended :: AgentClient -> STM () +notifySuspended c = do + -- unsafeIOToSTM $ putStrLn "notifySuspended" + writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) + writeTVar (agentState c) ASSuspended endOperation :: AgentClient -> AgentOperation -> STM () -> STM () endOperation c op endedAction = do diff --git a/src/Simplex/Messaging/Transport/HTTP2/Client.hs b/src/Simplex/Messaging/Transport/HTTP2/Client.hs index 61b7043a8..170e8740f 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, whenM) +import Simplex.Messaging.Util (eitherToMaybe) import UnliftIO.STM import UnliftIO.Timeout @@ -65,7 +65,7 @@ data HClient = HClient host :: TransportHost, port :: ServiceName, config :: HTTP2ClientConfig, - reqQ :: TBQueue (Request, TVar Bool, TMVar HTTP2Response) + reqQ :: TBQueue (Request, 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, pending, respVar) <- atomically $ readTBQueue reqQ - whenM (readTVarIO pending) . void . sendReq req $ \r -> do + (req, respVar) <- atomically $ readTBQueue reqQ + sendReq req $ \r -> do respBody <- getHTTP2Body r (bodyHeadSize config) let resp = HTTP2Response {response = r, respBody} atomically $ putTMVar respVar resp @@ -189,10 +189,9 @@ closeHTTP2Client = mapM_ uninterruptibleCancel . action sendRequest :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) sendRequest HTTP2Client {client_ = HClient {config, reqQ}} req reqTimeout_ = do resp <- newEmptyTMVarIO - pending <- newTVarIO True + atomically $ writeTBQueue reqQ (req, resp) let reqTimeout = http2RequestTimeout config reqTimeout_ - maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` (atomically (writeTBQueue reqQ (req, pending, resp)) >> atomically (takeTMVar resp))) - `E.finally` atomically (writeTVar pending False) + maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` atomically (takeTMVar resp)) -- | 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 a2b68c695..7e203cf9f 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -553,8 +553,6 @@ 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 @@ -3559,15 +3557,6 @@ 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 diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 8a5b444ff..482d57230 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -30,11 +30,9 @@ 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, serverBracket, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn') +import SMPClient (copyWebCredential, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn') import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A @@ -50,16 +48,15 @@ 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 (..), defaultHTTP2BufferSize) +import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..)) 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_, wait, withAsync) +import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_) import UnliftIO.STM import UnliftIO.Timeout (timeout) import Util @@ -90,8 +87,6 @@ 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 @@ -445,46 +440,6 @@ 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 a33da6bc1ebddbd93c87ce069b28d8b9392382b8 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:36:06 +0000 Subject: [PATCH 12/44] agent: validate, request and commit queue changes in one helper --- src/Simplex/Messaging/Agent.hs | 111 +++++++++++++++++---------------- 1 file changed, 56 insertions(+), 55 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 2e65df384..369ed9846 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2369,12 +2369,9 @@ 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' . 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 + ICDuplexSecure _rId senderKey -> withServer' . tryAtomicCommand . void $ + requestAndCommit c connId "ICDuplexSecure" duplexConn (\(_, rq :| _, _) -> secure rq senderKey) $ + \_ (cData, _, sq :| _) -> void $ 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) @@ -2391,14 +2388,12 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do throwE e _ -> withStore' c $ \db -> deleteConnRcvQueue db rq >> deleteCommand db cmdId ICQSecure rId senderKey -> - withServer $ \srv -> tryAtomicCommand $ do - rq_ <- withConnLock c connId "ICQSecure" . withSwitchingQueues srv $ \_ _ _ rq' _ -> pure rq' - forM_ rq_ $ \rq -> do - secureQueue c NRMBackground rq senderKey + withServer $ \srv -> tryAtomicCommand . void $ + requestAndCommit c connId "ICQSecure" (switchingQueues srv) (\(_, _, _, rq, _) -> 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 + \_ (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) @@ -2407,76 +2402,76 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do 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 -> + switchingQueues :: SMPServer -> AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue, RcvQueue, RcvQueue)) + switchingQueues srv = duplexConn $>>= \(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 + | otherwise -> pure $ Just (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 -> tryCommand $ do - sq_ <- withConnLock c connId "ICQSndSecure" . withSecuringQueues srv $ \ConnData {connAgentVersion} _ _ sq' _ -> pure (connAgentVersion, sq') - forM_ sq_ $ \(connAgentVersion, sq) -> do + withServer $ \srv -> tryCommand . void $ + requestAndCommit c connId "ICQSndSecure" (securingQueues srv) secureNewQueue $ \_ (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 + secureNewQueue :: (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue, SndQueue, SndQueue) -> AM () + secureNewQueue (ConnData {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 -> + securingQueues :: SMPServer -> AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue, SndQueue, SndQueue)) + securingQueues srv = duplexConn $>>= \(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 + Just oldSq -> pure $ Just (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 -> 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 + withServer $ \srv -> tryAtomicCommand . void $ + requestAndCommit c connId "ICQDelete" (removedQueue srv) deleteRemovedQueue $ \deleted (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 -> + deleteRemovedQueue :: (ConnData, RcvQueue, NonEmpty RcvQueue, NonEmpty SndQueue) -> AM (Either AgentErrorType ()) + deleteRemovedQueue (_, rq, _, _) = + tryAllErrors (deleteQueue c NRMBackground rq) >>= \case + Left e | temporaryOrHostError e -> throwE e + deleted -> pure deleted + removedQueue :: SMPServer -> AM (Maybe (ConnData, RcvQueue, NonEmpty RcvQueue, NonEmpty SndQueue)) + removedQueue srv = duplexConn $>>= \(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 + pure $ Just (cData, rq', rq'' :| rqs', sqs) _ -> Nothing <$ internalErr "ICQDelete: cannot delete the only queue in connection" where ack srv rId srvMsgId = @@ -2497,10 +2492,10 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do noServer a = case server_ of Nothing -> a _ -> internalErr "command requires no server" - withDuplexConn :: (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> AM (Maybe a)) -> AM (Maybe a) - withDuplexConn a = + duplexConn :: AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue)) + duplexConn = withStore c (`getConn` connId) >>= \case - SomeConn _ (DuplexConnection cData rqs sqs) -> a cData rqs sqs + SomeConn _ (DuplexConnection cData rqs sqs) -> pure $ Just (cData, rqs, sqs) _ -> Nothing <$ internalErr "command requires duplex connection" tryCommand action = tryMoveableCommand (action $> CCCompleted) tryAtomicCommand action = tryMoveableCommand (action $> CCDeleted) @@ -2895,6 +2890,12 @@ withConnLockNotify c connId name action = do t_ <- withConnLock c connId name action forM_ t_ $ atomically . writeTBQueue (subQ c) +requestAndCommit :: AgentClient -> ConnId -> Text -> AM (Maybe s) -> (s -> AM r) -> (r -> s -> AM a) -> AM (Maybe a) +requestAndCommit c connId name validate request commit = + withConnLock c connId name validate $>>= \s -> do + r <- request s + withConnLock c connId name $ validate $>>= fmap Just . commit r + 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 From 2a06cc10674d5c638a3ea9d200e9a602c8db7e69 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:36:24 +0000 Subject: [PATCH 13/44] agent: prevent the Secured queue status from replacing Active --- src/Simplex/Messaging/Agent.hs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 369ed9846..0b69cc82e 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2480,10 +2480,11 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do Left SEConnNotFound -> pure (pure Nothing) Left e -> throwE $ storeError e secure :: RcvQueue -> SMP.SndPublicAuthKey -> AM () - secure rq@RcvQueue {server} senderKey = do + secure rq@RcvQueue {server, rcvId} senderKey = do secureQueue c NRMBackground rq senderKey incSMPServerStat c userId server connSecured - withStore' c $ \db -> setRcvQueueStatus db rq Secured + withConnLock c connId "secure" . withStore' c $ \db -> + getRcvQueue db connId server rcvId >>= mapM_ (\rq'@RcvQueue {status} -> when (status == Confirmed) $ setRcvQueueStatus db rq' Secured) where withServer a = case server_ of Just srv -> a srv From 425d53c2c2e1d34a19048a9d08c2b0e5f8814724 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:38:55 +0000 Subject: [PATCH 14/44] agent: accept a repeated acknowledgement, read queue status after ACK --- src/Simplex/Messaging/Agent.hs | 50 +++++++++++++++----------- tests/AgentTests/FunctionalAPITests.hs | 31 ++++++++++++++++ 2 files changed, 60 insertions(+), 21 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 0b69cc82e..72cf03769 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2338,13 +2338,13 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do AInternalCommand cmd -> case cmd of ICAckDel rId srvMsgId msgId -> withServer $ \srv -> tryAtomicCommand $ do - recordAck <- ack srv rId srvMsgId + acked <- ack srv rId srvMsgId withConnLockNotify c connId "ICAckDel" $ do - t_ <- recordAck + t_ <- recordAck srvMsgId acked withStore' c (\db -> deleteMsg db connId msgId >> deleteCommand db cmdId) pure t_ ICAck rId srvMsgId -> withServer $ \srv -> - tryCommand $ ack srv rId srvMsgId >>= withConnLockNotify c connId "ICAck" + tryCommand $ ack srv rId srvMsgId >>= withConnLockNotify c connId "ICAck" . recordAck srvMsgId ICAllowSecure _rId senderKey -> withServer' . tryMoveableCommand $ do (SomeConn _ conn, AcceptedConfirmation {senderConf, ownConnInfo}) <- withConnLock c connId "ICAllowSecure" . withStore c $ \db -> runExceptT $ (,) <$> ExceptT (getConn db connId) <*> ExceptT (getAcceptedConfirmation db connId) @@ -2474,11 +2474,14 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do pure $ Just (cData, rq', rq'' :| rqs', sqs) _ -> Nothing <$ internalErr "ICQDelete: cannot delete the only queue in connection" where + ack :: SMPServer -> SMP.RecipientId -> SMP.MsgId -> AM (Maybe (RcvQueue, Bool)) ack srv rId srvMsgId = withStore' c (\db -> getRcvQueue db connId srv rId) >>= \case - Right rq -> ackQueueMessage c rq srvMsgId - Left SEConnNotFound -> pure (pure Nothing) + Right rq -> Just . (rq,) <$> ackQueueMessage c rq srvMsgId + Left SEConnNotFound -> pure Nothing Left e -> throwE $ storeError e + recordAck :: SMP.MsgId -> Maybe (RcvQueue, Bool) -> AM (Maybe ATransmission) + recordAck srvMsgId = maybe (pure Nothing) $ \(rq, drained) -> recordQueueAck c rq srvMsgId drained secure :: RcvQueue -> SMP.SndPublicAuthKey -> AM () secure rq@RcvQueue {server, rcvId} senderKey = do secureQueue c NRMBackground rq senderKey @@ -2899,15 +2902,15 @@ requestAndCommit c connId name validate request commit = 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 - withConnLock c connId "ackMessage" $ do - t_ <- recordAck + join <$> requestAndCommit c connId "ackMessage" markConnUserAck (uncurry $ ackQueueMessage c) recordAck + where + recordAck :: Bool -> (RcvQueue, SMP.MsgId) -> AM (Maybe ATransmission) + recordAck drained (rq, srvMsgId) = do + t_ <- recordQueueAck c rq srvMsgId drained 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) @@ -3041,23 +3044,28 @@ 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 (AM (Maybe ATransmission)) -ackQueueMessage c rq@RcvQueue {userId, connId, server, rcvSwchStatus} srvMsgId = do +ackQueueMessage :: AgentClient -> RcvQueue -> SMP.MsgId -> AM Bool +ackQueueMessage c rq@RcvQueue {userId, server} srvMsgId = do incSMPServerStat c userId server ackAttempts tryAllErrors (sendAck c rq srvMsgId) >>= \case - Right drained -> pure $ sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND - Left (SMP _ SMP.NO_MSG) -> pure $ sendMsgNtf ackNoMsgErrs False + Right drained -> drained <$ incSMPServerStat c userId server ackMsgs + Left (SMP _ SMP.NO_MSG) -> False <$ incSMPServerStat c userId server ackNoMsgErrs Left e -> do unless (temporaryOrHostError e) $ incSMPServerStat c userId server ackOtherErrs throwE e + +recordQueueAck :: AgentClient -> RcvQueue -> SMP.MsgId -> Bool -> AM (Maybe ATransmission) +recordQueueAck c rq@RcvQueue {connId, server, rcvId} srvMsgId drained = + ifM (liftIO $ hasGetLock c rq) + (do atomically $ releaseGetLock c rq + brokerTs_ <- eitherToMaybe <$> tryAllErrors (withStore c $ \db -> getRcvMsgBrokerTs db connId srvMsgId) + pure $ Just ("", connId, AEvt SAEConn $ MSGNTF srvMsgId brokerTs_)) + (Nothing <$ when drained deleteEndedQueue) where - sendMsgNtf stat ended = do - incSMPServerStat c userId server stat - ifM (liftIO $ hasGetLock c rq) - (do atomically $ releaseGetLock c rq - brokerTs_ <- eitherToMaybe <$> tryAllErrors (withStore c $ \db -> getRcvMsgBrokerTs db connId srvMsgId) - pure $ Just ("", connId, AEvt SAEConn $ MSGNTF srvMsgId brokerTs_)) - (Nothing <$ when ended (deleteRcvQueueAsync c rq)) + deleteEndedQueue = + withStore' c (\db -> getRcvQueue db connId server rcvId) >>= \case + Right rq'@RcvQueue {rcvSwchStatus = Just RSReceivedQEND} -> deleteRcvQueueAsync c rq' + _ -> pure () deleteRcvQueueAsync :: AgentClient -> RcvQueue -> AM () deleteRcvQueueAsync c rq@RcvQueue {connId, server, rcvId} = do diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 7e203cf9f..e8451267e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -698,6 +698,8 @@ functionalAPITests ps = do #endif it "should delete connections after connection lock is released" $ testDeleteConnectionsAfterConnLock + it "should acknowledge message twice while the server does not respond" $ + testAckMessageTwiceStallingServer ps describe "Delivery receipts" $ do it "should send and receive delivery receipt" $ withSmpServer ps testDeliveryReceipts it "should deliver receipt again after client restart without acknowledgement" $ testDuplicateReceipt ps False False @@ -5037,6 +5039,35 @@ testDeleteConnectionsAfterConnLock = atomically $ putTMVar unlocked () timeout 5_000000 (wait deleted) `shouldReturn` Just (Right ()) +testAckMessageTwiceStallingServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testAckMessageTwiceStallingServer ps@(t, _) = + withSmpServer ps $ + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> do + (aId, msgId) <- withPausedProxyOn testPort2 testPort3 $ \_ resume -> do + atomically $ putTMVar resume () + withAgent 1 agentCfg initAgentServers testDB $ \a -> + withAgent 2 agentCfg bServers testDB2 $ \b -> runRight $ do + (aId, bId) <- makeConnection a b + sentId <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT sentId) + ("", _, Msg' msgId _ "hello") <- get b + pure (aId, msgId) + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> + withAgent 2 agentCfg bServers testDB2 $ \b -> do + let ack = runExceptT $ ackMessage b aId msgId Nothing + userAcked = withTransaction (store $ agentEnv b) (`DB.query_` "SELECT conn_id, internal_id FROM rcv_messages WHERE user_ack = 1") + waitUserAck = userAcked >>= \(msgs :: [(ConnId, Int64)]) -> when (null msgs) $ threadDelay 10000 >> waitUserAck + withAsync ack $ \ack1 -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + withTransaction (store $ agentEnv b) (`DB.execute_` "UPDATE rcv_messages SET user_ack = 0") + withAsync ack $ \ack2 -> do + timeout 5_000000 waitUserAck `shouldReturn` Just () + atomically $ putTMVar resume () + timeout 5_000000 (wait ack1) `shouldReturn` Just (Right ()) + timeout 5_000000 (wait ack2) `shouldReturn` Just (Right ()) + where + bServers = initAgentServersLongConnect {smp = userServers [testSMPServer2]} + testDeliveryReceipts :: (HasCallStack, HasTestEnv) => IO () testDeliveryReceipts = withAgentClients2 $ \a b -> runRight_ $ do From 158f5664bd065ce58b09174f83efea8d6abaf601 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:40:16 +0000 Subject: [PATCH 15/44] agent: record or delete a created queue in one helper --- src/Simplex/Messaging/Agent.hs | 51 ++++++++++++++++------------------ 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 72cf03769..efcb847e4 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1188,14 +1188,16 @@ 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 - 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 + rq' <- recordNewQueue c nm connId "createRcvQueue" tSess rq (withStore c $ \db -> updateNewConnRcv db connId rq subMode) $ \rq' -> + rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure (rq', qUri) +recordNewQueue :: AgentClient -> NetworkRequestMode -> ConnId -> Text -> SMPTransportSession -> NewRcvQueue -> AM r -> (r -> AM a) -> AM a +recordNewQueue c nm connId name tSess q record continue = do + recorded <- withConnLock c connId name $ tryAllErrors record >>= mapM continue + either (\e -> tryAllErrors (deleteNewQueue c nm tSess q) >> throwE e) pure recorded + checkClientNotices :: AgentClient -> SMPServerWithAuth -> AM () checkClientNotices AgentClient {clientNotices, presetServers} (ProtoServerWithAuth srv@(ProtocolServer {host}) _) = do notices <- readTVarIO clientNotices @@ -1735,11 +1737,8 @@ 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 - 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 + rq' <- recordNewQueue c nm connId "createReplyQueue" tSess rq (withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode) $ \rq' -> + rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure qInfo @@ -2978,23 +2977,21 @@ switchDuplexConnection c nm cmdId_ (DuplexConnection ConnData {connId, userId} r -- 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} - 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 + addRcvQueue = + 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" + recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(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' abortConnectionSwitch' :: AgentClient -> ConnId -> AM ConnectionStats abortConnectionSwitch' c connId = From de6838274c1d13b093b867e6350597e7d3c12541 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:43:40 +0000 Subject: [PATCH 16/44] agent: abort the earlier switch when a switch is aborted and restarted --- src/Simplex/Messaging/Agent.hs | 40 +++++++++++++++++--------- src/Simplex/Messaging/Agent/Client.hs | 4 +++ tests/AgentTests/FunctionalAPITests.hs | 22 ++++++++++++++ 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index efcb847e4..4bd876926 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -199,6 +199,7 @@ import qualified Data.Text as T import Data.Time.Clock import Data.Time.Clock.System (systemToUTCTime) import Data.Traversable (mapAccumL) +import Data.Unique (Unique, newUnique) import Data.Word (Word16, Word32) import Simplex.FileTransfer.Agent (closeXFTPAgent, deleteSndFileInternal, deleteSndFileRemote, deleteSndFilesInternal, deleteSndFilesRemote, startXFTPSndWorkers, startXFTPWorkers, toFSFilePath, xftpDeleteRcvFile', xftpDeleteRcvFiles', xftpPrepareReceiveFile', xftpPrepareSendDescription', xftpPrepareSendFile', xftpReceiveFile', xftpSendDescription', xftpSendFile', xftpStartReceiveFile', xftpStartSendFile') import Simplex.FileTransfer.Description (ValidFileDescription) @@ -2320,19 +2321,20 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do 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 -> - 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" + noServer . tryAtomicCommand $ do + (conn, replaced, switchId) <- withConnLock c connId "switchConnection" startSwitch + switchDuplexConnection c NRMBackground (Just cmdId) switchId conn replaced `allFinally` endRcvSwitch c connId switchId + >>= notify . SWITCH QDRcv SPStarted where - getConnToSwitch = + startSwitch :: AM (Connection 'CDuplex, RcvQueue, Unique) + startSwitch = withStore c (`getConn` connId) >>= \case - SomeConn _ (DuplexConnection cData (rq :| _) _) + SomeConn _ conn@(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 + | otherwise -> (conn,rq,) <$> newRcvSwitch c connId + _ -> throwE $ CMD PROHIBITED "SWCH: not duplex" DEL -> withServer' . tryAtomicCommand $ deleteConnection' c NRMBackground connId >> notify OK AInternalCommand cmd -> case cmd of ICAckDel rId srvMsgId msgId -> withServer $ \srv -> @@ -2955,19 +2957,27 @@ getConnectionQueueInfo' c nm connId = do switchConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM ConnectionStats switchConnection' c nm connId = do - (cData, rqs, sqs, rq') <- withConnLock c connId "switchConnection" $ + (cData, rqs, sqs, rq', switchId) <- withConnLock c connId "switchConnection" $ withStore c (`getConn` connId) >>= \case 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 - pure (cData, rqs, sqs, rq') + (cData, rqs, sqs, rq',) <$> newRcvSwitch c connId _ -> throwE $ CMD PROHIBITED "switchConnection: not duplex" - switchDuplexConnection c nm Nothing (DuplexConnection cData rqs sqs) rq' + switchDuplexConnection c nm Nothing switchId (DuplexConnection cData rqs sqs) rq' `allFinally` endRcvSwitch c connId switchId -switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats -switchDuplexConnection c nm cmdId_ (DuplexConnection ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do +newRcvSwitch :: AgentClient -> ConnId -> AM Unique +newRcvSwitch c connId = do + switchId <- liftIO newUnique + switchId <$ atomically (TM.insert connId switchId $ rcvSwitches c) + +endRcvSwitch :: AgentClient -> ConnId -> Unique -> AM () +endRcvSwitch c connId switchId = atomically $ TM.alter (mfilter (/= switchId)) connId $ rcvSwitches c + +switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Unique -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats +switchDuplexConnection c nm cmdId_ switchId (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 @@ -2983,7 +2993,8 @@ switchDuplexConnection c nm cmdId_ (DuplexConnection ConnData {connId, userId} r (cData,rqs',sqs',rq1,) <$> withStore c (\db -> addConnRcvQueue db connId rq' SMSubscribe) _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do - when (rcvSwchStatus rq1 /= Just RSSwitchStarted) $ deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: aborted") + started <- (Just switchId ==) <$> liftIO (TM.lookupIO connId $ rcvSwitches c) + when (rcvSwchStatus rq1 /= Just RSSwitchStarted || not started) $ 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") @@ -3008,6 +3019,7 @@ abortConnectionSwitch' c connId = rq' <- withStore' c $ \db -> do mapM_ (setRcvQueueDeleted db) delRqs setRcvSwitchStatus db rq Nothing + atomically $ TM.delete connId $ rcvSwitches c forM_ delRqs $ \RcvQueue {server, rcvId} -> enqueueCommand c "" connId (Just server) $ AInternalCommand $ ICDeleteRcvQueue rcvId let rqs'' = updatedQs rq' rqs' conn' = DuplexConnection cData rqs'' sqs diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index a5779ff0b..b3b3b8a56 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -234,6 +234,7 @@ import Data.Text (Text) import Data.Text.Encoding import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) +import Data.Unique (Unique) import Data.Word (Word16, Word32) import qualified Data.X509.Validation as XV import Network.Socket (HostName) @@ -406,6 +407,7 @@ data AgentClient = AgentClient agentEnv :: Env, proxySessTs :: TVar UTCTime, serviceRequests :: TMap ConnId (TMVar (Either AgentErrorType SMP.MsgBody)), + rcvSwitches :: TMap ConnId Unique, smpServersStats :: TMap (UserId, SMPServer) AgentSMPServerStats, xftpServersStats :: TMap (UserId, XFTPServer) AgentXFTPServerStats, ntfServersStats :: TMap (UserId, NtfServer) AgentNtfServerStats, @@ -574,6 +576,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf deleteLock <- createLockIO smpSubWorkers <- TM.emptyIO serviceRequests <- TM.emptyIO + rcvSwitches <- TM.emptyIO smpServersStats <- TM.emptyIO xftpServersStats <- TM.emptyIO ntfServersStats <- TM.emptyIO @@ -627,6 +630,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentEnv, proxySessTs, serviceRequests, + rcvSwitches, smpServersStats, xftpServersStats, ntfServersStats, diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index e8451267e..abd0810d1 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -634,6 +634,8 @@ functionalAPITests ps = do 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 delete the new queue when the switch is aborted and started again while the queue is created" $ + testSwitchRestartedWhileNewQueue 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" $ @@ -4458,6 +4460,26 @@ testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testSwitchRestartedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchRestartedWhileNewQueue 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 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ abortConnectionSwitch b aId + setUserNetworkInfo b $ UserNetworkInfo UNNone False + void . runRight $ switchConnectionAsync b "" aId + atomically $ putTMVar resume () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED "switchConnection: aborted") + setUserNetworkInfo b $ UserNetworkInfo UNWifi True + get b =##> \case ("", c, SWITCH QDRcv SPStarted _) -> c == aId; _ -> False + waitRcvQueueRecords b 2 + storeLogQueues testStoreLogFile2 `shouldReturn` (2, 1) + testJoinConnectionDeletedWhileReplyQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testJoinConnectionDeletedWhileReplyQueue ps@(t, _) = withSmpServer ps $ From 8d86e1956ca67f9869d352e5f632c649722fe32a Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:45:53 +0000 Subject: [PATCH 17/44] agent: prevent waits for the notification command queue in deletion --- src/Simplex/Messaging/Agent.hs | 2 +- tests/AgentTests/FunctionalAPITests.hs | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 4bd876926..0ae23c828 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3154,7 +3154,7 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do unsubNtfConnIds :: NonEmpty ConnId -> AM' () unsubNtfConnIds connIds' = do ns <- asks ntfSupervisor - atomically $ writeTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds') + liftIO $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds') notify = liftIO . nonBlockingWriteTBQueue (subQ c) deleteConnQueues :: AgentClient -> NetworkRequestMode -> Bool -> Bool -> [RcvQueue] -> AM' (Map ConnId (Either AgentErrorType ())) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index abd0810d1..9742c7d56 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -97,7 +97,7 @@ import SMPClient import Simplex.Messaging.Agent hiding (acceptContact, createConnection, deleteConnection, deleteConnections, getConnShortLink, joinConnection, sendMessage, setConnShortLink, subscribeConnection, suspendConnection) import qualified Simplex.Messaging.Agent as A import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), UserNetworkInfo (..), UserNetworkType (..), sendAgentMessage, waitForUserNetwork) -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), Env (..), InitialAgentServers (..), createAgentStore) +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), Env (..), InitialAgentServers (..), NtfSupervisor (..), NtfSupervisorCommand (..), createAgentStore) import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, REQ, SENT) import qualified Simplex.Messaging.Agent.Protocol as A import Simplex.Messaging.Agent.Store (Connection' (..), SomeConn' (..), StoredRcvQueue (..), StoredSndQueue (..)) @@ -583,6 +583,8 @@ functionalAPITests ps = do testDeleteConnectionAsync ps it "should delete connection without receive queue when event queue is full" $ testDeleteConnectionAsyncFullQueue + it "should delete connection when notification command queue is full" $ + testDeleteConnectionFullNtfQueue ps it "join connection when reply queue creation fails" $ testJoinConnectionAsyncReplyError ps describe "delete connection waiting for delivery" $ do @@ -3948,6 +3950,23 @@ testDeleteConnectionAsyncFullQueue = void . atomically . flushTBQueue $ subQ a get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False +testDeleteConnectionFullNtfQueue :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () +testDeleteConnectionFullNtfQueue ps = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + (connId, _) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe + let q = ntfSubQ $ ntfSupervisor $ agentEnv a + setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} + fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill + setNtfSuspended True + atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) + atomically $ isEmptyTBQueue q >>= checkSTM + atomically fill + timeout 5_000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) + setNtfSuspended False + get a =##> \case ("", "", DEL_RCVQS [(c, _, _, Nothing)]) -> c == connId; _ -> False + get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False + fillSubQ :: AgentClient -> IO () fillSubQ c = atomically fill where From 99cb1c6d29b53c6400b65fe2cbb13f2b62070026 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:46:14 +0000 Subject: [PATCH 18/44] clients: assign the creation time of a request once --- src/Simplex/Messaging/Client.hs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 6ad316db4..a743c1b30 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1392,15 +1392,14 @@ 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 = do - ts <- getCurrentTime +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = -- two separate "atomically" needed to avoid blocking E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ (addRequest ts) rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) + (atomically $ ifM (readTVar connected) (mapM_ addRequest 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 + addRequest r@Request {corrId} = TM.insert corrId r sentCommands removeRequest Request {corrId} = TM.delete corrId sentCommands failRequest :: Request err msg -> STM () From 33c9bbf9c44912708c9ebf193773e76f32e20171 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:46:56 +0000 Subject: [PATCH 19/44] agent: write DEL_USER and DEL_CONNS with the event helpers --- src/Simplex/Messaging/Agent.hs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 0ae23c828..b45438550 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -933,8 +933,8 @@ deleteUser' c@AgentClient {smpServersStats, xftpServersStats} userId delSMPQueue lift $ saveServersStats c where delUser = - whenM (withStore' c (`deleteUserWithoutConns` userId)) . liftIO $ - nonBlockingWriteTBQueue (subQ c) ("", "", AEvt SAENone $ DEL_USER userId) + whenM (withStore' c (`deleteUserWithoutConns` userId)) $ + notifySub c $ DEL_USER userId setUserService' :: AgentClient -> UserId -> Bool -> AM () setUserService' c userId enable = do @@ -3139,7 +3139,7 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do -- ! between completed deletions of connections, and deletions delayed due to wait for delivery (see deleteConn) deliveryTimeout <- if waitDelivery then asks (Just . connDeleteDeliveryTimeout . config) else pure Nothing cIds_ <- lift $ L.nonEmpty . catMaybes . rights <$> withStoreBatch' c (\db -> map (deleteConn db deliveryTimeout) (M.keys delRs)) - forM_ cIds_ $ \cIds -> notify ("", "", AEvt SAEConn $ DEL_CONNS cIds) + forM_ cIds_ $ notifySub' c "" . DEL_CONNS pure res where partitionResultsConns :: @@ -3155,7 +3155,6 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do unsubNtfConnIds connIds' = do ns <- asks ntfSupervisor liftIO $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds') - notify = liftIO . nonBlockingWriteTBQueue (subQ c) deleteConnQueues :: AgentClient -> NetworkRequestMode -> Bool -> Bool -> [RcvQueue] -> AM' (Map ConnId (Either AgentErrorType ())) deleteConnQueues c nm waitDelivery ntf rqs = do From 4b38ccad8b6afd596df4e6391e547aa7e6aa219e Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:24:24 +0000 Subject: [PATCH 20/44] docs: state that a new switch start replaces the switch identifier --- plans/2026-11-21-agent-no-blocking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index ec6bc5da3..7f82e6489 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -55,7 +55,7 @@ sequenceDiagram - deletion under the locks of its connections; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; - - each switch start has an identifier; an abort removes it, and the switch whose identifier was removed is aborted after its queue is created; + - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created; - the receive queue status is set to Secured under the lock, only from Confirmed; - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. From 128d8561e4a4b17a4aa28e7d3306426a7e7d8ce7 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:44:15 +0000 Subject: [PATCH 21/44] agent: delete the new queue when deletion waits for delivery --- .../Messaging/Agent/Store/AgentStore.hs | 10 ++++++--- tests/AgentTests/FunctionalAPITests.hs | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 41685f2e2..6108adecd 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -2756,11 +2756,15 @@ getConnData deleted' forUpdate db connId' = FROM connections WHERE conn_id = ? AND deleted = ? |] -#if defined(dbPostgres) - <> (if forUpdate then " FOR UPDATE" else "") -#endif + <> (if forUpdate then forUpdateClause else "") ) (connId', BI deleted') + where + forUpdateClause = + " AND deleted_at_wait_delivery IS NULL" +#if defined(dbPostgres) + <> " FOR UPDATE" +#endif lockConnForUpdate :: DB.Connection -> ConnId -> IO () lockConnForUpdate db connId = do diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 9742c7d56..e56216315 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -98,6 +98,7 @@ import Simplex.Messaging.Agent hiding (acceptContact, createConnection, deleteCo import qualified Simplex.Messaging.Agent as A import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), UserNetworkInfo (..), UserNetworkType (..), sendAgentMessage, waitForUserNetwork) import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), Env (..), InitialAgentServers (..), NtfSupervisor (..), NtfSupervisorCommand (..), createAgentStore) +import Simplex.Messaging.Agent.Lock (withLock') import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, REQ, SENT) import qualified Simplex.Messaging.Agent.Protocol as A import Simplex.Messaging.Agent.Store (Connection' (..), SomeConn' (..), StoredRcvQueue (..), StoredSndQueue (..)) @@ -636,6 +637,8 @@ functionalAPITests ps = do 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 delete the new queue when the connection is deleted waiting for delivery while the queue is created" $ + testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps it "should delete the new queue when the switch is aborted and started again while the queue is created" $ testSwitchRestartedWhileNewQueue ps it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ @@ -4479,6 +4482,24 @@ testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue 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 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + withLock' (deleteLock b) "test" $ do + runRight_ $ deleteConnectionAsync b True aId + atomically $ putTMVar resume () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + get b =##> \case ("", "", DEL_RCVQS [(c, _, _, Nothing)]) -> c == aId; _ -> False + get b =##> \case ("", "", DEL_CONNS [c]) -> c == aId; _ -> False + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + testSwitchRestartedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchRestartedWhileNewQueue ps@(t, _) = withSmpServer ps $ From d44ca7385cacd19419c110192242086937456cf5 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:44:21 +0000 Subject: [PATCH 22/44] agent: read the connection once in each step of acknowledgement --- src/Simplex/Messaging/Agent.hs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index b45438550..8c10457d9 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2903,29 +2903,27 @@ requestAndCommit c connId name validate request commit = ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM (Maybe ATransmission) ackMessage' c cmdId_ connId msgId rcptInfo_ = - join <$> requestAndCommit c connId "ackMessage" markConnUserAck (uncurry $ ackQueueMessage c) recordAck + join <$> requestAndCommit c connId "ackMessage" markConnUserAck (\(_, rq, srvMsgId) -> ackQueueMessage c rq srvMsgId) recordAck where - recordAck :: Bool -> (RcvQueue, SMP.MsgId) -> AM (Maybe ATransmission) - recordAck drained (rq, srvMsgId) = do + recordAck :: Bool -> (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId) -> AM (Maybe ATransmission) + recordAck drained (duplexConn_, rq, srvMsgId) = do t_ <- recordQueueAck c rq srvMsgId drained - withStore c (`getConn` connId) >>= \case - SomeConn _ conn@DuplexConnection {} -> sendRcpt conn - _ -> pure () + mapM_ sendRcpt duplexConn_ t_ <$ del - markConnUserAck :: AM (Maybe (RcvQueue, SMP.MsgId)) + markConnUserAck :: AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) markConnUserAck = do SomeConn _ conn <- withStore c (`getConn` connId) case conn of - DuplexConnection {} -> markUserAck - RcvConnection {} -> markUserAck + DuplexConnection {} -> markUserAck $ Just conn + RcvConnection {} -> markUserAck Nothing 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 = + markUserAck :: Maybe (Connection 'CDuplex) -> AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) + markUserAck duplexConn_ = withStore' c (\db -> setMsgUserAck db connId $ InternalId msgId) >>= \case - Right r -> pure $ Just r + Right (rq, srvMsgId) -> pure $ Just (duplexConn_, rq, srvMsgId) Left (SEMsgNotFound _) -> Nothing <$ del Left e -> throwE $ storeError e del :: AM () From 81dfcddcf63856d3486a6158922e64a1f5b00c2a Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:44:25 +0000 Subject: [PATCH 23/44] docs: add the deletion rule, state that commands are not queued late --- plans/2026-11-21-agent-no-blocking.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 7f82e6489..2b8b0fb2e 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -53,6 +53,7 @@ sequenceDiagram - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - deletion under the locks of its connections; + - a connection whose deletion waits for delivery is not given new queues; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created; @@ -65,6 +66,6 @@ sequenceDiagram - the notification command of connection deletion. - clients: - a message in the response to ACK, SUB or GET is written to msgQ without waiting; - - a command waits for send-queue space only until its response timeout, and is not sent after it ends; + - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. - moved to separate pull requests: the HTTP/2 request timeout, the SUSPENDED event written without waiting. From 8aa2ed0d9b83019f6cb71e2203afb76bf5c585af Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:01:59 +0000 Subject: [PATCH 24/44] agent: prevent repeated processing of switch commands in ratchet sync --- src/Simplex/Messaging/Agent.hs | 8 ++-- .../Messaging/Agent/Store/AgentStore.hs | 13 ++++++ tests/AgentTests/FunctionalAPITests.hs | 40 +++++++++++++++++++ 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 8c10457d9..1a1158b56 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2410,7 +2410,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do case find ((replaceQId ==) . dbQId) rqs of Just rq1 | status /= Confirmed -> Nothing <$ withStore' c (`deleteCommand` cmdId) - | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand srv | otherwise -> pure $ Just (cData, rqs, sqs, rq', rq1) _ -> Nothing <$ internalErr "ICQSecure: no switching queue found" _ -> Nothing <$ internalErr "ICQSecure: queue address not found in connection" @@ -2440,7 +2440,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do case findQ (srv, sId) sqs of Nothing -> Nothing <$ internalErr "ICQSndSecure: queue address not found in connection" Just sq'@SndQueue {dbReplaceQueueId} - | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand srv | otherwise -> case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of Just oldSq -> pure $ Just (cData, rqs, sqs, sq', oldSq) Nothing -> do @@ -2522,11 +2522,11 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do Right CCDeleted -> pure () internalErr s = cmdError $ INTERNAL $ s <> ": " <> show (agentCommandTag command) cmdError e = notify (ERR e) >> withStore' c (`deleteCommand` cmdId) - postponeCommand = do + postponeCommand srv = 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 <- liftIO $ hasNonQSecureCommand db connId srv pending <$ ExceptT (createCommand db corrId connId server_ command) when otherCmds . atomically $ hasWorkToDo' doWork notify :: forall e. AEntityI e => AEvent e -> AM () diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 6108adecd..8702667b7 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -177,6 +177,7 @@ module Simplex.Messaging.Agent.Store.AgentStore getPendingCommandServers, getAllPendingCommandConns, getPendingServerCommand, + hasNonQSecureCommand, updateCommandServer, deleteCommand, -- Notification device token persistence @@ -1746,6 +1747,18 @@ getPendingServerCommand db connId srv_ = getWorkItem "command" getCmdId getComma pendingCommand (corrId, userId, command, createdAt) = PendingCommand {cmdId, corrId, userId, connId, command, createdAt} markCommandFailed cmdId = DB.execute db "UPDATE commands SET failed = 1 WHERE command_id = ?" (Only cmdId) +hasNonQSecureCommand :: DB.Connection -> ConnId -> SMPServer -> IO Bool +hasNonQSecureCommand db connId (SMPServer host port _) = + maybeFirstRow' False fromOnlyBI $ + DB.query + db + [sql| + SELECT 1 FROM commands + WHERE conn_id = ? AND host = ? AND port = ? AND failed = 0 AND command_tag NOT IN (?,?) + LIMIT 1 + |] + (connId, host, port, AInternalCommandTag ICQSecure_, AInternalCommandTag ICQSndSecure_) + updateCommandServer :: DB.Connection -> AsyncCmdId -> SMPServer -> IO (Either StoreError ()) updateCommandServer db cmdId srv@(SMPServer host port _) = runExceptT $ do serverKeyHash_ <- ExceptT $ getServerKeyHash_ db srv diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index e56216315..6586d20cd 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -645,6 +645,8 @@ functionalAPITests ps = do testSwitchRatchetSyncBeforeNewQueue ps it "should secure the new queue and complete the switch after ratchet synchronization" $ testFastSwitchRatchetSyncWhileSecuring ps + it "should wait for ratchet synchronization with the switch commands of both directions on one server" $ + testSwitchBothDirectionsRatchetSync ps describe "should switch delivery to the new queue" $ testServerMatrix2 ps testSwitchConnection describe "should switch to new queue asynchronously" $ @@ -4594,6 +4596,44 @@ 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 ()) +testSwitchBothDirectionsRatchetSync :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchBothDirectionsRatchetSync ps@(t, ASType qsType _) = withSmpServer ps $ do + a <- getSMPAgentClient' 1 agentCfgV7 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] + nGet a =##> \case ("", "", DOWN _ cs) -> bId `elem` cs; _ -> False + b <- getSMPAgentClient' 3 agentCfg initAgentServers testDB2 + runRight_ $ do + subscribeConnection b aId + phaseSnd b aId SPStarted [Just SSSendingQKEY, Nothing] + phaseRcv a bId SPConfirmed [Just RSSendingQADD, Nothing] + disposeAgentClient a + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do + _ <- switchConnectionAsync b "" aId + phaseRcv b aId SPStarted [Just RSSendingQADD, Nothing] + withAgent 4 agentCfg initAgentServers testDB $ \a' -> do + runRight_ $ do + subscribeConnection a' bId + phaseSnd a' bId SPStarted [Just SSSecuringQueue, Nothing] + disposeAgentClient b + cmdIds <- srv2CommandIds a' + length cmdIds `shouldBe` 2 + void . runRight $ synchronizeRatchet a' bId PQSupportOn True + cmdIds' <- waitCommandIdsChange a' cmdIds (100 :: Int) + cmdIds' `shouldNotBe` cmdIds + threadDelay 1000000 + srv2CommandIds a' `shouldReturn` cmdIds' + where + srv2CommandIds :: AgentClient -> IO [Int64] + srv2CommandIds c = map snd . filter ((Just testPort2 ==) . fst) <$> withTransaction (store $ agentEnv c) (`DB.query_` "SELECT port, command_id FROM commands ORDER BY command_id") + waitCommandIdsChange c cmdIds n = do + cmdIds' <- srv2CommandIds c + if cmdIds' /= cmdIds || n == 0 then pure cmdIds' else threadDelay 100000 >> waitCommandIdsChange c cmdIds (n - 1) + endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b From 1efa2fbf69889725b8a865dfefa4850e0a90ed04 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:02:03 +0000 Subject: [PATCH 25/44] docs: state that postponed switch commands follow other commands --- plans/2026-11-21-agent-no-blocking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 2b8b0fb2e..8c4090f23 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -58,7 +58,7 @@ sequenceDiagram - a concurrent acknowledgement of a deleted message is dropped; - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created; - the receive queue status is set to Secured under the lock, only from Confirmed; - - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, resumed after synchronization; + - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. - agent, events written without waiting: - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; From cd3f7a70445c2ddf8503e141afecf806814b1f34 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:20:46 +0000 Subject: [PATCH 26/44] tests: read the QKEY delivery event in the two-way switch test --- tests/AgentTests/FunctionalAPITests.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 6586d20cd..2508007ed 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -4609,6 +4609,7 @@ testSwitchBothDirectionsRatchetSync ps@(t, ASType qsType _) = withSmpServer ps $ runRight_ $ do subscribeConnection b aId phaseSnd b aId SPStarted [Just SSSendingQKEY, Nothing] + phaseSnd b aId SPConfirmed [Just SSSendingQKEY, Nothing] phaseRcv a bId SPConfirmed [Just RSSendingQADD, Nothing] disposeAgentClient a setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] From 9a33fd44b0d6091fbb8cf08316b9ee30f1183568 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:51:10 +0000 Subject: [PATCH 27/44] agent: prevent a switch queue left on the server by synchronous deletion --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 7 ++++--- tests/AgentTests/FunctionalAPITests.hs | 25 +++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 8c4090f23..14bdd30c7 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -52,7 +52,7 @@ sequenceDiagram - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - - deletion under the locks of its connections; + - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - a connection whose deletion waits for delivery is not given new queues; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 1a1158b56..7ce983db8 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3093,7 +3093,6 @@ suspendConnection' c nm connId = do 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 -- currently it is used only in tests deleteConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM () deleteConnection' c nm connId = toConnResult connId =<< deleteConnections' c nm [connId] @@ -3107,7 +3106,6 @@ connRcvQueues = \case SndConnection _ _ -> [] NewConnection _ -> [] --- Unlike deleteConnectionsAsync, this function does not mark connections as deleted in case of deletion failure. deleteConnections' :: AgentClient -> NetworkRequestMode -> [ConnId] -> AM (Map ConnId (Either AgentErrorType ())) deleteConnections' = deleteConnections_ getConns False False {-# INLINE deleteConnections' #-} @@ -3212,7 +3210,10 @@ deleteConnections_ :: AM (Map ConnId (Either AgentErrorType ())) deleteConnections_ _ _ _ _ _ [] = pure M.empty deleteConnections_ getConnections ntf waitDelivery c nm connIds = do - (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ prepareDeleteConnections_ getConnections c waitDelivery connIds + (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ do + r@(_, _, connIds') <- prepareDeleteConnections_ getConnections c waitDelivery connIds + unless waitDelivery . withStore' c $ \db -> forM_ connIds' $ setConnDeleted db False + pure r rcvRs <- lift $ deleteConnQueues c nm waitDelivery ntf rqs let rs' = M.union rs rcvRs notifyResultError rs' diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 2508007ed..5e9c8920d 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -639,6 +639,8 @@ functionalAPITests ps = do testSwitchConnectionDeletedWhileNewQueue ps it "should delete the new queue when the connection is deleted waiting for delivery while the queue is created" $ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps + it "should delete the new queue when it is recorded while the connection deletion waits for the server" $ + testSwitchNewQueueRecordedWhileDeleting ps it "should delete the new queue when the switch is aborted and started again while the queue is created" $ testSwitchRestartedWhileNewQueue ps it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ @@ -4502,6 +4504,29 @@ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps@(t, _) = get b =##> \case ("", "", DEL_CONNS [c]) -> c == aId; _ -> False storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testSwitchNewQueueRecordedWhileDeleting :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchNewQueueRecordedWhileDeleting (t, _) = do + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> do + aId <- withPausedProxyOn testPort testPort3 $ \_ resume -> do + atomically $ putTMVar resume () + withAgent 1 agentCfg oldServers testDB $ \a -> + withAgent 2 agentCfg oldServers testDB2 $ \b -> runRight $ fst <$> makeConnection a b + withPausedProxyOn testPort testPort3 $ \deleting resumeDelete -> + withPausedProxyOn testPort2 testPort3 $ \creating resumeCreate -> + withAgent 2 agentCfg newServers testDB2 $ \b -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar creating) `shouldReturn` Just () + withAsync (runExceptT $ deleteConnection b aId) $ \deleted -> do + timeout 5_000000 (atomically $ takeTMVar deleting) `shouldReturn` Just () + atomically $ putTMVar resumeCreate () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + atomically $ putTMVar resumeDelete () + timeout 5_000000 (wait deleted) `shouldReturn` Just (Right ()) + storeLogQueues testStoreLogFile2 `shouldReturn` (3, 2) + where + oldServers = initAgentServersLongConnect {smp = userServers [SMPServer testHost2 testPort testKeyHash]} + newServers = initAgentServersLongConnect {smp = userServers [testSMPServer2]} + testSwitchRestartedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchRestartedWhileNewQueue ps@(t, _) = withSmpServer ps $ From f620a6be8d16b1a05010062718fe5b113fb388c0 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:53:19 +0000 Subject: [PATCH 28/44] agent: prevent waits for the notification command queue in a switch --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 4 ++-- tests/AgentTests/NotificationTests.hs | 34 +++++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 14bdd30c7..ed1ec5431 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -63,7 +63,7 @@ sequenceDiagram - agent, events written without waiting: - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - - the notification command of connection deletion. + - the notification commands of connection deletion, ICQDelete and QEND. - clients: - a message in the response to ACK, SUB or GET is written to msgQ without waiting; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 7ce983db8..4716bd753 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2453,7 +2453,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId when enableNtfs $ do ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) let conn' = DuplexConnection cData rqs sqs cStats <- connectionStats c conn' notify $ SWITCH QDRcv SPCompleted cStats @@ -4306,7 +4306,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr unless completed $ do when enableNtfs $ do ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) let conn' = DuplexConnection cData' (keptRq :| keptRqs) sqs cStats <- connectionStats c conn' notify $ SWITCH QDRcv SPCompleted cStats diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index accf6723f..c4bd529b7 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -66,8 +66,8 @@ import SMPAgentClient (agentCfg, initAgentServers, initAgentServers2, testDB, te import SMPClient import Simplex.Messaging.Agent hiding (checkNtfToken, createConnection, joinConnection, registerNtfToken, sendMessage, verifyNtfToken) import qualified Simplex.Messaging.Agent as A -import Simplex.Messaging.Agent.Client (ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers) +import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers, NtfSupervisor (..), NtfSupervisorCommand (..)) import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, SENT) import Simplex.Messaging.Agent.Store.AgentStore (getSavedNtfToken) import Simplex.Messaging.Agent.Store.Common (withTransaction) @@ -89,6 +89,7 @@ import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo (QueueInfo (..)) import Simplex.Messaging.Transport (ASrvTransport) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) +import Simplex.Messaging.Util (unlessM) import System.Process (callCommand) import Test.Hspec hiding (fit, it) import UnliftIO @@ -177,6 +178,15 @@ notificationTests ps@(t, _) = do testServerMatrix2 ps $ \servers -> withAPNSMockServer $ \apns -> withNtfServer t $ testSwitchNotifications agentCfg fastSwitchComplete servers apns + describe "should complete switch when notification command queue is full" $ do + it "slow rotation" $ + withSmpServer ps $ + withAPNSMockServer $ \apns -> + withNtfServer t $ testSwitchFullNtfQueue agentCfgV7 switchComplete apns + it "fast rotation" $ + withSmpServer ps $ + withAPNSMockServer $ \apns -> + withNtfServer t $ testSwitchFullNtfQueue agentCfg fastSwitchComplete apns it "should keep sending notifications for old token" $ withSmpServer ps $ withAPNSMockServer $ \apns -> @@ -903,6 +913,26 @@ testSwitchNotifications cfg completeSwitch servers apns = liftIO $ threadDelay 500000 testMessage "hello again" +testSwitchFullNtfQueue :: HasTestEnv => AgentConfig -> (AgentClient -> ByteString -> AgentClient -> ByteString -> ExceptT AgentErrorType IO ()) -> APNSMockServer -> IO () +testSwitchFullNtfQueue cfg completeSwitch apns = + withAgentClientsCfg2 cfg cfg $ \a b -> do + (aId, bId) <- runRight $ do + (aId, bId) <- makeConnection a b + exchangeGreetings a bId b aId + _ <- registerTestToken a "abcd" NMInstant apns + pure (aId, bId) + let q = ntfSubQ $ ntfSupervisor $ agentEnv a + setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} + fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill + setNtfSuspended True + atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) + atomically $ isEmptyTBQueue q >>= checkSTM + atomically fill + runRight_ $ do + _ <- switchConnectionAsync a "" bId + completeSwitch a bId b aId + setNtfSuspended False + testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () testNotificationsOldToken apns = withAgentClients3 $ \a b c -> runRight_ $ do From de119c4032c5abc26081e0b59c49d43d1438971c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:55:33 +0000 Subject: [PATCH 29/44] agent: prevent an error event when an asynchronous switch is aborted --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 25 ++++++++++++++----------- tests/AgentTests/FunctionalAPITests.hs | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index ed1ec5431..1745da525 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -56,7 +56,7 @@ sequenceDiagram - a connection whose deletion waits for delivery is not given new queues; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; - - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created; + - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created, without an event from an asynchronous switch; - the receive queue status is set to Secured under the lock, only from Confirmed; - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 4716bd753..c25dd7121 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2324,7 +2324,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do noServer . tryAtomicCommand $ do (conn, replaced, switchId) <- withConnLock c connId "switchConnection" startSwitch switchDuplexConnection c NRMBackground (Just cmdId) switchId conn replaced `allFinally` endRcvSwitch c connId switchId - >>= notify . SWITCH QDRcv SPStarted + >>= maybe (withStore' c (`deleteCommand` cmdId)) (notify . SWITCH QDRcv SPStarted) where startSwitch :: AM (Connection 'CDuplex, RcvQueue, Unique) startSwitch = @@ -2965,6 +2965,7 @@ switchConnection' c nm connId = do (cData, rqs, sqs, rq',) <$> newRcvSwitch c connId _ -> throwE $ CMD PROHIBITED "switchConnection: not duplex" switchDuplexConnection c nm Nothing switchId (DuplexConnection cData rqs sqs) rq' `allFinally` endRcvSwitch c connId switchId + >>= maybe (throwE $ CMD PROHIBITED "switchConnection: aborted") pure newRcvSwitch :: AgentClient -> ConnId -> AM Unique newRcvSwitch c connId = do @@ -2974,7 +2975,7 @@ newRcvSwitch c connId = do endRcvSwitch :: AgentClient -> ConnId -> Unique -> AM () endRcvSwitch c connId switchId = atomically $ TM.alter (mfilter (/= switchId)) connId $ rcvSwitches c -switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Unique -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats +switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Unique -> Connection 'CDuplex -> RcvQueue -> AM (Maybe ConnectionStats) switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do checkRQSwchStatus rq RSSwitchStarted clientVRange <- asks $ smpClientVRange . config @@ -2992,15 +2993,17 @@ switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do started <- (Just switchId ==) <$> liftIO (TM.lookupIO connId $ rcvSwitches c) - when (rcvSwchStatus rq1 /= Just RSSwitchStarted || not started) $ 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' + if rcvSwchStatus rq1 /= Just RSSwitchStarted || not started + then Nothing <$ deleteRcvQueueAsync c rq'' + else do + 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''] + Just <$> connectionStats c (DuplexConnection cData rqs'' sqs') abortConnectionSwitch' :: AgentClient -> ConnId -> AM ConnectionStats abortConnectionSwitch' c connId = diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 5e9c8920d..bbabc8bfc 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -643,6 +643,8 @@ functionalAPITests ps = do testSwitchNewQueueRecordedWhileDeleting ps it "should delete the new queue when the switch is aborted and started again while the queue is created" $ testSwitchRestartedWhileNewQueue ps + it "should end the asynchronous switch without an event when it is aborted while the queue is created" $ + testSwitchAsyncAbortedWhileNewQueue 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" $ @@ -4547,6 +4549,28 @@ testSwitchRestartedWhileNewQueue ps@(t, _) = waitRcvQueueRecords b 2 storeLogQueues testStoreLogFile2 `shouldReturn` (2, 1) +testSwitchAsyncAbortedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchAsyncAbortedWhileNewQueue 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 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> do + void . runRight $ switchConnectionAsync b "" aId + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ abortConnectionSwitch b aId + atomically $ putTMVar resume () + timeout 5_000000 (waitNoCommands b) `shouldReturn` Just () + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitRcvQueueRecords b 1 + noMessages b "nothing else should be delivered" + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + where + waitNoCommands c = do + cmds :: [(ConnId, Int64)] <- withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, command_id FROM commands") + unless (null cmds) $ threadDelay 100000 >> waitNoCommands c + testJoinConnectionDeletedWhileReplyQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testJoinConnectionDeletedWhileReplyQueue ps@(t, _) = withSmpServer ps $ From b4e3329fd1468f9b28c3b5f61da5809d5add320c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:53:05 +0000 Subject: [PATCH 30/44] tests: time out the switch with a full notification command queue --- tests/AgentTests/NotificationTests.hs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index c4bd529b7..1efe82c2e 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -928,9 +928,7 @@ testSwitchFullNtfQueue cfg completeSwitch apns = atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) atomically $ isEmptyTBQueue q >>= checkSTM atomically fill - runRight_ $ do - _ <- switchConnectionAsync a "" bId - completeSwitch a bId b aId + timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) setNtfSuspended False testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () From f8890ac32f16a1c6dc565d523fd8fb90204cb182 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:53:05 +0000 Subject: [PATCH 31/44] plans: lock holders never wait for notification command queue space --- plans/2026-11-21-agent-no-blocking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 1745da525..21db906a0 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -12,7 +12,7 @@ 1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails. 2. The second locked step reads the connection again; when its state changed, the step is dropped, postponed during ratchet synchronization, or undone. 3. A queue created on a server is recorded under the connection lock or deleted from the server; connection deletion takes the same locks. -4. API threads and lock holders never wait for space in subQ or msgQ. +4. API threads and lock holders never wait for space in subQ or msgQ; lock holders never wait for space in ntfSubQ. ## Helpers From 36d3207292cf14c70335873fa998168702638608 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:34:03 +0000 Subject: [PATCH 32/44] clients: simplify command sending; request time in system seconds --- src/Simplex/Messaging/Client.hs | 51 ++++++++++++++------------------- tests/SMPProxyTests.hs | 22 ++------------ 2 files changed, 25 insertions(+), 48 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index a743c1b30..281817357 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -155,10 +155,10 @@ 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) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -172,6 +172,7 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) +import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -214,7 +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 - connected <- newTVarIO True + connected <- newTVarIO False clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -483,7 +484,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: NominalDiffTime, + sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -528,7 +529,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: UTCTime, + createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -665,9 +666,10 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS `E.finally` (failPendingRequests c >> disconnected c') failPendingRequests :: PClient v err msg -> IO () - failPendingRequests PClient {connected, sentCommands} = atomically $ do - writeTVar connected False - swapTVar sentCommands mempty >>= mapM_ failRequest + failPendingRequests PClient {sentCommands} = atomically $ swapTVar sentCommands mempty >>= mapM_ failRequest + where + failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError send :: Transport c => ProtocolClient v err msg -> THandle v c 'TClient -> IO () send ProtocolClient {client_ = PClient {sndQ}} h = forever $ atomically (readTBQueue sndQ) >>= sendPending @@ -691,9 +693,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getCurrentTime - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL - diff <- diffUTCTime ts <$> readTVarIO lastReceived + ts <- getSystemSeconds + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL + diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -1392,19 +1394,13 @@ 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 = - -- two separate "atomically" needed to avoid blocking - E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ addRequest 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)) +sendBlock ProtocolClient {client_ = PClient {sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of + Just _ -> register >> send + Nothing -> E.bracket_ register unregister send 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 + register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands + unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands + send = withAsync (atomically $ writeTBQueue sndQ t) (const getResponses) nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do @@ -1412,7 +1408,7 @@ nonBlockingWriteTBQueue q x = do 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, sentCommands, msgQ}} nm tOut Request {corrId, entityId, pending, responseVar} = do +getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} nm tOut Request {entityId, pending, responseVar} = do r <- fromMaybe (netTimeoutInt tcpTimeout nm) tOut `timeout` atomically (takeTMVar responseVar) response <- atomically $ do writeTVar pending False @@ -1421,10 +1417,7 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, se -- See `processMsg`. ((r <|>) <$> tryTakeTMVar responseVar) >>= \case Just r' -> writeTVar timeoutErrorCount 0 $> r' - Nothing -> do - modifyTVar' timeoutErrorCount (+ 1) - when (isNothing msgQ) $ TM.delete corrId sentCommands - pure $ Left PCEResponseTimeout + Nothing -> modifyTVar' timeoutErrorCount (+ 1) $> Left PCEResponseTimeout pure Response {entityId, response} mkTransmission :: Protocol v err msg => ProtocolClient v err msg -> ClientCommand msg -> IO (PCTransmission err msg) @@ -1440,7 +1433,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getCurrentTime + createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 29b6f10c6..dca8d792b 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -74,8 +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 describe "agent client reconnection" $ do @@ -642,34 +640,20 @@ 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) - 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 + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} 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 + threadDelay 3000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From 4c2ee391b67dc4a487e4174432e6d4dfce032516 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:36:46 +0000 Subject: [PATCH 33/44] clients: fail commands of a disconnected client without queueing them --- src/Simplex/Messaging/Client.hs | 17 ++++++++++------- tests/SMPProxyTests.hs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 281817357..46408cdee 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -215,7 +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 - connected <- newTVarIO False + connected <- newTVarIO True clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -666,10 +666,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 @@ -1394,13 +1393,17 @@ 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 {sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of Just _ -> register >> send Nothing -> E.bracket_ register unregister send where register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands - send = withAsync (atomically $ writeTBQueue sndQ t) (const getResponses) + send = withAsync (atomically $ ifM (readTVar connected) (writeTBQueue sndQ t) (mapM_ failRequest rs)) (const getResponses) + +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 diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index dca8d792b..115dfb12b 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 it "releases command kept for late response" $ \_ -> testLateResponseCommandReleased describe "agent client reconnection" $ do @@ -640,6 +642,20 @@ 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) + pClientSentCommandsCount c `shouldReturn` 0 + atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 + testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do From 953dac4b3f3e56305e3e9442ef927bf08508348d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:39:29 +0000 Subject: [PATCH 34/44] clients: revert command sending to f8890ac3 --- src/Simplex/Messaging/Client.hs | 38 ++++++++++++++++++--------------- tests/SMPProxyTests.hs | 6 +++--- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 46408cdee..a743c1b30 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -155,10 +155,10 @@ 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) +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) @@ -172,7 +172,6 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) -import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -484,7 +483,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: Int64, + sentCommandsTTL :: NominalDiffTime, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -529,7 +528,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: SystemSeconds, + createdAt :: UTCTime, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -692,9 +691,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getSystemSeconds - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL - 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 @@ -1393,13 +1392,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 = case msgQ of - Just _ -> register >> send - Nothing -> E.bracket_ register unregister send +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = + -- two separate "atomically" needed to avoid blocking + E.bracketOnError + (atomically $ ifM (readTVar connected) (mapM_ addRequest 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 - register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands - unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands - send = withAsync (atomically $ ifM (readTVar connected) (writeTBQueue sndQ t) (mapM_ failRequest rs)) (const getResponses) + 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} = @@ -1411,7 +1412,7 @@ nonBlockingWriteTBQueue q x = do 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 @@ -1420,7 +1421,10 @@ 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) @@ -1436,7 +1440,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getSystemSeconds + createdAt <- getCurrentTime pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 115dfb12b..29b6f10c6 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -658,18 +658,18 @@ testClosedClientCommandsFail = testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do + 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 = 2} + 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 3000000 + threadDelay 1000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From f0bdba64ac3ee4ccec11e25514a715c7ab8da28f Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:56:42 +0000 Subject: [PATCH 35/44] clients: send a block only while connected, with one dispatch on msgQ --- src/Simplex/Messaging/Client.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index a743c1b30..d5ff97bc0 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1394,13 +1394,13 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv 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 = -- two separate "atomically" needed to avoid blocking - E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ addRequest 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)) + case msgQ of + Just _ -> send >>= get + Nothing -> E.bracketOnError send (\_ -> atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands) get where - addRequest r@Request {corrId} = TM.insert corrId r sentCommands - removeRequest Request {corrId} = TM.delete corrId sentCommands + send = sendOrFail $ forM_ rs (\r@Request {corrId} -> TM.insert corrId r sentCommands) >> tryWriteTBQueue sndQ t + get sent = if sent then getResponses else withAsync (sendOrFail $ True <$ writeTBQueue sndQ t) (const getResponses) + sendOrFail a = atomically $ ifM (readTVar connected) a (True <$ mapM_ failRequest rs) failRequest :: Request err msg -> STM () failRequest Request {pending, responseVar} = From c9ae815ac5e327275eea4d7a7ec1c8e96d8024fd Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:57:11 +0000 Subject: [PATCH 36/44] clients: request creation time in system seconds --- src/Simplex/Messaging/Client.hs | 15 ++++++++------- tests/SMPProxyTests.hs | 6 +++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index d5ff97bc0..c072812e0 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -158,7 +158,7 @@ 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 (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -172,6 +172,7 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) +import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -483,7 +484,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: NominalDiffTime, + sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -528,7 +529,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: UTCTime, + createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -691,9 +692,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getCurrentTime - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL - diff <- diffUTCTime ts <$> readTVarIO lastReceived + ts <- getSystemSeconds + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL + diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -1440,7 +1441,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getCurrentTime + createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 29b6f10c6..115dfb12b 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -658,18 +658,18 @@ testClosedClientCommandsFail = testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} 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 + threadDelay 3000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From c55ef71e3c563b24e5fd68240ac0998f51e02e7b Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:11:28 +0000 Subject: [PATCH 37/44] clients: write a message received in a response to msgQ in its order of reception --- src/Simplex/Messaging/Client.hs | 35 +++++++++++++++---------------- src/Simplex/Messaging/Protocol.hs | 6 ++++++ 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index c072812e0..96b5a049b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -732,7 +732,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS (True <$ tryPutTMVar responseVar (if entityId == entId then clientResp else Left unexpected)) (pure False) if wasPending - then pure Nothing + then pure $ case clientResp of + Right r | entityId == entId && responseEvent r -> Just (entId, STEvent clientResp) + _ -> Nothing else sendMsg $ if entityId == entId then STResponse command clientResp else STUnexpectedError unexpected where unexpected = unexpectedResponse respOrErr @@ -874,36 +876,33 @@ createSMPQueue c nm nonce_ (rKey, rpKey) dhKey auth subMode qrd ntfCreds = subscribeSMPQueue :: SMPClient -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPClientError IO (Maybe ServiceId) subscribeSMPQueue c rpKey rId = do liftIO $ enablePings c - sendSMPCommand c NRMBackground (Just rpKey) rId SUB >>= liftIO . processSUBResponse_ c rId >>= except + sendSMPCommand c NRMBackground (Just rpKey) rId SUB >>= except . processSUBResponse_ -- | Subscribe to multiple SMP queues batching commands if supported. -- This command is always sent in background request mode subscribeSMPQueues :: SMPClient -> NonEmpty (RecipientId, RcvPrivateAuthKey) -> IO (NonEmpty (Either SMPClientError (Maybe ServiceId))) subscribeSMPQueues c qs = do liftIO $ enablePings c - sendProtocolCommands c NRMBackground cs >>= mapM (processSUBResponse c) + L.map processSUBResponse <$> sendProtocolCommands c NRMBackground cs where cs = L.map (\(rId, rpKey) -> (rId, Just rpKey, Cmd SRecipient SUB)) qs -- This command is always sent in background request mode streamSubscribeSMPQueues :: SMPClient -> NonEmpty (RecipientId, RcvPrivateAuthKey) -> ([(RecipientId, Either SMPClientError (Maybe ServiceId))] -> IO ()) -> IO () -streamSubscribeSMPQueues c qs cb = streamProtocolCommands c NRMBackground cs $ mapM process >=> cb +streamSubscribeSMPQueues c qs cb = streamProtocolCommands c NRMBackground cs $ cb . map process where cs = L.map (\(rId, rpKey) -> (rId, Just rpKey, Cmd SRecipient SUB)) qs - process r@(Response rId _) = (rId,) <$> processSUBResponse c r + process r@(Response rId _) = (rId, processSUBResponse r) -processSUBResponse :: SMPClient -> Response ErrorType BrokerMsg -> IO (Either SMPClientError (Maybe ServiceId)) -processSUBResponse c (Response rId r) = pure r $>>= processSUBResponse_ c rId +processSUBResponse :: Response ErrorType BrokerMsg -> Either SMPClientError (Maybe ServiceId) +processSUBResponse (Response _ r) = r >>= processSUBResponse_ -processSUBResponse_ :: SMPClient -> RecipientId -> BrokerMsg -> IO (Either SMPClientError (Maybe ServiceId)) -processSUBResponse_ c rId = \case - OK -> pure $ Right Nothing - SOK serviceId_ -> pure $ Right serviceId_ - cmd@MSG {} -> writeSMPMessage c rId cmd $> Right Nothing - r' -> pure . Left $ unexpectedResponse r' - -writeSMPMessage :: SMPClient -> RecipientId -> BrokerMsg -> IO () -writeSMPMessage c rId msg = mapM_ (`nonBlockingWriteTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) +processSUBResponse_ :: BrokerMsg -> Either SMPClientError (Maybe ServiceId) +processSUBResponse_ = \case + OK -> Right Nothing + SOK serviceId_ -> Right serviceId_ + MSG {} -> Right Nothing + r' -> Left $ unexpectedResponse r' serverTransmission :: ProtocolClient v err msg -> NonEmpty (RecipientId, ServerTransmission err msg) -> ServerTransmissionBatch v err msg serverTransmission ProtocolClient {thParams, client_ = PClient {transportSession}} ts = (transportSession, thParams, ts) @@ -916,7 +915,7 @@ getSMPMessage :: SMPClient -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPCli getSMPMessage c rpKey rId = sendSMPCommand c NRMInteractive (Just rpKey) rId GET >>= \case OK -> pure Nothing - cmd@(MSG msg) -> liftIO (writeSMPMessage c rId cmd) $> Just msg + MSG msg -> pure $ Just msg r -> throwE $ unexpectedResponse r {-# INLINE getSMPMessage #-} @@ -1119,7 +1118,7 @@ ackSMPMessage :: SMPClient -> RcvPrivateAuthKey -> QueueId -> MsgId -> ExceptT S ackSMPMessage c rpKey rId msgId = sendSMPCommand c NRMBackground (Just rpKey) rId (ACK msgId) >>= \case OK -> pure True - cmd@MSG {} -> liftIO (writeSMPMessage c rId cmd) $> False + MSG {} -> pure False r -> throwE $ unexpectedResponse r -- | Irreversibly suspend SMP queue. diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 05efa40c5..a26428e34 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -1842,6 +1842,8 @@ class (ProtocolTypeI (ProtoType msg), ProtocolEncoding v err msg, ProtocolEncodi useServiceAuth :: ProtoCommand msg -> Bool protocolPing :: ProtoCommand msg protocolError :: msg -> Maybe err + responseEvent :: msg -> Bool + responseEvent _ = False type ProtoServer msg = ProtocolServer (ProtoType msg) @@ -1862,6 +1864,10 @@ instance Protocol SMPVersion ErrorType BrokerMsg where ERR e -> Just e _ -> Nothing {-# INLINE protocolError #-} + responseEvent = \case + MSG {} -> True + _ -> False + {-# INLINE responseEvent #-} class ProtocolMsgTag (Tag msg) => ProtocolEncoding v err msg | msg -> err, msg -> v where type Tag msg From 2eb02bb396212dbbe3bd1734188083b98fd90647 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:17:15 +0000 Subject: [PATCH 38/44] clients: check the entity of a response once --- src/Simplex/Messaging/Client.hs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 96b5a049b..44395b78b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -724,16 +724,17 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS TM.lookupIO corrId sentCommands >>= \case Nothing -> sendMsg $ STUnexpectedError unexpected Just Request {entityId, command, pending, responseVar} -> do + let resp = if entityId == entId then clientResp else Left unexpected wasPending <- atomically $ do TM.delete corrId sentCommands ifM (swapTVar pending False) - (True <$ tryPutTMVar responseVar (if entityId == entId then clientResp else Left unexpected)) + (True <$ tryPutTMVar responseVar resp) (pure False) if wasPending - then pure $ case clientResp of - Right r | entityId == entId && responseEvent r -> Just (entId, STEvent clientResp) + then pure $ case resp of + Right r | responseEvent r -> Just (entId, STEvent resp) _ -> Nothing else sendMsg $ if entityId == entId then STResponse command clientResp else STUnexpectedError unexpected where From 9c6121e646b98b971ac7ec7a7cf8019b693e5d83 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:19:04 +0000 Subject: [PATCH 39/44] agent: simplify acknowledgement, new queue recording and command postponement --- src/Simplex/Messaging/Agent.hs | 28 +++++++++++++-------------- src/Simplex/Messaging/Agent/Client.hs | 1 - 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index c25dd7121..27600a738 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1189,13 +1189,13 @@ 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' <- recordNewQueue c nm connId "createRcvQueue" tSess rq (withStore c $ \db -> updateNewConnRcv db connId rq subMode) $ \rq' -> + rq' <- recordNewQueue c nm "createRcvQueue" tSess rq (withStore c $ \db -> updateNewConnRcv db connId rq subMode) $ \rq' -> rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure (rq', qUri) -recordNewQueue :: AgentClient -> NetworkRequestMode -> ConnId -> Text -> SMPTransportSession -> NewRcvQueue -> AM r -> (r -> AM a) -> AM a -recordNewQueue c nm connId name tSess q record continue = do +recordNewQueue :: AgentClient -> NetworkRequestMode -> Text -> SMPTransportSession -> NewRcvQueue -> AM r -> (r -> AM a) -> AM a +recordNewQueue c nm name tSess q@RcvQueue {connId} record continue = do recorded <- withConnLock c connId name $ tryAllErrors record >>= mapM continue either (\e -> tryAllErrors (deleteNewQueue c nm tSess q) >> throwE e) pure recorded @@ -1738,7 +1738,7 @@ 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' <- recordNewQueue c nm connId "createReplyQueue" tSess rq (withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode) $ \rq' -> + rq' <- recordNewQueue c nm "createReplyQueue" tSess rq (withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode) $ \rq' -> rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure qInfo @@ -2524,10 +2524,10 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do cmdError e = notify (ERR e) >> withStore' c (`deleteCommand` cmdId) postponeCommand srv = do liftIO $ noWorkToDo doWork - otherCmds <- withStore c $ \db -> runExceptT $ do - liftIO $ deleteCommand db cmdId - pending <- liftIO $ hasNonQSecureCommand db connId srv - pending <$ ExceptT (createCommand db corrId connId server_ command) + otherCmds <- withStore c $ \db -> do + deleteCommand db cmdId + pending <- hasNonQSecureCommand db connId srv + (pending <$) <$> createCommand db corrId connId server_ command when otherCmds . atomically $ hasWorkToDo' doWork notify :: forall e. AEntityI e => AEvent e -> AM () notify cmd = @@ -2913,15 +2913,13 @@ ackMessage' c cmdId_ connId msgId rcptInfo_ = markConnUserAck :: AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) markConnUserAck = do SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection {} -> markUserAck $ Just conn - RcvConnection {} -> markUserAck Nothing + duplexConn_ <- case conn of + DuplexConnection {} -> pure $ Just conn + RcvConnection {} -> pure Nothing 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 :: Maybe (Connection 'CDuplex) -> AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) - markUserAck duplexConn_ = + -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged withStore' c (\db -> setMsgUserAck db connId $ InternalId msgId) >>= \case Right (rq, srvMsgId) -> pure $ Just (duplexConn_, rq, srvMsgId) Left (SEMsgNotFound _) -> Nothing <$ del @@ -2991,7 +2989,7 @@ switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, 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" - recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do + recordNewQueue c nm "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do started <- (Just switchId ==) <$> liftIO (TM.lookupIO connId $ rcvSwitches c) if rcvSwchStatus rq1 /= Just RSSwitchStarted || not started then Nothing <$ deleteRcvQueueAsync c rq'' diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index b3b3b8a56..3978592ac 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -1166,7 +1166,6 @@ checkNoConnLock AgentClient {connLockHolders, connLockViolations} = do 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 From 3398bac30727b9913facb2f142ed21ca463202ec Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:28:44 +0000 Subject: [PATCH 40/44] tests: remove duplicate switch tests, share full queue helpers --- tests/AgentTests/FunctionalAPITests.hs | 109 ++++++++++--------------- tests/AgentTests/NotificationTests.hs | 15 +--- 2 files changed, 45 insertions(+), 79 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index bbabc8bfc..eea996e4e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -58,6 +58,7 @@ module AgentTests.FunctionalAPITests agentCfgVPrevPQ, agentCfgV7, testServerInformation, + withFullNtfSubQ, #if defined(dbPostgres) workItemReadTests, #endif @@ -631,12 +632,8 @@ functionalAPITests ps = do 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 + testSwitchRatchetSyncWhileNewQueue ps it "should delete the new queue when the connection is deleted waiting for delivery while the queue is created" $ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps it "should delete the new queue when it is recorded while the connection deletion waits for the server" $ @@ -1242,7 +1239,7 @@ testAcceptContactStallingServer ps@(t, ASType qsType _) = 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 + pure () where bServers = initAgentServers {smp = userServers [testSMPServer2]} @@ -3400,10 +3397,7 @@ testAckMessageFullQueue = get a ##> ("", bId, SENT msgId) withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight_ $ do ("", _, 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 ()) - void . atomically . flushTBQueue $ subQ b + liftIO . withFullSubQ b $ timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) getMSGNTF b aId makeConnection :: AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId) @@ -3682,24 +3676,22 @@ testAckMessageFullQueues = withAgentClients2 $ \a b -> do 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 + withFullSubQ b $ do + 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 ()) timeout 5_000000 (receiveMsgs b $ (aId, "hello 2") : 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 + withFullSubQ a $ do + 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] getInAnyOrder a [resultSizeErr "subscribeConnections", resultSizeErr "deleteConnections"] where resultSizeErr :: String -> ATransmission -> Bool @@ -3954,9 +3946,7 @@ 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 + withFullSubQ a $ timeout 5000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False testDeleteConnectionFullNtfQueue :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () @@ -3964,22 +3954,27 @@ testDeleteConnectionFullNtfQueue ps = withSmpServer ps $ withAgent 1 agentCfg initAgentServers testDB $ \a -> do (connId, _) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe - let q = ntfSubQ $ ntfSupervisor $ agentEnv a - setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} - fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill - setNtfSuspended True - atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) - atomically $ isEmptyTBQueue q >>= checkSTM - atomically fill - timeout 5_000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) - setNtfSuspended False + withFullNtfSubQ a $ timeout 5_000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) get a =##> \case ("", "", DEL_RCVQS [(c, _, _, Nothing)]) -> c == connId; _ -> False get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False -fillSubQ :: AgentClient -> IO () -fillSubQ c = atomically fill +withFullNtfSubQ :: AgentClient -> IO a -> IO a +withFullNtfSubQ c action = do + setNtfSuspended True + atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) + atomically $ isEmptyTBQueue q >>= checkSTM + atomically fill + action <* setNtfSuspended False + where + q = ntfSubQ $ ntfSupervisor $ agentEnv c + setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp c) $ \s -> s {opSuspended = suspended} + fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill + +withFullSubQ :: AgentClient -> IO a -> IO a +withFullSubQ c action = atomically fill *> action <* atomically (flushTBQueue q) where - fill = unlessM (isFullTBQueue $ subQ c) $ writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) >> fill + q = subQ c + fill = unlessM (isFullTBQueue q) $ writeTBQueue q ("", "", AEvt SAENone SUSPENDED) >> fill testWaitDeliveryNoPending :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () testWaitDeliveryNoPending ps = withAgentClients2 $ \alice bob -> @@ -4278,9 +4273,7 @@ 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 + withFullSubQ a $ timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ()) nGet a =##> \case ("", "", DEL_USER u) -> u == auId; _ -> False testDeleteUserStatsErrorFullQueue :: HasTestEnv => IO () @@ -4288,10 +4281,9 @@ 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 + withFullSubQ a $ do + 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") get a =##> \case ("", "", ERR (A.INTERNAL _)) -> True; _ -> False testUsersNoServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () @@ -4456,8 +4448,8 @@ receiveMsgs c msgs = (_, 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, _) = +testSwitchRatchetSyncWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchRatchetSyncWhileNewQueue ps@(t, _) = withSmpServer ps $ withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b @@ -4466,28 +4458,13 @@ testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = 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 + void . runRight $ synchronizeRatchet b aId PQSupportOn True atomically $ putTMVar resume () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED "switchConnection: send prohibited") 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 $ \_ -> - 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 resume () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") - storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) - testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps@(t, _) = withSmpServer ps $ @@ -5931,9 +5908,7 @@ testServiceUnavailableFullQueue (t, msType) = do 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 + withFullSubQ service $ timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ()) getInAnyOrder service [ \case ("", "", AEvt SAEConn (ERR (BROKER _ NO_SERVICE))) -> True; _ -> False, diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index 1efe82c2e..1054fab13 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -66,8 +66,8 @@ import SMPAgentClient (agentCfg, initAgentServers, initAgentServers2, testDB, te import SMPClient import Simplex.Messaging.Agent hiding (checkNtfToken, createConnection, joinConnection, registerNtfToken, sendMessage, verifyNtfToken) import qualified Simplex.Messaging.Agent as A -import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers, NtfSupervisor (..), NtfSupervisorCommand (..)) +import Simplex.Messaging.Agent.Client (ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers) import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, SENT) import Simplex.Messaging.Agent.Store.AgentStore (getSavedNtfToken) import Simplex.Messaging.Agent.Store.Common (withTransaction) @@ -89,7 +89,6 @@ import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo (QueueInfo (..)) import Simplex.Messaging.Transport (ASrvTransport) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) -import Simplex.Messaging.Util (unlessM) import System.Process (callCommand) import Test.Hspec hiding (fit, it) import UnliftIO @@ -921,15 +920,7 @@ testSwitchFullNtfQueue cfg completeSwitch apns = exchangeGreetings a bId b aId _ <- registerTestToken a "abcd" NMInstant apns pure (aId, bId) - let q = ntfSubQ $ ntfSupervisor $ agentEnv a - setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} - fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill - setNtfSuspended True - atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) - atomically $ isEmptyTBQueue q >>= checkSTM - atomically fill - timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) - setNtfSuspended False + withFullNtfSubQ a $ timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () testNotificationsOldToken apns = From 4a42ac975484efdd70a82143bf2682897d5f8b27 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:28:44 +0000 Subject: [PATCH 41/44] plans: correct the agent no-blocking plan to the code --- plans/2026-11-21-agent-no-blocking.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 21db906a0..9d6ca0ec0 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -9,14 +9,14 @@ ## Rules -1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails. -2. The second locked step reads the connection again; when its state changed, the step is dropped, postponed during ratchet synchronization, or undone. +1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails, and `disposeAgentClient` then throws. +2. The locked step after a server request reads again the state that its writes depend on; when that state changed, the step is dropped, postponed during ratchet synchronization, or undone. 3. A queue created on a server is recorded under the connection lock or deleted from the server; connection deletion takes the same locks. 4. API threads and lock holders never wait for space in subQ or msgQ; lock holders never wait for space in ntfSubQ. ## Helpers -- `requestAndCommit`: validates the connection under the lock, makes the request, validates again and commits under the lock. +- `requestAndCommit`: makes the request between two locked runs of the caller's check, which may write or end the step, and commits after the second run in its lock. - `recordNewQueue`: records a queue created on a server under the lock, or deletes it from the server. ## Sequence @@ -50,7 +50,7 @@ sequenceDiagram - agent, connection locks: - `requestAndCommit` in ICDuplexSecure, ICQSecure, ICQSndSecure, ICQDelete and `ackMessage`; - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; + - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, ICReplyDel, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - a connection whose deletion waits for delivery is not given new queues; @@ -60,12 +60,11 @@ sequenceDiagram - the receive queue status is set to Secured under the lock, only from Confirmed; - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. -- agent, events written without waiting: +- agent, events and notification commands written without waiting: - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - the notification commands of connection deletion, ICQDelete and QEND. - clients: - - a message in the response to ACK, SUB or GET is written to msgQ without waiting; + - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. -- moved to separate pull requests: the HTTP/2 request timeout, the SUSPENDED event written without waiting. From 29890639615e371b2523de8adcb3c5bd223b45e7 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:35:32 +0000 Subject: [PATCH 42/44] tests: import the full notification queue helper --- tests/AgentTests/NotificationTests.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index 1054fab13..8f98552ab 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -37,6 +37,7 @@ import AgentTests.FunctionalAPITests withAgentClients3, withAgentClientsCfg2, withAgentClientsCfgServers2, + withFullNtfSubQ, (##>), (=##>), pattern CON, From 9b0838274b072d9e512700573fe11957393824d5 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:45:26 +0000 Subject: [PATCH 43/44] clients: keep requests for late responses until disconnection --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Client.hs | 12 ++---------- tests/SMPProxyTests.hs | 17 +++++++---------- 3 files changed, 10 insertions(+), 21 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 9d6ca0ec0..22fd092a9 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -67,4 +67,4 @@ sequenceDiagram - clients: - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. + - a command that ends without a response is removed, except in clients with msgQ, where it is kept until its late response or disconnection. diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 44395b78b..ca741f378 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -172,7 +172,6 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) -import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -484,7 +483,6 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -505,7 +503,6 @@ defaultClientConfig clientALPN useSNI serverVRange = { qSize = 64, defaultTransport = ("443", transport @TLS), networkConfig = defaultNetworkConfig, - sentCommandsTTL = 15 * 60, clientALPN, serviceCredentials = Nothing, serverVRange, @@ -529,7 +526,6 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -585,7 +581,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, sentCommandsTTL, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do +getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, 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) @@ -687,13 +683,11 @@ 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, sentCommands}} = loop smpPingInterval + monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount}} = loop smpPingInterval where loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getSystemSeconds - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle @@ -1441,7 +1435,6 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = @@ -1449,7 +1442,6 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc { corrId, entityId, command, - createdAt, pending, responseVar } diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 115dfb12b..8920432b5 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -76,8 +76,8 @@ smpProxyTests = do testForwardOversizedNotKept it "fails commands of closed client at once" $ \_ -> testClosedClientCommandsFail - it "releases command kept for late response" $ \_ -> - testLateResponseCommandReleased + it "delivers late response to the message queue" $ \_ -> + testLateResponseDelivered describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -656,23 +656,20 @@ testClosedClientCommandsFail = pClientSentCommandsCount c `shouldReturn` 0 atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 -testLateResponseCommandReleased :: HasTestEnv => IO () -testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do +testLateResponseDelivered :: HasTestEnv => IO () +testLateResponseDelivered = + 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 = 2} - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] (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 3000000 + (_, _, [(_, STResponse _ (Left (PCEProtocolError SMP.AUTH)))]) <- atomically $ readTBQueue msgQ 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 From 6826cf605280eca62dd207c92a8993de3e0d4d7b Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:07:39 +0000 Subject: [PATCH 44/44] agent: plan requests without contested connection locks --- plans/2026-11-21-agent-no-blocking.md | 231 ++++++++++++++++++++------ 1 file changed, 176 insertions(+), 55 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 22fd092a9..9f25e6f00 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -1,70 +1,191 @@ -# Agent without waits on slow servers and full queues +# Agent without network requests under contested locks -## Problem +Line references are to master 3f57fcdc: A = src/Simplex/Messaging/Agent.hs, AC = Agent/Client.hs, AS = Agent/Store/AgentStore.hs, ST = Agent/Store.hs, C = Client.hs, schema = Agent/Store/SQLite/Migrations/agent_schema.sql, Subscriber.hs = simplex-chat src/Simplex/Chat/Library/Subscriber.hs. -- One subscriber thread processes received messages, each under the lock of its connection. -- Worker and API threads held that lock across server requests, up to 75 seconds per attempt, so one slow server stopped the messages of all connections. -- An acknowledgement held the lock while it waited for space in msgQ, which only the subscriber drains, after it takes the same lock. -- API calls waited for space in subQ, which the app drains while it holds its own locks. +## Problems -## Rules +1. A server request is made while the connection lock is held: up to 75 s per direct request (45 s connect and 30 s response, C:434-435), and several requests in sequence at some sites (A:2392-2394, 4427-4430). The subscriber, the single thread that processes received messages of all connections (A:3698), waits for that lock when a message of the connection arrives, so messages of all connections stop. +2. An acknowledgement holds the connection lock while its thread waits for space in msgQ, which only the subscriber drains, after it takes the same lock: deadlock. +3. A rotation stays in progress forever after its QADD or QUSE is refused, and crashes between transactions of rotation handlers and of message storage leave a rotation half-done or a message missing on one queue. -1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails, and `disposeAgentClient` then throws. -2. The locked step after a server request reads again the state that its writes depend on; when that state changed, the step is dropped, postponed during ratchet synchronization, or undone. -3. A queue created on a server is recorded under the connection lock or deleted from the server; connection deletion takes the same locks. -4. API threads and lock holders never wait for space in subQ or msgQ; lock holders never wait for space in ntfSubQ. +## Scope -## Helpers +Unchanged from master: +- delivery of events to the app (subQ, its writers, event deferral); +- connection deletion: the fork per call, deleteLock across DEL batches, the cleanup pass; +- the multi-connection lock of sendMessagesB_ (A:2182); +- PostgreSQL row locking, except https://github.com/simplex-chat/simplexmq/pull/2104; +- joinConnection, which holds no connection lock on master; the invitation lock (A:964, 1627, 1644). -- `requestAndCommit`: makes the request between two locked runs of the caller's check, which may write or end the step, and commits after the second run in its lock. -- `recordNewQueue`: records a queue created on a server under the lock, or deletes it from the server. +The order of link data is a separate change. LSET and LDEL are sent without the lock (change 1), so an LSET can reach the server after an LDEL of the same link and publish it again. -## Sequence +## Decisions + +| Date | Decision | +|---|---| +| 2026-11-24 | An abort cancels the rotation step in progress and deletes its new queue. | +| 2026-11-24 | The old KEY handshake is removed; SMP client version 3, with sender-secured queues, is the minimum. | +| 2026-11-24 | The protocol client keeps timed-out requests until their response or disconnection. | +| 2026-11-25 | Old-handshake rows in progress end with a version error; joining an invitation without a sender-secured queue is refused. | +| 2026-11-25 | A rotation refused by the server with AUTH returns to its state before it started; an abort is refused once QADD is stored. | +| 2026-11-25 | Acknowledgements stay asynchronous and keep master's order: ACK, then receipt; the receipt is stored only when the ratchet allows sending. | +| 2026-11-26 | Downgrade is not supported. | + +## Changes + +### 1. The connection lock covers database work only + +Each server request that master makes under the connection lock is moved out of it. A step that has a command row (change 2) becomes: +- P: under the lock, one transaction checks that the row exists (otherwise the step ends without a request), reads the state, decides the request, and writes what the request needs; +- the request, with no lock held; +- C: under the lock, one transaction that applies by the rules of change 2, re-reads the state it writes, and writes the outcome. + +Events, worker wake-ups and notification commands of P and C follow their commit. ```mermaid sequenceDiagram - participant W as Worker of connection X - participant L as Lock of X - participant S as Slow server + participant W as Executor of the row + participant L as Connection lock + participant S as Server participant Sub as Subscriber - participant P as Protocol clients - rect rgb(255,228,228) - Note over W,P: Before W->>L: take - W->>S: SKEY, confirmation - Sub--xL: MSG for X waits up to 75 s - P--xSub: MSG for Y, Z: msgQ full, writers wait - end - rect rgb(226,244,226) - Note over W,P: After - W->>L: read, validate, release - W->>S: SKEY, confirmation, without the lock - Sub->>L: MSG for X waits for database work only - P->>Sub: MSG for Y, Z processed - W->>L: read again, validate, write - end + W->>W: P: row exists? read, decide, write (one transaction) + W->>L: release + W->>S: request + Sub->>L: take, process a message, release + S-->>W: response + W->>L: take + W->>W: C: by the row rules, re-read, write (one transaction) + W->>L: release ``` -## Changes +Sites with a row: + +| Site | Request | P | C | When the state read in C differs | +|---|---|---|---|---| +| ACK command (A:2309, 2846-2881) and synchronous ackMessage (change 3) | ACK | row; message present (absent: the row ends without ACK, A:2864); user_ack set (A:2859; the asynchronous form set it when the row was stored, A:1022); queue read by id without the deleted filter; ACK skipped for a missing or marked queue | receipt (A:2869-2876) unless the ratchet does not allow sending; MROk deletion (A:2877-2880); message deletion (A:2867); drained-queue deletion (A:2975, 2987) | ratchet prohibits sending: receipt skipped | +| ICAck (A:2323-2324) | ACK | row; queue by (server, rcvId) with the deleted filter (AS:790); missing: no ACK (A:2437) | drained-queue deletion | | +| ICAckDel (A:2318-2322) | ACK | row; queue as ICAck | message deletion (A:2321); drained-queue deletion | | +| ICAllowSecure (A:2325-2348) | SKEY | row; sender key present, or a reply queue without sender-secure mode: ERR A_VERSION; RcvConnection: upgrade to duplex (A:4413-4415) and the confirmation stored (A:4466-4485), held (change 2, rule 9); DuplexConnection: the confirmation stored when the send queue has no delivery of a connection-info message | Secured (A:4449); messages.internal_ts of the confirmation set to now; a temporary error on another server moves the row to that server (CCMoved, A:2337-2344) | | +| ICDuplexSecure (A:2349-2351) | none | the row ends with ERR A_VERSION | | | +| ICReplyDel (A:2352-2355) | SKEY | row; SndConnection | Secured; the connection's deletion (A:1809) is requested once, after C or after the permanent-error exit, not after each attempt (master's allFinally runs inside the retried action) | | +| ICDeleteRcvQueue (A:2358-2365) | DEL | row; deleted queue (AS:793-796) | temporary error below the limit: delete_errors + 1, row kept; otherwise record removed (A:2362-2365) | | +| ICQSecure (A:2366-2384) | KEY | row; new queue by address, Confirmed (A:2371), with its replaced queue (A:2369-2370); ratchet prohibits sending: ERR, row ends | Secured, RSSendingQUSE, QUSE stored (A:2376-2377) | ratchet prohibits sending: ERR, row ends, no writes | +| ICQSndSecure (A:2385-2409) | SKEY, SEND confirmation | row; new send queue by address with its replaced queue; without a replaced queue and with a queue at SSSendingQEND: QEND stored, no request (A:2407-2409) | Active, primary, SSSendingQEND, QEND stored, deliveries counted and resumed (A:2395-2403) | ratchet prohibits sending: the status writes with ERR, as master (A:2395-2403, 2488) | +| ICQDelete (A:2410-2432) | DEL | row; queue by address at RSReceivedMessage (A:2417) | record removed; NSCCreate and SWITCH after commit (A:2425-2431) | | +| SWCH (A:2310-2315, 2905-2921) and switchConnection' (A:2893-2903, change 3) | NEW | row; head queue at RSSwitchStarted (A:2907); ratchet prohibits sending: status cleared, ERR, row ends | queue recorded (A:2916); QADD stored (A:2918); RSSendingQADD (A:2919) | ratchet prohibits sending: the new queue is deleted (rule 5), status cleared, ERR | +| LSET command (A:2268-2271) | LSET | row; credentials created when absent (A:1272-1293); data prepared | LINK | | +| acceptContact' (A:1745-1764, change 3) | SKEY, NEW, SEND | change 3 | change 3 | | +| JOIN service request (A:2295-2307, change 3) | NEW, SEND | change 3 | change 3 | | + +Sites without a row: setConnShortLink' (A:1247-1279), deleteConnShortLink' (A:1314-1321) and suspendConnection' (A:2995-3003) read under the lock and send LSET, LDEL or OFF without it; nothing is written after the request. + +For the three ACK sites, the GET lock is released and MSGNTF is written after OK or NO_MSG, as on master (A:2983-2986), whether or not C finds the row. After a permanent error, the GET lock is also released; the error is reported without MSGNTF. + +The ACK of problem 2 is solved by this change together with the protocol client of this branch, in which the thread that receives a response writes its MSG to msgQ and the requester writes nothing to msgQ. + +### 2. The command row records each split step + +```mermaid +stateDiagram-v2 + [*] --> Stored: created by an API call, the subscriber or a C + Stored --> Executing: an executor claims it (in memory, one process) + Executing --> Stored: temporary error recorded, claim released + Executing --> Done: C deletes the row and writes the outcome + Executing --> Failed: permanent error, the row is deleted, ERR + Stored --> Gone: an obsoleting operation deletes the row + Executing --> Undone: C finds no row, or the connection marked deleted, and undoes + Done --> [*] + Failed --> [*] + Gone --> [*] + Undone --> [*] +``` + +Rules: +1. Every P starts by checking that its row exists; a missing row ends the step without a request and without an event. +2. A C that ends the step (success, permanent error, obsolete state) starts with `DELETE FROM commands WHERE command_id = ? RETURNING 1` and writes its outcome only when a row is returned. A C that records a temporary failure (ICDeleteRcvQueue's delete_errors) writes only while the row exists and keeps it. +3. Operations that make a step obsolete delete its row in their own transaction: + - the abort (A:2923-2945) deletes the connection's SWCH and ICQSecure rows; + - the peer's repeated QADD deletes the ICQSndSecure rows of the earlier new send queues that it deletes (delSqs, A:4131, 4137); + - the end of a synchronous call deletes its own row (change 3). +4. A C that finds its connection marked deleted (AS:2748-2762 with the deleted filter) writes no outcome, deletes its row and runs the undo. +5. Undo of NEW: the created queue is recorded with deleted = 1 and an ICDeleteRcvQueue row while the connection row exists; when the connection row is gone, DEL is sent once. +6. Within one process, an executor claims the row by command id for its attempt (an in-memory set). The worker's read returns no work while the oldest row of its key is claimed; the claimant wakes the key's worker when it releases the claim. +7. Across the app and the iOS extension, nothing is claimed in the store: the first C that deletes the row writes the outcome. KEY and SKEY with the same key, DEL (AUTH) and ACK (NO_MSG) are repeatable; NEW is undone. +8. C reads queues by address where the row names them, because queue ids are reused (AS:2370-2375). +9. Deliveries of a connection wait while it has an ALLOW_SECURE, REPLY_DEL or JOIN row: + - the delivery work read (AS:1116-1132) returns no message for such a connection, by a `NOT EXISTS` join on commands (conn_id index); + - every transaction that deletes such a row is followed by a wake of the delivery workers of the connection's send queues, in the process that ran it; + - on resume, existing delivery workers are woken (A:2607 passes False), which also covers a row that the other process deleted. + +### 3. Synchronous calls with their own rows + +acceptContact', sendServiceRequest' and sendServiceRequestAsync', switchConnection', and the synchronous ackMessage: +1. The call stores, in its first transaction, the row that its asynchronous form stores, with a flag in the encoded command that marks a synchronous call, and claims it. + - acceptContact': a JOIN row (JRInvitationDR or JRConnReq, as acceptContactAsync', A:993-995); the transaction is refused when the connection already has a JOIN row. + - the service request: the JOIN JRServiceReq row (A:1853). + - switchConnection': the SWCH row with RSSwitchStarted (A:1052-1053). + - ackMessage: the ACK row with user_ack (A:1017-1023). +2. The call executes the row in its own thread, by change 1 for SWCH and ACK, and as below for JOIN rows, and returns the outcome. +3. On an error, the call returns the error to its caller, as master does, deletes its row, releases the claim and wakes the key's worker. State written before the error stays, as on master, and a repeated call continues from it (A:1757-1762). +4. After a crash, the worker deletes a flagged row in its P without a request. The chat ignores JOINED with an empty corrId (Subscriber.hs:533-535, 736-738), so the row is not resumed. +5. acceptContact' takes the connection lock only for its database steps (A:1746 holds it across the call): + - P1: row; dispatch on the connection as A:1757-1762; the send queue recorded (A:1586-1588) or reused; + - SKEY unless Secured; P2: Secured (A:4449); + - NEW of the reply queue when P1 found none (A:4460-4462); P3: the reply queue recorded (AS:646-651) while the row exists, otherwise undone (change 2, rule 5); + - SEND of the confirmation (A:4429-4430); + - C: Confirmed (A:4431); the invitation deleted (A:1763); the row deleted. +6. The service request, both forms: + - P1: row; P2 after NEW: the reply queue recorded while the row exists (AS:646-651); + - SEND (A:1675), only after P2 found the row; + - the asynchronous form repeats attempts after temporary errors and QUOTA, as A:2459-2471, while the next attempt starts before expiresAt (A:1859); + - the call then waits for the reply (A:1866-1867), deletes its row and runs its cleanup (A:1868-1870) in the same thread, without the connection lock, so no attempt runs after its cleanup; + - a row left by a crash has no waiter: the worker deletes it (A:2299-2300). + +### 4. Late responses are committed like on-time responses + +A late response reaches the subscriber as STResponse (A:3622-3636). Master reads the queue with getRcvConn, which filters deleted queues and deleted connections (AS:610, 2757), and emits ERR CONN NOT_FOUND with an empty connection id when it finds none (A:3647-3649). + +| Late response | Master | Change | +|---|---|---| +| SUB: OK, SOK, MSG | processed (A:3624-3631) | unchanged | +| ACK: MSG | processed (A:3632-3633) | unchanged | +| ACK: OK, NO_MSG, error | ignored (A:3634), or ERR CONN NOT_FOUND for a deleted queue | the connection's ACK, ACK_DEL and client ACK rows are read (conn_id index) and decoded; the row whose server message id matches (ICAck and ICAckDel store it; the client ACK row stores the agent message id, mapped through rcv_messages.broker_id) runs its C; the GET lock and MSGNTF as for on-time responses | +| DEL: OK, AUTH, error | ignored (A:3635), or ERR CONN NOT_FOUND | the queue record is read including deleted queues; with a DELETE_RCV_QUEUE or QDELETE row, that row runs its C; for a queue of a connection marked deleted, the record is removed | +| NEW: IDS | ignored (A:3636) | the rows with a NEW request on the response's server (SWCH, NEW, JOIN; server index) are read and decoded; the row whose stored public key equals the request's key records the queue when its step has none recorded, and otherwise the queue is deleted | +| SEND | ignored (A:3636) | unchanged; the retry is sent; the peer drops a repeated message, except an invitation to an address without ratchet keys, which creates a second request (A:4235-4244), as on master | + +A row with a NEW request stores the generated keys in its encoded command in the P before NEW: the NEW command (A:2263-2267), SWCH, and JOIN rows that create a reply queue. createConnection and prepared links have no row; their late IDS stays ignored, as on master. + +```mermaid +sequenceDiagram + participant W as Executor + participant S as Server + participant P as Protocol client + participant Sub as Subscriber + W->>S: request (row present) + Note over W: timeout, temporary error, claim released + S-->>P: response after the timeout + P->>Sub: late response (STResponse) + Sub->>Sub: find the row or the record; C by the row rules + W->>W: next attempt: P finds no row, nothing sent +``` + +### 5. Rotation + +1. AUTH of QADD or QUSE (A:2690, 2692) resets the receiving rotation, when the refusing send queue is the connection's only send queue and its delivery row exists, and the new receive queue named in the message still replaces a queue at RSSendingQADD or RSSendingQUSE. The reset is the abort's transaction (A:2935-2938), taken under the connection lock, together with the deletion of the refused delivery; ERR A_QUEUE is written as on master (A:2690, 2826). +2. Abort is allowed only at RSSwitchStarted: ST:210-222 loses the RSSendingQADD branch, so canAbortSwitch (A:3185) is False from RSSendingQADD for every peer version. +3. The writes of the first message on a new queue (A:3738-3747: status, primary, RSReceivedMessage, ICQDelete row) become one transaction, in master's position before decryption (A:3751). +4. QADD, QKEY, QUSE and QEND (A:4121-4221) write their effects in the transaction that stores the decrypted message (A:3833-3850). An error of a handler is returned as a value inside that transaction: the decryption and the message are stored as on master, and the handler's error is reported as on master. +5. A message is stored with all its deliveries in one transaction (A:2561-2579 with A:2591-2601). +6. switchConnectionAsync' (A:1052-1053), the abort (A:2935-2938) and deleteRcvQueueAsync (A:2991-2992) each write their state and their command row in one transaction. + +### 6. Small fixes -- agent, connection locks: - - `requestAndCommit` in ICDuplexSecure, ICQSecure, ICQSndSecure, ICQDelete and `ackMessage`; - - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, ICReplyDel, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - - a connection whose deletion waits for delivery is not given new queues; - - the record step of an acknowledgement reads the queue again; - - a concurrent acknowledgement of a deleted message is dropped; - - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created, without an event from an asynchronous switch; - - the receive queue status is set to Secured under the lock, only from Confirmed; - - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - - SWCH is refused while the ratchet is not synchronized. -- agent, events and notification commands written without waiting: - - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - - the notification commands of connection deletion, ICQDelete and QEND. -- clients: - - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - - a command that ends without a response is removed, except in clients with msgQ, where it is kept until its late response or disconnection. +1. A GET lock records the session of its GET; it is also released when that session ends (AC:813-818 releases only subscribed queues). +2. The ACK row's P reads the queue without the deleted filter (master's synchronous retry fails at AS:1235 after a QEND marked the queue, A:2865). C reads no queue. During ratchet synchronization the receipt is skipped without an error; master writes ERR INTERNAL after the ACK (A:2876, 2488). The peer gets no delivery receipt either way. +3. ackMessageAsync' (A:1001-1023) reads the message's queue by id without the deleted filter. For a removed queue, the ACK row is keyed by the primary queue's server, and its step deletes the message and stores the receipt without an ACK. A queue id reused by a newer queue (AS:2370-2375; rcv_messages.rcv_queue_id has no foreign key, schema:124) resolves to that queue, as on master. +4. Connection deletion also takes the receive queues already marked deleted (AS:2872-2875 filters deleted = 0) and deletes them with the others; a DEL for a queue the server already deleted returns AUTH, reported in DEL_RCVQS (A:3091-3099, 3083). +5. The old KEY handshake: no ICDuplexSecure rows are created (A:4035); a confirmation with a sender key is refused; joining an invitation whose queue has no sender-secure mode is refused with A_VERSION where the invitation is checked (compatibleInvitationUri, A:1598-1605, used by A:965 and A:1540); the minimum SMP client version of smpClientVRange becomes 3. Every supported relay, from version 15 (Transport.hs:222-226), returns the queue mode that the client requests (Server.hs:1738). +6. Client.hs: a batch block is sent after its callers' waits end, until the client disconnects; master's forked writer was not ended at disconnection. +7. Processing of a received message (A:3698) reads the connection and its queues after it takes the connection lock; before the lock, only the queue's connection id is read (A:3648). Subscription responses and event errors (A:3619-3631) are unchanged.