diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index c835a6829..6cbc36652 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -299,7 +299,7 @@ jobs:
chmod -fR 777 ~/.cabal ./dist-client-postgres || :; git config --global --add safe.directory '*'
scripts/ci/prune-old-builds.sh dist-client-postgres
cabal update
- 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
mkdir -p /out
bin=$(find /project/dist-client-postgres -name simplexmq-test -type f -executable)
cp "$bin" /out/simplexmq-test-client-postgres
@@ -503,7 +503,7 @@ jobs:
run: |
scripts/ci/prune-old-builds.sh dist-newstyle dist-postgres dist-client-postgres
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
else
cabal build --builddir=dist-postgres --jobs=$(nproc) --enable-tests -fserver_postgres --ghc-options=-O0
cabal build --jobs=$(nproc) --ghc-options=-O0
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..9f25e6f00
--- /dev/null
+++ b/plans/2026-11-21-agent-no-blocking.md
@@ -0,0 +1,191 @@
+# Agent without network requests under contested locks
+
+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.
+
+## Problems
+
+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.
+
+## Scope
+
+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).
+
+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.
+
+## 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 Executor of the row
+ participant L as Connection lock
+ participant S as Server
+ participant Sub as Subscriber
+ W->>L: take
+ 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
+```
+
+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
+
+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.
diff --git a/scripts/ci/README.md b/scripts/ci/README.md
index 1c9a1a30a..7d5f9ac12 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: 2 entries, 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: 6 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. In both builds, the ubuntu-24.04 x86-64 entry named "PostgreSQL agent store" builds and runs only 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", in parallel with the other entries; its build directory has its own cache key. 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. In both builds, the ubuntu-24.04 x86-64 entry named "PostgreSQL agent store" builds and runs only 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", in parallel with the other entries; its build directory has its own cache key. After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image.
## Test selection
diff --git a/simplexmq.cabal b/simplexmq.cabal
index 3b70db982..323b14314 100644
--- a/simplexmq.cabal
+++ b/simplexmq.cabal
@@ -94,6 +94,11 @@ flag slow_servers
manual: True
default: False
+flag conn_lock_checks
+ description: Fail agent server requests made inside a connection lock, for tests.
+ manual: True
+ default: False
+
flag server_postgres
description: Build server with support of PostgreSQL.
manual: True
@@ -429,6 +434,8 @@ library
cpp-options: -DswiftJSON
if flag(slow_servers)
cpp-options: -Dslow_servers
+ if flag(conn_lock_checks)
+ cpp-options: -Dconn_lock_checks
if !flag(client_library)
build-depends:
case-insensitive ==1.2.*
@@ -683,6 +690,8 @@ test-suite simplexmq-test
cpp-options: -DdbServerPostgres
if flag(slow_servers)
cpp-options: -Dslow_servers
+ if flag(conn_lock_checks)
+ cpp-options: -Dconn_lock_checks
if flag(client_postgres)
cpp-options: -DdbPostgres
else
diff --git a/src/Simplex/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..27600a738 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 #-}
@@ -198,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)
@@ -326,13 +328,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' ()
@@ -360,6 +362,10 @@ disposeAgentClient c@AgentClient {acThread, agentEnv = Env {store}} = do
disconnectAgentClient c
mapM_ killThread t_
liftIO $ closeDBStore store
+#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
@@ -660,7 +666,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
@@ -927,8 +933,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)) $
+ notifySub c $ DEL_USER userId
setUserService' :: AgentClient -> UserId -> Bool -> AM ()
setUserService' c userId enable = do
@@ -1034,8 +1040,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)
@@ -1181,11 +1189,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
- rq' <- withStore c $ \db -> updateNewConnRcv db connId rq subMode
- lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_
+ 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 -> 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
+
checkClientNotices :: AgentClient -> SMPServerWithAuth -> AM ()
checkClientNotices AgentClient {clientNotices, presetServers} (ProtoServerWithAuth srv@(ProtocolServer {host}) _) = do
notices <- readTVarIO clientNotices
@@ -1245,15 +1258,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 +1325,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
@@ -1724,8 +1738,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
- rq' <- withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode
- lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_
+ 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
@@ -1743,7 +1757,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
@@ -1865,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)
@@ -1912,7 +1925,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 +1999,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 +2047,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 +2239,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 +2308,47 @@ 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
+ ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >>= mapM_ (atomically . writeTBQueue subQ) >> notify OK
SWCH ->
- noServer . tryAtomicWithLock "switchConnection" $
- withStore c (`getConn` connId) >>= \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
+ >>= maybe (withStore' c (`deleteCommand` cmdId)) (notify . SWITCH QDRcv SPStarted)
+ where
+ startSwitch :: AM (Connection 'CDuplex, RcvQueue, Unique)
+ startSwitch =
+ withStore c (`getConn` connId) >>= \case
+ 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"
+ | 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 ->
- 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
+ acked <- ack srv rId srvMsgId
+ withConnLockNotify c connId "ICAckDel" $ do
+ t_ <- recordAck srvMsgId acked
+ 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" . recordAck srvMsgId
+ 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,101 +2370,125 @@ 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 . 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)
_ -> 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 . 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
+ \_ (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
+ 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 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"
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 . 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
+ 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 srv
+ | otherwise -> case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of
+ 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 -> 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 . 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 . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId])
+ let conn' = DuplexConnection cData rqs sqs
+ cStats <- connectionStats c conn'
+ notify $ SWITCH QDRcv SPCompleted cStats
+ either (notify . ERR) pure deleted
+ where
+ 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
+ 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
+ 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} 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
@@ -2449,11 +2497,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 a =
+ duplexConn :: AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue))
+ duplexConn =
withStore c (`getConn` connId) >>= \case
- SomeConn _ conn@DuplexConnection {} -> a conn
- _ -> internalErr "command requires duplex connection"
+ 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)
tryMoveableCommand action = withRetryInterval2 ri $ \_ loop -> do
@@ -2472,11 +2520,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 srv = do
+ liftIO $ noWorkToDo doWork
+ 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 =
let t = (corrId, connId, AEvt (sAEntity @e) cmd)
@@ -2843,24 +2895,33 @@ withConnLockNotify c connId name action = do
t_ <- withConnLock c connId name action
forM_ t_ $ atomically . writeTBQueue (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"
+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_ =
+ join <$> requestAndCommit c connId "ackMessage" markConnUserAck (\(_, rq, srvMsgId) -> ackQueueMessage c rq srvMsgId) recordAck
where
- ack :: AM () -> AM (Maybe ATransmission)
- ack afterAck =
+ recordAck :: Bool -> (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId) -> AM (Maybe ATransmission)
+ recordAck drained (duplexConn_, rq, srvMsgId) = do
+ t_ <- recordQueueAck c rq srvMsgId drained
+ mapM_ sendRcpt duplexConn_
+ t_ <$ del
+ markConnUserAck :: AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId))
+ markConnUserAck = do
+ SomeConn _ conn <- withStore c (`getConn` connId)
+ 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
withStore' c (\db -> setMsgUserAck db connId $ InternalId msgId) >>= \case
- Right (rq, srvMsgId) -> do
- t_ <- ackQueueMessage c rq srvMsgId
- afterAck
- t_ <$ del
+ Right (rq, srvMsgId) -> pure $ Just (duplexConn_, rq, srvMsgId)
Left (SEMsgNotFound _) -> Nothing <$ del
Left e -> throwE $ storeError e
del :: AM ()
@@ -2891,19 +2952,29 @@ 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', switchId) <- 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'
+ (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
-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
+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 (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
-- try to get the server that is different from all queues, or at least from the primary rcv queue
@@ -2913,12 +2984,24 @@ 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
+ 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 "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''
+ 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 =
@@ -2935,6 +3018,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
@@ -2968,23 +3052,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 (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 -> sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND
- Left (SMP _ SMP.NO_MSG) -> 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
@@ -2993,17 +3082,18 @@ 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
-- currently it is used only in tests
deleteConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM ()
deleteConnection' c nm connId = toConnResult connId =<< deleteConnections' c nm [connId]
@@ -3017,7 +3107,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' #-}
@@ -3047,7 +3136,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 ::
@@ -3062,8 +3151,7 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do
unsubNtfConnIds :: NonEmpty ConnId -> AM' ()
unsubNtfConnIds connIds' = do
ns <- asks ntfSupervisor
- atomically $ writeTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds')
- notify = atomically . writeTBQueue (subQ c)
+ liftIO $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds')
deleteConnQueues :: AgentClient -> NetworkRequestMode -> Bool -> Bool -> [RcvQueue] -> AM' (Map ConnId (Either AgentErrorType ()))
deleteConnQueues c nm waitDelivery ntf rqs = do
@@ -3123,7 +3211,10 @@ 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 $ 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'
@@ -3133,8 +3224,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
@@ -3779,6 +3870,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 +3913,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
@@ -4214,7 +4307,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
@@ -4408,11 +4501,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..3978592ac 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,
@@ -232,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)
@@ -332,6 +335,10 @@ 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))
@@ -386,6 +393,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
@@ -396,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,
@@ -556,10 +568,15 @@ 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
serviceRequests <- TM.emptyIO
+ rcvSwitches <- TM.emptyIO
smpServersStats <- TM.emptyIO
xftpServersStats <- TM.emptyIO
ntfServersStats <- TM.emptyIO
@@ -602,6 +619,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf
agentState,
getMsgLocks,
connLocks,
+#if defined(conn_lock_checks)
+ connLockHolders,
+ connLockViolations,
+#endif
invLocks,
deleteLock,
smpSubWorkers,
@@ -609,6 +630,7 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf
agentEnv,
proxySessTs,
serviceRequests,
+ rcvSwitches,
smpServersStats,
xftpServersStats,
ntfServersStats,
@@ -693,6 +715,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 +726,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 +896,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 +918,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 +1122,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' c@AgentClient {connLocks} connId name = withLockMap connLocks connId name . withLockHolder c name
{-# INLINE withConnLock' #-}
withInvLock :: AgentClient -> ByteString -> Text -> AM a -> AM a
@@ -1108,7 +1134,7 @@ withInvLock' AgentClient {invLocks} = withLockMap invLocks
{-# INLINE withInvLock' #-}
withConnLocks :: AgentClient -> Set ConnId -> Text -> AM' a -> AM' a
-withConnLocks AgentClient {connLocks} = withLocksMap connLocks
+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
@@ -1122,6 +1148,39 @@ withLocksMap = withGetLocks . getMapLock
getMapLock :: Ord k => TMap k Lock -> k -> IO Lock
getMapLock locks key = either id id <$> TM.lookupOrInsertIO key createLock locks
+#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 connLockHolders)
+ (\prev_ -> atomically $ TM.alter (const prev_) t connLockHolders)
+ (const a)
+
+checkNoConnLock :: AgentClient -> AM ()
+checkNoConnLock AgentClient {connLockHolders, connLockViolations} = do
+ t <- myThreadId
+ name_ <- liftIO $ TM.lookupIO t connLockHolders
+ forM_ name_ $ \name -> do
+ 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 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
+{-# 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
withClient_ c nm tSess@(_, srv, _) action = do
cl <- getProtocolServerClient c nm tSess
@@ -1643,7 +1702,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 +1900,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 +2177,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
diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs
index 41685f2e2..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
@@ -2756,11 +2769,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/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs
index 884e783d0..ca741f378 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,7 +154,8 @@ 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)
@@ -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
@@ -655,10 +662,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
@@ -712,15 +718,18 @@ 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 Nothing
+ 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
unexpected = unexpectedResponse respOrErr
@@ -763,6 +772,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.
@@ -859,36 +871,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 = atomically $ mapM_ (`writeTBQueue` 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)
@@ -901,7 +910,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 #-}
@@ -1104,7 +1113,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.
@@ -1344,19 +1353,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 +1374,40 @@ 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 =
+ -- two separate "atomically" needed to avoid blocking
+ case msgQ of
+ Just _ -> send >>= get
+ Nothing -> E.bracketOnError send (\_ -> atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands) get
+ where
+ 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} =
+ 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 +1416,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
@@ -1425,7 +1445,6 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentC
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/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
diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs
index 6c201c35d..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
@@ -97,7 +98,8 @@ 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.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 (..))
@@ -106,7 +108,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)
@@ -124,7 +126,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 (..))
@@ -278,6 +280,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)
@@ -365,6 +370,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
@@ -377,6 +384,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
@@ -429,6 +437,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
@@ -525,6 +537,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
@@ -549,6 +563,10 @@ functionalAPITests ps = do
it "should subscribe to multiple connections with pending messages" $
withSmpServer ps $
testBatchedPendingMessages 10 5
+ 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
it "should send multiple messages to the same connection" $ withSmpServer ps testSendMessagesB
it "should send messages to the 2 connections" $ withSmpServer ps testSendMessagesB2
@@ -565,6 +583,10 @@ 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 "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
@@ -583,6 +605,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" $
@@ -593,6 +619,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" $
@@ -603,6 +630,24 @@ 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 ratchet synchronization starts while the queue is created" $
+ 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" $
+ 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" $
+ 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" $
@@ -656,6 +701,15 @@ functionalAPITests ps = do
describe "getConnectionVerifyCodes" $
it "should return the same codes for both peers" $
withSmpServer ps testConnectionVerifyCodes
+ 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
+ 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
@@ -1170,6 +1224,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
+ pure ()
+ where
+ bServers = initAgentServers {smp = userServers [testSMPServer2]}
+
testDeleteAcceptedContactRequest :: (HasCallStack, HasTestEnv) => Bool -> Bool -> IO ()
testDeleteAcceptedContactRequest useDR asyncAccept =
withAgentClients2 $ \alice bob -> runRight_ $ do
@@ -1661,6 +1734,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 $ \_ ->
+ 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 resume ()
+ 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
@@ -3276,6 +3385,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 $ do
+ (aId, bId) <- makeConnection a b
+ exchangeGreetings a bId b aId
+ pure (aId, bId)
+ runRight_ $ do
+ msgId <- sendMessage a bId SMP.noMsgFlags "hello again"
+ get a ##> ("", bId, SENT msgId)
+ withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight_ $ do
+ ("", _, Msg' msgId _ "hello again") <- getMsg b aId $ get 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)
makeConnection = makeConnection_ PQSupportOn
@@ -3543,6 +3667,38 @@ testBatchedPendingMessages nCreate nMsgs =
("", cId, AEvt SAEConn (Msg' msgId _ "hello")) -> pure $ Right (cId, msgId)
r -> error $ "unexpected event: " <> show r
+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
+ 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
+ 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
+ resultSizeErr name = \case
+ ("", "", AEvt SAEConn (ERR (A.INTERNAL e))) -> (name <> " result size") `isPrefixOf` e
+ _ -> False
+
testSendMessagesB :: HasTestEnv => IO ()
testSendMessagesB = withAgentClients2 $ \a b -> runRight_ $ do
(aId, bId) <- makeConnection a b
@@ -3786,6 +3942,40 @@ 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
+ 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 ()
+testDeleteConnectionFullNtfQueue ps =
+ withSmpServer ps $
+ withAgent 1 agentCfg initAgentServers testDB $ \a -> do
+ (connId, _) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe
+ 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
+
+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
+ q = subQ c
+ fill = unlessM (isFullTBQueue q) $ writeTBQueue q ("", "", AEvt SAENone SUSPENDED) >> fill
+
testWaitDeliveryNoPending :: HasTestEnv => (ASrvTransport, AStoreType) -> IO ()
testWaitDeliveryNoPending ps = withAgentClients2 $ \alice bob ->
withSmpServerStoreLogOn ps testPort $ \_ -> runRight_ $ do
@@ -4079,6 +4269,23 @@ 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]
+ withFullSubQ a $ timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ())
+ 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_")
+ 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 ()
testUsersNoServer ps = withAgentClientsCfg2 aCfg agentCfg $ \a b -> do
(aId, bId, auId, _aId', bId') <- withSmpServerStoreLogOn ps testPort $ \_ -> runRight $ do
@@ -4215,6 +4422,245 @@ 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
+
+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
+ 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 $ synchronizeRatchet b aId PQSupportOn True
+ atomically $ putTMVar resume ()
+ 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)
+
+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)
+
+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 $
+ 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)
+
+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 $
+ 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 $ \_ ->
+ 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 resume ()
+ 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 $
+ 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 ())
+
+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]
+ phaseSnd b aId SPConfirmed [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
@@ -4687,6 +5133,70 @@ testConnectionVerifyCodes =
codes1'' <- getConnectionVerifyCodes a bId
liftIO $ codes1'' `shouldBe` codes1
+#if defined(conn_lock_checks)
+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"]
+#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 ())
+
+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
@@ -5389,6 +5899,22 @@ 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
+ withFullSubQ service $ timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ())
+ 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/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs
index accf6723f..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,
@@ -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,16 @@ 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)
+ withFullNtfSubQ a $ timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ())
+
testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO ()
testNotificationsOldToken apns =
withAgentClients3 $ \a b c -> runRight_ $ do
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/SMPClient.hs b/tests/SMPClient.hs
index 24f49cea7..80fc06fef 100644
--- a/tests/SMPClient.hs
+++ b/tests/SMPClient.hs
@@ -24,7 +24,7 @@ import qualified Data.X509 as X
import qualified Data.X509.File as XF
import qualified Data.X509.Validation as XV
import Network.Socket
-import Network.Socket.ByteString (recv)
+import Network.Socket.ByteString (recv, sendAll)
import qualified Network.TLS as TLS
import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..))
import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..))
@@ -45,6 +45,7 @@ import Simplex.Messaging.Version
import Simplex.Messaging.Version.Internal
import System.Directory (copyFile, removeFile)
import Test.Hspec hiding (fit, it)
+import UnliftIO.Async (race_)
import UnliftIO.Concurrent
import qualified UnliftIO.Exception as E
import UnliftIO.STM (TMVar, atomically, checkSTM, newEmptyTMVarIO, orElse, putTMVar, readTMVar, readTVar, registerDelay, takeTMVar, tryPutTMVar)
@@ -81,6 +82,9 @@ testPort = testServerPort 1
testPort2 :: HasTestEnv => ServiceName
testPort2 = testServerPort 2
+testPort3 :: HasTestEnv => ServiceName
+testPort3 = testServerPort 8
+
ntfTestPort :: HasTestEnv => ServiceName
ntfTestPort = testServerPort 3
@@ -494,6 +498,22 @@ withStallingServerOn' port action = do
(pure ())
(const $ action accepted closed)
+withPausedProxyOn :: HasCallStack => ServiceName -> ServiceName -> (TMVar () -> TMVar () -> IO a) -> IO a
+withPausedProxyOn port srvPort action = do
+ accepted <- 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 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 resume)
+
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 02b87a0e0..8920432b5 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 "delivers late response to the message queue" $ \_ ->
+ testLateResponseDelivered
describe "agent client reconnection" $ do
it "reconnects after a connect is cancelled mid-flight" $ \_ ->
testAgentClientReconnectAfterCancel
@@ -623,6 +629,48 @@ 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
+
+testLateResponseDelivered :: HasTestEnv => IO ()
+testLateResponseDelivered =
+ withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do
+ g <- C.newRandom
+ ts <- getCurrentTime
+ msgQ <- newTBQueueIO 4
+ 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
+ (_, _, [(_, STResponse _ (Left (PCEProtocolError SMP.AUTH)))]) <- atomically $ readTBQueue msgQ
+ pClientSentCommandsCount c `shouldReturn` 0
+
-- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an
-- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which
-- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is