diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c835a6829..1ed4a9e24 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -33,6 +33,7 @@ jobs: runs-on: ubuntu-latest outputs: reduced: ${{ github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == true || (github.event_name == 'push' && github.ref_type == 'branch' && github.repository != 'simplex-chat/simplexmq') }} + resolver: ${{ steps.changes.outputs.resolver }} steps: - name: Reject a manual run on a tag if: github.event_name == 'workflow_dispatch' && github.ref_type == 'tag' @@ -40,6 +41,33 @@ jobs: echo "::error::A manual run starts on a branch; to retry a release, re-run the jobs of its tag push." exit 1 + - name: Clone project to check changes + if: github.event_name != 'push' + uses: actions/checkout@v3 + with: + fetch-depth: 2 + + - name: Check changes + id: changes + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + case "$GITHUB_EVENT_NAME" in + pull_request) + base=HEAD^1 + ;; + workflow_dispatch) + base=$(gh api "repos/$GITHUB_REPOSITORY/compare/master...$GITHUB_REF_NAME" --jq .merge_base_commit.sha) + git fetch -q --depth=1 origin "$base" + ;; + *) + echo "resolver=true" >> "$GITHUB_OUTPUT" + exit 0 + ;; + esac + git diff --quiet "$base" HEAD -- scripts/resolver/service .github/workflows/build.yml || echo "resolver=true" >> "$GITHUB_OUTPUT" + - name: Clone project if: startsWith(github.ref, 'refs/tags/v') uses: actions/checkout@v3 @@ -95,6 +123,7 @@ jobs: cache_o0: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/stable') }} image_cache: ghcr.io/${{ github.repository_owner }}/simplexmq-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }} source_hashes: dist-newstyle/sources.sha256 + resolver: ${{ needs.maybe-release.outputs.resolver == 'true' && matrix.os == '24.04' && matrix.arch == 'x86-64' }} runs-on: ${{ matrix.runner }} services: &build-services postgres: @@ -158,6 +187,47 @@ jobs: with: submodules: recursive + - name: Set up uv + if: env.resolver == 'true' + # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Lint resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + run: uv run --frozen ruff check . + + - name: Set up Node + if: env.resolver == 'true' + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Build SNRC contracts + if: env.resolver == 'true' + env: + SNRC_CONTRACTS: ${{ runner.temp }}/snrc + SNRC_CONTRACTS_REPO: https://github.com/brenzi-agent/simplex-namespace-contract + SNRC_CONTRACTS_COMMIT: ac7c68789b129de925a876b1eafa320c6a095693 + COREPACK_ENABLE_DOWNLOAD_PROMPT: 0 + run: | + git clone -q --filter=blob:none "$SNRC_CONTRACTS_REPO" "$SNRC_CONTRACTS" + cd "$SNRC_CONTRACTS" + git checkout -q "$SNRC_CONTRACTS_COMMIT" + git submodule -q update --init --filter=blob:none ens-contracts + corepack enable + pnpm install --frozen-lockfile + cd ens-contracts + pnpm install --frozen-lockfile + pnpm exec hardhat compile + + - name: Test resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + env: + SNRC_CONTRACTS: ${{ runner.temp }}/snrc + run: uv run --frozen pytest -v + - name: Set up Docker Buildx if: matrix.should_run == true uses: simplex-chat/docker-setup-buildx-action@v3 @@ -296,11 +366,7 @@ jobs: if: matrix.should_run == true && matrix.client_postgres == true shell: docker exec -t builder sh -eu {0} run: | - 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 - mkdir -p /out + cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks ${{ env.ghc_options }} simplexmq-test bin=$(find /project/dist-client-postgres -name simplexmq-test -type f -executable) cp "$bin" /out/simplexmq-test-client-postgres @@ -503,10 +569,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 - else - cabal build --builddir=dist-postgres --jobs=$(nproc) --enable-tests -fserver_postgres --ghc-options=-O0 - cabal build --jobs=$(nproc) --ghc-options=-O0 + cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks --ghc-options=-O0 simplexmq-test fi - name: Record source hashes for -O0 build (GHC 8.10.7) @@ -552,29 +615,3 @@ jobs: should_run: true client_postgres: true steps: *build-steps - -# ============================= -# Resolver test job -# ============================= - -# The SNRC resolver is Python, so this job needs none of the Haskell toolchain -# above and runs independently of it. - - resolver-test: - name: "resolver (python)" - runs-on: ubuntu-latest - steps: - - name: Clone project - uses: actions/checkout@v3 - - - name: Set up uv - # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - - - name: Lint - working-directory: scripts/resolver/service - run: uv run --frozen ruff check . - - - name: Test - working-directory: scripts/resolver/service - run: uv run --frozen pytest -v diff --git a/.github/workflows/resolver-mainnet.yml b/.github/workflows/resolver-mainnet.yml new file mode 100644 index 000000000..e4411a733 --- /dev/null +++ b/.github/workflows/resolver-mainnet.yml @@ -0,0 +1,26 @@ +name: resolver mainnet + +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + pull_request: + paths: + - .github/workflows/resolver-mainnet.yml + +jobs: + mainnet: + name: "resolver on mainnet" + runs-on: ubuntu-latest + steps: + - name: Clone project + uses: actions/checkout@v3 + + - name: Set up uv + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Test known names + working-directory: scripts/resolver/service + env: + SNRC_MAINNET_RPC: ${{ secrets.SNRC_MAINNET_RPC || 'https://ethereum-rpc.publicnode.com' }} + run: uv run --frozen pytest -v test_ground_truth.py -k MainnetTests diff --git a/Dockerfile b/Dockerfile index 06b59e6e1..89310f553 100644 --- a/Dockerfile +++ b/Dockerfile @@ -45,6 +45,9 @@ WORKDIR /project ARG APP RUN if [ -z "$APP" ]; then printf "Please spcify \$APP build-arg.\n"; exit 1; fi +# Check that git submodules are checked out +RUN if [ ! -f cbits/blst/src/server.c ] || [ ! -f cbits/libbbs/src/bbs.c ]; then printf "Git submodules are missing, run: git submodule update --init --recursive\n"; exit 1; fi + # Compile app RUN cabal update RUN cabal build exe:$APP diff --git a/README.md b/README.md index 3ece2a4c2..3d4116a57 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im - `smp-server` - You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -125,12 +125,13 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im -p 5223:5223 \ -v $HOME/simplex/smp/config:/etc/opt/simplex:z \ -v $HOME/simplex/smp/logs:/var/opt/simplex:z \ + -u "non_root_user_id" simplexchat/smp-server:latest ``` - `xftp-server` - You must change **your_ip_or_domain** and **maximum_storage**. + You must change **your_ip_or_domain** and **maximum_storage**. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -139,6 +140,7 @@ On Linux, you can deploy smp and xftp server using Docker. This will download im -v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/files:/srv/xftp:z \ + -u "non_root_user_id" simplexchat/xftp-server:latest ``` @@ -174,8 +176,9 @@ On Linux, you can build smp server using Docker. git clone https://github.com/simplex-chat/simplexmq cd simplexmq git checkout stable - DOCKER_BUILDKIT=1 docker build -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For xmp-server - DOCKER_BUILDKIT=1 docker build -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server + git submodule update --init --recursive + DOCKER_BUILDKIT=1 docker build --network=host -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For smp-server + DOCKER_BUILDKIT=1 docker build --network=host -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server ``` 2. Create directories for persistent Docker configuration: @@ -188,7 +191,7 @@ On Linux, you can build smp server using Docker. - `smp-server` - You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server: + You must change **your_ip_or_domain**. `-e "PASS=password"` is optional variable to password-protect your `smp` server. Passwords can contain printable ASCII characters except whitespace, `@`, `:` and `/`. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -196,12 +199,13 @@ On Linux, you can build smp server using Docker. -p 5223:5223 \ -v $HOME/simplex/smp/config:/etc/opt/simplex:z \ -v $HOME/simplex/smp/logs:/var/opt/simplex:z \ + -u "non_root_user_id" simplexchat/smp-server:latest ``` - `xftp-server` - You must change **your_ip_or_domain** and **maximum_storage**. + You must change **your_ip_or_domain** and **maximum_storage**. Run the container as a non-root user (`-u "non_root_user_id"`) with ownership of the mounted directories to mitigate privilege escalation. ```sh docker run -d \ -e "ADDR=your_ip_or_domain" \ @@ -210,6 +214,7 @@ On Linux, you can build smp server using Docker. -v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \ -v $HOME/simplex/xftp/files:/srv/xftp:z \ + -u "non_root_user_id" simplexchat/xftp-server:latest ``` @@ -234,6 +239,7 @@ On Linux, you can build smp server using Docker. git clone https://github.com/simplex-chat/simplexmq cd simplexmq git checkout stable + git submodule update --init --recursive cabal update cabal build exe:smp-server exe:xftp-server ``` diff --git a/cbits/libbbs b/cbits/libbbs index 5a51a4307..59a0f4bf3 160000 --- a/cbits/libbbs +++ b/cbits/libbbs @@ -1 +1 @@ -Subproject commit 5a51a4307e7983d76165e654f34507def5ed409f +Subproject commit 59a0f4bf32e195cb6883de8374825c0f4764c717 diff --git a/plans/2026-10-23-server-stats-persistence-design.md b/plans/2026-10-23-server-stats-persistence-design.md new file mode 100644 index 000000000..d30290714 --- /dev/null +++ b/plans/2026-10-23-server-stats-persistence-design.md @@ -0,0 +1,227 @@ +# SMP server stats persistence + +## Problem + +SMP server stats live in `IORef`s and are written to `smp-server-stats.log` only on clean shutdown or the control port `save` command (`saveServer`, `Server.hs:240`, `Server.hs:1036`). At startup the file is restored and renamed to `.bak` (`Server.hs:2540`), so no stats file exists while the server runs. A crash loses all stats since start, including lifetime counters (`*_services_assoc_*`, `*_services_sub_*`, `ntfNewCreated`, `msgSentBlock`) and the active-queue period sets. Without the file, `qCount` and `ntfCount` start from 0 and drift, and `msgCount` stays wrong until the first expiration run (`Server.hs:491`). + +## Goals + +- Crash loses at most one save interval of stats. +- Postgres-mode servers keep stats in the database, covered by database backups. +- Memory-mode servers keep stats in the file, written atomically. +- `qCount`, `msgCount`, `ntfCount` are correct after every start. + +## Non-goals + +- Persisting counters that the file does not persist today (`srvSubOk/More/Fewer/Diff/*Total`, `rcvServicesSubMsg`, `rcvServicesSubDuplicate`, `authDelayExceeded`, `cmdSlotWait*`, `msgRecvAckTimes`). +- XFTP and notification server stats. +- Resetting week/month sets when the server is down on a Monday or the 1st (existing behaviour). + +## Configuration + +- `ServerConfig.statsSaveInterval :: Int64`, seconds. +- INI `[STORE_LOG] stats_save_interval`, default 300. Generated ini gets `# stats_save_interval = 300` next to `prometheus_interval` (`Main/Init.hs:107`). +- Persistence is active only when `serverStatsBackupFile` is set (`log_stats = on`), as today. The same path is the memory-mode stats file and the Postgres-mode import source. + +## Architecture + +New module `Simplex.Messaging.Server.StatsStore`: + +```haskell +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath -- import source +#endif +``` + +`Env` selects the backend from `ServerStoreCfg`: `SSCMemory` gives `StatsFile`, `SSCDatabase` gives `StatsDB` with the queue store's `DBStore`. Queue and message store classes are unchanged. The module exposes load and save functions; `Server.hs` does not branch on the backend. + +### PeriodStats + +Each of `day`, `week`, `month` in `PeriodStats` gets a pending `IORef IntSet` of hashes added since the last successful save, and a pending-reset flag. `updatePeriodStats` inserts into the pending set when it inserts into the main set. A reset (rollover) empties the main and pending sets and sets the flag. + +The six persisted sets are identified by `PeriodSet`: + +| `PeriodSet` | value | source | +|---|---|---| +| `PSMsgDay` | 1 | `activeQueues.day` | +| `PSMsgWeek` | 2 | `activeQueues.week` | +| `PSMsgMonth` | 3 | `activeQueues.month` | +| `PSNtfDay` | 4 | `activeQueuesNtf.day` | +| `PSNtfWeek` | 5 | `activeQueuesNtf.week` | +| `PSNtfMonth` | 6 | `activeQueuesNtf.month` | + +## Data flow + +### Startup (replaces `restoreServerStats`) + +Postgres mode: +1. If the `server_stats` row exists, load it and load `server_stats_queues` into the six sets. A load error logs and exits. +2. Else if the file exists, parse it (parse error logs and exits), write the row and all set hashes in one transaction, rename the file to `.bak`. +3. Else start with empty stats. + +A file present together with an existing row is ignored and left in place, with a warning in the log. + +Memory mode: if the file exists, load it without renaming; else start with empty stats. + +In all cases, after loading: +- `qCount` is set from `getEntityCounts`, `msgCount` from the message restore stats, `ntfCount` from the notification restore stats. +- `msgExpired` and `msgNtfExpired` add the counts expired during startup, as `restoreServerStats` does today. + +### Save + +`saveStatsThread` runs every `statsSaveInterval` seconds. Shutdown (`saveServer`) and control port `save` run the same save. Every save and the rollover hold `savingLock`. The save function does not take the lock itself: `stopServer` and control `save` already hold it around `saveServer`, and the rollover calls save twice inside one lock. + +Postgres mode, one transaction: +1. For each set with the pending-reset flag: `DELETE FROM server_stats_queues WHERE period_set = ?`. +2. For each set: `INSERT INTO server_stats_queues (period_set, queue_hash) SELECT ?, unnest(?::BIGINT[]) ON CONFLICT DO NOTHING` with the swapped-out pending hashes. +3. `INSERT ... ON CONFLICT (server_stats_id) DO UPDATE` of all counter columns and `saved_at`. + +On commit the pending-reset flags are cleared. On failure the swapped-out pending hashes are merged back into the pending sets, flags stay set, the error is logged, and the next save retries. + +Memory mode: write `strEncode` of `ServerStatsData` to `.tmp`, then rename over ``. On failure, log, remove the temp file, keep the old file. + +### Daily rollover (`logServerStats`) + +Under `savingLock`: +1. Save, flushing pending hashes of the ending period. +2. Swap counters and write the daily line as today; reset the day sets, the week sets on Monday, the month sets on the 1st, setting their pending-reset flags. +3. Save, deleting the reset sets' rows and storing the zeroed counters. + +A crash between steps 2 and 3 restores pre-rollover counters, and the next daily line counts them twice; the window is one save. + +## Schema + +Migration `20261023_server_stats` in `QueueStore/Postgres/Migrations.hs`; down migration drops both tables; `server_schema.sql` regenerated. + +```sql +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); +``` + +Times are epoch seconds, as in existing tables. `qCount`, `msgCount`, `ntfCount` are not stored; they are recomputed at startup. + +Expected size at month end on current servers (1.5M monthly and 1.3M notification monthly queues mid-month, Oct 14): 4–6M hash rows, 300–400MB with the primary key index. Each save inserts only new hashes. + +Manual correction, with the server stopped: + +```sql +UPDATE server_stats SET rcv_services_assoc_new = rcv_services_assoc_new + 835795; +``` + +## Error handling + +| Failure | Behaviour | +|---|---| +| DB load at startup | Log, exit. Starting with zeros would overwrite the row on the first save. | +| File parse at startup or import | Log, exit (as today). | +| Periodic DB save | Log, merge pending hashes back, keep reset flags, retry next interval. | +| Memory file write | Log, remove temp file, keep old file. | +| Shutdown save | Log. | + +## Testing + +In `tests/ServerTests.hs`, next to the existing stats tests (`:1049`, `:1196`): + +1. Memory mode, 1s interval: after activity, the file read while the server runs has matching counters; a restart from a copy of that mid-run file restores them; the file is not renamed. +2. Postgres: while the server runs, the `server_stats` row and `server_stats_queues` counts per set match the activity. +3. Postgres import: file and no row produce the row with file values and a `.bak` file; file and existing row keep the row and leave the file in place. +4. No stats source with existing queues and messages: `qCount`, `msgCount`, `ntfCount` equal store counts. +5. `StatsStore` against Postgres: save/load round trip; pending hashes merged back after a failed save; reset flags delete only the flagged sets; load after rollover returns only new-period hashes. +6. Pure functions: pending-hash merge and pending-reset flag handling. + +Postgres tests run with `-fserver_postgres`, as existing ones do. diff --git a/plans/2026-10-23-server-stats-persistence-implementation-plan.md b/plans/2026-10-23-server-stats-persistence-implementation-plan.md new file mode 100644 index 000000000..f071efc7a --- /dev/null +++ b/plans/2026-10-23-server-stats-persistence-implementation-plan.md @@ -0,0 +1,1594 @@ +# SMP Server Stats Persistence Implementation Plan + +**Goal:** SMP server stats survive crashes: periodic saves to Postgres (Postgres mode) or an atomically written file (memory mode), with active-queue sets saved incrementally. + +**Architecture:** A new `Simplex.Messaging.Server.StatsStore` module loads and saves `ServerStatsData` through a file or a database backend. `PeriodStats` tracks hashes added since the last save so the database receives only new hashes. `Server.hs` restores on start, recomputes store counts, saves on a timer, around the daily rollover, and on shutdown, all under `savingLock`. + +**Tech Stack:** Haskell (GHC 9.6.3), postgresql-simple, hspec, cabal with `-fserver_postgres`. + +**Spec:** `plans/2026-10-23-server-stats-persistence-design.md` + +## Global Constraints + +- Build and test with `-fserver_postgres`; PostgreSQL must run on `localhost:5432` (see `contributing/PROJECT.md`). Use the same flags for every command so cabal does not rebuild between steps: `cabal build -fserver_postgres --ghc-options=-O0`, `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="..."`. +- Never wait with `sleep`/polling loops; run commands in the foreground with a timeout. +- Format changed Haskell with fourmolu (`fourmolu -i `); files with CPP (`Server.hs`, `Env/STM.hs`, `StatsStore.hs`, test files with CPP) are formatted by fragment, matching surrounding style. +- No new compiler warnings (library uses `-Weverything`); imports used only under `dbServerPostgres` go inside the `#if defined(dbServerPostgres)` block. +- Comments only where code cannot state it (ordering, invariants); no plan/spec references in code. +- Commit messages: `: `, max 50 chars, imperative, no body, no co-author. +- `server_stats_queues.period_set` values are fixed: 1 msg day, 2 msg week, 3 msg month, 4 ntf day, 5 ntf week, 6 ntf month. +- Column order of `server_stats` in the migration, `statsFields`, and the `FromRow StatsRow` instance must be identical. +- Default save interval 300 seconds, INI key `[STORE_LOG] stats_save_interval`. + +**User decisions (already made):** +- Postgres-mode servers store stats in a Postgres table; the existing file is imported once when the database has no stats row, then renamed to `.bak`; afterwards the database is the only source and corrections are done with SQL. +- One `BIGINT` column per persisted metric (not a text blob or JSONB). +- Active-queue sets are stored incrementally in a hash table (`server_stats_queues`), only new hashes inserted per save, rows of reset sets deleted. +- Memory-mode servers save the file periodically with temp file + rename and no longer rename it to `.bak` at startup. +- Scope: the metrics persisted in the file today, plus recomputing `qCount`/`msgCount`/`ntfCount` from the store on every start. +- Save interval is an INI option with default 300 seconds, active only when `log_stats = on`. + +--- + +## File Structure + +| File | Responsibility | +|---|---| +| `src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs` | New migration `20261023_server_stats` | +| `src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql` | Regenerated schema dump | +| `src/Simplex/Messaging/Server/Env/STM.hs` | `statsSaveInterval` config, `defStatsSaveInterval`, pending tracking switch in `newEnv` | +| `src/Simplex/Messaging/Server/Main.hs`, `Main/Init.hs` | INI option read and generated ini comment | +| `src/Simplex/Messaging/Server/Stats.hs` | Pending hashes in `PeriodStats`, `newServerStats` switch | +| `src/Simplex/Messaging/Server/StatsStore.hs` (new) | Load/save stats via file or database | +| `src/Simplex/Messaging/Server.hs` | Restore, periodic save thread, rollover and shutdown saves | +| `simplexmq.cabal` | New library module and test module | +| `tests/CoreTests/ServerStatsTests.hs` (new) | Pending tracking, file and database store tests | +| `tests/ServerTests.hs`, `tests/SMPClient.hs`, `tests/Test.hs` | Server-level tests, test config, registration | + +--- + +### Task 1: Add server_stats schema migration + +**Goal:** Postgres tables for persisted stats exist and the schema dump matches. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs` (migration list at the top; definitions appended at the end of the file) +- Modify: `src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql` (regenerated by the schema dump test) + +**Acceptance Criteria:** +- [ ] `server_stats` has `server_stats_id SMALLINT PRIMARY KEY CHECK (server_stats_id = 1)`, `saved_at`, `from_time` and 84 counter columns, all `BIGINT NOT NULL` +- [ ] `server_stats_queues(period_set SMALLINT, queue_hash BIGINT, PRIMARY KEY (period_set, queue_hash))` +- [ ] Down migration drops both tables +- [ ] `/SMP server schema dump/` tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server schema dump/"` → 2 examples, 0 failures (second run, after the first run rewrote the dump) + +**Steps:** + +- [ ] **Step 1: Register the migration** + +In `serverSchemaMigrations`, after the `20260918_expire_messages` entry: + +```haskell + ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), + ("20261023_server_stats", m20261023_server_stats, Just down_m20261023_server_stats) + ] +``` + +- [ ] **Step 2: Append migration definitions at the end of the file** + +```haskell +m20261023_server_stats :: Text +m20261023_server_stats = + [r| +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); + |] + +down_m20261023_server_stats :: Text +down_m20261023_server_stats = + [r| +DROP TABLE server_stats_queues; + +DROP TABLE server_stats; + |] +``` + +- [ ] **Step 3: Run the schema dump test to regenerate the dump** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server schema dump/"` +Expected: "verify and overwrite schema dump" FAILS once (dump differs) and rewrites `server_schema.sql`; "verify schema down migrations" passes. + +- [ ] **Step 4: Run it again** + +Run the same command. +Expected: 2 examples, 0 failures. `git diff --stat` shows `server_schema.sql` with the two new tables and their primary keys only. + +- [ ] **Step 5: Commit** + +```bash +git add src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +git commit -m "smp server: add server_stats tables" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs", "src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/SMP server schema dump/\"", "acceptanceCriteria": ["server_stats singleton row with 84 counter columns", "server_stats_queues with composite PK", "down migration drops both tables", "schema dump tests pass"], "modelTier": "mechanical"} +``` + +--- + +### Task 2: Add stats_save_interval config option + +**Goal:** `ServerConfig.statsSaveInterval` is read from `[STORE_LOG] stats_save_interval` (default 300) and documented in the generated ini. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/Env/STM.hs` (export list near `defNtfExpirationHours`; constants after `defaultNtfExpiration`; `ServerConfig` after `serverStatsBackupFile`) +- Modify: `src/Simplex/Messaging/Server/Main.hs:497` (config record) +- Modify: `src/Simplex/Messaging/Server/Main/Init.hs:106-108` (ini text) +- Modify: `tests/SMPClient.hs:266` (test config) + +**Acceptance Criteria:** +- [ ] `defStatsSaveInterval = 300` exported from `Env.STM` +- [ ] `statsSaveInterval` read with `readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval"` +- [ ] Generated ini contains `# stats_save_interval = 300` after `# prometheus_interval = 60` +- [ ] `/Server CLIs/` tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Server CLIs/"` → 0 failures + +**Steps:** + +- [ ] **Step 1: Config field and default in `Env/STM.hs`** + +Export list, after `defNtfExpirationHours,`: + +```haskell + defNtfExpirationHours, + defStatsSaveInterval, +``` + +After the `defaultNtfExpiration` definition: + +```haskell +defStatsSaveInterval :: Int64 +defStatsSaveInterval = 300 +``` + +In `ServerConfig`, after `serverStatsBackupFile`: + +```haskell + -- | file to save and restore stats + serverStatsBackupFile :: Maybe FilePath, + -- | interval to save stats, seconds + statsSaveInterval :: Int64, +``` + +- [ ] **Step 2: Read the option in `Main.hs`** + +After `serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log",`: + +```haskell + serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log", + statsSaveInterval = readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini, +``` + +- [ ] **Step 3: Document it in the generated ini (`Main/Init.hs`)** + +Replace: + +```haskell + <> "# Log interval for real-time Prometheus metrics\n\ + \# prometheus_interval = 60\n\n\ + \[AUTH]\n\ +``` + +with: + +```haskell + <> "# Log interval for real-time Prometheus metrics\n\ + \# prometheus_interval = 60\n\n" + <> "# Interval to save server statistics, seconds (requires log_stats)\n" + <> ("# stats_save_interval = " <> tshow defStatsSaveInterval <> "\n\n") + <> "[AUTH]\n\ +``` + +The rest of the `[AUTH]` literal stays unchanged. + +- [ ] **Step 4: Test config (`tests/SMPClient.hs`, `cfgMS`)** + +After `serverStatsBackupFile = Nothing,`: + +```haskell + serverStatsBackupFile = Nothing, + statsSaveInterval = defStatsSaveInterval, +``` + +`SMPClient.hs` already imports `Simplex.Messaging.Server.Env.STM` unqualified. + +- [ ] **Step 5: Build and run CLI tests** + +Run: `cabal build -fserver_postgres --ghc-options=-O0 all` +Expected: builds with no new warnings. +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Server CLIs/"` +Expected: 0 failures. + +- [ ] **Step 6: Commit** + +```bash +git add src/Simplex/Messaging/Server/Env/STM.hs src/Simplex/Messaging/Server/Main.hs src/Simplex/Messaging/Server/Main/Init.hs tests/SMPClient.hs +git commit -m "smp server: add stats_save_interval option" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/Env/STM.hs", "src/Simplex/Messaging/Server/Main.hs", "src/Simplex/Messaging/Server/Main/Init.hs", "tests/SMPClient.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Server CLIs/\"", "acceptanceCriteria": ["defStatsSaveInterval = 300 exported", "statsSaveInterval read from STORE_LOG", "generated ini documents the option", "CLI tests pass"], "modelTier": "mechanical"} +``` + +--- + +### Task 3: Track pending active-queue hashes + +**Goal:** `PeriodStats` optionally records hashes added and sets reset since the last save; SMP `ServerStats` enables it only for Postgres-mode servers with stats persistence. + +**Files:** +- Modify: `src/Simplex/Messaging/Server/Stats.hs` (export list; `newServerStats`; `PeriodStats`; `newPeriodStats`; `periodStatCounts`; `updatePeriodStats`) +- Modify: `src/Simplex/Messaging/Server/Env/STM.hs:548,574` (`newEnv`) +- Create: `tests/CoreTests/ServerStatsTests.hs` +- Modify: `tests/Test.hs` (import and `describe` in "Core tests"), `simplexmq.cabal` (test `other-modules`, after `CoreTests.SOCKSSettings`) + +**Acceptance Criteria:** +- [ ] `newPeriodStats` has no pending tracking (XFTP and NTF servers unchanged) +- [ ] `newPendingPeriodStats` records each hash once per period until taken +- [ ] Day reset always, week reset on Monday, month reset on the 1st set `pendingReset = True` and clear `pendingAdded` +- [ ] `restorePendingHashes` merges taken hashes back (union, reset flags OR-ed) +- [ ] `newEnv` enables tracking only when `serverStatsBackupFile` is set and the store is Postgres +- [ ] `/Core tests/Server stats tests/pending period stats/` pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` → 4 examples, 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing tests** + +Create `tests/CoreTests/ServerStatsTests.hs`: + +```haskell +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +module CoreTests.ServerStatsTests where + +import Data.Hashable (hash) +import Data.IORef +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.Maybe (isNothing) +import Data.Time.Calendar (fromGregorian) +import Data.Time.Clock (UTCTime (..)) +import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Server.Stats +import Test.Hspec hiding (fit, it) +import Util + +serverStatsTests :: Spec +serverStatsTests = + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + +q1, q2, q3, q4, q5 :: EntityId +q1 = EntityId "queue1" +q2 = EntityId "queue2" +q3 = EntityId "queue3" +q4 = EntityId "queue4" +q5 = EntityId "queue5" + +hashes :: [EntityId] -> IntSet +hashes = IS.fromList . map (hash . unEntityId) + +utcDay :: Integer -> Int -> Int -> UTCTime +utcDay y m d = UTCTime (fromGregorian y m d) 3600 + +-- 2026-06-10 is Wednesday, 2026-06-08 is Monday, 2026-06-01 is Monday and the 1st +wednesday, monday, monday1st :: UTCTime +wednesday = utcDay 2026 6 10 +monday = utcDay 2026 6 8 +monday1st = utcDay 2026 6 1 + +noPending :: PendingHashes +noPending = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +resetPending :: PendingHashes +resetPending = PendingHashes {pendingReset = True, pendingAdded = IS.empty} + +added :: [EntityId] -> PendingHashes +added qs = PendingHashes {pendingReset = False, pendingAdded = hashes qs} + +testNoPending :: IO () +testNoPending = do + ps <- newPeriodStats + isNothing (pendingPeriods ps) `shouldBe` True + updatePeriodStats ps q1 + readIORef (day ps) `shouldReturn` hashes [q1] + ServerStats {activeQueues, activeQueuesNtf} <- newServerStats False wednesday + isNothing (pendingPeriods activeQueues) `shouldBe` True + isNothing (pendingPeriods activeQueuesNtf) `shouldBe` True + +testPendingAdded :: IO () +testPendingAdded = do + ServerStats {activeQueues = ps} <- newServerStats True wednesday + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + mapM_ (updatePeriodStats ps) [q1, q2, q1] + takePendingHashes pendingDay `shouldReturn` added [q1, q2] + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q1 + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q3 + takePendingHashes pendingDay `shouldReturn` added [q3] + takePendingHashes pendingWeek `shouldReturn` added [q1, q2, q3] + takePendingHashes pendingMonth `shouldReturn` added [q1, q2, q3] + readIORef (day ps) `shouldReturn` hashes [q1, q2, q3] + +testPendingReset :: IO () +testPendingReset = do + ps <- newPendingPeriodStats + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + updatePeriodStats ps q1 + PeriodStatCounts {dayCount, weekCount, monthCount} <- periodStatCounts ps wednesday + (dayCount, weekCount, monthCount) `shouldBe` ("1", "", "") + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` added [q1] + takePendingHashes pendingMonth `shouldReturn` added [q1] + updatePeriodStats ps q2 + _ <- periodStatCounts ps monday + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` resetPending + takePendingHashes pendingMonth `shouldReturn` added [q2] + readIORef (month ps) `shouldReturn` hashes [q1, q2] + updatePeriodStats ps q3 + _ <- periodStatCounts ps monday1st + mapM takePendingHashes [pendingDay, pendingWeek, pendingMonth] `shouldReturn` [resetPending, resetPending, resetPending] + mapM readIORef [day ps, week ps, month ps] `shouldReturn` [IS.empty, IS.empty, IS.empty] + updatePeriodStats ps q4 + takePendingHashes pendingMonth `shouldReturn` added [q4] + +testMergePending :: IO () +testMergePending = do + mergePendingHashes (added [q1]) (added [q2]) `shouldBe` added [q1, q2] + mergePendingHashes resetPending (added [q2]) `shouldBe` PendingHashes {pendingReset = True, pendingAdded = hashes [q2]} + ref <- newIORef $ added [q5] + restorePendingHashes ref PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4]} + readIORef ref `shouldReturn` PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4, q5]} +``` + +Register it. In `tests/Test.hs` imports, after `import CoreTests.SOCKSSettings`: + +```haskell +import CoreTests.SOCKSSettings +import CoreTests.ServerStatsTests +``` + +In "Core tests", after `describe "Message store tests" msgStoreTests`: + +```haskell + describe "Message store tests" msgStoreTests + describe "Server stats tests" serverStatsTests +``` + +In `simplexmq.cabal` test-suite `other-modules`, after `CoreTests.SOCKSSettings`: + +``` + CoreTests.SOCKSSettings + CoreTests.ServerStatsTests +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: compile error — `pendingPeriods`, `PendingPeriods`, `PendingHashes`, `takePendingHashes`, `newPendingPeriodStats`, `mergePendingHashes`, `restorePendingHashes` not in scope; `newServerStats` applied to too many arguments. + +- [ ] **Step 3: Implement pending tracking in `Stats.hs`** + +Export list, replace `newPeriodStats,` with: + +```haskell + newPeriodStats, + newPendingPeriodStats, + PendingPeriods (..), + PendingHashes (..), + takePendingHashes, + restorePendingHashes, + mergePendingHashes, +``` + +`newServerStats`: change the signature and the two `PeriodStats` allocations, and add a `where`: + +```haskell +newServerStats :: Bool -> UTCTime -> IO ServerStats +newServerStats trackPending ts = do +``` + +```haskell + activeQueues <- newActiveQueues +``` + +```haskell + activeQueuesNtf <- newActiveQueues +``` + +and after the final `pure ServerStats {...}` expression of `newServerStats`: + +```haskell + rslvStats + } + where + newActiveQueues = if trackPending then newPendingPeriodStats else newPeriodStats +``` + +Replace the `PeriodStats` type and `newPeriodStats`: + +```haskell +data PeriodStats = PeriodStats + { day :: IORef IntSet, + week :: IORef IntSet, + month :: IORef IntSet, + pendingPeriods :: Maybe PendingPeriods + } + +-- hashes added and sets reset since the last successful save +data PendingPeriods = PendingPeriods + { pendingDay :: IORef PendingHashes, + pendingWeek :: IORef PendingHashes, + pendingMonth :: IORef PendingHashes + } + +data PendingHashes = PendingHashes + { pendingReset :: Bool, + pendingAdded :: IntSet + } + deriving (Eq, Show) + +newPeriodStats :: IO PeriodStats +newPeriodStats = newPeriodStats_ Nothing + +newPendingPeriodStats :: IO PeriodStats +newPendingPeriodStats = do + pendingDay <- newIORef noPendingHashes + pendingWeek <- newIORef noPendingHashes + pendingMonth <- newIORef noPendingHashes + newPeriodStats_ $ Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} + +newPeriodStats_ :: Maybe PendingPeriods -> IO PeriodStats +newPeriodStats_ pendingPeriods = do + day <- newIORef IS.empty + week <- newIORef IS.empty + month <- newIORef IS.empty + pure PeriodStats {day, week, month, pendingPeriods} + +noPendingHashes :: PendingHashes +noPendingHashes = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +takePendingHashes :: IORef PendingHashes -> IO PendingHashes +takePendingHashes ref = atomicModifyIORef' ref (noPendingHashes,) + +restorePendingHashes :: IORef PendingHashes -> PendingHashes -> IO () +restorePendingHashes ref taken = atomicModifyIORef'_ ref $ mergePendingHashes taken + +mergePendingHashes :: PendingHashes -> PendingHashes -> PendingHashes +mergePendingHashes (PendingHashes r hs) (PendingHashes r' hs') = PendingHashes (r || r') (IS.union hs hs') +``` + +Replace `periodStatCounts`: + +```haskell +periodStatCounts :: PeriodStats -> UTCTime -> IO PeriodStatCounts +periodStatCounts ps ts = do + let d = utctDay ts + (_, wDay) = mondayStartWeek d + MonthDay _ mDay = d + pending_ = pendingPeriods ps + dayCount <- periodCount 1 (day ps) (pendingDay <$> pending_) + weekCount <- periodCount wDay (week ps) (pendingWeek <$> pending_) + monthCount <- periodCount mDay (month ps) (pendingMonth <$> pending_) + pure PeriodStatCounts {dayCount, weekCount, monthCount} + where + periodCount :: Int -> IORef IntSet -> Maybe (IORef PendingHashes) -> IO Text + periodCount 1 ref pRef_ = do + -- pending is reset before the set, so a hash added concurrently can only be persisted for the new period + mapM_ (`atomicWriteIORef` PendingHashes {pendingReset = True, pendingAdded = IS.empty}) pRef_ + tshow . IS.size <$> atomicSwapIORef ref IS.empty + periodCount _ _ _ = pure "" +``` + +Replace `updatePeriodStats`: + +```haskell +updatePeriodStats :: PeriodStats -> EntityId -> IO () +updatePeriodStats ps (EntityId pId) = do + updatePeriod (day ps) (pendingDay <$> pendingPeriods ps) + updatePeriod (week ps) (pendingWeek <$> pendingPeriods ps) + updatePeriod (month ps) (pendingMonth <$> pendingPeriods ps) + where + ph = hash pId + updatePeriod ref pRef_ = unlessM (IS.member ph <$> readIORef ref) $ do + atomicModifyIORef'_ ref $ IS.insert ph + mapM_ (\pRef -> atomicModifyIORef'_ pRef $ \p -> p {pendingAdded = IS.insert ph $ pendingAdded p}) pRef_ +``` + +- [ ] **Step 4: Enable tracking in `newEnv` (`Env/STM.hs`)** + +Add `serverStatsBackupFile` to the `newEnv` pattern: + +```haskell +newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes, serverStatsBackupFile} = do +``` + +Replace `serverStats <- newServerStats =<< getCurrentTime`: + +```haskell + serverStats <- newServerStats (isJust serverStatsBackupFile && isJust (dbStoreCfg serverStoreCfg)) =<< getCurrentTime +``` + +- [ ] **Step 5: Run tests to verify they pass** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 4 examples, 0 failures. `cabal build -fserver_postgres --ghc-options=-O0 all` shows no new warnings (XFTP and NTF servers compile unchanged). + +- [ ] **Step 6: Commit** + +```bash +git add src/Simplex/Messaging/Server/Stats.hs src/Simplex/Messaging/Server/Env/STM.hs tests/CoreTests/ServerStatsTests.hs tests/Test.hs simplexmq.cabal +git commit -m "smp server: track pending active queue hashes" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/Stats.hs", "src/Simplex/Messaging/Server/Env/STM.hs", "tests/CoreTests/ServerStatsTests.hs", "tests/Test.hs", "simplexmq.cabal"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Core tests/Server stats tests/\"", "acceptanceCriteria": ["newPeriodStats without pending", "pending hashes recorded once per period", "reset flags per day/Monday/1st", "restore merges taken hashes", "newEnv tracks pending only for Postgres with persistence", "4 tests pass"], "modelTier": "standard"} +``` + +--- + +### Task 4: Add StatsStore module + +**Goal:** `loadStats`/`saveStats` persist `ServerStatsData` to a file (atomic replace) or to Postgres (row upsert, incremental hashes, one-time file import). + +**Files:** +- Create: `src/Simplex/Messaging/Server/StatsStore.hs` +- Modify: `simplexmq.cabal` (library `exposed-modules` in the `!flag(client_library)` block, after `Simplex.Messaging.Server.Stats`) +- Modify: `tests/CoreTests/ServerStatsTests.hs` + +**Acceptance Criteria:** +- [ ] File save writes `.tmp` then renames; load does not rename; missing file gives `Nothing`; invalid file throws; write errors are logged, not thrown +- [ ] DB save deletes rows of flagged sets, inserts pending hashes (batches of 10000, `ON CONFLICT DO NOTHING`), upserts the row, in one transaction +- [ ] DB save failure logs and restores taken pending hashes +- [ ] DB load returns the row and all six sets; unknown `period_set` throws +- [ ] DB load with no row imports the file in one transaction and renames it to `.bak`; with a row, the file is left in place with a warning +- [ ] Round trip preserves every persisted field (distinct values per field) + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` → 13 examples, 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing tests** + +In `tests/CoreTests/ServerStatsTests.hs` add `{-# LANGUAGE CPP #-}` to the pragmas, extend imports: + +```haskell +import qualified Data.ByteString.Char8 as B +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.StatsStore +import System.Directory (doesFileExist) +#if defined(dbServerPostgres) +import Control.Exception (bracket) +import Control.Monad (void) +import CoreTests.MsgStoreTests (testPostgresStoreConfig) +import qualified Database.PostgreSQL.Simple as DB +import Data.String (fromString) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) +import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) +import Simplex.Messaging.Server.QueueStore.Postgres (PostgresQueueStore (..)) +#endif +``` + +Replace `serverStatsTests`: + +```haskell +serverStatsTests :: Spec +serverStatsTests = do + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + describe "stats file" $ do + it "should save and load stats" testFileSaveLoad + it "should return no stats without file" testFileMissing + it "should log and continue when file cannot be written" testFileSaveError + it "should fail on invalid file" testFileParseError +#if defined(dbServerPostgres) + describe "stats database" $ do + it "should save and load stats with period sets" testDBSaveLoad + it "should save added hashes and delete reset sets" testDBResetAndAdded + it "should keep pending hashes when save fails" testDBSaveFailure + it "should import stats file when database has no stats" testDBImportFile + it "should ignore stats file when database has stats" testDBIgnoreFile +#endif +``` + +Append the helpers and tests: + +```haskell +statsFile :: HasTestEnv => FilePath +statsFile = testPath "smp-server-stats.log" + +-- every zero counter line of the file encoding gets a distinct value, so a column order mistake changes the result +distinctCounters :: ServerStatsData -> ServerStatsData +distinctCounters d = either error id $ strDecode $ B.unlines $ zipWith setValue [1 :: Int ..] $ B.lines $ strEncode d + where + setValue i l = case B.breakSubstring "=" l of + (k, "=0") -> k <> "=" <> B.pack (show i) + _ -> l + +newDistinctStats :: Bool -> IO ServerStats +newDistinctStats trackPending = do + ss <- newServerStats trackPending wednesday + setServerStats ss . distinctCounters =<< getServerStatsData ss + pure ss + +testFileSaveLoad :: HasTestEnv => IO () +testFileSaveLoad = do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + updatePeriodStats (activeQueuesNtf ss) q2 + saveStats (StatsFile statsFile) ss + doesFileExist (statsFile <> ".tmp") `shouldReturn` False + expected <- getServerStatsData ss + Just d <- loadStats (StatsFile statsFile) + strEncode d `shouldBe` strEncode expected + doesFileExist statsFile `shouldReturn` True + +testFileMissing :: HasTestEnv => IO () +testFileMissing = (isNothing <$> loadStats (StatsFile statsFile)) `shouldReturn` True + +testFileSaveError :: HasTestEnv => IO () +testFileSaveError = do + let f = testPath "missing/smp-server-stats.log" + saveStats (StatsFile f) =<< newServerStats False wednesday + doesFileExist f `shouldReturn` False + +testFileParseError :: HasTestEnv => IO () +testFileParseError = do + B.writeFile statsFile "invalid" + loadStats (StatsFile statsFile) `shouldThrow` anyIOException + +#if defined(dbServerPostgres) +withStatsDB :: HasTestEnv => (DBStore -> IO a) -> IO a +withStatsDB action = bracket (newMsgStore testPostgresStoreConfig :: IO PostgresMsgStore) closeMsgStore $ action . dbStore . queueStore + +testDBSaveLoad :: HasTestEnv => IO () +testDBSaveLoad = withStatsDB $ \st -> do + ss <- newDistinctStats True + mapM_ (updatePeriodStats $ activeQueues ss) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + expected <- getServerStatsData ss + Just d <- getDBStats st + strEncode d `shouldBe` strEncode expected {_qCount = 0} + _day (_activeQueues d) `shouldBe` hashes [q1, q2] + _month (_activeQueuesNtf d) `shouldBe` hashes [q3] + +testDBResetAndAdded :: HasTestEnv => IO () +testDBResetAndAdded = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + mapM_ (updatePeriodStats msgQueues) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + updatePeriodStats msgQueues q4 + _ <- periodStatCounts msgQueues wednesday + updatePeriodStats msgQueues q5 + saveStats (StatsDB st statsFile) ss + Just ServerStatsData {_activeQueues, _activeQueuesNtf} <- getDBStats st + _day _activeQueues `shouldBe` hashes [q5] + _week _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _month _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _day _activeQueuesNtf `shouldBe` hashes [q3] + +testDBSaveFailure :: HasTestEnv => IO () +testDBSaveFailure = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + updatePeriodStats (activeQueues ss) q2 + renameTable st "server_stats_queues" "server_stats_queues_moved" + saveStats (StatsDB st statsFile) ss + renameTable st "server_stats_queues_moved" "server_stats_queues" + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + saveStats (StatsDB st statsFile) ss + Just d' <- getDBStats st + _day (_activeQueues d') `shouldBe` hashes [q1, q2] + where + renameTable st from to = withTransaction st $ \db -> void $ DB.execute_ db $ fromString $ "ALTER TABLE " <> from <> " RENAME TO " <> to + +testDBImportFile :: HasTestEnv => IO () +testDBImportFile = withStatsDB $ \st -> do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + d <- getServerStatsData ss + B.writeFile statsFile $ strEncode d + Just imported <- loadStats (StatsDB st statsFile) + strEncode imported `shouldBe` strEncode d + doesFileExist statsFile `shouldReturn` False + doesFileExist (statsFile <> ".bak") `shouldReturn` True + Just saved <- getDBStats st + strEncode saved `shouldBe` strEncode d {_qCount = 0} + +testDBIgnoreFile :: HasTestEnv => IO () +testDBIgnoreFile = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + saved <- getServerStatsData ss + B.writeFile statsFile . strEncode =<< getServerStatsData =<< newDistinctStats False + Just loaded <- loadStats (StatsDB st statsFile) + strEncode loaded `shouldBe` strEncode saved {_qCount = 0} + doesFileExist statsFile `shouldReturn` True +#endif +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: compile error — module `Simplex.Messaging.Server.StatsStore` not found. + +- [ ] **Step 3: Create `src/Simplex/Messaging/Server/StatsStore.hs`** + +```haskell +{-# LANGUAGE CPP #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} + +module Simplex.Messaging.Server.StatsStore + ( StatsStore (..), + loadStats, + saveStats, +#if defined(dbServerPostgres) + PeriodSet (..), + getDBStats, +#endif + ) +where + +import qualified Control.Exception as E +import Control.Logger.Simple +import Control.Monad +import qualified Data.ByteString.Char8 as B +import qualified Data.Text as T +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Util (ifM, tshow) +import System.Directory (doesFileExist, removeFile, renameFile) +import UnliftIO.Exception (tryAny) +#if defined(dbServerPostgres) +import Data.Bifunctor (bimap) +import Data.IORef (IORef) +import Data.Int (Int16, Int64) +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.List (find, intersperse) +import qualified Data.List.NonEmpty as L +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import Database.PostgreSQL.Simple (Only (..), Query) +import qualified Database.PostgreSQL.Simple as DB +import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) +import Database.PostgreSQL.Simple.ToField (ToField (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Util (toChunks, whenM) +#endif + +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath +#endif + +loadStats :: StatsStore -> IO (Maybe ServerStatsData) +loadStats = \case + StatsFile f -> ifM (doesFileExist f) (Just <$> readStatsFile f) (pure Nothing) +#if defined(dbServerPostgres) + StatsDB st f -> + getDBStats st >>= \case + Just d -> do + whenM (doesFileExist f) $ logWarn $ "server stats file " <> T.pack f <> " is ignored, stats are restored from the database" + pure $ Just d + Nothing -> ifM (doesFileExist f) (Just <$> importStatsFile st f) (pure Nothing) +#endif + +saveStats :: StatsStore -> ServerStats -> IO () +saveStats = \case + StatsFile f -> saveStatsFile f +#if defined(dbServerPostgres) + StatsDB st _ -> saveDBStats st +#endif + +readStatsFile :: FilePath -> IO ServerStatsData +readStatsFile f = do + logNote $ "restoring server stats from file " <> T.pack f + strDecode <$> B.readFile f >>= \case + Right d -> pure d + Left e -> E.throwIO $ userError $ "error parsing server stats file " <> f <> ": " <> e + +saveStatsFile :: FilePath -> ServerStats -> IO () +saveStatsFile f ss = do + d <- getServerStatsData ss + tryAny (B.writeFile tmp (strEncode d) >> renameFile tmp f) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to file " <> T.pack f <> ": " <> tshow e + void $ tryAny $ removeFile tmp + where + tmp = f <> ".tmp" + +#if defined(dbServerPostgres) +data PeriodSet = PSMsgDay | PSMsgWeek | PSMsgMonth | PSNtfDay | PSNtfWeek | PSNtfMonth + deriving (Bounded, Enum, Eq, Ord, Show) + +-- stored in server_stats_queues.period_set, the values must not change +periodSetId :: PeriodSet -> Int16 +periodSetId = \case + PSMsgDay -> 1 + PSMsgWeek -> 2 + PSMsgMonth -> 3 + PSNtfDay -> 4 + PSNtfWeek -> 5 + PSNtfMonth -> 6 + +instance ToField PeriodSet where + toField = toField . periodSetId + +periodSetFromId :: Int16 -> Maybe PeriodSet +periodSetFromId i = find ((i ==) . periodSetId) [minBound .. maxBound] + +periodSetHashes :: ServerStatsData -> PeriodSet -> IntSet +periodSetHashes ServerStatsData {_activeQueues = q, _activeQueuesNtf = n} = \case + PSMsgDay -> _day q + PSMsgWeek -> _week q + PSMsgMonth -> _month q + PSNtfDay -> _day n + PSNtfWeek -> _week n + PSNtfMonth -> _month n + +periodSetPending :: ServerStats -> PeriodSet -> Maybe (IORef PendingHashes) +periodSetPending ServerStats {activeQueues, activeQueuesNtf} = \case + PSMsgDay -> pendingDay <$> pendingPeriods activeQueues + PSMsgWeek -> pendingWeek <$> pendingPeriods activeQueues + PSMsgMonth -> pendingMonth <$> pendingPeriods activeQueues + PSNtfDay -> pendingDay <$> pendingPeriods activeQueuesNtf + PSNtfWeek -> pendingWeek <$> pendingPeriods activeQueuesNtf + PSNtfMonth -> pendingMonth <$> pendingPeriods activeQueuesNtf + +getDBStats :: DBStore -> IO (Maybe ServerStatsData) +getDBStats st = + withTransaction st $ \db -> + DB.query_ db selectStatsQuery >>= \case + StatsRow d : _ -> Just . withPeriodSets d <$> DB.fold_ db "SELECT period_set, queue_hash FROM server_stats_queues" M.empty addHash + [] -> pure Nothing + where + addHash sets (psId :: Int16, h :: Int64) = case periodSetFromId psId of + Just ps -> pure $! M.alter (Just . maybe (IS.singleton h') (IS.insert h')) ps sets + Nothing -> E.throwIO $ userError $ "unknown period_set " <> show psId + where + h' = fromIntegral h + withPeriodSets d sets = + d + { _activeQueues = periodData PSMsgDay PSMsgWeek PSMsgMonth, + _activeQueuesNtf = periodData PSNtfDay PSNtfWeek PSNtfMonth + } + where + periodData dp wp mp = PeriodStatsData {_day = get dp, _week = get wp, _month = get mp} + get p = M.findWithDefault IS.empty p sets + +importStatsFile :: DBStore -> FilePath -> IO ServerStatsData +importStatsFile st f = do + d <- readStatsFile f + withTransaction st $ \db -> do + void $ DB.execute_ db "DELETE FROM server_stats_queues" + forM_ [minBound .. maxBound] $ \ps -> insertHashes db ps $ periodSetHashes d ps + upsertStats db d + renameFile f $ f <> ".bak" + logNote "server stats imported to the database" + pure d + +saveDBStats :: DBStore -> ServerStats -> IO () +saveDBStats st ss = do + taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> + forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref + d <- getServerStatsData ss + tryAny (withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to the database: " <> tshow e + forM_ taken $ \(_, ref, p) -> restorePendingHashes ref p + where + savePending db (ps, _, PendingHashes {pendingReset, pendingAdded}) = do + when pendingReset $ void $ DB.execute db "DELETE FROM server_stats_queues WHERE period_set = ?" (Only ps) + insertHashes db ps pendingAdded + +insertHashes :: DB.Connection -> PeriodSet -> IntSet -> IO () +insertHashes db ps hs = + forM_ (toChunks hashInsertBatch $ IS.toList hs) $ \hs' -> + void $ + DB.executeMany + db + "INSERT INTO server_stats_queues (period_set, queue_hash) VALUES (?, ?) ON CONFLICT DO NOTHING" + (map (\h -> (ps, fromIntegral h :: Int64)) $ L.toList hs') + +-- rows per INSERT statement, bounds the query size of the one-time file import +hashInsertBatch :: Int +hashInsertBatch = 10000 + +upsertStats :: DB.Connection -> ServerStatsData -> IO () +upsertStats db d = do + savedAt <- systemSeconds <$> getSystemTime + void $ DB.execute db upsertStatsQuery $ savedAt : map (($ d) . snd) statsFields + +selectStatsQuery :: Query +selectStatsQuery = "SELECT " <> commaSep (map fst statsFields) <> " FROM server_stats WHERE server_stats_id = 1" + +upsertStatsQuery :: Query +upsertStatsQuery = + "INSERT INTO server_stats (server_stats_id, saved_at, " + <> commaSep cols + <> ") VALUES (1, ?, " + <> commaSep (map (const "?") cols) + <> ") ON CONFLICT (server_stats_id) DO UPDATE SET " + <> commaSep (map (\c -> c <> " = EXCLUDED." <> c) ("saved_at" : cols)) + where + cols = map fst statsFields + +commaSep :: [Query] -> Query +commaSep = mconcat . intersperse ", " + +-- the order must match the FromRow StatsRow instance +statsFields :: [(Query, ServerStatsData -> Int64)] +statsFields = + ("from_time", round . utcTimeToPOSIXSeconds . _fromTime) + : map + (fmap (fromIntegral .)) + ( [ ("q_created", _qCreated), + ("q_secured", _qSecured), + ("q_deleted_all", _qDeletedAll), + ("q_deleted_new", _qDeletedNew), + ("q_deleted_secured", _qDeletedSecured), + ("q_deleted_all_b", _qDeletedAllB), + ("q_blocked", _qBlocked), + ("q_sub", _qSub), + ("q_sub_all_b", _qSubAllB), + ("q_sub_auth", _qSubAuth), + ("q_sub_duplicate", _qSubDuplicate), + ("q_sub_prohibited", _qSubProhibited), + ("q_sub_end", _qSubEnd), + ("q_sub_end_b", _qSubEndB), + ("ntf_created", _ntfCreated), + ("ntf_new_created", _ntfNewCreated), + ("ntf_deleted", _ntfDeleted), + ("ntf_deleted_b", _ntfDeletedB), + ("ntf_sub", _ntfSub), + ("ntf_sub_b", _ntfSubB), + ("ntf_sub_auth", _ntfSubAuth), + ("ntf_sub_duplicate", _ntfSubDuplicate), + ("msg_sent", _msgSent), + ("msg_sent_auth", _msgSentAuth), + ("msg_sent_quota", _msgSentQuota), + ("msg_sent_large", _msgSentLarge), + ("msg_sent_block", _msgSentBlock), + ("msg_recv", _msgRecv), + ("msg_recv_get", _msgRecvGet), + ("msg_get", _msgGet), + ("msg_get_no_msg", _msgGetNoMsg), + ("msg_get_auth", _msgGetAuth), + ("msg_get_duplicate", _msgGetDuplicate), + ("msg_get_prohibited", _msgGetProhibited), + ("msg_expired", _msgExpired), + ("msg_sent_ntf", _msgSentNtf), + ("msg_recv_ntf", _msgRecvNtf), + ("msg_ntfs", _msgNtfs), + ("msg_ntfs_b", _msgNtfsB), + ("msg_ntf_no_sub", _msgNtfNoSub), + ("msg_ntf_lost", _msgNtfLost), + ("msg_ntf_expired", _msgNtfExpired) + ] + <> proxyFields "p_relays" _pRelays + <> proxyFields "p_relays_own" _pRelaysOwn + <> proxyFields "p_msg_fwds" _pMsgFwds + <> proxyFields "p_msg_fwds_own" _pMsgFwdsOwn + <> [("p_msg_fwds_recv", _pMsgFwdsRecv)] + <> serviceFields "rcv_services" _rcvServices + <> serviceFields "ntf_services" _ntfServices + <> map + (fmap (. _rslvStats)) + [ ("rslv_reqs", _rslvReqs), + ("rslv_succ", _rslvSucc), + ("rslv_not_found", _rslvNotFound), + ("rslv_resolver_errs", _rslvResolverErrs), + ("rslv_disabled", _rslvDisabled) + ] + ) + where + proxyFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("requests", _pRequests), + ("successes", _pSuccesses), + ("errors_connect", _pErrorsConnect), + ("errors_compat", _pErrorsCompat), + ("errors_other", _pErrorsOther) + ] + serviceFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("assoc_new", _srvAssocNew), + ("assoc_duplicate", _srvAssocDuplicate), + ("assoc_updated", _srvAssocUpdated), + ("assoc_removed", _srvAssocRemoved), + ("sub_count", _srvSubCount), + ("sub_duplicate", _srvSubDuplicate), + ("sub_queues", _srvSubQueues), + ("sub_end", _srvSubEnd) + ] + +newtype StatsRow = StatsRow ServerStatsData + +instance FromRow StatsRow where + fromRow = do + _fromTime <- posixSecondsToUTCTime . fromIntegral <$> field @Int64 + _qCreated <- field + _qSecured <- field + _qDeletedAll <- field + _qDeletedNew <- field + _qDeletedSecured <- field + _qDeletedAllB <- field + _qBlocked <- field + _qSub <- field + _qSubAllB <- field + _qSubAuth <- field + _qSubDuplicate <- field + _qSubProhibited <- field + _qSubEnd <- field + _qSubEndB <- field + _ntfCreated <- field + _ntfNewCreated <- field + _ntfDeleted <- field + _ntfDeletedB <- field + _ntfSub <- field + _ntfSubB <- field + _ntfSubAuth <- field + _ntfSubDuplicate <- field + _msgSent <- field + _msgSentAuth <- field + _msgSentQuota <- field + _msgSentLarge <- field + _msgSentBlock <- field + _msgRecv <- field + _msgRecvGet <- field + _msgGet <- field + _msgGetNoMsg <- field + _msgGetAuth <- field + _msgGetDuplicate <- field + _msgGetProhibited <- field + _msgExpired <- field + _msgSentNtf <- field + _msgRecvNtf <- field + _msgNtfs <- field + _msgNtfsB <- field + _msgNtfNoSub <- field + _msgNtfLost <- field + _msgNtfExpired <- field + _pRelays <- proxyStatsP + _pRelaysOwn <- proxyStatsP + _pMsgFwds <- proxyStatsP + _pMsgFwdsOwn <- proxyStatsP + _pMsgFwdsRecv <- field + _rcvServices <- serviceStatsP + _ntfServices <- serviceStatsP + _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field + pure $ + StatsRow + ServerStatsData + { _fromTime, + _qCreated, + _qSecured, + _qDeletedAll, + _qDeletedAllB, + _qDeletedNew, + _qDeletedSecured, + _qBlocked, + _qSub, + _qSubAllB, + _qSubAuth, + _qSubDuplicate, + _qSubProhibited, + _qSubEnd, + _qSubEndB, + _ntfCreated, + _ntfNewCreated, + _ntfDeleted, + _ntfDeletedB, + _ntfSub, + _ntfSubB, + _ntfSubAuth, + _ntfSubDuplicate, + _msgSent, + _msgSentAuth, + _msgSentQuota, + _msgSentLarge, + _msgSentBlock, + _msgRecv, + _msgRecvAckTimes = emptyTimeBuckets, + _msgRecvGet, + _msgGet, + _msgGetNoMsg, + _msgGetAuth, + _msgGetDuplicate, + _msgGetProhibited, + _msgExpired, + _activeQueues = newPeriodStatsData, + _msgSentNtf, + _msgRecvNtf, + _activeQueuesNtf = newPeriodStatsData, + _msgNtfs, + _msgNtfsB, + _msgNtfNoSub, + _msgNtfLost, + _msgNtfExpired, + _pRelays, + _pRelaysOwn, + _pMsgFwds, + _pMsgFwdsOwn, + _pMsgFwdsRecv, + _ntfServices, + _rcvServices, + _rcvServicesSubMsg = 0, + _rcvServicesSubDuplicate = 0, + _authDelayExceeded = 0, + _cmdSlotWaits = 0, + _cmdSlotWaitMs = 0, + _cmdSlotWaitMaxMs = 0, + _cmdSlotWaitTimeouts = 0, + _qCount = 0, + _msgCount = 0, + _ntfCount = 0, + _rslvStats + } + where + proxyStatsP = ProxyStatsData <$> field <*> field <*> field <*> field <*> field + serviceStatsP = do + _srvAssocNew <- field + _srvAssocDuplicate <- field + _srvAssocUpdated <- field + _srvAssocRemoved <- field + _srvSubCount <- field + _srvSubDuplicate <- field + _srvSubQueues <- field + _srvSubEnd <- field + pure newServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} +#endif +``` + +In `simplexmq.cabal`, library `exposed-modules` (the `!flag(client_library)` block), after `Simplex.Messaging.Server.Stats`: + +``` + Simplex.Messaging.Server.Stats + Simplex.Messaging.Server.StatsStore +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 13 examples, 0 failures (the failing-save test logs one "error saving server stats to the database" line). +Run: `cabal build --ghc-options=-O0 lib:simplexmq` (without `-fserver_postgres`) +Expected: builds with no warnings from `StatsStore.hs`. + +- [ ] **Step 5: Commit** + +```bash +git add src/Simplex/Messaging/Server/StatsStore.hs simplexmq.cabal tests/CoreTests/ServerStatsTests.hs +git commit -m "smp server: add stats store" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server/StatsStore.hs", "simplexmq.cabal", "tests/CoreTests/ServerStatsTests.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/Core tests/Server stats tests/\"", "acceptanceCriteria": ["atomic file save, no rename on load", "DB save deletes reset sets, inserts pending, upserts row in one tx", "failed DB save restores pending", "DB load with sets; unknown period_set throws", "import once with .bak; row wins over file", "round trip with distinct values", "13 tests pass", "builds without server_postgres"], "modelTier": "frontier"} +``` + +--- + +### Task 5: Save stats periodically in the server + +**Goal:** The SMP server restores stats through `StatsStore`, recomputes store counts on every start, and saves stats on a timer, around the daily rollover and on shutdown under `savingLock`. + +**Files:** +- Modify: `src/Simplex/Messaging/Server.hs` (imports; `raceAny_` thread list ~:186; `saveServer` ~:239; `serverStatsThread_`/`logServerStats` ~:510-530; `saveServerStats`/`restoreServerStats` ~:2515-2549) +- Modify: `tests/ServerTests.hs` (imports; `serverTests` list; `testRestoreMessages`; `testRestoreExpireMessages`; new tests) + +**Acceptance Criteria:** +- [ ] Postgres mode loads from `server_stats` (or imports the file once); memory mode loads the file without renaming +- [ ] Load errors log and exit +- [ ] `qCount`, `msgCount`, `ntfCount` are set from the store on every start; startup expiration counts are added to `msgExpired`/`msgNtfExpired` +- [ ] `saveStatsThread` saves every `statsSaveInterval` seconds under `savingLock` when `serverStatsBackupFile` is set +- [ ] Daily rollover saves before and after writing the daily line, holding `savingLock` +- [ ] Shutdown and control `save` save stats before the message store is closed +- [ ] Existing restore tests pass for memory and Postgres stores; new tests pass + +**Verify:** `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/"` → 0 failures + +**Steps:** + +- [ ] **Step 1: Write the failing server tests (`tests/ServerTests.hs`)** + +Imports: change `import Data.Maybe (catMaybes)` to `import Data.Maybe (catMaybes, fromMaybe)`. In the `#if defined(dbServerPostgres)` import block add: + +```haskell +import CoreTests.ServerStatsTests (withStatsDB) +import Simplex.Messaging.Server.StatsStore (getDBStats) +``` + +In `serverTests`, after `describe "Restore messages (old / v2)" testRestoreExpireMessages`: + +```haskell + describe "Restore messages (old / v2)" testRestoreExpireMessages + describe "Save server stats" $ do + testSaveStatsPeriodically + testStartupStoreCounts +``` + +Add after `checkStats`: + +```haskell +readSavedStats :: HasTestEnv => AStoreType -> IO ServerStatsData +readSavedStats = \case + ASType _ SMSMemory -> do + logSize testServerStatsBackupFile `shouldReturn` 101 + either error id . strDecode <$> B.readFile testServerStatsBackupFile +#if defined(dbServerPostgres) + ASType _ SMSPostgres -> withStatsDB $ fmap (fromMaybe $ error "no saved stats") . getDBStats +#else + ASType _ SMSPostgres -> error "compiled without server_postgres flag" +#endif + +testSaveStatsPeriodically :: SpecWith (ASrvTransport, AStoreType) +testSaveStatsPeriodically = + it "should save stats while running and restore them on start" $ \(at@(ATransport t), msType) -> do + removeFileIfExists testServerStatsBackupFile + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, statsSaveInterval = 1} + (rId, stats1, snapshot) <- withSmpServerConfigOn at cfg' testPort $ \_ -> do + rId <- runClient t $ \h -> runClient t $ \rh -> do + (sId, rId, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello") + pure rId + threadDelay 1500000 + stats1 <- readSavedStats msType + snapshot <- case msType of + ASType _ SMSMemory -> Just <$> B.readFile testServerStatsBackupFile + _ -> pure Nothing + pure (rId, stats1, snapshot) + checkStats stats1 [rId] 1 0 + -- a crash leaves the last periodic save, not the save on shutdown + mapM_ (B.writeFile testServerStatsBackupFile) snapshot + stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 1500000 >> readSavedStats msType + checkStats stats2 [rId] 1 0 + removeFileIfExists testServerStatsBackupFile + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + +testStartupStoreCounts :: SpecWith (ASrvTransport, AStoreType) +testStartupStoreCounts = + it "should count stored queues and messages on start without saved stats" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = cfgMS msType + withSmpServerConfigOn at cfg' testPort $ \_ -> runClient t $ \h -> runClient t $ \rh -> do + (sId, _, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello 1") + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () + let cfg2 = updateCfg cfg' $ \cfg_ -> cfg_ {prometheusInterval = Just 1} + metrics <- withSmpServerConfigOn at cfg2 testPort $ \_ -> threadDelay 1500000 >> B.readFile testPrometheusMetricsFile + let expected = case msType of + ASType SQSMemory _ -> ["simplex_smp_messages_total 2", "simplex_smp_queues_total1 1"] + -- Postgres queue count is a reltuples estimate + _ -> ["simplex_smp_messages_total 2"] + forM_ expected $ \l -> B.lines metrics `shouldContain` [l] + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient +``` + +Update the existing restore tests to read stats through `readSavedStats`: + +In `testRestoreMessages`, replace each of the three pairs + +```haskell + logSize testServerStatsBackupFile `shouldReturn` 101 + Right stats1 <- strDecode <$> B.readFile testServerStatsBackupFile +``` + +(and the same for `stats2`, `stats3`) with + +```haskell + stats1 <- readSavedStats msType +``` + +(`stats2`, `stats3` respectively), and replace `removeFile testServerStatsBackupFile` with `removeFileIfExists testServerStatsBackupFile`. + +In `testRestoreExpireMessages`, replace + +```haskell + Right ServerStatsData {_msgExpired} <- strDecode <$> B.readFile testServerStatsBackupFile +``` + +with + +```haskell + ServerStatsData {_msgExpired} <- readSavedStats msType +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/Save server stats/"` +Expected: FAIL — memory: "should save stats while running" fails (`logSize` finds no file while running); both stores: "should count stored queues and messages" fails (`simplex_smp_messages_total 0` or `simplex_smp_queues_total1 0`); Postgres: `readSavedStats` gets "no saved stats". + +- [ ] **Step 3: Server imports (`Server.hs`)** + +After `import Simplex.Messaging.Server.Stats`: + +```haskell +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore +``` + +Remove `renameFile` from `import UnliftIO.Directory (doesFileExist, renameFile)` if no other use remains (check with `rg -n "renameFile" src/Simplex/Messaging/Server.hs` after Step 7). + +In the existing `#if defined(dbServerPostgres)` import block: + +```haskell +#if defined(dbServerPostgres) +import Simplex.Messaging.Server.MsgStore.Postgres (getDbMessageStats) +import qualified Simplex.Messaging.Server.QueueStore.Postgres as PQ +#endif +``` + +- [ ] **Step 4: Start the save thread** + +In the `raceAny_` list: + +```haskell + <> serverStatsThread_ cfg + <> saveStatsThread_ cfg + <> prometheusMetricsThread_ cfg +``` + +After `serverStatsThread_` definition (before `logServerStats`): + +```haskell + saveStatsThread_ :: ServerConfig s -> [M s ()] + saveStatsThread_ ServerConfig {serverStatsBackupFile = Just _, statsSaveInterval} = [saveStatsThread statsSaveInterval] + saveStatsThread_ _ = [] + + saveStatsThread :: Int64 -> M s () + saveStatsThread interval = do + labelMyThread "saveStatsThread" + lock <- asks $ savingLock . server + forever $ do + liftIO $ threadDelay' $ 1000000 * interval + withLock' lock "saveStats" saveServerStats +``` + +- [ ] **Step 5: Save around the daily rollover (`logServerStats`)** + +Before `let interval = 1000000 * logInterval`: + +```haskell + lock <- asks $ savingLock . server + u <- askUnliftIO + let interval = 1000000 * logInterval +``` + +Replace `withFile statsFilePath AppendMode $ \h -> liftIO $ do` with + +```haskell + withFile statsFilePath AppendMode $ \h -> withLock' lock "logStats" $ liftIO $ do + unliftIO u saveServerStats + hSetBuffering h LineBuffering +``` + +(`hSetBuffering h LineBuffering` is the existing first line.) After the last statement of that block, the multi-line `T.hPutStrLn h $ T.intercalate "," (...)`, add at the same indentation: + +```haskell + unliftIO u saveServerStats +``` + +- [ ] **Step 6: Save stats before closing the store (`saveServer`)** + +```haskell + saveServer :: Bool -> M s () + saveServer drainMsgs = do + -- the database stats store is closed together with the message store + saveServerStats + ms <- asks msgStore_ + liftIO $ saveServerMessages drainMsgs ms >> closeMsgStore (fromMsgStore ms) + saveServerNtfs +``` + +- [ ] **Step 7: Replace `saveServerStats` and `restoreServerStats`** + +Replace both definitions with: + +```haskell +serverStatsStore :: M s (Maybe StatsStore) +serverStatsStore = do + ms <- asks msgStore_ + fmap (statsStore ms) <$> asks (serverStatsBackupFile . config) + where + statsStore :: MsgStore s -> FilePath -> StatsStore + statsStore = \case + StoreMemory _ -> StatsFile +#if defined(dbServerPostgres) + StoreDatabase ms -> StatsDB (PQ.dbStore $ queueStore ms) +#endif + +saveServerStats :: M s () +saveServerStats = do + ss <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . (`saveStats` ss)) + +restoreServerStats :: forall s. MsgStoreClass s => Maybe MessageStats -> MessageStats -> M s () +restoreServerStats msgStats_ ntfStats = do + s <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . tryAny . loadStats >=> restore s) + st <- asks msgStore + EntityCounts {queueCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + liftIO $ do + writeIORef (qCount s) queueCount + writeIORef (msgCount s) $ maybe 0 storedMsgsCount msgStats_ + writeIORef (ntfCount s) $ storedMsgsCount ntfStats + atomicModifyIORef'_ (msgExpired s) (+ maybe 0 expiredMsgsCount msgStats_) + atomicModifyIORef'_ (msgNtfExpired s) (+ expiredMsgsCount ntfStats) + where + restore s = \case + Right (Just d) -> liftIO (setServerStats s d) >> logNote "server stats restored" + Right Nothing -> pure () + Left e -> do + logError $ "error restoring server stats: " <> tshow e + liftIO exitFailure +``` + +`restoreServerStats` keeps its call site (`restoreServerStats msgStats_ ntfStats`, ~:182). Check that `renameFile` and `B.readFile`/`strDecode` imports are still used elsewhere in `Server.hs`; remove only unused ones. + +- [ ] **Step 8: Build without warnings** + +Run: `cabal build -fserver_postgres --ghc-options=-O0 all` and `cabal build --ghc-options=-O0 lib:simplexmq` +Expected: no warnings in changed files. + +- [ ] **Step 9: Run server tests** + +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/SMP server via TLS/"` +Expected: 0 failures for memory and postgres-only stores, including "Save server stats", "Restore messages", "Restore messages (old / v2)". +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Core tests/Server stats tests/"` +Expected: 13 examples, 0 failures. +Run: `cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match="/Notifications server/"` +Expected: 0 failures (uses `withSmpServerStoreLogOn` with stats persistence). + +- [ ] **Step 10: Commit** + +```bash +git add src/Simplex/Messaging/Server.hs tests/ServerTests.hs +git commit -m "smp server: save stats periodically" +``` + +```json:metadata +{"files": ["src/Simplex/Messaging/Server.hs", "tests/ServerTests.hs"], "verifyCommand": "cabal test -fserver_postgres --ghc-options=-O0 --test-show-details=streaming --test-option=--match=\"/SMP server via TLS/\"", "acceptanceCriteria": ["restore via StatsStore per mode", "load errors exit", "store counts recomputed every start", "periodic save under savingLock", "rollover saves before and after daily line", "shutdown saves before closing store", "existing and new server tests pass"], "modelTier": "frontier"} +``` diff --git a/plans/2026-11-03-unacked-data-timeout.md b/plans/2026-11-03-unacked-data-timeout.md new file mode 100644 index 000000000..7264b72b5 --- /dev/null +++ b/plans/2026-11-03-unacked-data-timeout.md @@ -0,0 +1,26 @@ +# Unacknowledged-data timeout + +## Problem + +On Linux and Android, a client connection to a server that becomes unreachable while data is unacknowledged fails only after about 15 minutes. Until then, the client sends into the dead connection. + +## Cause + +On Linux and Android, TCP keep-alive probes are not sent while the connection has unacknowledged or unsent data. Such a connection is closed only at the retransmission limit (`tcp_retries2` = 15, about 15 minutes). On macOS and iOS, a connection is closed by keep-alive `keepIdle + keepIntvl * keepCnt` after the last received segment, with or without unacknowledged data. + +## Fix + +- `KeepAliveOpts.unackedDataTimeout :: Maybe Bool`: + - `Just True`: on. + - `Nothing` or `Just False`: off; JSON without the field is parsed as `Nothing`. +- `setSocketKeepAlive`, option on: + - Linux and Android: `TCP_USER_TIMEOUT` = `keepIdle + keepIntvl * keepCnt` seconds (90 s with the default keep-alive values). + - macOS, iOS and Windows: not set. +- `transportClientConfig`: `unackedDataTimeout = Nothing` when a SOCKS proxy is used for the host. + +## Scope + +- Client connections with keep-alive: SMP, NTF and XFTP clients (`transportClientConfig`). +- Unchanged: + - outgoing connections of servers (`defaultNetworkConfig`) and remote control (`defaultTransportClientConfig`): `unackedDataTimeout = Nothing`; + - `defaultHTTP2ClientConfig`: keep-alive not set. diff --git a/protocol/simplex-messaging.md b/protocol/simplex-messaging.md index 989884e3f..1ded3fd1a 100644 --- a/protocol/simplex-messaging.md +++ b/protocol/simplex-messaging.md @@ -34,6 +34,7 @@ Version 21, 2026-07-05 - [Secure queue by recipient](#secure-queue-by-recipient) - [Set queue recipient keys](#set-queue-recipient-keys) - [Set short link](#set-short-link) + - [Swap short link data](#swap-short-link-data) - [Delete short link](#delete-short-link) - [Enable notifications command](#enable-notifications-command) - [Disable notifications command](#disable-notifications-command) @@ -57,6 +58,7 @@ Version 21, 2026-07-05 - [Subscribe to multiple queue notifications](#subscribe-to-multiple-queue-notifications) - [Router messages](#router-messages) - [Link response](#link-response) + - [Current link data response](#current-link-data-response) - [Queue subscription response](#queue-subscription-response) - [Service subscription response](#service-subscription-response) - [All service messages received](#all-service-messages-received) @@ -86,7 +88,7 @@ It's designed with the focus on communication security and integrity, under the It is designed as a low level protocol for other application protocols to solve the problem of secure and private message transmission, making [MITM attack][1] very difficult at any part of the message transmission system. -This document describes SMP protocol version 23. Versions 1-5 are discontinued. The version history: +This document describes SMP protocol version 24. Versions 1-5 are discontinued. The version history: - v1: binary protocol encoding - v2: message flags (used to control notifications) @@ -110,6 +112,7 @@ This document describes SMP protocol version 23. Versions 1-5 are discontinued. - v21: server public information in handshake - v22: `RNAME` says whether a name can be registered, not only what it resolves to - v23: version in nonces of forwarded commands, random nonces for forwarded responses +- v24: LSWP command to swap short link data and recipient keys (LCUR response); LSET is refused on queues with several recipient keys ## Introduction @@ -547,12 +550,13 @@ smpCommand = ping / recipientCmd / senderCommand / proxyCommand / notifierCommand / linkCommand / routerMsg recipientCmd = create / subscribe / subscribeMultiple / rcvSecure / recipientKeys / enableNotifications / disableNotifications / getMessage / - acknowledge / suspend / delete / getQueueInfo / setShortLink / deleteShortLink + acknowledge / suspend / delete / getQueueInfo / setShortLink / swapShortLink / + deleteShortLink senderCommand = send / sndSecure linkCommand = setLinkKey / getLinkData proxyCommand = proxySession / proxyForward / relayForward notifierCommand = subscribeNotifications / subscribeNotificationsMultiple -routerMsg = queueIds / linkResponse / serviceOk / serviceOkMultiple / +routerMsg = queueIds / linkResponse / currentLinkData / serviceOk / serviceOkMultiple / message / allReceived / notifierIdResponse / messageNotification / proxySessionKey / proxyResponse / relayResponse / unsubscribed / serviceUnsubscribed / deleted / @@ -708,6 +712,8 @@ recipientKey = length x509encoded This command added to allow multiple group owners manage data of the same queue link. +The router MUST respond with `AUTH` error and keep the current keys if the queue recipient keys changed after the command was authorized. + #### Set short link This command is used to associate a short link with the queue: @@ -723,6 +729,27 @@ length2 = 2*2 OCTET ; Word16, network byte order (big-endian) The router responds with `OK` response if successful. +From v24 the router responds with `ERR AUTH` when the queue has more than one recipient key: the link data of such a queue can only be changed with `LSWP`. + +#### Swap short link data + +This command is used by the owners of a contact address short link to replace its user data and, optionally, the queue recipient keys, only when the stored user data has the hash the owner sends (added in v24): + +```abnf +swapShortLink = %s"LSWP " linkId userDataHash optRecipientKeys encFixedData encUserData +linkId = shortString +userDataHash = shortString ; SHA-256 hash of the stored encrypted user data (without length prefix) +optRecipientKeys = %s"0" / (%s"1" recipientKeysList) ; the new recipient keys of the queue +encFixedData = largeString ; encrypted fixed link data, must be the same as stored +encUserData = largeString ; new encrypted user data +``` + +The router responds with `ERR AUTH` if the queue is not a contact queue, has no short link, or if the link ID or fixed data differ from the stored ones. + +If the hash of the stored user data differs from `userDataHash`, the router responds with [current link data response](#current-link-data-response) (`LCUR`) with the stored user data, and changes nothing. + +Otherwise the router stores the user data and, when present, the recipient keys in one atomic step, and responds with `OK`. + #### Delete short link This command is used to remove a short link association from the queue: @@ -1166,7 +1193,7 @@ fwdCommandKey = length x509encoded transmission = *OCTET ; note that it is not prefixed with the length ``` -The destination router having received this command decrypts both encryption layers (proxy and client), rejects it with `ERR CRYPTO` if the correlation ID of the decrypted transmission differs from `fwdCorrId`, verifies client authorization as usual, processes it, and send the double encrypted `RRES` response to proxy. +The destination router having received this command decrypts both encryption layers (proxy and client), rejects it with `ERR CRYPTO` if the correlation ID of the decrypted transmission differs from `fwdCorrId` or, when `fwdSmpVersion` is below 23, if `fwdCorrId` was already used in this session, verifies client authorization as usual, processes it, and send the double encrypted `RRES` response to proxy. The number of such correlation IDs in one session is limited, and the destination router closes the session when the limit is exceeded. The shared secret for encrypting transmission bodies between proxy router and destination router is agreed from proxy and destination router keys exchanged in handshake headers - proxy and router use the same shared secret during the session for the encryption between them. @@ -1249,6 +1276,15 @@ encFixedData = largeString ; encrypted fixed link data encUserData = largeString ; encrypted user data ``` +#### Current link data response + +Sent in response to `LSWP` command when the hash of the stored user data differs from the hash in the command: + +```abnf +currentLinkData = %s"LCUR " encUserData +encUserData = largeString ; the stored encrypted user data +``` + #### Queue subscription response Sent in response to `SUB` and `NSUB` commands: diff --git a/scripts/ci/README.md b/scripts/ci/README.md index 1c9a1a30a..b1d9ecc82 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -9,7 +9,17 @@ | 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. The ubuntu-24.04 x86-64 entry also runs the tests built with `-fclient_postgres -fslow_servers -fconn_lock_checks` (agent with the PostgreSQL store, XFTP servers that delay responses for the slow-server test, and an agent that fails server requests made inside a connection lock, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store". After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. + +The ubuntu-24.04 x86-64 entry also lints and tests the resolver (scripts/resolver/service, steps "Lint resolver" and "Test resolver"): +- on a push; +- on a pull request or a manual run that changes scripts/resolver/service or build.yml. A manual run is compared with its merge base with master. + +"Build SNRC contracts" builds the simplex-namespace-contract commit set in the step; test_ground_truth.py deploys it to a Hardhat node, seeds it with scripts/seed-lookup-states.mjs and checks the resolver's answer for each seeded name. + +`resolver-mainnet.yml` checks the resolver's answers for known mainnet names daily, on a manual run and on a pull request that changes it. The RPC is the secret `SNRC_MAINNET_RPC`, or a public endpoint without it. + +Local run: scripts/resolver/README.md, "Resolver API reference". The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. ## Test selection diff --git a/scripts/docker/entrypoint-smp-server b/scripts/docker/entrypoint-smp-server index 7b1aaac2d..51ba1db94 100755 --- a/scripts/docker/entrypoint-smp-server +++ b/scripts/docker/entrypoint-smp-server @@ -63,7 +63,7 @@ if [ ! -f "${confd}/smp-server.ini" ]; then --store-log \ --daily-stats \ --source-code \ - "$@" > /dev/null 2>&1 + "$@" > /dev/null # Fix path to certificates if [ -n "${WEB_MANUAL}" ]; then diff --git a/scripts/resolver/.env.example b/scripts/resolver/.env.example index d5c629dff..58dd029b4 100644 --- a/scripts/resolver/.env.example +++ b/scripts/resolver/.env.example @@ -30,3 +30,9 @@ TRUSTED_NODE_URL=https://mainnet-checkpoint-sync.attestant.io # SNRC_LOG_COLOR=always # coloured `docker compose logs` # SNRC_LOG_LEVEL=debug # also log health checks and idle connections # SNRC_TRUSTED_PROXIES=172.16.0.0/12 # behind a reverse proxy on the host; see README + +# .simplex contracts on mainnet; unset, .simplex names answer 400. See README, +# "Configuring addresses". +# SNRC_REGISTRY_SIMPLEX=0xa7f6497be2f1aa41aa2db55aba8a6e0145dff0d2 +# SNRC_REGISTRAR_SIMPLEX=0x44052f7dc9c1cef20b0319a6b75288988dbb12a1 +# SNRC_CONTROLLER_SIMPLEX=0x8005011c6e966656cdb9a222e9a4792600a37219 # proxy diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index 2f0c59d67..23a966748 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -149,6 +149,13 @@ uv run pytest uv run ruff check . ``` +`test_ground_truth.py` runs only with its variables set: `SNRC_CONTRACTS`, a simplex-namespace-contract checkout with `ens-contracts` compiled (the CI step "Build SNRC contracts"), and `SNRC_MAINNET_RPC`, a mainnet JSON-RPC endpoint: + +```sh +SNRC_CONTRACTS=../snrc uv run pytest test_ground_truth.py +SNRC_MAINNET_RPC=https://ethereum-rpc.publicnode.com uv run pytest test_ground_truth.py -k MainnetTests +``` + Dependencies are locked in `uv.lock`; the Docker image installs exactly those. Three routes, versioned separately from the protocol so each only changes when diff --git a/scripts/resolver/docker-compose.yml b/scripts/resolver/docker-compose.yml index 68a4156b6..84f844b0c 100644 --- a/scripts/resolver/docker-compose.yml +++ b/scripts/resolver/docker-compose.yml @@ -157,7 +157,9 @@ services: # (mainnet `.testing` and `.simplex`). Set explicitly here # only if you're deploying against a different network or contract. # SNRC_REGISTRY_TESTING: 0x... - # Registrar and controller, same cascade. + # SNRC_REGISTRY_SIMPLEX: 0x... + # Registrar and controller, same cascade. Unset or empty means the default, + # so every TLD has all three; override the three of a TLD together. # SNRC_REGISTRAR_TESTING: 0x... # SNRC_CONTROLLER_TESTING: 0x... # Set in .env (see .env.example); unset or empty means the resolver's default. diff --git a/scripts/resolver/service/snrc-resolve.py b/scripts/resolver/service/snrc-resolve.py index f9cb306fa..d902e4de2 100755 --- a/scripts/resolver/service/snrc-resolve.py +++ b/scripts/resolver/service/snrc-resolve.py @@ -119,7 +119,8 @@ ) # Each TLD is its own SNRC deployment with its own ENSRegistry. Dispatch -# happens on the rightmost label of the queried name. +# happens on the rightmost label of the queried name. A TLD without an entry +# answers 400 tldNotConfigured. # `... or "..."` makes the script's defaults the single source of truth: # unset AND empty-string both fall through to the literal. docker-compose # can therefore pass `SNRC_REGISTRY_TESTING=${SNRC_REGISTRY_TESTING:-}` diff --git a/scripts/resolver/service/test_ground_truth.py b/scripts/resolver/service/test_ground_truth.py new file mode 100644 index 000000000..028343c8e --- /dev/null +++ b/scripts/resolver/service/test_ground_truth.py @@ -0,0 +1,156 @@ +import json +import os +import socket +import subprocess +import sys +import time +import unittest +from datetime import datetime, timedelta, timezone +from urllib.error import HTTPError +from urllib.request import urlopen + +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTRACTS = os.environ.get("SNRC_CONTRACTS", "") +MAINNET_RPC = os.environ.get("SNRC_MAINNET_RPC", "") +LOCAL_RPC = "http://127.0.0.1:8545" +LOCAL_OWNER = "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266" +CONTACT = "https://localhost/a#ground-truth" +SIMPLEX_MAINNET = { + "SNRC_REGISTRY_SIMPLEX": "0xa7f6497be2f1aa41aa2db55aba8a6e0145dff0d2", + "SNRC_REGISTRAR_SIMPLEX": "0x44052f7dc9c1cef20b0319a6b75288988dbb12a1", + "SNRC_CONTROLLER_SIMPLEX": "0x8005011c6e966656cdb9a222e9a4792600a37219", +} + + +def get(url): + try: + with urlopen(url, timeout=30) as r: + return r.status, json.load(r) + except HTTPError as e: + return e.code, json.load(e) + + +def wait_for(url, process): + for _ in range(600): + if process.poll() is not None: + raise RuntimeError(f"{process.args[0]} exited with {process.returncode}") + try: + urlopen(url, timeout=1).close() + return + except HTTPError: + return + except OSError: + time.sleep(0.5) + raise TimeoutError(url) + + +def start_resolver(test_class, env): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + process = subprocess.Popen( + [sys.executable, os.path.join(HERE, "snrc-resolve.py")], + env={**os.environ, **env, "SNRC_BIND": "127.0.0.1", "SNRC_PORT": str(port), "SNRC_WORKERS": "1"}, + ) + test_class.addClassCleanup(process.terminate) + url = f"http://127.0.0.1:{port}" + wait_for(url + "/health", process) + return url + + +class GroundTruthTestCase(unittest.TestCase): + def registration(self, name): + status, body = get(f"{self.url}/v2/resolve/{name}") + self.assertEqual(status, 200, body) + return body["lastBlockTs"], body["registration"] + + def assert_registered(self, name, contact=None): + now, reg = self.registration(name) + self.assertEqual(reg["type"], "registered", name) + self.assertGreater(reg["graceUntil"], now) + if contact is not None: + self.assertEqual(reg["nameRecord"]["simplexContact"], contact) + return now, reg + + def assert_type(self, name, type_, **fields): + reg = self.registration(name)[1] + self.assertEqual(reg["type"], type_, name) + for key, value in fields.items(): + self.assertEqual(reg[key], value, name) + + +@unittest.skipUnless(CONTRACTS, "SNRC_CONTRACTS is not set") +class LocalChainTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + start = datetime.now(timezone.utc) - timedelta(days=900) + node = subprocess.Popen( + [os.path.join("node_modules", ".bin", "hardhat"), "--network", "hardhat", "node"], + cwd=os.path.join(CONTRACTS, "ens-contracts"), + env={**os.environ, "HARDHAT_INITIAL_DATE": start.isoformat()}, + stdout=subprocess.DEVNULL, + ) + cls.addClassCleanup(node.terminate) + wait_for(LOCAL_RPC, node) + env = {**os.environ, "SIMPLEX_TLD": "simplex", "RPC_URL": LOCAL_RPC, "CONTACT_LINK": CONTACT} + subprocess.run(["node", "scripts/deploy-local.mjs"], cwd=CONTRACTS, env=env, check=True) + with open(os.path.join(CONTRACTS, "deployments.local.json")) as f: + cls.addrs = json.load(f) + subprocess.run(["node", "scripts/seed-lookup-states.mjs"], cwd=CONTRACTS, env={**env, "ADDRS": json.dumps(cls.addrs)}, check=True) + cls.url = start_resolver(cls, { + "SNRC_RPC": LOCAL_RPC, + "SNRC_MULTICALL": cls.addrs["Multicall"], + "SNRC_REGISTRY_SIMPLEX": cls.addrs["ENSRegistry"], + "SNRC_REGISTRAR_SIMPLEX": cls.addrs["BaseRegistrarImplementation"], + "SNRC_CONTROLLER_SIMPLEX": cls.addrs["ETHRegistrarController"], + }) + + def test_a_live_name_is_registered_with_its_records(self): + now, reg = self.assert_registered("bakery.simplex", [CONTACT]) + self.assertGreater(reg["expires"], now) + self.assertEqual(reg["nameRecord"]["owner"], LOCAL_OWNER) + self.assert_registered("nolink.simplex", []) + + def test_a_name_in_grace_is_registered(self): + now, reg = self.assert_registered("expiring.simplex", [CONTACT]) + self.assertLess(reg["expires"], now) + + def test_a_held_subname_is_registered(self): + reg = self.assert_registered("menu.bakery.simplex")[1] + self.assertEqual(reg["nameRecord"]["name"], "menu.bakery.simplex") + self.assertEqual(reg["nameRecord"]["owner"], self.addrs["SubnameRegistrar"].lower()) + + def test_names_nobody_holds_are_available_at_the_launch_price(self): + pricing = {"registrationPrices": {}, "basePrice": 5000, "minLabelLength": 6} + for name in ("sunflower.simplex", "lapsed.simplex", "menu.expiring.simplex"): + self.assert_type(name, "available", pricing=pricing) + + def test_reserved_names_carry_their_reason(self): + for name, reason in (("simplex.simplex", "internal"), ("brandname.simplex", "trademark"), ("privacy.simplex", "community")): + self.assert_type(name, "reserved", reservedReason=reason) + + def test_v1_answers_each_state_by_its_status(self): + status, body = get(f"{self.url}/resolve/bakery.simplex") + self.assertEqual((status, body["simplexContact"]), (200, [CONTACT])) + for name, code in (("sunflower.simplex", 404), ("lapsed.simplex", 410), ("menu.expiring.simplex", 404)): + self.assertEqual(get(f"{self.url}/resolve/{name}")[0], code, name) + + +@unittest.skipUnless(MAINNET_RPC, "SNRC_MAINNET_RPC is not set") +class MainnetTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + cls.url = start_resolver(cls, {"SNRC_RPC": MAINNET_RPC, **SIMPLEX_MAINNET}) + + def test_known_names_are_registered(self): + self.assert_registered("foobar.testing", ["https://smp16.simplex.im/a#Q_F00BA7"]) + self.assert_registered("bitcoin.testing") + self.assert_registered("evgenypoberezkin.simplex") + + def test_reserved_names_carry_their_reason(self): + for name in ("simplex.testing", "simplex.simplex"): + self.assert_type(name, "reserved", reservedReason="internal") + + def test_a_name_nobody_registered_is_available(self): + for name in ("groundtruthcheck.testing", "groundtruthcheck.simplex"): + self.assert_type(name, "available") diff --git a/scripts/resolver/service/test_snrc_resolve.py b/scripts/resolver/service/test_snrc_resolve.py index 76c3ebc5f..e922f333f 100644 --- a/scripts/resolver/service/test_snrc_resolve.py +++ b/scripts/resolver/service/test_snrc_resolve.py @@ -2074,7 +2074,7 @@ def test_unknown_settings_are_refused_at_start(self): class DefaultsTests(unittest.TestCase): - def test_every_tld_has_all_three_contracts_by_default(self): + def test_both_tlds_resolve_on_mainnet_by_default(self): fresh = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(fresh) for table in (fresh.REGISTRIES, fresh.REGISTRARS, fresh.CONTROLLERS): diff --git a/scripts/simplexmq-reproduce-builds.sh b/scripts/simplexmq-reproduce-builds.sh index ec480b369..38638afd3 100755 --- a/scripts/simplexmq-reproduce-builds.sh +++ b/scripts/simplexmq-reproduce-builds.sh @@ -23,7 +23,8 @@ mkdir -p "$init_dir/$TAG-$repo_name/from-source" "$init_dir/$TAG-$repo_name/preb git -C "$tempdir" clone "$repo.git" &&\ cd "$tempdir/${repo_name}" &&\ - git checkout "$TAG" + git checkout "$TAG" &&\ + git submodule update --init --recursive for os in 22.04 24.04; do os_url="$(printf '%s' "$os" | tr '.' '_')" diff --git a/simplexmq.cabal b/simplexmq.cabal index 3b70db982..090d13af4 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 @@ -314,6 +319,7 @@ library Simplex.Messaging.Server.QueueStore.STM Simplex.Messaging.Server.QueueStore.Types Simplex.Messaging.Server.Stats + Simplex.Messaging.Server.StatsStore Simplex.Messaging.Server.StoreLog Simplex.Messaging.Server.StoreLog.ReadWrite Simplex.Messaging.Server.StoreLog.Types @@ -429,6 +435,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.* @@ -548,7 +556,7 @@ executable xftp-server apps/common default-extensions: StrictData - ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=incomplete-uni-patterns -Werror=missing-methods -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -O2 -threaded -rtsopts + ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=incomplete-uni-patterns -Werror=missing-methods -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -O2 -threaded -rtsopts "-with-rtsopts=-N -F1.2 -A16m -I0.01 -Iw15 -T -ki2k --disable-delayed-os-memory-return" build-depends: base , bytestring @@ -580,12 +588,15 @@ test-suite simplexmq-test CoreTests.CryptoTests CoreTests.EncodingTests CoreTests.EthCryptoTests + CoreTests.KeepAliveTests CoreTests.LockTests CoreTests.MsgStoreTests CoreTests.RetryIntervalTests CoreTests.SOCKSSettings + CoreTests.ServerStatsTests CoreTests.StoreLogTests CoreTests.TSessionSubs + CoreTests.TransportTests CoreTests.UtilTests CoreTests.VersionRangeTests FileDescriptionTests @@ -683,6 +694,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..be100e3d4 100644 --- a/src/Simplex/FileTransfer/Agent.hs +++ b/src/Simplex/FileTransfer/Agent.hs @@ -81,7 +81,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (strDecode, strEncode) import Simplex.Messaging.Protocol (ProtocolServer, ProtocolType (..), XFTPServer) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (allFinally, catchAll_, catchAllErrors, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) +import Simplex.Messaging.Util (allFinally, catchAll_, catchAllErrors, catchOwn_, handleAllErrors, ifM, liftError, tshow, unlessM, whenM) import System.FilePath (takeFileName, ()) import UnliftIO import UnliftIO.Directory @@ -196,11 +196,15 @@ runXFTPRcvWorker c srv Worker {doWork} = do cfg <- asks config forever $ do lift $ waitForWork doWork - liftIO $ assertAgentForeground c - runXFTPOperation cfg + withXFTPDownloadPermit c $ downloadChunks cfg where - runXFTPOperation :: AgentConfig -> AM () - runXFTPOperation AgentConfig {rcvFilesTTL, reconnectInterval = ri, xftpConsecutiveRetries} = + downloadChunks :: AgentConfig -> XFTPDownloadPermit -> AM () + downloadChunks cfg permit = do + liftIO $ assertAgentForeground c + runXFTPOperation cfg permit + unlessM (atomically $ isEmptyTMVar doWork) $ downloadChunks cfg permit + runXFTPOperation :: AgentConfig -> XFTPDownloadPermit -> AM () + runXFTPOperation AgentConfig {rcvFilesTTL, reconnectInterval = ri, xftpConsecutiveRetries} permit = withWork c doWork (\db -> getNextRcvChunkToDownload db srv rcvFilesTTL) $ \case (RcvFileChunk {rcvFileId, rcvFileEntityId, fileTmpPath, replicas = []}, _, redirectEntityId_) -> rcvWorkerInternalError c rcvFileId rcvFileEntityId redirectEntityId_ (Just fileTmpPath) (INTERNAL "chunk has no replicas") @@ -210,11 +214,12 @@ runXFTPRcvWorker c srv Worker {doWork} = do liftIO $ waitWhileSuspended c liftIO $ waitForUserNetwork c incXFTPServerStat c userId srv downloadAttempts - downloadFileChunk fc replica approvedRelays + downloadFileChunk permit fc replica approvedRelays `catchAllErrors` \e -> retryOnError "XFTP rcv worker" (retryLoop loop e delay') (retryDone e) e where retryLoop loop e replicaDelay = do flip catchAllErrors (\_ -> pure ()) $ do + liftIO $ releaseXFTPDownloadPermit c permit when (serverHostError e) $ notify c (fromMaybe rcvFileEntityId redirectEntityId_) (RFWARN e) liftIO $ closeXFTPServerClient c userId server digest withStore' c $ \db -> updateRcvChunkReplicaDelay db rcvChunkReplicaId replicaDelay @@ -225,15 +230,15 @@ runXFTPRcvWorker c srv Worker {doWork} = do XFTP _ XFTP.AUTH -> downloadAuthErrs _ -> downloadErrs rcvWorkerInternalError c rcvFileId rcvFileEntityId redirectEntityId_ (Just fileTmpPath) e - downloadFileChunk :: RcvFileChunk -> RcvFileChunkReplica -> Bool -> AM () - downloadFileChunk RcvFileChunk {userId, rcvFileId, rcvFileEntityId, rcvChunkId, chunkNo, chunkSize, digest, fileTmpPath} replica approvedRelays = do + downloadFileChunk :: XFTPDownloadPermit -> RcvFileChunk -> RcvFileChunkReplica -> Bool -> AM () + downloadFileChunk permit RcvFileChunk {userId, rcvFileId, rcvFileEntityId, rcvChunkId, chunkNo, chunkSize, digest, fileTmpPath} replica approvedRelays = do unlessM ((approvedRelays ||) <$> ipAddressProtected') $ throwE $ FILE NOT_APPROVED fsFileTmpPath <- lift $ toFSFilePath fileTmpPath chunkPath <- uniqueCombine fsFileTmpPath $ show chunkNo let chSize = unFileSize chunkSize chunkSpec = XFTPRcvChunkSpec chunkPath chSize (unFileDigest digest) relChunkPath = fileTmpPath takeFileName chunkPath - agentXFTPDownloadChunk c userId digest replica chunkSpec + agentXFTPDownloadChunk c permit userId digest replica chunkSpec liftIO $ waitUntilForeground c (entityId, complete, progress) <- handleAllErrors (rcvFileError c rcvFileId) . withStore c $ \db -> runExceptT $ do liftIO $ lockRcvFileForUpdate db rcvFileId @@ -316,9 +321,10 @@ runXFTPRcvLocalWorker c Worker {doWork} = do void $ liftError (FILE . FILE_IO . show) $ decryptChunks encSize chunkPaths key nonce $ \_ -> pure destFile case redirect of Nothing -> do + -- RFDONE lets the consumer delete the shared receive prefix. + -- Finish chunk cleanup before publishing completion. + lift $ forM_ tmpPath (removePath <=< toFSFilePath) notify c rcvFileEntityId $ RFDONE fsSavePath - flip catchAllErrors (\e -> logError $ "XFTP rcv worker error: " <> tshow e) $ - lift $ forM_ tmpPath (removePath <=< toFSFilePath) liftIO $ waitUntilForeground c withStore' c (`updateRcvFileComplete` rcvFileId) Just RcvFileRedirect {redirectFileInfo, redirectDbId} -> do @@ -360,7 +366,7 @@ xftpDeleteRcvFiles' c rcvFileEntityIds = do void $ batchFiles updateRcvFileDeleted toMarkDeleted workPath <- getXFTPWorkPath liftIO . forM_ toDelete $ \RcvFile {prefixPath} -> - (removePath . (workPath )) prefixPath `catchAll_` pure () + (removePath . (workPath )) prefixPath `catchOwn_` pure () where fileComplete RcvFile {status} = status == RFSComplete || status == RFSError batchFiles :: (DB.Connection -> DBRcvFileId -> IO a) -> [RcvFile] -> AM' [Either AgentErrorType a] @@ -669,7 +675,7 @@ deleteSndFilesInternal c sndFileEntityIds = flip E.finally (atomically $ mapM_ ( let (toDelete, toMarkDeleted) = partition fileComplete sndFiles workPath <- getXFTPWorkPath liftIO . forM_ toDelete $ \SndFile {prefixPath} -> - mapM_ (removePath . (workPath )) prefixPath `catchAll_` pure () + mapM_ (removePath . (workPath )) prefixPath `catchOwn_` pure () batchFiles_ deleteSndFile' toDelete batchFiles_ updateSndFileDeleted toMarkDeleted where @@ -682,7 +688,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/FileTransfer/Client/Agent.hs b/src/Simplex/FileTransfer/Client/Agent.hs index 55cae5d3c..0462b2450 100644 --- a/src/Simplex/FileTransfer/Client/Agent.hs +++ b/src/Simplex/FileTransfer/Client/Agent.hs @@ -34,7 +34,7 @@ import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ProtocolServer (..), XFTPServer) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (catchAll_) +import Simplex.Messaging.Util (catchOwn_) import UnliftIO type XFTPClientVar = TMVar (Either XFTPClientAgentError XFTPClient) @@ -132,5 +132,5 @@ closeXFTPServerClient XFTPClientAgent {xftpClients, config} srv = closeClient cVar = do let NetworkConfig {tcpConnectTimeout} = xftpNetworkConfig $ xftpConfig config netTimeoutInt tcpConnectTimeout NRMBackground `timeout` atomically (readTMVar cVar) >>= \case - Just (Right client) -> closeXFTPClient client `catchAll_` pure () + Just (Right client) -> closeXFTPClient client `catchOwn_` pure () _ -> pure () diff --git a/src/Simplex/FileTransfer/Client/Main.hs b/src/Simplex/FileTransfer/Client/Main.hs index 59dfc5e33..2bec1a6d8 100644 --- a/src/Simplex/FileTransfer/Client/Main.hs +++ b/src/Simplex/FileTransfer/Client/Main.hs @@ -12,11 +12,13 @@ module Simplex.FileTransfer.Client.Main ( SendOptions (..), + ReceiveOptions (..), CLIError (..), xftpClientCLI, xftpClientDeprecationNotice, cliSendFile, cliSendFileOpts, + cliReceiveFile, encodeWebURI, decodeWebURI, fileWebLink, @@ -61,7 +63,7 @@ import Simplex.FileTransfer.Description import Simplex.FileTransfer.Protocol import Simplex.FileTransfer.Transport (XFTPRcvChunkSpec (..)) import Simplex.FileTransfer.Types -import Simplex.FileTransfer.Util (uniqueCombine) +import Simplex.FileTransfer.Util (createNewFile, createUniqueDirectory, createUniqueFile, uniqueCombine) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.File (CryptoFile (..), FTCryptoError (..)) import qualified Simplex.Messaging.Crypto.File as CF @@ -70,6 +72,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (StrEncoding (..)) import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Protocol (ProtoServerWithAuth (..), ProtocolServer (..), SenderId, SndPrivateAuthKey, XFTPServer, XFTPServerWithAuth) +import Simplex.Messaging.ServiceScheme (SrvLoc (..)) import Simplex.Messaging.Util (groupAllOn, ifM, stateTVar', tshow, whenM) import System.Exit (exitFailure) import System.FilePath (splitFileName, ()) @@ -287,7 +290,7 @@ cliSendFileOpts SendOptions {filePath, outputDir, numRecipients, xftpServers, re encryptFileForUpload g fileName = do fileSize <- fromInteger <$> getFileSize filePath when (fileSize > maxFileSize) $ throwE $ CLIError $ "Files bigger than " <> maxFileSizeStr <> " are not supported" - encPath <- getEncPath tempPath "xftp" + encPath <- liftIO $ getTempPath tempPath >>= (`createUniqueFile` "xftp.encrypted") key <- atomically $ C.randomSbKey g nonce <- atomically $ C.randomCbNonce g let fileHdr = smpEncode FileHeader {fileName, fileExtra = Nothing} @@ -397,8 +400,8 @@ cliSendFileOpts SendOptions {filePath, outputDir, numRecipients, xftpServers, re sndReplicas (SentFileChunkReplica {server} : _) replicaId replicaKey = [FileChunkReplica {server, replicaId, replicaKey}] writeFileDescriptions :: String -> [FileDescription 'FRecipient] -> FileDescription 'FSender -> IO ([FilePath], FilePath) writeFileDescriptions fileName fdRcvs fdSnd = do - outDir <- uniqueCombine (fromMaybe "." outputDir) (fileName <> ".xftp") - createDirectoryIfMissing True outDir + forM_ outputDir $ createDirectoryIfMissing True + outDir <- createUniqueDirectory (fromMaybe "." outputDir) (fileName <> ".xftp") fdRcvPaths <- forM (zip [1 ..] fdRcvs) $ \(i :: Int, fd) -> do let fdPath = outDir ("rcv" <> show i <> ".xftp") B.writeFile fdPath $ strEncode fd @@ -419,8 +422,7 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, | otherwise = getFileDescription' fileDescription receive :: Int -> ValidFileDescription 'FRecipient -> ExceptT CLIError IO () receive depth (ValidFileDescription FileDescription {size, digest, key, nonce, chunks, redirect}) = do - encPath <- getEncPath tempPath "xftp" - createDirectory encPath + encPath <- liftIO $ getTempPath tempPath >>= (`createUniqueDirectory` "xftp.encrypted") a <- liftIO $ newXFTPAgent defaultXFTPClientAgentConfig liftIO $ printNoNewLine "Downloading file..." downloadedChunks <- newTVarIO [] @@ -448,7 +450,7 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, | otherwise -> throwE $ CLIError "Redirect chain too long" Nothing -> do liftIO $ printNoNewLine "Decrypting file..." - CryptoFile path _ <- withExceptT cliCryptoError $ decryptChunks encSize chunkPaths key nonce $ fmap CF.plain . getFilePath + CryptoFile path _ <- withExceptT cliCryptoError $ decryptChunks encSize chunkPaths key nonce $ fmap CF.plain . createFilePath whenM (doesPathExist encPath) $ removeDirectoryRecursive encPath liftIO $ do printNoNewLine $ "File downloaded: " <> path @@ -469,12 +471,12 @@ cliReceiveFile ReceiveOptions {fileDescription, filePath, retryCount, tempPath, when verbose $ putStrLn "" pure (chunkNo, chunkPath) downloadFileChunk _ _ _ _ _ _ = throwE $ CLIError "chunk has no replicas" - getFilePath :: Text -> ExceptT String IO FilePath - getFilePath name = case filePath of + createFilePath :: Text -> ExceptT String IO FilePath + createFilePath name = case filePath of Just path -> - ifM (doesDirectoryExist path) (uniqueCombine path name') $ - ifM (doesFileExist path) (throwE "File already exists") (pure path) - _ -> (`uniqueCombine` name') . ( "Downloads") =<< getHomeDirectory + ifM (doesDirectoryExist path) (liftIO $ createUniqueFile path name') $ + ifM (doesFileExist path) (throwE "File already exists") (path <$ createNewFile path) + _ -> liftIO . (`createUniqueFile` name') . ( "Downloads") =<< getHomeDirectory where name' = T.unpack name @@ -534,8 +536,8 @@ getFileDescription' path = getFileDescription path >>= \case AVFD fd -> either (throwE . CLIError) pure $ checkParty fd -getEncPath :: MonadIO m => Maybe FilePath -> String -> m FilePath -getEncPath path name = (`uniqueCombine` (name <> ".encrypted")) =<< maybe (liftIO getCanonicalTemporaryDirectory) pure path +getTempPath :: Maybe FilePath -> IO FilePath +getTempPath = maybe getCanonicalTemporaryDirectory pure withReconnect :: Show e => XFTPClientAgent -> XFTPServer -> Int -> (XFTPClient -> ExceptT e IO a) -> ExceptT CLIError IO a withReconnect a srv n run = withRetry n $ do @@ -601,9 +603,9 @@ decodeWebURI fragment = do strDecode yaml >>= validateFileDescription -- | Extract web link host and URI fragment from a file description. --- Returns (hostname, uriFragment) for https://hostname/#uriFragment. +-- Returns (authority, uriFragment) for https://authority/#uriFragment. fileWebLink :: FileDescription 'FRecipient -> Maybe (B.ByteString, B.ByteString) fileWebLink fd@FileDescription {chunks} = case chunks of (FileChunk {replicas = FileChunkReplica {server = ProtocolServer {host}} : _} : _) -> - Just (strEncode (L.head host), encodeWebURI fd) + Just (strEncode (SrvLoc (L.head host) ""), encodeWebURI fd) _ -> Nothing diff --git a/src/Simplex/FileTransfer/Description.hs b/src/Simplex/FileTransfer/Description.hs index bfc1896fd..9e90783da 100644 --- a/src/Simplex/FileTransfer/Description.hs +++ b/src/Simplex/FileTransfer/Description.hs @@ -234,6 +234,7 @@ instance StrEncoding AFileDescription where validateFileDescription :: FileDescription p -> Either String (ValidFileDescription p) validateFileDescription fd@FileDescription {size, chunks, redirect} + | null chunks = Left "no chunks" | chunkNos /= [1 .. length chunks] = Left "chunk numbers are not sequential" | chunksSize chunks /= unFileSize size = Left "chunks total size is different than file size" | any incorrectChunkSize chunks = Left "incorrect chunk size" diff --git a/src/Simplex/FileTransfer/Server.hs b/src/Simplex/FileTransfer/Server.hs index 35cab97e1..9605b0fdc 100644 --- a/src/Simplex/FileTransfer/Server.hs +++ b/src/Simplex/FileTransfer/Server.hs @@ -25,18 +25,20 @@ import Control.Monad.Reader import Control.Monad.Trans.Except import qualified Data.Aeson as J import Data.Bifunctor (first) +import qualified Data.ByteString.Base64.URL as B64 import Data.ByteString.Builder (Builder, byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB +import Data.Either (fromRight) import Data.Int (Int64) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Text as T import qualified Data.Text.IO as T -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (systemSeconds, utcToSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import Data.Word (Word32) @@ -76,20 +78,21 @@ import Simplex.Messaging.Transport.Buffer (trimCR) import Simplex.Messaging.Transport.HTTP2 import Simplex.Messaging.Transport.HTTP2.File (fileBlockSize) import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) -import Simplex.Messaging.Transport.Server (SNICredentialUsed, TransportServerConfig (..), runLocalTCPServer) +import Simplex.Messaging.Transport.Server (SNICredentialUsed, SocketState, TransportServerConfig (..), getSocketStats, runLocalTCPServer) import Simplex.Messaging.Server.Web (serveStaticPageH2) import Simplex.Messaging.Util import Simplex.Messaging.Version import System.Environment (lookupEnv) import System.Exit (exitFailure) -import System.FilePath (()) +import System.FilePath (takeExtension, ()) import System.IO (hPrint, hPutStrLn, universalNewlineMode) +import System.IO.Error (isDoesNotExistError) #ifdef slow_servers import System.Random (getStdRandom, randomR) #endif import UnliftIO import UnliftIO.Concurrent (threadDelay) -import UnliftIO.Directory (canonicalizePath, doesFileExist, removeFile, renameFile) +import UnliftIO.Directory (canonicalizePath, doesDirectoryExist, doesFileExist, listDirectory, removeFile, renameFile) import qualified UnliftIO.Exception as E type M s a = ReaderT (XFTPEnv s) IO a @@ -99,6 +102,7 @@ data XFTPTransportRequest = XFTPTransportRequest reqBody :: HTTP2Body, request :: H.Request, sendResponse :: H.Response -> IO (), + closeSession :: IO (), sniUsed :: SNICredentialUsed, addCORS :: Bool } @@ -133,8 +137,10 @@ data EntitlementChecked = EntNotChecked | EntChecked (Maybe SessionEntitlement) xftpServer :: forall s. FileStoreClass s => XFTPServerConfig s -> TMVar Bool -> M s () xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpiration, fileExpiration, xftpServerVRange, information} started = do - expireServerFiles Nothing fileExpiration restoreServerStats + expireServerFiles Nothing fileExpiration `onException` stopServer + removeTmpUploads + removeUnstoredFiles raceAny_ ( runServer : expireFiles fileExpiration @@ -156,25 +162,28 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira let cleanup sessionId = atomically $ TM.delete sessionId sessions srvParams = if isJust httpCreds_ then defaultSupportedParamsHTTPS else defaultSupportedParams webCanonicalRoot_ <- liftIO $ mapM canonicalizePath (webStaticPath cfg) - liftIO . runHTTP2Server started xftpPort defaultHTTP2BufferSize srvParams srvCreds httpCreds_ transportConfig inactiveClientExpiration cleanup $ \sniUsed sessionId sessionALPN r sendResponse -> do + socketState <- asks sockets + liftIO . runHTTP2Server socketState started xftpPort defaultHTTP2BufferSize srvParams srvCreds httpCreds_ transportConfig inactiveClientExpiration cleanup $ \sniUsed closeSession sessionId sessionALPN r sendResponse -> do let addCORS' = sniUsed && addCORSHeaders transportConfig case H.requestMethod r of Just "OPTIONS" | addCORS' -> sendResponse $ H.responseNoBody N.ok200 corsPreflightHeaders Just "GET" | sniUsed -> forM_ webCanonicalRoot_ $ \root -> serveStaticPageH2 root r sendResponse - _ -> do - reqBody <- getHTTP2Body r xftpBlockSize - let v = VersionXFTP 1 - thServerVRange = versionToRange v - thParams0 = THandleParams {sessionId, blockSize = xftpBlockSize, thVersion = v, thServerVRange, thAuth = Nothing, implySessId = False, encryptBlock = Nothing, serviceAuth = False, serverInfo = Nothing} - req0 = XFTPTransportRequest {thParams = thParams0, request = r, reqBody, sendResponse, sniUsed, addCORS = addCORS'} - flip runReaderT env $ case sessionALPN of - Nothing -> processRequest req0 - Just alpn - | alpn == xftpALPNv1 || alpn == httpALPN11 || (sniUsed && alpn == "h2") -> - xftpServerHandshakeV1 chain signKey sessions req0 >>= \case - Nothing -> pure () - Just thParams -> processRequest req0 {thParams} - | otherwise -> liftIO . sendResponse $ H.responseNoBody N.ok200 (corsHeaders addCORS') + _ -> + timeout (fileTimeout cfg) (getHTTP2Body r xftpBlockSize) >>= \case + Nothing -> logWarn "request receiving timeout, closing connection" >> closeSession + Just reqBody -> do + let v = VersionXFTP 1 + thServerVRange = versionToRange v + thParams0 = THandleParams {sessionId, blockSize = xftpBlockSize, thVersion = v, thServerVRange, thAuth = Nothing, implySessId = False, encryptBlock = Nothing, serviceAuth = False, serverInfo = Nothing} + req0 = XFTPTransportRequest {thParams = thParams0, request = r, reqBody, sendResponse, closeSession, sniUsed, addCORS = addCORS'} + flip runReaderT env $ case sessionALPN of + Nothing -> processRequest req0 + Just alpn + | alpn == xftpALPNv1 || alpn == httpALPN11 || (sniUsed && alpn == "h2") -> + xftpServerHandshakeV1 chain signKey sessions req0 >>= \case + Nothing -> pure () + Just thParams -> processRequest req0 {thParams} + | otherwise -> liftIO . sendResponse $ H.responseNoBody N.ok200 (corsHeaders addCORS') xftpServerHandshakeV1 :: X.CertificateChain -> C.APrivateSignKey -> TMap SessionId Handshake -> XFTPTransportRequest -> M s (Maybe (THandleParams XFTPVersion 'TServer)) xftpServerHandshakeV1 chain serverSignKey sessions XFTPTransportRequest {thParams = thParams0@THandleParams {sessionId}, request, reqBody = HTTP2Body {bodyHead}, sendResponse, sniUsed, addCORS} = do s <- atomically $ TM.lookup sessionId sessions @@ -282,13 +291,21 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira serverStatsThread_ :: XFTPServerConfig s -> [M s ()] serverStatsThread_ XFTPServerConfig {logStatsInterval = Just interval, logStatsStartTime, serverStatsLogFile} = [logServerStats logStatsStartTime interval serverStatsLogFile] - serverStatsThread_ _ = [] + serverStatsThread_ XFTPServerConfig {logStatsStartTime} = [resetPeriodStats logStatsStartTime] + + resetPeriodStats :: Int64 -> M s () + resetPeriodStats startAt = do + FileServerStats {filesDownloaded} <- asks serverStats + liftIO $ do + delayUntilDayTime startAt + forever $ do + void . periodStatCounts filesDownloaded =<< getCurrentTime + threadDelay' $ 1_000_000 * periodStatsInterval logServerStats :: Int64 -> Int64 -> FilePath -> M s () logServerStats startAt logInterval statsFilePath = do - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime liftIO $ putStrLn $ "server stats log enabled: " <> statsFilePath - liftIO $ threadDelay' $ 1_000_000 * (initialDelay + if initialDelay < 0 then 86_400 else 0) + liftIO $ delayUntilDayTime startAt FileServerStats {fromTime, filesCreated, fileRecipients, filesUploaded, filesExpired, filesDeleted, filesDownloaded, fileDownloads, fileDownloadAcks, filesCount, filesSize} <- asks serverStats let interval = 1_000_000 * logInterval forever $ do @@ -335,21 +352,23 @@ xftpServer cfg@XFTPServerConfig {xftpPort, transportConfig, inactiveClientExpira labelMyThread "savePrometheusMetrics" liftIO $ putStrLn $ "Prometheus metrics saved every " <> show saveInterval <> " seconds to " <> metricsFile ss <- asks serverStats + socketState <- asks sockets rtsOpts <- liftIO $ maybe ("set " <> rtsOptionsEnv) T.pack <$> lookupEnv (T.unpack rtsOptionsEnv) let interval = 1000000 * saveInterval saveMetrics = do ts <- getCurrentTime - sm <- getFileServerMetrics ss rtsOpts + sm <- getFileServerMetrics ss socketState rtsOpts writeFileAtomic metricsFile (xftpPrometheusMetrics sm ts) liftIO $ forever $ do threadDelay interval saveMetrics `catchAny` \e -> logError $ "Prometheus metrics error: " <> tshow e - getFileServerMetrics :: FileServerStats -> T.Text -> IO FileServerMetrics - getFileServerMetrics ss rtsOptions = do + getFileServerMetrics :: FileServerStats -> SocketState -> T.Text -> IO FileServerMetrics + getFileServerMetrics ss socketState rtsOptions = do d <- getFileServerStatsData ss + socketStats <- (xftpPort,) <$> getSocketStats socketState let fd = periodStatDataCounts $ _filesDownloaded d - pure FileServerMetrics {statsData = d, filesDownloadedPeriods = fd, rtsOptions} + pure FileServerMetrics {statsData = d, filesDownloadedPeriods = fd, socketStats, rtsOptions} controlPortThread_ :: XFTPServerConfig s -> [M s ()] controlPortThread_ XFTPServerConfig {controlPort = Just port} = [runCPServer port] @@ -423,7 +442,7 @@ data ServerFile = ServerFile } processRequest :: FileStoreClass s => XFTPTransportRequest -> M s () -processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHead}, sendResponse, addCORS} +processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHead}, sendResponse, closeSession, addCORS} | B.length bodyHead /= xftpBlockSize = sendXFTPResponse ("", NoEntity, FRErr BLOCK) Nothing | otherwise = case xftpDecodeTServer thParams bodyHead of @@ -440,21 +459,25 @@ processRequest XFTPTransportRequest {thParams, reqBody = body@HTTP2Body {bodyHea where sendXFTPResponse t' serverFile_ = do let t_ = xftpEncodeTransmission thParams t' + sendTimeout <- asks $ fileTimeout . config #ifdef slow_servers randomDelay #endif - liftIO $ sendResponse $ H.responseStreaming N.ok200 (corsHeaders addCORS) $ streamBody t_ + liftIO $ case t_ of + Left _ -> sendResponse $ responseBuilder paddingError + Right t -> case serverFile_ of + Nothing -> sendResponse $ responseBuilder $ byteString t + Just serverFile -> withAsync (closeAfter sendTimeout) $ \_ -> sendResponse $ H.responseStreaming N.ok200 (corsHeaders addCORS) $ streamBody t serverFile where - streamBody t_ send done = do - case t_ of - Left _ -> do - send "padding error" -- TODO respond with BLOCK error? - done - Right t -> do - send $ byteString t - -- timeout sending file in the same way as receiving - forM_ serverFile_ $ \ServerFile {filePath, fileSize, sbState} -> do - withFile filePath ReadMode $ \h -> sendEncFile h send sbState fileSize + responseBuilder = H.responseBuilder N.ok200 (corsHeaders addCORS) + paddingError = "padding error" -- TODO respond with BLOCK error? + closeAfter sendTimeout = do + threadDelay sendTimeout + logWarn "file sending timeout, closing connection" + closeSession + streamBody t ServerFile {filePath, fileSize, sbState} send done = do + send $ byteString t + withFile filePath ReadMode $ \h -> sendEncFile h send sbState fileSize done #ifdef slow_servers @@ -500,7 +523,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case XFTPServerConfig {allowNewFiles, newFileBasicAuth} <- asks config pure $ allowNewFiles && maybe True ((== auth) . Just) newFileBasicAuth XFTPReqCmd fId fr (FileCmd _ cmd) -> case cmd of - FADD rks -> noFile =<< addRecipients fId rks + FADD rks -> noFile =<< addFileRecipients fId rks FPUT -> noFile =<< receiveServerFile fr FDEL -> noFile =<< deleteServerFile fr FGET rDhKey -> sendServerFile fr rDhKey @@ -514,7 +537,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case createFile :: FileInfo -> NonEmpty RcvPublicAuthKey -> Maybe Word32 -> M s FileResponse createFile file rks storageHours = do st <- asks fileStore - r <- runExceptT $ do + r <- mask_ $ runExceptT $ do sizes <- asks $ allowedChunkSizes . config unless (size file `elem` sizes) $ throwE SIZE now <- liftIO getSystemSeconds @@ -527,7 +550,7 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case fileExpiresAt = RoundedSystemTime $ ((nowSeconds + secs + fileTimePrecision - 1) `div` fileTimePrecision) * fileTimePrecision -- TODO validate body empty sId <- ExceptT $ addFileRetry st file 3 ts (Just fileExpiresAt) - rcps <- mapM (ExceptT . addRecipientRetry st 3 sId) rks + rcps <- ExceptT $ addRecipientsRetry st 3 sId rks lift $ withFileLog $ \sl -> do logAddFile sl sId file ts (Just fileExpiresAt) EntityActive logAddRecipients sl sId rcps @@ -545,27 +568,22 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case _ -> defaultMax addFileRetry :: s -> FileInfo -> Int -> RoundedFileTime -> Maybe RoundedFileTime -> M s (Either XFTPErrorType XFTPFileId) addFileRetry st file n ts expiresAt = - retryAdd n $ \sId -> runExceptT $ do - ExceptT $ addFile st sId file ts expiresAt EntityActive - pure sId - addRecipientRetry :: s -> Int -> XFTPFileId -> RcvPublicAuthKey -> M s (Either XFTPErrorType FileRecipient) - addRecipientRetry st n sId rpk = - retryAdd n $ \rId -> runExceptT $ do - let rcp = FileRecipient rId rpk - ExceptT $ addRecipient st sId rcp - pure rcp - retryAdd :: Int -> (XFTPFileId -> IO (Either XFTPErrorType a)) -> M s (Either XFTPErrorType a) - retryAdd 0 _ = pure $ Left INTERNAL - retryAdd n add = do - fId <- getFileId - liftIO (add fId) >>= \case - Left DUPLICATE_ -> retryAdd (n - 1) add + retryAdd n getFileId $ \sId -> (sId <$) <$> addFile st sId file ts expiresAt EntityActive + addRecipientsRetry :: s -> Int -> XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s (Either XFTPErrorType (NonEmpty FileRecipient)) + addRecipientsRetry st n sId rks = + retryAdd n (mapM (\rpk -> (`FileRecipient` rpk) <$> getFileId) rks) $ \rcps -> (rcps <$) <$> addRecipients st sId rcps + retryAdd :: Int -> M s a -> (a -> IO (Either XFTPErrorType b)) -> M s (Either XFTPErrorType b) + retryAdd 0 _ _ = pure $ Left INTERNAL + retryAdd n newIds add = do + ids <- newIds + liftIO (add ids) >>= \case + Left DUPLICATE_ -> retryAdd (n - 1) newIds add r -> pure r - addRecipients :: XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s FileResponse - addRecipients sId rks = do + addFileRecipients :: XFTPFileId -> NonEmpty RcvPublicAuthKey -> M s FileResponse + addFileRecipients sId rks = do st <- asks fileStore - r <- runExceptT $ do - rcps <- mapM (ExceptT . addRecipientRetry st 3 sId) rks + r <- mask_ $ runExceptT $ do + rcps <- ExceptT $ addRecipientsRetry st 3 sId rks lift $ withFileLog $ \sl -> logAddRecipients sl sId rcps stats <- asks serverStats liftIO $ atomicModifyIORef'_ (fileRecipients stats) (+ length rks) @@ -573,14 +591,39 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case pure $ FRRcvIds rIds pure $ either FRErr id r receiveServerFile :: FileRec -> M s FileResponse - receiveServerFile FileRec {senderId, fileInfo = FileInfo {size, digest}, filePath} = case bodyPart of + receiveServerFile FileRec {senderId, fileInfo = FileInfo {size, digest}} = case bodyPart of Nothing -> pure $ FRErr SIZE -- TODO validate body size from request before downloading, once it's populated - Just getBody -> skipCommitted $ mask $ \restore -> ifM reserve (receive restore) (pure $ FRErr QUOTA) + Just getBody -> do + receivedBody <- newTVarIO False + let getBody' n = getBody n >>= \bs -> bs <$ when (not $ B.null bs) (atomically $ writeTVar receivedBody True) + replaceUpload receivedBody $ receiveUncommitted getBody' >>= maybe skipCommitted pure where + replaceUpload receivedBody upload = do + uploads <- asks uploadingFiles + prevUpload <- newEmptyTMVarIO + let startUpload = do + a <- asyncWithUnmask $ \unmask -> uninterruptibleMask_ (atomically $ readTMVar prevUpload) >>= mapM_ cancel >> unmask upload + a <$ atomically (TM.lookupInsert senderId a uploads >>= putTMVar prevUpload) + removeUpload a = atomically (TM.alter (mfilter (/= a)) senderId uploads) + bracket startUpload removeUpload waitCatch >>= \case + Right r -> pure r + Left e + | isAsyncCancellation e -> ifM (readTVarIO receivedBody) (pure $ FRErr TIMEOUT) skipCommitted + | otherwise -> pure $ FRErr TIMEOUT -- having a filePath means the file is already uploaded and committed, must not change anything - skipCommitted = ifM (isJust <$> readTVarIO filePath) (liftIO $ drain $ fromIntegral size) + receiveUncommitted getBody' = do + st <- asks fileStore + liftIO (getFile st SFSender senderId) >>= \case + Right (FileRec {filePath}, _) -> + ifM (isJust <$> readTVarIO filePath) (pure Nothing) $ + Just <$> mask (\restore -> ifM reserve (receive getBody' restore) (pure $ FRErr QUOTA)) + Left e -> pure $ Just $ FRErr e + skipCommitted = drainCommitted where + drainCommitted = do + t <- asks $ fileTimeout . config + liftIO $ fromMaybe (FRErr TIMEOUT) <$> timeout t (drain $ fromIntegral size) -- can't send FROk without reading the request body or a client will block on sending it -- can't send any old error as the client would fail or restart indefinitely drain s = do @@ -594,11 +637,14 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case quota <- asks $ fromMaybe maxBound . fileSizeQuota . config atomically . stateTVar' us $ \used -> let used' = used + fromIntegral size in if used' <= quota then (True, used') else (False, used) - receive restore = do + receive getBody' restore = do path <- asks $ filesPath . config + tmpId <- randomId 12 let fPath = path serverFileName senderId - (restore (receiveChunk $ XFTPRcvChunkSpec fPath size digest) `onException` release fPath) >>= \case + tmpPath = fPath <> "." <> B.unpack (strEncode tmpId) <> tmpUploadExtension + (restore (receiveChunk getBody' $ XFTPRcvChunkSpec tmpPath size digest) `onException` release tmpPath) >>= \case Right () -> do + renameFile tmpPath fPath stats <- asks serverStats st <- asks fileStore liftIO (setFilePath st senderId fPath) >>= \case @@ -608,15 +654,26 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case incFileStat filesCount liftIO $ atomicModifyIORef'_ (filesSize stats) (+ fromIntegral size) pure FROk - Left _e -> FRErr AUTH <$ release fPath - Left e -> FRErr e <$ release fPath - release fPath = do + Left _e -> releaseQuota >> uploadedResponse fPath + Left e -> FRErr e <$ release tmpPath + uploadedResponse fPath = do + st <- asks fileStore + liftIO (getFile st SFSender senderId) >>= \case + Right (FileRec {filePath = uploadedPath, fileStatus}, _) -> + (,) <$> readTVarIO uploadedPath <*> readTVarIO fileStatus >>= \case + (Just _, _) -> pure FROk + (Nothing, EntityActive) -> pure $ FRErr AUTH + _ -> FRErr AUTH <$ removeUpload fPath + Left AUTH -> FRErr AUTH <$ removeUpload fPath + Left e -> pure $ FRErr e + release fPath = releaseQuota >> removeUpload fPath + releaseQuota = do us <- asks usedStorage atomically $ modifyTVar' us $ subtract (fromIntegral size) - liftIO $ whenM (doesFileExist fPath) (removeFile fPath) `catch` logFileError - receiveChunk spec = do + removeUpload fPath = liftIO $ whenM (doesFileExist fPath) (removeFile fPath) `catch` logFileError + receiveChunk getBody' spec = do t <- asks $ fileTimeout . config - liftIO $ fromMaybe (Left TIMEOUT) <$> timeout t (runExceptT $ receiveFile getBody spec) + liftIO $ fromMaybe (Left TIMEOUT) <$> timeout t (runExceptT $ receiveFile getBody' spec) sendServerFile :: FileRec -> RcvPublicDhKey -> M s (FileResponse, Maybe ServerFile) sendServerFile FileRec {senderId, filePath, fileInfo = FileInfo {size}} rDhKey = do readTVarIO filePath >>= \case @@ -652,31 +709,27 @@ processXFTPRequest ent HTTP2Body {bodyPart} = \case -- pure FROk deleteServerFile_ :: FileStoreClass s => FileRec -> M s (Either XFTPErrorType ()) -deleteServerFile_ fr@FileRec {senderId} = do +deleteServerFile_ fr@FileRec {senderId} = mask_ $ do withFileLog (`logDeleteFile` senderId) deleteOrBlockServerFile_ fr filesDeleted (`deleteFile` senderId) -- this also deletes the file from storage, but doesn't include it in delete statistics blockServerFile :: FileStoreClass s => FileRec -> BlockingInfo -> M s (Either XFTPErrorType ()) -blockServerFile fr@FileRec {senderId} info = do +blockServerFile fr@FileRec {senderId} info = mask_ $ do withFileLog $ \sl -> logBlockFile sl senderId info - deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info True + deleteOrBlockServerFile_ fr filesBlocked $ \st -> blockFile st senderId info -deleteOrBlockServerFile_ :: FileStoreClass s => FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType ())) -> M s (Either XFTPErrorType ()) +deleteOrBlockServerFile_ :: FileRec -> (FileServerStats -> IORef Int) -> (s -> IO (Either XFTPErrorType (Maybe FilePath))) -> M s (Either XFTPErrorType ()) deleteOrBlockServerFile_ FileRec {filePath, fileInfo} stat storeAction = mask_ $ runExceptT $ do path <- readTVarIO filePath - stats <- asks serverStats - ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (forM_ path $ \p -> whenM (doesFileExist p) (removeFile p >> deletedStats stats)) + ExceptT $ first (\(_ :: SomeException) -> FILE_IO) <$> try (forM_ path $ \p -> whenM (doesFileExist p) (removeFile p)) st <- asks fileStore - ExceptT $ liftIO $ storeAction st - forM_ path $ \_ -> do - us <- asks usedStorage - atomically $ modifyTVar' us $ subtract (fromIntegral $ size fileInfo) + removed <- ExceptT $ liftIO $ storeAction st + forM_ removed $ \p -> lift $ do + subtractStoredFile $ size fileInfo + whenM (doesFileExist p) $ + removeFile p `catch` \(e :: SomeException) -> logError $ "failed to remove file " <> tshow p <> ": " <> tshow e lift $ incFileStat stat - where - deletedStats stats = do - liftIO $ atomicModifyIORef'_ (filesCount stats) (subtract 1) - liftIO $ atomicModifyIORef'_ (filesSize stats) (subtract $ fromIntegral $ size fileInfo) entitlementValid :: SystemSeconds -> SystemSeconds -> Bool entitlementValid now expiresAt = roundedSeconds expiresAt + 86400 > roundedSeconds now @@ -690,27 +743,45 @@ expireServerFiles itemDelay expCfg = do old <- liftIO $ expireBeforeEpoch expCfg filesCount <- liftIO $ getFileCount st logNote $ "Expiration check: " <> tshow filesCount <> " files" - expireLoop st us now old + expireLoop st now old usedEnd <- readTVarIO us logNote $ "Used " <> mbs usedStart <> " -> " <> mbs usedEnd <> ", " <> mbs (usedStart - usedEnd) <> " reclaimed." where mbs bs = tshow (bs `div` 1048576) <> "mb" - expireLoop st us now old = do + expireLoop st now old = do expired <- liftIO $ expiredFiles st now old 10000 - forM_ expired $ \(_, filePath_, _) -> do - mapM_ threadDelay itemDelay - forM_ filePath_ $ \fp -> - whenM (doesFileExist fp) $ - removeFile fp `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e let sIds = map (\(sId, _, _) -> sId) expired unless (null sIds) $ do + uploads <- asks uploadingFiles + forM_ sIds $ \sId -> atomically (TM.lookupDelete sId uploads) >>= mapM_ cancel withFileLog $ \sl -> mapM_ (logDeleteFile sl) sIds - liftIO $ deleteFiles st sIds - forM_ expired $ \(_, filePath_, fileSize) -> do - forM_ filePath_ $ \_ -> - atomically $ modifyTVar' us $ subtract (fromIntegral fileSize) + deleted <- liftIO $ deleteFiles st sIds + forM_ deleted $ \(_, filePath_, fileSize) -> do + forM_ filePath_ $ \fp -> do + whenM (doesFileExist fp) $ + (removeFile fp >> mapM_ threadDelay itemDelay) `catch` \(e :: SomeException) -> logError $ "failed to remove expired file " <> tshow fp <> ": " <> tshow e + subtractStoredFile fileSize incFileStat filesExpired - expireLoop st us now old + expireLoop st now old + +periodStatsInterval :: Int64 +periodStatsInterval = 86400 + +removeUnstoredFiles :: FileStoreClass s => M s () +removeUnstoredFiles = do + dir <- asks $ filesPath . config + st <- asks fileStore + whenM ((> 0) <$> liftIO (getFileCount st)) $ do + removed <- filterM (unstored st) =<< listDirectory dir + forM_ removed $ \f -> removeFile (dir f) `catchAny` \_ -> pure () + unless (null removed) $ logNote $ "Removed " <> tshow (length removed) <> " files without records" + where + unstored st name = case B64.decode $ B.pack name of + Right sId -> + liftIO (getFile st SFSender $ EntityId sId) >>= \case + Right (FileRec {filePath}, _) -> isNothing <$> readTVarIO filePath + Left e -> pure $ e == AUTH + Left _ -> pure False randomId :: Int -> M s ByteString randomId n = atomically . C.randomBytes n =<< asks random @@ -726,6 +797,24 @@ incFileStat statSel = do stats <- asks serverStats liftIO $ atomicModifyIORef'_ (statSel stats) (+ 1) +tmpUploadExtension :: String +tmpUploadExtension = ".tmp" + +removeTmpUploads :: M s () +removeTmpUploads = do + path <- asks $ filesPath . config + whenM (doesDirectoryExist path) $ + listDirectory path >>= mapM_ (removeFile . (path )) . filter ((tmpUploadExtension ==) . takeExtension) + +subtractStoredFile :: Word32 -> M s () +subtractStoredFile storedSize = do + us <- asks usedStorage + atomically $ modifyTVar' us $ subtract (fromIntegral storedSize) + stats <- asks serverStats + liftIO $ do + atomicModifyIORef'_ (filesCount stats) (subtract 1) + atomicModifyIORef'_ (filesSize stats) (subtract $ fromIntegral storedSize) + saveServerStats :: M s () saveServerStats = asks (serverStatsBackupFile . config) @@ -736,7 +825,7 @@ saveServerStats = B.writeFile f $ strEncode stats logNote "server stats saved" -restoreServerStats :: FileStoreClass s => M s () +restoreServerStats :: M s () restoreServerStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStats where restoreStats f = whenM (doesFileExist f) $ do @@ -744,9 +833,8 @@ restoreServerStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStat liftIO (strDecode <$> B.readFile f) >>= \case Right d@FileServerStatsData {_filesCount = statsFilesCount, _filesSize = statsFilesSize} -> do s <- asks serverStats - st <- asks fileStore - _filesCount <- liftIO $ getFileCount st - _filesSize <- readTVarIO =<< asks usedStorage + _filesCount <- readIORef $ filesCount s + _filesSize <- readIORef $ filesSize s liftIO $ setFileServerStats s d {_filesCount, _filesSize} renameFile f $ f <> ".bak" logNote "server stats restored" diff --git a/src/Simplex/FileTransfer/Server/Env.hs b/src/Simplex/FileTransfer/Server/Env.hs index 516e83bbc..8e7bbc7ba 100644 --- a/src/Simplex/FileTransfer/Server/Env.hs +++ b/src/Simplex/FileTransfer/Server/Env.hs @@ -22,16 +22,20 @@ module Simplex.FileTransfer.Server.Env fileStore, fromFileStore, defaultInactiveClientExpiration, + defaultXFTPKeepAlive, + defaultXFTPUserTimeout, defFileExpirationHours, defaultFileExpiration, newXFTPServerEnv, readFileStoreType, runWithStoreConfig, + migrateFileStore, checkFileStoreMode, importToDatabase, exportFromDatabase, ) where +import Control.Concurrent.Async (Async) import Control.Logger.Simple import Control.Monad import Crypto.Random @@ -45,7 +49,7 @@ import Data.Word (Word16, Word32) import Data.X509.Validation (Fingerprint (..)) import Network.Socket import qualified Network.TLS as T -import Simplex.FileTransfer.Protocol (FileCmd, FileInfo (..), XFTPFileId) +import Simplex.FileTransfer.Protocol (FileCmd, FileInfo (..), FileResponse, XFTPFileId) import Simplex.FileTransfer.Server.Stats import Data.Either (fromRight) import Data.Ini (Ini, lookupValue) @@ -66,11 +70,14 @@ import Simplex.FileTransfer.Server.StoreLog import Simplex.FileTransfer.Transport (VersionRangeXFTP) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.BBS (BBSPublicKey) -import Simplex.Messaging.Protocol (BasicAuth, RcvPublicAuthKey) +import Simplex.Messaging.Protocol (BasicAuth, RcvPublicAuthKey, SenderId) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.Information (ServerPublicInfo) +import Simplex.Messaging.TMap (TMap) +import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport (EntitlementConfig (..)) -import Simplex.Messaging.Transport.Server (ReloadableCredential, ServerCredentials (..), TransportServerConfig (..), acceptCredential, loadFingerprint, loadServerCredential, newReloadableCredential) +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts (..)) +import Simplex.Messaging.Transport.Server (ReloadableCredential, ServerCredentials (..), SocketState, TransportServerConfig (..), acceptCredential, loadFingerprint, loadServerCredential, newReloadableCredential, newSocketState) import Simplex.Messaging.Util (tshow) import System.IO (IOMode (..)) import UnliftIO.STM @@ -127,16 +134,30 @@ defaultInactiveClientExpiration = checkInterval = 3600 -- seconds, 1 hours } +defaultXFTPKeepAlive :: KeepAliveOpts +defaultXFTPKeepAlive = + KeepAliveOpts + { keepIdle = 60, + keepIntvl = 10, + keepCnt = 6, + unackedDataTimeout = Nothing + } + +defaultXFTPUserTimeout :: Int +defaultXFTPUserTimeout = 180000 + data XFTPEnv s = XFTPEnv { config :: XFTPServerConfig s, store :: FileStore s, usedStorage :: TVar Int64, + uploadingFiles :: TMap SenderId (Async FileResponse), storeLog :: Maybe (StoreLog 'WriteMode), random :: TVar ChaChaDRG, serverIdentity :: C.KeyHash, tlsServerCreds :: T.Credential, httpServerCreds :: Maybe ReloadableCredential, - serverStats :: FileServerStats + serverStats :: FileServerStats, + sockets :: SocketState } fileStore :: XFTPEnv s -> s @@ -201,16 +222,18 @@ newXFTPServerEnv config@XFTPServerConfig {serverStoreCfg, fileSizeQuota, fileExp st <- newFileStore dbCfg pure (StoreDatabase st, Nothing) #endif - used <- getUsedStorage (fromFileStore store) + (storedCount, used) <- getUsedStorage (fromFileStore store) usedStorage <- newTVarIO used + uploadingFiles <- TM.emptyIO forM_ fileSizeQuota $ \quota -> do logNote $ "Total / available storage: " <> tshow quota <> " / " <> tshow (quota - used) when (quota < used) $ logWarn "WARNING: storage quota is less than used storage, no files can be uploaded!" tlsServerCreds <- loadServerCredential xftpCredentials httpServerCreds <- forM httpCredentials $ \creds -> newReloadableCredential acceptCredential creds =<< loadServerCredential creds Fingerprint fp <- loadFingerprint xftpCredentials - serverStats <- newFileServerStats =<< getCurrentTime - pure XFTPEnv {config, store, usedStorage, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats} + serverStats <- newFileServerStats storedCount used =<< getCurrentTime + sockets <- newSocketState + pure XFTPEnv {config, store, usedStorage, uploadingFiles, storeLog, random, tlsServerCreds, httpServerCreds, serverIdentity = C.KeyHash fp, serverStats, sockets} data XFTPRequest = XFTPReqNew FileInfo (NonEmpty RcvPublicAuthKey) (Maybe BasicAuth) (Maybe Word32) @@ -247,6 +270,13 @@ runWithStoreConfig (AFSType SFSPostgres) ini storeLogFilePath confirmMigrations error "server binary is compiled without support for PostgreSQL database" #endif +migrateFileStore :: XFTPStoreConfig s -> IO () +migrateFileStore = \case + XSCMemory _ -> pure () +#if defined(dbServerPostgres) + XSCDatabase dbCfg -> (newFileStore dbCfg :: IO PostgresFileStore) >>= closeFileStore +#endif + -- | Validate startup config when store_files=database. checkFileStoreMode :: Ini -> AFStoreType -> FilePath -> IO () checkFileStoreMode ini (AFSType SFSPostgres) storeLogFilePath = do diff --git a/src/Simplex/FileTransfer/Server/Main.hs b/src/Simplex/FileTransfer/Server/Main.hs index 18b6a620c..dd5f65d61 100644 --- a/src/Simplex/FileTransfer/Server/Main.hs +++ b/src/Simplex/FileTransfer/Server/Main.hs @@ -32,7 +32,7 @@ import Options.Applicative import Simplex.FileTransfer.Chunks import Simplex.FileTransfer.Description (FileSize (..)) import Simplex.FileTransfer.Server (runXFTPServer) -import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig, AFStoreType (..), defFileExpirationHours, defaultFileExpiration, defaultInactiveClientExpiration, readFileStoreType, runWithStoreConfig, checkFileStoreMode, importToDatabase, exportFromDatabase) +import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig, AFStoreType (..), defFileExpirationHours, defaultFileExpiration, defaultInactiveClientExpiration, defaultXFTPKeepAlive, defaultXFTPUserTimeout, readFileStoreType, runWithStoreConfig, migrateFileStore, checkFileStoreMode, importToDatabase, exportFromDatabase) import Simplex.FileTransfer.Transport (alpnSupportedXFTPhandshakes, supportedFileServerVRange) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Entitlement (entitlementIssuerKeys) @@ -50,6 +50,7 @@ import Simplex.Messaging.Transport.HTTP2 (httpALPN) import Simplex.Messaging.Transport.Server (ServerCredentials (..), TransportServerConfig (..), acceptCredential, defaultCredentialCheckInterval, mkTransportServerConfig) import Simplex.Messaging.Util (eitherToMaybe, safeDecodeUtf8, tshow) import System.Directory (createDirectoryIfMissing, doesFileExist) +import System.Exit (exitSuccess) import System.FilePath (combine) import System.IO (BufferMode (..), hSetBuffering, stderr, stdout) import Text.Read (readMaybe) @@ -92,7 +93,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do iniFile = combine cfgPath "file-server.ini" serverVersion = "SimpleX XFTP server v" <> simplexmqVersionCommit defaultServerPort = "443" - executableName = "file-server" + executableName = "xftp-server" storeLogFilePath = combine logPath "file-server-store.log" defaultStaticPath = combine logPath "www" runDatabaseCmd cmd ini = case cmd of @@ -201,9 +202,9 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do <> "\n\ \[INACTIVE_CLIENTS]\n\ \# TTL and interval to check inactive clients\n\ - \disconnect = off\n" - <> ("# ttl = " <> tshow (ttl defaultInactiveClientExpiration) <> "\n") - <> ("# check_interval = " <> tshow (checkInterval defaultInactiveClientExpiration) <> "\n") + \disconnect = on\n" + <> ("ttl = " <> tshow (ttl defaultInactiveClientExpiration) <> "\n") + <> ("check_interval = " <> tshow (checkInterval defaultInactiveClientExpiration) <> "\n") <> "\n\ \[WEB]\n\ \# Set path to generate static mini-site for server information\n" @@ -213,7 +214,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do \# TLS credentials for HTTPS web server on the same port as XFTP.\n\ \# cert = " <> T.pack (cfgPath `combine` "web.crt") <> "\n\ \# key = " <> T.pack (cfgPath `combine` "web.key") <> "\n" - runServer StartOptions {confirmMigrations} ini = do + runServer StartOptions {maintenance, confirmMigrations} ini = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering fp <- checkSavedFingerprint cfgPath defaultX509Config @@ -228,6 +229,10 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do Right fsType -> do checkFileStoreMode ini fsType storeLogFilePath runWithStoreConfig fsType ini storeLogFilePath confirmMigrations $ \storeCfg -> do + when maintenance $ do + migrateFileStore storeCfg + putStrLn "Server started in 'maintenance' mode, exiting" + exitSuccess let cfg = serverConfig storeCfg printXFTPConfig cfg case webStaticPath' of @@ -331,7 +336,7 @@ xftpServerCLI_ generateSite serveStaticFiles cfgPath logPath = do (fromMaybe False $ iniOnOff "TRANSPORT" "log_tls_errors" ini) (Just $ alpnSupportedXFTPhandshakes <> httpALPN) False - in cfg {addCORSHeaders = isJust httpCredentials_}, + in cfg {addCORSHeaders = isJust httpCredentials_, tcpKeepAlive = Just defaultXFTPKeepAlive, tcpUserTimeout = Just defaultXFTPUserTimeout}, responseDelay = 0, webStaticPath = webStaticPath' } @@ -345,8 +350,9 @@ data CliCommand data StoreCmd = SCImport | SCExport -newtype StartOptions = StartOptions - { confirmMigrations :: MigrationConfirmation +data StartOptions = StartOptions + { maintenance :: Bool, + confirmMigrations :: MigrationConfirmation } data InitOptions = InitOptions @@ -435,6 +441,12 @@ cliCommandP cfgPath logPath iniFile = pure InitOptions {enableStoreLog, signAlgorithm, ip, fqdn, filesPath, fileSizeQuota, webStaticPath} startOptsP :: Parser StartOptions startOptsP = do + maintenance <- + switch + ( long "maintenance" + <> short 'm' + <> help "Do not start the server, only apply database migrations" + ) confirmMigrations <- option parseConfirmMigrations @@ -443,7 +455,7 @@ cliCommandP cfgPath logPath iniFile = <> help "Confirm PostgreSQL database migration: up, down (default is manual confirmation)" <> value MCConsole ) - pure StartOptions {confirmMigrations} + pure StartOptions {maintenance, confirmMigrations} storeCmdP :: Parser StoreCmd storeCmdP = hsubparser diff --git a/src/Simplex/FileTransfer/Server/Prometheus.hs b/src/Simplex/FileTransfer/Server/Prometheus.hs index f30525822..987d20766 100644 --- a/src/Simplex/FileTransfer/Server/Prometheus.hs +++ b/src/Simplex/FileTransfer/Server/Prometheus.hs @@ -16,14 +16,17 @@ import qualified Data.Text as T import Data.Time.Clock (UTCTime (..), diffUTCTime) import Data.Time.Clock.System (systemEpochDay) import Data.Time.Format.ISO8601 (iso8601Show) +import Network.Socket (ServiceName) import Simplex.FileTransfer.Server.Stats import Simplex.Messaging.Server.Stats (PeriodStatCounts (..)) import Simplex.Messaging.Transport (simplexMQVersion) +import Simplex.Messaging.Transport.Server (SocketStats (..)) import Simplex.Messaging.Util (tshow) data FileServerMetrics = FileServerMetrics { statsData :: FileServerStatsData, filesDownloadedPeriods :: PeriodStatCounts, + socketStats :: (ServiceName, SocketStats), rtsOptions :: Text } @@ -35,7 +38,7 @@ xftpPrometheusMetrics :: FileServerMetrics -> UTCTime -> Text xftpPrometheusMetrics sm ts = time <> files <> info where - FileServerMetrics {statsData, filesDownloadedPeriods, rtsOptions} = sm + FileServerMetrics {statsData, filesDownloadedPeriods, socketStats = (port, sockets), rtsOptions} = sm FileServerStatsData { _fromTime, _filesCreated, @@ -87,7 +90,7 @@ xftpPrometheusMetrics sm ts = \simplex_xftp_files_blocked " <> mshow _filesBlocked <> "\n\ \# filesBlocked\n\ \\n\ - \# HELP simplex_xftp_file_downloads File downloads\n\ + \# HELP simplex_xftp_file_downloads Started file downloads\n\ \# TYPE simplex_xftp_file_downloads counter\n\ \simplex_xftp_file_downloads " <> mshow _fileDownloads <> "\n\ \# fileDownloads\n\ @@ -97,27 +100,27 @@ xftpPrometheusMetrics sm ts = \simplex_xftp_file_download_acks " <> mshow _fileDownloadAcks <> "\n\ \# fileDownloadAcks\n\ \\n\ - \# HELP simplex_xftp_files_count_total Total files count \n\ + \# HELP simplex_xftp_files_count_total Stored files\n\ \# TYPE simplex_xftp_files_count_total gauge\n\ \simplex_xftp_files_count_total " <> mshow _filesCount <> "\n\ \# filesCount\n\ \\n\ - \# HELP simplex_xftp_files_size Size of files \n\ + \# HELP simplex_xftp_files_size Size of stored files, bytes\n\ \# TYPE simplex_xftp_files_size gauge\n\ \simplex_xftp_files_size " <> mshow _filesSize <> "\n\ \# filesSize \n\ \\n\ - \# HELP simplex_xftp_files_count_daily Daily files count\n\ + \# HELP simplex_xftp_files_count_daily Distinct files downloaded in the current day\n\ \# TYPE simplex_xftp_files_count_daily gauge\n\ \simplex_xftp_files_count_daily " <> mstr (dayCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.dayCount\n\ \\n\ - \# HELP simplex_xftp_files_count_weekly Weekly files count\n\ + \# HELP simplex_xftp_files_count_weekly Distinct files downloaded in the current week\n\ \# TYPE simplex_xftp_files_count_weekly gauge\n\ \simplex_xftp_files_count_weekly " <> mstr (weekCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.weekCount\n\ \\n\ - \# HELP simplex_xftp_files_count_monthly Monthly files count\n\ + \# HELP simplex_xftp_files_count_monthly Distinct files downloaded in the current month\n\ \# TYPE simplex_xftp_files_count_monthly gauge\n\ \simplex_xftp_files_count_monthly " <> mstr (monthCount filesDownloadedPeriods) <> "\n\ \# filesDownloaded.monthCount\n\ @@ -130,6 +133,16 @@ xftpPrometheusMetrics sm ts = \# TYPE simplex_xftp_info gauge\n\ \simplex_xftp_info{version=\"" <> T.pack simplexMQVersion <> "\",rts_options=\"" <> rtsOptions <> "\"} 1\n\ \\n" + <> socketsMetric socketsAccepted "simplex_xftp_sockets_accepted" "Accepted sockets" + <> socketsMetric socketsClosed "simplex_xftp_sockets_closed" "Closed sockets" + <> socketsMetric socketsActive "simplex_xftp_sockets_active" "Active sockets" + <> socketsMetric socketsLeaked "simplex_xftp_sockets_leaked" "Leaked sockets" + socketsMetric :: (SocketStats -> Int) -> Text -> Text -> Text + socketsMetric sel metric descr = + "# HELP " <> metric <> " " <> descr <> "\n" + <> "# TYPE " <> metric <> " gauge\n" + <> metric <> "{port=\"" <> T.pack port <> "\"} " <> mshow (sel sockets) <> "\n" + <> "\n" mstr a = a <> " " <> tsEpoch mshow :: Show a => a -> Text mshow = mstr . tshow diff --git a/src/Simplex/FileTransfer/Server/Stats.hs b/src/Simplex/FileTransfer/Server/Stats.hs index 619413839..9e7f8ec31 100644 --- a/src/Simplex/FileTransfer/Server/Stats.hs +++ b/src/Simplex/FileTransfer/Server/Stats.hs @@ -50,8 +50,8 @@ data FileServerStatsData = FileServerStatsData } deriving (Show) -newFileServerStats :: UTCTime -> IO FileServerStats -newFileServerStats ts = do +newFileServerStats :: Int -> Int64 -> UTCTime -> IO FileServerStats +newFileServerStats storedCount storedSize ts = do fromTime <- newIORef ts filesCreated <- newIORef 0 fileRecipients <- newIORef 0 @@ -62,8 +62,8 @@ newFileServerStats ts = do filesDownloaded <- newPeriodStats fileDownloads <- newIORef 0 fileDownloadAcks <- newIORef 0 - filesCount <- newIORef 0 - filesSize <- newIORef 0 + filesCount <- newIORef storedCount + filesSize <- newIORef storedSize pure FileServerStats {fromTime, filesCreated, fileRecipients, filesUploaded, filesExpired, filesDeleted, filesBlocked, filesDownloaded, fileDownloads, fileDownloadAcks, filesCount, filesSize} getFileServerStatsData :: FileServerStats -> IO FileServerStatsData diff --git a/src/Simplex/FileTransfer/Server/Store.hs b/src/Simplex/FileTransfer/Server/Store.hs index 371a5eea4..fc37296da 100644 --- a/src/Simplex/FileTransfer/Server/Store.hs +++ b/src/Simplex/FileTransfer/Server/Store.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} @@ -24,7 +25,10 @@ import Data.Kind (Type) import Control.Concurrent.STM import Control.Monad import qualified Data.Attoparsec.ByteString.Char8 as A +import Data.Either (rights) import Data.Int (Int64) +import Data.List.NonEmpty (NonEmpty) +import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, isJust) import Data.Set (Set) @@ -41,7 +45,7 @@ import System.IO (IOMode (..)) import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Util (ifM) +import Simplex.Messaging.Util (anyM, ifM) data FSType = FSMemory | FSPostgres @@ -77,16 +81,15 @@ class FileStoreClass s where closeFileStore :: s -> IO () addFile :: s -> SenderId -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> IO (Either XFTPErrorType ()) setFilePath :: s -> SenderId -> FilePath -> IO (Either XFTPErrorType ()) - addRecipient :: s -> SenderId -> FileRecipient -> IO (Either XFTPErrorType ()) - deleteFile :: s -> SenderId -> IO (Either XFTPErrorType ()) - deleteFiles :: s -> [SenderId] -> IO () - deleteFiles s = mapM_ (void . deleteFile s) - blockFile :: s -> SenderId -> BlockingInfo -> Bool -> IO (Either XFTPErrorType ()) + addRecipients :: s -> SenderId -> NonEmpty FileRecipient -> IO (Either XFTPErrorType ()) + deleteFile :: s -> SenderId -> IO (Either XFTPErrorType (Maybe FilePath)) + deleteFiles :: s -> [SenderId] -> IO [(SenderId, Maybe FilePath, Word32)] + blockFile :: s -> SenderId -> BlockingInfo -> IO (Either XFTPErrorType (Maybe FilePath)) deleteRecipient :: s -> RecipientId -> FileRec -> IO () getFile :: s -> SFileParty p -> XFTPFileId -> IO (Either XFTPErrorType (FileRec, C.APublicAuthKey)) ackFile :: s -> RecipientId -> IO (Either XFTPErrorType ()) expiredFiles :: s -> SystemSeconds -> Int64 -> Int -> IO [(SenderId, Maybe FilePath, Word32)] - getUsedStorage :: s -> IO Int64 + getUsedStorage :: s -> IO (Int, Int64) getFileCount :: s -> IO Int -- STM in-memory store @@ -125,28 +128,31 @@ instance FileStoreClass STMFileStore where pure $ Right () _ -> pure $ Left AUTH - addRecipient st@STMFileStore {recipients} senderId (FileRecipient rId rKey) = atomically $ + addRecipients st@STMFileStore {recipients} senderId rcps = atomically $ withFile st senderId $ \FileRec {recipientIds} -> do rIds <- readTVar recipientIds - mem <- TM.member rId recipients - if rId `S.member` rIds || mem + let newIds = map (\(FileRecipient rId _) -> rId) $ L.toList rcps + newIdSet = S.fromList newIds + stored <- anyM $ map (`TM.member` recipients) newIds + if S.size newIdSet /= length newIds || not (S.disjoint newIdSet rIds) || stored then pure $ Left DUPLICATE_ else do - writeTVar recipientIds $! S.insert rId rIds - TM.insert rId (senderId, rKey) recipients + writeTVar recipientIds $! S.union newIdSet rIds + forM_ rcps $ \(FileRecipient rId rKey) -> TM.insert rId (senderId, rKey) recipients pure $ Right () - deleteFile STMFileStore {files, recipients} senderId = atomically $ do - TM.lookupDelete senderId files >>= \case - Just FileRec {recipientIds} -> do - readTVar recipientIds >>= mapM_ (`TM.delete` recipients) - pure $ Right () - _ -> pure $ Left AUTH + deleteFile st senderId = atomically $ deleteFileRec st senderId >>= maybe (pure $ Left AUTH) (fmap Right . readTVar . filePath) + + deleteFiles st = fmap catMaybes . mapM (atomically . deleteFileSize) + where + deleteFileSize sId = + deleteFileRec st sId >>= mapM (\FileRec {fileInfo = FileInfo {size}, filePath} -> (sId,,size) <$> readTVar filePath) - blockFile st senderId info _deleted = atomically $ - withFile st senderId $ \FileRec {fileStatus} -> do + blockFile st senderId info = atomically $ + withFile st senderId $ \FileRec {filePath, fileStatus} -> do + path <- swapTVar filePath Nothing writeTVar fileStatus $! EntityBlocked info - pure $ Right () + pure $ Right path deleteRecipient STMFileStore {recipients} rId FileRec {recipientIds} = atomically $ do TM.delete rId recipients @@ -179,15 +185,19 @@ instance FileStoreClass STMFileStore where pure $ Just (sId, path, size) else pure Nothing - getUsedStorage STMFileStore {files} = foldM addSize 0 =<< readTVarIO files + getUsedStorage STMFileStore {files} = foldM addSize (0, 0) =<< readTVarIO files where - addSize acc FileRec {fileInfo = FileInfo {size}, filePath} = - ifM (isJust <$> readTVarIO filePath) (pure $! acc + fromIntegral size) (pure acc) + addSize acc@(!n, !used) FileRec {fileInfo = FileInfo {size}, filePath} = + ifM (isJust <$> readTVarIO filePath) (pure (n + 1, used + fromIntegral size)) (pure acc) getFileCount STMFileStore {files} = M.size <$> readTVarIO files -- Internal STM helpers +deleteFileRec :: STMFileStore -> SenderId -> STM (Maybe FileRec) +deleteFileRec STMFileStore {files, recipients} senderId = + TM.lookupDelete senderId files >>= mapM (\fr@FileRec {recipientIds} -> fr <$ (readTVar recipientIds >>= mapM_ (`TM.delete` recipients))) + newFileRec :: SenderId -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> STM FileRec newFileRec senderId fileInfo createdAt expiresAt status = do recipientIds <- newTVar S.empty diff --git a/src/Simplex/FileTransfer/Server/Store/Postgres.hs b/src/Simplex/FileTransfer/Server/Store/Postgres.hs index af040e902..dfb15567b 100644 --- a/src/Simplex/FileTransfer/Server/Store/Postgres.hs +++ b/src/Simplex/FileTransfer/Server/Store/Postgres.hs @@ -11,6 +11,7 @@ module Simplex.FileTransfer.Server.Store.Postgres ( PostgresFileStore (..), importFileStore, exportFileStore, + withDB', ) where @@ -46,7 +47,7 @@ import Simplex.FileTransfer.Server.Store.Postgres.Migrations (xftpServerMigratio import Simplex.FileTransfer.Server.StoreLog import Simplex.FileTransfer.Transport (XFTPErrorType (..)) import Simplex.Messaging.Agent.Store.Postgres (closeDBStore, createDBStore) -import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withRetriedTransaction, withTransaction) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationConfirmation (..)) import qualified Simplex.Messaging.Crypto as C @@ -100,31 +101,35 @@ instance FileStoreClass PostgresFileStore where DB.execute db "UPDATE files SET file_path = ? WHERE sender_id = ? AND file_path IS NULL AND status = 'active'" (fPath, sId) withLog "setFilePath" st $ \s -> logPutFile s sId fPath - addRecipient st senderId (FileRecipient rId rKey) = E.uninterruptibleMask_ $ runExceptT $ do - void $ withDB "addRecipient" st $ \db -> + addRecipients st senderId rcps = E.uninterruptibleMask_ $ runExceptT $ do + void $ withDB "addRecipients" st $ \db -> E.try - ( DB.execute + ( DB.executeMany db "INSERT INTO recipients (recipient_id, sender_id, recipient_key) VALUES (?,?,?)" - (rId, senderId, Binary (C.encodePubKey rKey)) + (map (\(FileRecipient rId rKey) -> (rId, senderId, Binary (C.encodePubKey rKey))) $ L.toList rcps) ) >>= either handleDuplicate (pure . Right) - withLog "addRecipient" st $ \s -> logAddRecipients s senderId (pure $ FileRecipient rId rKey) + withLog "addRecipients" st $ \s -> logAddRecipients s senderId rcps deleteFile st sId = E.uninterruptibleMask_ $ runExceptT $ do - assertUpdated $ withDB' "deleteFile" st $ \db -> - DB.execute db "DELETE FROM files WHERE sender_id = ?" (Only sId) + path <- withDB "deleteFile" st $ \db -> + firstRow fromOnly AUTH $ DB.query db "DELETE FROM files WHERE sender_id = ? RETURNING file_path" (Only sId) withLog "deleteFile" st $ \s -> logDeleteFile s sId + pure path deleteFiles st sIds = E.uninterruptibleMask_ $ do - withTransaction (dbStore st) $ \db -> - DB.execute db "DELETE FROM files WHERE sender_id IN ?" (Only (In sIds)) - withLog "deleteFiles" st $ \s -> mapM_ (logDeleteFile s) sIds - - blockFile st sId info _deleted = E.uninterruptibleMask_ $ runExceptT $ do - assertUpdated $ withDB' "blockFile" st $ \db -> - DB.execute db "UPDATE files SET status = ? WHERE sender_id = ?" (EntityBlocked info, sId) + deleted <- fmap toFileSizes $ withRetriedTransaction (dbStore st) $ \db -> + DB.query db "DELETE FROM files WHERE sender_id IN ? RETURNING sender_id, file_path, file_size" (Only (In sIds)) + withLog "deleteFiles" st $ \s -> mapM_ (\(sId, _, _) -> logDeleteFile s sId) deleted + pure deleted + + blockFile st sId info = E.uninterruptibleMask_ $ runExceptT $ do + path <- withDB "blockFile" st $ \db -> + firstRow fromOnly AUTH (DB.query db "SELECT file_path FROM files WHERE sender_id = ? FOR UPDATE" (Only sId)) + >>= mapM (\p -> p <$ DB.execute db "UPDATE files SET status = ?, file_path = NULL WHERE sender_id = ?" (EntityBlocked info, sId)) withLog "blockFile" st $ \s -> logBlockFile s sId info + pure path deleteRecipient st rId _fr = void $ runExceptT $ withDB' "deleteRecipient" st $ \db -> @@ -154,19 +159,16 @@ instance FileStoreClass PostgresFileStore where withLog "ackFile" st $ \s -> logAckFile s rId expiredFiles st now old limit = - fmap toResult $ withTransaction (dbStore st) $ \db -> + fmap toFileSizes $ withTransaction (dbStore st) $ \db -> DB.query db - "(SELECT sender_id, file_path, file_size FROM files WHERE expires_at < ? LIMIT ?) UNION ALL (SELECT sender_id, file_path, file_size FROM files WHERE expires_at IS NULL AND created_at < ? LIMIT ?)" - (roundedSeconds now, limit, old - fileTimePrecision, limit) - where - toResult :: [(SenderId, Maybe FilePath, Int32)] -> [(SenderId, Maybe FilePath, Word32)] - toResult = map (\(sId, path, size) -> (sId, path, fromIntegral size)) + "SELECT sender_id, file_path, file_size FROM ((SELECT sender_id, file_path, file_size FROM files WHERE expires_at < ? LIMIT ?) UNION ALL (SELECT sender_id, file_path, file_size FROM files WHERE expires_at IS NULL AND created_at < ? LIMIT ?)) expired LIMIT ?" + (roundedSeconds now, limit, old - fileTimePrecision, limit, limit) getUsedStorage st = withTransaction (dbStore st) $ \db -> do - [Only total] <- DB.query_ db "SELECT COALESCE(SUM(file_size::BIGINT), 0)::BIGINT FROM files WHERE file_path IS NOT NULL" - pure total + [(count, total)] <- DB.query_ db "SELECT COUNT(*), COALESCE(SUM(file_size::BIGINT), 0)::BIGINT FROM files WHERE file_path IS NOT NULL" + pure (fromIntegral (count :: Int64), total) getFileCount st = withTransaction (dbStore st) $ \db -> do @@ -175,6 +177,9 @@ instance FileStoreClass PostgresFileStore where -- Internal helpers +toFileSizes :: [(SenderId, Maybe FilePath, Int32)] -> [(SenderId, Maybe FilePath, Word32)] +toFileSizes = map (\(sId, path, size) -> (sId, path, fromIntegral size)) + mkFileRec :: SenderId -> FileInfo -> Maybe FilePath -> RoundedFileTime -> Maybe RoundedFileTime -> ServerEntityStatus -> IO FileRec mkFileRec senderId fileInfo path createdAt expiresAt status = do filePath <- newTVarIO path @@ -196,7 +201,7 @@ rowToFileRec (sId, size, digest, sndKeyBs, path, createdAt, expiresAt, status) = withDB :: forall a. Text -> PostgresFileStore -> (DB.Connection -> IO (Either XFTPErrorType a)) -> ExceptT XFTPErrorType IO a withDB op st action = - ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr + ExceptT $ withRetriedTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either XFTPErrorType a) logErr e = logError ("STORE: " <> err) $> Left INTERNAL diff --git a/src/Simplex/FileTransfer/Server/StoreLog.hs b/src/Simplex/FileTransfer/Server/StoreLog.hs index 5a6d99c7a..82479f2b5 100644 --- a/src/Simplex/FileTransfer/Server/StoreLog.hs +++ b/src/Simplex/FileTransfer/Server/StoreLog.hs @@ -23,6 +23,7 @@ where import Control.Applicative (optional, (<|>)) import Control.Concurrent.STM +import Control.Monad (void) import Control.Monad.Except import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString.Base64.URL as B64 @@ -124,11 +125,10 @@ readFileStore f st = mapM_ (addFileLogRecord . LB.toStrict) . LB.lines =<< LB.re PutFile qId path | takeFileName path == serverFileName qId -> setFilePath st qId path | otherwise -> pure $ Left AUTH - AddRecipients sId rcps -> runExceptT $ addRecipients sId rcps - DeleteFile sId -> deleteFile st sId - BlockFile sId info -> blockFile st sId info True + AddRecipients sId rcps -> addRecipients st sId rcps + DeleteFile sId -> void <$> deleteFile st sId + BlockFile sId info -> void <$> blockFile st sId info AckFile rId -> ackFile st rId - addRecipients sId rcps = mapM_ (ExceptT . addRecipient st sId) rcps writeFileStore :: StoreLog 'WriteMode -> STMFileStore -> IO () writeFileStore s STMFileStore {files, recipients} = do diff --git a/src/Simplex/FileTransfer/Transport.hs b/src/Simplex/FileTransfer/Transport.hs index f32b4ad70..e6aa0bb27 100644 --- a/src/Simplex/FileTransfer/Transport.hs +++ b/src/Simplex/FileTransfer/Transport.hs @@ -45,6 +45,8 @@ import Control.Monad import Control.Monad.Except import Control.Monad.IO.Class import Control.Monad.Trans.Except +import Crypto.Hash (Context, hashFinalize, hashInit, hashUpdate) +import Crypto.Hash.Algorithms (SHA256) import qualified Data.Aeson.TH as J import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Bifunctor (first) @@ -52,8 +54,8 @@ import qualified Data.ByteArray as BA import Data.ByteString.Builder (Builder, byteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B -import qualified Data.ByteString.Lazy.Char8 as LB import Data.Functor (($>)) +import Data.IORef (modifyIORef', newIORef, readIORef) import Data.Word (Word16, Word32) import Network.HTTP2.Client (HTTP2Error) import qualified Simplex.Messaging.Crypto as C @@ -195,13 +197,13 @@ sendEncFile h send = go go sbState sz = getFileChunk h sz >>= \ch -> do let (encCh, sbState') = LC.sbEncryptChunk sbState ch - send (byteString encCh) `E.catch` \(e :: E.SomeException) -> print e >> E.throwIO e + send (byteString encCh) `E.catch` \(e :: E.SomeException) -> logInfo ("sendEncFile: " <> tshow e) >> E.throwIO e go sbState' $ sz - fromIntegral (B.length ch) receiveFile :: (Int -> IO ByteString) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E.catches` handlers where - receive h sz = hReceiveFile getBody h sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE + receive write sz = receiveFileBlocks getBody write sz >>= \sz' -> pure $ if sz' == 0 then Right () else Left SIZE handlers = [ E.Handler $ \(e :: HTTP2Error) -> logWarn (err e) $> Left TIMEOUT, E.Handler $ \(e :: E.SomeException) -> if isAsyncCancellation e then E.throwIO e else logError (err e) $> Left FILE_IO @@ -211,14 +213,17 @@ receiveFile getBody chunk = ExceptT $ runExceptT (receiveFile_ receive chunk) `E receiveEncFile :: (Int -> IO ByteString) -> LC.SbState -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveEncFile getBody = receiveFile_ . receive where - receive sbState h sz = first err <$> receiveSbFile getBody h sbState sz + receive sbState write sz = first err <$> receiveSbBlocks getBody write sbState sz err RFESize = SIZE err RFECrypto = CRYPTO data ReceiveFileError = RFESize | RFECrypto receiveSbFile :: (Int -> IO ByteString) -> Handle -> LC.SbState -> Word32 -> IO (Either ReceiveFileError ()) -receiveSbFile getBody h = receive +receiveSbFile getBody h = receiveSbBlocks getBody (B.hPut h) + +receiveSbBlocks :: (Int -> IO ByteString) -> (ByteString -> IO ()) -> LC.SbState -> Word32 -> IO (Either ReceiveFileError ()) +receiveSbBlocks getBody write = receive where receive sbState sz = do ch <- getBody fileBlockSize @@ -229,7 +234,7 @@ receiveSbFile getBody h = receive let (ch', rest) = B.splitAt (fromIntegral sz) ch (decCh, sbState') = LC.sbDecryptChunk sbState ch' sz' = sz - fromIntegral (B.length ch') - B.hPut h decCh + write decCh if sz' > 0 then receive sbState' sz' else do @@ -241,14 +246,16 @@ receiveSbFile getBody h = receive | otherwise -> pure $ Left RFESize authSz = fromIntegral C.authTagSize -receiveFile_ :: (Handle -> Word32 -> IO (Either XFTPErrorType ())) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () +receiveFile_ :: ((ByteString -> IO ()) -> Word32 -> IO (Either XFTPErrorType ())) -> XFTPRcvChunkSpec -> ExceptT XFTPErrorType IO () receiveFile_ receive XFTPRcvChunkSpec {filePath, chunkSize, chunkDigest} = do + hashCtx <- liftIO $ newIORef (hashInit :: Context SHA256) + let write h ch = B.hPut h ch >> modifyIORef' hashCtx (`hashUpdate` ch) #if __GLASGOW_HASKELL__ == 810 - ExceptT $ UE.bracket (openFile filePath WriteMode) hClose (`receive` chunkSize) + ExceptT $ UE.bracket (openFile filePath WriteMode) hClose $ \h -> receive (write h) chunkSize #else - ExceptT $ withFile filePath WriteMode (`receive` chunkSize) + ExceptT $ withFile filePath WriteMode $ \h -> receive (write h) chunkSize #endif - digest' <- liftIO $ LC.sha256Hash <$> LB.readFile filePath + digest' <- liftIO $ BA.convert . hashFinalize <$> readIORef hashCtx when (digest' /= chunkDigest) $ throwE DIGEST data XFTPErrorType diff --git a/src/Simplex/FileTransfer/Util.hs b/src/Simplex/FileTransfer/Util.hs index 661a2fd5c..38025fea5 100644 --- a/src/Simplex/FileTransfer/Util.hs +++ b/src/Simplex/FileTransfer/Util.hs @@ -1,14 +1,19 @@ module Simplex.FileTransfer.Util ( uniqueCombine, createUniqueDirectory, + createUniqueFile, + createNewFile, safeFileNameStr, removePath, ) where +import Data.Bits ((.|.)) +import Foreign.C.Error (throwErrnoPathIfMinus1, throwErrnoPathIfMinus1_) import Simplex.Messaging.Util (ifM, whenM) import System.FilePath (makeValid, splitExtensions, takeFileName, ()) import System.IO.Error (isAlreadyExistsError) +import System.Posix.Internals (c_close, c_safe_open, o_CREAT, o_EXCL, o_WRONLY, withFilePath) import UnliftIO import UnliftIO.Directory @@ -32,6 +37,18 @@ createUniqueDirectory filePath dirName = tryCreate (0 :: Int) let d = candidatePath filePath dirName n in (d <$ createDirectory d) `catch` \e -> if isAlreadyExistsError e then tryCreate (n + 1) else throwIO e +createUniqueFile :: MonadUnliftIO m => FilePath -> String -> m FilePath +createUniqueFile filePath fileName = tryCreate (0 :: Int) + where + tryCreate n = + let f = candidatePath filePath fileName n + in (f <$ createNewFile f) `catch` \e -> if isAlreadyExistsError e then tryCreate (n + 1) else throwIO e + +createNewFile :: MonadIO m => FilePath -> m () +createNewFile f = liftIO . mask_ $ do + fd <- withFilePath f $ \p -> throwErrnoPathIfMinus1 "createNewFile" f $ c_safe_open p (o_WRONLY .|. o_CREAT .|. o_EXCL) 0o666 + throwErrnoPathIfMinus1_ "createNewFile" f $ c_close fd + candidatePath :: FilePath -> String -> Int -> FilePath candidatePath filePath fileName n = filePath (name <> suffix <> ext) where diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 940a8bde3..8694013d3 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 #-} @@ -292,7 +293,7 @@ getSMPAgentClient_ clientId cfg initServers@InitialAgentServers {smp, xftp, netC runAgent = do liftIO $ checkServers "SMP" smp >> checkServers "XFTP" xftp currentTs <- liftIO getCurrentTime - notices <- liftIO $ withTransaction store (`getClientNotices` presetServers) `catchOwn'` \_ -> pure [] + notices <- liftIO $ withTransaction store (`getClientNotices` presetServers) `catchOwn_` pure [] c@AgentClient {acThread} <- liftIO . newAgentClient clientId initServers currentTs notices =<< ask t <- runAgentThreads c `forkFinally` const (liftIO $ disconnectAgentClient c) atomically . writeTVar acThread . Just =<< mkWeakThreadId t @@ -326,13 +327,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 +361,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 +665,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_ {-# INLINE ackMessage #-} getConnectionQueueInfo :: AgentClient -> NetworkRequestMode -> ConnId -> AE ServerQueueInfo @@ -927,8 +932,8 @@ deleteUser' c@AgentClient {smpServersStats, xftpServersStats} userId delSMPQueue lift $ saveServersStats c where delUser = - whenM (withStore' c (`deleteUserWithoutConns` userId)) . atomically $ - writeTBQueue (subQ c) ("", "", AEvt SAENone $ DEL_USER userId) + whenM (withStore' c (`deleteUserWithoutConns` userId)) . liftIO $ + nonBlockingWriteTBQueue (subQ c) ("", "", AEvt SAENone $ DEL_USER userId) setUserService' :: AgentClient -> UserId -> Bool -> AM () setUserService' c userId enable = do @@ -1034,8 +1039,10 @@ deleteConnectionsAsync_ :: AM () -> AgentClient -> Bool -> [ConnId] -> AM () deleteConnectionsAsync_ onSuccess c waitDelivery connIds = case connIds of [] -> onSuccess _ -> do - (_, rqs, connIds') <- prepareDeleteConnections_ getConns c waitDelivery connIds - withStore' c $ \db -> forM_ connIds' $ setConnDeleted db waitDelivery + rqs <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnectionsAsync" . runExceptT $ do + (_, rqs, connIds') <- prepareDeleteConnections_ getConns c waitDelivery connIds + withStore' c $ \db -> forM_ connIds' $ setConnDeleted db waitDelivery + pure rqs void . lift . forkIO $ withLock' (deleteLock c) "deleteConnectionsAsync" $ deleteConnQueues c NRMBackground waitDelivery True rqs >> void (runExceptT onSuccess) @@ -1181,8 +1188,11 @@ createRcvQueue c nm userId connId srvWithAuth@(ProtoServerWithAuth srv _) enable newRcvQueue_ c nm userId connId srvWithAuth vr qd (isJust ntfServer_) subMode nonce_ e2eKeys `catchAllErrors` \e -> liftIO (print e) >> throwE e incSMPServerStat c userId srv connCreated - rq' <- withStore c $ \db -> updateNewConnRcv db connId rq subMode - lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + recorded <- withConnLock c connId "createRcvQueue" $ do + r <- tryAllErrors $ withStore c $ \db -> updateNewConnRcv db connId rq subMode + forM_ r $ \rq' -> lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + pure r + rq' <- either (\e -> tryAllErrors (deleteNewQueue c nm tSess rq) >> throwE e) pure recorded mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure (rq', qUri) @@ -1212,6 +1222,7 @@ setConnShortLinkAsync' c corrId connId userLinkData clientData = getConnShortLinkAsync' :: AgentClient -> UserId -> ACorrId -> Maybe ConnId -> ConnShortLink 'CMContact -> AM ConnId getConnShortLinkAsync' c userId corrId connId_ shortLink@(CSLContact _ _ srv _) = do + checkShortLinkServer srv connId <- case connId_ of Just existingConnId -> do -- connId and srv can be unrelated: connId is used as "mailbox" for LDATA delivery, @@ -1244,16 +1255,19 @@ getConnShortLinkAsync' c userId corrId connId_ shortLink@(CSLContact _ _ srv _) } createNewConn db g cData SCMInvitation +checkShortLinkServer :: SMPServer -> AM () +checkShortLinkServer = void . liftEitherWith (CMD PROHIBITED . ("short link: " <>)) . SMP.requireKeyHash + setConnShortLink' :: AgentClient -> NetworkRequestMode -> ConnId -> SConnectionMode c -> UserConnLinkData c -> Maybe CRClientData -> NewRatchetKeys -> Maybe CR.InitialKeys -> AM (ConnShortLink c) -setConnShortLink' c nm connId cMode userLinkData clientData rotateKeys pqKeys_ = - 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 +1326,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 @@ -1332,6 +1347,7 @@ getConnLinkPrivKey' c connId = do getConnShortLink' :: forall c. AgentClient -> NetworkRequestMode -> UserId -> ConnShortLink c -> AM (FixedLinkData c, ConnLinkData c, ConnectionRequestUri c) getConnShortLink' c nm userId = \case CSLInvitation _ srv linkId linkKey -> do + checkShortLinkServer srv g <- asks random C.AuthAlg a <- asks $ sndAuthAlg . config invLink <- withStore' c $ \db -> do @@ -1347,6 +1363,7 @@ getConnShortLink' c nm userId = \case withStore' c $ \db -> setInvShortLinkSndId db invLink sndId decryptData srv linkKey k ld CSLContact _ _ srv linkKey -> do + checkShortLinkServer srv let (linkId, k) = SL.contactShortLinkKdf linkKey ld <- getQueueLink c nm userId srv linkId decryptData srv linkKey k ld @@ -1574,7 +1591,7 @@ createRatchet_ db g connId maxSupported pqSupport e2eRcvParams@(CR.E2ERatchetPar (_, rcDHRs) <- atomically $ C.generateKeyPair g rcParams <- liftEitherWith (SEAgentError . cryptoError) $ CR.pqX3dhSnd pks e2eRcvParams let rcVs = CR.RatchetVersions {current = v, maxSupported} - rc = CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams + rc <- liftEitherWith (SEAgentError . cryptoError) $ CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams liftIO $ createSndRatchet db connId rc e2eSndParams pure (rc, e2eSndParams) @@ -1636,7 +1653,9 @@ joinConnSrv' c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo pqSup su doJoin :: Maybe RcvQueue -> Maybe SndQueue -> AM SndQueueSecured doJoin rq_ sq_ = do ((cData, sq), (e2eSndParams, lnkId_)) <- startJoinInvitation c userId connId sq_ enableNtfs inv pqSup - secureConfirmQueue c nm cData rq_ sq srv cInfo e2eSndParams subMode + (secureConfirmQueue c nm cData rq_ sq srv cInfo e2eSndParams subMode `catchError` \e -> do + unless (isJust sq_) $ void $ withStore' c $ \db -> deleteNewConnSnd db connId + throwError e) >>= (mapM_ (delInvSL c connId srv) lnkId_ $>) joinConnSrv' c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo pqSupport subMode srv mkInner = lift (compatibleContactUri cReqUri) >>= \case @@ -1724,8 +1743,11 @@ createReplyQueue c nm ConnData {userId, connId, enableNtfs} SndQueue {smpClientV (rq, qUri, tSess, sessId, serviceId_) <- newRcvQueue c nm userId connId srv (versionToRange smpClientVersion) SCMInvitation (isJust ntfServer_) subMode incSMPServerStat c userId (qServer rq) connCreated let qInfo = toVersionT qUri smpClientVersion - rq' <- withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode - lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + recorded <- withConnLock c connId "createReplyQueue" $ do + r <- tryAllErrors $ withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode + forM_ r $ \rq' -> lift . when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_ + pure r + rq' <- either (\e -> tryAllErrors (deleteNewQueue c nm tSess rq) >> throwE e) pure recorded mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure qInfo @@ -1743,7 +1765,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 +1887,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 +1933,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 +2007,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 +2055,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 +2247,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 +2316,46 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do JOIN (JRServiceReq cReq@(CRContactUri ConnReqUriData {crSmpQueues = q :| _} _) pqEnc signKey_) subMode connInfo -> noServer $ do triedHosts <- newTVarIO S.empty tryCommand . withNextSrv c userId storageSrvs triedHosts [qServer q] $ \srv -> - withConnLock c connId "JOIN service request" $ - atomically (TM.lookup connId (serviceRequests c)) >>= \case - Nothing -> pure () - Just v -> do - let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo - void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) - `catchAllErrors` \e -> + atomically (TM.lookup connId (serviceRequests c)) >>= \case + Nothing -> pure () + Just v -> do + let mkInner replyQInfo binding = AgentServiceRequest (replyQInfo :| []) (signServiceReq (C.unStored <$> signKey_) binding connInfo) connInfo + void (joinConnSrv' c NRMBackground userId connId False cReq connInfo pqEnc subMode srv mkInner) + `catchAllErrors` \e -> + whenM (atomically $ TM.member connId (serviceRequests c)) $ if temporaryOrHostError e then throwE e else atomically $ void $ tryPutTMVar v $ Left e -- will not overwrite existing result LET confId ownCInfo -> withServer' . tryAtomicCommand $ allowConnection' c (Just cmdId) connId confId ownCInfo >> notify OK ACK msgId rcptInfo_ -> withServer' . tryAtomicCommand $ ackMessage' c (Just cmdId) connId msgId rcptInfo_ >> notify OK SWCH -> - noServer . tryAtomicWithLock "switchConnection" $ - withStore c (`getConn` connId) >>= \case + noServer . tryAtomicCommand $ + withConnLock c connId "switchConnection" getConnToSwitch >>= \case SomeConn _ conn@(DuplexConnection _ (replaced :| _rqs) _) -> switchDuplexConnection c NRMBackground (Just cmdId) conn replaced >>= notify . SWITCH QDRcv SPStarted _ -> throwE $ CMD PROHIBITED "SWCH: not duplex" + where + getConnToSwitch = + withStore c (`getConn` connId) >>= \case + SomeConn _ (DuplexConnection cData (rq :| _) _) + | ratchetSyncSendProhibited cData -> do + when (rcvSwchStatus rq == Just RSSwitchStarted) . void . withStore' c $ \db -> setRcvSwitchStatus db rq Nothing + throwE $ CMD PROHIBITED "switchConnection: send prohibited" + conn -> pure conn DEL -> withServer' . tryAtomicCommand $ deleteConnection' c NRMBackground connId >> notify OK AInternalCommand cmd -> case cmd of ICAckDel rId srvMsgId msgId -> withServer $ \srv -> - tryAtomicCommand $ withConnLockNotify c connId "ICAckDel" $ do - t_ <- ack srv rId srvMsgId - withStore' c (\db -> deleteMsg db connId msgId >> deleteCommand db cmdId) - pure t_ + tryAtomicCommand $ do + recordAck <- ack srv rId srvMsgId + withConnLockNotify c connId "ICAckDel" $ do + t_ <- recordAck + withStore' c (\db -> deleteMsg db connId msgId >> deleteCommand db cmdId) + pure t_ ICAck rId srvMsgId -> withServer $ \srv -> - tryCommand $ withConnLockNotify c connId "ICAck" $ ack srv rId srvMsgId - ICAllowSecure _rId senderKey -> withServer' . tryMoveableWithLock "ICAllowSecure" $ do + tryCommand $ ack srv rId srvMsgId >>= withConnLockNotify c connId "ICAck" + ICAllowSecure _rId senderKey -> withServer' . tryMoveableCommand $ do (SomeConn _ conn, AcceptedConfirmation {senderConf, ownConnInfo}) <- - withStore c $ \db -> runExceptT $ (,) <$> ExceptT (getConn db connId) <*> ExceptT (getAcceptedConfirmation db connId) + withConnLock c connId "ICAllowSecure" . withStore c $ \db -> runExceptT $ (,) <$> ExceptT (getConn db connId) <*> ExceptT (getAcceptedConfirmation db connId) let connectReplyQueues_ cData sq_ = case L.nonEmpty $ smpReplyQueues senderConf of Just qs -> connectReplyQueues c cmdId cData ownConnInfo sq_ qs $> CCDeleted Nothing -> pure CCCompleted @@ -2346,95 +2377,120 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do where server = qServer sq _ -> throwE $ INTERNAL $ "incorrect connection type " <> show (internalCmdTag cmd) - ICDuplexSecure _rId senderKey -> withServer' . tryAtomicWithLock "ICDuplexSecure" . withDuplexConn $ \(DuplexConnection cData (rq :| _) (sq :| _)) -> do - secure rq senderKey - void $ enqueueMessage c (Just cmdId) cData sq SMP.MsgFlags {notification = True} HELLO - ICReplyDel -> withServer' . tryWithLock "ICReplyDel" $ + ICDuplexSecure _rId senderKey -> withServer' . tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICDuplexSecure" . withDuplexConn $ \_ (rq :| _) _ -> pure $ Just rq + forM_ rq_ $ \rq -> do + secure rq senderKey + withConnLock c connId "ICDuplexSecure" . withDuplexConn $ \cData _ (sq :| _) -> + Just <$> enqueueMessage c (Just cmdId) cData sq SMP.MsgFlags {notification = True} HELLO + ICReplyDel -> withServer' . tryCommand $ withStore c (`getConn` connId) >>= \case SomeConn _ (SndConnection cData sq) -> sendReplySync c NRMBackground (cData, sq) _ -> throwE $ INTERNAL "ICReplyDel: incorrect connection type" -- ICDeleteConn is no longer used, but it can be present in old client databases ICDeleteConn -> withStore' c (`deleteCommand` cmdId) - ICDeleteRcvQueue rId -> withServer $ \srv -> tryAtomicWithLock "ICDeleteRcvQueue" $ do + ICDeleteRcvQueue rId -> withServer $ \srv -> tryAtomicCommand $ do rq <- withStore c (\db -> getDeletedRcvQueue db connId srv rId) maxErrs <- asks $ deleteErrorCount . config - tryAllErrors (deleteQueue c NRMBackground rq) >>= \case + deleted <- tryAllErrors (deleteQueue c NRMBackground rq) + withConnLock c connId "ICDeleteRcvQueue" $ case deleted of Left e | temporaryOrHostError e && deleteErrors rq + 1 < maxErrs -> do withStore' c (`incRcvDeleteErrors` rq) throwE e _ -> withStore' c $ \db -> deleteConnRcvQueue db rq >> deleteCommand db cmdId ICQSecure rId senderKey -> - withServer $ \srv -> tryAtomicWithLock "ICQSecure" . withDuplexConn $ \(DuplexConnection cData rqs sqs) -> - case find (sameQueue (srv, rId)) rqs of - Just rq'@RcvQueue {server, sndId, status, dbReplaceQueueId = Just replaceQId} -> - case find ((replaceQId ==) . dbQId) rqs of - Just rq1 -> if status /= Confirmed then withStore' c (`deleteCommand` cmdId) else do - secureQueue c NRMBackground rq' senderKey - -- we may add more statistics special to queue rotation later on, - -- not accounting secure during rotation for now: - -- incSMPServerStat c userId server connSecured - rq1' <- withStore' c $ \db -> setRcvQueueStatus db rq' Secured >> setRcvSwitchStatus db rq1 (Just RSSendingQUSE) - void . enqueueMessages c cData sqs SMP.noMsgFlags $ QUSE [((server, sndId), True)] - withStore' c (`deleteCommand` cmdId) - let rqs' = updatedQs rq1' rqs - conn' = DuplexConnection cData rqs' sqs - cStats <- connectionStats c conn' - notify $ SWITCH QDRcv SPSecured cStats - _ -> internalErr "ICQSecure: no switching queue found" - _ -> internalErr "ICQSecure: queue address not found in connection" + withServer $ \srv -> tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICQSecure" . withSwitchingQueues srv $ \_ _ _ rq' _ -> pure rq' + forM_ rq_ $ \rq -> do + secureQueue c NRMBackground rq senderKey + -- we may add more statistics special to queue rotation later on, + -- not accounting secure during rotation for now: + -- incSMPServerStat c userId server connSecured + withConnLock c connId "ICQSecure" . withSwitchingQueues srv $ \cData rqs sqs rq'@RcvQueue {server, sndId} rq1 -> do + rq1' <- withStore' c $ \db -> setRcvQueueStatus db rq' Secured >> setRcvSwitchStatus db rq1 (Just RSSendingQUSE) + void . enqueueMessages c cData sqs SMP.noMsgFlags $ QUSE [((server, sndId), True)] + withStore' c (`deleteCommand` cmdId) + let rqs' = updatedQs rq1' rqs + conn' = DuplexConnection cData rqs' sqs + cStats <- connectionStats c conn' + notify $ SWITCH QDRcv SPSecured cStats + where + withSwitchingQueues :: SMPServer -> (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> RcvQueue -> RcvQueue -> AM a) -> AM (Maybe a) + withSwitchingQueues srv a = withDuplexConn $ \cData rqs sqs -> + case find (sameQueue (srv, rId)) rqs of + Just rq'@RcvQueue {status, dbReplaceQueueId = Just replaceQId} -> + case find ((replaceQId ==) . dbQId) rqs of + Just rq1 + | status /= Confirmed -> Nothing <$ withStore' c (`deleteCommand` cmdId) + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | otherwise -> Just <$> a cData rqs sqs rq' rq1 + _ -> Nothing <$ internalErr "ICQSecure: no switching queue found" + _ -> Nothing <$ internalErr "ICQSecure: queue address not found in connection" ICQSndSecure sId -> - withServer $ \srv -> tryWithLock "ICQSndSecure" . withDuplexConn $ \(DuplexConnection cData@ConnData {connAgentVersion} rqs sqs) -> - case findQ (srv, sId) sqs of - Nothing -> internalErr "ICQSndSecure: queue address not found in connection" - Just sq'@SndQueue {dbReplaceQueueId} -> - case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of - Just oldSq -> do - secureSndQueue c NRMBackground sq' - let confMsg = smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_ = Nothing, encConnInfo = ""} - void $ sendConfirmation c NRMBackground sq' confMsg - oldSq' <- withStore' c $ \db -> do - setSndQueueStatus db sq' Active - setSndQueuePrimary db connId sq' - setSndSwitchStatus db oldSq $ Just SSSendingQEND - let sq'' = (sq' :: SndQueue) {status = Active, primary = True, dbReplaceQueueId = Nothing} - pending <- withStore' c $ \db -> countSndQueueDeliveries db sq'' - atomically $ modifyTVar' (msgDeliveryOp c) $ \s -> s {opsInProgress = opsInProgress s + pending} - lift $ resumeMsgDelivery c sq'' - void $ enqueueMessages c cData [oldSq, sq''] SMP.noMsgFlags $ QEND [qAddress oldSq] - let conn' = DuplexConnection cData rqs (updatedQs oldSq' $ updatedQs sq'' sqs) - cStats <- connectionStats c conn' - notify $ SWITCH QDSnd SPSecured cStats - Nothing -> - forM_ (find (\q -> sndSwchStatus q == Just SSSendingQEND) sqs) $ \oldSq -> - void $ enqueueMessages c cData [oldSq, sq'] SMP.noMsgFlags $ QEND [qAddress oldSq] + withServer $ \srv -> tryCommand $ do + sq_ <- withConnLock c connId "ICQSndSecure" . withSecuringQueues srv $ \ConnData {connAgentVersion} _ _ sq' _ -> pure (connAgentVersion, sq') + forM_ sq_ $ \(connAgentVersion, sq) -> do + secureSndQueue c NRMBackground sq + let confMsg = smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_ = Nothing, encConnInfo = ""} + void $ sendConfirmation c NRMBackground sq confMsg + withConnLock c connId "ICQSndSecure" . withSecuringQueues srv $ \cData rqs sqs sq' oldSq -> do + oldSq' <- withStore' c $ \db -> do + setSndQueueStatus db sq' Active + setSndQueuePrimary db connId sq' + setSndSwitchStatus db oldSq $ Just SSSendingQEND + let sq'' = (sq' :: SndQueue) {status = Active, primary = True, dbReplaceQueueId = Nothing} + pending <- withStore' c $ \db -> countSndQueueDeliveries db sq'' + atomically $ modifyTVar' (msgDeliveryOp c) $ \s -> s {opsInProgress = opsInProgress s + pending} + lift $ resumeMsgDelivery c sq'' + void $ enqueueMessages c cData [oldSq, sq''] SMP.noMsgFlags $ QEND [qAddress oldSq] + let conn' = DuplexConnection cData rqs (updatedQs oldSq' $ updatedQs sq'' sqs) + cStats <- connectionStats c conn' + notify $ SWITCH QDSnd SPSecured cStats + where + withSecuringQueues :: SMPServer -> (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> SndQueue -> SndQueue -> AM a) -> AM (Maybe a) + withSecuringQueues srv a = withDuplexConn $ \cData rqs sqs -> + case findQ (srv, sId) sqs of + Nothing -> Nothing <$ internalErr "ICQSndSecure: queue address not found in connection" + Just sq'@SndQueue {dbReplaceQueueId} + | ratchetSyncSendProhibited cData -> Nothing <$ postponeCommand + | otherwise -> case dbReplaceQueueId >>= \replaceQId -> find ((replaceQId ==) . dbQId) sqs of + Just oldSq -> Just <$> a cData rqs sqs sq' oldSq + Nothing -> do + forM_ (find (\q -> sndSwchStatus q == Just SSSendingQEND) sqs) $ \oldSq -> + void $ enqueueMessages c cData [oldSq, sq'] SMP.noMsgFlags $ QEND [qAddress oldSq] + pure Nothing ICQDelete rId -> do - withServer $ \srv -> tryAtomicWithLock "ICQDelete" . withDuplexConn $ \(DuplexConnection cData@ConnData {enableNtfs} rqs sqs) -> do - case removeQ (srv, rId) rqs of - Nothing -> internalErr "ICQDelete: queue address not found in connection" - Just (rq'@RcvQueue {primary}, rq'' : rqs') - | primary -> internalErr "ICQDelete: cannot delete primary rcv queue" - | otherwise -> do - checkRQSwchStatus rq' RSReceivedMessage - tryAllErrors (deleteQueue c NRMBackground rq') >>= \case - Right () -> finalizeSwitch - Left e - | temporaryOrHostError e -> throwE e - | otherwise -> finalizeSwitch >> notify (ERR e) - where - finalizeSwitch = do - withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId - when enableNtfs $ do - ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) - let conn' = DuplexConnection cData (rq'' :| rqs') sqs - cStats <- connectionStats c conn' - notify $ SWITCH QDRcv SPCompleted cStats - _ -> internalErr "ICQDelete: cannot delete the only queue in connection" + withServer $ \srv -> tryAtomicCommand $ do + rq_ <- withConnLock c connId "ICQDelete" . withRemovedQueue srv $ \_ rq' _ _ -> pure rq' + forM_ rq_ $ \rq -> do + deleted <- tryAllErrors (deleteQueue c NRMBackground rq) + case deleted of + Left e | temporaryOrHostError e -> throwE e + _ -> withConnLock c connId "ICQDelete" . withRemovedQueue srv $ \cData@ConnData {enableNtfs} rq' rqs sqs -> do + withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId + when enableNtfs $ do + ns <- asks ntfSupervisor + liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + let conn' = DuplexConnection cData rqs sqs + cStats <- connectionStats c conn' + notify $ SWITCH QDRcv SPCompleted cStats + either (notify . ERR) pure deleted + where + withRemovedQueue :: SMPServer -> (ConnData -> RcvQueue -> NonEmpty RcvQueue -> NonEmpty SndQueue -> AM a) -> AM (Maybe a) + withRemovedQueue srv a = withDuplexConn $ \cData rqs sqs -> + case removeQ (srv, rId) rqs of + Nothing -> Nothing <$ internalErr "ICQDelete: queue address not found in connection" + Just (rq'@RcvQueue {primary}, rq'' : rqs') + | primary -> Nothing <$ internalErr "ICQDelete: cannot delete primary rcv queue" + | otherwise -> do + checkRQSwchStatus rq' RSReceivedMessage + Just <$> a cData rq' (rq'' :| rqs') sqs + _ -> Nothing <$ internalErr "ICQDelete: cannot delete the only queue in connection" where ack srv rId srvMsgId = withStore' c (\db -> getRcvQueue db connId srv rId) >>= \case Right rq -> ackQueueMessage c rq srvMsgId - Left SEConnNotFound -> pure Nothing + Left SEConnNotFound -> pure (pure Nothing) Left e -> throwE $ storeError e secure :: RcvQueue -> SMP.SndPublicAuthKey -> AM () secure rq@RcvQueue {server} senderKey = do @@ -2449,11 +2505,11 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do noServer a = case server_ of Nothing -> a _ -> internalErr "command requires no server" - withDuplexConn :: (Connection 'CDuplex -> AM ()) -> AM () + withDuplexConn :: (ConnData -> NonEmpty RcvQueue -> NonEmpty SndQueue -> AM (Maybe a)) -> AM (Maybe a) withDuplexConn a = withStore c (`getConn` connId) >>= \case - SomeConn _ conn@DuplexConnection {} -> a conn - _ -> internalErr "command requires duplex connection" + SomeConn _ (DuplexConnection cData rqs sqs) -> a cData rqs sqs + _ -> Nothing <$ internalErr "command requires duplex connection" tryCommand action = tryMoveableCommand (action $> CCCompleted) tryAtomicCommand action = tryMoveableCommand (action $> CCDeleted) tryMoveableCommand action = withRetryInterval2 ri $ \_ loop -> do @@ -2472,11 +2528,15 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do Right CCCompleted -> withStore' c (`deleteCommand` cmdId) Right CCMoved -> pure () -- command processing moved to another command queue Right CCDeleted -> pure () - tryWithLock name = tryCommand . withConnLock c connId name - tryAtomicWithLock name = tryAtomicCommand . withConnLock c connId name - tryMoveableWithLock name = tryMoveableCommand . withConnLock c connId name internalErr s = cmdError $ INTERNAL $ s <> ": " <> show (agentCommandTag command) cmdError e = notify (ERR e) >> withStore' c (`deleteCommand` cmdId) + postponeCommand = do + liftIO $ noWorkToDo doWork + otherCmds <- withStore c $ \db -> runExceptT $ do + liftIO $ deleteCommand db cmdId + pending <- liftIO $ either (const True) isJust <$> getPendingServerCommand db connId server_ + pending <$ ExceptT (createCommand db corrId connId server_ command) + when otherCmds . atomically $ hasWorkToDo' doWork notify :: forall e. AEntityI e => AEvent e -> AM () notify cmd = let t = (corrId, connId, AEvt (sAEntity @e) cmd) @@ -2515,7 +2575,9 @@ enqueueMessageB :: forall t. Traversable t => AgentClient -> Maybe AsyncCmdId -> enqueueMessageB c cmdId_ reqs = do cfg <- asks config (_, reqMids) <- unsafeWithStore c $ \db -> do - res@(_, rs) <- mapAccumLM (\ids r -> storeSentMsg db cfg ids r `E.catchAny` \e -> (ids,) <$> handleInternal e) IM.empty reqs + res@(_, rs) <- + mapAccumLM (\ids r -> storeSentMsg db cfg ids r `catchItemError` \e -> (ids,) <$> handleInternal e) IM.empty reqs + `catchRolledBack` \e -> pure (IM.empty, Left e <$ reqs) when (all isRight rs) $ mapM_ (deleteCommand db) cmdId_ pure res forME reqMids $ submitSentMsg c @@ -2543,25 +2605,21 @@ storeSentMsg db cfg aMessageIds = \case Nothing -> do (mbId_, r) <- case csqs_ of Left e -> pure (Nothing, Left e) - Right (cData, sq :| _) -> do - mbId <- createSndMsgBody db aMessage - (Just mbId,) <$> storeSentMsg_ cData sq mbId aMessage + Right (cData, sq :| _) -> storeSentMsg_ cData sq Nothing aMessage let aMessageIds' = maybe id (`IM.insert` (mbId_, aMessage)) i_ aMessageIds pure (aMessageIds', r) VRRef i -> case csqs_ of Left e -> pure $ (aMessageIds, Left e) Right (cData, sq :| _) -> case IM.lookup i aMessageIds of - Just (Just mbId, aMessage) -> (aMessageIds,) <$> storeSentMsg_ cData sq mbId aMessage - Just (Nothing, aMessage) -> do - mbId <- createSndMsgBody db aMessage - let aMessageIds' = IM.insert i (Just mbId, aMessage) aMessageIds - (aMessageIds',) <$> storeSentMsg_ cData sq mbId aMessage + Just (mbId_, aMessage) -> do + (mbId_', r) <- storeSentMsg_ cData sq mbId_ aMessage + pure (IM.insert i (mbId_', aMessage) aMessageIds, r) Nothing -> pure (aMessageIds, Left $ INTERNAL "enqueueMessageB: storeSentMsg missing saved message body id") where - storeSentMsg_ cData@ConnData {connId} sq sndMsgBodyId aMessage = fmap (first storeError) $ runExceptT $ do + storeSentMsg_ cData@ConnData {connId, pqSupport} sq mbId_ aMessage = fmap (either (\e -> (mbId_, Left $ storeError e)) (bimap Just Right)) $ runExceptT $ do let AgentConfig {e2eEncryptVRange} = cfg internalTs <- liftIO getCurrentTime - (internalId, internalSndId, prevMsgHash) <- ExceptT $ updateSndIds db connId + (internalId, internalSndId, prevMsgHash) <- ExceptT $ getNextSndIds db connId -- We need to do pre-flight encoding that is not stored in database -- to calculate its hash and remember it on connection (createSndMsg -> updateSndMsgHash) -- to enable next enqueue. @@ -2569,14 +2627,16 @@ storeSentMsg db cfg aMessageIds = \case let agentMsgStr = encodeAgentMsgStr aMessage internalSndId prevMsgHash internalHash = C.sha256Hash agentMsgStr currentE2EVersion = maxVersion e2eEncryptVRange + withExceptT (SEAgentError . cryptoError) $ CR.rcCheckCanPad (e2eEncAgentMsgLength pqSupport) agentMsgStr + sndMsgBodyId <- liftIO $ maybe (createSndMsgBody db aMessage) pure mbId_ + liftIO $ updateLastIdsSnd_ db connId internalId internalSndId (mek, paddedLen, pqEnc) <- agentRatchetEncryptHeader db cData e2eEncAgentMsgLength pqEnc_ currentE2EVersion - withExceptT (SEAgentError . cryptoError) $ CR.rcCheckCanPad paddedLen agentMsgStr let msgType = aMessageType aMessage -- msgBody is empty, because snd_messages record is linked to snd_message_bodies msgData = SndMsgData {internalId, internalSndId, internalTs, msgType, msgFlags, msgBody = "", pqEncryption = pqEnc, internalHash, prevMsgHash, sndMsgPrepData_ = Just SndMsgPrepData {encryptKey = mek, paddedLen, sndMsgBodyId}} liftIO $ createSndMsg db connId msgData liftIO $ createSndMsgDelivery db sq internalId - pure (req, internalId, pqEnc) + pure (sndMsgBodyId, (req, internalId, pqEnc)) encodeAgentMsgStr :: AMessage -> InternalSndId -> PrevSndMsgHash -> ByteString encodeAgentMsgStr aMessage internalSndId prevMsgHash = do @@ -2809,7 +2869,7 @@ runSmpQueueMsgDelivery c@AgentClient {subQ} sq@SndQueue {userId, connId, server, notifyDel msgId $ MERR (unId msgId) err msgIds_ <- withStore' c $ \db -> do msgIds_ <- getExpiredSndMessages db connId sq expireTs - forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchAll_` pure () + forM_ msgIds_ $ \msgId' -> deleteSndMsgDelivery db connId sq msgId' False `catchItemError` \_ -> pure () pure msgIds_ forM_ (L.nonEmpty msgIds_) $ \msgIds -> do notify $ MERRS (L.map unId msgIds) err @@ -2841,7 +2901,7 @@ retrySndOp c loop = do withConnLockNotify :: AgentClient -> ConnId -> Text -> AM (Maybe ATransmission) -> AM () withConnLockNotify c connId name action = do t_ <- withConnLock c connId name action - forM_ t_ $ atomically . writeTBQueue (subQ c) + forM_ t_ $ liftIO . nonBlockingWriteTBQueue (subQ c) ackMessage' :: AgentClient -> Maybe AsyncCmdId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM () ackMessage' c cmdId_ connId msgId rcptInfo_ = withConnLockNotify c connId "ackMessage" $ do @@ -2858,9 +2918,11 @@ ackMessage' c cmdId_ connId msgId rcptInfo_ = withConnLockNotify c connId "ackMe -- 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 + recordAck <- ackQueueMessage c rq srvMsgId afterAck - t_ <$ del + t_ <- recordAck + del + pure t_ Left (SEMsgNotFound _) -> Nothing <$ del Left e -> throwE $ storeError e del :: AM () @@ -2891,19 +2953,20 @@ getConnectionQueueInfo' c nm connId = do NewConnection _ -> throwE $ CMD PROHIBITED "getConnectionQueueInfo: NewConnection" switchConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM ConnectionStats -switchConnection' c nm connId = - withConnLock c connId "switchConnection" $ +switchConnection' c nm connId = do + (cData, rqs, sqs, rq') <- withConnLock c connId "switchConnection" $ withStore c (`getConn` connId) >>= \case - SomeConn _ conn@(DuplexConnection cData rqs@(rq :| _rqs) _) + SomeConn _ (DuplexConnection cData rqs@(rq :| _rqs) sqs) | isJust (switchingRQ rqs) -> throwE $ CMD PROHIBITED "switchConnection: already switching" | otherwise -> do when (ratchetSyncSendProhibited cData) $ throwE $ CMD PROHIBITED "switchConnection: send prohibited" rq' <- withStore' c $ \db -> setRcvSwitchStatus db rq $ Just RSSwitchStarted - switchDuplexConnection c nm Nothing conn rq' + pure (cData, rqs, sqs, rq') _ -> throwE $ CMD PROHIBITED "switchConnection: not duplex" + switchDuplexConnection c nm Nothing (DuplexConnection cData rqs sqs) rq' switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats -switchDuplexConnection c nm cmdId_ (DuplexConnection cData@ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do +switchDuplexConnection c nm cmdId_ (DuplexConnection ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do checkRQSwchStatus rq RSSwitchStarted clientVRange <- asks $ smpClientVRange . config -- try to get the server that is different from all queues, or at least from the primary rcv queue @@ -2913,12 +2976,23 @@ switchDuplexConnection c nm cmdId_ (DuplexConnection cData@ConnData {connId, use -- The problem is that currently subscription already exists, and we do not support queues with credentials but without subscriptions. (q, qUri, tSess, sessId, serviceId_) <- newRcvQueue c nm userId connId srv' clientVRange SCMInvitation False SMSubscribe let rq' = (q :: NewRcvQueue) {primary = True, dbReplaceQueueId = Just dbQueueId} - rq'' <- withStore c $ \db -> addConnRcvQueue db connId rq' SMSubscribe - lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ - void . enqueueMessages c cData sqs SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] - rq1 <- withStore' c $ \db -> setRcvSwitchStatus db rq (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ - let rqs' = updatedQs rq1 rqs <> [rq''] - connectionStats c $ DuplexConnection cData rqs' sqs + switched <- withConnLock c connId "switchConnection" $ do + recorded <- tryAllErrors $ + withStore c (`getConn` connId) >>= \case + SomeConn _ (DuplexConnection cData rqs' sqs') | Just rq1 <- findQ (qAddress rq) rqs' -> + (cData,rqs',sqs',rq1,) <$> withStore c (\db -> addConnRcvQueue db connId rq' SMSubscribe) + _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" + forM recorded $ \(cData, rqs', sqs', rq1, rq'') -> do + when (rcvSwchStatus rq1 /= Just RSSwitchStarted) $ deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: aborted") + when (ratchetSyncSendProhibited cData) $ do + void $ withStore' c $ \db -> setRcvSwitchStatus db rq1 Nothing + deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: send prohibited") + lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ + void . enqueueMessages c cData sqs' SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] + rq1' <- withStore' c $ \db -> setRcvSwitchStatus db rq1 (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ + let rqs'' = updatedQs rq1' rqs' <> [rq''] + connectionStats c $ DuplexConnection cData rqs'' sqs' + either (\e -> tryAllErrors (deleteNewQueue c nm tSess q) >> throwE e) pure switched abortConnectionSwitch' :: AgentClient -> ConnId -> AM ConnectionStats abortConnectionSwitch' c connId = @@ -2968,12 +3042,12 @@ synchronizeRatchet' c connId pqSupport' force = withConnLock c connId "synchroni | otherwise -> throwE $ CMD PROHIBITED "synchronizeRatchet: not allowed" _ -> throwE $ CMD PROHIBITED "synchronizeRatchet: not duplex" -ackQueueMessage :: AgentClient -> RcvQueue -> SMP.MsgId -> AM (Maybe ATransmission) +ackQueueMessage :: AgentClient -> RcvQueue -> SMP.MsgId -> AM (AM (Maybe ATransmission)) ackQueueMessage c rq@RcvQueue {userId, connId, server, rcvSwchStatus} srvMsgId = do incSMPServerStat c userId server ackAttempts tryAllErrors (sendAck c rq srvMsgId) >>= \case - Right drained -> sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND - Left (SMP _ SMP.NO_MSG) -> sendMsgNtf ackNoMsgErrs False + Right drained -> pure $ sendMsgNtf ackMsgs $ drained && rcvSwchStatus == Just RSReceivedQEND + Left (SMP _ SMP.NO_MSG) -> pure $ sendMsgNtf ackNoMsgErrs False Left e -> do unless (temporaryOrHostError e) $ incSMPServerStat c userId server ackOtherErrs throwE e @@ -2993,14 +3067,16 @@ deleteRcvQueueAsync c rq@RcvQueue {connId, server, rcvId} = do -- | Suspend SMP agent connection (OFF command) in Reader monad suspendConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM () -suspendConnection' c nm connId = withConnLock c connId "suspendConnection" $ do - SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection _ rqs _ -> mapM_ (suspendQueue c nm) rqs - RcvConnection _ rq -> suspendQueue c nm rq - ContactConnection _ rq -> suspendQueue c nm rq - SndConnection _ _ -> throwE $ CONN SIMPLEX "suspendConnection" - NewConnection _ -> throwE $ CMD PROHIBITED "suspendConnection" +suspendConnection' c nm connId = do + rqs <- withConnLock c connId "suspendConnection" $ do + SomeConn _ conn <- withStore c (`getConn` connId) + case conn of + DuplexConnection _ rqs _ -> pure $ L.toList rqs + RcvConnection _ rq -> pure [rq] + ContactConnection _ rq -> pure [rq] + SndConnection _ _ -> throwE $ CONN SIMPLEX "suspendConnection" + NewConnection _ -> throwE $ CMD PROHIBITED "suspendConnection" + mapM_ (suspendQueue c nm) (rqs :: [RcvQueue]) -- | Delete SMP agent connection (DEL command) in Reader monad -- unlike deleteConnectionAsync, this function does not mark connection as deleted in case of deletion failure @@ -3063,7 +3139,7 @@ prepareDeleteConnections_ getConnections c waitDelivery connIds = do unsubNtfConnIds connIds' = do ns <- asks ntfSupervisor atomically $ writeTBQueue (ntfSubQ ns) (NSCDeleteSub, connIds') - notify = atomically . writeTBQueue (subQ c) + notify = liftIO . nonBlockingWriteTBQueue (subQ c) deleteConnQueues :: AgentClient -> NetworkRequestMode -> Bool -> Bool -> [RcvQueue] -> AM' (Map ConnId (Either AgentErrorType ())) deleteConnQueues c nm waitDelivery ntf rqs = do @@ -3078,6 +3154,7 @@ deleteConnQueues c nm waitDelivery ntf rqs = do deleteQueueRecs rs = do maxErrs <- asks $ deleteErrorCount . config rs' <- rights <$> withStoreBatch' c (\db -> map (deleteQueueRec db maxErrs) rs) + forM_ [rq | ((rq, _), Just (Just _)) <- rs'] $ \RcvQueue {userId, server} -> incSMPServerStat c userId server connDeleted let delQ ((rq, _), err_) = (qConnId rq,qServer rq,queueId rq,) <$> err_ delQs_ = L.nonEmpty $ mapMaybe delQ rs' forM_ delQs_ $ \delQs -> notify ("", "", AEvt SAEConn $ DEL_RCVQS delQs) @@ -3088,14 +3165,13 @@ deleteConnQueues c nm waitDelivery ntf rqs = do Int -> (RcvQueue, Either AgentErrorType ()) -> IO ((RcvQueue, Either AgentErrorType ()), Maybe (Maybe AgentErrorType)) -- Nothing - no event, Just Nothing - no error - deleteQueueRec db maxErrs (rq@RcvQueue {userId, server}, r) = case r of + deleteQueueRec db maxErrs (rq, r) = case r of Right _ -> deleteConnRcvQueue db rq $> ((rq, r), Just Nothing) Left e | temporaryOrHostError e && deleteErrors rq + 1 < maxErrs -> incRcvDeleteErrors db rq $> ((rq, r), Nothing) | otherwise -> do deleteConnRcvQueue db rq -- attempts and successes are counted in deleteQueues function - incSMPServerStat c userId server connDeleted pure ((rq, Right ()), Just (Just e)) notify = when ntf . atomically . writeTBQueue (subQ c) connResults :: [(RcvQueue, Either AgentErrorType ())] -> Map ConnId (Either AgentErrorType ()) @@ -3123,7 +3199,7 @@ deleteConnections_ :: AM (Map ConnId (Either AgentErrorType ())) deleteConnections_ _ _ _ _ _ [] = pure M.empty deleteConnections_ getConnections ntf waitDelivery c nm connIds = do - (rs, rqs, _) <- prepareDeleteConnections_ getConnections c waitDelivery connIds + (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ prepareDeleteConnections_ getConnections c waitDelivery connIds rcvRs <- lift $ deleteConnQueues c nm waitDelivery ntf rqs let rs' = M.union rs rcvRs notifyResultError rs' @@ -3133,8 +3209,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 @@ -3450,14 +3526,15 @@ suspendAgent c 0 = do where suspend opSel = atomically $ modifyTVar' (opSel c) $ \s -> s {opSuspended = True} suspendAgent c@AgentClient {agentState = as} maxDelay = do - state <- + (prevState, state) <- atomically $ do - writeTVar as ASSuspending + prevState <- swapTVar as ASSuspending suspendOperation c AONtfNetwork $ pure () suspendOperation c AORcvNetwork $ suspendOperation c AOSndFiles $ suspendMsgDelivery c - readTVar as + (prevState,) <$> readTVar as + unless (prevState == ASSuspending) . void . forkIO $ notifySuspended c when (state == ASSuspending) $ do void . forkIO $ removeDeletedOrFailedSndFilesInProgress c void . forkIO $ do @@ -3779,6 +3856,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 +3899,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 @@ -4370,7 +4449,8 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr | otherwise = do (_, rcDHRs) <- atomically . C.generateKeyPair =<< asks random rcParams <- liftEitherWith cryptoError $ CR.pqX3dhSnd (pk1, pk2, CR.APRKP CR.SRKSProposed <$> pKem) e2eOtherPartyParams - recreateRatchet replyKey_ (Just $ EREADY lastExternalSndId) $ CR.initSndRatchet rcVs k2Rcv rcDHRs rcParams + rcRatchet <- liftEitherWith cryptoError $ CR.initSndRatchet rcVs k2Rcv rcDHRs rcParams + recreateRatchet replyKey_ (Just $ EREADY lastExternalSndId) rcRatchet checkMsgIntegrity :: PrevExternalSndId -> ExternalSndId -> PrevRcvMsgHash -> ByteString -> MsgIntegrity checkMsgIntegrity prevExtSndId extSndId internalPrevMsgHash receivedPrevMsgHash @@ -4408,11 +4488,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..0f8b50c6a 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -89,6 +89,8 @@ module Simplex.Messaging.Agent.Client agentNtfCheckSubscription, agentNtfCheckSubscriptions, agentNtfDeleteSubscription, + withXFTPDownloadPermit, + releaseXFTPDownloadPermit, agentXFTPDownloadChunk, agentXFTPNewChunk, agentXFTPUploadChunk, @@ -99,6 +101,7 @@ module Simplex.Messaging.Agent.Client sendAck, suspendQueue, deleteQueue, + deleteNewQueue, deleteQueues, logServer, logSecret, @@ -137,6 +140,7 @@ module Simplex.Messaging.Agent.Client waitForWork, hasWorkToDo, hasWorkToDo', + noWorkToDo, withWork, withWork_, withWorkItems, @@ -169,6 +173,8 @@ module Simplex.Messaging.Agent.Client withStoreIsolation', withStoreBatch, withStoreBatch', + catchItemError, + catchRolledBack, unsafeWithStore, storeError, notifySub, @@ -192,6 +198,7 @@ module Simplex.Messaging.Agent.Client SMPTransportSession, NtfTransportSession, XFTPTransportSession, + XFTPDownloadPermit, ProxiedRelay (..), SMPConnectedClient (..), ) @@ -229,6 +236,7 @@ import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) +import qualified Data.Text as T import Data.Text.Encoding import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) @@ -250,7 +258,7 @@ import Simplex.Messaging.Agent.RetryInterval import Simplex.Messaging.Agent.Stats import Simplex.Messaging.Agent.Store import Simplex.Messaging.Agent.Store.AgentStore -import Simplex.Messaging.Agent.Store.Common (DBStore, IsolationLevel (..), withTransactionIsolation) +import Simplex.Messaging.Agent.Store.Common (DBStore, IsolationLevel (..), abortsTransaction, isTransactionConflict, withTransactionIsolation) import Simplex.Messaging.Agent.Store.DB (SQLError) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Entity @@ -311,27 +319,31 @@ import Simplex.Messaging.Protocol import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo -import Simplex.Messaging.Server.Information (ServerPublicInfo) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (clientSupport)) import Simplex.Messaging.Session import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), newNtfCredsSMPVersion) +import Simplex.Messaging.Transport (HandshakeError (..), SMPServiceRole (..), SMPVersion, ServiceCredentials (..), SessionId, THClientService' (..), THandleAuth (..), THandleParams (sessionId, thAuth, thVersion, serverInfo), TransportError (..), VersionSMP, newNtfCredsSMPVersion, pattern VersionSMP) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Credentials import Simplex.Messaging.Util import Simplex.Messaging.Version import System.Mem.Weak (Weak, deRefWeak) import System.Random (randomR) -import UnliftIO (mapConcurrently, timeout) +import UnliftIO (QSem, mapConcurrently, newQSem, signalQSem, timeout, waitQSem) import UnliftIO.Async (async) -import UnliftIO.Concurrent (forkIO, mkWeakThreadId) +import UnliftIO.Concurrent (forkIO, mkWeakThreadId, myThreadId) import UnliftIO.Directory (doesFileExist, getTemporaryDirectory, removeFile) import qualified UnliftIO.Exception as E import UnliftIO.STM #if !defined(dbPostgres) import qualified Database.SQLite.Simple as SQL #endif +#if defined(conn_lock_checks) +import qualified Data.Text as T +import UnliftIO.Concurrent (myThreadId) +#endif type ClientVar msg = SessionVar (Either (AgentErrorType, Maybe UTCTime) (Client msg)) @@ -345,6 +357,8 @@ type NtfTransportSession = TransportSession NtfResponse type XFTPTransportSession = TransportSession FileResponse +type XFTPDownloadPermit = TVar (Maybe XFTPTransportSession) + data AgentClient = AgentClient { acThread :: TVar (Maybe (Weak ThreadId)), active :: TVar Bool, @@ -361,10 +375,12 @@ data AgentClient = AgentClient ntfClients :: TMap NtfTransportSession NtfClientVar, xftpServers :: TMap UserId (UserServers 'PXFTP), xftpClients :: TMap XFTPTransportSession XFTPClientVar, + xftpDownloadSessions :: QSem, userEntitlements :: TMap UserId EntitlementCredential, useNetworkConfig :: TVar (NetworkConfig, NetworkConfig), -- (slow, fast) networks presetDomains :: [HostName], presetServers :: [SMPServer], + presetClientSupport :: TVar ClientSupport, userNetworkInfo :: TVar UserNetworkInfo, userNetworkUpdated :: TVar (Maybe UTCTime), subscrConns :: TVar (Set ConnId), @@ -386,6 +402,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 @@ -534,8 +554,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf ntfClients <- TM.emptyIO xftpServers <- newTVarIO $ M.map mkUserServers xftp xftpClients <- TM.emptyIO + xftpDownloadSessions <- newQSem $ xftpMaxDownloadSessions cfg userEntitlements <- newTVarIO entitlements useNetworkConfig <- newTVarIO (slowNetworkConfig netCfg, netCfg) + presetClientSupport <- newTVarIO $ ClientSupport Nothing Nothing Nothing userNetworkInfo <- newTVarIO $ UserNetworkInfo UNOther True userNetworkUpdated <- newTVarIO Nothing subscrConns <- newTVarIO S.empty @@ -556,6 +578,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState <- newTVarIO ASForeground getMsgLocks <- TM.emptyIO connLocks <- TM.emptyIO +#if defined(conn_lock_checks) + connLockHolders <- TM.emptyIO + connLockViolations <- newTVarIO [] +#endif invLocks <- TM.emptyIO deleteLock <- createLockIO smpSubWorkers <- TM.emptyIO @@ -578,10 +604,12 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf ntfClients, xftpServers, xftpClients, + xftpDownloadSessions, userEntitlements, useNetworkConfig, presetDomains, presetServers, + presetClientSupport, userNetworkInfo, userNetworkUpdated, subscrConns, @@ -602,6 +630,10 @@ newAgentClient clientId InitialAgentServers {smp, ntf, xftp, entitlements, netCf agentState, getMsgLocks, connLocks, +#if defined(conn_lock_checks) + connLockHolders, + connLockViolations, +#endif invLocks, deleteLock, smpSubWorkers, @@ -693,6 +725,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 +736,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 @@ -760,13 +794,13 @@ getSMPProxyClient c@AgentClient {active, smpClients, smpProxiedRelays, workerSeq Nothing -> Left $ BROKER (B.unpack $ strEncode srv) TIMEOUT smpConnectClient :: AgentClient -> NetworkRequestMode -> SMPTransportSession -> TMap SMPServer ProxiedRelayVar -> SMPClientVar -> AM SMPConnectedClient -smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm tSess@(userId, srv, _) prs v = +smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains, presetServers} nm tSess@(userId, srv, _) prs v = newProtocolClient c tSess smpClients connectClient v `catchAllErrors` \e -> lift (resubscribeSMPSession c tSess) >> throwE e where connectClient :: SMPClientVar -> AM SMPConnectedClient connectClient v' = do - cfg <- lift $ getClientConfig c smpCfg + cfg@ProtocolClientConfig {serverVRange} <- lift $ getClientConfig c smpCfg g <- asks random service <- getServiceCredentials c userId srv let cfg' = cfg {serviceCredentials = fst <$> service} @@ -776,6 +810,7 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm ExceptT $ getProtocolClient g nm tSess cfg' presetDomains (Just msgQ) ts $ smpClientDisconnected c tSess env v' prs atomically $ SS.setSessionId tSess (sessionId $ thParams smp) $ currentSubs c updateClientService service smp + when (isPresetServer srv presetServers) $ updateClientSupport (maxVersion serverVRange) smp pure SMPConnectedClient {connectedClient = smp, proxiedRelays = prs} updateClientService service smp = case (service, smpClientServiceId smp) of (Just (_, serviceId_), Just serviceId) -> withStore' c $ \db -> do @@ -784,6 +819,24 @@ smpConnectClient c@AgentClient {smpClients, msgQ, proxySessTs, presetDomains} nm (Just _, Nothing) -> withStore' c $ \db -> deleteClientService db userId srv -- e.g., server version downgrade (Nothing, Just _) -> logError "server returned serviceId without service credentials in request" (Nothing, Nothing) -> pure () + updateClientSupport clientVersion smp = + forM_ (clientSupport =<< eitherToMaybe =<< serverInfo (thParams smp)) $ \cs -> + atomically (stateTVar' (presetClientSupport c) $ mergeClientSupport clientVersion cs) + >>= mapM_ (notifySub c . CLIENT_SUPPORT) + +mergeClientSupport :: VersionSMP -> ClientSupport -> ClientSupport -> (Maybe ClientSupport, ClientSupport) +mergeClientSupport v new cs = + (cs' <$ guard (cs' /= cs), cs') + where + cs' = + ClientSupport + { minClientVersion = case (minClientVersion cs, mfilter unsupported $ minClientVersion new) of + (Just m, Just m') | fromDate m <= fromDate m' -> Just m + (m_, m_') -> m_' <|> m_, + stableRelease = stableRelease new <|> stableRelease cs, + betaRelease = betaRelease new <|> betaRelease cs + } + unsupported MinClientVersion {protocolVersion} = VersionSMP protocolVersion > v smpClientDisconnected :: AgentClient -> SMPTransportSession -> Env -> SMPClientVar -> TMap SMPServer ProxiedRelayVar -> SMPClient -> IO () smpClientDisconnected c@AgentClient {active, smpClients, smpProxiedRelays} tSess@(userId, srv, cId) env v prs client = do @@ -872,6 +925,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 +947,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 @@ -961,7 +1016,7 @@ newProtocolClient :: newProtocolClient c tSess@(userId, srv, entityId_) clients connectClient v = tryAllErrors (connectClient v) >>= \case Right client -> do - logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv <> " (user " <> bshow userId <> maybe "" (" for entity " <>) entityId_ <> ")" + logInfo . safeDecodeUtf8 $ "Agent connected to " <> showServer srv <> " (user " <> bshow userId <> maybe "" (" for entity " <>) entityId_ <> ")" atomically $ putTMVar (sessionVar v) (Right client) liftIO $ nonBlockingWriteTBQueue (subQ c) ("", "", AEvt SAENone $ hostEvent CONNECT client) pure client @@ -1083,7 +1138,7 @@ closeClient_ c v = do NetworkConfig {tcpConnectTimeout} <- getNetworkConfig c E.handle (\BlockedIndefinitelyOnSTM -> pure ()) $ netTimeoutInt tcpConnectTimeout NRMBackground `timeout` atomically (readTMVar $ sessionVar v) >>= \case - Just (Right client) -> closeProtocolServerClient (protocolClient client) `catchAll_` pure () + Just (Right client) -> closeProtocolServerClient (protocolClient client) `catchOwn_` pure () _ -> pure () closeXFTPServerClient :: AgentClient -> UserId -> XFTPServer -> FileDigest -> IO () @@ -1096,7 +1151,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 +1163,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 +1177,40 @@ 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 _ [] batch = batch +checkBatchOutsideConnLock c qs batch = tryAllErrors' (checkNoConnLock c) >>= either (\e -> pure $ map (,Left e) qs) (const batch) +#else +withLockHolder :: AgentClient -> Text -> m a -> m a +withLockHolder _ _ = id +{-# 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 @@ -1377,21 +1466,23 @@ runXFTPServerTest c@AgentClient {presetDomains} nm userId (ProtoServerWithAuth s let tSess = (userId, srv, Nothing) ts <- readTVarIO $ proxySessTs c X.getXFTPClient tSess cfg {xftpNetworkConfig} presetDomains ts (\_ -> pure Nothing) (\_ -> pure ()) >>= \case - Right xftp -> withTestChunk filePath $ do - (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - digest <- liftIO $ C.sha256Hash <$> B.readFile filePath - let file = FileInfo {sndKey, size = chSize, digest} - chunkSpec = X.XFTPChunkSpec {filePath, chunkOffset = 0, chunkSize = chSize} - r <- runExceptT $ do - (sId, [rId], _) <- liftError (testErr TSCreateFile) $ X.createXFTPChunk xftp spKey file [rcvKey] auth Nothing - liftError (testErr TSUploadFile) $ X.uploadXFTPChunk xftp spKey sId chunkSpec - liftError (testErr TSDownloadFile) $ X.downloadXFTPChunk g xftp rpKey rId $ XFTPRcvChunkSpec rcvPath chSize digest - rcvDigest <- liftIO $ C.sha256Hash <$> B.readFile rcvPath - unless (digest == rcvDigest) $ throwE $ ProtocolTestFailure TSCompareFile $ XFTP (B.unpack $ strEncode srv) DIGEST - liftError (testErr TSDeleteFile) $ X.deleteXFTPChunk xftp spKey sId - ok <- netTimeoutInt (tcpTimeout xftpNetworkConfig) nm `timeout` X.closeXFTPClient xftp - pure $ r >> maybe (Left (ProtocolTestFailure TSDisconnect $ BROKER addr TIMEOUT)) (const $ Right $ serverInfo (X.thParams xftp)) ok + Right xftp -> withTestChunk filePath test `E.finally` removeTestFile rcvPath + where + test = do + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + digest <- liftIO $ C.sha256Hash <$> B.readFile filePath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = X.XFTPChunkSpec {filePath, chunkOffset = 0, chunkSize = chSize} + r <- runExceptT $ do + (sId, [rId], _) <- liftError (testErr TSCreateFile) $ X.createXFTPChunk xftp spKey file [rcvKey] auth Nothing + liftError (testErr TSUploadFile) $ X.uploadXFTPChunk xftp spKey sId chunkSpec + liftError (testErr TSDownloadFile) $ X.downloadXFTPChunk g xftp rpKey rId $ XFTPRcvChunkSpec rcvPath chSize digest + rcvDigest <- liftIO $ C.sha256Hash <$> B.readFile rcvPath + unless (digest == rcvDigest) $ throwE $ ProtocolTestFailure TSCompareFile $ XFTP (B.unpack $ strEncode srv) DIGEST + liftError (testErr TSDeleteFile) $ X.deleteXFTPChunk xftp spKey sId + ok <- netTimeoutInt (tcpTimeout xftpNetworkConfig) nm `timeout` X.closeXFTPClient xftp + pure $ r >> maybe (Left (ProtocolTestFailure TSDisconnect $ BROKER addr TIMEOUT)) (const $ Right $ serverInfo (X.thParams xftp)) ok Left e -> pure $ Left (testErr TSConnect e) where addr = B.unpack $ strEncode srv @@ -1408,7 +1499,9 @@ runXFTPServerTest c@AgentClient {presetDomains} nm userId (ProtoServerWithAuth s withTestChunk fp = E.bracket_ (createTestChunk fp) - (whenM (doesFileExist fp) $ removeFile fp `catchAll_` pure ()) + (removeTestFile fp) + removeTestFile :: FilePath -> IO () + removeTestFile fp = whenM (doesFileExist fp) $ removeFile fp `catchAll_` pure () -- this creates a new DRG on purpose to avoid blocking the one used in the agent createTestChunk :: FilePath -> IO () createTestChunk fp = B.writeFile fp =<< atomically . C.randomBytes chSize =<< C.newRandom @@ -1643,7 +1736,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 +1934,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 +2211,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 @@ -2216,10 +2314,40 @@ agentNtfDeleteSubscription :: AgentClient -> NtfSubscriptionId -> NtfToken -> AM agentNtfDeleteSubscription c subId NtfToken {ntfServer, ntfPrivKey} = withNtfClient c NRMBackground ntfServer subId "SDEL" $ \ntf -> ntfDeleteSubscription ntf ntfPrivKey subId -agentXFTPDownloadChunk :: AgentClient -> UserId -> FileDigest -> RcvFileChunkReplica -> XFTPRcvChunkSpec -> AM () -agentXFTPDownloadChunk c userId (FileDigest chunkDigest) RcvFileChunkReplica {server, replicaId = ChunkReplicaId fId, replicaKey} chunkSpec = do +withXFTPDownloadPermit :: AgentClient -> (XFTPDownloadPermit -> AM a) -> AM a +withXFTPDownloadPermit c action = + ExceptT $ E.bracket (newTVarIO Nothing) (liftIO . releaseXFTPDownloadPermit c) (runExceptT . action) + +agentXFTPDownloadChunk :: AgentClient -> XFTPDownloadPermit -> UserId -> FileDigest -> RcvFileChunkReplica -> XFTPRcvChunkSpec -> AM () +agentXFTPDownloadChunk c@AgentClient {xftpServers} permit userId (FileDigest chunkDigest) RcvFileChunkReplica {server, replicaId = ChunkReplicaId fId, replicaKey} chunkSpec = do g <- asks random - withXFTPClient c (userId, server, chunkDigest) "FGET" $ \xftp -> X.downloadXFTPChunk g xftp replicaKey fId chunkSpec + tSess@(_, _, entId_) <- mkTransportSession c userId server chunkDigest + let download = withLogClient c NRMBackground tSess chunkDigest "FGET" $ \xftp -> X.downloadXFTPChunk g xftp replicaKey fId chunkSpec + downloadAndClose = download `allFinally` liftIO (closeClient c xftpClients tSess) + downloadWithPermit = liftIO (holdXFTPDownloadPermit c permit tSess) >> download + ifM + (liftIO userServer) + (if isJust entId_ then downloadAndClose else download) + downloadWithPermit + where + userServer :: IO Bool + userServer = maybe False (\srvs -> any (`S.member` knownHosts srvs) $ serverHosts server) <$> TM.lookupIO userId xftpServers + +holdXFTPDownloadPermit :: AgentClient -> XFTPDownloadPermit -> XFTPTransportSession -> IO () +holdXFTPDownloadPermit c permit tSess = + readTVarIO permit >>= \case + Nothing -> E.mask_ $ waitQSem (xftpDownloadSessions c) >> setSession + Just tSess' + | tSess' == tSess -> pure () + | otherwise -> closeClient c xftpClients tSess' >> setSession + where + setSession = atomically $ writeTVar permit $ Just tSess + +releaseXFTPDownloadPermit :: AgentClient -> XFTPDownloadPermit -> IO () +releaseXFTPDownloadPermit c permit = + readTVarIO permit >>= mapM_ (\tSess -> closeClient c xftpClients tSess >> returnPermit) + where + returnPermit = E.mask_ $ signalQSem (xftpDownloadSessions c) >> atomically (writeTVar permit Nothing) agentXFTPNewChunk :: AgentClient -> SndFileChunk -> Int -> XFTPServerWithAuth -> Maybe Word32 -> AM NewSndChunkReplica agentXFTPNewChunk c SndFileChunk {userId, chunkSpec = XFTPChunkSpec {chunkSize}, digest = FileDigest chunkDigest} n (ProtoServerWithAuth srv auth) storageHours = do @@ -2374,9 +2502,9 @@ endAgentOperation c op = endOperation c op $ case op of suspendSendingAndDatabase c AOSndNetwork -> suspendOperation c AODatabase $ - notifySuspended c + setSuspended c AODatabase -> - notifySuspended c + setSuspended c suspendMsgDelivery :: AgentClient -> STM () suspendMsgDelivery c = @@ -2387,7 +2515,7 @@ suspendSendingAndDatabase :: AgentClient -> STM () suspendSendingAndDatabase c = suspendOperation c AOSndNetwork $ suspendOperation c AODatabase $ - notifySuspended c + setSuspended c suspendOperation :: AgentClient -> AgentOperation -> STM () -> STM () suspendOperation c op endedAction = do @@ -2395,11 +2523,15 @@ suspendOperation c op endedAction = do -- unsafeIOToSTM $ putStrLn $ "suspendOperation_ " <> show op <> " " <> show n when (n == 0) $ whenSuspending c endedAction -notifySuspended :: AgentClient -> STM () -notifySuspended c = do - -- unsafeIOToSTM $ putStrLn "notifySuspended" - writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) - writeTVar (agentState c) ASSuspended +setSuspended :: AgentClient -> STM () +setSuspended c = writeTVar (agentState c) ASSuspended + +notifySuspended :: AgentClient -> IO () +notifySuspended AgentClient {agentState, subQ} = do + suspended <- atomically $ readTVar agentState >>= \case + ASSuspending -> retry + s -> pure $ s == ASSuspended + when suspended . atomically $ writeTBQueue subQ ("", "", AEvt SAENone SUSPENDED) endOperation :: AgentClient -> AgentOperation -> STM () -> STM () endOperation c op endedAction = do @@ -2488,7 +2620,7 @@ withStore' c action = withStore c $ fmap Right . action {-# INLINE withStore' #-} withStore :: AgentClient -> (DB.Connection -> IO (Either StoreError a)) -> AM a -withStore c action = withStore_ c (`withTransaction` action) +withStore c = withStoreIsolation c ReadCommitted withStoreIsolation' :: AgentClient -> IsolationLevel -> (DB.Connection -> IO a) -> AM a withStoreIsolation' c isolation action = withStoreIsolation c isolation $ fmap Right . action @@ -2518,18 +2650,26 @@ withStore_ c transaction = do unsafeWithStore :: AgentClient -> (DB.Connection -> IO a) -> AM' a unsafeWithStore c action = do st <- asks store - liftIO $ agentOperationBracket c AODatabase (\_ -> pure ()) $ withTransaction st action + liftIO $ agentOperationBracket c AODatabase (\_ -> pure ()) $ withTransactionIsolation st ReadCommitted action withStoreBatch :: Traversable t => AgentClient -> (DB.Connection -> t (IO (Either AgentErrorType a))) -> AM' (t (Either AgentErrorType a)) withStoreBatch c actions = do st <- asks store liftIO . agentOperationBracket c AODatabase (\_ -> pure ()) $ - withTransaction st $ - mapM (`E.catch` handleInternal) . actions + withTransactionIsolation st ReadCommitted $ \db -> do + let items = actions db + mapM (`catchItemError` handleInternal) items `catchRolledBack` \e -> pure (Left e <$ items) where handleInternal :: E.SomeException -> IO (Either AgentErrorType a) handleInternal = pure . Left . INTERNAL . show +catchItemError :: IO a -> (E.SomeException -> IO a) -> IO a +catchItemError = E.catchJust $ \e -> if isTransactionConflict e || abortsTransaction e then Nothing else Just e + +catchRolledBack :: IO a -> (AgentErrorType -> IO a) -> IO a +catchRolledBack = E.catchJust $ \e -> + if abortsTransaction e && not (isTransactionConflict e) then Just (INTERNAL $ "transaction rolled back after " <> show e) else Nothing + withStoreBatch' :: Traversable t => AgentClient -> (DB.Connection -> t (IO a)) -> AM' (t (Either AgentErrorType a)) withStoreBatch' c actions = withStoreBatch c (fmap (fmap Right) . actions) {-# INLINE withStoreBatch' #-} diff --git a/src/Simplex/Messaging/Agent/Env/SQLite.hs b/src/Simplex/Messaging/Agent/Env/SQLite.hs index d32be79b1..0a8bd9f29 100644 --- a/src/Simplex/Messaging/Agent/Env/SQLite.hs +++ b/src/Simplex/Messaging/Agent/Env/SQLite.hs @@ -171,11 +171,13 @@ data AgentConfig = AgentConfig logStatsInterval :: Int64, cleanupStepInterval :: Int, maxWorkerRestartsPerMin :: Int, + prohibitRequestsInConnLock :: Bool, storedMsgDataTTL :: NominalDiffTime, rcvFilesTTL :: NominalDiffTime, sndFilesTTL :: NominalDiffTime, xftpConsecutiveRetries :: Int, xftpMaxRecipientsPerRequest :: Int, + xftpMaxDownloadSessions :: Int, deleteErrorCount :: Int, keepAddressKeys :: Int, ntfCron :: Word16, @@ -249,11 +251,13 @@ defaultAgentConfig = logStatsInterval = 10 * 1000000, -- 10 seconds cleanupStepInterval = 200000, -- 200ms maxWorkerRestartsPerMin = 5, + prohibitRequestsInConnLock = False, storedMsgDataTTL = 21 * nominalDay, rcvFilesTTL = 2 * nominalDay, sndFilesTTL = nominalDay, xftpConsecutiveRetries = 3, xftpMaxRecipientsPerRequest = 200, + xftpMaxDownloadSessions = 16, deleteErrorCount = 10, keepAddressKeys = 3, ntfCron = 20, -- minutes diff --git a/src/Simplex/Messaging/Agent/Protocol.hs b/src/Simplex/Messaging/Agent/Protocol.hs index 1d28db006..2cd843387 100644 --- a/src/Simplex/Messaging/Agent/Protocol.hs +++ b/src/Simplex/Messaging/Agent/Protocol.hs @@ -287,6 +287,7 @@ import Simplex.Messaging.Protocol pattern SMPServer, ) import qualified Simplex.Messaging.Protocol as SMP +import Simplex.Messaging.Server.Information (ClientSupport) import Simplex.Messaging.ServiceScheme import Simplex.Messaging.Transport.Client (TransportHost, TransportHosts_ (..)) import Simplex.Messaging.Util @@ -449,6 +450,7 @@ data AEvent (e :: AEntity) where ERR :: AgentErrorType -> AEvent AEConn ERRS :: NonEmpty (ConnId, AgentErrorType) -> AEvent AENone SUSPENDED :: AEvent AENone + CLIENT_SUPPORT :: ClientSupport -> AEvent AENone RFPROG :: Int64 -> Int64 -> AEvent AERcvFile RFDONE :: FilePath -> AEvent AERcvFile RFERR :: AgentErrorType -> AEvent AERcvFile @@ -534,6 +536,7 @@ data AEventTag (e :: AEntity) where ERR_ :: AEventTag AEConn ERRS_ :: AEventTag AENone SUSPENDED_ :: AEventTag AENone + CLIENT_SUPPORT_ :: AEventTag AENone -- XFTP commands and responses RFDONE_ :: AEventTag AERcvFile RFPROG_ :: AEventTag AERcvFile @@ -601,6 +604,7 @@ aEventTag = \case ERR _ -> ERR_ ERRS _ -> ERRS_ SUSPENDED -> SUSPENDED_ + CLIENT_SUPPORT _ -> CLIENT_SUPPORT_ RFPROG {} -> RFPROG_ RFDONE {} -> RFDONE_ RFERR {} -> RFERR_ @@ -1741,7 +1745,7 @@ instance ConnectionModeI m => StrEncoding (ConnShortLink m) where where (authority, paramHosts) = case sch of SLSSimplex -> ("simplex:", h : hs) - SLSServer -> ("https://" <> strEncode h, hs) + SLSServer -> ("https://" <> strEncode (SrvLoc h ""), hs) lnkIdStr = if B.null lnkId then "" else B64.encodeUnpadded lnkId <> "/" queryStr = if B.null query then "" else "?" <> query query = @@ -1800,12 +1804,12 @@ instance Encoding AConnShortLink where smpP = smpP >>= \case CMInvitation -> do - (srv, lnkId, k) <- smpP - pure $ ACSL SCMInvitation $ CSLInvitation SLSServer srv lnkId (LinkKey k) + ((hs, p, kh), lnkId, k) <- smpP + pure $ ACSL SCMInvitation $ CSLInvitation SLSServer (SMPServer hs p kh) lnkId (LinkKey k) CMContact -> do ct <- ctTypeP =<< A.anyChar - (srv, k) <- smpP - pure $ ACSL SCMContact $ CSLContact SLSServer ct srv (LinkKey k) + ((hs, p, kh), k) <- smpP + pure $ ACSL SCMContact $ CSLContact SLSServer ct (SMPServer hs p kh) (LinkKey k) ctTypeP :: Char -> Parser ContactConnType ctTypeP = \case diff --git a/src/Simplex/Messaging/Agent/Store.hs b/src/Simplex/Messaging/Agent/Store.hs index 67415c718..9ccedc120 100644 --- a/src/Simplex/Messaging/Agent/Store.hs +++ b/src/Simplex/Messaging/Agent/Store.hs @@ -809,7 +809,7 @@ data StoreError SEServerNotFound | -- | Connection already used. SEConnDuplicate - | -- | Confirmed snd queue already exists. + | -- | Snd queue already exists: confirmed, or in another connection. SESndQueueExists | -- | Wrong connection type, e.g. "send" connection when "receive" or "duplex" is expected, or vice versa. -- 'upgradeRcvConnToDuplex' and 'upgradeSndConnToDuplex' do not allow duplex connections - they would also return this error. diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 41685f2e2..042832aef 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -49,6 +49,7 @@ module Simplex.Messaging.Agent.Store.AgentStore createNewConn, updateNewConnRcv, updateNewConnSnd, + deleteNewConnSnd, createSndConn, getClientNotices, updateClientNotices, @@ -130,6 +131,8 @@ module Simplex.Messaging.Agent.Store.AgentStore updateRcvMsgHash, createSndMsgBody, updateSndIds, + getNextSndIds, + updateLastIdsSnd_, createSndMsg, updateSndMsgHash, createSndMsgDelivery, @@ -285,6 +288,7 @@ module Simplex.Messaging.Agent.Store.AgentStore fromOnlyBI, getWorkItem, getWorkItems, + catchNonConflict, ) where @@ -359,7 +363,7 @@ import Database.SQLite.Simple.QQ (sql) #endif checkConstraint :: StoreError -> IO (Either StoreError a) -> IO (Either StoreError a) -checkConstraint err action = action `E.catch` (pure . Left . handleSQLError err) +checkConstraint err action = action `catchNonConflict` (pure . Left . handleSQLError err) handleSQLError :: StoreError -> SQLError -> StoreError #if defined(dbPostgres) @@ -567,14 +571,18 @@ updateNewConnSnd db connId sq = updateConn :: IO (Either StoreError SndQueue) updateConn = addConnSndQueue_ db connId sq +deleteNewConnSnd :: DB.Connection -> ConnId -> IO () +deleteNewConnSnd db connId = DB.execute db "DELETE FROM snd_queues WHERE conn_id = ? AND status = 'new'" (Only connId) + createSndConn :: DB.Connection -> TVar ChaChaDRG -> ConnData -> NewSndQueue -> IO (Either StoreError (ConnId, SndQueue)) createSndConn db gVar cData q@SndQueue {server} = -- check confirmed snd queue doesn't already exist, to prevent it being deleted by REPLACE in insertSndQueue_ - ifM (liftIO $ checkConfirmedSndQueueExists_ db q) (pure $ Left SESndQueueExists) $ - createConn_ db gVar cData $ \connId -> do + ifM (liftIO $ checkConfirmedSndQueueExists_ db q) (pure $ Left SESndQueueExists) . runExceptT $ do + (connId, sq) <- ExceptT . createConn_ db gVar cData $ \connId -> do serverKeyHash_ <- createServer db server createConnRecord db connId cData SCMInvitation insertSndQueue_ db connId q serverKeyHash_ + (connId,) <$> except sq createConnRecord :: DB.Connection -> ConnId -> ConnData -> SConnectionMode c -> IO () createConnRecord db connId ConnData {userId, connAgentVersion, enableNtfs, pqSupport, serviceRequestExpiresAt} cMode = do @@ -670,10 +678,9 @@ addConnSndQueue db connId sq = _ -> pure $ Left SEConnNotFound addConnSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> IO (Either StoreError SndQueue) -addConnSndQueue_ db connId sq@SndQueue {server} = - ifM (checkConfirmedSndQueueExists_ db sq) (pure $ Left SESndQueueExists) $ do - serverKeyHash_ <- createServer db server - Right <$> insertSndQueue_ db connId sq serverKeyHash_ +addConnSndQueue_ db connId sq@SndQueue {server} = do + serverKeyHash_ <- createServer db server + insertSndQueue_ db connId sq serverKeyHash_ setRcvQueueStatus :: DB.Connection -> RcvQueue -> QueueStatus -> IO () setRcvQueueStatus db RcvQueue {rcvId, server = ProtocolServer {host, port}} status = @@ -1041,10 +1048,15 @@ createSndMsgBody db aMessage = updateSndIds :: DB.Connection -> ConnId -> IO (Either StoreError (InternalId, InternalSndId, PrevSndMsgHash)) updateSndIds db connId = runExceptT $ do + ids@(internalId, internalSndId, _) <- ExceptT $ getNextSndIds db connId + liftIO $ updateLastIdsSnd_ db connId internalId internalSndId + pure ids + +getNextSndIds :: DB.Connection -> ConnId -> IO (Either StoreError (InternalId, InternalSndId, PrevSndMsgHash)) +getNextSndIds db connId = runExceptT $ do (lastInternalId, lastInternalSndId, prevSndHash) <- ExceptT $ retrieveLastIdsAndHashSnd_ db connId let internalId = InternalId $ unId lastInternalId + 1 internalSndId = InternalSndId $ unSndId lastInternalSndId + 1 - liftIO $ updateLastIdsSnd_ db connId internalId internalSndId pure (internalId, internalSndId, prevSndHash) createSndMsg :: DB.Connection -> ConnId -> SndMsgData -> IO () @@ -1172,7 +1184,12 @@ getWorkItems itemName getIds getItem markFailed = tryGetItem :: (Show i, AnyStoreError e) => String -> (i -> IO (Either e a)) -> (i -> IO ()) -> i -> ExceptT e IO a tryGetItem itemName getItem markFailed itemId = ExceptT getItem' `catchE` \e -> mark >> throwE e where - getItem' = E.handleJust workItemError (pure . Left . fromSomeException) $ getItem itemId + getItem' = getItem itemId `catchNonConflict` readError + readError e +#if defined(dbPostgres) + | abortsTransaction e = E.throwIO $ RetryAfter (markFailed itemId) $ itemName <> " ID " <> show itemId <> " read error: " <> show e +#endif + | otherwise = pure $ Left $ fromSomeException e mark = handleWrkErr itemName ("markFailed ID " <> show itemId) $ markFailed itemId -- Errors caught by this function will suspend worker as if there is no more work, @@ -1182,8 +1199,11 @@ handleWrkErr itemName opName action = ExceptT $ first mkError <$> E.tryJust work mkError :: E.SomeException -> e mkError e = mkWorkItemError $ itemName <> " " <> opName <> " error: " <> show e -workItemError :: E.SomeException -> Maybe E.SomeException -workItemError e = if isTransactionConflict e then Nothing else Just e +workItemError :: E.Exception e => e -> Maybe e +workItemError e = if isTransactionConflict (E.toException e) then Nothing else Just e + +catchNonConflict :: E.Exception e => IO a -> (e -> IO a) -> IO a +catchNonConflict = E.catchJust workItemError updatePendingMsgRIState :: DB.Connection -> ConnId -> InternalId -> RI2State -> IO () updatePendingMsgRIState db connId msgId RI2State {slowInterval, fastInterval} = @@ -1637,10 +1657,17 @@ createCommand db corrId connId srv_ cmd = runExceptT $ do (host_, port_, serverKeyHash_) <- serverFields createdAt <- liftIO getCurrentTime liftIO . E.handle handleErr $ +#if defined(dbPostgres) + DB.execute + db + "INSERT INTO commands (host, port, corr_id, conn_id, command_tag, command, server_key_hash, created_at) SELECT ?, ?, ?, conn_id, ?, ?, ?::BYTEA, ?::TIMESTAMPTZ FROM connections WHERE conn_id = ? FOR KEY SHARE" + (host_, port_, Binary corrId, cmdTag, cmd, serverKeyHash_, createdAt, connId) +#else DB.execute db "INSERT INTO commands (host, port, corr_id, conn_id, command_tag, command, server_key_hash, created_at) VALUES (?,?,?,?,?,?,?,?)" (host_, port_, Binary corrId, connId, cmdTag, cmd, serverKeyHash_, createdAt) +#endif where cmdTag = agentCommandTag cmd #if defined(dbPostgres) @@ -2099,7 +2126,7 @@ getNextNtfSubNTFActions db ntfServer@(NtfServer ntfHost ntfPort _) ntfBatchSize markNtfSubActionNtfFailed_ :: DB.Connection -> ConnId -> IO () markNtfSubActionNtfFailed_ db connId = - DB.execute db "UPDATE ntf_subscriptions SET ntf_failed = 1 where conn_id = ?" (Only connId) + DB.execute db "UPDATE ntf_subscriptions SET ntf_failed = 1, updated_by_supervisor = 0 where conn_id = ?" (Only connId) getNextNtfSubSMPActions :: DB.Connection -> SMPServer -> Int -> IO (Either StoreError [Either StoreError (NtfSubSMPAction, NtfSubscription)]) getNextNtfSubSMPActions db smpServer@(SMPServer smpHost smpPort _) ntfBatchSize = @@ -2144,7 +2171,7 @@ getNextNtfSubSMPActions db smpServer@(SMPServer smpHost smpPort _) ntfBatchSize markNtfSubActionSMPFailed_ :: DB.Connection -> ConnId -> IO () markNtfSubActionSMPFailed_ db connId = - DB.execute db "UPDATE ntf_subscriptions SET smp_failed = 1 where conn_id = ?" (Only connId) + DB.execute db "UPDATE ntf_subscriptions SET smp_failed = 1, updated_by_supervisor = 0 where conn_id = ?" (Only connId) markUpdatedByWorker :: DB.Connection -> ConnId -> IO () markUpdatedByWorker db connId = @@ -2398,13 +2425,13 @@ insertRcvQueue_ db connId' rq@RcvQueue {..} subMode serverKeyHash_ = do -- * createSndConn helpers -insertSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> Maybe C.KeyHash -> IO SndQueue +insertSndQueue_ :: DB.Connection -> ConnId -> NewSndQueue -> Maybe C.KeyHash -> IO (Either StoreError SndQueue) insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do -- to preserve ID if the queue already exists. -- possibly, it can be done in one query. currQId_ <- maybeFirstRow fromOnly $ DB.query db "SELECT snd_queue_id FROM snd_queues WHERE conn_id = ? AND host = ? AND port = ? AND snd_id = ?" (connId', host server, port server, sndId) qId <- maybe (newQueueId_ <$> DB.query db "SELECT snd_queue_id FROM snd_queues WHERE conn_id = ? ORDER BY snd_queue_id DESC LIMIT 1" (Only connId')) pure currQId_ - DB.execute + (rs :: [Only Int]) <- DB.query db [sql| INSERT INTO snd_queues @@ -2426,10 +2453,12 @@ insertSndQueue_ db connId' sq@SndQueue {..} serverKeyHash_ = do replace_snd_queue_id=EXCLUDED.replace_snd_queue_id, smp_client_version=EXCLUDED.smp_client_version, server_key_hash=EXCLUDED.server_key_hash + WHERE snd_queues.conn_id = EXCLUDED.conn_id + RETURNING 1 |] ((host server, port server, sndId, queueMode, connId', sndPrivateKey, e2ePubKey, e2eDhSecret) :. (status, qId, BI primary, dbReplaceQueueId, smpClientVersion, serverKeyHash_)) - pure (sq :: NewSndQueue) {connId = connId', dbQueueId = qId} + pure $ if null rs then Left SESndQueueExists else Right (sq :: NewSndQueue) {connId = connId', dbQueueId = qId} newQueueId_ :: [Only Int64] -> DBEntityId newQueueId_ [] = DBEntityId 1 @@ -3156,7 +3185,9 @@ createWithRandomId' db gVar create = tryCreate 3 #if defined(dbPostgres) handleErr n e = case constraintViolation e of Just _ -> tryCreate (n - 1) - Nothing -> pure . Left . SEInternal $ bshow e + Nothing + | isTransactionConflict (E.toException e) -> E.throwIO e + | otherwise -> pure . Left . SEInternal $ bshow e #else handleErr n e | SQL.sqlError e == SQL.ErrorConstraint = tryCreate (n - 1) diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs index 8629d1d3b..b36cb0603 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Common.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Agent.Store.Postgres.Common DBStorePool (..), DBOpts (..), IsolationLevel (..), + RetryAfter (..), newDBStorePool, withConnection, withConnection', @@ -17,12 +18,15 @@ module Simplex.Messaging.Agent.Store.Postgres.Common withTransaction', withTransactionPriority, withTransactionIsolation, + withRetriedTransaction, + withRetriedTransactionPriority, isTransactionConflict, + abortsTransaction, withSavepoint, ) where -import Control.Logger.Simple (logWarn) +import Control.Logger.Simple (logError, logWarn) import Control.Monad (void) import Control.Concurrent.MVar import Control.Concurrent.STM @@ -104,15 +108,41 @@ withTransactionPriority st priority action = withConnectionPriority st priority transaction conn = PSQL.withTransaction conn $ action conn -- isolation for agent transactions; postgresql-simple is not a dependency of SQLite builds -data IsolationLevel = RepeatableRead +data IsolationLevel = ReadCommitted | RepeatableRead + +data RetryAfter = RetryAfter (IO ()) String + +instance Show RetryAfter where + show (RetryAfter _ reason) = reason + +instance E.Exception RetryAfter withTransactionIsolation :: DBStore -> IsolationLevel -> (PSQL.Connection -> IO a) -> IO a -withTransactionIsolation st isolation action = withConnection st transaction +withTransactionIsolation st isolation action = withConnection st $ transaction (3 :: Int) where - transaction conn = retryTransaction 3 $ PSQL.withTransactionLevel level conn $ action conn + transaction n conn + | n > 0 = + E.try (inTransaction conn $ action conn) >>= \case + Right r -> pure r + Left e@(RetryAfter prepare _) -> do + logError $ "transaction rolled back after " <> tshow e + inTransaction conn prepare + transaction (n - 1) conn + | otherwise = inTransaction conn $ action conn + inTransaction conn = retryTransaction 3 . PSQL.withTransactionLevel level conn level = case isolation of + ReadCommitted -> PSQL.ReadCommitted RepeatableRead -> PSQL.RepeatableRead +withRetriedTransaction :: DBStore -> (PSQL.Connection -> IO a) -> IO a +withRetriedTransaction st = withRetriedTransactionPriority st False +{-# INLINE withRetriedTransaction #-} + +withRetriedTransactionPriority :: DBStore -> Bool -> (PSQL.Connection -> IO a) -> IO a +withRetriedTransactionPriority st priority action = withConnectionPriority st priority transaction + where + transaction conn = retryTransaction 3 $ PSQL.withTransaction conn $ action conn + retryTransaction :: Int -> IO a -> IO a retryTransaction n transaction | n > 0 = E.tryJust conflict transaction >>= either retryAfter pure @@ -126,6 +156,11 @@ retryTransaction n transaction isTransactionConflict :: E.SomeException -> Bool isTransactionConflict = maybe False conflictState . E.fromException +abortsTransaction :: E.SomeException -> Bool +abortsTransaction e = case E.fromException e of + Just (_ :: PSQL.SqlError) -> True + Nothing -> False + conflictState :: PSQL.SqlError -> Bool conflictState = (`elem` ["40001", "40P01"]) . PSQL.sqlState diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql index 33de2a8de..c1a14a830 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/agent_postgres_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); @@ -177,7 +178,7 @@ CREATE TABLE smp_agent_test_protocol_schema.commands ( command bytea NOT NULL, agent_version integer DEFAULT 1 NOT NULL, server_key_hash bytea, - created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00-05'::timestamp with time zone NOT NULL, failed smallint DEFAULT 0 ); @@ -240,14 +241,14 @@ CREATE TABLE smp_agent_test_protocol_schema.connections ( ratchet_sync_state text DEFAULT 'ok'::text NOT NULL, deleted_at_wait_delivery timestamp with time zone, pq_support smallint DEFAULT 0 NOT NULL, - created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT '1970-01-01 00:00:00-05'::timestamp with time zone NOT NULL, service_request_expires_at timestamp with time zone ); CREATE TABLE smp_agent_test_protocol_schema.deleted_snd_chunk_replicas ( - deleted_snd_chunk_replica_id bigint NOT NULL, + deleted_snd_chunk_replica_id bigint CONSTRAINT deleted_snd_chunk_replicas_deleted_snd_chunk_replica_i_not_null NOT NULL, user_id bigint NOT NULL, xftp_server_id bigint NOT NULL, replica_id bytea NOT NULL, @@ -274,7 +275,7 @@ ALTER TABLE smp_agent_test_protocol_schema.deleted_snd_chunk_replicas ALTER COLU CREATE TABLE smp_agent_test_protocol_schema.encrypted_rcv_message_hashes ( - encrypted_rcv_message_hash_id bigint NOT NULL, + encrypted_rcv_message_hash_id bigint CONSTRAINT encrypted_rcv_message_hashe_encrypted_rcv_message_hash_not_null NOT NULL, conn_id bytea NOT NULL, hash bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -417,7 +418,7 @@ ALTER TABLE smp_agent_test_protocol_schema.ntf_tokens_to_delete ALTER COLUMN ntf CREATE TABLE smp_agent_test_protocol_schema.processed_ratchet_key_hashes ( - processed_ratchet_key_hash_id bigint NOT NULL, + processed_ratchet_key_hash_id bigint CONSTRAINT processed_ratchet_key_hashe_processed_ratchet_key_hash_not_null NOT NULL, conn_id bytea NOT NULL, hash bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -650,8 +651,8 @@ ALTER TABLE smp_agent_test_protocol_schema.skipped_messages ALTER COLUMN skipped CREATE TABLE smp_agent_test_protocol_schema.snd_file_chunk_replica_recipients ( - snd_file_chunk_replica_recipient_id bigint NOT NULL, - snd_file_chunk_replica_id bigint NOT NULL, + snd_file_chunk_replica_recipient_id bigint CONSTRAINT snd_file_chunk_replica_reci_snd_file_chunk_replica_rec_not_null NOT NULL, + snd_file_chunk_replica_id bigint CONSTRAINT snd_file_chunk_replica_recip_snd_file_chunk_replica_id_not_null NOT NULL, rcv_replica_id bytea NOT NULL, rcv_replica_key bytea NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs index 46ea836dc..28160e64d 100644 --- a/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Common.hs @@ -16,6 +16,7 @@ module Simplex.Messaging.Agent.Store.SQLite.Common withTransactionPriority, withTransactionIsolation, isTransactionConflict, + abortsTransaction, withSavepoint, dbBusyLoop, storeKey, @@ -109,7 +110,7 @@ withTransactionPriority st@DBStore {dbClosed} priority action = withConnectionPr transaction db@DB.Connection {conn} = SQL.withImmediateTransaction conn $ action db -- isolation for agent transactions; postgresql-simple is not a dependency of SQLite builds -data IsolationLevel = RepeatableRead +data IsolationLevel = ReadCommitted | RepeatableRead withTransactionIsolation :: DBStore -> IsolationLevel -> (DB.Connection -> IO a) -> IO a withTransactionIsolation st _ = withTransaction st @@ -117,6 +118,9 @@ withTransactionIsolation st _ = withTransaction st isTransactionConflict :: E.SomeException -> Bool isTransactionConflict _ = False +abortsTransaction :: E.SomeException -> Bool +abortsTransaction _ = False + -- No-op for SQLite, just tries the action. -- This provides a consistent interface with the PostgreSQL version. withSavepoint :: DB.Connection -> SQL.Query -> IO a -> IO (Either SQLError a) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 884e783d0..656cf463b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -30,7 +30,7 @@ module Simplex.Messaging.Client ( -- * Connect (disconnect) client to (from) SMP server TransportSession, SMPTransportSession, - ProtocolClient (thParams, sessionTs), + ProtocolClient (thParams, sessionTs, connectedServer), SMPClient, ProxiedRelay (..), getProtocolClient, @@ -57,6 +57,7 @@ module Simplex.Messaging.Client secureSndSMPQueue, proxySecureSndSMPQueue, addSMPQueueLink, + swapSMPQueueLink, deleteSMPQueueLink, secureGetSMPQueueLink, proxySecureGetSMPQueueLink, @@ -74,6 +75,7 @@ module Simplex.Messaging.Client deleteSMPQueues, connectSMPProxiedRelay, proxySMPMessage, + proxySMPCommand, proxyResolveName, directResolveName, forwardSMPTransmission, @@ -119,7 +121,10 @@ module Simplex.Messaging.Client PCTransmission, mkTransmission, authTransmission, + pClientSndQ, + pClientSentCommandsCount, smpClientStub, + sendProtocolCommand_, -- * For debugging TBQueueInfo (..), @@ -151,10 +156,11 @@ import Data.Int (Int64) import Data.List (find, isSuffixOf) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as L -import Data.Maybe (catMaybes, fromMaybe) +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -171,7 +177,7 @@ import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport -import Simplex.Messaging.Transport.Client (SocksAuth (..), SocksProxyWithAuth (..), TransportClientConfig (..), TransportHost (..), defaultSMPPort, runTransportClient) +import Simplex.Messaging.Transport.Client (SocksAuth (..), SocksProxyWithAuth (..), TransportClientConfig (..), TransportHost (..), defaultSMPPort, runTLSTransportClient') import Simplex.Messaging.Transport.HTTP2 (httpALPN11) import Simplex.Messaging.Transport.KeepAlive import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts, x509validate) @@ -187,6 +193,7 @@ data ProtocolClient v err msg = ProtocolClient { action :: Maybe (Weak ThreadId), thParams :: THandleParams v 'TClient, sessionTs :: UTCTime, + connectedServer :: ProtoServer msg, client_ :: PClient v err msg } @@ -210,7 +217,8 @@ 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 + let srv = "smp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@localhost:5001" + connected <- newTVarIO True clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -235,10 +243,11 @@ smpClientStub g sessionId thVersion thAuth = do serverInfo = Nothing }, sessionTs = ts, + connectedServer = srv, client_ = PClient { connected, - transportSession = (1, "smp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@localhost:5001", Nothing), + transportSession = (1, srv, Nothing), transportHost = "localhost", tcpConnectTimeout, tcpTimeout, @@ -254,6 +263,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 @@ -443,9 +455,11 @@ defaultNetworkConfig = transportClientConfig :: NetworkConfig -> NetworkRequestMode -> TransportHost -> Bool -> Maybe [ALPN] -> TransportClientConfig transportClientConfig NetworkConfig {socksProxy, socksMode, tcpConnectTimeout, tcpKeepAlive, logTLSErrors} nm host useSNI clientALPN = - TransportClientConfig {socksProxy = useSocksProxy socksMode, tcpConnectTimeout = tOut, tcpKeepAlive, logTLSErrors, clientCredentials = Nothing, clientALPN, useSNI} + TransportClientConfig {socksProxy = socks, tcpConnectTimeout = tOut, tcpKeepAlive = keepAlive, logTLSErrors, clientCredentials = Nothing, clientALPN, useSNI} where tOut = netTimeoutInt tcpConnectTimeout nm + socks = useSocksProxy socksMode + keepAlive = (\ka -> if isJust socks then ka {unackedDataTimeout = Nothing} else ka) <$> tcpKeepAlive socksProxy' = (\(SocksProxyWithAuth _ proxy) -> proxy) <$> socksProxy useSocksProxy SMAlways = socksProxy' useSocksProxy SMOnion = case host of @@ -476,6 +490,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, + sentCommandsTTL :: NominalDiffTime, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -496,6 +511,7 @@ defaultClientConfig clientALPN useSNI serverVRange = { qSize = 64, defaultTransport = ("443", transport @TLS), networkConfig = defaultNetworkConfig, + sentCommandsTTL = 15 * 60, clientALPN, serviceCredentials = Nothing, serverVRange, @@ -519,6 +535,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, + createdAt :: UTCTime, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -574,7 +591,7 @@ type SMPTransportSession = TransportSession BrokerMsg -- A single queue can be used for multiple 'SMPClient' instances, -- as 'SMPServerTransmission' includes server information. getProtocolClient :: forall v err msg. Protocol v err msg => TVar ChaChaDRG -> NetworkRequestMode -> TransportSession msg -> ProtocolClientConfig v -> [HostName] -> Maybe (TBQueue (ServerTransmissionBatch v err msg)) -> UTCTime -> (ProtocolClient v err msg -> IO ()) -> IO (Either (ProtocolClientError err) (ProtocolClient v err msg)) -getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do +getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, sentCommandsTTL, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do case chooseTransportHost networkConfig (host srv) of Right useHost -> (getCurrentTime >>= mkProtocolClient useHost >>= runClient useTransport useHost) @@ -616,7 +633,7 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS let tcConfig = (transportClientConfig networkConfig nm useHost useSNI useALPN) {clientCredentials = serviceCreds <$> serviceCredentials} socksCreds = clientSocksCredentials networkConfig proxySessTs transportSession tId <- - restore (runTransportClient tcConfig socksCreds useHost port' (Just $ keyHash srv) (client t c cVar)) + restore (runTLSTransportClient' defaultSupportedParams Nothing tcConfig socksCreds useHost port' (Just $ keyHash srv) (client t c cVar)) `forkFinally` \r -> let err = either toNetworkError (const NEFailedError) r in void $ atomically $ tryPutTMVar cVar $ Left $ PCENetworkError err @@ -638,15 +655,16 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS web = useWebPort networkConfig presetDomains srv - client :: forall c. Transport c => TProxy c 'TClient -> PClient v err msg -> TMVar (Either (ProtocolClientError err) (ProtocolClient v err msg)) -> c 'TClient -> IO () - client _ c cVar h = do + client :: forall c. Transport c => TProxy c 'TClient -> PClient v err msg -> TMVar (Either (ProtocolClientError err) (ProtocolClient v err msg)) -> IO (TransportHost, ServiceName) -> c 'TClient -> IO () + client _ c cVar connectedAddress h = do ks <- if agreeSecret then Just <$> atomically (C.generateKeyPair g) else pure Nothing serviceKeys_ <- mapM (\creds -> (creds,) <$> atomically (C.generateKeyPair g)) serviceCredentials runExceptT (protocolClientHandshake @v @err @msg h ks (keyHash srv) serverVRange proxyServer serviceKeys_) >>= \case Left e -> atomically . putTMVar cVar . Left $ PCETransportError e Right th@THandle {params} -> do sessionTs <- getCurrentTime - let c' = ProtocolClient {action = Nothing, client_ = c, thParams = params, sessionTs} + connectedServer <- if proxyServer then (\(connectedHost, connectedPort) -> srv {host = [connectedHost], port = connectedPort}) <$> connectedAddress else pure srv + let c' = ProtocolClient {action = Nothing, client_ = c, thParams = params, sessionTs, connectedServer} atomically $ writeTVar (lastReceived c) sessionTs atomically $ do writeTVar (connected c) True @@ -655,10 +673,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS `E.finally` (failPendingRequests c >> disconnected c') failPendingRequests :: PClient v err msg -> IO () - failPendingRequests PClient {sentCommands} = atomically $ swapTVar sentCommands mempty >>= mapM_ failRequest - where - failRequest Request {pending, responseVar} = - whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + failPendingRequests PClient {connected, sentCommands} = atomically $ do + writeTVar connected False + swapTVar sentCommands mempty >>= mapM_ failRequest send :: Transport c => ProtocolClient v err msg -> THandle v c 'TClient -> IO () send ProtocolClient {client_ = PClient {sndQ}} h = forever $ atomically (readTBQueue sndQ) >>= sendPending @@ -677,12 +694,14 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS atomically $ writeTVar timeoutErrorCount 0 monitor :: ProtocolClient v err msg -> IO () - monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount}} = loop smpPingInterval + monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount, sentCommands}} = loop smpPingInterval where loop :: Int64 -> IO () loop delay = do threadDelay' delay - diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived + ts <- getCurrentTime + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL + diff <- diffUTCTime ts <$> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -692,7 +711,7 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS -- sendProtocolCommand/getResponse updates counter for each command cnt <- readTVarIO timeoutErrorCount -- drop client when maxCnt of commands have timed out in sequence, but only after some time has passed after last received response - when (maxCnt == 0 || cnt < maxCnt || diff < recoverWindow) $ loop smpPingInterval + when (not proxyServer && (maxCnt == 0 || cnt < maxCnt || diff < recoverWindow)) $ loop smpPingInterval recoverWindow = 15 * 60 -- seconds maxCnt = smpPingCount networkConfig @@ -763,6 +782,9 @@ closeProtocolClient :: ProtocolClient v err msg -> IO () closeProtocolClient = mapM_ (deRefWeak >=> mapM_ killThread) . action {-# INLINE closeProtocolClient #-} +pClientSentCommandsCount :: ProtocolClient v err msg -> IO Int +pClientSentCommandsCount ProtocolClient {client_ = PClient {sentCommands}} = M.size <$> readTVarIO sentCommands + -- | SMP client error type. data ProtocolClientError err = -- | Correctly parsed SMP server ERR response. @@ -888,7 +910,7 @@ processSUBResponse_ c rId = \case r' -> pure . Left $ unexpectedResponse r' writeSMPMessage :: SMPClient -> RecipientId -> BrokerMsg -> IO () -writeSMPMessage c rId msg = atomically $ mapM_ (`writeTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) +writeSMPMessage c rId msg = mapM_ (`nonBlockingWriteTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) serverTransmission :: ProtocolClient v err msg -> NonEmpty (RecipientId, ServerTransmission err msg) -> ServerTransmissionBatch v err msg serverTransmission ProtocolClient {thParams, client_ = PClient {transportSession}} ts = (transportSession, thParams, ts) @@ -982,6 +1004,15 @@ addSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> Recip addSMPQueueLink c nm rpKey rId lnkId d = okSMPCommand (LSET lnkId d) c nm rpKey rId {-# INLINE addSMPQueueLink #-} +swapSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> RecipientId -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> ExceptT SMPClientError IO (Maybe EncUserDataBytes) +swapSMPQueueLink c nm rpKey rId lnkId h ks_ d + | thVersion (thParams c) >= linkSwapSMPVersion = + sendSMPCommand c nm (Just rpKey) rId (LSWP lnkId h ks_ d) >>= \case + OK -> pure Nothing + LCUR ud -> pure $ Just ud + r -> throwE $ unexpectedResponse r + | otherwise = throwE $ PCETransportError TEVersion + -- | Delete queue link deleteSMPQueueLink :: SMPClient -> NetworkRequestMode -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPClientError IO () deleteSMPQueueLink = okSMPCommand LDEL @@ -1344,19 +1375,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 +1396,41 @@ sendProtocolCommand c nm = sendProtocolCommand_ c nm Nothing Nothing -- -- Please note: if nonce is passed it is also used as a correlation ID sendProtocolCommand_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> NetworkRequestMode -> Maybe C.CbNonce -> Maybe Int -> Maybe C.APrivateAuthKey -> EntityId -> ProtoCommand msg -> ExceptT (ProtocolClientError err) IO msg -sendProtocolCommand_ c@ProtocolClient {client_ = PClient {sndQ}, thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = +sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serviceAuth}} nm nonce_ tOut pKey entId cmd = ExceptT $ uncurry sendRecv =<< mkTransmission_ c nonce_ (entId, pKey, cmd) where - -- two separate "atomically" needed to avoid blocking sendRecv :: Either TransportError SentRawTransmission -> Request err msg -> IO (Either (ProtocolClientError err) msg) sendRecv t_ r = case t_ of Left e -> pure . Left $ PCETransportError e Right t | B.length s > blockSize - 2 -> pure . Left $ PCETransportError TELargeMsg - | otherwise -> do - nonBlockingWriteTBQueue sndQ (Just r, s) - response <$> getResponse c nm tOut r + | otherwise -> response <$> sendBlock c [r] (Just r, s) (getResponse c nm tOut r) where s = tEncodeBatch1 serviceAuth t +sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = do + ts <- getCurrentTime + -- two separate "atomically" needed to avoid blocking + E.bracketOnError + (atomically $ ifM (readTVar connected) (mapM_ (addRequest ts) rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) + (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) + (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) + where + addRequest ts r@Request {corrId} = TM.insert corrId r {createdAt = ts} sentCommands + removeRequest Request {corrId} = TM.delete corrId sentCommands + +failRequest :: Request err msg -> STM () +failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do sent <- atomically $ tryWriteTBQueue q x unless sent $ void $ forkIO $ atomically $ writeTBQueue q x getResponse :: ProtocolClient v err msg -> NetworkRequestMode -> Maybe Int -> Request err msg -> IO (Response err msg) -getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} nm tOut Request {entityId, pending, responseVar} = do +getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, sentCommands, msgQ}} nm tOut Request {corrId, entityId, pending, responseVar} = do r <- fromMaybe (netTimeoutInt tcpTimeout nm) tOut `timeout` atomically (takeTMVar responseVar) response <- atomically $ do writeTVar pending False @@ -1399,14 +1439,17 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} n -- See `processMsg`. ((r <|>) <$> tryTakeTMVar responseVar) >>= \case Just r' -> writeTVar timeoutErrorCount 0 $> r' - Nothing -> modifyTVar' timeoutErrorCount (+ 1) $> Left PCEResponseTimeout + Nothing -> do + modifyTVar' timeoutErrorCount (+ 1) + when (isNothing msgQ) $ TM.delete corrId sentCommands + pure $ Left PCEResponseTimeout pure Response {entityId, response} mkTransmission :: Protocol v err msg => ProtocolClient v err msg -> ClientCommand msg -> IO (PCTransmission err msg) mkTransmission c = mkTransmission_ c Nothing mkTransmission_ :: forall v err msg. Protocol v err msg => ProtocolClient v err msg -> Maybe C.CbNonce -> ClientCommand msg -> IO (PCTransmission err msg) -mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentCommands}} nonce_ (entityId, pKey_, command) = do +mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonce_ (entityId, pKey_, command) = do nonce@(C.CbNonce corrId) <- maybe (atomically $ C.randomCbNonce clientCorrId) pure nonce_ let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth thParams (CorrId corrId, entityId, command) auth = authTransmission (thAuth thParams) (useServiceAuth command) pKey_ (Just nonce) tForAuth @@ -1415,6 +1458,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentC where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do + createdAt <- getCurrentTime pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = @@ -1422,10 +1466,10 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId, sentC { corrId, entityId, command, + createdAt, pending, responseVar } - atomically $ TM.insert corrId r sentCommands pure r authTransmission :: Maybe (THandleAuth 'TClient) -> Bool -> Maybe C.APrivateAuthKey -> Maybe C.CbNonce -> ByteString -> Either TransportError (Maybe TAuthorizations) diff --git a/src/Simplex/Messaging/Client/Agent.hs b/src/Simplex/Messaging/Client/Agent.hs index 46d36a03c..20710e3a7 100644 --- a/src/Simplex/Messaging/Client/Agent.hs +++ b/src/Simplex/Messaging/Client/Agent.hs @@ -52,7 +52,7 @@ import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as L import Data.Map.Strict (Map) import qualified Data.Map.Strict as M -import Data.Maybe (isJust, isNothing) +import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Set as S import Data.Text.Encoding import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime) @@ -82,7 +82,7 @@ import Simplex.Messaging.Session import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport -import Simplex.Messaging.Util (catchAll_, ifM, safeDecodeUtf8, stateTVar', toChunks, tshow, whenM, ($>>=), (<$$>)) +import Simplex.Messaging.Util (catchAll_, diffToMicroseconds, ifM, safeDecodeUtf8, stateTVar', threadDelay', toChunks, tshow, whenM, ($>>=), (<$$>)) import System.Timeout (timeout) import UnliftIO (async) import UnliftIO.STM @@ -107,6 +107,9 @@ data SMPClientAgentConfig = SMPClientAgentConfig { smpCfg :: ProtocolClientConfig SMPVersion, reconnectInterval :: RetryInterval, persistErrorInterval :: NominalDiffTime, + maxPersistedErrors :: Int, + maxConnectingClients :: Maybe Int, + sessionPerConnectedServer :: Bool, msgQSize :: Maybe Natural, agentQSize :: Natural, agentSubsBatchSize :: Int, @@ -124,6 +127,9 @@ defaultSMPClientAgentConfig = maxInterval = 10 * second }, persistErrorInterval = 30, -- seconds + maxPersistedErrors = 1000, + maxConnectingClients = Nothing, + sessionPerConnectedServer = False, msgQSize = Just 2048, agentQSize = 2048, agentSubsBatchSize = 1360, @@ -143,6 +149,9 @@ data SMPClientAgent p = SMPClientAgent randomDrg :: TVar ChaChaDRG, smpClients :: TMap SMPServer SMPClientVar, smpSessions :: TMap SessionId (OwnServer, SMPClient), + connectedServerSessions :: Maybe (TMap SMPServer SessionId), + connectingClients :: TVar Int, + persistedErrors :: TVar Int, -- Only one service subscription can exist per server with this agent. -- With correctly functioning SMP server, queue and service subscriptions can't be -- active at the same time. @@ -159,7 +168,7 @@ data SMPClientAgent p = SMPClientAgent type OwnServer = Bool newSMPClientAgent :: SParty p -> SMPClientAgentConfig -> Maybe DBService -> TVar ChaChaDRG -> IO (SMPClientAgent p) -newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize} dbService randomDrg = do +newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize, sessionPerConnectedServer} dbService randomDrg = do active <- newTVarIO True startedAt <- getCurrentTime -- Only subscribing agents receive server transmissions, should not be created until processed to prevent deadlock. @@ -167,6 +176,9 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize agentQ <- newTBQueueIO agentQSize smpClients <- TM.emptyIO smpSessions <- TM.emptyIO + connectedServerSessions <- if sessionPerConnectedServer then Just <$> TM.emptyIO else pure Nothing + connectingClients <- newTVarIO 0 + persistedErrors <- newTVarIO 0 activeServiceSubs <- TM.emptyIO activeQueueSubs <- TM.emptyIO pendingServiceSubs <- TM.emptyIO @@ -185,6 +197,9 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize randomDrg, smpClients, smpSessions, + connectedServerSessions, + connectingClients, + persistedErrors, activeServiceSubs, activeQueueSubs, pendingServiceSubs, @@ -194,8 +209,7 @@ newSMPClientAgent agentParty agentCfg@SMPClientAgentConfig {msgQSize, agentQSize } data DBService = DBService - { getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials), - updateServiceId :: SMPServer -> Maybe ServiceId -> IO (Either SMPClientError ()) + { getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials) } -- | Get or create SMP client for SMPServer @@ -204,7 +218,7 @@ getSMPServerClient' ca srv = snd <$> getSMPServerClient'' ca srv {-# INLINE getSMPServerClient' #-} getSMPServerClient'' :: SMPClientAgent p -> SMPServer -> ExceptT SMPClientError IO (OwnServer, SMPClient) -getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, workerSeq} srv = do +getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, connectedServerSessions, connectingClients, persistedErrors, workerSeq} srv = do ts <- liftIO getCurrentTime withGetSessVar workerSeq srv smpClients ts (ExceptT . newSMPClient) waitForSMPClient where @@ -224,29 +238,54 @@ getSMPServerClient'' ca@SMPClientAgent {agentCfg, smpClients, smpSessions, worke Nothing -> throwE PCEResponseTimeout newSMPClient :: SMPClientVar -> IO (Either SMPClientError (OwnServer, SMPClient)) - newSMPClient v = do - r <- connectClient ca srv v `E.catches` clientHandlers + newSMPClient v = withConnectSlot $ \slot -> E.mask $ \restore -> do + r <- if slot then restore (connectClient ca srv v) `E.catches` clientHandlers else pure $ Left PCEResponseTimeout case r of Right smp -> do logInfo . decodeUtf8 $ "Agent connected to " <> showServer srv let !owned = isOwnServer ca srv !c = (owned, smp) - atomically $ do - putTMVar (sessionVar v) (Right c) - TM.insert (sessionId $ thParams smp) c smpSessions - notify ca $ CAConnected srv $ smpClientServiceId smp - pure $ Right c + atomically (sharedSession smp c) >>= \case + Just c0 -> Right c0 <$ E.uninterruptibleMask_ (closeProtocolClient smp) + Nothing -> do + notify ca $ CAConnected srv $ smpClientServiceId smp + pure $ Right c Left e -> do let ei = persistErrorInterval agentCfg - if ei == 0 + persisted <- if slot && ei > 0 then atomically $ takeSlot persistedErrors $ maxPersistedErrors agentCfg else pure False + if not persisted then atomically $ do putTMVar (sessionVar v) (Left (e, Nothing)) removeSessVar v srv smpClients else do ts <- addUTCTime ei <$> liftIO getCurrentTime atomically $ putTMVar (sessionVar v) (Left (e, Just ts)) - reconnectClient ca srv + let removeError = atomically $ removeSessVar v srv smpClients >> modifyTVar' persistedErrors (subtract 1) + void (forkIO $ restore (threadDelay' $ diffToMicroseconds ei) `E.finally` removeError) `E.onException` removeError + restore $ reconnectClient ca srv pure $ Left e + where + sharedSession :: SMPClient -> (OwnServer, SMPClient) -> STM (Maybe (OwnServer, SMPClient)) + sharedSession smp c = + (pure connectedServerSessions $>>= TM.lookup (connectedServer smp) $>>= (`TM.lookup` smpSessions)) >>= \case + Just c0 -> Just c0 <$ putTMVar (sessionVar v) (Right c0) + Nothing -> do + putTMVar (sessionVar v) (Right c) + whenM (activeClientSession ca smp srv) $ do + TM.insert sessId c smpSessions + forM_ connectedServerSessions $ TM.insert (connectedServer smp) sessId + pure Nothing + where + sessId = sessionId $ thParams smp + + withConnectSlot :: (Bool -> IO a) -> IO a + withConnectSlot = + E.bracket + (atomically $ takeSlot connectingClients $ fromMaybe maxBound $ maxConnectingClients agentCfg) + (`when` atomically (modifyTVar' connectingClients (subtract 1))) + + takeSlot :: TVar Int -> Int -> STM Bool + takeSlot slots limit = stateTVar' slots $ \n -> if n < limit then (True, n + 1) else (False, n) isOwnServer :: SMPClientAgent p -> SMPServer -> OwnServer isOwnServer SMPClientAgent {agentCfg} ProtocolServer {host} = @@ -258,10 +297,7 @@ connectClient :: SMPClientAgent p -> SMPServer -> SMPClientVar -> IO (Either SMP connectClient ca@SMPClientAgent {agentCfg, dbService, smpClients, smpSessions, msgQ, randomDrg, startedAt} srv v = case dbService of Just dbs -> runExceptT $ do creds <- ExceptT $ getCredentials dbs srv - smp <- ExceptT $ getClient cfg {serviceCredentials = Just creds} - whenM (atomically $ activeClientSession ca smp srv) $ - ExceptT $ updateServiceId dbs srv $ smpClientServiceId smp - pure smp + ExceptT $ getClient cfg {serviceCredentials = Just creds} Nothing -> getClient cfg where cfg = smpCfg agentCfg @@ -280,6 +316,8 @@ connectClient ca@SMPClientAgent {agentCfg, dbService, smpClients, smpSessions, m qVar_ <- TM.lookupIO srv $ activeQueueSubs ca atomically $ do TM.delete sessId smpSessions + forM_ (connectedServerSessions ca) $ \ss -> + whenM ((Just sessId ==) <$> TM.lookup (connectedServer smp) ss) $ TM.delete (connectedServer smp) ss removeSessVar v srv smpClients sSub <- pure sVar_ $>>= updateServiceSub qSubs <- pure qVar_ $>>= updateQueueSubs diff --git a/src/Simplex/Messaging/Crypto.hs b/src/Simplex/Messaging/Crypto.hs index 16d5b3d22..9495e7abe 100644 --- a/src/Simplex/Messaging/Crypto.hs +++ b/src/Simplex/Messaging/Crypto.hs @@ -263,7 +263,7 @@ import Simplex.Messaging.Agent.Store.DB (Binary (..), FromField (..), ToField (. import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll, parseString) -import Simplex.Messaging.Util (packZipWith, stateTVar', (<$?>)) +import Simplex.Messaging.Util (forceDecoded, packZipWith, stateTVar', (<$?>)) -- | Cryptographic algorithms. data Algorithm = Ed25519 | Ed448 | X25519 | X448 @@ -1274,9 +1274,9 @@ newtype SignedObject a = SignedObject {getSignedExact :: X.SignedExact a} instance (Typeable a, Eq a, Show a, ASN1Object a) => FromField (SignedObject a) where #if defined(dbPostgres) - fromField f dat = SignedObject <$> blobFieldDecoder X.decodeSignedObject f dat + fromField f dat = SignedObject <$> blobFieldDecoder decodeSignedObject f dat #else - fromField = fmap SignedObject . blobFieldDecoder X.decodeSignedObject + fromField = fmap SignedObject . blobFieldDecoder decodeSignedObject #endif instance (Eq a, Show a, ASN1Object a) => ToField (SignedObject a) where @@ -1284,7 +1284,10 @@ instance (Eq a, Show a, ASN1Object a) => ToField (SignedObject a) where instance (Eq a, Show a, ASN1Object a) => Encoding (SignedObject a) where smpEncode (SignedObject exact) = smpEncode . Large $ X.encodeSignedObject exact - smpP = fmap SignedObject . X.decodeSignedObject . unLarge <$?> smpP + smpP = fmap SignedObject . decodeSignedObject . unLarge <$?> smpP + +decodeSignedObject :: (Eq a, Show a, ASN1Object a) => ByteString -> Either String (X.SignedExact a) +decodeSignedObject = forceDecoded (length . show) . X.decodeSignedObject encodeCertChain :: X.CertificateChain -> L.NonEmpty Large encodeCertChain cc = L.fromList $ map Large blobs @@ -1294,7 +1297,7 @@ encodeCertChain cc = L.fromList $ map Large blobs certChainP :: A.Parser X.CertificateChain certChainP = do rawChain <- X.CertificateChainRaw . map unLarge . L.toList <$> smpP - either (fail . show) pure $ X.decodeCertificateChain rawChain + either fail pure . forceDecoded (length . show) . first show $ X.decodeCertificateChain rawChain -- | Signature verification. -- @@ -1590,7 +1593,7 @@ x509ToPrivate' pk = x509ToPrivate (pk, []) >>= privKey {-# INLINE x509ToPrivate' #-} decodeASNKey :: ASN1Object a => ByteString -> Either String (a, [ASN1]) -decodeASNKey = fromASN1 <=< first show . decodeASN1 DER . fromStrict +decodeASNKey = forceDecoded (length . snd) . fromASN1 <=< first show . decodeASN1 DER . fromStrict asnKeyError :: (a, [ASN1]) -> Either String b asnKeyError = \case diff --git a/src/Simplex/Messaging/Crypto/Ratchet.hs b/src/Simplex/Messaging/Crypto/Ratchet.hs index d09dd5b17..2a60cec7e 100644 --- a/src/Simplex/Messaging/Crypto/Ratchet.hs +++ b/src/Simplex/Messaging/Crypto/Ratchet.hs @@ -84,13 +84,16 @@ module Simplex.Messaging.Crypto.Ratchet RatchetKEM (..), RatchetKEMAccepted (..), RatchetKey (..), + EncMessageHeader (..), + EncRatchetMessage (..), + paddedHeaderLen, fullHeaderLen, applySMDiff, ) where import Control.Applicative ((<|>)) -import Control.Monad (unless) +import Control.Monad (unless, when) import Control.Monad.Except import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except @@ -470,7 +473,7 @@ pqX3dhSnd :: DhAlgorithm a => AE2EPrivRatchetParams a -> E2ERatchetParams 'RKSPr -- 3. replied 2. received pqX3dhSnd (spk1, spk2, spKem_) (E2ERatchetParams _ rk1 rk2 rKem_) = do (ks_, kem_) <- sndPq - let initParams = pqX3dh (publicKey spk1, rk1) (dh' rk1 spk2) (dh' rk2 spk1) (dh' rk2 spk2) kem_ + initParams <- pqX3dh (publicKey spk1, rk1) (dh' rk1 spk2) (dh' rk2 spk1) (dh' rk2 spk2) kem_ pure (initParams, ks_) where sndPq :: Either CryptoError (Maybe KEMKeyPair, Maybe RatchetKEMAccepted) @@ -486,7 +489,7 @@ pqX3dhRcv :: forall s a. (RatchetKEMStateI s, DhAlgorithm a) => RcvE2EPrivRatche -- 1. sent 4. received in reply pqX3dhRcv (rpk1, rpk2, rpKem_) (E2ERatchetParams _ sk1 sk2 sKem_) = do kem_ <- rcvPq - let initParams = pqX3dh (sk1, publicKey rpk1) (dh' sk2 rpk1) (dh' sk1 rpk2) (dh' sk2 rpk2) (snd <$> kem_) + initParams <- liftEither $ pqX3dh (sk1, publicKey rpk1) (dh' sk2 rpk1) (dh' sk1 rpk2) (dh' sk2 rpk2) (snd <$> kem_) pure (initParams, fst <$> kem_) where rcvPq :: ExceptT CryptoError IO (Maybe (KEMKeyPair, RatchetKEMAccepted)) @@ -498,9 +501,10 @@ pqX3dhRcv (rpk1, rpk2, rpKem_) (E2ERatchetParams _ sk1 sk2 sKem_) = do Nothing -> throwE CERatchetKEMState _ -> pure Nothing -- both parties can send "proposal" in case of ratchet renegotiation -pqX3dh :: DhAlgorithm a => (PublicKey a, PublicKey a) -> DhSecret a -> DhSecret a -> DhSecret a -> Maybe RatchetKEMAccepted -> RatchetInitParams +pqX3dh :: DhAlgorithm a => (PublicKey a, PublicKey a) -> DhSecret a -> DhSecret a -> DhSecret a -> Maybe RatchetKEMAccepted -> Either CryptoError RatchetInitParams pqX3dh (sk1, rk1) dh1 dh2 dh3 kemAccepted = - RatchetInitParams {assocData, rcVerifyCodePQ = Str vcPQ, ratchetKey = RatchetKey sk, sndHK = Key hk, rcvNextHK = Key nhk, kemAccepted} + mapM_ checkDhSecret [dh1, dh2, dh3] + $> RatchetInitParams {assocData, rcVerifyCodePQ = Str vcPQ, ratchetKey = RatchetKey sk, sndHK = Key hk, rcvNextHK = Key nhk, kemAccepted} where assocData = Str $ pubKeyBytes sk1 <> pubKeyBytes rk1 dhs = dhBytes' dh1 <> dhBytes' dh2 <> dhBytes' dh3 <> pq @@ -645,30 +649,31 @@ instance FromField MessageKey where fromField = blobFieldDecoder smpDecode -- // above added for KEM -- @ initSndRatchet :: - forall a. (AlgorithmI a, DhAlgorithm a) => RatchetVersions -> PublicKey a -> PrivateKey a -> (RatchetInitParams, Maybe KEMKeyPair) -> Ratchet a + forall a. (AlgorithmI a, DhAlgorithm a) => RatchetVersions -> PublicKey a -> PrivateKey a -> (RatchetInitParams, Maybe KEMKeyPair) -> Either CryptoError (Ratchet a) initSndRatchet rcVersion rcDHRr rcDHRs (RatchetInitParams {assocData, rcVerifyCodePQ, ratchetKey, sndHK, rcvNextHK, kemAccepted}, rcPQRs_) = do -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(SK, DH(state.DHRs, state.DHRr) || state.PQRss) - let (rcRK, rcCKs, rcNHKs) = rootKdf ratchetKey rcDHRr rcDHRs (rcPQRss <$> kemAccepted) - pqOn = isJust rcPQRs_ - in Ratchet - { rcVersion, - rcAD = assocData, - rcVCPQ = Just rcVerifyCodePQ, - rcDHRs, - rcKEM = (`RatchetKEM` kemAccepted) <$> rcPQRs_, - rcSupportKEM = PQSupport pqOn, - rcEnableKEM = PQEncryption pqOn, - rcSndKEM = PQEncryption $ isJust kemAccepted, - rcRcvKEM = PQEncOff, - rcRK, - rcSnd = Just SndRatchet {rcDHRr, rcCKs, rcHKs = sndHK}, - rcRcv = Nothing, - rcPN = 0, - rcNs = 0, - rcNr = 0, - rcNHKs, - rcNHKr = rcvNextHK - } + (rcRK, rcCKs, rcNHKs) <- rootKdf ratchetKey rcDHRr rcDHRs (rcPQRss <$> kemAccepted) + let pqOn = isJust rcPQRs_ + pure + Ratchet + { rcVersion, + rcAD = assocData, + rcVCPQ = Just rcVerifyCodePQ, + rcDHRs, + rcKEM = (`RatchetKEM` kemAccepted) <$> rcPQRs_, + rcSupportKEM = PQSupport pqOn, + rcEnableKEM = PQEncryption pqOn, + rcSndKEM = PQEncryption $ isJust kemAccepted, + rcRcvKEM = PQEncOff, + rcRK, + rcSnd = Just SndRatchet {rcDHRr, rcCKs, rcHKs = sndHK}, + rcRcv = Nothing, + rcPN = 0, + rcNs = 0, + rcNr = 0, + rcNHKs, + rcNHKr = rcvNextHK + } -- | Receiving ratchet initialization, equivalent to RatchetInitBobPQ2HE in double ratchet spec -- @@ -923,8 +928,7 @@ rcEncryptHeader rc@Ratchet {rcSnd = Just sr@SndRatchet {rcCKs, rcHKs}, rcDHRs, r rcNs = rcNs + 1, rcSupportKEM = rcSupportKEM', rcEnableKEM = rcEnableKEM', - rcVersion = rcVersion', - rcKEM = if pqEnc_ == Just PQEncOff then (\rck -> rck {rcKEMs = Nothing}) <$> rcKEM else rcKEM + rcVersion = rcVersion' } pure (msgEncryptKey, rc') where @@ -1039,10 +1043,10 @@ rcDecrypt g rc@Ratchet {rcRcv, rcAD = Str rcAD, rcVersion} rcMKSkipped msg' = do -- state.DHRs = GENERATE_DH() (_, rcDHRs') <- atomically $ generateKeyPair @a g -- state.RK, state.CKr, state.NHKr = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || ss) - let (rcRK', rcCKr', rcNHKr') = rootKdf rcRK msgDHRs rcDHRs kemSS - -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || state.PQRss) - (rcRK'', rcCKs', rcNHKs') = rootKdf rcRK' msgDHRs rcDHRs' kemSS' - sndKEM = isJust kemSS' + (rcRK', rcCKr', rcNHKr') <- liftEither $ rootKdf rcRK msgDHRs rcDHRs kemSS + -- state.RK, state.CKs, state.NHKs = KDF_RK_HE(state.RK, DH(state.DHRs, state.DHRr) || state.PQRss) + (rcRK'', rcCKs', rcNHKs') <- liftEither $ rootKdf rcRK' msgDHRs rcDHRs' kemSS' + let sndKEM = isJust kemSS' rcvKEM = isJust kemSS rcEnableKEM' = PQEncryption $ sndKEM || rcvKEM || isJust rcKEM' pure @@ -1149,14 +1153,21 @@ rcDecrypt g rc@Ratchet {rcRcv, rcAD = Str rcAD, rcVersion} rcMKSkipped msg' = do -- DECRYPT(mk, cipher-text, CONCAT(AD, enc_header)) tryE $ decryptAEAD mk iv (rcAD <> emHeader) emBody emAuthTag -rootKdf :: (AlgorithmI a, DhAlgorithm a) => RatchetKey -> PublicKey a -> PrivateKey a -> Maybe KEMSharedKey -> (RatchetKey, RatchetKey, Key) +rootKdf :: (AlgorithmI a, DhAlgorithm a) => RatchetKey -> PublicKey a -> PrivateKey a -> Maybe KEMSharedKey -> Either CryptoError (RatchetKey, RatchetKey, Key) rootKdf (RatchetKey rk) k pk kemSecret_ = - let dhOut = dhBytes' (dh' k pk) + let dhSecret = dh' k pk + dhOut = dhBytes' dhSecret ss = case kemSecret_ of Just (KEMSharedKey s) -> dhOut <> BA.convert s Nothing -> dhOut (rk', ck, nhk) = hkdf3 rk ss "SimpleXRootRatchet" - in (RatchetKey rk', RatchetKey ck, Key nhk) + in checkDhSecret dhSecret $> (RatchetKey rk', RatchetKey ck, Key nhk) + +-- RFC 7748 section 6.2: X25519 and X448 produce the all-zero secret for low-order public keys +checkDhSecret :: DhSecret a -> Either CryptoError () +checkDhSecret s = when (BA.constEq dhOut $ B.replicate (B.length dhOut) '\0') $ Left $ CryptoHeaderError "all-zero DH secret" + where + dhOut = dhBytes' s chainKdf :: RatchetKey -> (RatchetKey, Key, IV, IV) chainKdf (RatchetKey ck) = diff --git a/src/Simplex/Messaging/Encoding/String.hs b/src/Simplex/Messaging/Encoding/String.hs index bde94e4a7..0ec1df18a 100644 --- a/src/Simplex/Messaging/Encoding/String.hs +++ b/src/Simplex/Messaging/Encoding/String.hs @@ -30,6 +30,7 @@ import qualified Data.Aeson.Encoding as JE import qualified Data.Aeson.Types as JT import Data.Attoparsec.ByteString.Char8 (Parser) import qualified Data.Attoparsec.ByteString.Char8 as A +import Data.Bifunctor (first) import qualified Data.ByteString.Base64.URL as U import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B @@ -52,7 +53,7 @@ import qualified Data.X509.Validation as XV import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import Simplex.Messaging.Encoding import Simplex.Messaging.Parsers (parseAll) -import Simplex.Messaging.Util (bshow, safeDecodeUtf8, (<$?>)) +import Simplex.Messaging.Util (bshow, forceDecoded, safeDecodeUtf8, (<$?>)) class TextEncoding a where textEncode :: a -> Text @@ -164,7 +165,7 @@ instance StrEncoding UTCTime where instance StrEncoding X.CertificateChain where strEncode = (\(X.CertificateChainRaw blobs) -> strEncodeList blobs) . X.encodeCertificateChain {-# INLINE strEncode #-} - strP = either (fail . show) pure . X.decodeCertificateChain . X.CertificateChainRaw =<< strListP + strP = forceDecoded (length . show) . first show . X.decodeCertificateChain . X.CertificateChainRaw <$?> strListP {-# INLINE strP #-} instance StrEncoding XV.Fingerprint where diff --git a/src/Simplex/Messaging/Notifications/Protocol.hs b/src/Simplex/Messaging/Notifications/Protocol.hs index 423a048e1..44f096f9b 100644 --- a/src/Simplex/Messaging/Notifications/Protocol.hs +++ b/src/Simplex/Messaging/Notifications/Protocol.hs @@ -384,13 +384,9 @@ data SMPQueueNtf = SMPQueueNtf instance Encoding SMPQueueNtf where smpEncode SMPQueueNtf {smpServer, notifierId} = smpEncode (smpServer, notifierId) smpP = do - smpServer <- updateSMPServerHosts <$> (requireKeyHash <$?> smpP) + smpServer <- updateSMPServerHosts <$> smpP notifierId <- smpP pure SMPQueueNtf {smpServer, notifierId} - where - requireKeyHash srv - | B.null (C.unKeyHash (keyHash srv)) = Left "SMP server without key hash" - | otherwise = Right srv instance StrEncoding SMPQueueNtf where strEncode SMPQueueNtf {smpServer, notifierId} = strEncode smpServer <> "/" <> strEncode notifierId diff --git a/src/Simplex/Messaging/Notifications/Server.hs b/src/Simplex/Messaging/Notifications/Server.hs index 04b1fe228..5aa4040b6 100644 --- a/src/Simplex/Messaging/Notifications/Server.hs +++ b/src/Simplex/Messaging/Notifications/Server.hs @@ -24,7 +24,6 @@ where import Control.Concurrent (threadDelay) import Control.Concurrent.Async (mapConcurrently) -import qualified Control.Exception as E import Control.Logger.Simple import Control.Monad import Control.Monad.Except @@ -48,14 +47,14 @@ import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Text.Encoding (decodeLatin1) -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import GHC.IORef (atomicSwapIORef) import GHC.Stats (getRTSStats) import Network.Socket (ServiceName, Socket, socketToHandle) import Numeric.Natural (Natural) -import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError, ServerTransmission (..)) +import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError, ServerTransmission (..), nonBlockingWriteTBQueue) import Simplex.Messaging.Client.Agent import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String @@ -170,9 +169,8 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} logServerStats :: Int64 -> Int64 -> FilePath -> M () logServerStats startAt logInterval statsFilePath = do - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime logNote $ "server stats log enabled: " <> T.pack statsFilePath - liftIO $ threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) + liftIO $ delayUntilDayTime startAt NtfServerStats {fromTime, tknCreated, tknVerified, tknDeleted, tknReplaced, subCreated, subDeleted, ntfReceived, ntfDelivered, ntfFailed, ntfCronDelivered, ntfCronFailed, ntfVrfQueued, ntfVrfDelivered, ntfVrfFailed, ntfVrfInvalidTkn, activeTokens, activeSubs} <- asks serverStats let interval = 1000000 * logInterval @@ -254,8 +252,9 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} d <- getNtfServerStatsData ss let psTkns = periodStatDataCounts $ _activeTokens d psSubs = periodStatDataCounts $ _activeSubs d - (tokenCount, approxSubCount, lastNtfCount) <- getEntityCounts st - pure NtfServerMetrics {statsData = d, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, approxSubCount, lastNtfCount, rtsOptions} + NtfEntityCounts {tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount} <- getEntityCounts st + let tokenCount = sum $ map snd tokenStatusCounts + pure NtfServerMetrics {statsData = d, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount, rtsOptions} getNtfRealTimeMetrics :: NtfEnv -> IO NtfRealTimeMetrics getNtfRealTimeMetrics NtfEnv {subscriber, pushServer} = do @@ -396,6 +395,7 @@ ntfServer cfg@NtfServerConfig {transports, transportConfig = tCfg, startOptions} putStat "ntfReceived" ntfReceived putStat "ntfDelivered" ntfDelivered putStat "ntfFailed" ntfFailed + putStat "ntfDropped" ntfDropped putStat "ntfCronDelivered" ntfCronDelivered putStat "ntfCronFailed" ntfCronFailed putStat "ntfVrfQueued" ntfVrfQueued @@ -491,22 +491,21 @@ subscribeSrvSubs ca st batchSize (srv, srvId, service_) = do -- this function is concurrency-safe - only onle subscriber per server can be created at a time, -- other threads would wait for the first thread to create it. subscribeNtfs :: NtfSubscriber -> NtfPostgresStore -> SMPServer -> Int64 -> ServerNtfSub -> IO () -subscribeNtfs NtfSubscriber {smpSubscribers, subscriberSeq, smpAgent = ca} st smpServer srvId ntfSub = - getSubscriberVar - >>= either createSMPSubscriber waitForSMPSubscriber +subscribeNtfs NtfSubscriber {smpSubscribers, subscriberSeq, smpAgent = ca} st smpServer srvId ntfSub = do + ts <- getCurrentTime + withGetSessVar' subscriberSeq smpServer smpSubscribers ts createSMPSubscriber waitForSMPSubscriber >>= mapM_ (\sub -> atomically $ writeTQueue (subscriberSubQ sub) ntfSub) where - getSubscriberVar :: IO (Either SMPSubscriberVar SMPSubscriberVar) - getSubscriberVar = getSessVarIO subscriberSeq smpServer smpSubscribers =<< getCurrentTime - createSMPSubscriber :: SMPSubscriberVar -> IO (Maybe SMPSubscriber) createSMPSubscriber v = - E.handle (\(e :: SomeException) -> logError ("SMP subscriber exception: " <> tshow e) >> removeSubscriber v) $ do - q <- newTQueueIO - tId <- mkWeakThreadId =<< forkIO (runSMPSubscriber smpServer srvId q) - let sub = SMPSubscriber {smpServer, smpServerId = srvId, subscriberSubQ = q, subThreadId = tId} - atomically $ putTMVar (sessionVar v) sub -- this makes it available for other threads - pure $ Just sub + ( do + q <- newTQueueIO + tId <- mkWeakThreadId =<< forkIO (runSMPSubscriber smpServer srvId q) + let sub = SMPSubscriber {smpServer, smpServerId = srvId, subscriberSubQ = q, subThreadId = tId} + atomically $ putTMVar (sessionVar v) sub -- this makes it available for other threads + pure $ Just sub + ) + `catchOwn'` \e -> logError ("SMP subscriber exception: " <> tshow e) >> removeSubscriber v waitForSMPSubscriber :: SMPSubscriberVar -> IO (Maybe SMPSubscriber) waitForSMPSubscriber v = @@ -537,18 +536,21 @@ ntfSubscriber NtfSubscriber {smpAgent = ca@SMPClientAgent {msgQ = msgQ_, agentQ} ps <- asks pushServer stats <- asks serverStats forever $ do - ((_, srv@(SMPServer (h :| _) _ _), _), THandleParams {sessionId}, ts) <- atomically $ readTBQueue msgQ + ((_, srv, _), THandleParams {sessionId}, ts) <- atomically $ readTBQueue msgQ forM_ ts $ \(ntfId, t) -> case t of STUnexpectedError e -> logError $ "SMP client unexpected error: " <> tshow e -- uncorrelated response, should not happen + STResponse _ r@(Right (SMP.NMSG _ _)) -> processNtf st ps stats srv sessionId ntfId r STResponse {} -> pure () -- it was already reported as timeout error - STEvent msgOrErr -> do + STEvent r -> processNtf st ps stats srv sessionId ntfId r + where + processNtf st ps stats srv sessionId ntfId msgOrErr = do let smpQueue = SMPQueueNtf srv ntfId case msgOrErr of Right (SMP.NMSG nmsgNonce encNMsgMeta) -> do ntfTs <- liftIO getSystemTime liftIO $ updatePeriodStats (activeSubs stats) ntfId let newNtf = PNMessageData {smpQueue, ntfTs, nmsgNonce, encNMsgMeta} - srvHost = safeDecodeUtf8 $ strEncode h + srvHost = safeDecodeUtf8 $ strEncode $ L.head $ host srv isOwn = isOwnServer ca srv liftIO (addTokenLastNtf st newNtf) >>= \case Right (tkn, lastNtfs) -> do @@ -643,13 +645,15 @@ showServer' :: SMPServer -> Text showServer' = decodeLatin1 . strEncode . host pushNotification :: NtfPushServer -> Maybe T.Text -> OwnServer -> NtfTknRec -> PushNotification -> M () -pushNotification s srvHost_ isOwn tkn@NtfTknRec {ntfTknId, token = token@(DeviceToken pp _)} ntf = +pushNotification s srvHost_ isOwn tkn@NtfTknRec {token = token@(DeviceToken pp _)} ntf = ifM (pushProviderAllowed token) - (getOrCreatePushWorker s (srvHost_, pp, hash (unEntityId ntfTknId) `mod` pushWorkersPerServer) isOwn >>= atomically . (`writeTBQueue` (tkn, ntf))) + (getOrCreatePushWorker s (srvHost_, pp, pushTokenShardId 8 tkn) isOwn >>= liftIO . (`nonBlockingWriteTBQueue` (tkn, ntf))) (logWarn "skipping disabled APNS test push provider") - where - pushWorkersPerServer = 8 + +pushTokenShardId :: Int -> NtfTknRec -> Int +pushTokenShardId pushWorkersPerServer NtfTknRec {ntfTknId} = + hash (unEntityId ntfTknId) `mod` pushWorkersPerServer pushProviderAllowed :: DeviceToken -> M Bool pushProviderAllowed (DeviceToken PPApnsTest _) = asks (allowTestPushProvider . config) @@ -712,7 +716,7 @@ runPushWorker s srvHost_ isOwn q = forever $ do | otherwise = liftIO $ logError "bad notification token status" deliverNotification :: NtfPostgresStore -> PushProvider -> NtfTknRec -> PushNotification -> IO (Either PushProviderError ()) deliverNotification st pp tkn@NtfTknRec {ntfTknId} ntf' = do - (deliver, clientVar) <- getPushClient s pp + (deliver, clientVar) <- getPushClient s pp tokenShardId runExceptT (deliver tkn ntf') >>= \case Right _ -> pure $ Right () Left e -> case e of @@ -725,11 +729,12 @@ runPushWorker s srvHost_ isOwn q = forever $ do err e PPPermanentError -> err e where + tokenShardId = pushTokenShardId 8 tkn retryDeliver :: PushClientVar -> Text -> IO (Either PushProviderError ()) retryDeliver oldVar reason = do logWarn $ "retrying push (" <> tshow pp <> ", " <> tshow ntfTknId <> "): " <> reason - atomically $ removeSessVar oldVar pp (pushClients s) - (deliver, _) <- getPushClient s pp + atomically $ removeSessVar oldVar (pp, tokenShardId) (pushClients s) + (deliver, _) <- getPushClient s pp tokenShardId runExceptT (deliver tkn ntf') >>= \case Right _ -> pure $ Right () Left e -> case e of diff --git a/src/Simplex/Messaging/Notifications/Server/Env.hs b/src/Simplex/Messaging/Notifications/Server/Env.hs index 0395f93ef..04a0774ad 100644 --- a/src/Simplex/Messaging/Notifications/Server/Env.hs +++ b/src/Simplex/Messaging/Notifications/Server/Env.hs @@ -30,11 +30,9 @@ module Simplex.Messaging.Notifications.Server.Env import Control.Concurrent (ThreadId) import qualified Control.Exception as E import Control.Logger.Simple -import Control.Monad import Control.Monad.Except import Control.Monad.Trans.Except import Crypto.Random -import Data.Functor (($>)) import Data.Int (Int64) import Simplex.Messaging.Agent.RetryInterval import Data.List.NonEmpty (NonEmpty) @@ -54,7 +52,7 @@ import Simplex.Messaging.Notifications.Server.Stats import Simplex.Messaging.Notifications.Server.Store.Postgres import Simplex.Messaging.Notifications.Server.Store.Types import Simplex.Messaging.Notifications.Transport (NTFVersion, VersionRangeNTF) -import Simplex.Messaging.Protocol (BasicAuth, CorrId, Party (..), SMPServer, SParty (..), ServiceId, Transmission) +import Simplex.Messaging.Protocol (BasicAuth, CorrId, Party (..), SMPServer, SParty (..), Transmission) import Simplex.Messaging.Server.Env.STM (StartOptions (..)) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.QueueStore.Postgres.Config (PostgresStoreCfg (..)) @@ -66,7 +64,6 @@ import Simplex.Messaging.Transport.Credentials (genCredentials, tlsCredentials) import Simplex.Messaging.Transport.Server (AddHTTP, ServerCredentials, TransportServerConfig, loadFingerprint, loadServerCredential) import Simplex.Messaging.Util (isAsyncCancellation, liftEitherWith, tshow) import Simplex.Messaging.Util () -import System.Exit (exitFailure) import System.Mem.Weak (Weak) import UnliftIO.STM @@ -132,7 +129,7 @@ newNtfServerEnv config@NtfServerConfig {pushQSize, smpAgentCfg, apnsConfig, dbSt serverStats <- newNtfServerStats =<< getCurrentTime pure NtfEnv {config, subscriber, pushServer, store, random, tlsServerCreds, serverIdentity = C.KeyHash fp, serverStats} where - mkDbService g st = DBService {getCredentials, updateServiceId} + mkDbService g st = DBService {getCredentials} where getCredentials :: SMPServer -> IO (Either SMPClientError ServiceCredentials) getCredentials srv = runExceptT $ do @@ -148,8 +145,6 @@ newNtfServerEnv config@NtfServerConfig {pushQSize, smpAgentCfg, apnsConfig, dbSt let tlsCreds = tlsCredentials [cred] setNtfServiceCredentials db srvId tlsCreds pure tlsCreds - updateServiceId :: SMPServer -> Maybe ServiceId -> IO (Either SMPClientError ()) - updateServiceId srv serviceId_ = withClientDB "" st $ \db -> updateNtfServiceId db srv serviceId_ data NtfSubscriber = NtfSubscriber { smpSubscribers :: TMap SMPServer SMPSubscriberVar, @@ -177,7 +172,7 @@ data NtfPushServer = NtfPushServer { pushWorkers :: TMap (Maybe T.Text, PushProvider, Int) PushWorkerVar, -- Int is the worker shard pushWorkerSeq :: TVar Int, pushQSize :: Natural, - pushClients :: TMap PushProvider PushClientVar, + pushClients :: TMap (PushProvider, Int) PushClientVar, pushClientSeq :: TVar Int, apnsConfig :: APNSPushClientConfig } @@ -203,11 +198,11 @@ newNtfPushServer pushQSize apnsConfig = do -- | Single-flight access to the per-provider push client with bounded retry. -- The returned PushClientVar is the handle retryDeliver passes to removeSessVar to evict -- this specific instance before re-fetching. -getPushClient :: NtfPushServer -> PushProvider -> IO (PushProviderClient, PushClientVar) -getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInterval}} pp = +getPushClient :: NtfPushServer -> PushProvider -> Int -> IO (PushProviderClient, PushClientVar) +getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInterval}} pp tokenShardId = withRetryIntervalCount reconnectInterval $ \n _delay loop -> do ts <- getCurrentTime - E.try (getSessVarIO (pushClientSeq s) pp (pushClients s) ts >>= either (newPushClient s pp) waitForPushClient) >>= \case + E.try (atomically (getSessVar (pushClientSeq s) (pp, tokenShardId) (pushClients s) ts) >>= either (newPushClient s pp tokenShardId) waitForPushClient) >>= \case Right result -> pure result Left e | isAsyncCancellation e -> E.throwIO e @@ -216,15 +211,15 @@ getPushClient s@NtfPushServer {apnsConfig = APNSPushClientConfig {reconnectInter loop | otherwise -> E.throwIO e -newPushClient :: NtfPushServer -> PushProvider -> PushClientVar -> IO (PushProviderClient, PushClientVar) -newPushClient NtfPushServer {pushClients, apnsConfig} pp v = do +newPushClient :: NtfPushServer -> PushProvider -> Int -> PushClientVar -> IO (PushProviderClient, PushClientVar) +newPushClient NtfPushServer {pushClients, apnsConfig} pp tokenShardId v = do r <- E.try $ case apnsProviderHost pp of Nothing -> pure $ \_ _ -> pure () Just host -> apnsPushProviderClient <$> createAPNSPushClient host apnsConfig atomically $ do putTMVar (sessionVar v) r case r of - Left _ -> removeSessVar v pp pushClients + Left _ -> removeSessVar v (pp, tokenShardId) pushClients Right _ -> pure () either E.throwIO (\c -> pure (c, v)) r diff --git a/src/Simplex/Messaging/Notifications/Server/Prometheus.hs b/src/Simplex/Messaging/Notifications/Server/Prometheus.hs index 8277da632..0f1ac4cdf 100644 --- a/src/Simplex/Messaging/Notifications/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Notifications/Server/Prometheus.hs @@ -31,7 +31,9 @@ data NtfServerMetrics = NtfServerMetrics activeTokensCounts :: PeriodStatCounts, activeSubsCounts :: PeriodStatCounts, tokenCount :: Int64, + tokenStatusCounts :: [(Text, Int64)], approxSubCount :: Int64, + subStatusCounts :: [(Text, Int64)], lastNtfCount :: Int64, rtsOptions :: Text } @@ -61,7 +63,7 @@ ntfPrometheusMetrics :: NtfServerMetrics -> NtfRealTimeMetrics -> UTCTime -> Tex ntfPrometheusMetrics sm rtm ts = time <> tokens <> subscriptions <> notifications <> info where - NtfServerMetrics {statsData, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, approxSubCount, lastNtfCount, rtsOptions} = sm + NtfServerMetrics {statsData, activeTokensCounts = psTkns, activeSubsCounts = psSubs, tokenCount, tokenStatusCounts, approxSubCount, subStatusCounts, lastNtfCount, rtsOptions} = sm NtfRealTimeMetrics { threadsCount, srvSubscribers, @@ -86,6 +88,7 @@ ntfPrometheusMetrics sm rtm ts = _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -137,6 +140,7 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_tokens_total gauge\n\ \simplex_ntf_tokens_total " <> mshow tokenCount <> "\n# tokenCount\n\ \\n" + <> gaugeMetrics "simplex_pg_ntf_token_status_total" (statusMetrics tokenStatusCounts) "Total count of each token status" "tokenStatusCounts" subscriptions = "# Subscriptions\n\ \# -------------\n\ @@ -165,6 +169,7 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_subscriptions_approx_total gauge\n\ \simplex_ntf_subscriptions_approx_total " <> mshow approxSubCount <> "\n# approxSubCount\n\ \\n" + <> gaugeMetrics "simplex_pg_ntf_subscription_status_total" (statusMetrics subStatusCounts) "Total count of each subscription status, approximate for ACTIVE, DELETED and AUTH" "subStatusCounts" <> showSubMetric ntfActiveServiceSubs "simplex_ntf_smp_service_subscription_active_" "Active" <> showSubMetric ntfActiveQueueSubs "simplex_ntf_smp_subscription_active_" "Active" <> showSubMetric ntfPendingServiceSubs "simplex_ntf_smp_service_subscription_pending_" "Pending" @@ -189,6 +194,10 @@ ntfPrometheusMetrics sm rtm ts = \# TYPE simplex_ntf_notifications_failed counter\n\ \simplex_ntf_notifications_failed " <> mshow _ntfFailed <> "\n# ntfFailed\n\ \\n\ + \# HELP simplex_ntf_notifications_dropped Notifications not pushed because the push queue is full\n\ + \# TYPE simplex_ntf_notifications_dropped counter\n\ + \simplex_ntf_notifications_dropped " <> mshow _ntfDropped <> "\n# ntfDropped\n\ + \\n\ \# HELP simplex_ntf_notifications_periodic_delivered Delivered periodic notifications\n\ \# TYPE simplex_ntf_notifications_periodic_delivered counter\n\ \simplex_ntf_notifications_periodic_delivered " <> mshow _ntfCronDelivered <> "\n# ntfCronDelivered\n\ @@ -284,6 +293,7 @@ ntfPrometheusMetrics sm rtm ts = <> T.concat (map (\(param, value) -> name <> param <> " " <> mshow value <> "\n") subMetrics) <> "# " <> codeRef <> "\n\n" metricHost host = "{server=\"" <> host <> "\"}" + statusMetrics = map (\(status, cnt) -> ("{status=\"" <> status <> "\"}", fromIntegral cnt)) mstr a = a <> " " <> tsEpoch mshow :: Show a => a -> Text mshow = mstr . tshow diff --git a/src/Simplex/Messaging/Notifications/Server/Stats.hs b/src/Simplex/Messaging/Notifications/Server/Stats.hs index b23fc6301..7162cc44f 100644 --- a/src/Simplex/Messaging/Notifications/Server/Stats.hs +++ b/src/Simplex/Messaging/Notifications/Server/Stats.hs @@ -41,6 +41,7 @@ data NtfServerStats = NtfServerStats ntfReceivedAuth :: IORef Int, ntfDelivered :: IORef Int, ntfFailed :: IORef Int, + ntfDropped :: IORef Int, ntfReceivedOwn :: StatsByServer, ntfReceivedAuthOwn :: StatsByServer, ntfDeliveredOwn :: StatsByServer, @@ -67,6 +68,7 @@ data NtfServerStatsData = NtfServerStatsData _ntfReceivedAuth :: Int, _ntfDelivered :: Int, _ntfFailed :: Int, + _ntfDropped :: Int, _ntfReceivedOwn :: StatsByServerData, _ntfReceivedAuthOwn :: StatsByServerData, _ntfDeliveredOwn :: StatsByServerData, @@ -94,6 +96,7 @@ newNtfServerStats ts = do ntfReceivedAuth <- newIORef 0 ntfDelivered <- newIORef 0 ntfFailed <- newIORef 0 + ntfDropped <- newIORef 0 ntfReceivedOwn <- TM.emptyIO ntfReceivedAuthOwn <- TM.emptyIO ntfDeliveredOwn <- TM.emptyIO @@ -119,6 +122,7 @@ newNtfServerStats ts = do ntfReceivedAuth, ntfDelivered, ntfFailed, + ntfDropped, ntfReceivedOwn, ntfReceivedAuthOwn, ntfDeliveredOwn, @@ -146,6 +150,7 @@ getNtfServerStatsData s@NtfServerStats {fromTime} = do _ntfReceivedAuth <- readIORef $ ntfReceivedAuth s _ntfDelivered <- readIORef $ ntfDelivered s _ntfFailed <- readIORef $ ntfFailed s + _ntfDropped <- readIORef $ ntfDropped s _ntfReceivedOwn <- getStatsByServer $ ntfReceivedOwn s _ntfReceivedAuthOwn <- getStatsByServer $ ntfReceivedAuthOwn s _ntfDeliveredOwn <- getStatsByServer $ ntfDeliveredOwn s @@ -171,6 +176,7 @@ getNtfServerStatsData s@NtfServerStats {fromTime} = do _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -199,6 +205,7 @@ setNtfServerStats s@NtfServerStats {fromTime} d@NtfServerStatsData {_fromTime} = writeIORef (ntfReceivedAuth s) $! _ntfReceivedAuth d writeIORef (ntfDelivered s) $! _ntfDelivered d writeIORef (ntfFailed s) $! _ntfFailed d + writeIORef (ntfDropped s) $! _ntfDropped d setStatsByServer (ntfReceivedOwn s) $! _ntfReceivedOwn d setStatsByServer (ntfReceivedAuthOwn s) $! _ntfReceivedAuthOwn d setStatsByServer (ntfDeliveredOwn s) $! _ntfDeliveredOwn d @@ -226,6 +233,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, @@ -251,6 +259,7 @@ instance StrEncoding NtfServerStatsData where "ntfReceivedAuth=" <> strEncode _ntfReceivedAuth, "ntfDelivered=" <> strEncode _ntfDelivered, "ntfFailed=" <> strEncode _ntfFailed, + "ntfDropped=" <> strEncode _ntfDropped, "ntfReceivedOwn=" <> strEncode _ntfReceivedOwn, "ntfReceivedAuthOwn=" <> strEncode _ntfReceivedAuthOwn, "ntfDeliveredOwn=" <> strEncode _ntfDeliveredOwn, @@ -278,6 +287,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth <- opt "ntfReceivedAuth=" _ntfDelivered <- "ntfDelivered=" *> strP <* A.endOfLine _ntfFailed <- opt "ntfFailed=" + _ntfDropped <- opt "ntfDropped=" _ntfReceivedOwn <- statByServerP "ntfReceivedOwn=" _ntfReceivedAuthOwn <- statByServerP "ntfReceivedAuthOwn=" _ntfDeliveredOwn <- statByServerP "ntfDeliveredOwn=" @@ -305,6 +315,7 @@ instance StrEncoding NtfServerStatsData where _ntfReceivedAuth, _ntfDelivered, _ntfFailed, + _ntfDropped, _ntfReceivedOwn, _ntfReceivedAuthOwn, _ntfDeliveredOwn, diff --git a/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs b/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs index eae815a5b..ac4d44edd 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs +++ b/src/Simplex/Messaging/Notifications/Server/Store/Migrations.hs @@ -18,7 +18,8 @@ ntfServerSchemaMigrations = [ ("20250417_initial", m20250417_initial, Nothing), ("20250517_service_cert", m20250517_service_cert, Just down_m20250517_service_cert), ("20250830_queue_ids_hash", m20250830_queue_ids_hash, Just down_m20250830_queue_ids_hash), - ("20251219_service_cert_per_server", m20251219_service_cert_per_server, Just down_m20251219_service_cert_per_server) + ("20251219_service_cert_per_server", m20251219_service_cert_per_server, Just down_m20251219_service_cert_per_server), + ("20261112_status_counts_autovacuum", m20261112_status_counts_autovacuum, Just down_m20261112_status_counts_autovacuum) ] -- | The list of migrations in ascending order by date @@ -250,6 +251,32 @@ ALTER TABLE smp_servers |] <> resetNtfServices +m20261112_status_counts_autovacuum :: Text +m20261112_status_counts_autovacuum = + [r| +CREATE INDEX idx_subscriptions_uncommon_status ON subscriptions(status) WHERE status NOT IN ('ACTIVE', 'DELETED', 'AUTH'); + +ALTER TABLE subscriptions SET ( + autovacuum_vacuum_scale_factor = 0.02, + autovacuum_analyze_scale_factor = 0.01, + autovacuum_vacuum_cost_limit = 1000 +); + +ALTER TABLE last_notifications SET ( + autovacuum_vacuum_scale_factor = 0.02, + autovacuum_analyze_scale_factor = 0.01 +); + |] + +down_m20261112_status_counts_autovacuum :: Text +down_m20261112_status_counts_autovacuum = + [r| +ALTER TABLE last_notifications RESET (autovacuum_vacuum_scale_factor, autovacuum_analyze_scale_factor); +ALTER TABLE subscriptions RESET (autovacuum_vacuum_scale_factor, autovacuum_analyze_scale_factor, autovacuum_vacuum_cost_limit); + +DROP INDEX idx_subscriptions_uncommon_status; + |] + resetNtfServices :: Text resetNtfServices = [r| diff --git a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs index fd739993b..95bea2fe1 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs +++ b/src/Simplex/Messaging/Notifications/Server/Store/Postgres.hs @@ -31,7 +31,6 @@ module Simplex.Messaging.Notifications.Server.Store.Postgres getUsedSMPServers, getNtfServiceCredentials, setNtfServiceCredentials, - updateNtfServiceId, getServerNtfSubscriptions, findNtfSubscription, getNtfSubscription, @@ -49,6 +48,7 @@ module Simplex.Messaging.Notifications.Server.Store.Postgres batchUpdateSrvSubErrors, removeServiceAndAssociations, addTokenLastNtf, + NtfEntityCounts (..), getEntityCounts, withDB', withClientDB, @@ -88,7 +88,6 @@ import Simplex.Messaging.Agent.Store.Postgres.DB (fromTextField_) import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..)) import Simplex.Messaging.Client (ProtocolClientError (..), SMPClientError) import Simplex.Messaging.Encoding -import Simplex.Messaging.Encoding.String import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Store.Migrations @@ -105,6 +104,7 @@ import Text.Hex (decodeHex) #if !defined(dbPostgres) import qualified Data.X509 as X import Simplex.Messaging.Agent.Store.Postgres.DB (blobFieldDecoder) +import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Util (eitherToMaybe) #endif @@ -316,44 +316,6 @@ setNtfServiceCredentials db srvId (kh, (cert, pk)) = |] (kh, cert, pk, srvId) -updateNtfServiceId :: DB.Connection -> SMPServer -> Maybe ServiceId -> IO () -updateNtfServiceId db srv newServiceId_ = do - maybeFirstRow id (getSMPServiceForUpdate_ db srv) >>= mapM_ updateService - where - updateService (srvId, currServiceId_) = unless (currServiceId_ == newServiceId_) $ do - when (isJust currServiceId_) $ do - void $ removeServiceAssociation_ db srvId - logError $ "STORE: service ID for " <> enc (host srv) <> toServiceId <> ", removed sub associations" - void $ case newServiceId_ of - Just newServiceId -> - DB.execute - db - [sql| - UPDATE smp_servers - SET ntf_service_id = ?, - smp_notifier_count = 0, - smp_notifier_ids_hash = DEFAULT - WHERE smp_server_id = ? - |] - (newServiceId, srvId) - Nothing -> - DB.execute - db - [sql| - UPDATE smp_servers - SET ntf_service_id = NULL, - ntf_service_cert = NULL, - ntf_service_cert_hash = NULL, - ntf_service_priv_key = NULL, - smp_notifier_count = 0, - smp_notifier_ids_hash = DEFAULT - WHERE smp_server_id = ? - |] - (Only srvId) - toServiceId = maybe " removed" ((" changed to " <>) . enc) newServiceId_ - enc :: StrEncoding a => a -> Text - enc = decodeLatin1 . strEncode - getServerNtfSubscriptions :: NtfPostgresStore -> Int64 -> Maybe NtfSubscriptionId -> Int -> IO (Either ErrorType [ServerNtfSub]) getServerNtfSubscriptions st srvId afterSubId_ count = withDB' "getServerNtfSubscriptions" st $ \db -> do @@ -619,11 +581,11 @@ removeServiceAssociation_ db srvId = db [sql| UPDATE subscriptions s - SET status = ?, ntf_service_assoc = FALSE + SET status = CASE WHEN s.status IN ? THEN ? ELSE s.status END, ntf_service_assoc = FALSE WHERE smp_server_id = ? - AND (s.status != ? OR s.ntf_service_assoc != FALSE) + AND ((s.status IN ? AND s.status != ?) OR s.ntf_service_assoc != FALSE) |] - (NSInactive, srvId, NSInactive) + (In subscribeNtfStatuses, NSInactive, srvId, In subscribeNtfStatuses, NSInactive) removeServiceAndAssociations :: NtfPostgresStore -> SMPServer -> IO (Either ErrorType (Int64, Int)) removeServiceAndAssociations st srv = do @@ -650,9 +612,6 @@ removeServiceAndAssociations st srv = do [sql| UPDATE smp_servers SET ntf_service_id = NULL, - ntf_service_cert = NULL, - ntf_service_cert_hash = NULL, - ntf_service_priv_key = NULL, smp_notifier_count = 0, smp_notifier_ids_hash = DEFAULT WHERE smp_server_id = ? @@ -728,13 +687,32 @@ toLastNtf (qRow :. (ts, nonce, Binary encMeta)) = let ntfTs = MkSystemTime (systemSeconds $ utcToSystemTime ts) 0 in PNMessageData {smpQueue = rowToSMPQueue qRow, ntfTs, nmsgNonce = nonce, encNMsgMeta = encMeta} -getEntityCounts :: NtfPostgresStore -> IO (Int64, Int64, Int64) +data NtfEntityCounts = NtfEntityCounts + { tokenStatusCounts :: [(Text, Int64)], + approxSubCount :: Int64, + subStatusCounts :: [(Text, Int64)], + lastNtfCount :: Int64 + } + +getEntityCounts :: NtfPostgresStore -> IO NtfEntityCounts getEntityCounts st = - fmap (fromRight (0, 0, 0)) $ withDB' "getEntityCounts" st $ \db -> do - tCnt <- count <$> DB.query_ db "SELECT count(1) FROM tokens" - sCnt <- count <$> DB.query_ db "SELECT reltuples::BIGINT FROM pg_class WHERE relname = 'subscriptions' AND relkind = 'r'" - nCnt <- count <$> DB.query_ db "SELECT count(1) FROM last_notifications" - pure (tCnt, sCnt, nCnt) + fmap (fromRight $ NtfEntityCounts [] 0 [] 0) $ withDB' "getEntityCounts" st $ \db -> do + tokenStatusCounts <- DB.query_ db "SELECT status, count(1) FROM tokens GROUP BY status" + approxSubCount <- count <$> DB.query_ db "SELECT reltuples::BIGINT FROM pg_class WHERE relname = 'subscriptions' AND relkind = 'r'" + uncommonSubCounts <- DB.query_ db "SELECT status, count(1) FROM subscriptions WHERE status NOT IN ('ACTIVE', 'DELETED', 'AUTH') GROUP BY status" + commonSubCounts <- + DB.query_ + db + [sql| + SELECT v.status, (v.freq * GREATEST(c.reltuples, 0))::BIGINT + FROM pg_stats s + CROSS JOIN LATERAL unnest(s.most_common_vals::TEXT::TEXT[], s.most_common_freqs) AS v(status, freq) + JOIN pg_class c ON c.oid = 'subscriptions'::regclass + WHERE s.schemaname = current_schema() AND s.tablename = 'subscriptions' AND s.attname = 'status' + AND v.status IN ('ACTIVE', 'DELETED', 'AUTH') + |] + lastNtfCount <- count <$> DB.query_ db "SELECT count(1) FROM last_notifications" + pure NtfEntityCounts {tokenStatusCounts, approxSubCount, subStatusCounts = commonSubCounts <> uncommonSubCounts, lastNtfCount} where count (Only n : _) = n count [] = 0 @@ -757,7 +735,7 @@ withDB op st = withDB_ op st False withDB_ :: forall a. Text -> NtfPostgresStore -> Bool -> (DB.Connection -> IO (Either ErrorType a)) -> IO (Either ErrorType a) withDB_ op st priority action = - E.uninterruptibleMask_ $ E.try (withTransactionPriority (dbStore st) priority action) >>= either logErr pure + E.uninterruptibleMask_ $ E.try (withRetriedTransactionPriority (dbStore st) priority action) >>= either logErr pure where logErr :: E.SomeException -> IO (Either ErrorType a) logErr e = logError ("STORE: " <> err) $> Left (STORE err) @@ -766,7 +744,7 @@ withDB_ op st priority action = withClientDB :: Text -> NtfPostgresStore -> (DB.Connection -> IO a) -> IO (Either SMPClientError a) withClientDB op st action = - E.uninterruptibleMask_ $ E.try (withTransaction (dbStore st) action) >>= bimapM logErr pure + E.uninterruptibleMask_ $ E.try (withRetriedTransaction (dbStore st) action) >>= bimapM logErr pure where logErr :: E.SomeException -> IO SMPClientError logErr e = logError ("STORE: " <> op <> ", withDB, " <> tshow e) $> PCEIOError (E.displayException e) diff --git a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql index 627ee9dcf..218f13cd7 100644 --- a/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql +++ b/src/Simplex/Messaging/Notifications/Server/Store/ntf_server_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); @@ -140,7 +141,8 @@ CREATE TABLE ntf_server.last_notifications ( sent_at timestamp with time zone NOT NULL, nmsg_nonce bytea NOT NULL, nmsg_data bytea NOT NULL -); +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); @@ -197,7 +199,8 @@ CREATE TABLE ntf_server.subscriptions ( smp_notifier_key bytea NOT NULL, status text NOT NULL, ntf_service_assoc boolean DEFAULT false NOT NULL -); +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01', autovacuum_vacuum_cost_limit='1000'); @@ -270,6 +273,10 @@ CREATE INDEX idx_subscriptions_token_id ON ntf_server.subscriptions USING btree +CREATE INDEX idx_subscriptions_uncommon_status ON ntf_server.subscriptions USING btree (status) WHERE (status <> ALL (ARRAY['ACTIVE'::text, 'DELETED'::text, 'AUTH'::text])); + + + CREATE UNIQUE INDEX idx_tokens_push_provider_token ON ntf_server.tokens USING btree (push_provider, push_provider_token, verify_key); diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 05efa40c5..aa66a2a68 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -64,6 +64,8 @@ module Simplex.Messaging.Protocol EncFixedDataBytes, EncUserDataBytes, EncDataBytes (..), + LinkDataHash (..), + linkDataHash, NewNtfCreds (..), ServerNtfCreds (..), Party (..), @@ -213,6 +215,7 @@ module Simplex.Messaging.Protocol sameSrvAddr, sameSrvAddr', noAuthSrv, + requireKeyHash, toMsgInfo, -- * TCP transport functions @@ -602,6 +605,7 @@ data Command (p :: Party) where KEY :: SndPublicAuthKey -> Command Recipient RKEY :: NonEmpty RcvPublicAuthKey -> Command Recipient LSET :: LinkId -> QueueLinkData -> Command Recipient + LSWP :: LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> Command Recipient LDEL :: Command Recipient NKEY :: NtfPublicAuthKey -> RcvNtfPublicDhKey -> Command Recipient NDEL :: Command Recipient @@ -689,6 +693,13 @@ instance ToField EncDataBytes where toField (EncDataBytes s) = toField (Binary s) {-# INLINE toField #-} +newtype LinkDataHash = LinkDataHash ByteString + deriving (Eq, Show) + deriving newtype (Encoding) + +linkDataHash :: EncUserDataBytes -> LinkDataHash +linkDataHash (EncDataBytes s) = LinkDataHash $ C.sha256Hash s + data NewNtfCreds = NewNtfCreds NtfPublicAuthKey RcvNtfPublicDhKey deriving (Show) instance StrEncoding SubscriptionMode where @@ -753,6 +764,7 @@ data BrokerMsg where -- SMP broker messages (responses, client messages, notifications) IDS :: QueueIdsKeys -> BrokerMsg LNK :: SenderId -> QueueLinkData -> BrokerMsg + LCUR :: EncUserDataBytes -> BrokerMsg -- | Service subscription success - confirms when queue was associated with the service SOK :: Maybe ServiceId -> BrokerMsg -- | The number of queues and XOR-hash of their IDs subscribed with SUBS command @@ -970,6 +982,7 @@ data CommandTag (p :: Party) where KEY_ :: CommandTag Recipient RKEY_ :: CommandTag Recipient LSET_ :: CommandTag Recipient + LSWP_ :: CommandTag Recipient LDEL_ :: CommandTag Recipient NKEY_ :: CommandTag Recipient NDEL_ :: CommandTag Recipient @@ -999,6 +1012,7 @@ deriving instance Show CmdTag data BrokerMsgTag = IDS_ | LNK_ + | LCUR_ | SOK_ | SOKS_ | MSG_ @@ -1034,6 +1048,7 @@ instance PartyI p => Encoding (CommandTag p) where KEY_ -> "KEY" RKEY_ -> "RKEY" LSET_ -> "LSET" + LSWP_ -> "LSWP" LDEL_ -> "LDEL" NKEY_ -> "NKEY" NDEL_ -> "NDEL" @@ -1063,6 +1078,7 @@ instance ProtocolMsgTag CmdTag where "KEY" -> Just $ CT SRecipient KEY_ "RKEY" -> Just $ CT SRecipient RKEY_ "LSET" -> Just $ CT SRecipient LSET_ + "LSWP" -> Just $ CT SRecipient LSWP_ "LDEL" -> Just $ CT SRecipient LDEL_ "NKEY" -> Just $ CT SRecipient NKEY_ "NDEL" -> Just $ CT SRecipient NDEL_ @@ -1095,6 +1111,7 @@ instance Encoding BrokerMsgTag where smpEncode = \case IDS_ -> "IDS" LNK_ -> "LNK" + LCUR_ -> "LCUR" SOK_ -> "SOK" SOKS_ -> "SOKS" MSG_ -> "MSG" @@ -1118,6 +1135,7 @@ instance ProtocolMsgTag BrokerMsgTag where decodeTag = \case "IDS" -> Just IDS_ "LNK" -> Just LNK_ + "LCUR" -> Just LCUR_ "SOK" -> Just SOK_ "SOKS" -> Just SOKS_ "MSG" -> Just MSG_ @@ -1334,13 +1352,13 @@ instance ProtocolTypeI p => IsString (ProtocolServer p) where instance ProtocolTypeI p => Encoding (ProtocolServer p) where smpEncode ProtocolServer {host, port, keyHash} = smpEncode (host, port, keyHash) - smpP = do + smpP = requireKeyHash <$?> do (host, port, keyHash) <- smpP pure ProtocolServer {scheme = protocolTypeI @p, host, port, keyHash} instance ProtocolTypeI p => StrEncoding (ProtocolServer p) where strEncode ProtocolServer {scheme, host, port, keyHash} = - strEncodeServer scheme (strEncode host) port keyHash Nothing + strEncodeServer scheme host port keyHash Nothing strP = serverStrP >>= \case (AProtocolServer _ srv, Nothing) -> either fail pure $ checkProtocolType srv @@ -1353,6 +1371,11 @@ instance ProtocolTypeI p => ToJSON (ProtocolServer p) where instance ProtocolTypeI p => FromJSON (ProtocolServer p) where parseJSON = strParseJSON "ProtocolServer" +requireKeyHash :: ProtocolServer p -> Either String (ProtocolServer p) +requireKeyHash srv@ProtocolServer {keyHash} + | B.null (C.unKeyHash keyHash) = Left "server without key hash" + | otherwise = Right srv + newtype BasicAuth = BasicAuth {unBasicAuth :: ByteString} deriving (Ord, Show) @@ -1388,7 +1411,7 @@ deriving instance Show AProtoServerWithAuth instance ProtocolTypeI p => StrEncoding (ProtoServerWithAuth p) where strEncode (ProtoServerWithAuth ProtocolServer {scheme, host, port, keyHash} auth_) = - strEncodeServer scheme (strEncode host) port keyHash auth_ + strEncodeServer scheme host port keyHash auth_ strP = (\(AProtoServerWithAuth _ srv) -> checkProtocolType srv) <$?> strP instance StrEncoding AProtoServerWithAuth where @@ -1419,18 +1442,19 @@ legacyEncodeServer ProtocolServer {host, port, keyHash} = smpEncode (L.head host, port, keyHash) legacyServerP :: forall p. ProtocolTypeI p => Parser (ProtocolServer p) -legacyServerP = do +legacyServerP = requireKeyHash <$?> do (h, port, keyHash) <- smpP pure ProtocolServer {scheme = protocolTypeI @p, host = [h], port, keyHash} legacyStrEncodeServer :: ProtocolTypeI p => ProtocolServer p -> ByteString legacyStrEncodeServer ProtocolServer {scheme, host, port, keyHash} = - strEncodeServer scheme (strEncode $ L.head host) port keyHash Nothing + strEncodeServer scheme [L.head host] port keyHash Nothing -strEncodeServer :: ProtocolTypeI p => SProtocolType p -> ByteString -> ServiceName -> C.KeyHash -> Maybe BasicAuth -> ByteString +strEncodeServer :: ProtocolTypeI p => SProtocolType p -> NonEmpty TransportHost -> ServiceName -> C.KeyHash -> Maybe BasicAuth -> ByteString strEncodeServer scheme host port keyHash auth_ = - strEncode scheme <> "://" <> strEncode keyHash <> maybe "" ((":" <>) . strEncode) auth_ <> "@" <> host <> portStr + strEncode scheme <> "://" <> strEncode keyHash <> maybe "" ((":" <>) . strEncode) auth_ <> "@" <> hostStr <> portStr where + hostStr = B.intercalate "," $ map (strEncode . (`SrvLoc` "")) $ L.toList host portStr = B.pack $ if null port then "" else ':' : port serverStrP :: Parser (AProtocolServer, Maybe BasicAuth) @@ -1885,6 +1909,7 @@ instance PartyI p => ProtocolEncoding SMPVersion ErrorType (Command p) where KEY k -> e (KEY_, ' ', k) RKEY ks -> e (RKEY_, ' ', ks) LSET lnkId d -> e (LSET_, ' ', lnkId, d) + LSWP lnkId h keys_ d -> e (LSWP_, ' ', lnkId, h, keys_, d) LDEL -> e LDEL_ NKEY k dhKey -> e (NKEY_, ' ', k, dhKey) NDEL -> e NDEL_ @@ -1980,6 +2005,7 @@ instance ProtocolEncoding SMPVersion ErrorType Cmd where KEY_ -> KEY <$> _smpP RKEY_ -> RKEY <$> _smpP LSET_ -> LSET <$> _smpP <*> smpP + LSWP_ -> LSWP <$> _smpP <*> smpP <*> smpP <*> smpP LDEL_ -> pure LDEL NKEY_ -> NKEY <$> _smpP <*> smpP NDEL_ -> pure NDEL @@ -2028,6 +2054,7 @@ instance ProtocolEncoding SMPVersion ErrorType BrokerMsg where where ids = e (IDS_, ' ', rcvId, sndId, srvDh) LNK sId d -> e (LNK_, ' ', sId, d) + LCUR d -> e (LCUR_, ' ', d) SOK serviceId_ | v >= serviceCertsSMPVersion -> e (SOK_, ' ', serviceId_) | otherwise -> e OK_ -- won't happen, the association with the service requires v >= serviceCertsSMPVersion @@ -2090,6 +2117,7 @@ instance ProtocolEncoding SMPVersion ErrorType BrokerMsg where serverNtfCreds <- p4 pure $ IDS QIK {rcvId, sndId, rcvPublicDhKey, queueMode, linkId, serviceId, serverNtfCreds} LNK_ -> LNK <$> _smpP <*> smpP + LCUR_ -> LCUR <$> _smpP SOK_ -> SOK <$> _smpP SOKS_ -> serviceRespP SOKS NID_ -> NID <$> _smpP <*> smpP diff --git a/src/Simplex/Messaging/Server.hs b/src/Simplex/Messaging/Server.hs index 314069373..846fd9fa8 100644 --- a/src/Simplex/Messaging/Server.hs +++ b/src/Simplex/Messaging/Server.hs @@ -42,6 +42,7 @@ module Simplex.Messaging.Server ) where +import Control.Applicative ((<|>)) import Control.Concurrent.STM (throwSTM) import qualified Control.Exception as E import Control.Logger.Simple @@ -59,6 +60,7 @@ import qualified Data.ByteString.Builder as BLD import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB +import qualified Data.ByteString.Short as SBS import Data.Constraint (Dict (..)) import Data.Dynamic (toDyn) import Data.Either (fromRight, isRight, partitionEithers) @@ -81,7 +83,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1) import qualified Data.Text.IO as T -import Data.Time.Clock (UTCTime (..), diffTimeToPicoseconds, getCurrentTime) +import Data.Time.Clock (UTCTime (..), getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Time.Format.ISO8601 (iso8601Show) import Data.Type.Equality @@ -96,7 +98,7 @@ import Network.Socket (ServiceName, Socket, socketToHandle) import qualified Network.TLS as TLS import Numeric.Natural (Natural) import Simplex.Messaging.Agent.Lock -import Simplex.Messaging.Client (NetworkConfig (..), NetworkRequestMode (..), ProtocolClient (thParams), ProtocolClientConfig (..), ProtocolClientError (..), SMPClient, SMPClientError, clientHandlers, forwardSMPTransmission, netTimeoutInt, smpProxyError, temporaryClientError) +import Simplex.Messaging.Client (NetworkConfig (..), NetworkRequestMode (..), ProtocolClient (thParams), ProtocolClientConfig (..), ProtocolClientError (..), SMPClient, SMPClientError, chooseTransportHost, clientHandlers, forwardSMPTransmission, netTimeoutInt, smpProxyError, temporaryClientError) import Simplex.Messaging.Client.Agent (OwnServer, SMPClientAgent (..), SMPClientAgentConfig (..), SMPClientAgentEvent (..), closeSMPClientAgent, getSMPServerClient'', isOwnServer, lookupSMPServerClient, getConnectedSMPServerClient) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding @@ -106,7 +108,7 @@ import Simplex.Messaging.Server.Control import Simplex.Messaging.Server.Env.STM as Env import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Server.MsgStore -import Simplex.Messaging.Server.Names (NamesEnv, closeNamesEnv, resolveName) +import Simplex.Messaging.Server.Names (NameFailure (..), NamesEnv, closeNamesEnv, resolveName) import Simplex.Messaging.Server.MsgStore.STM import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.NtfStore @@ -116,6 +118,7 @@ import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.QueueStore.STM (withLoadedQueues) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore import Simplex.Messaging.Server.StoreLog (foldLogLines) import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) @@ -144,6 +147,7 @@ import GHC.Conc.Sync (threadLabel) #if defined(dbServerPostgres) import Simplex.Messaging.Server.MsgStore.Postgres (getDbMessageStats) +import qualified Simplex.Messaging.Server.QueueStore.Postgres as PQ #endif -- | Runs an SMP server using passed configuration. @@ -192,7 +196,9 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt : sigIntHandlerThread : map runServer transports <> expireMessagesThread_ cfg + <> expireClientsThread_ cfg <> serverStatsThread_ cfg + <> saveStatsThread_ cfg <> prometheusMetricsThread_ cfg <> controlPortThread_ cfg ) @@ -236,10 +242,11 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt saveServer :: Bool -> M s () saveServer drainMsgs = do + -- the database stats store is closed together with the message store + saveServerStats ms <- asks msgStore_ liftIO $ saveServerMessages drainMsgs ms >> closeMsgStore (fromMsgStore ms) saveServerNtfs - saveServerStats closeServer :: M s () closeServer = do @@ -247,14 +254,18 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt asks namesEnv >>= liftIO . mapM_ closeNamesEnv processClientSub :: - forall sub. + forall sub p. + (PartyI p, ServiceParty p) => + s -> + SParty p -> Server s -> (Server s -> ServerSubscribers s) -> (Client s -> TMap QueueId sub) -> + (Client s -> TVar Bool) -> (Client s -> TVar (Int64, IdsHash)) -> Maybe (sub -> IO ()) -> Client s -> ClientSub -> IO () - processClientSub srv srvSubscribers clientSubs clientServiceSubs unsub_ clnt sub = + processClientSub ms party srv srvSubscribers clientSubs clientServiceSubscribed clientServiceSubs unsub_ clnt sub = uninterruptibleMask_ $ atomically (updateSubscribers clnt sub) >>= endPreviousSubscriptions @@ -296,6 +307,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt cancelServiceSubs serviceId = checkAnotherClient $ \c -> do changedSubs@(n, idsHash) <- swapTVar (clientServiceSubs c) (0, mempty) + writeTVar (clientServiceSubscribed c) False pure [(c, CSADecreaseSubs changedSubs, (serviceId, ENDS n idsHash))] checkAnotherClient :: (Client s -> STM [PrevClientSub s]) -> Maybe (Client s) -> STM [PrevClientSub s] checkAnotherClient mkSub = \case @@ -305,7 +317,12 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt endPreviousSubscriptions :: [PrevClientSub s] -> IO () endPreviousSubscriptions = mapM_ $ \(c, subAction, evt) -> do - atomically $ modifyTVar' pendingEvents $ IM.alter (Just . maybe [evt] (evt <|)) (clientId c) + evt' <- case subAction of + CSADecreaseSubs _ -> do + current <- liftIO $ getServiceQueueCountHash @(StoreQueue s) (queueStore ms) party (fst evt) + pure $ either (const evt) ((fst evt,) . uncurry ENDS) current + _ -> pure evt + atomically $ modifyTVar' pendingEvents $ IM.alter (Just . maybe [evt'] (evt' <|)) (clientId c) case subAction of CSAEndSub qId -> atomically (endSub c qId) >>= unsubPrev -- like endSub, also removes the delivery subscription from the service client's subscriptions map, @@ -458,6 +475,27 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt expireMessagesThread_ ServerConfig {messageExpiration = Just msgExp} = [expireMessagesThread msgExp] expireMessagesThread_ _ = [] + expireClientsThread_ :: ServerConfig s -> [M s ()] + expireClientsThread_ ServerConfig {inactiveClientExpiration = Just expCfg} = [expireClientsThread expCfg] + expireClientsThread_ _ = [] + + expireClientsThread :: ExpirationConfig -> M s () + expireClientsThread expCfg = do + labelMyThread "expireClients" + srv <- asks server + liftIO $ forever $ do + threadDelay' $ checkInterval expCfg * 1000000 + old <- expireBeforeEpoch expCfg + getServerClients srv >>= mapM_ (expireClient srv old) + where + expireClient srv old c@Client {rcvActiveAt, sndActiveAt, closeTransport} = do + ts <- max <$> readTVarIO rcvActiveAt <*> readTVarIO sndActiveAt + when (systemSeconds ts < old) $ whenM (noSubscriptions srv c) closeTransport + noSubscriptions srv Client {clientId} = + not <$> anyM [hasSubs (subscribers srv), hasSubs (ntfSubscribers srv)] + where + hasSubs ServerSubscribers {subClients} = IS.member clientId <$> readTVarIO subClients + expireMessagesThread :: ExpirationConfig -> M s () expireMessagesThread ExpirationConfig {checkInterval, ttl} = do ms <- asks msgStore @@ -499,18 +537,34 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt [logServerStats logStatsStartTime interval serverStatsLogFile] serverStatsThread_ _ = [] + saveStatsThread_ :: ServerConfig s -> [M s ()] + saveStatsThread_ ServerConfig {serverStatsBackupFile = Just _, statsSaveInterval} = [saveStatsThread statsSaveInterval] + saveStatsThread_ _ = [] + + saveStatsThread :: Int64 -> M s () + saveStatsThread interval = do + labelMyThread "saveStatsThread" + lock <- asks $ savingLock . server + forever $ do + liftIO $ threadDelay' $ 1000000 * interval + withLock' lock "saveStats" saveServerStats + logServerStats :: Int64 -> Int64 -> FilePath -> M s () logServerStats startAt logInterval statsFilePath = do labelMyThread "logServerStats" - initialDelay <- (startAt -) . fromIntegral . (`div` 1000000_000000) . diffTimeToPicoseconds . utctDayTime <$> liftIO getCurrentTime liftIO $ putStrLn $ "server stats log enabled: " <> statsFilePath - liftIO $ threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) - ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, rcvServices, ntfServices, rslvStats} + liftIO $ delayUntilDayTime startAt + ss@ServerStats {fromTime, qCreated, qSecured, qDeletedAll, qDeletedAllB, qDeletedNew, qDeletedSecured, qSub, qSubAllB, qSubAuth, qSubDuplicate, qSubProhibited, qSubEnd, qSubEndB, ntfCreated, ntfDeleted, ntfDeletedB, ntfSub, ntfSubB, ntfSubAuth, ntfSubDuplicate, msgSent, msgSentAuth, msgSentQuota, msgSentLarge, msgRecv, msgRecvGet, msgGet, msgGetNoMsg, msgGetAuth, msgGetDuplicate, msgGetProhibited, msgExpired, activeQueues, msgSentNtf, msgRecvNtf, activeQueuesNtf, qCount, msgCount, ntfCount, pRelays, pRelaysOwn, pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, pMsgFwdsBelow23, pMsgFwdsFrom23, pMsgFwdsRecvBelow23, pMsgFwdsRecvFrom23, rcvServices, ntfServices, rslvStats} <- asks serverStats st <- asks msgStore + EntityCounts {queueCount, notifierCount, rcvServiceCount, ntfServiceCount, rcvServiceQueuesCount, ntfServiceQueuesCount} <- + liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + lock <- asks $ savingLock . server + u <- askUnliftIO let interval = 1000000 * logInterval forever $ do - handleAny (\e -> logError $ "Server stats log error: " <> tshow e) $ withFile statsFilePath AppendMode $ \h -> liftIO $ do + handleAny (\e -> logError $ "Server stats log error: " <> tshow e) $ withFile statsFilePath AppendMode $ \h -> withLock' lock "logStats" $ liftIO $ do + unliftIO u saveServerStats hSetBuffering h LineBuffering EntityCounts {queueCount, notifierCount, rcvServiceCount, ntfServiceCount, rcvServiceQueuesCount, ntfServiceQueuesCount} <- getEntityCounts @(StoreQueue s) $ queueStore st @@ -563,6 +617,10 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt pMsgFwds' <- getResetProxyStatsData pMsgFwds pMsgFwdsOwn' <- getResetProxyStatsData pMsgFwdsOwn pMsgFwdsRecv' <- atomicSwapIORef pMsgFwdsRecv 0 + pMsgFwdsBelow23' <- atomicSwapIORef pMsgFwdsBelow23 0 + pMsgFwdsFrom23' <- atomicSwapIORef pMsgFwdsFrom23 0 + pMsgFwdsRecvBelow23' <- atomicSwapIORef pMsgFwdsRecvBelow23 0 + pMsgFwdsRecvFrom23' <- atomicSwapIORef pMsgFwdsRecvFrom23 0 rcvServices' <- getServiceStatsData rcvServices ntfServices' <- getServiceStatsData ntfServices qCount' <- readIORef qCount @@ -643,15 +701,17 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt <> showServiceStats rcvServices' <> showServiceStats ntfServices' <> showNameResolverStats rslvStats' + <> map tshow [pMsgFwdsBelow23', pMsgFwdsFrom23', pMsgFwdsRecvBelow23', pMsgFwdsRecvFrom23'] ) + unliftIO u saveServerStats liftIO $ threadDelay' interval where showProxyStats ProxyStatsData {_pRequests, _pSuccesses, _pErrorsConnect, _pErrorsCompat, _pErrorsOther} = map tshow [_pRequests, _pSuccesses, _pErrorsConnect, _pErrorsCompat, _pErrorsOther] showServiceStats ServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} = map tshow [_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd] - showNameResolverStats NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = - map tshow [_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled] + showNameResolverStats NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = + map tshow [_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected] prometheusMetricsThread_ :: ServerConfig s -> [M s ()] prometheusMetricsThread_ ServerConfig {prometheusInterval = Just interval, prometheusMetricsFile} = @@ -685,7 +745,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt pure ServerMetrics {statsData = d, activeQueueCounts = ps, activeNtfCounts = psNtf, entityCounts, rtsOptions} getRealTimeMetrics :: Env s -> IO RealTimeMetrics - getRealTimeMetrics Env {sockets, msgStore_ = ms, server = srv@Server {subscribers, ntfSubscribers}} = do + getRealTimeMetrics Env {sockets, msgStore_ = ms, server = srv@Server {subscribers, ntfSubscribers}, proxyAgent = ProxyAgent {smpAgent = SMPClientAgent {smpSessions, connectingClients, persistedErrors}}} = do socketStats <- mapM (traverse getSocketStats) =<< readTVarIO sockets #if MIN_VERSION_base(4,18,0) threadsCount <- length <$> listThreads @@ -693,12 +753,15 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt let threadsCount = 0 #endif clientsCount <- IM.size <$> getServerClients srv + relaySessionsCount <- M.size <$> readTVarIO smpSessions + relayConnectingCount <- readTVarIO connectingClients + relayPersistedErrorsCount <- readTVarIO persistedErrors (deliveredSubs, deliveredTimes) <- getDeliveredMetrics =<< getSystemSeconds smpSubs <- getSubscribersMetrics subscribers ntfSubs <- getSubscribersMetrics ntfSubscribers loadedCounts <- loadedQueueCounts $ fromMsgStore ms fwdWorkerQLength <- fmap sum . mapM fwdQLength =<< getServerClients srv - pure RealTimeMetrics {socketStats, threadsCount, clientsCount, deliveredSubs, deliveredTimes, smpSubs, ntfSubs, loadedCounts, fwdWorkerQLength} + pure RealTimeMetrics {socketStats, threadsCount, clientsCount, relaySessionsCount, relayConnectingCount, relayPersistedErrorsCount, deliveredSubs, deliveredTimes, smpSubs, ntfSubs, loadedCounts, fwdWorkerQLength} where fwdQLength Client {fwdWorkers} = atomically $ readTVar fwdWorkers >>= fmap sum . mapM lengthTBQueue getSubscribersMetrics ServerSubscribers {queueSubscribers, serviceSubscribers, totalServiceSubs, subClients} = do @@ -732,10 +795,10 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt let serverInfo = LB.toStrict . J.encode <$> information labelMyThread $ "smp handshake for " <> transportName tp liftIO (timeout smpHandshakeTimeout . runExceptT $ smpServerHandshake srvCert srvSignKey h ks kh smpServerVRange serverInfo $ getClientService ms g idSize) >>= \case - Just (Right th) -> runClientTransport (processSubs srv) th + Just (Right th) -> runClientTransport (processSubs srv ms) th _ -> pure () where - processSubs srv = (processClientSub srv subscribers subscriptions serviceSubsCount (Just cancelSub), processClientSub srv ntfSubscribers ntfSubscriptions ntfServiceSubsCount Nothing) + processSubs srv ms = (processClientSub ms SRecipientService srv subscribers subscriptions serviceSubscribed serviceSubsCount (Just cancelSub), processClientSub ms SNotifierService srv ntfSubscribers ntfSubscriptions ntfServiceSubscribed ntfServiceSubsCount Nothing) getClientService :: s -> TVar ChaChaDRG -> Int -> SMPServiceRole -> X.CertificateChain -> XV.Fingerprint -> ExceptT TransportError IO ServiceId getClientService ms g idSize role cert fp = do @@ -1058,7 +1121,7 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi ts <- liftIO getSystemTime nextClientId <- asks clientSeq clientId <- atomically $ stateTVar' nextClientId $ \next -> (next, next + 1) - c <- liftIO $ newClient clientId q thParams ts + c <- liftIO $ newClient clientId q thParams ts (closeConnection $ connection h) runClientThreads c `finally` clientDisconnected c where runClientThreads :: Client s -> M s () @@ -1066,17 +1129,9 @@ runClientTransport processSubs h@THandle {params = thParams@THandleParams {sessi s <- asks server ms <- asks msgStore whenM (liftIO $ insertServerClient c s) $ do - expCfg <- asks $ inactiveClientExpiration . config - th <- newMVar h -- put TH under a fair lock to interleave messages and command responses + th <- newMVar h labelMyThread . B.unpack $ "client $" <> encode sessionId - raceAny_ $ [liftIO $ send th c, liftIO $ sendMsg th c, client processSubs s ms c, receive h ms c] <> disconnectThread_ c s expCfg - disconnectThread_ :: Client s -> Server s -> Maybe ExpirationConfig -> [M s ()] - disconnectThread_ c s (Just expCfg) = [liftIO $ disconnectTransport h (rcvActiveAt c) (sndActiveAt c) expCfg (noSubscriptions c s)] - disconnectThread_ _ _ _ = [] - noSubscriptions Client {clientId} s = - not <$> anyM [hasSubs (subscribers s), hasSubs (ntfSubscribers s)] - where - hasSubs ServerSubscribers {subClients} = IS.member clientId <$> readTVarIO subClients + raceAny_ [liftIO $ send th c, liftIO $ sendMsg th c, liftIO $ sendDelayed c, client processSubs s ms c, receive h ms c] controlPortAuth :: Handle -> Maybe BasicAuth -> Maybe BasicAuth -> TVar CPClientRole -> BasicAuth -> IO () controlPortAuth h user admin role auth = do @@ -1195,15 +1250,24 @@ sendResponses c@Client {sndQ} stats authDelay since rs@(ts, _) | otherwise = atomically $ writeTBQueue sndQ rs sendAfterDelay :: Client s -> ServerStats -> Int64 -> SystemTime -> (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]) -> IO () -sendAfterDelay c@Client {sndQ, clientTHParams = THandleParams {sessionId}} stats delay since rs +sendAfterDelay c@Client {sndQ, delayedQ, clientTHParams = THandleParams {sessionId}} stats delay since rs | delay > 0 = do elapsed <- subtract (microseconds since) . microseconds <$> getSystemTime when (elapsed >= delay) $ incStat $ authDelayExceeded stats - forkClient c (B.unpack $ "client $" <> encode sessionId <> " auth") $ threadDelay' (delay - elapsed `mod` delay) >> write + due <- registerDelay $ fromIntegral $ delay - elapsed `mod` delay + atomically $ writeTBQueue delayedQ (due, rs) | otherwise = write where write = atomically $ writeTBQueue sndQ rs +sendDelayed :: Client s -> IO () +sendDelayed Client {sndQ, delayedQ, clientTHParams = THandleParams {sessionId}} = do + labelMyThread . B.unpack $ "client $" <> encode sessionId <> " auth" + forever $ do + (due, rs) <- atomically $ readTBQueue delayedQ + atomically $ unlessM (readTVar due) retry + atomically $ writeTBQueue sndQ rs + updateSlotWaitStats :: ServerStats -> SystemTime -> Bool -> IO () updateSlotWaitStats ServerStats {cmdSlotWaits, cmdSlotWaitMs, cmdSlotWaitMaxMs, cmdSlotWaitTimeouts} since taken = do waitMs <- fromIntegral . (`div` 1000) . subtract (microseconds since) . microseconds <$> getSystemTime @@ -1410,7 +1474,7 @@ client (processSub, processNtfSub) Server {subscribers} ms - clnt@Client {rcvQ, sndQ, msgQ, clientTHParams = thParams'@THandleParams {sessionId}, procThreads, fwdWorkers} = do + clnt@Client {clientId, rcvQ, sndQ, msgQ, clientTHParams = thParams'@THandleParams {sessionId}, procThreads, fwdWorkers, fwdCorrIds} = do labelMyThread . B.unpack $ "client $" <> encode sessionId <> " commands" stats <- asks serverStats authDelay <- asks $ authErrorDelay . config @@ -1432,11 +1496,12 @@ client prepareBatchSubs clntServiceId_ batch = do let (subMsgQs, rcvAssocQs, ntfAssocQs) = foldr partitionSubs ([], [], []) batch partitionSubs t (msgQs, rcvQs, ntfQs) = case t of - (Just (q, qr), (_, _, Cmd SRecipient SUB)) - | clntServiceId_ /= rcvServiceId qr -> ((q, qr) : msgQs, q : rcvQs, ntfQs) + (Just (_, QueueRec {status = EntityBlocked _}), (_, _, Cmd SRecipient SUB)) -> (msgQs, rcvQs, ntfQs) + (Just (q, qr), (_, entId, Cmd SRecipient SUB)) + | isJust clntServiceId_ || isJust (rcvServiceId qr) -> ((q, qr) : msgQs, q : rcvQs, ntfQs) | otherwise -> ((q, qr) : msgQs, rcvQs, ntfQs) - (Just (q, qr), (_, _, Cmd SNotifier NSUB)) - | clntServiceId_ /= (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, q : ntfQs) + (Just (q, qr), (_, entId, Cmd SNotifier NSUB)) + | isJust clntServiceId_ || isJust (notifier qr >>= ntfServiceId) -> (msgQs, rcvQs, q : ntfQs) _ -> (msgQs, rcvQs, ntfQs) runExceptT $ do rcvAssocs <- ifNotNull rcvAssocQs $ setService SRecipientService clntServiceId_ @@ -1513,8 +1578,9 @@ client incSrvStat srvAssocRemoved -- getSubscription may find a subscription for receiving service, where clientSubs also hold active deliveries for service subscriptions. -- For notification service it can only find one if storage and session states diverge. - r <- getSubscription - writeSub + r@(hasSub, _) <- getSubscription + atomically $ modifyTVar' (clientServiceSubs clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) + unless hasSub writeSub pure r Nothing -> do r@(hasSub, _) <- getSubscription @@ -1532,24 +1598,29 @@ client pure $ allowSMPProxy && maybe True ((== auth) . Just) newQueueBasicAuth getRelay = do ProxyAgent {smpAgent = a} <- asks proxyAgent - liftIO (getConnectedSMPServerClient a srv) >>= \case - Just r -> Just <$> proxyServerResponse a r - Nothing -> - forkProxiedCmd $ - liftIO (runExceptT (getSMPServerClient'' a srv) `E.catches` clientHandlers) - >>= proxyServerResponse a + let ProtocolClientConfig {networkConfig, defaultTransport} = smpCfg $ agentCfg a + relaySrv h = srv {host = [h], port = if null (port srv) then fst defaultTransport else port srv} + case relaySrv <$> chooseTransportHost networkConfig (host srv) of + Left e -> Just <$> proxyServerResponse a (Left e) + Right srv' -> + liftIO (getConnectedSMPServerClient a srv') >>= \case + Just r -> Just <$> proxyServerResponse a r + Nothing -> + forkProxiedCmd $ + liftIO (runExceptT (getSMPServerClient'' a srv') `E.catches` clientHandlers) + >>= proxyServerResponse a proxyServerResponse :: SMPClientAgent 'Sender -> Either SMPClientError (OwnServer, SMPClient) -> M s BrokerMsg proxyServerResponse a smp_ = do ServerStats {pRelays, pRelaysOwn} <- asks serverStats let inc = mkIncProxyStats pRelays pRelaysOwn + own = isOwnServer a srv case smp_ of - Right (own, smp) -> do + Right (_, smp) -> do inc own pRequests case proxyResp smp of r@PKEY {} -> r <$ inc own pSuccesses r -> r <$ inc own pErrorsCompat Left e -> do - let own = isOwnServer a srv inc own pRequests inc own $ if temporaryClientError e then pErrorsConnect else pErrorsOther logWarn $ "Error connecting: " <> decodeLatin1 (strEncode $ host srv) <> " " <> tshow e @@ -1565,23 +1636,32 @@ client Nothing -> ERR $ transportErr TENoServerAuth _ -> ERR $ transportErr TEVersion PFWD fwdV pubKey encBlock -> do - ProxyAgent {smpAgent = a} <- asks proxyAgent - ServerStats {pMsgFwds, pMsgFwdsOwn} <- asks serverStats + ProxyAgent {smpAgent = a, relayForwards} <- asks proxyAgent + ServerStats {pMsgFwds, pMsgFwdsOwn, pMsgFwdsBelow23, pMsgFwdsFrom23, pMsgFwdsRelayLimit} <- asks serverStats let inc = mkIncProxyStats pMsgFwds pMsgFwdsOwn liftIO (lookupSMPServerClient a sessId) >>= \case Just (own, smp) | Right fwdCorrId <- C.corrCbNonce (bs corrId) -> do inc own pRequests - forkProxiedCmd $ do - liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case - Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses - Left e -> ERR (smpProxyError e) <$ case e of - PCEProtocolError {} -> inc own pSuccesses - _ -> inc own pErrorsOther + incStat $ if fwdV < fwdNoncesSMPVersion then pMsgFwdsBelow23 else pMsgFwdsFrom23 + maxFwds <- asks $ proxyRelayConcurrency . config + forkProxiedCmd $ + bracket (atomically $ reserve maxFwds relayForwards) (\r -> when r $ atomically $ release relayForwards) $ \case + False -> ERR (smpProxyError PCEResponseTimeout) <$ (inc own pErrorsOther >> incStat pMsgFwdsRelayLimit) + True -> + liftIO (runExceptT (forwardSMPTransmission smp fwdCorrId fwdV pubKey encBlock) `E.catches` clientHandlers) >>= \case + Right (nonce_, r) -> PRES nonce_ r <$ inc own pSuccesses + Left e -> ERR (smpProxyError e) <$ case e of + PCEProtocolError {} -> inc own pSuccesses + _ -> inc own pErrorsOther Just _ -> pure $ Just $ ERR $ CMD SYNTAX Nothing -> inc False pRequests >> inc False pErrorsConnect $> Just (ERR $ PROXY NO_SESSION) where forkProxiedCmd :: M s BrokerMsg -> M s (Maybe BrokerMsg) forkProxiedCmd = forkCmd serverClientConcurrency corrId (EntityId sessId) (ERR $ smpProxyError PCEResponseTimeout) + reserve maxFwds v = stateTVar' v $ \fwds -> case M.lookup sessId fwds of + Just n | n >= maxFwds -> (False, fwds) + n_ -> (True, M.insert sessId (maybe 1 (+ 1) n_) fwds) + release v = modifyTVar' v $ M.update (\n -> if n > 1 then Just (n - 1) else Nothing) sessId -- Run a slow command on a thread, responding with timeoutErr if it was not started before the client timeout forkCmd :: (ServerConfig s -> Int) -> CorrId -> EntityId -> BrokerMsg -> M s BrokerMsg -> M s (Maybe a) forkCmd concurrency corrId entId timeoutErr cmdAction = @@ -1636,7 +1716,8 @@ client (selector, msg) <- liftIO (resolveName nenv q) <&> \case Right res -> (if answered (registration res) then rslvSucc else rslvNotFound, RNAME res) - Left e -> (rslvResolverErrs, ERR $ NAME e) + Left (QueryRejected e) -> (rslvRejected, ERR $ NAME e) + Left (ResolverFailed e) -> (rslvResolverErrs, ERR $ NAME e) incStat (selector st) $> msg where -- below v22 the encoder answers anything but a record as NAME NOT_FOUND @@ -1681,16 +1762,17 @@ client case command of SUB -> case batchSubs >>= \(msgs, rcvAssocs, _, subs) -> sequence (M.lookup entId rcvAssocs) $> (msgs, subs) of Left e -> pure $ Just (err e, Nothing) - Right (msgs, subs) -> withQueue' $ deliverSubMsg (M.lookup entId msgs) (M.lookup entId subs) + Right (msgs, subs) -> withQueue' $ \_ -> subscribeQueueAndDeliver (M.lookup entId msgs) (fromMaybe (Left INTERNAL) $ M.lookup entId subs) GET -> withQueue getMessage ACK msgId -> withQueue $ acknowledgeMsg msgId KEY sKey -> withQueue $ \q _ -> either err (corrId,entId,) <$> secureQueue_ q sKey - RKEY rKeys -> withQueue $ \q qr -> checkMode QMContact qr $ OK <$$ liftIO (updateKeys (queueStore ms) q rKeys) + RKEY rKeys -> withQueue $ \q qr -> checkMode QMContact qr $ OK <$$ liftIO (updateKeys (queueStore ms) q (Just $ recipientKeys qr) rKeys) LSET lnkId d -> withQueue $ \q qr -> case queueData qr of _ | isSecuredMsgQueue qr -> pure $ err AUTH Just (lnkId', _) | lnkId' /= lnkId -> pure $ err AUTH -- can't change link ID _ -> liftIO $ either err (const ok) <$> addQueueLinkData (queueStore ms) q lnkId d + LSWP lnkId h ks_ d -> withQueue $ \q qr -> checkMode QMContact qr $ maybe OK LCUR <$$> liftIO (swapQueueLinkData (queueStore ms) q lnkId h ks_ d) LDEL -> withQueue $ \q qr -> case queueData qr of Just _ -> liftIO $ either err (const ok) <$> deleteQueueLinkData (queueStore ms) q @@ -1822,11 +1904,11 @@ client suspendQueue_ :: (StoreQueue s, QueueRec) -> M s (Transmission BrokerMsg) suspendQueue_ (q, _) = liftIO $ either err (const ok) <$> suspendQueue (queueStore ms) q - deliverSubMsg :: Maybe Message -> Maybe (Either ErrorType (Bool, Maybe Sub)) -> StoreQueue s -> QueueRec -> M s ResponseAndMessage - deliverSubMsg msg_ r_ _ qr = case r_ of - Just (Right r) -> deliver r - Just (Left e) -> pure (err e, Nothing) - Nothing -> pure (err INTERNAL, Nothing) + subscribeQueueAndDeliver :: Maybe Message -> Either ErrorType (Bool, Maybe Sub) -> QueueRec -> M s ResponseAndMessage + subscribeQueueAndDeliver msg_ subResult qr = + case subResult of + Left e -> pure (err e, Nothing) + Right (hasSub, sub_) -> deliver (hasSub, sub_) where deliver :: (Bool, Maybe Sub) -> M s ResponseAndMessage deliver (hasSub, sub_) = do @@ -1932,7 +2014,7 @@ client if qCnt == expectedCnt then logNote $ logMsg <> tshow qCnt <> " queues)" else logError $ logMsg <> "expected " <> tshow expectedCnt <> "," <> tshow qCnt <> " queues)" - Left e -> do + Left e -> whenM (readTVarIO $ connected clnt) $ do logError $ "Service subscription error for " <> tshow serviceId <> ": " <> tshow e atomically $ writeTBQueue msgQ [(NoCorrId, NoEntity, ERR e)] deliverQueueMsg :: (Int64, Int, Int, NonEmpty (Transmission BrokerMsg)) -> RecipientId -> Either ErrorType (Maybe (QueueRec, Message)) -> IO (Int64, Int, Int, NonEmpty (Transmission BrokerMsg)) @@ -2192,6 +2274,14 @@ client | tCorrId == C.unCbNonce fwdCorrId -> pure $ tDecodeServer clntTHParams t | otherwise -> throwE CRYPTO _ -> throwE BLOCK + when (fwdVersion < fwdNoncesSMPVersion) $ do + let fwdId = SBS.toShort $ C.unCbNonce fwdCorrId + (used, recorded) <- atomically $ stateTVar' fwdCorrIds $ \ids -> ((S.member fwdId ids, S.size ids), S.insert fwdId ids) + when used $ throwE CRYPTO + maxIds <- asks $ maxFwdCorrIds . config + when (recorded >= maxIds) $ do + logWarn $ "Closing proxy session: limit of " <> tshow maxIds <> " forwarded commands below version 23" + throwIO $ userError "too many forwarded commands below version 23" let clntThAuth = Just $ THAuthServer {serverPrivKey, peerClientService = Nothing, peerEntitlement = Nothing, sessSecret' = Just clientSecret} encodeResp r = do r' <- case batchTransmissions clntTHParams [Right (Nothing, encodeTransmission clntTHParams r)] of @@ -2239,7 +2329,12 @@ client Nothing -> pure $ Just (corrId', entId', ERR $ CMD PROHIBITED) stats <- asks serverStats incStat $ pMsgFwdsRecv stats - traverse encodeResp r_ + incStat $ (if fwdVersion < fwdNoncesSMPVersion then pMsgFwdsRecvBelow23 else pMsgFwdsRecvFrom23) stats + traverse encodeResp r_ >>= \case + Just rres | any isAuthError r_ -> do + authDelay <- asks $ authErrorDelay . config + Nothing <$ liftIO (sendAfterDelay clnt stats authDelay startedAt ([(corrId, NoEntity, rres)], [])) + rres_ -> pure rres_ where forwardWorker :: EntityId -> M s (TBQueue (M s ())) forwardWorker (EntityId eId) = do @@ -2283,7 +2378,7 @@ client -- we delete subscription here, so the client with no subscriptions can be disconnected. sub <- atomically $ TM.lookupDelete entId $ subscriptions clnt liftIO $ mapM_ cancelSub sub - when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ whenM (((0 /=) . fst) <$> readTVar (serviceSubsCount clnt)) $ do + when (isJust rcvServiceId && rcvServiceId == clntServiceId) $ atomically $ do modifyTVar' (serviceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash (recipientId q)) modifyTVar' (totalServiceSubs subscribers) $ subtractServiceSubs (1, queueIdHash (recipientId q)) liftIO $ processSub clnt $ CSDeleted entId rcvServiceId @@ -2293,6 +2388,11 @@ client stats <- asks serverStats deleted <- asks ntfStore >>= liftIO . (`deleteNtfs` nId) when (deleted > 0) $ liftIO $ atomicModifyIORef'_ (ntfCount stats) (subtract deleted) + when (isJust ntfServiceId && ntfServiceId == clntServiceId) $ do + ntfSubscribers <- asks (ntfSubscribers . server) + atomically $ do + modifyTVar' (ntfServiceSubsCount clnt) $ subtractServiceSubs (1, queueIdHash nId) + modifyTVar' (totalServiceSubs ntfSubscribers) $ subtractServiceSubs (1, queueIdHash nId) liftIO $ processNtfSub clnt $ CSDeleted nId ntfServiceId updateDeletedStats qr pure ok @@ -2518,38 +2618,39 @@ restoreServerNtfs = ntfErr :: Show e => String -> e -> String ntfErr op e = op <> " error (" <> show e <> "): " <> B.unpack (B.take 100 s) -saveServerStats :: M s () -saveServerStats = - asks (serverStatsBackupFile . config) - >>= mapM_ (\f -> asks serverStats >>= liftIO . getServerStatsData >>= liftIO . saveStats f) +serverStatsStore :: M s (Maybe StatsStore) +serverStatsStore = do + ms <- asks msgStore_ + fmap (statsStore ms) <$> asks (serverStatsBackupFile . config) where - saveStats f stats = do - logNote $ "saving server stats to file " <> T.pack f - B.writeFile f $ strEncode stats - logNote "server stats saved" + statsStore :: MsgStore s -> FilePath -> StatsStore + statsStore = \case + StoreMemory _ -> StatsFile +#if defined(dbServerPostgres) + StoreDatabase ms -> StatsDB (PQ.dbStore $ queueStore ms) +#endif + +saveServerStats :: M s () +saveServerStats = do + ss <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . (`saveStats` ss)) restoreServerStats :: forall s. MsgStoreClass s => Maybe MessageStats -> MessageStats -> M s () -restoreServerStats msgStats_ ntfStats = asks (serverStatsBackupFile . config) >>= mapM_ restoreStats +restoreServerStats msgStats_ ntfStats = do + s <- asks serverStats + serverStatsStore >>= mapM_ (liftIO . tryAny . loadStats >=> restore s) + st <- asks msgStore + EntityCounts {queueCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st + liftIO $ do + writeIORef (qCount s) queueCount + writeIORef (msgCount s) $ maybe 0 storedMsgsCount msgStats_ + writeIORef (ntfCount s) $ storedMsgsCount ntfStats + atomicModifyIORef'_ (msgExpired s) (+ maybe 0 expiredMsgsCount msgStats_) + atomicModifyIORef'_ (msgNtfExpired s) (+ expiredMsgsCount ntfStats) where - restoreStats f = whenM (doesFileExist f) $ do - logNote $ "restoring server stats from file " <> T.pack f - liftIO (strDecode <$> B.readFile f) >>= \case - Right d@ServerStatsData {_qCount = statsQCount, _msgCount = statsMsgCount, _ntfCount = statsNtfCount} -> do - s <- asks serverStats - st <- asks msgStore - EntityCounts {queueCount = _qCount} <- liftIO $ getEntityCounts @(StoreQueue s) $ queueStore st - let _msgCount = maybe statsMsgCount storedMsgsCount msgStats_ - _ntfCount = storedMsgsCount ntfStats - _msgExpired' = _msgExpired d + maybe 0 expiredMsgsCount msgStats_ - _msgNtfExpired' = _msgNtfExpired d + expiredMsgsCount ntfStats - liftIO $ setServerStats s d {_qCount, _msgCount, _ntfCount, _msgExpired = _msgExpired', _msgNtfExpired = _msgNtfExpired'} - renameFile f $ f <> ".bak" - logNote "server stats restored" - compareCounts "Queue" statsQCount _qCount - compareCounts "Message" statsMsgCount _msgCount - compareCounts "Notification" statsNtfCount _ntfCount - Left e -> do - logNote $ "error restoring server stats: " <> T.pack e - liftIO exitFailure - compareCounts name statsCnt storeCnt = - when (statsCnt /= storeCnt) $ logWarn $ name <> " count differs: stats: " <> tshow statsCnt <> ", store: " <> tshow storeCnt + restore s = \case + Right (Just d) -> liftIO (setServerStats s d) >> logNote "server stats restored" + Right Nothing -> pure () + Left e -> do + logError $ "error restoring server stats: " <> tshow e + liftIO exitFailure diff --git a/src/Simplex/Messaging/Server/Env/STM.hs b/src/Simplex/Messaging/Server/Env/STM.hs index 608efb0f5..80a760e14 100644 --- a/src/Simplex/Messaging/Server/Env/STM.hs +++ b/src/Simplex/Messaging/Server/Env/STM.hs @@ -64,13 +64,17 @@ module Simplex.Messaging.Server.Env.STM defaultMsgQueueQuota, defMsgExpirationDays, defNtfExpirationHours, + defStatsSaveInterval, defaultMessageExpiration, defaultNtfExpiration, defaultInactiveClientExpiration, defaultProxyClientConcurrency, + defaultProxyConnectConcurrency, + defaultProxyRelayConcurrency, defaultNameResolverConcurrency, defaultForwardWorkers, defaultMaxClientCmdWait, + defaultMaxFwdCorrIds, defaultAuthErrorDelayMs, readWriteQueueStore, noPostgresExitStr, @@ -86,6 +90,7 @@ import Control.Monad import Control.Monad.Reader (ReaderT) import qualified Crypto.PubKey.RSA as RSA import Crypto.Random +import Data.ByteString.Short (ShortByteString) import Data.Int (Int64) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IM @@ -96,6 +101,7 @@ import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty) import Data.Map.Strict (Map) import Data.Maybe (isJust) +import Data.Set (Set) import qualified Data.Text as T import Data.Time.Clock (getCurrentTime) import Data.Time.Clock.System (SystemTime) @@ -128,7 +134,7 @@ import Simplex.Messaging.Server.StoreLog.ReadWrite import Simplex.Messaging.SystemTime import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM -import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, THandleParams, TransportPeer (..), VersionRangeSMP) +import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, SessionId, THandleParams, TransportPeer (..), VersionRangeSMP) import Simplex.Messaging.Transport.Server import Simplex.Messaging.Util (ifM, tshow, whenM, ($>>=)) import System.Directory (doesFileExist) @@ -176,6 +182,8 @@ data ServerConfig s = ServerConfig serverStatsLogFile :: FilePath, -- | file to save and restore stats serverStatsBackupFile :: Maybe FilePath, + -- | interval to save stats, seconds + statsSaveInterval :: Int64, -- | interval and file to save prometheus metrics prometheusInterval :: Maybe Int, prometheusMetricsFile :: FilePath, @@ -197,6 +205,8 @@ data ServerConfig s = ServerConfig smpAgentCfg :: SMPClientAgentConfig, allowSMPProxy :: Bool, -- auth is the same with `newQueueBasicAuth` serverClientConcurrency :: Int, + -- | max forwarded commands awaiting a response from one destination relay + proxyRelayConcurrency :: Int, -- | max concurrent forwarded name resolutions per proxy connection, enforced in forkCmd. -- Much higher than serverClientConcurrency: forwarded RSLVs from many clients -- aggregate over a single proxy->relay connection (only servers send proxied @@ -204,6 +214,7 @@ data ServerConfig s = ServerConfig serverResolverConcurrency :: Int, serverForwardWorkers :: Int, maxClientCmdWait :: Int, + maxFwdCorrIds :: Int, -- | public-namespace resolver config; Nothing disables the names role namesConfig :: Maybe NamesConfig, -- | server public information @@ -239,6 +250,9 @@ defaultNtfExpiration = checkInterval = 3600 -- seconds, 1 hour } +defStatsSaveInterval :: Int64 +defStatsSaveInterval = 300 + defaultInactiveClientExpiration :: ExpirationConfig defaultInactiveClientExpiration = ExpirationConfig @@ -249,6 +263,12 @@ defaultInactiveClientExpiration = defaultProxyClientConcurrency :: Int defaultProxyClientConcurrency = 500 +defaultProxyConnectConcurrency :: Int +defaultProxyConnectConcurrency = 1000 + +defaultProxyRelayConcurrency :: Int +defaultProxyRelayConcurrency = 512 + defaultNameResolverConcurrency :: Int defaultNameResolverConcurrency = 5000 @@ -258,6 +278,9 @@ defaultForwardWorkers = 8 defaultMaxClientCmdWait :: Int defaultMaxClientCmdWait = 60000000 -- microseconds +defaultMaxFwdCorrIds :: Int +defaultMaxFwdCorrIds = 65536 + defaultAuthErrorDelayMs :: Int64 defaultAuthErrorDelayMs = 50 @@ -425,8 +448,10 @@ data ClientSub | CSDeleted QueueId (Maybe ServiceId) -- includes previously associated service IDs | CSService ServiceId (Int64, IdsHash) -- only send END to idividual client subs on message delivery, not of SSUB/NSSUB -newtype ProxyAgent = ProxyAgent - { smpAgent :: SMPClientAgent 'Sender +data ProxyAgent = ProxyAgent + { smpAgent :: SMPClientAgent 'Sender, + -- forwarded commands awaiting a response, per relay session + relayForwards :: TVar (Map SessionId Int) } type ClientId = Int @@ -442,15 +467,18 @@ data Client s = Client rcvQ :: TBQueue (NonEmpty (VerifiedTransmission s)), sndQ :: TBQueue (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg]), msgQ :: TBQueue (NonEmpty (Transmission BrokerMsg)), + delayedQ :: TBQueue (TVar Bool, (NonEmpty (Transmission BrokerMsg), [Transmission BrokerMsg])), procThreads :: TVar Int, fwdWorkers :: TVar (IntMap (TBQueue (M s ()))), endThreads :: TVar (IntMap (Weak ThreadId)), endThreadSeq :: TVar Int, + fwdCorrIds :: TVar (Set ShortByteString), clientTHParams :: THandleParams SMPVersion 'TServer, connected :: TVar Bool, createdAt :: SystemTime, rcvActiveAt :: TVar SystemTime, - sndActiveAt :: TVar SystemTime + sndActiveAt :: TVar SystemTime, + closeTransport :: IO () } type VerifiedTransmission s = (Maybe (StoreQueue s, QueueRec), Transmission Cmd) @@ -504,8 +532,8 @@ newServerSubscribers = do pendingEvents <- newTVarIO IM.empty pure ServerSubscribers {queueSubscribers, serviceSubscribers, totalServiceSubs, subClients, pendingEvents} -newClient :: ClientId -> Natural -> THandleParams SMPVersion 'TServer -> SystemTime -> IO (Client s) -newClient clientId qSize clientTHParams createdAt = do +newClient :: ClientId -> Natural -> THandleParams SMPVersion 'TServer -> SystemTime -> IO () -> IO (Client s) +newClient clientId qSize clientTHParams createdAt closeTransport = do subscriptions <- TM.emptyIO ntfSubscriptions <- TM.emptyIO serviceSubscribed <- newTVarIO False @@ -515,10 +543,12 @@ newClient clientId qSize clientTHParams createdAt = do rcvQ <- newTBQueueIO qSize sndQ <- newTBQueueIO qSize msgQ <- newTBQueueIO qSize + delayedQ <- newTBQueueIO qSize procThreads <- newTVarIO 0 fwdWorkers <- newTVarIO IM.empty endThreads <- newTVarIO IM.empty endThreadSeq <- newTVarIO 0 + fwdCorrIds <- newTVarIO mempty connected <- newTVarIO True rcvActiveAt <- newTVarIO createdAt sndActiveAt <- newTVarIO createdAt @@ -534,15 +564,18 @@ newClient clientId qSize clientTHParams createdAt = do rcvQ, sndQ, msgQ, + delayedQ, procThreads, fwdWorkers, endThreads, endThreadSeq, + fwdCorrIds, clientTHParams, connected, createdAt, rcvActiveAt, - sndActiveAt + sndActiveAt, + closeTransport } newSubscription :: SubscriptionThread -> STM Sub @@ -557,7 +590,7 @@ newProhibitedSub = do return Sub {subThread = ProhibitSub, delivered} newEnv :: ServerConfig s -> IO (Env s) -newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes} = do +newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smpAgentCfg, information, messageExpiration, msgQueueQuota, namesConfig, msgIdBytes, serverStatsBackupFile} = do when (msgIdBytes < 24) $ do logError "Error: msgIdBytes must be at least 24" exitFailure @@ -585,7 +618,7 @@ newEnv config@ServerConfig {smpCredentials, httpCredentials, serverStoreCfg, smp newReloadableCredential checkHTTPSCredentials creds cred Fingerprint fp <- loadFingerprint smpCredentials let serverIdentity = KeyHash fp - serverStats <- newServerStats =<< getCurrentTime + serverStats <- newServerStats (isJust serverStatsBackupFile && isJust (dbStoreCfg serverStoreCfg)) =<< getCurrentTime sockets <- newTVarIO [] clientSeq <- newTVarIO 0 proxyAgent <- newSMPProxyAgent smpAgentCfg random @@ -692,7 +725,8 @@ noPostgresExitStr = newSMPProxyAgent :: SMPClientAgentConfig -> TVar ChaChaDRG -> IO ProxyAgent newSMPProxyAgent smpAgentCfg random = do smpAgent <- newSMPClientAgent SSender smpAgentCfg Nothing random - pure ProxyAgent {smpAgent} + relayForwards <- newTVarIO mempty + pure ProxyAgent {smpAgent, relayForwards} readWriteQueueStore :: forall q. StoreQueueClass q => Bool -> (RecipientId -> QueueRec -> IO q) -> FilePath -> STMQueueStore q -> IO (StoreLog 'WriteMode) readWriteQueueStore tty mkQ = readWriteStoreLog (readQueueStore tty mkQ) (writeQueueStore @q) diff --git a/src/Simplex/Messaging/Server/Information.hs b/src/Simplex/Messaging/Server/Information.hs index 2f1f046e7..11057063b 100644 --- a/src/Simplex/Messaging/Server/Information.hs +++ b/src/Simplex/Messaging/Server/Information.hs @@ -10,6 +10,8 @@ module Simplex.Messaging.Server.Information ( ServerInformation (..), ServerPublicConfig (..), ServerPublicInfo (..), + ClientSupport (..), + MinClientVersion (..), ServerPersistenceMode (..), ServerConditions (..), HostingType (..), @@ -26,6 +28,8 @@ import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Int (Int64) import Data.Maybe (isJust) import Data.Text (Text) +import Data.Time.Calendar (Day) +import Data.Word (Word16) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (defaultJSON, dropPrefix, enumJSON) @@ -55,7 +59,8 @@ data ServerPublicInfo = ServerPublicInfo complaintsContacts :: Maybe ServerContactAddress, hosting :: Maybe Entity, hostingType :: Maybe HostingType, - serverCountry :: Maybe Text + serverCountry :: Maybe Text, + clientSupport :: Maybe ClientSupport } deriving (Show) @@ -70,12 +75,13 @@ emptyServerInfo sourceCode = complaintsContacts = Nothing, hosting = Nothing, hostingType = Nothing, - serverCountry = Nothing + serverCountry = Nothing, + clientSupport = Nothing } hasServerInfo :: ServerPublicInfo -> Bool -hasServerInfo ServerPublicInfo {usageConditions, operator, website, adminContacts, complaintsContacts, hosting, hostingType, serverCountry} = - isJust usageConditions || isJust operator || isJust website || isJust adminContacts || isJust complaintsContacts || isJust hosting || isJust hostingType || isJust serverCountry +hasServerInfo ServerPublicInfo {usageConditions, operator, website, adminContacts, complaintsContacts, hosting, hostingType, serverCountry, clientSupport} = + isJust usageConditions || isJust operator || isJust website || isJust adminContacts || isJust complaintsContacts || isJust hosting || isJust hostingType || isJust serverCountry || isJust clientSupport data ServerPersistenceMode = SPMMemoryOnly | SPMQueues | SPMMessages deriving (Show) @@ -120,6 +126,16 @@ data ServerContactAddress = ServerContactAddress data PGPKey = PGPKey {pkURI :: Text, pkFingerprint :: Text} deriving (Show) +data ClientSupport = ClientSupport + { minClientVersion :: Maybe MinClientVersion, + stableRelease :: Maybe Text, + betaRelease :: Maybe Text + } + deriving (Eq, Show) + +data MinClientVersion = MinClientVersion {protocolVersion :: Word16, fromDate :: Day} + deriving (Eq, Show) + $(J.deriveJSON (enumJSON $ dropPrefix "SPM") ''ServerPersistenceMode) $(J.deriveJSON defaultJSON ''ServerConditions) @@ -132,6 +148,10 @@ $(J.deriveJSON defaultJSON ''ServerContactAddress) $(J.deriveJSON defaultJSON ''ServerPublicConfig) +$(J.deriveJSON defaultJSON ''MinClientVersion) + +$(J.deriveJSON defaultJSON ''ClientSupport) + $(J.deriveJSON defaultJSON ''ServerPublicInfo) $(J.deriveJSON defaultJSON ''ServerInformation) diff --git a/src/Simplex/Messaging/Server/Main.hs b/src/Simplex/Messaging/Server/Main.hs index 7c68ab836..ba7506ef9 100644 --- a/src/Simplex/Messaging/Server/Main.hs +++ b/src/Simplex/Messaging/Server/Main.hs @@ -56,6 +56,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1, encodeUtf8) import qualified Data.Text.IO as T +import Data.Time.Format.ISO8601 (iso8601ParseM) import Options.Applicative import Simplex.Messaging.Agent.Protocol (ConnectionLink (..), ConnectionMode (..), connReqUriP') import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) @@ -340,7 +341,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = s -> case strDecode $ encodeUtf8 $ T.pack s of Right auth -> pure . Just $ ServerPassword auth - _ -> putStrLn "Invalid password. Only latin letters, digits and symbols other than '@' and ':' are allowed" >> serverPassword + _ -> putStrLn "Invalid password. Passwords can contain printable ASCII characters except whitespace, '@', ':' and '/'" >> serverPassword checkInitOptions InitOptions {sourceCode, serverInfo, operatorCountry, hostingCountry} = do let err_ | isNothing sourceCode && hasServerInfo serverInfo = @@ -440,6 +441,9 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = transports = iniTransports ini sharedHTTP = any (\(_, _, addHTTP) -> addHTTP) transports iniStoreType = either error id $! readStoreType ini + iniStatsSaveInterval = case readIniDefault defStatsSaveInterval "STORE_LOG" "stats_save_interval" ini of + n | n < 1 -> error $ "invalid INI setting stats_save_interval: " <> show n + n -> n iniStoreCfg :: SupportedStore qs ms => SQSType qs -> SMSType ms -> ServerStoreCfg (MsgStoreType qs ms) iniStoreCfg SQSMemory SMSMemory = SSCMemory $ enableStoreLog' ini $> StorePaths {storeLogFile = storeLogFilePath, storeMsgsFile = restoreMessagesFile storeMsgsFilePath} #if defined(dbServerPostgres) @@ -495,6 +499,7 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = logStatsStartTime = 0, -- seconds from 00:00 UTC serverStatsLogFile = combine logPath "smp-server-stats.daily.log", serverStatsBackupFile = logStats $> combine logPath "smp-server-stats.log", + statsSaveInterval = iniStatsSaveInterval, prometheusInterval = eitherToMaybe (lookupValue "STORE_LOG" "prometheus_interval" ini) >>= readMaybe . T.unpack, prometheusMetricsFile = combine logPath "smp-server-metrics.txt", pendingENDInterval = 15000000, -- 15 seconds @@ -525,14 +530,18 @@ smpServerCLI_ generateSite serveStaticFiles attachStaticFiles cfgPath logPath = } }, ownServerDomains = either (const []) textToOwnServers $ lookupValue "PROXY" "own_server_domains" ini, + maxConnectingClients = Just $ readIniDefault defaultProxyConnectConcurrency "PROXY" "connect_concurrency" ini, + sessionPerConnectedServer = True, msgQSize = Nothing, -- to prevent accumulation of late responses, and deadlocks in SMP proxy persistErrorInterval = 30 -- seconds }, allowSMPProxy = True, serverClientConcurrency = readIniDefault defaultProxyClientConcurrency "PROXY" "client_concurrency" ini, + proxyRelayConcurrency = readIniDefault defaultProxyRelayConcurrency "PROXY" "relay_concurrency" ini, serverResolverConcurrency = readIniDefault defaultNameResolverConcurrency "NAMES" "resolver_concurrency" ini, serverForwardWorkers = readIniDefault defaultForwardWorkers "PROXY" "forward_workers" ini, maxClientCmdWait = defaultMaxClientCmdWait, + maxFwdCorrIds = defaultMaxFwdCorrIds, namesConfig = readNamesConfig ini, information = serverPublicInfo ini, startOptions @@ -691,9 +700,18 @@ serverPublicInfo ini = serverInfo <$!> infoValue "source_code" adminContacts = iniContacts "admin_simplex" "admin_email" "admin_pgp" "admin_pgp_fingerprint", complaintsContacts = iniContacts "complaints_simplex" "complaints_email" "complaints_pgp" "complaints_pgp_fingerprint", hosting = iniEntity "hosting" "hosting_country", - hostingType = either error id <$!> strDecodeIni "INFORMATION" "hosting_type" ini + hostingType = either error id <$!> strDecodeIni "INFORMATION" "hosting_type" ini, + clientSupport = iniClientSupport } infoValue name = eitherToMaybe $ lookupValue "INFORMATION" name ini + iniClientSupport = + let minClientVersion = MinClientVersion <$> (either error id <$!> strDecodeIni "INFORMATION" "client_min_version" ini) <*> (dateValue <$!> infoValue "client_min_version_date") + stableRelease = infoValue "client_stable_release" + betaRelease = infoValue "client_beta_release" + in case (minClientVersion, stableRelease, betaRelease) of + (Nothing, Nothing, Nothing) -> Nothing + _ -> Just ClientSupport {minClientVersion, stableRelease, betaRelease} + dateValue = fromMaybe (error "Use YYYY-MM-DD for client_min_version_date") . iso8601ParseM . T.unpack iniEntity nameField countryField = (\name -> Entity {name, country = countryValue countryField}) <$!> infoValue nameField @@ -948,7 +966,8 @@ cliCommandP cfgPath logPath iniFile = complaintsContacts = Nothing, hosting = fst hosting_, hostingType, - serverCountry + serverCountry, + clientSupport = Nothing }, operatorCountry = snd operator_, hostingCountry = snd hosting_, diff --git a/src/Simplex/Messaging/Server/Main/Init.hs b/src/Simplex/Messaging/Server/Main/Init.hs index 7762ec609..4893429b4 100644 --- a/src/Simplex/Messaging/Server/Main/Init.hs +++ b/src/Simplex/Messaging/Server/Main/Init.hs @@ -83,7 +83,7 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> ("enable = " <> onOff enableStoreLog <> "\n\n") <> "# Queue storage mode: `memory` or `database` (to store queue records in PostgreSQL database).\n\ \# `memory` - in-memory persistence, with optional append-only log (`enable = on`).\n\ - \# `database`- PostgreSQL databass (requires `store_messages = database`).\n\ + \# `database`- PostgreSQL database (requires `store_messages = database`).\n\ \store_queues = memory\n\n\ \# Database connection settings for PostgreSQL database (`store_queues = database`).\n" <> iniDbOpts dbOptions defaultDBOpts @@ -104,8 +104,10 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = <> "# Log daily server statistics to CSV file\n" <> ("log_stats = " <> onOff logStats <> "\n\n") <> "# Log interval for real-time Prometheus metrics\n\ - \# prometheus_interval = 60\n\n\ - \[AUTH]\n\ + \# prometheus_interval = 60\n\n" + <> "# Interval to save server statistics, seconds (requires log_stats)\n" + <> ("# stats_save_interval = " <> tshow defStatsSaveInterval <> "\n\n") + <> "[AUTH]\n\ \# Set new_queues option to off to completely prohibit creating new messaging queues.\n\ \# This can be useful when you want to decommission the server, but not all connections are switched yet.\n\ \new_queues = on\n\n\ @@ -160,6 +162,12 @@ iniFileContent cfgPath logPath opts host basicAuth controlPortPwds = \# Number of workers processing messages that one proxy server forwards to this server.\n\ \# Messages to one queue are processed by one worker, in the order they are received.\n" <> ("# forward_workers = " <> tshow defaultForwardWorkers) + <> "\n\n\ + \# Limit number of connections to destination servers being established at once.\n" + <> ("# connect_concurrency = " <> tshow defaultProxyConnectConcurrency) + <> "\n\n\ + \# Limit number of messages forwarded to one destination server and awaiting its response.\n" + <> ("# relay_concurrency = " <> tshow defaultProxyRelayConcurrency) <> "\n\n\ \[NAMES]\n\ \# Public-namespace resolution via the snrc-resolve.py REST resolver.\n\ @@ -242,6 +250,13 @@ informationIniContent InitOptions {sourceCode, serverInfo} = <> "\n\ \# Hosting type can be `virtual`, `dedicated`, `colocation`, `owned`\n" <> ("hosting_type = " <> maybe "virtual" (decodeLatin1 . strEncode) hostingType <> "\n\n") + <> "# Client support announced to the apps.\n\ + \# Clients with protocol version below client_min_version are not supported from client_min_version_date.\n\ + \# client_min_version = 23\n\ + \# client_min_version_date = YYYY-MM-DD\n\ + \# The latest app releases.\n\ + \# client_stable_release = 7.1.2\n\ + \# client_beta_release = 7.2.0-beta.1\n\n" where ServerPublicInfo {operator, website, hosting, hostingType, serverCountry} = serverInfo countryStr optName country = optDisabled country <> optName <> "_country = " <> fromMaybe "ISO-3166 2-letter code" country <> "\n" diff --git a/src/Simplex/Messaging/Server/MsgStore/Postgres.hs b/src/Simplex/Messaging/Server/MsgStore/Postgres.hs index 1b91b698e..201590513 100644 --- a/src/Simplex/Messaging/Server/MsgStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/MsgStore/Postgres.hs @@ -29,6 +29,7 @@ where import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad +import Control.Monad.IO.Class import Control.Monad.Trans.Except import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB @@ -109,9 +110,13 @@ instance MsgStoreClass PostgresMsgStore where foldRcvServiceMessages :: PostgresMsgStore -> ServiceId -> (a -> RecipientId -> Either ErrorType (Maybe (QueueRec, Message)) -> IO a) -> a -> IO (Either ErrorType a) foldRcvServiceMessages ms serviceId f acc = - runExceptT $ withDB' "foldRcvServiceMessages" (queueStore_ ms) $ \db -> - DB.fold - db + runExceptT $ foldPages NoEntity acc + where + foldPages afterId a = do + rows <- withDB' "foldRcvServiceMessages" (queueStore_ ms) $ \db -> DB.query db query (serviceId, afterId, pageSize) + (lastId, a') <- liftIO $ foldM f' (afterId, a) rows + if length rows < pageSize then pure a' else foldPages lastId a' + query = [sql| SELECT q.recipient_id, q.recipient_keys, q.rcv_dh_secret, q.sender_id, q.sender_key, q.queue_mode, @@ -126,16 +131,15 @@ instance MsgStoreClass PostgresMsgStore where ORDER BY message_id ASC LIMIT 1 ) m ON true - WHERE q.rcv_service_id = ? AND q.deleted_at IS NULL; + WHERE q.rcv_service_id = ? AND q.deleted_at IS NULL AND q.recipient_id > ? + ORDER BY q.recipient_id ASC + LIMIT ?; |] - (Only serviceId) - acc - f' - where - f' a (qRow :. mRow) = + f' (_, a) (qRow :. mRow) = let (rId, qr) = rowToQueueRec qRow msg_ = toMaybeMessage mRow - in f a rId $ Right ((qr,) <$> msg_) + in (rId,) <$> f a rId (Right ((qr,) <$> msg_)) + pageSize = 100 :: Int queueStore = queueStore_ {-# INLINE queueStore #-} diff --git a/src/Simplex/Messaging/Server/Names.hs b/src/Simplex/Messaging/Server/Names.hs index 601519c56..2cac91349 100644 --- a/src/Simplex/Messaging/Server/Names.hs +++ b/src/Simplex/Messaging/Server/Names.hs @@ -8,6 +8,7 @@ module Simplex.Messaging.Server.Names ( NamesConfig (..), RpcAuth (..), NamesEnv (..), + NameFailure (..), newNamesEnv, closeNamesEnv, pingEndpoint, @@ -59,25 +60,35 @@ pingEndpoint :: NamesEnv -> IO (Either ResolverError ()) pingEndpoint NamesEnv {resolverEnv, config} = fromMaybe (Left ResolverTimeout) <$> timeout (resolverTimeoutMs config * 1000) (healthHttp resolverEnv) -resolveName :: NamesEnv -> NameQuery -> IO (Either NameErrorType NameResponse) +data NameFailure + = QueryRejected NameErrorType + | ResolverFailed NameErrorType + deriving (Eq, Show) + +resolveName :: NamesEnv -> NameQuery -> IO (Either NameFailure NameResponse) resolveName env q = do r <- E.try (timeout (resolverTimeoutMs (config env) * 1000) (fetch env q)) case r of - Right result -> pure (fromMaybe (Left (RESOLVER "timeout")) result) + Right result -> pure (fromMaybe (Left (ResolverFailed (RESOLVER "timeout"))) result) Left e | Just (_ :: E.SomeAsyncException) <- E.fromException e -> E.throwIO e | otherwise -> do logError $ "[NAMES] resolver fetch raised " <> T.pack (E.displayException e) - pure (Left (RESOLVER "resolver error")) + pure (Left (ResolverFailed (RESOLVER "resolver error"))) -fetch :: NamesEnv -> NameQuery -> IO (Either NameErrorType NameResponse) +fetch :: NamesEnv -> NameQuery -> IO (Either NameFailure NameResponse) fetch NamesEnv {resolverEnv} q = first mapResolverError <$> resolveHttp resolverEnv (decodeLatin1 $ smpEncode q) -mapResolverError :: ResolverError -> NameErrorType +mapResolverError :: ResolverError -> NameFailure mapResolverError = \case - HttpStatusErr code -> RESOLVER ("HTTP " <> T.pack (show code)) - HttpFailure _ -> RESOLVER "transport failure" - BodyTooLarge -> RESOLVER "response too large" - InvalidJson _ -> RESOLVER "invalid response" - ResolverTimeout -> RESOLVER "timeout" + HttpStatusErr code (Just c) | c `elem` queryErrors -> QueryRejected (httpErr code) + HttpStatusErr code _ -> ResolverFailed (httpErr code) + HttpFailure _ -> ResolverFailed $ RESOLVER "transport failure" + BodyTooLarge -> ResolverFailed $ RESOLVER "response too large" + InvalidJson _ -> ResolverFailed $ RESOLVER "invalid response" + ResolverTimeout -> ResolverFailed $ RESOLVER "timeout" + where + httpErr code = RESOLVER ("HTTP " <> T.pack (show code)) + -- error codes of /v2/resolve listed in scripts/resolver/README.md + queryErrors = ["tldNotConfigured", "notFullyQualified", "labelNotRecorded", "noPriceOracle"] diff --git a/src/Simplex/Messaging/Server/Names/HttpResolver.hs b/src/Simplex/Messaging/Server/Names/HttpResolver.hs index b1620447b..73c6db1e7 100644 --- a/src/Simplex/Messaging/Server/Names/HttpResolver.hs +++ b/src/Simplex/Messaging/Server/Names/HttpResolver.hs @@ -9,8 +9,8 @@ -- The Python REST resolver (see scripts/resolver/snrc-resolve.py) exposes -- -- GET /v2/resolve/ -> 200 with a NameRegistration JSON document, for --- all three registration shapes; 400 for unknown --- TLDs, 502 for upstream RPC failures +-- all three registration shapes; 400 or 502 with +-- a fixed `error` code in the body -- GET /v1/resolve/ -> 200 with a NameRecord, what relays before SMP -- v22 call as /resolve -- GET /health -> 200 when the resolver process is ready @@ -34,7 +34,9 @@ module Simplex.Messaging.Server.Names.HttpResolver where import qualified Control.Exception as E +import Control.Monad ((<=<)) import qualified Data.Aeson as J +import qualified Data.Aeson.Types as JT import Data.Bifunctor (first) import qualified Data.ByteArray.Encoding as BAE import Data.ByteString.Char8 (ByteString) @@ -79,7 +81,7 @@ data ResolverEnv = ResolverEnv data ResolverError = HttpFailure HttpException - | HttpStatusErr Int + | HttpStatusErr Int (Maybe Text) | BodyTooLarge | InvalidJson String | ResolverTimeout @@ -137,7 +139,7 @@ httpGet ResolverEnv {manager, baseUrl, authHdr, timeoutMicro, maxResponseBytes} result <- E.try $ withResponse req manager $ \res -> do let status = HT.statusCode (responseStatus res) if status >= 400 - then pure (Left (HttpStatusErr status)) + then Left . HttpStatusErr status . errorCode <$> brReadSome (responseBody res) maxResponseBytes else do bs <- brReadSome (responseBody res) (maxResponseBytes + 1) pure $ if BL.length bs > fromIntegral maxResponseBytes then Left BodyTooLarge else Right bs @@ -146,3 +148,4 @@ httpGet ResolverEnv {manager, baseUrl, authHdr, timeoutMicro, maxResponseBytes} httpError = \case HC.HttpExceptionRequest _ HC.ResponseTimeout -> ResolverTimeout e -> HttpFailure e + errorCode = JT.parseMaybe (J..: "error") <=< J.decode diff --git a/src/Simplex/Messaging/Server/Prometheus.hs b/src/Simplex/Messaging/Server/Prometheus.hs index d0c8f4480..945f864d2 100644 --- a/src/Simplex/Messaging/Server/Prometheus.hs +++ b/src/Simplex/Messaging/Server/Prometheus.hs @@ -43,6 +43,9 @@ data RealTimeMetrics = RealTimeMetrics { socketStats :: [(ServiceName, SocketStats)], threadsCount :: Int, clientsCount :: Int, + relaySessionsCount :: Int, + relayConnectingCount :: Int, + relayPersistedErrorsCount :: Int, deliveredSubs :: RTSubscriberMetrics, deliveredTimes :: TimeBuckets, smpSubs :: RTSubscriberMetrics, @@ -68,6 +71,9 @@ prometheusMetrics sm rtm ts = { socketStats, threadsCount, clientsCount, + relaySessionsCount, + relayConnectingCount, + relayPersistedErrorsCount, deliveredSubs, deliveredTimes, smpSubs, @@ -125,6 +131,11 @@ prometheusMetrics sm rtm ts = _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, _rcvServices, _ntfServices, _rcvServicesSubMsg, @@ -384,6 +395,11 @@ prometheusMetrics sm rtm ts = \simplex_smp_relay_messages_requests{source=\"all\"} " <> mshow (_pRequests _pMsgFwds) <> "\n# pMsgFwds_pRequests\n\ \simplex_smp_relay_messages_requests{source=\"own\"} " <> mshow (_pRequests _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pRequests\n\ \\n\ + \# HELP simplex_smp_relay_messages_requests_version Message requests sent through relay, by forwarded command version.\n\ + \# TYPE simplex_smp_relay_messages_requests_version counter\n\ + \simplex_smp_relay_messages_requests_version{version=\"below_23\"} " <> mshow _pMsgFwdsBelow23 <> "\n# pMsgFwdsBelow23\n\ + \simplex_smp_relay_messages_requests_version{version=\"from_23\"} " <> mshow _pMsgFwdsFrom23 <> "\n# pMsgFwdsFrom23\n\ + \\n\ \# HELP simplex_smp_relay_messages_successes Successful messages sent through relay.\n\ \# TYPE simplex_smp_relay_messages_successes counter\n\ \simplex_smp_relay_messages_successes{source=\"all\"} " <> mshow (_pSuccesses _pMsgFwds) <> "\n# pMsgFwds_pSuccesses\n\ @@ -398,6 +414,10 @@ prometheusMetrics sm rtm ts = \simplex_smp_relay_messages_errors{source=\"own\",type=\"compat\"} " <> mshow (_pErrorsCompat _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pErrorsCompat\n\ \simplex_smp_relay_messages_errors{source=\"own\",type=\"other\"} " <> mshow (_pErrorsOther _pMsgFwdsOwn) <> "\n# pMsgFwdsOwn_pErrorsOther\n\ \\n\ + \# HELP simplex_smp_relay_messages_concurrency_limit Messages not sent through relay, as the limit of messages in flight to relay was reached.\n\ + \# TYPE simplex_smp_relay_messages_concurrency_limit counter\n\ + \simplex_smp_relay_messages_concurrency_limit " <> mshow _pMsgFwdsRelayLimit <> "\n# pMsgFwdsRelayLimit\n\ + \\n\ \# HELP simplex_smp_relay_messages_received Relay messages statistics.\n\ \# TYPE simplex_smp_relay_messages_received counter\n\ \simplex_smp_relay_messages_received " <> mshow _pMsgFwdsRecv <> "\n# pMsgFwdsRecv\n\ @@ -414,6 +434,21 @@ prometheusMetrics sm rtm ts = \# HELP simplex_smp_forward_worker_queue_length Forwarded commands waiting in forward worker queues.\n\ \# TYPE simplex_smp_forward_worker_queue_length gauge\n\ \simplex_smp_forward_worker_queue_length " <> mshow fwdWorkerQLength <> "\n# fwdWorkerQLength\n\ + \# HELP simplex_smp_relay_messages_received_version Messages received from proxies, by forwarded command version.\n\ + \# TYPE simplex_smp_relay_messages_received_version counter\n\ + \simplex_smp_relay_messages_received_version{version=\"below_23\"} " <> mshow _pMsgFwdsRecvBelow23 <> "\n# pMsgFwdsRecvBelow23\n\ + \simplex_smp_relay_messages_received_version{version=\"from_23\"} " <> mshow _pMsgFwdsRecvFrom23 <> "\n# pMsgFwdsRecvFrom23\n\ + \# HELP simplex_smp_relay_sessions_total Relay sessions of SMP proxy.\n\ + \# TYPE simplex_smp_relay_sessions_total gauge\n\ + \simplex_smp_relay_sessions_total " <> mshow relaySessionsCount <> "\n# relaySessionsCount\n\ + \\n\ + \# HELP simplex_smp_relay_connecting_total Relay connections being established by SMP proxy.\n\ + \# TYPE simplex_smp_relay_connecting_total gauge\n\ + \simplex_smp_relay_connecting_total " <> mshow relayConnectingCount <> "\n# relayConnectingCount\n\ + \\n\ + \# HELP simplex_smp_relay_persisted_errors_total Relay connection errors persisted by SMP proxy.\n\ + \# TYPE simplex_smp_relay_persisted_errors_total gauge\n\ + \simplex_smp_relay_persisted_errors_total " <> mshow relayPersistedErrorsCount <> "\n# relayPersistedErrorsCount\n\ \\n" services = "# Services\n\ @@ -502,7 +537,7 @@ prometheusMetrics sm rtm ts = \simplex_smp_" <> pfx <> "_services_sub_fewer_total " <> mshow (_srvSubFewerTotal ss) <> "\n# " <> pfx <> ".srvSubFewerTotal\n\ \\n" names = - let NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = _rslvStats + let NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = _rslvStats in "# Names\n\ \# -----\n\ \\n\ @@ -518,10 +553,14 @@ prometheusMetrics sm rtm ts = \# TYPE simplex_smp_names_not_found counter\n\ \simplex_smp_names_not_found " <> mshow _rslvNotFound <> "\n# rslvNotFound\n\ \\n\ - \# HELP simplex_smp_names_resolver_errs Resolver backend errors (HTTP 5xx, transport, decode, or timeout).\n\ + \# HELP simplex_smp_names_resolver_errs Failures of the resolver or its chain RPC: upstream errors, transport, decode, or timeout.\n\ \# TYPE simplex_smp_names_resolver_errs counter\n\ \simplex_smp_names_resolver_errs " <> mshow _rslvResolverErrs <> "\n# rslvResolverErrs\n\ \\n\ + \# HELP simplex_smp_names_rejected Lookups the resolver rejected: TLD not configured, name not fully qualified, label not recorded, or no price oracle.\n\ + \# TYPE simplex_smp_names_rejected counter\n\ + \simplex_smp_names_rejected " <> mshow _rslvRejected <> "\n# rslvRejected\n\ + \\n\ \# HELP simplex_smp_names_disabled RSLV requests rejected because no resolver is configured (names role off).\n\ \# TYPE simplex_smp_names_disabled counter\n\ \simplex_smp_names_disabled " <> mshow _rslvDisabled <> "\n# rslvDisabled\n\ diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs index 9c6e8d84a..a91cec889 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres.hs @@ -217,7 +217,31 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where atomically $ writeTVar (queueRec sq) $ Just q {queueData = Just (lnkId, d)} withLog "addQueueLinkData" st $ \s -> logCreateLink s rId lnkId d -- the sender key condition is checked in SQL because without cache each command reads its own copy of the queue record - qry = "UPDATE msg_queues SET fixed_data = ?, user_data = ?, link_id = ? WHERE recipient_id = ? AND deleted_at IS NULL AND (sender_key IS NULL OR queue_mode = ?)" + qry = "UPDATE msg_queues SET fixed_data = ?, user_data = ?, link_id = ? WHERE recipient_id = ? AND deleted_at IS NULL AND (sender_key IS NULL OR queue_mode = ?) AND get_byte(recipient_keys, 0) = 1" + + swapQueueLinkData :: PostgresQueueStore q -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) + swapQueueLinkData st sq lnkId h rKeys_ d = + withQueueRec sq $ \q -> + withDB "swapQueueLinkData" st swap >>= \case + Just ud -> pure $ Just ud + Nothing -> do + let !q' = q {recipientKeys = fromMaybe (recipientKeys q) rKeys_, queueData = Just (lnkId, d)} + atomically $ writeTVar (queueRec sq) $ Just q' + withLog "swapQueueLinkData" st $ \s -> logSwapLink s rId lnkId d rKeys_ + pure Nothing + where + rId = recipientId sq + swap db = + firstRow id AUTH (DB.query db "SELECT link_id, fixed_data, user_data FROM msg_queues WHERE recipient_id = ? AND deleted_at IS NULL FOR UPDATE" (Only rId)) + $>>= \case + (Just lnkId', Just fd', Just ud') + | lnkId' /= lnkId || fd' /= fst d -> pure $ Left AUTH + | linkDataHash ud' /= h -> pure $ Right $ Just ud' + | otherwise -> Right Nothing <$ updateLink db + _ -> pure $ Left AUTH + updateLink db = case rKeys_ of + Just rKeys -> DB.execute db "UPDATE msg_queues SET user_data = ?, recipient_keys = ? WHERE recipient_id = ?" (snd d, rKeys, rId) + Nothing -> DB.execute db "UPDATE msg_queues SET user_data = ? WHERE recipient_id = ?" (snd d, rId) deleteQueueLinkData :: PostgresQueueStore q -> q -> IO (Either ErrorType ()) deleteQueueLinkData st sq = @@ -245,11 +269,12 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where Just k | sKey /= k -> throwE AUTH _ -> pure () - updateKeys :: PostgresQueueStore q -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) - updateKeys st sq rKeys = + updateKeys :: PostgresQueueStore q -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys st sq prevKeys_ rKeys = withQueueRec sq $ \q -> do - assertUpdated $ withDB' "updateKeys" st $ \db -> - DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL" (rKeys, rId) + assertUpdated $ withDB' "updateKeys" st $ \db -> case prevKeys_ of + Just prevKeys -> DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL AND recipient_keys = ?" (rKeys, rId, prevKeys) + Nothing -> DB.execute db "UPDATE msg_queues SET recipient_keys = ? WHERE recipient_id = ? AND deleted_at IS NULL" (rKeys, rId) atomically $ writeTVar (queueRec sq) $ Just q {recipientKeys = rKeys} withLog "updateKeys" st $ \s -> logUpdateKeys s rId rKeys where @@ -384,12 +409,21 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where map fromOnly <$> DB.query db updateQuery (serviceId, In (map recipientId qs))) results <- liftIO $ forM qs $ \sq -> do let rId = recipientId sq - (rId,) <$> if S.member rId updated - then readQueueRecIO (queueRec sq) $>>= \q -> do + let updateRec q = + case party of + SRecipientService -> q {rcvServiceId = serviceId} + SNotifierService -> case notifier q of + Just nc -> q {notifier = Just nc {ntfServiceId = serviceId}} + Nothing -> q + (rId,) <$> (if S.member rId updated + then readQueueRecIO (queueRec sq) $>>= (\q -> do + let prevSrvId = case party of + SRecipientService -> rcvServiceId q + SNotifierService -> notifier q >>= ntfServiceId atomically $ writeTVar (queueRec sq) $ Just $ updateRec q - withLog "setQueueServices" st $ \sl -> logQueueService sl rId party serviceId - pure $ Right () - else pure $ Left AUTH + when (prevSrvId /= serviceId) $ withLog "setQueueServices" st $ \sl -> logQueueService sl (recipientId sq) party serviceId + pure $ Right ()) + else pure $ Left AUTH) pure $ M.fromList results where updateQuery = case party of @@ -397,11 +431,6 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where "UPDATE msg_queues SET rcv_service_id = ? WHERE recipient_id IN ? AND deleted_at IS NULL RETURNING recipient_id" SNotifierService -> "UPDATE msg_queues SET ntf_service_id = ? WHERE recipient_id IN ? AND notifier_id IS NOT NULL AND deleted_at IS NULL RETURNING recipient_id" - updateRec q = case party of - SRecipientService -> q {rcvServiceId = serviceId} - SNotifierService -> case notifier q of - Just nc -> q {notifier = Just nc {ntfServiceId = serviceId}} - Nothing -> q getQueueNtfServices :: PostgresQueueStore q -> [(NotifierId, a)] -> IO (Either ErrorType ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)])) getQueueNtfServices st ntfs = E.uninterruptibleMask_ $ runExceptT $ do @@ -412,16 +441,13 @@ instance StoreQueueClass q => QueueStoreClass q (PostgresQueueStore q) where if null snIds then ([], ntfs) else - let snIds' = foldl' (\m (sId, nId) -> M.alter (Just . maybe (S.singleton nId) (S.insert nId)) sId m) M.empty snIds - in foldr addService ([], ntfs) (M.assocs snIds') + let nsIds = M.fromList [(nId, sId) | (sId, nId) <- snIds] + (ssNtfs, deleteNtfs) = foldr (addNtf nsIds) (M.empty, []) ntfs + in (M.assocs ssNtfs, deleteNtfs) where - addService :: - (Maybe ServiceId, S.Set NotifierId) -> - ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)]) -> - ([(Maybe ServiceId, [(NotifierId, a)])], [(NotifierId, a)]) - addService (serviceId, snIds) (ssNtfs, ntfs') = - let (sNtfs, restNtfs) = partition (\(nId, _) -> S.member nId snIds) ntfs' - in ((serviceId, sNtfs) : ssNtfs, restNtfs) + addNtf nsIds ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId nsIds of + Just serviceId -> (M.alter (Just . maybe [ntf] (ntf :)) serviceId ssNtfs, deleteNtfs) + Nothing -> (ssNtfs, ntf : deleteNtfs) getServiceQueueCountHash :: (PartyI p, ServiceParty p) => PostgresQueueStore q -> SParty p -> ServiceId -> IO (Either ErrorType (Int64, IdsHash)) getServiceQueueCountHash st party serviceId = @@ -636,7 +662,7 @@ withDB' op st action = withDB op st $ fmap Right . action withDB :: forall a q. Text -> PostgresQueueStore q -> (DB.Connection -> IO (Either ErrorType a)) -> ExceptT ErrorType IO a withDB op st action = - ExceptT $ withTransaction (dbStore st) action `catchOwn'` logErr + ExceptT $ withRetriedTransaction (dbStore st) action `catchOwn'` logErr where logErr :: E.SomeException -> IO (Either ErrorType a) logErr e = logError ("STORE: " <> err) $> Left (STORE err) diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs index 165623258..6e71c65fa 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/Migrations.hs @@ -23,7 +23,10 @@ serverSchemaMigrations = ("20250915_queue_ids_hash", m20250915_queue_ids_hash, Just down_m20250915_queue_ids_hash), ("20260916_prometheus_indexes", m20260916_prometheus_indexes, Just down_m20260916_prometheus_indexes), ("20260917_msg_queues_hot", m20260917_msg_queues_hot, Just down_m20260917_msg_queues_hot), - ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages) + ("20260918_expire_messages", m20260918_expire_messages, Just down_m20260918_expire_messages), + ("20261023_server_stats", m20261023_server_stats, Just down_m20261023_server_stats), + ("20261108_rcv_service_queues", m20261108_rcv_service_queues, Just down_m20261108_rcv_service_queues), + ("20261121_server_stats_v2", m20261121_server_stats_v2, Just down_m20261121_server_stats_v2) ] -- | The list of migrations in ascending order by date @@ -1236,3 +1239,153 @@ BEGIN END; $$; |] + +m20261108_rcv_service_queues :: Text +m20261108_rcv_service_queues = + [r| +CREATE INDEX idx_msg_queues_rcv_service_active ON msg_queues (rcv_service_id, recipient_id) WHERE deleted_at IS NULL AND rcv_service_id IS NOT NULL; + |] + +down_m20261108_rcv_service_queues :: Text +down_m20261108_rcv_service_queues = + [r| +DROP INDEX idx_msg_queues_rcv_service_active; + |] + +m20261023_server_stats :: Text +m20261023_server_stats = + [r| +CREATE TABLE server_stats( + server_stats_id SMALLINT NOT NULL PRIMARY KEY CHECK (server_stats_id = 1), + saved_at BIGINT NOT NULL, + from_time BIGINT NOT NULL, + q_created BIGINT NOT NULL, + q_secured BIGINT NOT NULL, + q_deleted_all BIGINT NOT NULL, + q_deleted_new BIGINT NOT NULL, + q_deleted_secured BIGINT NOT NULL, + q_deleted_all_b BIGINT NOT NULL, + q_blocked BIGINT NOT NULL, + q_sub BIGINT NOT NULL, + q_sub_all_b BIGINT NOT NULL, + q_sub_auth BIGINT NOT NULL, + q_sub_duplicate BIGINT NOT NULL, + q_sub_prohibited BIGINT NOT NULL, + q_sub_end BIGINT NOT NULL, + q_sub_end_b BIGINT NOT NULL, + ntf_created BIGINT NOT NULL, + ntf_new_created BIGINT NOT NULL, + ntf_deleted BIGINT NOT NULL, + ntf_deleted_b BIGINT NOT NULL, + ntf_sub BIGINT NOT NULL, + ntf_sub_b BIGINT NOT NULL, + ntf_sub_auth BIGINT NOT NULL, + ntf_sub_duplicate BIGINT NOT NULL, + msg_sent BIGINT NOT NULL, + msg_sent_auth BIGINT NOT NULL, + msg_sent_quota BIGINT NOT NULL, + msg_sent_large BIGINT NOT NULL, + msg_sent_block BIGINT NOT NULL, + msg_recv BIGINT NOT NULL, + msg_recv_get BIGINT NOT NULL, + msg_get BIGINT NOT NULL, + msg_get_no_msg BIGINT NOT NULL, + msg_get_auth BIGINT NOT NULL, + msg_get_duplicate BIGINT NOT NULL, + msg_get_prohibited BIGINT NOT NULL, + msg_expired BIGINT NOT NULL, + msg_sent_ntf BIGINT NOT NULL, + msg_recv_ntf BIGINT NOT NULL, + msg_ntfs BIGINT NOT NULL, + msg_ntfs_b BIGINT NOT NULL, + msg_ntf_no_sub BIGINT NOT NULL, + msg_ntf_lost BIGINT NOT NULL, + msg_ntf_expired BIGINT NOT NULL, + p_relays_requests BIGINT NOT NULL, + p_relays_successes BIGINT NOT NULL, + p_relays_errors_connect BIGINT NOT NULL, + p_relays_errors_compat BIGINT NOT NULL, + p_relays_errors_other BIGINT NOT NULL, + p_relays_own_requests BIGINT NOT NULL, + p_relays_own_successes BIGINT NOT NULL, + p_relays_own_errors_connect BIGINT NOT NULL, + p_relays_own_errors_compat BIGINT NOT NULL, + p_relays_own_errors_other BIGINT NOT NULL, + p_msg_fwds_requests BIGINT NOT NULL, + p_msg_fwds_successes BIGINT NOT NULL, + p_msg_fwds_errors_connect BIGINT NOT NULL, + p_msg_fwds_errors_compat BIGINT NOT NULL, + p_msg_fwds_errors_other BIGINT NOT NULL, + p_msg_fwds_own_requests BIGINT NOT NULL, + p_msg_fwds_own_successes BIGINT NOT NULL, + p_msg_fwds_own_errors_connect BIGINT NOT NULL, + p_msg_fwds_own_errors_compat BIGINT NOT NULL, + p_msg_fwds_own_errors_other BIGINT NOT NULL, + p_msg_fwds_recv BIGINT NOT NULL, + rcv_services_assoc_new BIGINT NOT NULL, + rcv_services_assoc_duplicate BIGINT NOT NULL, + rcv_services_assoc_updated BIGINT NOT NULL, + rcv_services_assoc_removed BIGINT NOT NULL, + rcv_services_sub_count BIGINT NOT NULL, + rcv_services_sub_duplicate BIGINT NOT NULL, + rcv_services_sub_queues BIGINT NOT NULL, + rcv_services_sub_end BIGINT NOT NULL, + ntf_services_assoc_new BIGINT NOT NULL, + ntf_services_assoc_duplicate BIGINT NOT NULL, + ntf_services_assoc_updated BIGINT NOT NULL, + ntf_services_assoc_removed BIGINT NOT NULL, + ntf_services_sub_count BIGINT NOT NULL, + ntf_services_sub_duplicate BIGINT NOT NULL, + ntf_services_sub_queues BIGINT NOT NULL, + ntf_services_sub_end BIGINT NOT NULL, + rslv_reqs BIGINT NOT NULL, + rslv_succ BIGINT NOT NULL, + rslv_not_found BIGINT NOT NULL, + rslv_resolver_errs BIGINT NOT NULL, + rslv_disabled BIGINT NOT NULL +); + +CREATE TABLE server_stats_queues( + period_set SMALLINT NOT NULL, + queue_hash BIGINT NOT NULL, + PRIMARY KEY (period_set, queue_hash) +); + |] + +down_m20261023_server_stats :: Text +down_m20261023_server_stats = + [r| +DROP TABLE server_stats_queues; + +DROP TABLE server_stats; + |] + +m20261121_server_stats_v2 :: Text +m20261121_server_stats_v2 = + [r| +ALTER TABLE server_stats + ADD COLUMN rslv_rejected BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_below23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_from23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_recv_below23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_recv_from23 BIGINT NOT NULL DEFAULT 0, + ADD COLUMN p_msg_fwds_relay_limit BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmds BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmd_ms BIGINT NOT NULL DEFAULT 0, + ADD COLUMN fwd_worker_cmd_max_ms BIGINT NOT NULL DEFAULT 0; + |] + +down_m20261121_server_stats_v2 :: Text +down_m20261121_server_stats_v2 = + [r| +ALTER TABLE server_stats + DROP COLUMN rslv_rejected, + DROP COLUMN p_msg_fwds_below23, + DROP COLUMN p_msg_fwds_from23, + DROP COLUMN p_msg_fwds_recv_below23, + DROP COLUMN p_msg_fwds_recv_from23, + DROP COLUMN p_msg_fwds_relay_limit, + DROP COLUMN fwd_worker_cmds, + DROP COLUMN fwd_worker_cmd_ms, + DROP COLUMN fwd_worker_cmd_max_ms; + |] diff --git a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql index cea2e0835..f67a1c9d2 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql +++ b/src/Simplex/Messaging/Server/QueueStore/Postgres/server_schema.sql @@ -1,6 +1,7 @@ SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); @@ -424,7 +425,7 @@ CREATE TABLE smp_server.migrations ( CREATE TABLE smp_server.msg_queues ( recipient_id bytea NOT NULL, - recipient_keys bytea NOT NULL, + recipient_keys bytea CONSTRAINT msg_queues_recipient_key_not_null NOT NULL, rcv_dh_secret bytea NOT NULL, sender_id bytea NOT NULL, sender_key bytea, @@ -447,6 +448,115 @@ WITH (fillfactor='80', autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze +CREATE TABLE smp_server.server_stats ( + server_stats_id smallint NOT NULL, + saved_at bigint NOT NULL, + from_time bigint NOT NULL, + q_created bigint NOT NULL, + q_secured bigint NOT NULL, + q_deleted_all bigint NOT NULL, + q_deleted_new bigint NOT NULL, + q_deleted_secured bigint NOT NULL, + q_deleted_all_b bigint NOT NULL, + q_blocked bigint NOT NULL, + q_sub bigint NOT NULL, + q_sub_all_b bigint NOT NULL, + q_sub_auth bigint NOT NULL, + q_sub_duplicate bigint NOT NULL, + q_sub_prohibited bigint NOT NULL, + q_sub_end bigint NOT NULL, + q_sub_end_b bigint NOT NULL, + ntf_created bigint NOT NULL, + ntf_new_created bigint NOT NULL, + ntf_deleted bigint NOT NULL, + ntf_deleted_b bigint NOT NULL, + ntf_sub bigint NOT NULL, + ntf_sub_b bigint NOT NULL, + ntf_sub_auth bigint NOT NULL, + ntf_sub_duplicate bigint NOT NULL, + msg_sent bigint NOT NULL, + msg_sent_auth bigint NOT NULL, + msg_sent_quota bigint NOT NULL, + msg_sent_large bigint NOT NULL, + msg_sent_block bigint NOT NULL, + msg_recv bigint NOT NULL, + msg_recv_get bigint NOT NULL, + msg_get bigint NOT NULL, + msg_get_no_msg bigint NOT NULL, + msg_get_auth bigint NOT NULL, + msg_get_duplicate bigint NOT NULL, + msg_get_prohibited bigint NOT NULL, + msg_expired bigint NOT NULL, + msg_sent_ntf bigint NOT NULL, + msg_recv_ntf bigint NOT NULL, + msg_ntfs bigint NOT NULL, + msg_ntfs_b bigint NOT NULL, + msg_ntf_no_sub bigint NOT NULL, + msg_ntf_lost bigint NOT NULL, + msg_ntf_expired bigint NOT NULL, + p_relays_requests bigint NOT NULL, + p_relays_successes bigint NOT NULL, + p_relays_errors_connect bigint NOT NULL, + p_relays_errors_compat bigint NOT NULL, + p_relays_errors_other bigint NOT NULL, + p_relays_own_requests bigint NOT NULL, + p_relays_own_successes bigint NOT NULL, + p_relays_own_errors_connect bigint NOT NULL, + p_relays_own_errors_compat bigint NOT NULL, + p_relays_own_errors_other bigint NOT NULL, + p_msg_fwds_requests bigint NOT NULL, + p_msg_fwds_successes bigint NOT NULL, + p_msg_fwds_errors_connect bigint NOT NULL, + p_msg_fwds_errors_compat bigint NOT NULL, + p_msg_fwds_errors_other bigint NOT NULL, + p_msg_fwds_own_requests bigint NOT NULL, + p_msg_fwds_own_successes bigint NOT NULL, + p_msg_fwds_own_errors_connect bigint NOT NULL, + p_msg_fwds_own_errors_compat bigint NOT NULL, + p_msg_fwds_own_errors_other bigint NOT NULL, + p_msg_fwds_recv bigint NOT NULL, + rcv_services_assoc_new bigint NOT NULL, + rcv_services_assoc_duplicate bigint NOT NULL, + rcv_services_assoc_updated bigint NOT NULL, + rcv_services_assoc_removed bigint NOT NULL, + rcv_services_sub_count bigint NOT NULL, + rcv_services_sub_duplicate bigint NOT NULL, + rcv_services_sub_queues bigint NOT NULL, + rcv_services_sub_end bigint NOT NULL, + ntf_services_assoc_new bigint NOT NULL, + ntf_services_assoc_duplicate bigint NOT NULL, + ntf_services_assoc_updated bigint NOT NULL, + ntf_services_assoc_removed bigint NOT NULL, + ntf_services_sub_count bigint NOT NULL, + ntf_services_sub_duplicate bigint NOT NULL, + ntf_services_sub_queues bigint NOT NULL, + ntf_services_sub_end bigint NOT NULL, + rslv_reqs bigint NOT NULL, + rslv_succ bigint NOT NULL, + rslv_not_found bigint NOT NULL, + rslv_resolver_errs bigint NOT NULL, + rslv_disabled bigint NOT NULL, + rslv_rejected bigint DEFAULT 0 NOT NULL, + p_msg_fwds_below23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_from23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_recv_below23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_recv_from23 bigint DEFAULT 0 NOT NULL, + p_msg_fwds_relay_limit bigint DEFAULT 0 NOT NULL, + fwd_worker_cmds bigint DEFAULT 0 NOT NULL, + fwd_worker_cmd_ms bigint DEFAULT 0 NOT NULL, + fwd_worker_cmd_max_ms bigint DEFAULT 0 NOT NULL, + CONSTRAINT server_stats_server_stats_id_check CHECK ((server_stats_id = 1)) +); + + + +CREATE TABLE smp_server.server_stats_queues ( + period_set smallint NOT NULL, + queue_hash bigint NOT NULL +); + + + CREATE TABLE smp_server.services ( service_id bytea NOT NULL, service_role text NOT NULL, @@ -475,6 +585,16 @@ ALTER TABLE ONLY smp_server.msg_queues +ALTER TABLE ONLY smp_server.server_stats + ADD CONSTRAINT server_stats_pkey PRIMARY KEY (server_stats_id); + + + +ALTER TABLE ONLY smp_server.server_stats_queues + ADD CONSTRAINT server_stats_queues_pkey PRIMARY KEY (period_set, queue_hash); + + + ALTER TABLE ONLY smp_server.services ADD CONSTRAINT services_pkey PRIMARY KEY (service_id); @@ -513,6 +633,10 @@ CREATE INDEX idx_msg_queues_ntf_service_id ON smp_server.msg_queues USING btree +CREATE INDEX idx_msg_queues_rcv_service_active ON smp_server.msg_queues USING btree (rcv_service_id, recipient_id) WHERE ((deleted_at IS NULL) AND (rcv_service_id IS NOT NULL)); + + + CREATE INDEX idx_msg_queues_rcv_service_id ON smp_server.msg_queues USING btree (rcv_service_id, deleted_at); diff --git a/src/Simplex/Messaging/Server/QueueStore/STM.hs b/src/Simplex/Messaging/Server/QueueStore/STM.hs index b1ed8cc13..53d79afff 100644 --- a/src/Simplex/Messaging/Server/QueueStore/STM.hs +++ b/src/Simplex/Messaging/Server/QueueStore/STM.hs @@ -19,6 +19,7 @@ module Simplex.Messaging.Server.QueueStore.STM STMService (..), foldRcvServiceQueues, withLoadedQueues, + restoreQueueLinkData, setStoreLog, withLog', readQueueRecIO, @@ -34,8 +35,9 @@ import Data.Bitraversable (bimapM) import Data.Functor (($>)) import Data.Int (Int64) import Data.List (partition) -import Data.List.NonEmpty (NonEmpty) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M +import Data.Maybe (fromMaybe) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) @@ -118,7 +120,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where addQueue_ :: STMQueueStore q -> (RecipientId -> QueueRec -> IO q) -> RecipientId -> QueueRec -> IO (Either ErrorType q) addQueue_ st mkQ rId qr@QueueRec {senderId = sId, notifier, queueData, rcvServiceId} = do sq <- mkQ rId qr - add sq $>> withLog "addStoreQueue" st (\s -> logCreateQueue s rId qr) $> Right sq + E.uninterruptibleMask_ $ add sq $>> withLog "addStoreQueue" st (\s -> logCreateQueue s rId qr) $> Right sq where STMQueueStore {queues, senders, notifiers, links} = st add q = atomically $ ifM hasId (pure $ Left DUPLICATE_) $ Right () <$ do @@ -165,29 +167,34 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where _ -> Left AUTH addQueueLinkData :: STMQueueStore q -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) - addQueueLinkData st sq lnkId d = + addQueueLinkData st sq lnkId d = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= add) $>> withLog "addQueueLinkData" st (\s -> logCreateLink s rId lnkId d) where rId = recipientId sq qr = queueRec sq - add q = case queueData q of - _ | isSecuredMsgQueue q -> pure $ Left AUTH - Nothing -> addLink - Just (lnkId', d') | lnkId' == lnkId && fst d' == fst d -> addLink + add q = case recipientKeys q of + _ :| [] -> addLinkData st sq lnkId d q _ -> pure $ Left AUTH - where - addLink = do - TM.lookup lnkId (links st) >>= \case - Just rId' | rId' /= rId -> pure $ Left AUTH - _ -> do - let !q' = q {queueData = Just (lnkId, d)} - writeTVar qr $ Just q' - TM.insert lnkId rId $ links st - pure $ Right () + + swapQueueLinkData :: STMQueueStore q -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) + swapQueueLinkData st sq lnkId h rKeys_ d = + atomically (readQueueRec qr $>>= swap) $>>= \case + Just ud -> pure $ Right $ Just ud + Nothing -> Nothing <$$ withLog "swapQueueLinkData" st (\s -> logSwapLink s (recipientId sq) lnkId d rKeys_) + where + qr = queueRec sq + swap q = case queueData q of + Just (lnkId', (fd', ud')) + | lnkId' /= lnkId || fd' /= fst d -> pure $ Left AUTH + | linkDataHash ud' /= h -> pure $ Right $ Just ud' + | otherwise -> do + let !q' = q {recipientKeys = fromMaybe (recipientKeys q) rKeys_, queueData = Just (lnkId, d)} + writeTVar qr (Just q') $> Right Nothing + Nothing -> pure $ Left AUTH deleteQueueLinkData :: STMQueueStore q -> q -> IO (Either ErrorType ()) - deleteQueueLinkData st sq = + deleteQueueLinkData st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>> withLog "deleteQueueLinkData" st (`logDeleteLink` recipientId sq) where @@ -196,16 +203,18 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where TM.delete lnkId $ links st writeTVar qr $ Just q {queueData = Nothing} - updateKeys :: STMQueueStore q -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) - updateKeys st sq rKeys = - withQueueRec qr update + updateKeys :: STMQueueStore q -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys st sq prevKeys_ rKeys = + atomically (readQueueRec qr $>>= update) $>> withLog "updateKeys" st (\s -> logUpdateKeys s (recipientId sq) rKeys) where qr = queueRec sq - update q = writeTVar qr $ Just q {recipientKeys = rKeys} + update q + | maybe True (recipientKeys q ==) prevKeys_ = Right <$> writeTVar qr (Just q {recipientKeys = rKeys}) + | otherwise = pure $ Left AUTH secureQueue :: STMQueueStore q -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) - secureQueue st sq sKey = + secureQueue st sq sKey = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= secure) $>> withLog "secureQueue" st (\s -> logSecureQueue s (recipientId sq) sKey) where @@ -217,7 +226,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure $ Right () addQueueNotifier :: STMQueueStore q -> q -> NtfCreds -> IO (Either ErrorType (Maybe NtfCreds)) - addQueueNotifier st sq ntfCreds@NtfCreds {notifierId = nId} = + addQueueNotifier st sq ntfCreds@NtfCreds {notifierId = nId} = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= add) $>>= \nc_ -> nc_ <$$ withLog "addQueueNotifier" st (\s -> logAddNotifier s rId ntfCreds) where @@ -232,7 +241,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure $ Right nc_ deleteQueueNotifier :: STMQueueStore q -> q -> IO (Either ErrorType (Maybe NtfCreds)) - deleteQueueNotifier st sq = + deleteQueueNotifier st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>>= (<$$ withLog "deleteQueueNotifier" st (`logDeleteNotifier` recipientId sq)) where @@ -243,22 +252,22 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure nc suspendQueue :: STMQueueStore q -> q -> IO (Either ErrorType ()) - suspendQueue st sq = + suspendQueue st sq = E.uninterruptibleMask_ $ setStatus (queueRec sq) EntityOff $>> withLog "suspendQueue" st (`logSuspendQueue` recipientId sq) blockQueue :: STMQueueStore q -> q -> BlockingInfo -> IO (Either ErrorType ()) - blockQueue st sq info = + blockQueue st sq info = E.uninterruptibleMask_ $ setStatus (queueRec sq) (EntityBlocked info) $>> withLog "blockQueue" st (\sl -> logBlockQueue sl (recipientId sq) info) unblockQueue :: STMQueueStore q -> q -> IO (Either ErrorType ()) - unblockQueue st sq = + unblockQueue st sq = E.uninterruptibleMask_ $ setStatus (queueRec sq) EntityActive $>> withLog "unblockQueue" st (`logUnblockQueue` recipientId sq) updateQueueTime :: STMQueueStore q -> q -> SystemDate -> IO (Either ErrorType QueueRec) - updateQueueTime st sq t = withQueueRec qr update $>>= log' + updateQueueTime st sq t = E.uninterruptibleMask_ $ withQueueRec qr update $>>= log' where qr = queueRec sq update q@QueueRec {updatedAt} @@ -271,7 +280,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where | otherwise = pure $ Right q deleteStoreQueue :: STMQueueStore q -> q -> IO (Either ErrorType QueueRec) - deleteStoreQueue st sq = + deleteStoreQueue st sq = E.uninterruptibleMask_ $ withQueueRec qr delete $>>= (<$$ withLog "deleteStoreQueue" st (`logDeleteQueue` rId)) where @@ -287,7 +296,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure q getCreateService :: STMQueueStore q -> ServiceRec -> IO (Either ErrorType ServiceId) - getCreateService st sr@ServiceRec {serviceId = newSrvId, serviceRole, serviceCertHash = XV.Fingerprint fp} = + getCreateService st sr@ServiceRec {serviceId = newSrvId, serviceRole, serviceCertHash = XV.Fingerprint fp} = E.uninterruptibleMask_ $ TM.lookupIO fp serviceCerts >>= maybe (atomically $ TM.lookup fp serviceCerts >>= maybe newService checkService) @@ -315,7 +324,7 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where pure STMService {serviceRec = sr, serviceRcvQueues, serviceNtfQueues} setQueueService :: (PartyI p, ServiceParty p) => STMQueueStore q -> q -> SParty p -> Maybe ServiceId -> IO (Either ErrorType ()) - setQueueService st sq party serviceId = + setQueueService st sq party serviceId = E.uninterruptibleMask_ $ atomically (readQueueRec qr $>>= setService) $>> withLog "setQueueService" st (\sl -> logQueueService sl rId party serviceId) where @@ -355,10 +364,16 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where ssNtfs' = (Nothing, ntfs') : ssNtfs pure $ Right (ssNtfs', deleteNtfs) where - addService (ssNtfs, ntfs') (serviceId, s) = do - (snIds, _) <- readTVarIO $ serviceNtfQueues s - let (sNtfs, restNtfs) = partition (\(nId, _) -> S.member nId snIds) ntfs' - pure ((Just serviceId, sNtfs) : ssNtfs, restNtfs) + addService (ssNtfs, deleteNtfs) (serviceId, s) = do + (sNIds, _) <- readTVarIO $ serviceNtfQueues s + let (sNtfs, otherNtfs) = partition (\(nId, _) -> S.member nId sNIds) deleteNtfs + pure ((Just serviceId, sNtfs) : ssNtfs, otherNtfs) + addNtf ns qs ntf@(nId, _) (!ssNtfs, deleteNtfs) = case M.lookup nId ns >>= (`M.lookup` qs) of + Just q -> do + qr <- readTVarIO (queueRec q) + let serviceId = qr >>= notifier >>= ntfServiceId + pure (M.alter (Just . maybe [ntf] (ntf :)) serviceId ssNtfs, deleteNtfs) + Nothing -> pure (ssNtfs, ntf : deleteNtfs) getServiceQueueCountHash :: (PartyI p, ServiceParty p) => STMQueueStore q -> SParty p -> ServiceId -> IO (Either ErrorType (Int64, IdsHash)) getServiceQueueCountHash st party serviceId = @@ -370,6 +385,38 @@ instance StoreQueueClass q => QueueStoreClass q (STMQueueStore q) where SRecipientService -> serviceRcvQueues SNotifierService -> serviceNtfQueues +setQueueService_ :: (StoreQueueClass q, PartyI p, ServiceParty p) => STMQueueStore q -> Maybe QueueId -> q -> SParty p -> Maybe ServiceId -> IO (Either ErrorType (Maybe ServiceId)) +setQueueService_ st qId_ sq party serviceId = + atomically (readQueueRec qr $>>= setService) + $>>= \prevSrvId -> + if prevSrvId == serviceId + then pure $ Right prevSrvId + else prevSrvId <$$ withLog "setQueueService" st (\sl -> logQueueService sl rId party serviceId) + where + qr = queueRec sq + rId = recipientId sq + setService :: QueueRec -> STM (Either ErrorType (Maybe ServiceId)) + setService q@QueueRec {rcvServiceId = prevSrvId} = case party of + SRecipientService + | prevSrvId == serviceId -> pure $ Right prevSrvId + | otherwise -> do + updateServiceQueues serviceRcvQueues rId prevSrvId + let !q' = Just q {rcvServiceId = serviceId} + writeTVar qr q' $> Right prevSrvId + SNotifierService -> case notifier q of + Nothing -> pure $ Left AUTH + Just nc@NtfCreds {notifierId = nId, ntfServiceId = prevNtfSrvId} + | any (/= nId) qId_ -> pure $ Left AUTH + | prevNtfSrvId == serviceId -> pure $ Right prevNtfSrvId + | otherwise -> do + let !q' = Just q {notifier = Just nc {ntfServiceId = serviceId}} + updateServiceQueues serviceNtfQueues nId prevNtfSrvId + writeTVar qr q' $> Right prevNtfSrvId + updateServiceQueues :: (STMService -> TVar (Set QueueId, IdsHash)) -> QueueId -> Maybe ServiceId -> STM () + updateServiceQueues serviceSel qId prevSrvId = do + mapM_ (removeServiceQueue st serviceSel qId) prevSrvId + mapM_ (addServiceQueue st serviceSel qId) serviceId + foldRcvServiceQueues :: StoreQueueClass q => STMQueueStore q -> ServiceId -> (a -> (q, QueueRec) -> IO a) -> a -> IO a foldRcvServiceQueues st serviceId f acc = TM.lookupIO serviceId (services st) >>= \case @@ -385,6 +432,27 @@ withLoadedQueues st f = readTVarIO (queues st) >>= foldM run mempty where run !acc = fmap (acc <>) . f +restoreQueueLinkData :: StoreQueueClass q => STMQueueStore q -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) +restoreQueueLinkData st sq lnkId d = atomically $ readQueueRec (queueRec sq) $>>= addLinkData st sq lnkId d + +addLinkData :: StoreQueueClass q => STMQueueStore q -> q -> LinkId -> QueueLinkData -> QueueRec -> STM (Either ErrorType ()) +addLinkData st sq lnkId d q = case queueData q of + _ | isSecuredMsgQueue q -> pure $ Left AUTH + Nothing -> addLink + Just (lnkId', d') | lnkId' == lnkId && fst d' == fst d -> addLink + _ -> pure $ Left AUTH + where + rId = recipientId sq + qr = queueRec sq + addLink = do + TM.lookup lnkId (links st) >>= \case + Just rId' | rId' /= rId -> pure $ Left AUTH + _ -> do + let !q' = q {queueData = Just (lnkId, d)} + writeTVar qr $ Just q' + TM.insert lnkId rId $ links st + pure $ Right () + withQueueRec :: TVar (Maybe QueueRec) -> (QueueRec -> STM a) -> IO (Either ErrorType a) withQueueRec qr a = atomically $ readQueueRec qr >>= mapM a diff --git a/src/Simplex/Messaging/Server/QueueStore/Types.hs b/src/Simplex/Messaging/Server/QueueStore/Types.hs index e8d47751b..28e60f388 100644 --- a/src/Simplex/Messaging/Server/QueueStore/Types.hs +++ b/src/Simplex/Messaging/Server/QueueStore/Types.hs @@ -33,9 +33,10 @@ class StoreQueueClass q => QueueStoreClass q s where getQueues_ :: BatchParty p => s -> (RecipientId -> QueueRec -> IO q) -> SParty p -> [QueueId] -> IO [Either ErrorType q] getQueueLinkData :: s -> q -> LinkId -> IO (Either ErrorType QueueLinkData) addQueueLinkData :: s -> q -> LinkId -> QueueLinkData -> IO (Either ErrorType ()) + swapQueueLinkData :: s -> q -> LinkId -> LinkDataHash -> Maybe (NonEmpty RcvPublicAuthKey) -> QueueLinkData -> IO (Either ErrorType (Maybe EncUserDataBytes)) deleteQueueLinkData :: s -> q -> IO (Either ErrorType ()) secureQueue :: s -> q -> SndPublicAuthKey -> IO (Either ErrorType ()) - updateKeys :: s -> q -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) + updateKeys :: s -> q -> Maybe (NonEmpty RcvPublicAuthKey) -> NonEmpty RcvPublicAuthKey -> IO (Either ErrorType ()) addQueueNotifier :: s -> q -> NtfCreds -> IO (Either ErrorType (Maybe NtfCreds)) deleteQueueNotifier :: s -> q -> IO (Either ErrorType (Maybe NtfCreds)) suspendQueue :: s -> q -> IO (Either ErrorType ()) diff --git a/src/Simplex/Messaging/Server/Stats.hs b/src/Simplex/Messaging/Server/Stats.hs index 70a450652..d27649557 100644 --- a/src/Simplex/Messaging/Server/Stats.hs +++ b/src/Simplex/Messaging/Server/Stats.hs @@ -21,6 +21,12 @@ module Simplex.Messaging.Server.Stats getServerStatsData, setServerStats, newPeriodStats, + newPendingPeriodStats, + PendingPeriods (..), + PendingHashes (..), + takePendingHashes, + restorePendingHashes, + mergePendingHashes, newPeriodStatsData, getPeriodStatsData, setPeriodStats, @@ -124,6 +130,11 @@ data ServerStats = ServerStats pMsgFwds :: ProxyStats, pMsgFwdsOwn :: ProxyStats, pMsgFwdsRecv :: IORef Int, + pMsgFwdsBelow23 :: IORef Int, + pMsgFwdsFrom23 :: IORef Int, + pMsgFwdsRecvBelow23 :: IORef Int, + pMsgFwdsRecvFrom23 :: IORef Int, + pMsgFwdsRelayLimit :: IORef Int, rcvServices :: ServiceStats, ntfServices :: ServiceStats, rcvServicesSubMsg :: IORef Int, @@ -195,6 +206,11 @@ data ServerStatsData = ServerStatsData _pMsgFwds :: ProxyStatsData, _pMsgFwdsOwn :: ProxyStatsData, _pMsgFwdsRecv :: Int, + _pMsgFwdsBelow23 :: Int, + _pMsgFwdsFrom23 :: Int, + _pMsgFwdsRecvBelow23 :: Int, + _pMsgFwdsRecvFrom23 :: Int, + _pMsgFwdsRelayLimit :: Int, _ntfServices :: ServiceStatsData, _rcvServices :: ServiceStatsData, _rcvServicesSubMsg :: Int, @@ -214,8 +230,8 @@ data ServerStatsData = ServerStatsData } deriving (Show) -newServerStats :: UTCTime -> IO ServerStats -newServerStats ts = do +newServerStats :: Bool -> UTCTime -> IO ServerStats +newServerStats trackPending ts = do fromTime <- newIORef ts qCreated <- newIORef 0 qSecured <- newIORef 0 @@ -253,10 +269,10 @@ newServerStats ts = do msgGetDuplicate <- newIORef 0 msgGetProhibited <- newIORef 0 msgExpired <- newIORef 0 - activeQueues <- newPeriodStats + activeQueues <- newActiveQueues msgSentNtf <- newIORef 0 msgRecvNtf <- newIORef 0 - activeQueuesNtf <- newPeriodStats + activeQueuesNtf <- newActiveQueues msgNtfs <- newIORef 0 msgNtfsB <- newIORef 0 msgNtfNoSub <- newIORef 0 @@ -267,6 +283,11 @@ newServerStats ts = do pMsgFwds <- newProxyStats pMsgFwdsOwn <- newProxyStats pMsgFwdsRecv <- newIORef 0 + pMsgFwdsBelow23 <- newIORef 0 + pMsgFwdsFrom23 <- newIORef 0 + pMsgFwdsRecvBelow23 <- newIORef 0 + pMsgFwdsRecvFrom23 <- newIORef 0 + pMsgFwdsRelayLimit <- newIORef 0 rcvServices <- newServiceStats ntfServices <- newServiceStats rcvServicesSubMsg <- newIORef 0 @@ -336,6 +357,11 @@ newServerStats ts = do pMsgFwds, pMsgFwdsOwn, pMsgFwdsRecv, + pMsgFwdsBelow23, + pMsgFwdsFrom23, + pMsgFwdsRecvBelow23, + pMsgFwdsRecvFrom23, + pMsgFwdsRelayLimit, rcvServices, ntfServices, rcvServicesSubMsg, @@ -353,6 +379,8 @@ newServerStats ts = do ntfCount, rslvStats } + where + newActiveQueues = if trackPending then newPendingPeriodStats else newPeriodStats getServerStatsData :: ServerStats -> IO ServerStatsData getServerStatsData s = do @@ -407,6 +435,11 @@ getServerStatsData s = do _pMsgFwds <- getProxyStatsData $ pMsgFwds s _pMsgFwdsOwn <- getProxyStatsData $ pMsgFwdsOwn s _pMsgFwdsRecv <- readIORef $ pMsgFwdsRecv s + _pMsgFwdsBelow23 <- readIORef $ pMsgFwdsBelow23 s + _pMsgFwdsFrom23 <- readIORef $ pMsgFwdsFrom23 s + _pMsgFwdsRecvBelow23 <- readIORef $ pMsgFwdsRecvBelow23 s + _pMsgFwdsRecvFrom23 <- readIORef $ pMsgFwdsRecvFrom23 s + _pMsgFwdsRelayLimit <- readIORef $ pMsgFwdsRelayLimit s _rcvServices <- getServiceStatsData $ rcvServices s _ntfServices <- getServiceStatsData $ ntfServices s _rcvServicesSubMsg <- readIORef $ rcvServicesSubMsg s @@ -476,6 +509,11 @@ getServerStatsData s = do _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, _rcvServices, _ntfServices, _rcvServicesSubMsg, @@ -548,6 +586,11 @@ setServerStats s d = do setProxyStats (pMsgFwds s) $! _pMsgFwds d setProxyStats (pMsgFwdsOwn s) $! _pMsgFwdsOwn d writeIORef (pMsgFwdsRecv s) $! _pMsgFwdsRecv d + writeIORef (pMsgFwdsBelow23 s) $! _pMsgFwdsBelow23 d + writeIORef (pMsgFwdsFrom23 s) $! _pMsgFwdsFrom23 d + writeIORef (pMsgFwdsRecvBelow23 s) $! _pMsgFwdsRecvBelow23 d + writeIORef (pMsgFwdsRecvFrom23 s) $! _pMsgFwdsRecvFrom23 d + writeIORef (pMsgFwdsRelayLimit s) $! _pMsgFwdsRelayLimit d setServiceStats (rcvServices s) $! _rcvServices d setServiceStats (ntfServices s) $! _ntfServices d writeIORef (rcvServicesSubMsg s) $! _rcvServicesSubMsg d @@ -625,6 +668,10 @@ instance StrEncoding ServerStatsData where "pMsgFwdsOwn:", strEncode (_pMsgFwdsOwn d), "pMsgFwdsRecv=" <> strEncode (_pMsgFwdsRecv d), + "pMsgFwdsBelow23=" <> strEncode (_pMsgFwdsBelow23 d), + "pMsgFwdsFrom23=" <> strEncode (_pMsgFwdsFrom23 d), + "pMsgFwdsRecvBelow23=" <> strEncode (_pMsgFwdsRecvBelow23 d), + "pMsgFwdsRecvFrom23=" <> strEncode (_pMsgFwdsRecvFrom23 d), "rcvServices:", strEncode (_rcvServices d), "ntfServices:", @@ -699,6 +746,10 @@ instance StrEncoding ServerStatsData where _pMsgFwds <- proxyStatsP "pMsgFwds:" _pMsgFwdsOwn <- proxyStatsP "pMsgFwdsOwn:" _pMsgFwdsRecv <- opt "pMsgFwdsRecv=" + _pMsgFwdsBelow23 <- opt "pMsgFwdsBelow23=" + _pMsgFwdsFrom23 <- opt "pMsgFwdsFrom23=" + _pMsgFwdsRecvBelow23 <- opt "pMsgFwdsRecvBelow23=" + _pMsgFwdsRecvFrom23 <- opt "pMsgFwdsRecvFrom23=" _rcvServices <- serviceStatsP "rcvServices:" _ntfServices <- serviceStatsP "ntfServices:" _rslvStats <- @@ -758,6 +809,11 @@ instance StrEncoding ServerStatsData where _pMsgFwds, _pMsgFwdsOwn, _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit = 0, _rcvServices, _ntfServices, _rcvServicesSubMsg = 0, @@ -790,15 +846,51 @@ instance StrEncoding ServerStatsData where data PeriodStats = PeriodStats { day :: IORef IntSet, week :: IORef IntSet, - month :: IORef IntSet + month :: IORef IntSet, + pendingPeriods :: Maybe PendingPeriods + } + +-- hashes added and sets reset since the last successful save +data PendingPeriods = PendingPeriods + { pendingDay :: IORef PendingHashes, + pendingWeek :: IORef PendingHashes, + pendingMonth :: IORef PendingHashes } +data PendingHashes = PendingHashes + { pendingReset :: Bool, + pendingAdded :: IntSet + } + deriving (Eq, Show) + newPeriodStats :: IO PeriodStats -newPeriodStats = do +newPeriodStats = newPeriodStats_ Nothing + +newPendingPeriodStats :: IO PeriodStats +newPendingPeriodStats = do + pendingDay <- newIORef noPendingHashes + pendingWeek <- newIORef noPendingHashes + pendingMonth <- newIORef noPendingHashes + newPeriodStats_ $ Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} + +newPeriodStats_ :: Maybe PendingPeriods -> IO PeriodStats +newPeriodStats_ pendingPeriods = do day <- newIORef IS.empty week <- newIORef IS.empty month <- newIORef IS.empty - pure PeriodStats {day, week, month} + pure PeriodStats {day, week, month, pendingPeriods} + +noPendingHashes :: PendingHashes +noPendingHashes = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +takePendingHashes :: IORef PendingHashes -> IO PendingHashes +takePendingHashes ref = atomicModifyIORef' ref (noPendingHashes,) + +restorePendingHashes :: IORef PendingHashes -> PendingHashes -> IO () +restorePendingHashes ref taken = atomicModifyIORef'_ ref $ mergePendingHashes taken + +mergePendingHashes :: PendingHashes -> PendingHashes -> PendingHashes +mergePendingHashes (PendingHashes r hs) (PendingHashes r' hs') = PendingHashes (r || r') (IS.union hs hs') data PeriodStatsData = PeriodStatsData { _day :: IntSet, @@ -854,23 +946,29 @@ periodStatCounts ps ts = do let d = utctDay ts (_, wDay) = mondayStartWeek d MonthDay _ mDay = d - dayCount <- periodCount 1 $ day ps - weekCount <- periodCount wDay $ week ps - monthCount <- periodCount mDay $ month ps + pending_ = pendingPeriods ps + dayCount <- periodCount 1 (day ps) (pendingDay <$> pending_) + weekCount <- periodCount wDay (week ps) (pendingWeek <$> pending_) + monthCount <- periodCount mDay (month ps) (pendingMonth <$> pending_) pure PeriodStatCounts {dayCount, weekCount, monthCount} where - periodCount :: Int -> IORef IntSet -> IO Text - periodCount 1 ref = tshow . IS.size <$> atomicSwapIORef ref IS.empty - periodCount _ _ = pure "" + periodCount :: Int -> IORef IntSet -> Maybe (IORef PendingHashes) -> IO Text + periodCount 1 ref pRef_ = do + -- pending is reset before the set, so a hash added concurrently can only be persisted for the new period + mapM_ (`atomicWriteIORef` PendingHashes {pendingReset = True, pendingAdded = IS.empty}) pRef_ + tshow . IS.size <$> atomicSwapIORef ref IS.empty + periodCount _ _ _ = pure "" updatePeriodStats :: PeriodStats -> EntityId -> IO () updatePeriodStats ps (EntityId pId) = do - updatePeriod $ day ps - updatePeriod $ week ps - updatePeriod $ month ps + updatePeriod (day ps) (pendingDay <$> pendingPeriods ps) + updatePeriod (week ps) (pendingWeek <$> pendingPeriods ps) + updatePeriod (month ps) (pendingMonth <$> pendingPeriods ps) where ph = hash pId - updatePeriod ref = unlessM (IS.member ph <$> readIORef ref) $ atomicModifyIORef'_ ref $ IS.insert ph + updatePeriod ref pRef_ = unlessM (IS.member ph <$> readIORef ref) $ do + atomicModifyIORef'_ ref $ IS.insert ph + mapM_ (\pRef -> atomicModifyIORef'_ pRef $ \p -> p {pendingAdded = IS.insert ph $ pendingAdded p}) pRef_ data ProxyStats = ProxyStats { pRequests :: IORef Int, @@ -953,7 +1051,8 @@ data NameResolverStats = NameResolverStats rslvSucc :: IORef Int, rslvNotFound :: IORef Int, rslvResolverErrs :: IORef Int, - rslvDisabled :: IORef Int + rslvDisabled :: IORef Int, + rslvRejected :: IORef Int } newNameResolverStats :: IO NameResolverStats @@ -963,14 +1062,16 @@ newNameResolverStats = do rslvNotFound <- newIORef 0 rslvResolverErrs <- newIORef 0 rslvDisabled <- newIORef 0 - pure NameResolverStats {rslvReqs, rslvSucc, rslvNotFound, rslvResolverErrs, rslvDisabled} + rslvRejected <- newIORef 0 + pure NameResolverStats {rslvReqs, rslvSucc, rslvNotFound, rslvResolverErrs, rslvDisabled, rslvRejected} data NameResolverStatsData = NameResolverStatsData { _rslvReqs :: Int, _rslvSucc :: Int, _rslvNotFound :: Int, _rslvResolverErrs :: Int, - _rslvDisabled :: Int + _rslvDisabled :: Int, + _rslvRejected :: Int } deriving (Show) @@ -981,7 +1082,8 @@ newNameResolverStatsData = _rslvSucc = 0, _rslvNotFound = 0, _rslvResolverErrs = 0, - _rslvDisabled = 0 + _rslvDisabled = 0, + _rslvRejected = 0 } getNameResolverStatsData :: NameResolverStats -> IO NameResolverStatsData @@ -991,7 +1093,8 @@ getNameResolverStatsData s = do _rslvNotFound <- readIORef $ rslvNotFound s _rslvResolverErrs <- readIORef $ rslvResolverErrs s _rslvDisabled <- readIORef $ rslvDisabled s - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- readIORef $ rslvRejected s + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} getResetNameResolverStatsData :: NameResolverStats -> IO NameResolverStatsData getResetNameResolverStatsData s = do @@ -1000,7 +1103,8 @@ getResetNameResolverStatsData s = do _rslvNotFound <- atomicSwapIORef (rslvNotFound s) 0 _rslvResolverErrs <- atomicSwapIORef (rslvResolverErrs s) 0 _rslvDisabled <- atomicSwapIORef (rslvDisabled s) 0 - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- atomicSwapIORef (rslvRejected s) 0 + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} -- not thread safe; used on server start only setNameResolverStats :: NameResolverStats -> NameResolverStatsData -> IO () @@ -1010,9 +1114,10 @@ setNameResolverStats s d = do writeIORef (rslvNotFound s) $! _rslvNotFound d writeIORef (rslvResolverErrs s) $! _rslvResolverErrs d writeIORef (rslvDisabled s) $! _rslvDisabled d + writeIORef (rslvRejected s) $! _rslvRejected d instance StrEncoding NameResolverStatsData where - strEncode NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} = + strEncode NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} = "reqs=" <> strEncode _rslvReqs <> "\nsucc=" @@ -1023,13 +1128,16 @@ instance StrEncoding NameResolverStatsData where <> strEncode _rslvResolverErrs <> "\ndisabled=" <> strEncode _rslvDisabled + <> "\nrejected=" + <> strEncode _rslvRejected strP = do _rslvReqs <- "reqs=" *> strP <* A.endOfLine _rslvSucc <- "succ=" *> strP <* A.endOfLine _rslvNotFound <- "notFound=" *> strP <* A.endOfLine _rslvResolverErrs <- "resolverErrs=" *> strP <* A.endOfLine _rslvDisabled <- "disabled=" *> strP - pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled} + _rslvRejected <- (A.endOfLine *> "rejected=" *> strP) <|> pure 0 + pure NameResolverStatsData {_rslvReqs, _rslvSucc, _rslvNotFound, _rslvResolverErrs, _rslvDisabled, _rslvRejected} data ServiceStats = ServiceStats { srvAssocNew :: IORef Int, diff --git a/src/Simplex/Messaging/Server/StatsStore.hs b/src/Simplex/Messaging/Server/StatsStore.hs new file mode 100644 index 000000000..cecf1394c --- /dev/null +++ b/src/Simplex/Messaging/Server/StatsStore.hs @@ -0,0 +1,465 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} + +module Simplex.Messaging.Server.StatsStore + ( StatsStore (..), + loadStats, + saveStats, +#if defined(dbServerPostgres) + getDBStats, +#endif + ) +where + +import qualified Control.Exception as E +import Control.Logger.Simple +import Control.Monad +import qualified Data.ByteString.Char8 as B +import qualified Data.Text as T +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Util (ifM, tshow) +import System.Directory (doesFileExist, removeFile, renameFile) +import UnliftIO.Exception (tryAny) +#if defined(dbServerPostgres) +import Control.Concurrent.STM (readTVarIO) +import Data.Bifunctor (bimap) +import Data.IORef (IORef) +import Data.Int (Int16, Int64) +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.List (find, intersperse) +import qualified Data.List.NonEmpty as L +import qualified Data.Map.Strict as M +import Data.Maybe (catMaybes) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import Database.PostgreSQL.Simple (Only (..), Query) +import qualified Database.PostgreSQL.Simple as DB +import Database.PostgreSQL.Simple.FromRow (FromRow (..), field) +import Database.PostgreSQL.Simple.ToField (ToField (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore (..), withTransaction) +import Simplex.Messaging.Util (toChunks, whenM) +import UnliftIO.Exception (isSyncException) +#endif + +data StatsStore + = StatsFile FilePath +#if defined(dbServerPostgres) + | StatsDB DBStore FilePath +#endif + +loadStats :: StatsStore -> IO (Maybe ServerStatsData) +loadStats = \case + StatsFile f -> ifM (doesFileExist f) (Just <$> readStatsFile f) (pure Nothing) +#if defined(dbServerPostgres) + StatsDB st f -> + getDBStats st >>= \case + Just d -> do + whenM (doesFileExist f) $ logWarn $ "server stats file " <> T.pack f <> " is ignored, stats are restored from the database" + pure $ Just d + Nothing -> ifM (doesFileExist f) (Just <$> importStatsFile st f) (pure Nothing) +#endif + +saveStats :: StatsStore -> ServerStats -> IO () +saveStats = \case + StatsFile f -> saveStatsFile f +#if defined(dbServerPostgres) + StatsDB st _ -> saveDBStats st +#endif + +readStatsFile :: FilePath -> IO ServerStatsData +readStatsFile f = do + logNote $ "restoring server stats from file " <> T.pack f + strDecode <$> B.readFile f >>= \case + Right d -> pure d + Left e -> E.throwIO $ userError $ "error parsing server stats file " <> f <> ": " <> e + +saveStatsFile :: FilePath -> ServerStats -> IO () +saveStatsFile f ss = do + d <- getServerStatsData ss + tryAny (B.writeFile tmp (strEncode d) >> renameFile tmp f) >>= \case + Right () -> pure () + Left e -> do + logError $ "error saving server stats to file " <> T.pack f <> ": " <> tshow e + void $ tryAny $ removeFile tmp + where + tmp = f <> ".tmp" + +#if defined(dbServerPostgres) +data PeriodSet = PSMsgDay | PSMsgWeek | PSMsgMonth | PSNtfDay | PSNtfWeek | PSNtfMonth + deriving (Bounded, Enum, Eq, Ord, Show) + +-- stored in server_stats_queues.period_set, the values must not change +periodSetId :: PeriodSet -> Int16 +periodSetId = \case + PSMsgDay -> 1 + PSMsgWeek -> 2 + PSMsgMonth -> 3 + PSNtfDay -> 4 + PSNtfWeek -> 5 + PSNtfMonth -> 6 + +instance ToField PeriodSet where + toField = toField . periodSetId + +periodSetFromId :: Int16 -> Maybe PeriodSet +periodSetFromId i = find ((i ==) . periodSetId) [minBound .. maxBound] + +periodSetHashes :: ServerStatsData -> PeriodSet -> IntSet +periodSetHashes ServerStatsData {_activeQueues = q, _activeQueuesNtf = n} = \case + PSMsgDay -> _day q + PSMsgWeek -> _week q + PSMsgMonth -> _month q + PSNtfDay -> _day n + PSNtfWeek -> _week n + PSNtfMonth -> _month n + +periodSetPending :: ServerStats -> PeriodSet -> Maybe (IORef PendingHashes) +periodSetPending ServerStats {activeQueues, activeQueuesNtf} = \case + PSMsgDay -> pendingDay <$> pendingPeriods activeQueues + PSMsgWeek -> pendingWeek <$> pendingPeriods activeQueues + PSMsgMonth -> pendingMonth <$> pendingPeriods activeQueues + PSNtfDay -> pendingDay <$> pendingPeriods activeQueuesNtf + PSNtfWeek -> pendingWeek <$> pendingPeriods activeQueuesNtf + PSNtfMonth -> pendingMonth <$> pendingPeriods activeQueuesNtf + +getDBStats :: DBStore -> IO (Maybe ServerStatsData) +getDBStats st = + withTransaction st $ \db -> + DB.query_ db selectStatsQuery >>= \case + StatsRow d : _ -> Just . withPeriodSets d <$> DB.fold_ db "SELECT period_set, queue_hash FROM server_stats_queues" M.empty addHash + [] -> pure Nothing + where + addHash sets (psId :: Int16, h :: Int64) = case periodSetFromId psId of + Just ps -> pure $! M.alter (Just . maybe (IS.singleton h') (IS.insert h')) ps sets + Nothing -> E.throwIO $ userError $ "unknown period_set " <> show psId + where + h' = fromIntegral h + withPeriodSets d sets = + d + { _activeQueues = periodData PSMsgDay PSMsgWeek PSMsgMonth, + _activeQueuesNtf = periodData PSNtfDay PSNtfWeek PSNtfMonth + } + where + periodData dp wp mp = PeriodStatsData {_day = get dp, _week = get wp, _month = get mp} + get p = M.findWithDefault IS.empty p sets + +importStatsFile :: DBStore -> FilePath -> IO ServerStatsData +importStatsFile st f = do + d <- readStatsFile f + withTransaction st $ \db -> do + void $ DB.execute_ db "DELETE FROM server_stats_queues" + forM_ [minBound .. maxBound] $ \ps -> insertHashes db ps $ periodSetHashes d ps + upsertStats db d + renameFile f $ f <> ".bak" + logNote "server stats imported to the database" + pure d + +saveDBStats :: DBStore -> ServerStats -> IO () +saveDBStats st ss = ifM (readTVarIO $ dbClosed st) (logWarn "server stats are not saved: database store is closed") $ E.mask $ \unmask -> do + taken <- fmap catMaybes $ forM [minBound .. maxBound] $ \ps -> + forM (periodSetPending ss ps) $ \ref -> (ps,ref,) <$> takePendingHashes ref + d <- getServerStatsData ss + E.try @E.SomeException (unmask $ withTransaction st $ \db -> mapM_ (savePending db) taken >> upsertStats db d) >>= \case + Right () -> pure () + Left e -> do + forM_ taken $ \(_, ref, p) -> restorePendingHashes ref p + if isSyncException e + then logError $ "error saving server stats to the database: " <> tshow e + else E.throwIO e + where + savePending db (ps, _, PendingHashes {pendingReset, pendingAdded}) = do + when pendingReset $ void $ DB.execute db "DELETE FROM server_stats_queues WHERE period_set = ?" (Only ps) + insertHashes db ps pendingAdded + +insertHashes :: DB.Connection -> PeriodSet -> IntSet -> IO () +insertHashes db ps hs = + forM_ (toChunks hashInsertBatch $ IS.toList hs) $ \hs' -> + void $ + DB.executeMany + db + "INSERT INTO server_stats_queues (period_set, queue_hash) VALUES (?, ?) ON CONFLICT DO NOTHING" + (map (\h -> (ps, fromIntegral h :: Int64)) $ L.toList hs') + +-- rows per INSERT statement, bounds the query size +hashInsertBatch :: Int +hashInsertBatch = 10000 + +upsertStats :: DB.Connection -> ServerStatsData -> IO () +upsertStats db d = do + savedAt <- systemSeconds <$> getSystemTime + void $ DB.execute db upsertStatsQuery $ savedAt : map (($ d) . snd) statsFields + +selectStatsQuery :: Query +selectStatsQuery = "SELECT " <> commaSep (map fst statsFields) <> " FROM server_stats WHERE server_stats_id = 1" + +upsertStatsQuery :: Query +upsertStatsQuery = + "INSERT INTO server_stats (server_stats_id, saved_at, " + <> commaSep cols + <> ") VALUES (1, ?, " + <> commaSep (map (const "?") cols) + <> ") ON CONFLICT (server_stats_id) DO UPDATE SET " + <> commaSep (map (\c -> c <> " = EXCLUDED." <> c) ("saved_at" : cols)) + where + cols = map fst statsFields + +commaSep :: [Query] -> Query +commaSep = mconcat . intersperse ", " + +-- the order must match the FromRow StatsRow instance +statsFields :: [(Query, ServerStatsData -> Int64)] +statsFields = + ("from_time", round . utcTimeToPOSIXSeconds . _fromTime) + : map + (fmap (fromIntegral .)) + ( [ ("q_created", _qCreated), + ("q_secured", _qSecured), + ("q_deleted_all", _qDeletedAll), + ("q_deleted_new", _qDeletedNew), + ("q_deleted_secured", _qDeletedSecured), + ("q_deleted_all_b", _qDeletedAllB), + ("q_blocked", _qBlocked), + ("q_sub", _qSub), + ("q_sub_all_b", _qSubAllB), + ("q_sub_auth", _qSubAuth), + ("q_sub_duplicate", _qSubDuplicate), + ("q_sub_prohibited", _qSubProhibited), + ("q_sub_end", _qSubEnd), + ("q_sub_end_b", _qSubEndB), + ("ntf_created", _ntfCreated), + ("ntf_new_created", _ntfNewCreated), + ("ntf_deleted", _ntfDeleted), + ("ntf_deleted_b", _ntfDeletedB), + ("ntf_sub", _ntfSub), + ("ntf_sub_b", _ntfSubB), + ("ntf_sub_auth", _ntfSubAuth), + ("ntf_sub_duplicate", _ntfSubDuplicate), + ("msg_sent", _msgSent), + ("msg_sent_auth", _msgSentAuth), + ("msg_sent_quota", _msgSentQuota), + ("msg_sent_large", _msgSentLarge), + ("msg_sent_block", _msgSentBlock), + ("msg_recv", _msgRecv), + ("msg_recv_get", _msgRecvGet), + ("msg_get", _msgGet), + ("msg_get_no_msg", _msgGetNoMsg), + ("msg_get_auth", _msgGetAuth), + ("msg_get_duplicate", _msgGetDuplicate), + ("msg_get_prohibited", _msgGetProhibited), + ("msg_expired", _msgExpired), + ("msg_sent_ntf", _msgSentNtf), + ("msg_recv_ntf", _msgRecvNtf), + ("msg_ntfs", _msgNtfs), + ("msg_ntfs_b", _msgNtfsB), + ("msg_ntf_no_sub", _msgNtfNoSub), + ("msg_ntf_lost", _msgNtfLost), + ("msg_ntf_expired", _msgNtfExpired) + ] + <> proxyFields "p_relays" _pRelays + <> proxyFields "p_relays_own" _pRelaysOwn + <> proxyFields "p_msg_fwds" _pMsgFwds + <> proxyFields "p_msg_fwds_own" _pMsgFwdsOwn + <> [("p_msg_fwds_recv", _pMsgFwdsRecv)] + <> serviceFields "rcv_services" _rcvServices + <> serviceFields "ntf_services" _ntfServices + <> map + (fmap (. _rslvStats)) + [ ("rslv_reqs", _rslvReqs), + ("rslv_succ", _rslvSucc), + ("rslv_not_found", _rslvNotFound), + ("rslv_resolver_errs", _rslvResolverErrs), + ("rslv_disabled", _rslvDisabled), + ("rslv_rejected", _rslvRejected) + ] + <> [ ("p_msg_fwds_below23", _pMsgFwdsBelow23), + ("p_msg_fwds_from23", _pMsgFwdsFrom23), + ("p_msg_fwds_recv_below23", _pMsgFwdsRecvBelow23), + ("p_msg_fwds_recv_from23", _pMsgFwdsRecvFrom23), + ("p_msg_fwds_relay_limit", _pMsgFwdsRelayLimit), + ("fwd_worker_cmds", _fwdWorkerCmds), + ("fwd_worker_cmd_ms", _fwdWorkerCmdMs), + ("fwd_worker_cmd_max_ms", _fwdWorkerCmdMaxMs) + ] + ) + where + proxyFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("requests", _pRequests), + ("successes", _pSuccesses), + ("errors_connect", _pErrorsConnect), + ("errors_compat", _pErrorsCompat), + ("errors_other", _pErrorsOther) + ] + serviceFields pfx sel = + map + (bimap ((pfx <> "_") <>) (. sel)) + [ ("assoc_new", _srvAssocNew), + ("assoc_duplicate", _srvAssocDuplicate), + ("assoc_updated", _srvAssocUpdated), + ("assoc_removed", _srvAssocRemoved), + ("sub_count", _srvSubCount), + ("sub_duplicate", _srvSubDuplicate), + ("sub_queues", _srvSubQueues), + ("sub_end", _srvSubEnd) + ] + +newtype StatsRow = StatsRow ServerStatsData + +instance FromRow StatsRow where + fromRow = do + _fromTime <- posixSecondsToUTCTime . fromIntegral <$> field @Int64 + _qCreated <- field + _qSecured <- field + _qDeletedAll <- field + _qDeletedNew <- field + _qDeletedSecured <- field + _qDeletedAllB <- field + _qBlocked <- field + _qSub <- field + _qSubAllB <- field + _qSubAuth <- field + _qSubDuplicate <- field + _qSubProhibited <- field + _qSubEnd <- field + _qSubEndB <- field + _ntfCreated <- field + _ntfNewCreated <- field + _ntfDeleted <- field + _ntfDeletedB <- field + _ntfSub <- field + _ntfSubB <- field + _ntfSubAuth <- field + _ntfSubDuplicate <- field + _msgSent <- field + _msgSentAuth <- field + _msgSentQuota <- field + _msgSentLarge <- field + _msgSentBlock <- field + _msgRecv <- field + _msgRecvGet <- field + _msgGet <- field + _msgGetNoMsg <- field + _msgGetAuth <- field + _msgGetDuplicate <- field + _msgGetProhibited <- field + _msgExpired <- field + _msgSentNtf <- field + _msgRecvNtf <- field + _msgNtfs <- field + _msgNtfsB <- field + _msgNtfNoSub <- field + _msgNtfLost <- field + _msgNtfExpired <- field + _pRelays <- proxyStatsP + _pRelaysOwn <- proxyStatsP + _pMsgFwds <- proxyStatsP + _pMsgFwdsOwn <- proxyStatsP + _pMsgFwdsRecv <- field + _rcvServices <- serviceStatsP + _ntfServices <- serviceStatsP + _rslvStats <- NameResolverStatsData <$> field <*> field <*> field <*> field <*> field <*> field + _pMsgFwdsBelow23 <- field + _pMsgFwdsFrom23 <- field + _pMsgFwdsRecvBelow23 <- field + _pMsgFwdsRecvFrom23 <- field + _pMsgFwdsRelayLimit <- field + _fwdWorkerCmds <- field + _fwdWorkerCmdMs <- field + _fwdWorkerCmdMaxMs <- field + pure $ + StatsRow + ServerStatsData + { _fromTime, + _qCreated, + _qSecured, + _qDeletedAll, + _qDeletedAllB, + _qDeletedNew, + _qDeletedSecured, + _qBlocked, + _qSub, + _qSubAllB, + _qSubAuth, + _qSubDuplicate, + _qSubProhibited, + _qSubEnd, + _qSubEndB, + _ntfCreated, + _ntfNewCreated, + _ntfDeleted, + _ntfDeletedB, + _ntfSub, + _ntfSubB, + _ntfSubAuth, + _ntfSubDuplicate, + _msgSent, + _msgSentAuth, + _msgSentQuota, + _msgSentLarge, + _msgSentBlock, + _msgRecv, + _msgRecvAckTimes = emptyTimeBuckets, + _msgRecvGet, + _msgGet, + _msgGetNoMsg, + _msgGetAuth, + _msgGetDuplicate, + _msgGetProhibited, + _msgExpired, + _activeQueues = newPeriodStatsData, + _msgSentNtf, + _msgRecvNtf, + _activeQueuesNtf = newPeriodStatsData, + _msgNtfs, + _msgNtfsB, + _msgNtfNoSub, + _msgNtfLost, + _msgNtfExpired, + _pRelays, + _pRelaysOwn, + _pMsgFwds, + _pMsgFwdsOwn, + _pMsgFwdsRecv, + _pMsgFwdsBelow23, + _pMsgFwdsFrom23, + _pMsgFwdsRecvBelow23, + _pMsgFwdsRecvFrom23, + _pMsgFwdsRelayLimit, + _ntfServices, + _rcvServices, + _rcvServicesSubMsg = 0, + _rcvServicesSubDuplicate = 0, + _authDelayExceeded = 0, + _cmdSlotWaits = 0, + _cmdSlotWaitMs = 0, + _cmdSlotWaitMaxMs = 0, + _cmdSlotWaitTimeouts = 0, + _fwdWorkerCmds, + _fwdWorkerCmdMs, + _fwdWorkerCmdMaxMs, + _qCount = 0, + _msgCount = 0, + _ntfCount = 0, + _rslvStats + } + where + proxyStatsP = ProxyStatsData <$> field <*> field <*> field <*> field <*> field + serviceStatsP = do + _srvAssocNew <- field + _srvAssocDuplicate <- field + _srvAssocUpdated <- field + _srvAssocRemoved <- field + _srvSubCount <- field + _srvSubDuplicate <- field + _srvSubQueues <- field + _srvSubEnd <- field + pure newServiceStatsData {_srvAssocNew, _srvAssocDuplicate, _srvAssocUpdated, _srvAssocRemoved, _srvSubCount, _srvSubDuplicate, _srvSubQueues, _srvSubEnd} +#endif diff --git a/src/Simplex/Messaging/Server/StoreLog.hs b/src/Simplex/Messaging/Server/StoreLog.hs index 4ceb3cddd..d12701ffc 100644 --- a/src/Simplex/Messaging/Server/StoreLog.hs +++ b/src/Simplex/Messaging/Server/StoreLog.hs @@ -19,6 +19,7 @@ module Simplex.Messaging.Server.StoreLog writeStoreLogRecord, logCreateQueue, logCreateLink, + logSwapLink, logDeleteLink, logSecureQueue, logUpdateKeys, @@ -66,6 +67,7 @@ import System.FilePath (takeDirectory, takeFileName) data StoreLogRecord = CreateQueue RecipientId QueueRec | CreateLink RecipientId LinkId QueueLinkData + | CreateLinkKeys RecipientId LinkId QueueLinkData (NonEmpty RcvPublicAuthKey) | DeleteLink RecipientId | SecureQueue QueueId SndPublicAuthKey | UpdateKeys RecipientId (NonEmpty RcvPublicAuthKey) @@ -83,6 +85,7 @@ data StoreLogRecord data SLRTag = CreateQueue_ | CreateLink_ + | CreateLinkKeys_ | DeleteLink_ | SecureQueue_ | UpdateKeys_ @@ -154,6 +157,7 @@ instance StrEncoding SLRTag where strEncode = \case CreateQueue_ -> "CREATE" CreateLink_ -> "LINK" + CreateLinkKeys_ -> "LKEYS" DeleteLink_ -> "LDELETE" SecureQueue_ -> "SECURE" UpdateKeys_ -> "KEYS" @@ -171,6 +175,7 @@ instance StrEncoding SLRTag where A.choice [ "CREATE" $> CreateQueue_, "LINK" $> CreateLink_, + "LKEYS" $> CreateLinkKeys_, "LDELETE" $> DeleteLink_, "SECURE" $> SecureQueue_, "KEYS" $> UpdateKeys_, @@ -189,6 +194,7 @@ instance StrEncoding StoreLogRecord where strEncode = \case CreateQueue rId q -> B.unwords [strEncode CreateQueue_, "rid=" <> strEncode rId, strEncode q] CreateLink rId lnkId d -> strEncode (CreateLink_, rId, lnkId, d) + CreateLinkKeys rId lnkId d rKeys -> strEncode (CreateLinkKeys_, rId, lnkId, d, rKeys) DeleteLink rId -> strEncode (DeleteLink_, rId) SecureQueue rId sKey -> strEncode (SecureQueue_, rId, sKey) UpdateKeys rId rKeys -> strEncode (UpdateKeys_, rId, rKeys) @@ -206,6 +212,7 @@ instance StrEncoding StoreLogRecord where strP_ >>= \case CreateQueue_ -> CreateQueue <$> ("rid=" *> strP_) <*> strP CreateLink_ -> CreateLink <$> strP_ <*> strP_ <*> strP + CreateLinkKeys_ -> CreateLinkKeys <$> strP_ <*> strP_ <*> strP_ <*> strP DeleteLink_ -> DeleteLink <$> strP SecureQueue_ -> SecureQueue <$> strP_ <*> strP UpdateKeys_ -> UpdateKeys <$> strP_ <*> strP @@ -253,6 +260,13 @@ logCreateQueue s rId q = writeStoreLogRecord s $ CreateQueue rId q logCreateLink :: StoreLog 'WriteMode -> RecipientId -> LinkId -> QueueLinkData -> IO () logCreateLink s rId lnkId d = writeStoreLogRecord s $ CreateLink rId lnkId d +logSwapLink :: StoreLog 'WriteMode -> RecipientId -> LinkId -> QueueLinkData -> Maybe (NonEmpty RcvPublicAuthKey) -> IO () +logSwapLink s rId lnkId d = \case + Just rKeys -> do + writeStoreLogRecord s $ CreateLinkKeys rId lnkId d rKeys + logUpdateKeys s rId rKeys + Nothing -> logCreateLink s rId lnkId d + logDeleteLink :: StoreLog 'WriteMode -> RecipientId -> IO () logDeleteLink s = writeStoreLogRecord s . DeleteLink diff --git a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs index 21a5470aa..1bb279882 100644 --- a/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs +++ b/src/Simplex/Messaging/Server/StoreLog/ReadWrite.hs @@ -20,10 +20,10 @@ import Data.Text.Encoding (decodeLatin1) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ASubscriberParty (..), ErrorType, RecipientId, SParty (..)) import Simplex.Messaging.Server.QueueStore (QueueRec, ServiceRec (..)) -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), STMService (..), withLoadedQueues) +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), STMService (..), restoreQueueLinkData, withLoadedQueues) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.StoreLog -import Simplex.Messaging.Util (tshow, ($>>=)) +import Simplex.Messaging.Util (tshow, ($>>), ($>>=)) import System.IO writeQueueStore :: forall q. StoreQueueClass q => StoreLog 'WriteMode -> STMQueueStore q -> IO () @@ -43,10 +43,11 @@ readQueueStore tty mkQ f st = readLogLines tty f $ \_ -> processLine procLogRecord :: StoreLogRecord -> IO () procLogRecord = \case CreateQueue rId qr -> addQueue_ st mkQ rId qr >>= qError rId "CreateQueue" - CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> addQueueLinkData st q lnkId d + CreateLink rId lnkId d -> withQueue rId "CreateLink" $ \q -> restoreQueueLinkData st q lnkId d + CreateLinkKeys rId lnkId d rKeys -> withQueue rId "CreateLinkKeys" $ \q -> restoreQueueLinkData st q lnkId d $>> updateKeys st q Nothing rKeys DeleteLink rId -> withQueue rId "DeleteLink" $ \q -> deleteQueueLinkData st q SecureQueue qId sKey -> withQueue qId "SecureQueue" $ \q -> secureQueue st q sKey - UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q rKeys + UpdateKeys rId rKeys -> withQueue rId "UpdateKeys" $ \q -> updateKeys st q Nothing rKeys AddNotifier qId ntfCreds -> withQueue qId "AddNotifier" $ \q -> addQueueNotifier st q ntfCreds SuspendQueue qId -> withQueue qId "SuspendQueue" $ suspendQueue st BlockQueue qId info -> withQueue qId "BlockQueue" $ \q -> blockQueue st q info diff --git a/src/Simplex/Messaging/ServiceScheme.hs b/src/Simplex/Messaging/ServiceScheme.hs index 904ab971e..08e5512ed 100644 --- a/src/Simplex/Messaging/ServiceScheme.hs +++ b/src/Simplex/Messaging/ServiceScheme.hs @@ -31,7 +31,7 @@ data SrvLoc = SrvLoc TransportHost ServiceName instance StrEncoding SrvLoc where strEncode (SrvLoc host port) - | null port = strEncode host + | null port = h | otherwise = h <> B.pack (':' : port) where h = case host of diff --git a/src/Simplex/Messaging/Transport.hs b/src/Simplex/Messaging/Transport.hs index ae99e0069..d6de161e4 100644 --- a/src/Simplex/Messaging/Transport.hs +++ b/src/Simplex/Messaging/Transport.hs @@ -35,6 +35,7 @@ module Simplex.Messaging.Transport ( -- * SMP transport parameters SMPVersion, VersionSMP, + pattern VersionSMP, VersionRangeSMP, THandleSMP, alpnSupportedSMPHandshakes, @@ -54,6 +55,7 @@ module Simplex.Messaging.Transport serverInfoSMPVersion, nameAvailSMPVersion, fwdNoncesSMPVersion, + linkSwapSMPVersion, simplexMQVersion, smpBlockSize, TransportConfig (..), @@ -77,6 +79,7 @@ module Simplex.Messaging.Transport ALPN, connectTLS, closeTLS, + recvTLS, defaultSupportedParams, defaultSupportedParamsHTTPS, withTlsUnique, @@ -107,6 +110,8 @@ module Simplex.Messaging.Transport where import Control.Applicative (optional) +import Control.Concurrent (threadDelay) +import Control.Concurrent.Async (async, cancel) import Control.Concurrent.STM import Control.Monad import Control.Monad.Except @@ -143,7 +148,7 @@ import Simplex.Messaging.Server.Information import Simplex.Messaging.SystemTime (SystemSeconds) import Simplex.Messaging.Transport.Buffer import Simplex.Messaging.Transport.Shared -import Simplex.Messaging.Util (bshow, catchOwn', liftEitherWith, stateTVar', (<$$>)) +import Simplex.Messaging.Util (bshow, catchAll_, catchOwn', catchOwn_, liftEitherWith, stateTVar', (<$$>)) import Simplex.Messaging.Version import Simplex.Messaging.Version.Internal import System.IO.Error (isEOFError) @@ -178,6 +183,7 @@ smpBlockSize = 16384 -- 21 - server public information in handshake (7/5/2026) -- 22 - RNAME answers name availability as well as the record (7/25/2026) -- 23 - version in forwarded command nonce, random nonce in forwarded responses (10/2/2026) +-- 24 - LSWP command to swap short link data and recipient keys, LCUR response, LSET refused with many recipient keys (10/28/2026) data SMPVersion @@ -219,6 +225,9 @@ nameAvailSMPVersion = VersionSMP 22 fwdNoncesSMPVersion :: VersionSMP fwdNoncesSMPVersion = VersionSMP 23 +linkSwapSMPVersion :: VersionSMP +linkSwapSMPVersion = VersionSMP 24 + minClientSMPRelayVersion :: VersionSMP minClientSMPRelayVersion = VersionSMP 15 @@ -226,10 +235,10 @@ minServerSMPRelayVersion :: VersionSMP minServerSMPRelayVersion = VersionSMP 15 currentClientSMPRelayVersion :: VersionSMP -currentClientSMPRelayVersion = VersionSMP 23 +currentClientSMPRelayVersion = VersionSMP 24 currentServerSMPRelayVersion :: VersionSMP -currentServerSMPRelayVersion = VersionSMP 23 +currentServerSMPRelayVersion = VersionSMP 24 -- Max SMP protocol version to be used in e2e encrypted connection between -- client and server, as defined by SMP proxy. Normally set below the current @@ -376,11 +385,18 @@ withTlsUnique cxt f = STServer -> T.getPeerFinished STClient -> T.getFinished +-- tls stores the receive record state lazily, so until the next record arrives it retains the last one (up to 16KB). +-- Reading the negotiated cipher forces it. +recvTLS :: T.Context -> IO ByteString +recvTLS cxt = T.recvData cxt <* T.contextGetInformation cxt + closeTLS :: T.Context -> IO () -closeTLS ctx = - T.bye ctx -- sometimes socket was closed before 'TLS.bye' so we catch the 'Broken pipe' error here - `E.finally` T.contextClose ctx - `catchOwn'` \_ -> pure () +closeTLS ctx = do + byeThread <- async $ T.bye ctx + threadDelay 50000 + T.contextClose ctx + threadDelay 150000 + cancel byeThread defaultSupportedParams :: T.Supported defaultSupportedParams = @@ -438,7 +454,7 @@ instance Transport TLS where -- this function may return less than requested number of bytes cGet :: TLS p -> Int -> IO ByteString cGet TLS {tlsContext, tlsBuffer, tlsTransportConfig = TransportConfig {transportTimeout = t_}} n = - getBuffered tlsBuffer n t_ (T.recvData tlsContext) + getBuffered tlsBuffer n t_ (recvTLS tlsContext) cPut :: TLS p -> ByteString -> IO () cPut TLS {tlsContext, tlsTransportConfig = TransportConfig {transportTimeout = t_}} = @@ -446,7 +462,7 @@ instance Transport TLS where getLn :: TLS p -> IO ByteString getLn TLS {tlsContext, tlsBuffer} = do - getLnBuffered tlsBuffer (T.recvData tlsContext) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] + getLnBuffered tlsBuffer (recvTLS tlsContext) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] where handleTlsEOF = \case T.PostHandshake T.Error_EOF -> E.throwIO TEBadBlock diff --git a/src/Simplex/Messaging/Transport/Client.hs b/src/Simplex/Messaging/Transport/Client.hs index 24dcc4483..6081d3d77 100644 --- a/src/Simplex/Messaging/Transport/Client.hs +++ b/src/Simplex/Messaging/Transport/Client.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Transport.Client ( runTransportClient, runTLSTransportClient, + runTLSTransportClient', smpClientHandshake, defaultSMPPort, defaultTcpConnectTimeout, @@ -164,14 +165,17 @@ data ConnectionHandle c | CHTransport (c 'TClient) runTLSTransportClient :: Transport c => T.Supported -> Maybe XS.CertificateStore -> TransportClientConfig -> Maybe SocksCredentials -> TransportHost -> ServiceName -> Maybe C.KeyHash -> (c 'TClient -> IO a) -> IO a -runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tcpKeepAlive, clientCredentials, clientALPN, useSNI} socksCreds host port keyHash client = do +runTLSTransportClient tlsParams caStore_ cfg socksCreds host port keyHash = runTLSTransportClient' tlsParams caStore_ cfg socksCreds host port keyHash . const + +runTLSTransportClient' :: Transport c => T.Supported -> Maybe XS.CertificateStore -> TransportClientConfig -> Maybe SocksCredentials -> TransportHost -> ServiceName -> Maybe C.KeyHash -> (IO (TransportHost, ServiceName) -> c 'TClient -> IO a) -> IO a +runTLSTransportClient' tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tcpKeepAlive, clientCredentials, clientALPN, useSNI} socksCreds host port keyHash client = do serverCert <- newEmptyTMVarIO clientCredsSent <- newIORef False let hostName = B.unpack $ strEncode host clientParams = mkTLSClientParams tlsParams caStore_ hostName port keyHash clientCredentials clientCredsSent clientALPN useSNI serverCert - connectTCP = case socksProxy of - Just proxy -> connectSocksClient proxy socksCreds (hostAddr host) - _ -> connectTCPClient hostName + (connectTCP, connectedAddress) = case socksProxy of + Just proxy -> (connectSocksClient proxy socksCreds (hostAddr host), \_ -> pure (host, show $ socksPort port)) + _ -> (connectTCPClient hostName, fmap peerAddress . getPeerName) h <- newIORef Nothing let set hc = (>>= \c -> writeIORef h (Just $ hc c) $> c) E.bracket (set CHSocket $ connectTCP port) (\_ -> closeConn h) $ \sock -> do @@ -181,9 +185,9 @@ runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, tls <- set CHContext $ connectTLS (Just hostName) tCfg clientParams sock chain <- takePeerCertChain serverCert sent <- readIORef clientCredsSent - client =<< set CHTransport (getTransportConnection tCfg sent chain tls) + client (connectedAddress sock) =<< set CHTransport (getTransportConnection tCfg sent chain tls) where - closeConn = readIORef >=> mapM_ (\c -> E.uninterruptibleMask_ $ closeConn_ c `catchAll_` pure ()) + closeConn = readIORef >=> mapM_ (\c -> closeConn_ c `catchAll_` pure ()) closeConn_ = \case CHSocket sock -> close sock CHContext tls -> closeTLS tls @@ -193,6 +197,14 @@ runTLSTransportClient tlsParams caStore_ cfg@TransportClientConfig {socksProxy, THIPv6 addr -> SocksAddrIPV6 addr THOnionHost h -> SocksAddrDomainName h THDomainName h -> SocksAddrDomainName $ B.pack h + peerAddress = \case + SockAddrInet p addr -> (THIPv4 $ unifyLoopback $ hostAddressToTuple addr, show p) + SockAddrInet6 p _ (0, 0, 0xffff, addr) _ -> peerAddress $ SockAddrInet p $ toHostAddress $ toIPv4w addr + SockAddrInet6 p _ addr _ -> (THIPv6 addr, show p) + _ -> (host, port) + unifyLoopback = \case + (127, _, _, _) -> (127, 0, 0, 1) + addr -> addr connectTCPClient :: HostName -> ServiceName -> IO Socket connectTCPClient host port = withSocketsDo $ resolve >>= tryOpen err @@ -221,11 +233,28 @@ defaultSMPPort :: PortNumber defaultSMPPort = 5223 connectSocksClient :: SocksProxy -> Maybe SocksCredentials -> SocksHostAddress -> ServiceName -> IO Socket -connectSocksClient (SocksProxy addr) socksCreds hostAddr _port = do +connectSocksClient proxy socksCreds hostAddr _port = do let port = if null _port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe _port - fst <$> case socksCreds of - Just creds -> socksConnectAuth (defaultSocksConf addr) (SocksAddress hostAddr port) creds - _ -> socksConnect (defaultSocksConf addr) (SocksAddress hostAddr port) + destAddr = SocksAddress hostAddr port + E.bracketOnError connectProxy close $ \sock -> do + conf <- defaultSocksConf <$> getPeerName sock + sock <$ case socksCreds of + Just creds -> socksConnectWithSocketAuth sock conf destAddr creds + _ -> socksConnectWithSocket sock conf destAddr + where + -- socksConnect from Network.Socks5 always opens IPv4 socket + connectProxy = case proxy of + SocksProxy addr -> + E.bracketOnError (socket (sockFamily addr) Stream defaultProtocol) close $ \sock -> + connect sock addr $> sock + SocksProxyDomain host port -> connectTCPClient host (show port) + sockFamily = \case + SockAddrInet {} -> AF_INET + SockAddrInet6 {} -> AF_INET6 + SockAddrUnix {} -> AF_UNIX + +socksPort :: ServiceName -> PortNumber +socksPort port = if null port then defaultSMPPort else fromMaybe defaultSMPPort $ readMaybe port defaultSocksHost :: (Word8, Word8, Word8, Word8) defaultSocksHost = (127, 0, 0, 1) @@ -236,7 +265,9 @@ defaultSocksProxyWithAuth = SocksProxyWithAuth SocksIsolateByAuth defaultSocksPr defaultSocksProxy :: SocksProxy defaultSocksProxy = SocksProxy $ SockAddrInet 9050 $ tupleToHostAddress defaultSocksHost -newtype SocksProxy = SocksProxy SockAddr +data SocksProxy + = SocksProxy SockAddr + | SocksProxyDomain HostName PortNumber deriving (Eq) data SocksProxyWithAuth = SocksProxyWithAuth SocksAuth SocksProxy @@ -248,19 +279,23 @@ data SocksAuth | SocksIsolateByAuth -- this is default deriving (Eq, Show) -instance Show SocksProxy where show (SocksProxy addr) = show addr +instance Show SocksProxy where + show = \case + SocksProxy addr -> show addr + SocksProxyDomain host port -> host <> ":" <> show port instance StrEncoding SocksProxy where strEncode = B.pack . show strP = do host <- fromMaybe (THIPv4 defaultSocksHost) <$> optional strP port <- fromMaybe 9050 <$> optional (A.char ':' *> (fromInteger <$> A.decimal)) - SocksProxy <$> socksAddr port host + socksProxyP port host where - socksAddr port = \case - THIPv4 addr -> pure $ SockAddrInet port $ tupleToHostAddress addr - THIPv6 addr -> pure $ SockAddrInet6 port 0 addr 0 - _ -> fail "SOCKS5 host should be IPv4 or IPv6 address" + socksProxyP port = \case + THIPv4 addr -> pure $ SocksProxy $ SockAddrInet port $ tupleToHostAddress addr + THIPv6 addr -> pure $ SocksProxy $ SockAddrInet6 port 0 addr 0 + THDomainName host -> pure $ SocksProxyDomain host port + THOnionHost _ -> fail "SOCKS5 host cannot be onion address" instance StrEncoding SocksProxyWithAuth where strEncode (SocksProxyWithAuth auth proxy) = strEncode auth <> strEncode proxy diff --git a/src/Simplex/Messaging/Transport/HTTP2/Client.hs b/src/Simplex/Messaging/Transport/HTTP2/Client.hs index 170e8740f..5fa7dd971 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/Client.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/Client.hs @@ -44,7 +44,7 @@ import Simplex.Messaging.Protocol (NetworkError (..), toNetworkError) import Simplex.Messaging.Transport (ALPN, STransportPeer (..), SessionId, TLS (tlsALPN, tlsPeerCert, tlsUniq), TransportPeer (..), TransportPeerI (..), getServerVerifyKey) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTcpConnectTimeout, runTLSTransportClient) import Simplex.Messaging.Transport.HTTP2 -import Simplex.Messaging.Util (eitherToMaybe) +import Simplex.Messaging.Util (eitherToMaybe, whenM) import UnliftIO.STM import UnliftIO.Timeout @@ -65,7 +65,7 @@ data HClient = HClient host :: TransportHost, port :: ServiceName, config :: HTTP2ClientConfig, - reqQ :: TBQueue (Request, TMVar HTTP2Response) + reqQ :: TBQueue (Request, TVar Bool, TMVar HTTP2Response) } data HTTP2Response = HTTP2Response @@ -175,8 +175,8 @@ getVerifiedHTTP2ClientWith config host port disconnected setup = process :: HTTP2Client -> H.Client HTTP2Response process HTTP2Client {client_ = HClient {reqQ}} sendReq = forever $ do - (req, respVar) <- atomically $ readTBQueue reqQ - sendReq req $ \r -> do + (req, pending, respVar) <- atomically $ readTBQueue reqQ + whenM (readTVarIO pending) . void . sendReq req $ \r -> do respBody <- getHTTP2Body r (bodyHeadSize config) let resp = HTTP2Response {response = r, respBody} atomically $ putTMVar respVar resp @@ -184,14 +184,15 @@ getVerifiedHTTP2ClientWith config host port disconnected setup = -- | Disconnects client from the server and terminates client threads. closeHTTP2Client :: HTTP2Client -> IO () -closeHTTP2Client = mapM_ uninterruptibleCancel . action +closeHTTP2Client = mapM_ (void . async . cancel) . action sendRequest :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) sendRequest HTTP2Client {client_ = HClient {config, reqQ}} req reqTimeout_ = do resp <- newEmptyTMVarIO - atomically $ writeTBQueue reqQ (req, resp) + pending <- newTVarIO True let reqTimeout = http2RequestTimeout config reqTimeout_ - maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` atomically (takeTMVar resp)) + maybe (Left HCResponseTimeout) Right <$> (reqTimeout `timeout` (atomically (writeTBQueue reqQ (req, pending, resp)) >> atomically (takeTMVar resp))) + `E.finally` atomically (writeTVar pending False) -- | this function should not be used until HTTP2 is thread safe, use sendRequest sendRequestDirect :: HTTP2Client -> Request -> Maybe Int -> IO (Either HTTP2ClientError HTTP2Response) diff --git a/src/Simplex/Messaging/Transport/HTTP2/File.hs b/src/Simplex/Messaging/Transport/HTTP2/File.hs index 8e65c1cc3..e35476529 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/File.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/File.hs @@ -2,7 +2,7 @@ module Simplex.Messaging.Transport.HTTP2.File ( fileBlockSize, - hReceiveFile, + receiveFileBlocks, hSendFile, getFileChunk, ) where @@ -18,16 +18,16 @@ import System.IO (Handle) fileBlockSize :: Int fileBlockSize = 16384 -hReceiveFile :: (Int -> IO ByteString) -> Handle -> Word32 -> IO Int64 -hReceiveFile _ _ 0 = pure 0 -hReceiveFile getBody h size = get $ fromIntegral size +receiveFileBlocks :: (Int -> IO ByteString) -> (ByteString -> IO ()) -> Word32 -> IO Int64 +receiveFileBlocks _ _ 0 = pure 0 +receiveFileBlocks getBody write size = get $ fromIntegral size where get sz = do ch <- getBody fileBlockSize let chSize = fromIntegral $ B.length ch if | chSize > sz -> pure (chSize - sz) - | chSize > 0 -> B.hPut h ch >> get (sz - chSize) + | chSize > 0 -> write ch >> get (sz - chSize) | otherwise -> pure (-sz) hSendFile :: Handle -> (Builder -> IO ()) -> Word32 -> IO () diff --git a/src/Simplex/Messaging/Transport/HTTP2/Server.hs b/src/Simplex/Messaging/Transport/HTTP2/Server.hs index 23a99e43c..704f3b21f 100644 --- a/src/Simplex/Messaging/Transport/HTTP2/Server.hs +++ b/src/Simplex/Messaging/Transport/HTTP2/Server.hs @@ -6,7 +6,8 @@ module Simplex.Messaging.Transport.HTTP2.Server where import Control.Concurrent.Async (Async, async, uninterruptibleCancel) import Control.Concurrent.STM import Control.Monad -import Data.Time.Clock.System (getSystemTime, systemSeconds) +import Data.Maybe (catMaybes) +import Data.Time.Clock.System (SystemTime, getSystemTime, systemSeconds) import Network.HPACK (BufferSize) import Network.HTTP2.Server (Request, Response) import qualified Network.HTTP2.Server as H @@ -16,10 +17,10 @@ import Numeric.Natural (Natural) import Simplex.Messaging.Server.Expiration import Simplex.Messaging.Transport (ALPN, SessionId, TLS, tlsALPN, tlsUniq) import Simplex.Messaging.Transport.HTTP2 -import Simplex.Messaging.Transport.Server (ReloadableCredential, SNICredentialUsed, ServerCredentials, TLSServerCredential (..), TransportServerConfig (..), loadServerCredential, newSocketState, runTransportServerState_) -import Simplex.Messaging.Util (threadDelay') -import UnliftIO (finally) -import UnliftIO.Concurrent (forkIO, killThread, myThreadId) +import Simplex.Messaging.Transport.Server (ReloadableCredential, SNICredentialUsed, ServerCredentials, SocketState, TLSServerCredential (..), TransportServerConfig (..), loadServerCredential, newSocketState, runTransportServerState_) +import Simplex.Messaging.Util (threadDelay', unlessM) +import UnliftIO (bracket_, finally) +import UnliftIO.Concurrent (forkIO, killThread, myThreadId, threadDelay) type HTTP2ServerFunc = SessionId -> Maybe ALPN -> Request -> (Response -> IO ()) -> IO () @@ -54,7 +55,7 @@ getHTTP2Server HTTP2ServerConfig {qSize, http2Port, bufferSize, bodyHeadSize, se started <- newEmptyTMVarIO reqQ <- newTBQueueIO qSize action <- async $ - runHTTP2Server started http2Port bufferSize serverSupported srvCreds Nothing transportConfig Nothing (const $ pure ()) $ \_sniUsed sessionId sessionALPN r sendResponse -> do + newSocketState >>= \ss -> runHTTP2Server ss started http2Port bufferSize serverSupported srvCreds Nothing transportConfig Nothing (const $ pure ()) $ \_sniUsed _closeSession sessionId sessionALPN r sendResponse -> do reqBody <- getHTTP2Body r bodyHeadSize atomically $ writeTBQueue reqQ HTTP2Request {sessionId, sessionALPN, request = r, reqBody, sendResponse} void . atomically $ takeTMVar started @@ -63,11 +64,10 @@ getHTTP2Server HTTP2ServerConfig {qSize, http2Port, bufferSize, bodyHeadSize, se closeHTTP2Server :: HTTP2Server -> IO () closeHTTP2Server = uninterruptibleCancel . action -runHTTP2Server :: TMVar Bool -> ServiceName -> BufferSize -> T.Supported -> T.Credential -> Maybe ReloadableCredential -> TransportServerConfig -> Maybe ExpirationConfig -> (SessionId -> IO ()) -> (SNICredentialUsed -> HTTP2ServerFunc) -> IO () -runHTTP2Server started port bufferSize srvSupported srvCreds httpCreds_ transportConfig expCfg_ clientFinished = runHTTP2ServerWith_ expCfg_ clientFinished bufferSize setup +runHTTP2Server :: SocketState -> TMVar Bool -> ServiceName -> BufferSize -> T.Supported -> T.Credential -> Maybe ReloadableCredential -> TransportServerConfig -> Maybe ExpirationConfig -> (SessionId -> IO ()) -> (SNICredentialUsed -> IO () -> HTTP2ServerFunc) -> IO () +runHTTP2Server ss started port bufferSize srvSupported srvCreds httpCreds_ transportConfig expCfg_ clientFinished = runHTTP2ServerWith_ expCfg_ (Just $ firstRequestTimeout transportConfig) clientFinished bufferSize setup where setup handler = do - ss <- newSocketState let combinedCreds = TLSServerCredential {credential = srvCreds, sniCredential = httpCreds_} runTransportServerState_ ss started port srvSupported combinedCreds transportConfig $ \_ -> handler @@ -75,28 +75,53 @@ runHTTP2Server started port bufferSize srvSupported srvCreds httpCreds_ transpor runHTTP2ServerWith :: BufferSize -> ((TLS p -> IO ()) -> a) -> HTTP2ServerFunc -> a runHTTP2ServerWith bufferSize tlsSetup http2Server = runHTTP2ServerWith_ + Nothing Nothing (\_sessId -> pure ()) bufferSize (\handler -> tlsSetup $ \tls -> handler (False, tls)) - (const http2Server) + (\_ _ -> http2Server) -runHTTP2ServerWith_ :: Maybe ExpirationConfig -> (SessionId -> IO ()) -> BufferSize -> (((SNICredentialUsed, TLS p) -> IO ()) -> a) -> (SNICredentialUsed -> HTTP2ServerFunc) -> a -runHTTP2ServerWith_ expCfg_ clientFinished bufferSize setup http2Server = setup $ \(sniUsed, tls) -> do - activeAt <- newTVarIO =<< getSystemTime +runHTTP2ServerWith_ :: Maybe ExpirationConfig -> Maybe Int -> (SessionId -> IO ()) -> BufferSize -> (((SNICredentialUsed, TLS p) -> IO ()) -> a) -> (SNICredentialUsed -> IO () -> HTTP2ServerFunc) -> a +runHTTP2ServerWith_ expCfg_ firstRequestTimeout_ clientFinished bufferSize setup http2Server = setup $ \(sniUsed, tls) -> do + activity <- newClientActivity sessionThread <- myThreadId - tid_ <- mapM (forkIO . expireInactiveClient sessionThread activeAt) expCfg_ - withHTTP2 bufferSize (run sniUsed tls activeAt) (clientFinished $ tlsUniq tls) tls `finally` mapM_ killThread tid_ + tids <- + sequence $ + catMaybes + [ forkIO . expireInactiveClient sessionThread activity <$> expCfg_, + forkIO . closeWithoutRequest sessionThread activity <$> firstRequestTimeout_ + ] + withHTTP2 bufferSize (run sniUsed tls sessionThread activity) (clientFinished $ tlsUniq tls) tls `finally` mapM_ killThread tids where - run sniUsed tls activeAt cfg = H.run cfg $ \req _aux sendResp -> do - getSystemTime >>= atomically . writeTVar activeAt - http2Server sniUsed (tlsUniq tls) (tlsALPN tls) req (`sendResp` []) - expireInactiveClient sessionThread activeAt expCfg = loop + run sniUsed tls sessionThread activity cfg = H.run cfg $ \req _aux sendResp -> + trackRequest activity $ http2Server sniUsed (killThread sessionThread) (tlsUniq tls) (tlsALPN tls) req (`sendResp` []) + expireInactiveClient sessionThread ClientActivity {requestsInFlight, idleSince} expCfg = loop where loop = do threadDelay' $ checkInterval expCfg * 1000000 old <- expireBeforeEpoch expCfg - ts <- readTVarIO activeAt - if systemSeconds ts < old + (n, ts) <- atomically $ (,) <$> readTVar requestsInFlight <*> readTVar idleSince + if n == 0 && systemSeconds ts < old then killThread sessionThread else loop + closeWithoutRequest sessionThread ClientActivity {requestStarted} t = do + threadDelay t + unlessM (readTVarIO requestStarted) $ killThread sessionThread + +data ClientActivity = ClientActivity + { requestStarted :: TVar Bool, + requestsInFlight :: TVar Int, + idleSince :: TVar SystemTime + } + +newClientActivity :: IO ClientActivity +newClientActivity = ClientActivity <$> newTVarIO False <*> newTVarIO 0 <*> (newTVarIO =<< getSystemTime) + +trackRequest :: ClientActivity -> IO a -> IO a +trackRequest ClientActivity {requestStarted, requestsInFlight, idleSince} = bracket_ started ended + where + started = atomically $ writeTVar requestStarted True >> modifyTVar' requestsInFlight (+ 1) + ended = do + ts <- getSystemTime + atomically $ modifyTVar' requestsInFlight (subtract 1) >> writeTVar idleSince ts diff --git a/src/Simplex/Messaging/Transport/KeepAlive.hs b/src/Simplex/Messaging/Transport/KeepAlive.hs index 1d34a27f0..c6e6d461a 100644 --- a/src/Simplex/Messaging/Transport/KeepAlive.hs +++ b/src/Simplex/Messaging/Transport/KeepAlive.hs @@ -10,6 +10,7 @@ module Simplex.Messaging.Transport.KeepAlive setSocketKeepAlive, ) where +import Control.Monad (when) import qualified Data.Aeson.TH as J import Foreign.C (CInt (..)) import Network.Socket @@ -18,7 +19,8 @@ import Simplex.Messaging.Parsers (defaultJSON) data KeepAliveOpts = KeepAliveOpts { keepIdle :: Int, keepIntvl :: Int, - keepCnt :: Int + keepCnt :: Int, + unackedDataTimeout :: Maybe Bool } deriving (Eq, Show) @@ -27,7 +29,8 @@ defaultKeepAliveOpts = KeepAliveOpts { keepIdle = 30, keepIntvl = 15, - keepCnt = 4 + keepCnt = 4, + unackedDataTimeout = Nothing } _SOL_TCP :: CInt @@ -63,11 +66,21 @@ foreign import capi "netinet/tcp.h value TCP_KEEPCNT" _TCP_KEEPCNT :: CInt #endif +setSocketUnackedDataTimeout :: Socket -> Int -> IO () +#if defined(mingw32_HOST_OS) || defined(darwin_HOST_OS) +setSocketUnackedDataTimeout _ _ = pure () +#else +foreign import capi "netinet/tcp.h value TCP_USER_TIMEOUT" _TCP_USER_TIMEOUT :: CInt + +setSocketUnackedDataTimeout sock seconds = setSocketOption sock (SockOpt _SOL_TCP _TCP_USER_TIMEOUT) (seconds * 1000) +#endif + setSocketKeepAlive :: Socket -> KeepAliveOpts -> IO () -setSocketKeepAlive sock KeepAliveOpts {keepCnt, keepIdle, keepIntvl} = do +setSocketKeepAlive sock KeepAliveOpts {keepCnt, keepIdle, keepIntvl, unackedDataTimeout} = do setSocketOption sock KeepAlive 1 setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPIDLE) keepIdle setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPINTVL) keepIntvl setSocketOption sock (SockOpt _SOL_TCP _TCP_KEEPCNT) keepCnt + when (unackedDataTimeout == Just True) $ setSocketUnackedDataTimeout sock $ keepIdle + keepIntvl * keepCnt $(J.deriveJSON defaultJSON ''KeepAliveOpts) diff --git a/src/Simplex/Messaging/Transport/Server.hs b/src/Simplex/Messaging/Transport/Server.hs index 7915f64b3..c45724e7a 100644 --- a/src/Simplex/Messaging/Transport/Server.hs +++ b/src/Simplex/Messaging/Transport/Server.hs @@ -73,8 +73,9 @@ import GHC.IO.Exception (IOException, ioe_errno) import Network.Socket import qualified Network.TLS as T import Simplex.Messaging.Transport +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts, setSocketKeepAlive) import Simplex.Messaging.Transport.Shared -import Simplex.Messaging.Util (catchAll_, labelMyThread, stateTVar', tshow, unlessM) +import Simplex.Messaging.Util (catchAll, catchAll_, labelMyThread, stateTVar', tshow, unlessM) import System.Exit (exitFailure) import System.IO.Error (tryIOError) import System.Mem.Weak (Weak, deRefWeak) @@ -90,6 +91,9 @@ data TransportServerConfig = TransportServerConfig addCORSHeaders :: Bool, tlsSetupTimeout :: Int, transportTimeout :: Int, + firstRequestTimeout :: Int, + tcpKeepAlive :: Maybe KeepAliveOpts, + tcpUserTimeout :: Maybe Int, credentialCheckInterval :: Int } deriving (Eq, Show) @@ -144,6 +148,9 @@ mkTransportServerConfig logTLSErrors serverALPN askClientCert = addCORSHeaders = False, tlsSetupTimeout = 60000000, transportTimeout = 40000000, + firstRequestTimeout = 60000000, + tcpKeepAlive = Nothing, + tcpUserTimeout = Nothing, credentialCheckInterval = defaultCredentialCheckInterval } @@ -179,6 +186,7 @@ runTransportServerSocket started getSocket threadLabel srvParams cfg server = do where tCfg = serverTransportConfig cfg setupTLS conn = do + setServerSocketOptions cfg conn tls <- connectTLS Nothing tCfg srvParams conn (False,) <$> getTransportConnection tCfg True (X.CertificateChain []) tls @@ -191,6 +199,7 @@ runTransportServerSocketState ss started getSocket threadLabel srvSupported srvC runServer = runTransportServerSocketState_ ss started getSocket threadLabel (tlsSetupTimeout cfg) setupTLS server tCfg = serverTransportConfig cfg setupTLS conn = do + setServerSocketOptions cfg conn sniUsed <- newTVarIO False let srvParams = supportedTLSServerParams srvSupported srvCreds sniUsed $ serverALPN cfg h <- setupTLS_ srvParams @@ -207,6 +216,12 @@ runTransportServerSocketState ss started getSocket threadLabel srvSupported srvC tls <- connectTLS Nothing tCfg srvParams conn getTransportConnection tCfg True (X.CertificateChain []) tls +setServerSocketOptions :: TransportServerConfig -> Socket -> IO () +setServerSocketOptions TransportServerConfig {tcpKeepAlive, tcpUserTimeout} conn = do + mapM_ (setSocketKeepAlive conn) tcpKeepAlive `catchAll` \e -> logError ("Error setting TCP keep-alive " <> tshow e) + when (isSupportedSocketOption UserTimeout) $ + mapM_ (setSocketOption conn UserTimeout) tcpUserTimeout `catchAll` \e -> logError ("Error setting TCP user timeout " <> tshow e) + -- | Run a transport server with provided connection setup and handler. runTransportServerSocketState_ :: Transport c => SocketState -> TMVar Bool -> IO Socket -> String -> Int -> (Socket -> IO (SNICredentialUsed, c 'TServer)) -> (Socket -> (SNICredentialUsed, c 'TServer) -> IO ()) -> IO () runTransportServerSocketState_ ss started getSocket threadLabel tlsSetupTimeout setupTLS server = do @@ -296,8 +311,7 @@ startTCPServer started host port = withSocketsDo $ resolve >>= open >>= setStart select as = fromJust $ family AF_INET6 <|> family AF_INET where family f = find ((== f) . addrFamily) as - open addr = do - sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) + open addr = E.bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close $ \sock -> do setSocketOption sock ReuseAddr 1 withFdSocket sock setCloseOnExecIfNeeded logNote $ "binding to " <> tshow (addrAddress addr) diff --git a/src/Simplex/Messaging/Transport/WebSockets.hs b/src/Simplex/Messaging/Transport/WebSockets.hs index 3ab213dcd..700e449b4 100644 --- a/src/Simplex/Messaging/Transport/WebSockets.hs +++ b/src/Simplex/Messaging/Transport/WebSockets.hs @@ -27,6 +27,7 @@ import Simplex.Messaging.Transport STransportPeer (..), TransportPeerI (..), closeTLS, + recvTLS, smpBlockSize, withTlsUnique, ) @@ -106,7 +107,7 @@ makeTLSContextStream cxt = S.makeStream readStream writeStream where readStream :: IO (Maybe ByteString) - readStream = (Just <$> T.recvData cxt) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] + readStream = (Just <$> recvTLS cxt) `E.catches` [E.Handler handleTlsEOF, E.Handler handleEOF] where handleTlsEOF = \case T.PostHandshake T.Error_EOF -> pure Nothing diff --git a/src/Simplex/Messaging/Util.hs b/src/Simplex/Messaging/Util.hs index de7ba9236..7b2f2cd5d 100644 --- a/src/Simplex/Messaging/Util.hs +++ b/src/Simplex/Messaging/Util.hs @@ -41,10 +41,12 @@ module Simplex.Messaging.Util isAsyncCancellation, catchOwn', catchOwn, + catchOwn_, tryAllOwnErrors, tryAllOwnErrors', catchAllOwnErrors, catchAllOwnErrors', + forceDecoded, eitherToMaybe, listToEither, firstRow, @@ -59,6 +61,7 @@ module Simplex.Messaging.Util safeDecodeUtf8, timeoutThrow, threadDelay', + delayUntilDayTime, diffToMicroseconds, diffToMilliseconds, labelMyThread, @@ -95,7 +98,7 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import qualified Data.Text.IO as T -import Data.Time (NominalDiffTime) +import Data.Time (NominalDiffTime, diffTimeToPicoseconds, getCurrentTime, utctDayTime) import Data.Tuple (swap) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) @@ -335,6 +338,10 @@ catchOwn action handleInternal = run action `E.catch` \e -> if isAsyncCancellation e then E.throwIO e else run (handleInternal e) {-# INLINE catchOwn #-} +catchOwn_ :: IO a -> IO a -> IO a +catchOwn_ a = catchOwn' a . const +{-# INLINE catchOwn_ #-} + tryAllOwnErrors :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> ExceptT e m (Either e a) tryAllOwnErrors action = ExceptT $ Right <$> runExceptT action `catchOwn` (pure . Left . fromSomeException) {-# INLINE tryAllOwnErrors #-} @@ -351,6 +358,9 @@ catchAllOwnErrors' :: (AnyError e, MonadUnliftIO m) => ExceptT e m a -> (e -> m catchAllOwnErrors' action handler = tryAllOwnErrors' action >>= either handler pure {-# INLINE catchAllOwnErrors' #-} +forceDecoded :: (a -> Int) -> Either String a -> Either String a +forceDecoded force r = either (Left . show) (const r) $ pureTry $ either length force r + eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just {-# INLINE eitherToMaybe #-} @@ -415,6 +425,11 @@ threadDelay' = loop threadDelay $ fromIntegral maxWait loop $ time - maxWait +delayUntilDayTime :: Int64 -> IO () +delayUntilDayTime startAt = do + initialDelay <- (startAt -) . fromIntegral . (`div` 1000000000000) . diffTimeToPicoseconds . utctDayTime <$> getCurrentTime + threadDelay' $ 1000000 * (initialDelay + if initialDelay < 0 then 86400 else 0) + diffToMicroseconds :: NominalDiffTime -> Int64 diffToMicroseconds diff = truncate $ diff * 1000000 {-# INLINE diffToMicroseconds #-} diff --git a/src/Simplex/RemoteControl/Discovery.hs b/src/Simplex/RemoteControl/Discovery.hs index baff4adaa..ae11dd7f3 100644 --- a/src/Simplex/RemoteControl/Discovery.hs +++ b/src/Simplex/RemoteControl/Discovery.hs @@ -36,7 +36,7 @@ import Simplex.Messaging.Transport (TransportPeer (..), defaultSupportedParams) import qualified Simplex.Messaging.Transport as Transport import Simplex.Messaging.Transport.Client (TransportHost (..)) import Simplex.Messaging.Transport.Server (mkTransportServerConfig, runTransportServerSocket, startTCPServer) -import Simplex.Messaging.Util (ifM, tshow) +import Simplex.Messaging.Util (tshow) import Simplex.RemoteControl.Discovery.Multicast (setMembership) import Simplex.RemoteControl.Types import UnliftIO @@ -80,11 +80,9 @@ preferAddress RCCtrlAddress {address, interface} addrs = startTLSServer :: Maybe Word16 -> TMVar (Maybe N.PortNumber) -> TLS.Credential -> TLS.ServerHooks -> (Transport.TLS 'TServer -> IO ()) -> IO (Async ()) startTLSServer port_ startedOnPort credentials hooks server = async . liftIO $ do started <- newEmptyTMVarIO - bracketOnError (startTCPServer started Nothing $ maybe "0" show port_) (\_e -> setPort Nothing) $ \socket -> - ifM - (atomically $ readTMVar started) - (runServer started socket) - (setPort Nothing) + -- Acquisition can fail before the listener has a port to report. + (bracketOnError (startTCPServer started Nothing $ maybe "0" show port_) N.close $ runServer started) + `finally` setPort Nothing where runServer started socket = do port <- N.socketPort socket diff --git a/src/Simplex/RemoteControl/Invitation.hs b/src/Simplex/RemoteControl/Invitation.hs index 480838c31..e12786235 100644 --- a/src/Simplex/RemoteControl/Invitation.hs +++ b/src/Simplex/RemoteControl/Invitation.hs @@ -26,6 +26,7 @@ import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) +import Simplex.Messaging.ServiceScheme (SrvLoc (..)) import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.RemoteControl.Types (VersionRangeRCP) @@ -61,7 +62,7 @@ instance StrEncoding RCInvitation where [ "xrcp:/", strEncode ca, "@", - strEncode host, + strEncode (SrvLoc host ""), ":", strEncode port, "#/?", diff --git a/src/Simplex/RemoteControl/Types.hs b/src/Simplex/RemoteControl/Types.hs index 48c623e7c..2f9fe31fd 100644 --- a/src/Simplex/RemoteControl/Types.hs +++ b/src/Simplex/RemoteControl/Types.hs @@ -256,6 +256,12 @@ type SessionCode = ByteString type RCStepTMVar a = TMVar (Either RCErrorType a) -$(JQ.deriveJSON (sumTypeJSON $ dropPrefix "RCE") ''RCErrorType) +$( JQ.deriveJSON + ( sumTypeJSON $ \case + "RCETLSStartFailed" -> "tlsStartFailed" + name -> dropPrefix "RCE" name + ) + ''RCErrorType + ) $(JQ.deriveJSON defaultJSON ''RCCtrlAddress) diff --git a/tests/AgentTests.hs b/tests/AgentTests.hs index cb14f5fff..44b664169 100644 --- a/tests/AgentTests.hs +++ b/tests/AgentTests.hs @@ -20,7 +20,7 @@ import Simplex.Messaging.Transport (ASrvTransport) import Test.Hspec hiding (fit, it) #if defined(dbPostgres) -import AgentTests.FunctionalAPITests (workItemReadTests) +import AgentTests.FunctionalAPITests (abortedTransactionTests, transactionDeadlockTests, workItemReadTests) #else import AgentTests.SQLiteTests (storeTests) #endif @@ -38,6 +38,8 @@ agentCoreTests = do describe "resolve names" resolveNameTests #if defined(dbPostgres) describe "Work item reads" workItemReadTests + describe "Transaction deadlocks" transactionDeadlockTests + describe "Aborted transactions" abortedTransactionTests #endif agentTests :: (ASrvTransport, AStoreType) -> Spec diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index 40ca12cf9..b20831b84 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -30,6 +30,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (EntityId (..), ProtocolServer (..), QueueMode (..), currentSMPClientVersion, supportedSMPClientVRange, pattern VersionSMPC) import Simplex.Messaging.ServiceScheme (ServiceScheme (..)) +import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.Messaging.Version import Test.Hspec hiding (fit, it) import Util @@ -290,6 +291,16 @@ connectionRequestTests = it "should reject KEM ciphertext without KEM key in e2e params" $ strDecode @(RcvE2ERatchetParamsUri 'C.X448) (strEncode testE2ERatchetParams <> "&kem_ct=" <> strEncode (B.replicate 1039 '\0')) `shouldSatisfy` isLeft + it "should reject links with invalid key encoding" $ do + let invalidDhKeyQueueStr = "smp://1234-w==@smp.simplex.im:5223/3456-w==#/?v=1-4&dh=" <> url "MCowBQYDK2VuAyE9jiswwI3O_NlS8Fk3HJUW870EY2bAwmttMBsvRB9eV3o=" + invalidE2EParamsStrUri = "v%3D3%26x3dh%3DMEIwBQYDK2VvAzk9mKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D%2CMEIwBQYDK2VvAzkAmKuSYeQ_m0SixPDS8Wq8VBaTS1cW-Lp0n0h4Diu-kUpR-qXx4SDJ32YGEFoGFGSbGPry5Ychr6U%3D" + strDecode @AConnectionRequestUri ("simplex:/contact#/?v=6-8&smp=" <> url invalidDhKeyQueueStr) `shouldSatisfy` isLeft + strDecode @AConnectionRequestUri ("simplex:/invitation#/?v=6-8&smp=" <> url queueStr <> "&e2e=" <> invalidE2EParamsStrUri) `shouldSatisfy` isLeft + it "should generate a bracketed IPv6 application-server authority" $ do + let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + request = CRInvitationUri (connReqData {crScheme = SSAppServer $ SrvLoc ipv6Host ""}) testE2ERatchetParams + encoded = strEncode request + encoded `shouldSatisfy` B.isPrefixOf "https://[2001:db8::1]/invitation#/?" it "should serialize / parse queue address, connection invitations and contact addresses as binary" $ do smpEncodingTest queue smpEncodingTest queueNoQM -- this passes, no queue mode patch in SMPQueueUri encoding @@ -316,7 +327,18 @@ connectionRequestTests = smpEncodingTest (aBinaryConnReq contactAddress2queuesNew) smpEncodingTest (aBinaryConnReq contactAddressV6) smpEncodingTest (aBinaryConnReq contactAddressClientData) + it "should parse server without key hash only in short links as binary" $ do + let addr = queueAddr {smpServer = shortSrv} + smpDecode @SMPQueueUri (smpEncode $ SMPQueueUri supportedSMPClientVRange addr) `shouldSatisfy` isLeft + smpDecode @SMPQueueInfo (smpEncode $ SMPQueueInfo (VersionSMPC 1) addr) `shouldSatisfy` isLeft + smpEncodingTest $ ACSL SCMContact $ CSLContact SLSServer CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") + smpEncodingTest $ ACSL SCMInvitation $ CSLInvitation SLSServer shortSrv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") it "should serialize / parse short links" $ do + let ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + ipv6Srv = srv {host = [ipv6Host, "jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion"]} + linkKey = LinkKey "0123456789abcdef0123456789abcdef" + ipv6Contact = CSLContact SLSServer CCTContact ipv6Srv linkKey + ipv6Invitation = CSLInvitation SLSServer ipv6Srv (EntityId "0123456789abcdef01234567") linkKey CSLContact SLSServer CCTContact srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLContact SLSServer CCTGroup srv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/g#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLContact SLSServer CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") #==# "https://smp.simplex.im/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY" @@ -327,6 +349,10 @@ connectionRequestTests = CSLContact SLSSimplex CCTContact shortSrv (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im" CSLInvitation SLSSimplex srv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im%2Cjjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" CSLInvitation SLSSimplex shortSrv (EntityId "0123456789abcdef01234567") (LinkKey "0123456789abcdef0123456789abcdef") #==# "simplex:/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=smp.simplex.im" + ipv6Contact #==# "https://[2001:db8::1]/a#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" + ipv6Invitation #==# "https://[2001:db8::1]/i#MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3/MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY?h=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion&p=5223&c=1234-w" + smpEncodingTest ipv6Contact + smpEncodingTest ipv6Invitation it "should shorten / restore short links" $ do let contact = CSLContact SLSServer CCTContact shortenShortLink [srv] (contact srv (LinkKey "0123456789abcdef0123456789abcdef")) diff --git a/tests/AgentTests/DoubleRatchetTests.hs b/tests/AgentTests/DoubleRatchetTests.hs index 7a7b05f75..0fbdffe9b 100644 --- a/tests/AgentTests/DoubleRatchetTests.hs +++ b/tests/AgentTests/DoubleRatchetTests.hs @@ -10,6 +10,8 @@ {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -Wno-orphans #-} {-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-} +-- DhAlgorithm makes non-DH key constructors unreachable in lowOrderKeys, but GHC reports it as redundant +{-# OPTIONS_GHC -fno-warn-redundant-constraints #-} module AgentTests.DoubleRatchetTests where @@ -17,9 +19,14 @@ import Control.Concurrent.STM import Control.Monad (forM_, when) import Control.Monad.Except import Control.Monad.IO.Class +import Crypto.Cipher.AES (AES256) +import qualified Crypto.Error as CE +import qualified Crypto.PubKey.Curve25519 as X25519 +import qualified Crypto.PubKey.Curve448 as X448 import Crypto.Random (ChaChaDRG) import Data.Aeson (FromJSON, ToJSON, (.=)) import qualified Data.Aeson as J +import qualified Data.ByteArray as BA import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.Map.Strict as M @@ -52,6 +59,8 @@ doubleRatchetTests = do it "should decode v2 Ratchet with default field values" $ testDecodeV2RatchetJSON it "should agree the same ratchet parameters" $ testAlgs testX3dh it "should agree the same ratchet parameters with version 1" $ testAlgs testX3dhV1 + it "should reject low-order DH keys in key agreement" $ testAlgs testX3dhLowOrderKeys + it "should reject low-order DH key in message header" $ testAlgs testRatchetStepLowOrderKey describe "post-quantum hybrid KEM double-ratchet algorithm" $ do describe "hybrid KEM key agreement" $ do it "should propose KEM during agreement, but no shared secret" $ testAlgs testPqX3dhProposeInReply @@ -69,6 +78,7 @@ doubleRatchetTests = do describe "message tests, KEM proposed again in reply" $ runMessageTests initRatchetsKEMProposedAgain True it "should disable and re-enable KEM" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableEnableKEM it "should disable and re-enable KEM (always set PQEncryption)" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableEnableKEMStrict + it "should decrypt messages out of order after disabling KEM" $ withRatchets_ @X25519 initRatchetsKEMAccepted testDisableKEMOutOfOrder it "should enable KEM when it was not enabled in handshake" $ withRatchets_ @X25519 initRatchets testEnableKEM it "should enable KEM when it was not enabled in handshake (always set PQEncryption)" $ withRatchets_ @X25519 initRatchets testEnableKEMStrict @@ -295,6 +305,14 @@ testDisableEnableKEMStrict alice bob _ _ _ = do (alice, "now KEM is enabled") !#>! bob (bob, "KEM is enabled for both sides") !#>! alice +testDisableKEMOutOfOrder :: forall a. (AlgorithmI a, DhAlgorithm a) => TestRatchets a +testDisableKEMOutOfOrder alice bob encrypt decrypt _ = do + Right b1 <- withTVar (encrypt_ (Just PQEncOff)) hasSndKEM bob "disabling KEM" + Right b2 <- encrypt bob "KEM disabled" + Decrypted "KEM disabled" <- decrypt alice b2 + Decrypted "disabling KEM" <- decrypt alice b1 + pure () + testEnableKEM :: forall a. (AlgorithmI a, DhAlgorithm a) => TestRatchets a testEnableKEM alice bob _ _ _ = do (bob, "hello alice") \#> alice @@ -398,6 +416,51 @@ testX3dhV1 _ = do paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob paramsAlice `shouldBe` paramsBob +testX3dhLowOrderKeys :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () +testX3dhLowOrderKeys _ = do + g <- C.newRandom + let v = currentE2EEncryptVersion + (pksBob, AE2ERatchetParams _ e2eBob@(E2ERatchetParams _ bk1 bk2 _)) <- liftIO $ generateSndE2EParams @a g v Nothing + (pksAlice, e2eAlice@(E2ERatchetParams _ ak1 ak2 _)) <- liftIO $ generateRcvE2EParams @a g v PQSupportOff + Right _ <- pure $ pqX3dhSnd pksBob e2eAlice + Right _ <- runExceptT $ pqX3dhRcv pksAlice e2eBob + let params k1 k2 = E2ERatchetParams v k1 k2 Nothing :: E2ERatchetParams 'RKSProposed a + forM_ (lowOrderKeys ak1) $ \k -> do + pqX3dhSnd pksBob (params k ak2) `shouldBe` Left allZeroDhError + pqX3dhSnd pksBob (params ak1 k) `shouldBe` Left allZeroDhError + runExceptT (pqX3dhRcv pksAlice $ params k bk2) `shouldReturn` Left allZeroDhError + runExceptT (pqX3dhRcv pksAlice $ params bk1 k) `shouldReturn` Left allZeroDhError + +testRatchetStepLowOrderKey :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () +testRatchetStepLowOrderKey _ = do + g <- C.newRandom + (alice, Ratchet {rcSnd = Just SndRatchet {rcHKs}, rcAD = Str ad}, _, _, _) <- initRatchets @a + let decryptWithKey k = do + let hdr = MsgHeader {msgMaxVersion = currentE2EEncryptVersion, msgDHRs = k, msgKEM = Nothing, msgPN = 0, msgNs = 0} + ehIV = C.IV $ B.replicate (C.ivSize @AES256) '\0' + Right (ehAuthTag, ehBody) <- runExceptT $ C.encryptAEAD rcHKs ehIV (paddedHeaderLen PQSupportOff) ad (smpEncode hdr) + let emHeader = smpEncode EncMessageHeader {ehVersion = currentE2EEncryptVersion, ehIV, ehAuthTag, ehBody, ehLegacy = False} + runExceptT $ rcDecrypt g alice M.empty $ smpEncode EncRatchetMessage {emHeader, emAuthTag = ehAuthTag, emBody = "message"} + (validKey, _) <- atomically $ C.generateKeyPair @a g + decryptWithKey validKey >>= \case + Right (Left C.AESDecryptError, _, _) -> pure () + _ -> expectationFailure "header with valid key should be decrypted and ratchet advanced" + forM_ (lowOrderKeys validKey) $ \k -> + decryptWithKey k >>= \case + Left e -> e `shouldBe` allZeroDhError + Right _ -> expectationFailure "ratchet should not advance with low-order key" + +-- RFC 7748 section 6.2: u = 0 and u = 1 are low-order points on both curves and their twists +lowOrderKeys :: DhAlgorithm a => C.PublicKey a -> [C.PublicKey a] +lowOrderKeys = \case + C.PublicKeyX25519 k -> C.PublicKeyX25519 . CE.throwCryptoError . X25519.publicKey <$> lowOrderPoints (BA.length k) + C.PublicKeyX448 k -> C.PublicKeyX448 . CE.throwCryptoError . X448.publicKey <$> lowOrderPoints (BA.length k) + where + lowOrderPoints n = [B.replicate n '\0', B.cons '\1' $ B.replicate (n - 1) '\0'] + +allZeroDhError :: CryptoError +allZeroDhError = C.CryptoHeaderError "all-zero DH secret" + testPqX3dhProposeInReply :: forall a. (AlgorithmI a, DhAlgorithm a) => C.SAlgorithm a -> IO () testPqX3dhProposeInReply _ = do g <- C.newRandom @@ -535,8 +598,8 @@ initRatchets = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOff + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOff pure (alice, bob, encrypt' noSndKEM, decrypt' noRcvKEM, (\#>)) initRatchetsKEMProposed :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -552,8 +615,8 @@ initRatchetsKEMProposed = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsKEMAccepted :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -570,8 +633,8 @@ initRatchetsKEMAccepted = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsKEMProposedAgain :: forall a. (AlgorithmI a, DhAlgorithm a) => IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) @@ -587,8 +650,8 @@ initRatchetsKEMProposedAgain = do Right paramsAlice <- runExceptT $ pqX3dhRcv pksAlice e2eBob (_, pkBob3) <- atomically $ C.generateKeyPair g let vs = testRatchetVersions - bob = initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob - alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn + Right bob <- pure $ initSndRatchet vs (C.publicKey pkAlice2) pkBob3 paramsBob + let alice = initRcvRatchet vs pkAlice2 paramsAlice PQSupportOn pure (alice, bob, encrypt' hasSndKEM, decrypt' hasRcvKEM, (!#>)) initRatchetsV2 :: (AlgorithmI a, DhAlgorithm a) => Encrypt a -> Decrypt a -> IO (Ratchet a, Ratchet a, Encrypt a, Decrypt a, EncryptDecryptSpec a) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 5f6b0d835..90678a089 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -60,6 +60,8 @@ module AgentTests.FunctionalAPITests testServerInformation, #if defined(dbPostgres) workItemReadTests, + transactionDeadlockTests, + abortedTransactionTests, #endif ) where @@ -86,6 +88,7 @@ import qualified Data.Set as S import qualified Data.Text as T import Data.Text.Encoding (decodeLatin1) import qualified Data.Text.IO as T +import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (diffUTCTime, getCurrentTime) import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Data.Tuple (swap) @@ -106,7 +109,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) @@ -118,13 +121,13 @@ import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.Env.STM (AStoreType (..), ServerConfig (..), ServerStoreCfg (..), StorePaths (..)) import Simplex.Messaging.Server.Expiration -import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (..)) import Simplex.Messaging.Server.MsgStore.Types (SMSType (..), SQSType (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..)) -import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, VersionSMP, currentServerSMPRelayVersion, minClientSMPRelayVersion, minServerSMPRelayVersion, alpnSupportedSMPHandshakes) +import Simplex.Messaging.Transport (ASrvTransport, SMPVersion, VersionSMP, currentClientSMPRelayVersion, currentServerSMPRelayVersion, minClientSMPRelayVersion, minServerSMPRelayVersion, alpnSupportedSMPHandshakes) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) -import Simplex.Messaging.Util (bshow, diffToMicroseconds) +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 (..)) @@ -138,11 +141,12 @@ import XFTPClient (testXFTPServer, withXFTPServerThreadOn) #if defined(dbPostgres) import Database.PostgreSQL.Simple (Only (..), Query) import Fixtures -import Simplex.Messaging.Agent.Client (withStoreIsolation', withWork, withWorkItems) +import Simplex.Messaging.Agent.Client (withStore, withStore', withStoreBatch', withStoreIsolation', withWork, withWorkItems) import Simplex.Messaging.Agent.Env.SQLite (AM) -import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), RcvQueue, RcvQueueSub (..), ServiceAssoc) -import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNtfSubscription, createServer, createSndFile, deleteClientService, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile) +import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), ConnData (..), InternalId (..), RcvQueue, RcvQueueSub (..), ServiceAssoc) +import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNewConn, createNtfSubscription, createServer, createSndFile, createSndMsgDelivery, createUserRecord, deleteClientService, deleteConn, deleteSndMsgDelivery, deleteUserRecord, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile, updateNewConnSnd) import Simplex.Messaging.Agent.Store.Common (IsolationLevel (..)) +import Simplex.Messaging.Agent.Store.Entity (DBEntityId' (..)) import Simplex.Messaging.Notifications.Types (NtfAgentSubStatus (NASNew), NtfSubAction (NSANtf, NSASMP), NtfSubNTFAction (NSACreate), NtfSubSMPAction (NSASmpKey), newNtfSubscription) #endif #if defined(dbServerPostgres) @@ -278,6 +282,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) @@ -359,12 +366,16 @@ functionalAPITests ps = do withSmpServer ps testAgentClient3 it "should establish connection without PQ encryption and enable it" $ withSmpServer ps testEnablePQEncryption + it "should not store messages that are too large" $ + withSmpServer ps testLargeMessageNotStored it "should refuse joining already used invitation and keep connection" $ withSmpServer ps testJoinUsedInvitation it "should refuse confirmation with client version below the version of its agent" $ 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 +388,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 +441,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 @@ -465,6 +481,7 @@ functionalAPITests ps = do it "should not create connection for prepared invitation link with too large data" $ testPrepareInvitationLinkTooLarge ps it "should not create connection for prepared contact link with too large data" $ testPrepareContactLinkTooLarge ps it "should connect via short link prepared for existing contact connection" $ testPrepareConnShortLink ps + it "should refuse short links to servers without key hash" $ testShortLinkWithoutKeyHash ps describe "Message delivery" $ do describe "update connection agent version on received messages" $ do it "should increase if compatible, shouldn'ps decrease" $ @@ -525,6 +542,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 @@ -543,6 +562,8 @@ functionalAPITests ps = do testSuspendingAgentTimeout ps it "should send messages queued after file is sent before agent is suspended" $ testSuspendingAgentCompleteSendingFile ps + it "should suspend agent when event queue is full" $ + testSuspendingAgentFullQueue describe "Batching SMP commands" $ do it "should subscribe to multiple (200) subscriptions with batching" $ testBatchedSubscriptions 200 20 ps @@ -551,9 +572,16 @@ 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 +#if defined(dbPostgres) + it "should report every message of a batch rolled back after a database error" $ withSmpServer ps testSendMessagesRolledBack +#endif describe "Async agent commands" $ do describe "connect using async agent commands" $ testBasicMatrix2 ps testAsyncCommands @@ -567,6 +595,8 @@ functionalAPITests ps = do testBasicMatrix2 ps testAcceptContactAsync it "should delete connections using async command when server connection fails" $ testDeleteConnectionAsync ps + it "should delete connection without receive queue when event queue is full" $ + testDeleteConnectionAsyncFullQueue it "join connection when reply queue creation fails" $ testJoinConnectionAsyncReplyError ps describe "delete connection waiting for delivery" $ do @@ -585,6 +615,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" $ @@ -595,6 +629,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" $ @@ -605,6 +640,18 @@ functionalAPITests ps = do testFastSwitchDrainOldQueue ps it "should drain the old queue after QEND on the new queue and restart" $ testFastSwitchDrainOldQueueRestart ps + it "should receive messages while the server of the new queue does not respond" $ + testFastSwitchStallingNewServer ps + it "should delete the new queue when the switch is aborted while the queue is created" $ + testSwitchChangedWhileNewQueue abortConnectionSwitch "switchConnection: aborted" ps + it "should delete the new queue when ratchet synchronization starts while the queue is created" $ + testSwitchChangedWhileNewQueue (\c connId -> synchronizeRatchet c connId PQSupportOn True) "switchConnection: send prohibited" ps + it "should delete the new queue when the connection is deleted while the queue is created" $ + testSwitchConnectionDeletedWhileNewQueue ps + it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ + testSwitchRatchetSyncBeforeNewQueue ps + it "should secure the new queue and complete the switch after ratchet synchronization" $ + testFastSwitchRatchetSyncWhileSecuring ps describe "should switch delivery to the new queue" $ testServerMatrix2 ps testSwitchConnection describe "should switch to new queue asynchronously" $ @@ -655,9 +702,19 @@ functionalAPITests ps = do it "should pass with correct password" $ testSMPServerConnectionTest ps auth (srv auth) `shouldReturn` Right (Just (Right testServerInformation)) it "should fail without password" $ testSMPServerConnectionTest ps auth (srv Nothing) `shouldReturn` Left authErr it "should fail with incorrect password" $ testSMPServerConnectionTest ps auth (srv $ Just "wrong") `shouldReturn` Left authErr + describe "Client support from preset servers" $ do + it "should notify about unsupported version and app releases" $ testClientSupport ps + it "should not notify about supported version or servers that are not preset" $ testClientSupportNoEvent ps describe "getConnectionVerifyCodes" $ it "should return the same codes for both peers" $ withSmpServer ps testConnectionVerifyCodes + describe "Connection locks" $ do +#if defined(conn_lock_checks) + it "should prohibit server requests in connection lock" $ + withSmpServer ps testServerRequestInConnLock +#endif + it "should delete connections after connection lock is released" $ + testDeleteConnectionsAfterConnLock describe "Delivery receipts" $ do it "should send and receive delivery receipt" $ withSmpServer ps testDeliveryReceipts it "should deliver receipt again after client restart without acknowledgement" $ testDuplicateReceipt ps False False @@ -1028,37 +1085,30 @@ testEnablePQEncryption = sml <- largeMsg g PQSupportOn -- fail because of message size Left (A.CMD LARGE _) <- tryError $ A.sendMessage ca bId PQEncOn SMP.noMsgFlags lrg - (7, PQEncOff) <- A.sendMessage ca bId PQEncOn SMP.noMsgFlags sml - get ca =##> \case ("", connId, SENT 7) -> connId == bId; _ -> False - get cb =##> \case ("", connId, MsgErr' 6 MsgSkipped {} PQEncOff msg') -> connId == aId && msg' == sml; _ -> False - ackMessage cb aId 6 Nothing - -- -- fail in reply to sync IDss + (a, 6, sml) \#>! b Left (A.CMD LARGE _) <- tryError $ A.sendMessage cb aId PQEncOn SMP.noMsgFlags lrg - (8, PQEncOff) <- A.sendMessage cb aId PQEncOn SMP.noMsgFlags sml - get cb =##> \case ("", connId, SENT 8) -> connId == aId; _ -> False - get ca =##> \case ("", connId, MsgErr' 8 MsgSkipped {} PQEncOff msg') -> connId == bId && msg' == sml; _ -> False - ackMessage ca bId 8 Nothing - (a, 9, sml) \#>! b + (b, 7, sml) \#>! a + (a, 8, sml) \#>! b -- PQ encryption now enabled - (b, 10, sml) !#>! a - (a, 11, sml) !#>! b - (b, 12, sml) !#>! a + (b, 9, sml) !#>! a + (a, 10, sml) !#>! b + (b, 11, sml) !#>! a -- disabling PQ encryption - (a, 13, sml) !#>\ b - (b, 14, sml) !#>\ a - (a, 15, sml) \#>\ b - (b, 16, sml) \#>\ a + (a, 12, sml) !#>\ b + (b, 13, sml) !#>\ a + (a, 14, sml) \#>\ b + (b, 15, sml) \#>\ a -- enabling PQ encryption again - (a, 17, sml) \#>! b - (b, 18, sml) \#>! a - (a, 19, sml) \#>! b - (b, 20, sml) !#>! a - (a, 21, sml) !#>! b + (a, 16, sml) \#>! b + (b, 17, sml) \#>! a + (a, 18, sml) \#>! b + (b, 19, sml) !#>! a + (a, 20, sml) !#>! b -- disabling PQ encryption again - (b, 22, sml) !#>\ a - (a, 23, sml) !#>\ b - (b, 24, sml) \#>\ a - (a, 25, sml) \#>\ b + (b, 21, sml) !#>\ a + (a, 22, sml) !#>\ b + (b, 23, sml) \#>\ a + (a, 24, sml) \#>\ b -- PQ encryption is now disabled, but support remained enabled, so we still cannot send larger messages Left (A.CMD LARGE _) <- tryError $ A.sendMessage ca bId PQEncOff SMP.noMsgFlags (sml <> "123456") Left (A.CMD LARGE _) <- tryError $ A.sendMessage cb aId PQEncOff SMP.noMsgFlags (sml <> "123456") @@ -1077,6 +1127,18 @@ sndRcv pqEnc pqEnc' ((c1, id1), mId, msg) (c2, id2) = do get c2 =##> \case ("", connId, Msg' mId' pq msg') -> connId == id1 && mId' == mId && msg' == msg && pq == pqEnc; _ -> False ackMessage c2 id1 mId Nothing +testLargeMessageNotStored :: (HasCallStack, HasTestEnv) => IO () +testLargeMessageNotStored = + withAgentClients2 $ \a b -> runRight_ $ do + (aId, bId) <- makeConnection a b + Left (A.CMD LARGE _) <- tryError $ A.sendMessage a bId PQEncOn SMP.noMsgFlags $ B.replicate (e2eEncAgentMsgLength PQSupportOn) 'a' + liftIO $ unreferencedMsgBodies a `shouldReturn` [] + 2 <- sendMessage a bId SMP.noMsgFlags "hello" + get a ##> ("", bId, SENT 2) + get b =##> \case ("", c, Msg' 2 PQEncOn "hello") -> c == aId; _ -> False + ackMessage b aId 2 Nothing + liftIO $ skippedMsgKeys b `shouldReturn` [] + testAgentClient3 :: (HasCallStack, HasTestEnv) => IO () testAgentClient3 = withAgentClients3 $ \a b c -> runRight_ $ do @@ -1172,6 +1234,24 @@ testContactRequestZeroSecret ps = withSmpServer ps $ withAgentClients2 $ \alice void $ joinConnection bob 1 True qInfo "bob's connInfo" SMSubscribe get alice =##> \case ("", c, REQ _ _ "bob's connInfo") -> c == contactId; _ -> False +testAcceptContactStallingServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testAcceptContactStallingServer ps@(t, ASType qsType _) = + withSmpServer ps $ + withAgent 1 agentCfg initAgentServersLongConnect testDB $ \a -> do + (bId, invId) <- withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> + withAgent 2 agentCfg bServers testDB2 $ \b -> runRight $ do + (_, cReq) <- createConnection a 1 True SCMContact Nothing SMSubscribe + void $ joinConnection b 1 True cReq "bob's connInfo" SMSubscribe + ("", _, REQ invId _ "bob's connInfo") <- get a + (bId, _) <- A.prepareConnectionToAccept a 1 True invId PQSupportOn + pure (bId, invId) + withStallingServerOn' testPort2 $ \accepted _ -> + withAsync (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) $ \_ -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + Just (Left (A.CMD PROHIBITED _)) <- timeout 5_000000 . runExceptT $ synchronizeRatchet a bId PQSupportOn False + timeout 1_000000 (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) `shouldReturn` Nothing + where + bServers = initAgentServers {smp = userServers [testSMPServer2]} testDeleteAcceptedContactRequest :: (HasCallStack, HasTestEnv) => Bool -> Bool -> IO () testDeleteAcceptedContactRequest useDR asyncAccept = withAgentClients2 $ \alice bob -> runRight_ $ do @@ -1663,6 +1743,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 @@ -2355,6 +2471,20 @@ testPrepareConnShortLink ps = withSmpServer ps $ withAgentClients2 $ \a b -> do get b ##> ("", aId, CON) exchangeGreetings a bId b aId +testShortLinkWithoutKeyHash :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testShortLinkWithoutKeyHash ps = withSmpServer ps $ withAgentClients2 $ \a b -> do + let userCtData = UserContactData {direct = True, owners = [], relays = [], userData = UserLinkData "test user data", ratchetKeys = Nothing} + (_, CCLink _ (Just contactLink)) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMContact (Just $ UserContactLinkData userCtData) Nothing CR.IKPQOn False SMSubscribe + (_, CCLink _ (Just invLink)) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMInvitation (Just $ UserInvLinkData $ UserLinkData "test user data") Nothing CR.IKUsePQ False SMSubscribe + let hostOnlyLink = shortenShortLink [testSMPServer] contactLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLink b 1 hostOnlyLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLink b 1 $ shortenShortLink [testSMPServer] invLink + Left (A.CMD PROHIBITED _) <- runExceptT $ getConnShortLinkAsync b 1 "1" Nothing hostOnlyLink + withTransaction (store $ agentEnv b) (`DB.query_` "SELECT host, port FROM servers") `shouldReturn` ([] :: [(T.Text, T.Text)]) + withTransaction (store $ agentEnv b) getConnIds `shouldReturn` [] + (_, ContactLinkData _ userCtData', _) <- runRight $ getConnShortLink b 1 $ restoreShortLink [testSMPServer] hostOnlyLink + userCtData' `shouldBe` userCtData + connReqWithKeys :: BinaryConnectionRequestUri m -> Maybe AddressRatchetKeys -> ConnectionRequestUri m connReqWithKeys cr rk = case cr of BCRInvitationUri crData e2eParams -> CRInvitationUri crData e2eParams @@ -3239,6 +3369,11 @@ waitDeleted getMsgs msg = go (100 :: Int) connInvitations :: AgentClient -> IO [(InvitationId, Maybe ConnId)] connInvitations c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT invitation_id, contact_conn_id FROM conn_invitations") +unreferencedMsgBodies :: AgentClient -> IO [(Int64, Int64)] +unreferencedMsgBodies c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT snd_message_body_id, length(agent_msg) FROM snd_message_bodies b WHERE NOT EXISTS (SELECT 1 FROM snd_messages m WHERE m.snd_message_body_id = b.snd_message_body_id)") + +skippedMsgKeys :: AgentClient -> IO [(ConnId, Int64)] +skippedMsgKeys c = withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, msg_n FROM skipped_messages") getMsg :: AgentClient -> ConnId -> ExceptT AgentErrorType IO a -> ExceptT AgentErrorType IO a getMsg c cId action = do liftIO $ noMessages c "nothing should be delivered before GET" @@ -3278,6 +3413,24 @@ 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 $ do + fillSubQ b + timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ b + getMSGNTF b aId + makeConnection :: AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId) makeConnection = makeConnection_ PQSupportOn @@ -3461,6 +3614,15 @@ testSuspendingAgentCompleteSendingFile ps = suspendedOps :: AgentClient -> IO [Bool] suspendedOps c = mapM (\op -> opSuspended <$> readTVarIO (op c)) [rcvNetworkOp, sndFilesOp, msgDeliveryOp] +testSuspendingAgentFullQueue :: HasTestEnv => IO () +testSuspendingAgentFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + threadDelay 100000 + fillSubQ a + timeout 5_000000 (suspendAgent a 1_000000) `shouldReturn` Just () + void . atomically . flushTBQueue $ subQ a + nGet a ##> ("", "", SUSPENDED) + testBatchedSubscriptions :: HasTestEnv => Int -> Int -> (ASrvTransport, AStoreType) -> IO () testBatchedSubscriptions nCreate nDel ps@(t, ASType qsType _) = do (conns, conns') <- withAgentClientsCfgServers2 agentCfg agentCfg initAgentServers2 $ \a b -> do @@ -3562,6 +3724,40 @@ 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 + fillSubQ b + runRight_ $ forM_ conns $ \(_, bId') -> do + msgId' <- sendMessage a bId' SMP.noMsgFlags "hello" + get a ##> ("", bId', SENT msgId') + timeout 5_000000 (atomically $ isFullTBQueue (msgQ b) >>= checkSTM) `shouldReturn` Just () + timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ b + timeout 5_000000 (receiveMsgs b $ (aId, "hello 2") : map ((,"hello") . fst) conns) `shouldReturn` Just () + +testDuplicateConnIdsFullQueue :: HasTestEnv => IO () +testDuplicateConnIdsFullQueue = withAgentClients2 $ \a b -> do + (_, bId) <- runRight $ makeConnection a b + fillSubQ a + Just (Right subRs) <- timeout 5_000000 . runExceptT $ subscribeConnections a [bId, bId] + M.keys subRs `shouldBe` [bId] + Just (Right delRs) <- timeout 5_000000 . runExceptT $ deleteConnections a [bId, bId] + M.keys delRs `shouldBe` [bId] + void . atomically . flushTBQueue $ subQ a + getInAnyOrder a [resultSizeErr "subscribeConnections", resultSizeErr "deleteConnections"] + where + resultSizeErr :: String -> ATransmission -> Bool + resultSizeErr name = \case + ("", "", AEvt SAEConn (ERR (A.INTERNAL e))) -> (name <> " result size") `isPrefixOf` e + _ -> False + testSendMessagesB :: HasTestEnv => IO () testSendMessagesB = withAgentClients2 $ \a b -> runRight_ $ do (aId, bId) <- makeConnection a b @@ -3805,6 +4001,20 @@ testDeleteConnectionAsync ps = get a =##> \case ("", "", DEL_CONNS cs) -> length cs == 3 && all (`elem` connIds) cs; _ -> False liftIO $ noMessages a "nothing else should be delivered to alice" +testDeleteConnectionAsyncFullQueue :: HasTestEnv => IO () +testDeleteConnectionAsyncFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + (connId, _) <- runRight $ A.prepareConnectionToJoin a 1 True (CRInvitationUri connReqData testE2ERatchetParams12) PQSupportOn + fillSubQ a + timeout 5000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ a + get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False + +fillSubQ :: AgentClient -> IO () +fillSubQ c = atomically fill + where + fill = unlessM (isFullTBQueue $ subQ c) $ writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) >> fill + testWaitDeliveryNoPending :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () testWaitDeliveryNoPending ps = withAgentClients2 $ \alice bob -> withSmpServerStoreLogOn ps testPort $ \_ -> runRight_ $ do @@ -4098,6 +4308,26 @@ testDeleteUserQuietly = exchangeGreetingsMsgId 4 a bId b aId liftIO $ noMessages a "nothing else should be delivered to alice" +testDeleteUserFullQueue :: HasTestEnv => IO () +testDeleteUserFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] + fillSubQ a + timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ a + nGet a =##> \case ("", "", DEL_USER u) -> u == auId; _ -> False + +testDeleteUserStatsErrorFullQueue :: HasTestEnv => IO () +testDeleteUserStatsErrorFullQueue = + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] + withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats RENAME TO servers_stats_") + fillSubQ a + timeout 5_000000 (runExceptT $ deleteUser a auId False) `shouldReturn` Just (Right ()) + withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats_ RENAME TO servers_stats") + void . atomically . flushTBQueue $ subQ a + get a =##> \case ("", "", ERR (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 @@ -4234,6 +4464,138 @@ testFastSwitchDrainOldQueueRestart ps = subscribeConnection a bId drainOldQueue a bId b aId +testFastSwitchStallingNewServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testFastSwitchStallingNewServer ps@(t, ASType qsType _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServers testDB2 $ \b -> do + (aId, bId, aId', bId') <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ do + (aId, bId) <- makeConnection a b + (aId', bId') <- makeConnection a b + pure (aId, bId, aId', bId') + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t (cfgS2QS qsType) testPort2 $ \_ -> runRight_ $ do + _ <- switchConnectionAsync b "" aId + phaseRcv b aId SPStarted [Just RSSendingQADD, Nothing] + withStallingServerOn testPort2 $ + withAgent 1 agentCfg initAgentServersLongConnect testDB $ \a -> runRight_ $ do + void $ subscribeConnections a [bId, bId'] + void $ sendMessage b aId SMP.noMsgFlags "hello" + void $ sendMessage b aId' SMP.noMsgFlags "hello too" + liftIO $ timeout 5_000000 (receiveMsgs a [(bId, "hello"), (bId', "hello too")]) `shouldReturn` Just () + +receiveMsgs :: AgentClient -> [(ConnId, MsgBody)] -> IO () +receiveMsgs _ [] = pure () +receiveMsgs c msgs = + pGet c >>= \case + (_, cId, AEvt SAEConn (MSG _ _ body)) -> receiveMsgs c $ filter (/= (cId, body)) msgs + _ -> receiveMsgs c msgs + +testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () +testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ changeSwitch b aId + atomically $ putTMVar resume () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitRcvQueueRecords b 1 + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + +testSwitchConnectionDeletedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + runRight_ $ deleteConnection b aId + atomically $ putTMVar resume () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + +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 ()) + endSwitchOnNewQueue :: (HasCallStack, HasTestEnv) => AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId, AgentMsgId) endSwitchOnNewQueue a b = do (aId, bId) <- makeConnection a b @@ -4685,9 +5047,47 @@ testServerInformation = complaintsContacts = Nothing, hosting = Nothing, hostingType = Nothing, - serverCountry = Nothing + serverCountry = Nothing, + clientSupport = Nothing } +testClientSupport :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () +testClientSupport ps = + withClientSupportServers ps cs1 cs2 $ + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer], presetServers = [testSMPServer, testSMPServer2]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB2 $ \bob -> runRight_ $ do + (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing IKPQOn False SMSubscribe + nGet alice ##> ("", "", CLIENT_SUPPORT cs1) + (aliceId, _) <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn + _ <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + ("", _, CONF confId _ "bob's connInfo") <- get alice + allowConnection alice bobId confId "alice's connInfo" + nGet alice ##> ("", "", CLIENT_SUPPORT cs1 {stableRelease = Just "7.2.0"}) + get alice ##> ("", bobId, CON) + get bob ##> ("", aliceId, INFO "alice's connInfo") + get bob ##> ("", aliceId, CON) + where + Version v = currentClientSMPRelayVersion + cs1 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 1, fromDate = fromGregorian 2027 5 1}, stableRelease = Nothing, betaRelease = Nothing} + cs2 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 2, fromDate = fromGregorian 2027 9 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} + +testClientSupportNoEvent :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () +testClientSupportNoEvent ps = + withClientSupportServers ps cs1 cs2 $ + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer], presetServers = [testSMPServer]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB2 $ \bob -> + runRight_ . void $ makeConnection alice bob + where + Version v = currentClientSMPRelayVersion + cs1 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v, fromDate = fromGregorian 2027 5 1}, stableRelease = Nothing, betaRelease = Nothing} + cs2 = ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = v + 1, fromDate = fromGregorian 2027 5 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} + +withClientSupportServers :: HasTestEnv => (ASrvTransport, AStoreType) -> ClientSupport -> ClientSupport -> IO a -> IO a +withClientSupportServers (t, msType@(ASType qs _)) cs1 cs2 = + withSmpServerConfigOn t (withClientSupport cs1 $ cfgMS msType) testPort . const . withSmpServerConfigOn t (withClientSupport cs2 $ cfgS2QS qs) testPort2 . const + where + withClientSupport cs cfg' = updateCfg cfg' $ \cfg_ -> cfg_ {information = Just testServerInformation {clientSupport = Just cs}} + testConnectionVerifyCodes :: (HasCallStack, HasTestEnv) => IO () testConnectionVerifyCodes = withAgentClients2 $ \a b -> runRight_ $ do @@ -4706,6 +5106,41 @@ 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 ()) + testDeliveryReceipts :: (HasCallStack, HasTestEnv) => IO () testDeliveryReceipts = withAgentClients2 $ \a b -> runRight_ $ do @@ -5078,10 +5513,35 @@ workItemReadTests = do let st = store $ agentEnv a withTransaction st $ \db -> createCmd db >> DB.execute_ db "UPDATE commands SET command = 'bad'::bytea" doWork <- newTMVarIO () - runReaderT (runExceptT $ readCommand a doWork $ \_ -> pure ()) (agentEnv a) `shouldReturn` Right () + runAM a (readCommand a doWork $ \_ -> pure ()) `shouldReturn` Right () events <- atomically $ flushTBQueue $ subQ a length (filter workerError events) `shouldBe` 1 withTransaction st (`DB.query_` "SELECT failed FROM commands") `shouldReturn` [Only (1 :: Int)] + it "should mark a command failed when a server error aborts its read" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createCmd db + DB.execute_ db "CREATE FUNCTION fail_read() RETURNS BOOLEAN LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END $$; ALTER TABLE connections ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY; CREATE POLICY fail_read ON connections FOR SELECT USING (fail_read())" + doWork <- newTMVarIO () + runAM a (readCommand a doWork $ \_ -> pure ()) `shouldReturn` Right () + events <- atomically $ flushTBQueue $ subQ a + filter workerError events `shouldBe` [] + withTransaction st (`DB.query_` "SELECT failed FROM commands") `shouldReturn` [Only (1 :: Int)] + it "should report INTERNAL when a server error aborts the read of a command that stays unmarked" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createCmd db + DB.execute_ db "CREATE FUNCTION fail_read() RETURNS BOOLEAN LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END $$; ALTER TABLE connections ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY; CREATE POLICY fail_read ON connections FOR SELECT USING (fail_read())" + DB.execute_ db "CREATE FUNCTION skip_update() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END $$; CREATE TRIGGER skip_update BEFORE UPDATE ON commands FOR EACH ROW EXECUTE FUNCTION skip_update()" + doWork <- newTMVarIO () + Just (Left (A.INTERNAL e)) <- timeout 5000000 $ runAM a (readCommand a doWork $ \_ -> pure ()) + e `shouldContain` "sqlState = \\\"XX001\\\"" + it "should mark a ntf subscription failed when a server error aborts its read in a batch" $ + readBatchAfterServerError (NSANtf NSACreate) "ntf_failed" (readNtfActions testNtfServer) + it "should mark a ntf SMP action failed when a server error aborts its read in a batch" $ + readBatchAfterServerError (NSASMP NSASmpKey) "smp_failed" (readSMPActions testSMPServer) it "should retry the read 3 times on the same connection after serialization failures" $ do (r, pids) <- readWithErrors 3 "40001" r `shouldBe` Right () @@ -5115,6 +5575,22 @@ workItemReadTests = do createNtfSubscription db (newNtfSubscription 1 "conn1" testSMPServer Nothing testNtfServer NASNew) action `shouldReturn` Right () readNtfActions srv a doWork = withWorkItems a doWork $ withStoreIsolation' a RepeatableRead $ \db -> getNextNtfSubNTFActions db srv 10 readSMPActions srv a doWork = withWorkItems a doWork $ withStoreIsolation' a RepeatableRead $ \db -> getNextNtfSubSMPActions db srv 10 + readBatchAfterServerError :: HasTestEnv => NtfSubAction -> Query -> (AgentClient -> TMVar () -> (NonEmpty a -> AM ()) -> AM ()) -> IO () + readBatchAfterServerError action failedColumn readItems = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + withTransaction st $ \db -> do + createNtfSub action db + DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (?,?,?)" (1 :: Int64, "conn2" :: ConnId, SCMInvitation) + createNtfSubscription db (newNtfSubscription 1 "conn2" testSMPServer Nothing testNtfServer NASNew) action `shouldReturn` Right () + DB.execute_ db $ "UPDATE ntf_subscriptions SET updated_by_supervisor = 1; CREATE FUNCTION fail_update() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.conn_id = 'conn1' AND NEW." <> failedColumn <> " = OLD." <> failedColumn <> " THEN RAISE EXCEPTION 'test' USING ERRCODE = 'XX001'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_update BEFORE UPDATE ON ntf_subscriptions FOR EACH ROW EXECUTE FUNCTION fail_update()" + doWork <- newTMVarIO () + itemsRead <- newTVarIO (0 :: Int) + runAM a (readItems a doWork $ atomically . writeTVar itemsRead . length) `shouldReturn` Right () + readTVarIO itemsRead `shouldReturn` 1 + events <- atomically $ flushTBQueue $ subQ a + filter workerError events `shouldBe` [] + withTransaction st (\db -> DB.query_ db $ "SELECT conn_id, " <> failedColumn <> ", updated_by_supervisor FROM ntf_subscriptions ORDER BY conn_id") + `shouldReturn` [("conn1" :: ConnId, 1 :: Int, 0 :: Int), ("conn2", 0, 0)] createSndFile' :: DB.Connection -> IO () createSndFile' db = do g <- C.newRandom @@ -5139,7 +5615,7 @@ readWhileDeleting createItem lockItem waitingQuery deleteItem readItem = withAge reading <- withTransaction st $ \db -> do lockItem db [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" - r <- async $ runReaderT (runExceptT $ readItem a doWork $ \_ -> atomically $ writeTVar itemRead True) (agentEnv a) + r <- async $ runAM a (readItem a doWork $ \_ -> atomically $ writeTVar itemRead True) waitForLock st holder waitingQuery DB.execute_ db deleteItem pure r @@ -5157,7 +5633,7 @@ workerError (_, _, AEvt _ e) = case e of readWithErrors :: HasTestEnv => Int -> Query -> IO (Either AgentErrorType (), [Int]) readWithErrors failures errCode = withAgent 1 agentCfg initAgentServers testDB $ \a -> do pids <- newIORef [] - r <- runReaderT (runExceptT $ withStoreIsolation' a RepeatableRead $ readItem pids) (agentEnv a) + r <- runAM a (withStoreIsolation' a RepeatableRead $ readItem pids) (r,) <$> readIORef pids where readItem pids db = do @@ -5173,6 +5649,111 @@ waitForLock st holder waitingQuery = timeout 5000000 waitLoop `shouldReturn` Jus withTransaction st $ \db -> DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE ? = ANY (pg_blocking_pids(pid)) AND position(? IN query) > 0)" (holder, waitingQuery) unless waiting $ threadDelay 10000 >> waitLoop + +transactionDeadlockTests :: Spec +transactionDeadlockTests = do + it "should retry deadlocked deletions of a delivered message and its user" $ + deleteWithDeliveredMessage "DELETE FROM users" deleteUserInTransaction 0 + it "should retry deadlocked deletions of a delivered message and its user after deadlock_timeout" $ + deleteWithDeliveredMessage "DELETE FROM users" deleteUserInTransaction 2000000 + it "should retry deadlocked deletions of a delivered message and its connection in a batch" $ + deleteWithDeliveredMessage "DELETE FROM connections" deleteConnInBatch 2000000 + it "should retry the creation of a connection after a conflict" $ + createConnAfterConflict "conn1" `shouldReturn` Right "conn1" + it "should retry the creation of a connection with a random ID after a conflict" $ + isRight <$> createConnAfterConflict "" `shouldReturn` True + where + deleteUserInTransaction a recordPid userId _ = runAM a (withStore a $ \db -> recordPid db >> deleteUserRecord db userId) `shouldReturn` Right () + deleteConnInBatch a recordPid _ connId = runReaderT (withStoreBatch' a $ \db -> [recordPid db >> deleteConn db Nothing connId]) (agentEnv a) `shouldReturn` ([Right (Just connId)] :: [Either AgentErrorType (Maybe ConnId)]) + +abortedTransactionTests :: Spec +abortedTransactionTests = do + it "should keep the transaction that creates a command for a deleted connection" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + runAM a (withStore a $ \db -> createUserRecord db >> createCommand db "1" "deleted" Nothing (AClientCommand $ NEW True (ACM SCMInvitation) IKPQOn SMSubscribe False)) `shouldReturn` Right () + withTransaction (store $ agentEnv a) (`DB.query_` "SELECT count(*) FROM users") `shouldReturn` [Only (2 :: Int)] + it "should report every item of a batch rolled back after a database error" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + rs <- runReaderT (withStoreBatch' a $ \db -> [void $ createUserRecord db, DB.execute_ db "DO $$ BEGIN RAISE EXCEPTION 'test' USING ERRCODE = '23505'; END $$"]) (agentEnv a) + map isRight rs `shouldBe` [False, False] + withTransaction (store $ agentEnv a) (`DB.query_` "SELECT count(*) FROM users") `shouldReturn` [Only (1 :: Int)] + +testSendMessagesRolledBack :: HasTestEnv => IO () +testSendMessagesRolledBack = withAgentClients2 $ \a b -> do + (_, bId1) <- runRight $ makeConnection a b + (_, bId2) <- runRight $ makeConnection a b + withTransaction (store $ agentEnv a) $ \db -> do + DB.execute_ db "CREATE TABLE failing_conns (conn_id BYTEA); CREATE FUNCTION fail_snd_message() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.conn_id IN (SELECT conn_id FROM failing_conns) THEN RAISE EXCEPTION 'test' USING ERRCODE = '23505'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_snd_message BEFORE INSERT ON snd_messages FOR EACH ROW EXECUTE FUNCTION fail_snd_message()" + DB.execute db "INSERT INTO failing_conns (conn_id) VALUES (?)" (Only bId2) + rs <- runRight $ sendMessages a [(bId1, PQEncOn, SMP.noMsgFlags, vrValue "hello"), (bId2, PQEncOn, SMP.noMsgFlags, vrValue "hello")] + map isRight rs `shouldBe` [False, False] + +runAM :: AgentClient -> AM a -> IO (Either AgentErrorType a) +runAM a action = runReaderT (runExceptT action) (agentEnv a) + +createConnAfterConflict :: HasTestEnv => ConnId -> IO (Either AgentErrorType ConnId) +createConnAfterConflict connId = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + withTransaction (store $ agentEnv a) (`DB.execute_` "CREATE SEQUENCE inserts; CREATE FUNCTION fail_first_insert() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF nextval('inserts') = 1 THEN RAISE EXCEPTION 'test' USING ERRCODE = '40P01'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_first_insert BEFORE INSERT ON connections FOR EACH ROW EXECUTE FUNCTION fail_first_insert()") + g <- C.newRandom + runAM a . withStore a $ \db -> + createNewConn db g ConnData {userId = 1, connId, connAgentVersion = VersionSMPA 1, enableNtfs = True, lastExternalSndId = 0, deleted = False, ratchetSyncState = RSOk, pqSupport = PQSupportOn, serviceRequestExpiresAt = Nothing} SCMInvitation + +deleteWithDeliveredMessage :: HasTestEnv => String -> (AgentClient -> (DB.Connection -> IO ()) -> UserId -> ConnId -> IO ()) -> Int -> IO () +deleteWithDeliveredMessage deleteQuery deleteRecord lockTime = withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + g <- C.newRandom + (userId, sq) <- withTransaction st $ createMessage g + msgPids <- newIORef [] + deleterPids <- newIORef [] + (deletingMsg, deleting) <- withTransaction st $ \db -> do + void (DB.query db "SELECT 1 FROM commands WHERE conn_id = ? FOR UPDATE" (Only connId) :: IO [Only Int]) + [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" + deleting <- async $ deleteRecord a (recordPid deleterPids) userId connId + waitForLock st holder deleteQuery + [deleter] <- readIORef deleterPids + deletingMsg <- async $ runAM a (withStore' a $ \db' -> recordPid msgPids db' >> deleteSndMsgDelivery db' connId sq (InternalId 1) False) `shouldReturn` Right () + waitForLock st deleter "DELETE FROM messages" + threadDelay lockTime + pure (deletingMsg, deleting) + wait deletingMsg + wait deleting + withTransaction st (\db -> DB.query db "SELECT count(*) FROM connections WHERE conn_id = ?" (Only connId)) `shouldReturn` [Only (0 :: Int)] + attempts <- (+) <$> (length <$> readIORef msgPids) <*> (length <$> readIORef deleterPids) + attempts `shouldSatisfy` (> 2) + where + connId = "conn1" :: ConnId + recordPid :: IORef [Int] -> DB.Connection -> IO () + recordPid pids db = do + [Only pid] <- DB.query_ db "SELECT pg_backend_pid()" + atomicModifyIORef' pids $ \ps -> (pid : ps, ()) + createMessage g db = do + userId <- createUserRecord db + DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (?,?,?)" (userId, connId, SCMInvitation) + (_, sndPrivateKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPubKey, dhPrivKey) <- atomically $ C.generateKeyPair g + let newSq = + SndQueue + { userId, + connId, + server = testSMPServer, + sndId = SMP.EntityId "1234", + queueMode = Just SMP.QMMessaging, + sndPrivateKey, + e2ePubKey = Nothing, + e2eDhSecret = C.dh' dhPubKey dhPrivKey, + status = New, + dbQueueId = DBNewEntity, + primary = True, + dbReplaceQueueId = Nothing, + sndSwchStatus = Nothing, + smpClientVersion = SMP.VersionSMPC 1 + } + Right sq <- updateNewConnSnd db connId newSq + DB.execute db "INSERT INTO messages (conn_id, internal_id, internal_ts, internal_snd_id, msg_type) VALUES (?, 1, now(), 1, '')" (Only connId) + DB.execute db "INSERT INTO snd_messages (conn_id, internal_snd_id, internal_id, internal_hash) VALUES (?, 1, 1, '')" (Only connId) + createSndMsgDelivery db sq (InternalId 1) + createCommand db "1" connId Nothing (AClientCommand $ NEW True (ACM SCMInvitation) IKPQOn SMSubscribe False) `shouldReturn` Right () + pure (userId, sq) #endif testClientServiceConnection :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () @@ -5408,6 +5989,24 @@ testServiceUnavailableOnStartup (t, msType) = do ("", "", UP _ [_]) <- nGet user exchangeGreetingsMsgId 6 service uId user sId +testServiceUnavailableFullQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testServiceUnavailableFullQueue (t, msType) = do + withAgentClientsServers2 (agentCfg, initAgentServersClientService) (agentCfg, initAgentServers) $ \service user -> + withSmpServerStoreLogOn (t, msType) testPort $ \_ -> runRight_ . void $ makeConnection service user + let cfgNoService = updateCfg (cfgMS msType) $ \(cfg' :: ServerConfig s) -> + let ServerConfig {transportConfig} = cfg' + in cfg' {transportConfig = transportConfig {askClientCert = False}} :: ServerConfig s + withAgent 1 agentCfg initAgentServersClientService testDB $ \service -> + withSmpServerConfigOn t cfgNoService testPort $ \_ -> do + fillSubQ service + timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ()) + void . atomically . flushTBQueue $ subQ service + getInAnyOrder + service + [ \case ("", "", AEvt SAEConn (ERR (BROKER _ NO_SERVICE))) -> True; _ -> False, + \case ("", "", AEvt SAENone (UP _ [_])) -> True; _ -> False + ] + testMigrateConnectionsToService :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testMigrateConnectionsToService ps = do (((sId1, uId1), (uId2, sId2)), ((sId3, uId3), (uId4, sId4)), ((sId5, uId5), (uId6, sId6))) <- diff --git a/tests/AgentTests/SQLiteTests.hs b/tests/AgentTests/SQLiteTests.hs index d1ebb155a..82c4143f4 100644 --- a/tests/AgentTests/SQLiteTests.hs +++ b/tests/AgentTests/SQLiteTests.hs @@ -475,10 +475,9 @@ testUpgradeRcvConnToDuplex = testSndQueueOfAnotherConn :: SpecWith DBStore testSndQueueOfAnotherConn = - it "should not add confirmed SndQueue of another connection" . withStoreTransaction $ \db -> do + it "should not add SndQueue of another connection" . withStoreTransaction $ \db -> do g <- C.newRandom Right (_, sq) <- createSndConn db g cData1 sndQueue1 - setSndQueueStatus db sq Confirmed Right _ <- createNewConn db g cData1 {connId = "conn2"} SCMInvitation updateNewConnSnd db "conn2" sndQueue1 `shouldReturn` Left SESndQueueExists @@ -489,7 +488,7 @@ testSndQueueOfAnotherConn = addConnSndQueue db "conn2" sndQueue1 `shouldReturn` Left SESndQueueExists getConn db "conn1" - `shouldReturn` Right (SomeConn SCSnd (SndConnection cData1 (sq {status = Confirmed} :: SndQueue))) + `shouldReturn` Right (SomeConn SCSnd (SndConnection cData1 sq)) testUpgradeSndConnToDuplex :: SpecWith DBStore testUpgradeSndConnToDuplex = diff --git a/tests/CLITests.hs b/tests/CLITests.hs index 38fcb90cf..33e9b5cb0 100644 --- a/tests/CLITests.hs +++ b/tests/CLITests.hs @@ -13,10 +13,11 @@ import qualified Crypto.PubKey.RSA as RSA import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as BL import qualified Data.HashMap.Strict as HM -import Data.Ini (Ini (..), lookupValue, readIniFile, writeIniFile) +import Data.Ini (Ini (..), lookupValue, parseIni, readIniFile, writeIniFile) import Data.List (isInfixOf, isPrefixOf) import Data.Maybe (mapMaybe) import qualified Data.Text as T +import Data.Time.Calendar (fromGregorian) import qualified Data.X509 as X import qualified Data.X509.File as XF import Data.X509.Validation (Fingerprint (..)) @@ -30,7 +31,8 @@ import Simplex.FileTransfer.Server.Main (xftpServerCLI) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Server.CLI (simplexmqVersionCommit) import Simplex.Messaging.Server.Env.STM (ServerConfig (serverStoreCfg), ServerStoreCfg (SSCMemory), checkHTTPSCredentials, newEnv) -import Simplex.Messaging.Server.Main (smpServerCLI, smpServerCLI_) +import Simplex.Messaging.Server.Information (ClientSupport (..), MinClientVersion (..), ServerPublicInfo (clientSupport)) +import Simplex.Messaging.Server.Main (serverPublicInfo, smpServerCLI, smpServerCLI_) import Simplex.Messaging.Transport (TLS (..), Transport (cGet, cPut, getLn), TransportPeer (..), defaultSupportedParams, defaultSupportedParamsHTTPS, supportedClientSMPRelayVRange) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), defaultTransportClientConfig, runTLSTransportClient, smpClientHandshake) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC @@ -42,7 +44,7 @@ import System.Directory (doesFileExist) import System.Environment (withArgs) import System.Exit (ExitCode (..)) import System.FilePath (()) -import System.IO.Silently (capture_) +import System.IO.Silently (capture, capture_) import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Test.Main (ProcessResult (..), captureProcessResult, withStdin) @@ -57,6 +59,7 @@ import qualified Database.PostgreSQL.Simple as PSQL import Database.PostgreSQL.Simple.Types (Query (..)) import NtfClient (ntfTestServerDBConnectInfo, ntfTestServerDBConnstr, ntfTestServerDBOpts) import SMPClient (postgressBracket) +import XFTPClient (testXFTPDBConnectInfo) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Notifications.Server.Main #endif @@ -92,6 +95,8 @@ cliTests = do it "with store log, no password" $ smpServerTest True False it "static files" smpServerTestStatic it "cloud scripts disable embedded web without certificates" smpCloudScriptsDisableWeb + it "should not start with invalid stats_save_interval" smpServerInvalidStatsSaveInterval + it "reads client support information" smpServerClientSupport #if defined(dbServerPostgres) around_ (postgressBracket ntfTestServerDBConnectInfo) $ before_ (createNtfSchema ntfTestServerDBConnectInfo ntfTestServerDBOpts) $ describe "Ntf server CLI" $ do @@ -101,6 +106,12 @@ cliTests = do describe "XFTP server CLI" $ do it "should initialize, start and delete the server (no store log)" $ xftpServerTest False it "should initialize, start and delete the server (with store log)" $ xftpServerTest True + it "should exit in maintenance mode without starting the server" xftpServerMaintenanceTest +#if defined(dbServerPostgres) + around_ (postgressBracket testXFTPDBConnectInfo) $ + describe "XFTP server CLI with PostgreSQL" $ + it "should apply database migrations in maintenance mode" xftpServerMaintenanceDBTest +#endif describe "Static site on HTTPS port" $ do it "should serve the replaced web certificate with a 4096-bit RSA key without restart" testStaticSiteCertReload it "should throw the error of an invalid credential at start" testStaticSiteInvalidCredential @@ -278,6 +289,21 @@ testStartInvalidCredential = do (prExitCode, show <$> prException) `shouldBe` (ExitFailure 1, Nothing) prStdout `shouldBe` "invalid credential: no private key\n" +smpServerInvalidStatsSaveInterval :: HasTestEnv => IO () +smpServerInvalidStatsSaveInterval = do + let iniFile = cfgPath <> "/smp-server.ini" + capture_ (withArgs ["init", "-y", "--no-password"] $ smpServerCLI cfgPath logPath) + >>= (`shouldSatisfy` (("Server initialized, please provide additional server information in " <> iniFile) `isPrefixOf`)) + Right ini <- readIniFile iniFile + writeIniFile iniFile ini {iniSections = HM.adjust (("stats_save_interval", "0") :) "STORE_LOG" (iniSections ini)} + capture_ (withArgs ["start"] $ 5000000 `timeout` smpServerCLI cfgPath logPath) + `shouldThrow` errorCall "invalid INI setting stats_save_interval: 0" +smpServerClientSupport :: HasCallStack => IO () +smpServerClientSupport = do + Right ini <- pure $ parseIni "[INFORMATION]\nsource_code = https://github.com/simplex-chat/simplexmq\nclient_min_version = 24\nclient_min_version_date = 2027-05-01\nclient_stable_release = 7.2.0\n" + (clientSupport =<< serverPublicInfo ini) + `shouldBe` Just ClientSupport {minClientVersion = Just MinClientVersion {protocolVersion = 24, fromDate = fromGregorian 2027 5 1}, stableRelease = Just "7.2.0", betaRelease = Nothing} + smpCloudScriptsDisableWeb :: HasCallStack => IO () smpCloudScriptsDisableWeb = do linode <- readFile "scripts/smp-server-linode.sh" @@ -324,17 +350,64 @@ ntfServerTest storeLog = do xftpServerTest :: HasTestEnv => Bool -> IO () xftpServerTest storeLog = do - capture_ (withArgs (["init", "-p", testDir, "-q", "10gb"] <> ["--disable-store-log" | not storeLog]) $ xftpServerCLI fileCfgPath fileLogPath) - >>= (`shouldSatisfy` (("Server initialized, you can modify configuration in " <> fileCfgPath <> "/file-server.ini") `isPrefixOf`)) + xftpServerInit storeLog Right ini <- readIniFile $ fileCfgPath <> "/file-server.ini" lookupValue "STORE_LOG" "enable" ini `shouldBe` Right (if storeLog then "on" else "off") lookupValue "STORE_LOG" "log_stats" ini `shouldBe` Right "off" lookupValue "TRANSPORT" "port" ini `shouldBe` Right "443" + lookupValue "INACTIVE_CLIENTS" "disconnect" ini `shouldBe` Right "on" + lookupValue "INACTIVE_CLIENTS" "ttl" ini `shouldBe` Right "21600" + lookupValue "INACTIVE_CLIENTS" "check_interval" ini `shouldBe` Right "3600" doesFileExist (fileCfgPath <> "/ca.key") `shouldReturn` True r <- lines <$> capture_ (withArgs ["start"] $ (100000 `timeout` xftpServerCLI fileCfgPath fileLogPath) `catchAll_` pure (Just ())) r `shouldContain` ["SimpleX XFTP server v" <> simplexmqVersionCommit] r `shouldContain` (if storeLog then ["Store log: " <> fileLogPath <> "/file-server-store.log"] else ["Store log disabled."]) r `shouldContain` ["Listening on port 443..."] + xftpServerDelete + +xftpMaintenanceMessage :: String +xftpMaintenanceMessage = "Server started in 'maintenance' mode, exiting" + +xftpServerInit :: HasTestEnv => Bool -> IO () +xftpServerInit storeLog = + capture_ (withArgs (["init", "-p", testDir, "-q", "10gb"] <> ["--disable-store-log" | not storeLog]) $ xftpServerCLI fileCfgPath fileLogPath) + >>= (`shouldSatisfy` (("Server initialized, you can modify configuration in " <> fileCfgPath <> "/file-server.ini") `isPrefixOf`)) + +xftpServerMaintenance :: HasTestEnv => [String] -> IO () +xftpServerMaintenance opts = do + (out, r) <- capture (withArgs (["start", "--maintenance"] <> opts) (5000000 `timeout` xftpServerCLI fileCfgPath fileLogPath) `catchAll_` pure (Just ())) + r `shouldBe` Just () + let ls = lines out + ls `shouldContain` [xftpMaintenanceMessage] + ls `shouldNotContain` ["Listening on port 443..."] + +xftpServerDelete :: HasTestEnv => IO () +xftpServerDelete = do capture_ (withStdin "Y" . withArgs ["delete"] $ xftpServerCLI fileCfgPath fileLogPath) >>= (`shouldSatisfy` ("WARNING: deleting the server will make all queues inaccessible" `isPrefixOf`)) - doesFileExist (cfgPath <> "/ca.key") `shouldReturn` False + doesFileExist (fileCfgPath <> "/ca.key") `shouldReturn` False + +xftpServerMaintenanceTest :: HasTestEnv => IO () +xftpServerMaintenanceTest = do + xftpServerInit False + xftpServerMaintenance [] + xftpServerDelete + +#if defined(dbServerPostgres) +xftpServerMaintenanceDBTest :: HasTestEnv => IO () +xftpServerMaintenanceDBTest = do + xftpServerInit False + let iniFile = fileCfgPath <> "/file-server.ini" + schema = "xftp_server_cli" + dbSettings = [("store_files", "database"), ("db_connection", "postgresql://test_xftp_server_user@/test_xftp_server_db"), ("db_schema", T.pack schema)] + setDB = (<> dbSettings) . filter ((/= "store_files") . fst) + Right ini <- readIniFile iniFile + writeIniFile iniFile ini {iniSections = HM.adjust setDB "STORE_LOG" (iniSections ini)} + db <- PSQL.connect testXFTPDBConnectInfo + void $ PSQL.execute_ db $ Query $ "CREATE SCHEMA " <> B.pack schema + xftpServerMaintenance ["--confirm-migrations", "up"] + [PSQL.Only migrations] <- PSQL.query_ db $ Query $ "SELECT count(*) FROM " <> B.pack schema <> ".migrations" + migrations `shouldSatisfy` (> (0 :: Int)) + PSQL.close db + xftpServerDelete +#endif diff --git a/tests/CoreTests/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/CoreTests/CryptoTests.hs b/tests/CoreTests/CryptoTests.hs index 27ee6680c..26d0c4251 100644 --- a/tests/CoreTests/CryptoTests.hs +++ b/tests/CoreTests/CryptoTests.hs @@ -21,6 +21,7 @@ import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Either (isLeft, isRight) import Data.Int (Int64) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) @@ -46,6 +47,7 @@ import Simplex.Messaging.Crypto.SNTRUP761.Bindings.FFI (c_sntrup761_keypair) import Simplex.Messaging.Crypto.SNTRUP761.Bindings.RNG (RNGFunc) import Simplex.Messaging.Encoding (Large (..), smpDecode, smpEncode) import Simplex.Messaging.Encoding.String (strDecode, strEncode) +import Simplex.Messaging.Parsers (parseAll) import Simplex.Messaging.Transport.Client import Simplex.Messaging.Transport.Credentials (genCredentials) import System.Timeout (timeout) @@ -124,8 +126,10 @@ cryptoTests = do describe "Ed448" $ testEncoding C.SEd448 describe "X25519" $ testEncoding C.SX25519 describe "X448" $ testEncoding C.SX448 + it "should not decode keys with invalid encoding" testInvalidKeyEncoding describe "X509 chains" $ do it "should validate certificates" testValidateX509 + it "should not decode certificates with invalid encoding" testInvalidCertEncoding describe "sntrup761" $ do it "should enc/dec key" testSNTRUP761 it "should reject malformed KEM encodings" testSNTRUP761RejectsMalformedEncodings @@ -289,6 +293,15 @@ testEncoding alg = it "should encode / decode key" . ioProperty $ do C.decodePubKey (C.encodePubKey k) == Right k && C.decodePrivKey (C.encodePrivKey pk) == Right pk +testInvalidKeyEncoding :: IO () +testInvalidKeyEncoding = do + C.decodePubKey @C.APublicKey "\x30\x0a\x30\x05\x06\x03\x2b\x65\x6e\x03\x01\x3d" `shouldBe` Left bitStringError + C.decodePubKey @C.APublicKey "\x02\x01\x00\x03\x01\x3d" `shouldBe` Left bitStringError + C.decodePubKey @C.APublicKey ("\x30\x2a\x30\x05\x06\x03\x2b\x65\x6e\x03\x21\x00" <> B.replicate 32 '\1' <> "\x03\x01\x3d") `shouldBe` Left bitStringError + C.decodePrivKey @C.APrivateKey "\x30\x0f\x02\x01\x00\x30\x05\x06\x03\x2b\x65\x6e\x04\x03\x03\x01\x3d" `shouldBe` Left bitStringError + where + bitStringError = "TypeDecodingFailed \"bitstring: skip number not within bound 61 \\\"=\\\"\"" + testValidateX509 :: IO () testValidateX509 = do let checkChain = validateCertificateChain SMPClient.testKeyHash "localhost" "5223" . X.CertificateChain @@ -349,6 +362,24 @@ testValidateX509 = do otherLeaf <- genCredentials g (Just otherCA) (1, 24) "leaf" checkPinned [otherLeaf, ident, otherCA] `shouldReturn` [XV.UnknownCA, XV.UnknownCA] +testInvalidCertEncoding :: IO () +testInvalidCertEncoding = do + g <- C.newRandom + (k, _) <- atomically $ C.generateSignatureKeyPair C.SEd25519 g + (_, cert) <- genCredentials g Nothing (1, 24) "root" + let invalidBitString = "\x30\x03\x03\x01\x3d" + emptySignatureOID = "\x30\x35\x30\x2c" <> C.encodePubKey k <> "\x30\x02\x06\x00\x03\x01\x00" + emptySignatureOIDCert = "\x30\x82" <> smpEncode (Large $ X.getSignedData cert <> "\x30\x02\x06\x00\x03\x01\x00") + signedKey invalidBitString `shouldSatisfy` isLeft + signedKey emptySignatureOID `shouldSatisfy` isLeft + parseAll C.certChainP (smpEncode $ Large invalidBitString :| []) `shouldSatisfy` isLeft + strDecode @X.CertificateChain (strEncode invalidBitString) `shouldSatisfy` isLeft + X.decodeCertificateChain (X.CertificateChainRaw [emptySignatureOIDCert]) `shouldSatisfy` isRight + parseAll C.certChainP (smpEncode $ Large emptySignatureOIDCert :| []) `shouldSatisfy` isLeft + strDecode @X.CertificateChain (strEncode emptySignatureOIDCert) `shouldSatisfy` isLeft + where + signedKey s = C.getSignedExact <$> smpDecode @(C.SignedObject X.PubKey) (smpEncode $ Large s) + testSNTRUP761 :: IO () testSNTRUP761 = do drg <- C.newRandom diff --git a/tests/CoreTests/EncodingTests.hs b/tests/CoreTests/EncodingTests.hs index 4108bef2a..fbc3cdfb3 100644 --- a/tests/CoreTests/EncodingTests.hs +++ b/tests/CoreTests/EncodingTests.hs @@ -16,7 +16,7 @@ import Data.Time.ISO8601 (parseISO8601) import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (parseAll) -import Simplex.Messaging.Protocol (ProtocolServer (..), XFTPServer) +import Simplex.Messaging.Protocol (NtfServer, ProtoServerWithAuth (..), ProtocolServer (..), SMPServer, XFTPServer, legacyStrEncodeServer) import Simplex.Messaging.ServiceScheme (ServiceScheme (..), SrvLoc (..)) import Simplex.Messaging.Transport.Client (TransportHost (..)) import Test.Hspec hiding (fit, it) @@ -81,6 +81,8 @@ encodingTests = modifyMaxSuccess (const 1000) $ do shouldReject @TransportHost "[simplex.chat]" shouldReject @TransportHost "[smp.simplex.im]" describe "Encoding service locations" $ do + it "should encode and decode bracketed IPv6 host with implicit HTTPS port" $ + (SSAppServer $ SrvLoc ipv6Host "") #==# "https://[2001:db8::1]" it "should parse bracketed IPv6 host with port" $ do strDecode @ServiceScheme "https://[2001:db8::1]:8443" `shouldBe` Right (SSAppServer $ SrvLoc "2001:db8::1" "8443") @@ -89,12 +91,38 @@ encodingTests = modifyMaxSuccess (const 1000) $ do it "should reject bracketed non-IPv6 host" $ shouldReject @ServiceScheme "https://[simplex.chat]:8443" describe "Encoding protocol servers" $ do - it "should parse bracketed IPv6 server host with port" $ - case strDecode @XFTPServer "xftp://1234-w==@[2001:db8::1]:443" of - Left err -> expectationFailure err - Right (ProtocolServer _ parsedHost parsedPort _) -> do - parsedHost `shouldBe` (ipv6Host :| []) - parsedPort `shouldBe` "443" + it "should canonically round-trip IPv6 server hosts and ports" $ do + let xftp = either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer + ipv6Server = xftp {host = ipv6Host :| [], port = "5223"} + defaultPortServer = ipv6Server {port = ""} + ipv6First = ipv6Server {host = ipv6Host :| ["example.com"]} + ipv6Last = ipv6Server {host = "example.com" :| [ipv6Host]} + ipv6Server #==# "xftp://1234-w==@[2001:db8::1]:5223" + defaultPortServer #==# "xftp://1234-w==@[2001:db8::1]" + ipv6First #==# "xftp://1234-w==@[2001:db8::1],example.com:5223" + ipv6Last #==# "xftp://1234-w==@example.com,[2001:db8::1]:5223" + ipv6First {port = ""} #==# "xftp://1234-w==@[2001:db8::1],example.com" + ipv6Last {port = ""} #==# "xftp://1234-w==@example.com,[2001:db8::1]" + it "should bracket IPv6 for each protocol and authenticated and legacy encoders" $ do + let smp = (either error id (strDecode "smp://1234-w==@example.com:5223") :: SMPServer) {host = ipv6Host :| []} + ntf = (either error id (strDecode "ntf://1234-w==@example.com:5223") :: NtfServer) {host = ipv6Host :| []} + xftp = (either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer) {host = ipv6Host :| ["example.com"]} + strEncode smp `shouldBe` "smp://1234-w==@[2001:db8::1]:5223" + strDecode (strEncode smp) `shouldBe` Right smp + strEncode ntf `shouldBe` "ntf://1234-w==@[2001:db8::1]:5223" + strDecode (strEncode ntf) `shouldBe` Right ntf + let authenticated = ProtoServerWithAuth xftp (Just "user") + legacy = legacyStrEncodeServer xftp + strEncode authenticated `shouldBe` "xftp://1234-w==:user@[2001:db8::1],example.com:5223" + strDecode (strEncode authenticated) `shouldBe` Right authenticated + legacy `shouldBe` "xftp://1234-w==@[2001:db8::1]:5223" + strDecode legacy `shouldBe` Right xftp {host = ipv6Host :| []} + it "should preserve non-IPv6 server encodings" $ do + let xftp = either error id (strDecode "xftp://1234-w==@example.com:5223") :: XFTPServer + strEncode xftp {host = THIPv4 (192, 0, 2, 1) :| []} `shouldBe` "xftp://1234-w==@192.0.2.1:5223" + strEncode xftp `shouldBe` "xftp://1234-w==@example.com:5223" + strEncode xftp {host = "beccx4yfxxbvyhqypaavemqurytl6hozr47wfc7uuecacjqdvwpw2xid.onion" :| []} + `shouldBe` "xftp://1234-w==@beccx4yfxxbvyhqypaavemqurytl6hozr47wfc7uuecacjqdvwpw2xid.onion:5223" it "should reject bracketed non-IPv6 server host" $ shouldReject @XFTPServer "xftp://1234-w==@[simplex.chat]:443" where diff --git a/tests/CoreTests/KeepAliveTests.hs b/tests/CoreTests/KeepAliveTests.hs new file mode 100644 index 000000000..aa70bddad --- /dev/null +++ b/tests/CoreTests/KeepAliveTests.hs @@ -0,0 +1,45 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE NumericUnderscores #-} + +module CoreTests.KeepAliveTests where + +import Control.Exception (bracket, handle) +import Control.Monad (forever) +import qualified Data.ByteString.Char8 as B +import Data.Time.Clock (diffUTCTime, getCurrentTime) +import Foreign.C (CInt) +import Foreign.C.Error (Errno (..), eTIMEDOUT) +import GHC.IO.Exception (IOException (..)) +import Network.Socket +import Network.Socket.ByteString (sendAll) +import Simplex.Messaging.Transport.KeepAlive +import System.Info (os) +import System.Timeout (timeout) +import Test.Hspec hiding (fit, it) +import Util + +keepAliveTests :: Spec +keepAliveTests = linuxOnly $ it "should fail connection with data not accepted by peer only with unackedDataTimeout" testUnackedDataTimeout + where + linuxOnly t = if os == "linux" then t else before_ (pendingWith "Linux only") t + +testUnackedDataTimeout :: IO () +testUnackedDataTimeout = do + start <- getCurrentTime + sendToPeerNotReading (Just True) `shouldReturn` Just (Just timedOut) + (`diffUTCTime` start) <$> getCurrentTime >>= (`shouldSatisfy` (>= 2)) + sendToPeerNotReading Nothing `shouldReturn` Nothing + where + Errno timedOut = eTIMEDOUT + +sendToPeerNotReading :: Maybe Bool -> IO (Maybe (Maybe CInt)) +sendToPeerNotReading unackedDataTimeout = + bracket (socket AF_INET Stream defaultProtocol) close $ \srv -> do + bind srv $ SockAddrInet 0 $ tupleToHostAddress (127, 0, 0, 1) + listen srv 1 + addr <- getSocketName srv + bracket (socket AF_INET Stream defaultProtocol) close $ \c -> do + setSocketKeepAlive c KeepAliveOpts {keepIdle = 1, keepIntvl = 1, keepCnt = 1, unackedDataTimeout} + connect c addr + bracket (fst <$> accept srv) close $ \_ -> + timeout 8_000000 $ handle (pure . ioe_errno) $ forever $ sendAll c $ B.replicate 65536 'x' diff --git a/tests/CoreTests/MsgStoreTests.hs b/tests/CoreTests/MsgStoreTests.hs index df8fe96cd..20717336e 100644 --- a/tests/CoreTests/MsgStoreTests.hs +++ b/tests/CoreTests/MsgStoreTests.hs @@ -23,22 +23,28 @@ import Control.Monad.IO.Class import Control.Monad.Trans.Except import Crypto.Random (ChaChaDRG) import Data.ByteString.Char8 (ByteString) +import qualified Data.ByteString.Char8 as B +import Data.Functor (($>)) import Data.Int (Int64) import qualified Data.Map.Strict as M import Data.Time.Clock.System (SystemTime (..), getSystemTime) import Simplex.Messaging.Crypto (pattern MaxLenBS) import qualified Simplex.Messaging.Crypto as C -import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), noMsgFlags, randomMsgId) +import Simplex.Messaging.Encoding.String (strEncode) +import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), linkDataHash, noMsgFlags, randomMsgId) import Simplex.Messaging.Server.MsgStore.STM import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.NtfStore import Simplex.Messaging.Server.QueueStore import Simplex.Messaging.Server.QueueStore.QueueInfo -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), withLog') +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), readQueueRecIO, withLog') import Simplex.Messaging.Server.QueueStore.Types -import Simplex.Messaging.Server.StoreLog (closeStoreLog, openWriteStoreLog) +import Simplex.Messaging.Server.StoreLog (StoreLogRecord (..), closeStoreLog, openWriteStoreLog) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM +import Simplex.Messaging.Util (($>>=)) +import SMPClient (testStoreLogFile) +import System.IO.Unsafe (unsafeInterleaveIO) import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Util @@ -48,13 +54,15 @@ import AgentTests.FunctionalAPITests (runRight) import Control.Concurrent (forkIO) import Control.Concurrent.Async (AsyncCancelled (..), async, cancel, waitCatch) import qualified Control.Exception as E +import Data.List (sortOn) import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB import Simplex.Messaging.Agent.Store.Postgres.Common import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) +import Simplex.Messaging.Protocol (messageId) import Simplex.Messaging.Server.MsgStore.Postgres import Simplex.Messaging.Server.QueueStore.Postgres -import SMPClient (testStoreDBOpts) +import SMPClient (deadlockOnce, testStoreDBOpts) #endif msgStoreTests :: Spec @@ -63,14 +71,20 @@ msgStoreTests = do someMsgStoreTests testSMTStoreConfig it "should remove deleted queues from queue store maps" $ withMsgStore testSMTStoreConfig testDeleteQueueMaps it "should time out store log write" testStoreLogTimeout + it "should end the thread cancelled during store log write" testCancelStoreLogWrite + it "should log the queue change of the thread cancelled before store log write" $ withMsgStore testSMTStoreConfig testCancelBeforeStoreLogWrite #if defined(dbServerPostgres) describe "Postgres-only message store" $ do someMsgStoreTests testPostgresStoreConfig it "should correctly update message counts and canWrite flag" $ withMsgStore testPostgresStoreConfig testUpdateMessageCounts it "tryDelPeekMsg (ACK not from NSE) should reset message counts when queue is empty" $ withMsgStore testPostgresStoreConfig testResetMessageCounts + it "should fold service messages in pages without holding a database connection" $ withMsgStore testPostgresStoreConfig testFoldServiceMessagesInPages it "should expire messages across commit batches" $ withMsgStore testPostgresStoreConfig testExpireMessagesInBatches it "should fail database operations after the store is closed" $ withMsgStore testPostgresStoreConfig testClosedStore it "should time out database operation" $ withMsgStore testPostgresStoreConfig testDBOperationTimeout + it "should retry a message write aborted by a deadlock" $ withMsgStore testPostgresStoreConfig testWriteMsgDeadlock + it "should end the thread cancelled during database transaction" $ withMsgStore testPostgresStoreConfig testCancelDBTransaction + it "should end the thread cancelled during database query" $ withMsgStore testPostgresStoreConfig testCancelDBQuery it "should stop when cancelled during reconnect after database error" $ withMsgStore testPostgresStoreConfig testReconnectCancel #endif describe "Notification store" $ do @@ -83,6 +97,8 @@ msgStoreTests = do it "should write/ack messages" $ withMsgStore cfg testWriteAckMessages it "should peek the first message of each queue in a batch" $ withMsgStore cfg testPeekMsgs it "should not add link data to secured messaging queue" $ withMsgStore cfg testLinkDataSecuredQueue + it "should not update recipient keys changed after the command was verified" $ withMsgStore cfg testUpdateChangedKeys + it "should swap link data and recipient keys" $ withMsgStore cfg testSwapQueueLinkData -- TODO constrain to STM stores? withMsgStore :: MsgStoreClass s => MsgStoreConfig s -> (s -> IO ()) -> IO () @@ -282,6 +298,60 @@ testLinkDataSecuredQueue ms = do void $ ExceptT $ deleteQueue ms q void $ ExceptT $ deleteQueue ms cq +testUpdateChangedKeys :: MsgStoreClass s => s -> IO () +testUpdateChangedKeys ms = do + g <- C.newRandom + (k1, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (k2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let st = queueStore ms + (rId, qr@QueueRec {recipientKeys = ks}) <- testNewQueueRec g QMContact + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + ExceptT $ updateKeys st q (Just ks) [k1] + liftIO $ updateKeys st q (Just ks) [k2] `shouldReturn` Left AUTH + (_, QueueRec {recipientKeys}) <- ExceptT $ getQueueRec ms SRecipient rId + liftIO $ recipientKeys `shouldBe` [k1] + void $ ExceptT $ deleteQueue ms q +testSwapQueueLinkData :: MsgStoreClass s => s -> IO () +testSwapQueueLinkData ms = do + g <- C.newRandom + (rKey2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let st = queueStore ms + rndId = atomically $ EntityId <$> C.randomBytes 24 g + (fd, ud) = testLinkData + d1 = (fd, EncDataBytes "user data 1") + d2 = (fd, EncDataBytes "user data 2") + lnkId <- rndId + otherLnkId <- rndId + (rId, qr) <- testNewQueueRecData g QMContact (Just (lnkId, testLinkData)) + (noLinkRId, noLinkQr) <- testNewQueueRec g QMContact + let rKeys = recipientKeys qr <> [rKey2] + storedKeys = fmap recipientKeys <$> (getQueue ms SRecipient rId $>>= readQueueRecIO . queueRec) + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + noLinkQ <- ExceptT $ addQueue ms noLinkRId noLinkQr + liftIO $ do + swapQueueLinkData st noLinkQ lnkId (linkDataHash ud) Nothing d1 `shouldReturn` Left AUTH + swapQueueLinkData st q otherLnkId (linkDataHash ud) Nothing d1 `shouldReturn` Left AUTH + swapQueueLinkData st q lnkId (linkDataHash ud) Nothing (EncDataBytes "other fixed data", snd d1) `shouldReturn` Left AUTH + swapQueueLinkData st q lnkId (linkDataHash $ snd d1) (Just rKeys) d1 `shouldReturn` Right (Just ud) + getQueueLinkData st q lnkId `shouldReturn` Right testLinkData + storedKeys `shouldReturn` Right (recipientKeys qr) + swapQueueLinkData st q lnkId (linkDataHash ud) Nothing d1 `shouldReturn` Right Nothing + getQueueLinkData st q lnkId `shouldReturn` Right d1 + staleQ <- ExceptT $ getQueue ms SRecipient rId + liftIO $ do + swapQueueLinkData st q lnkId (linkDataHash $ snd d1) (Just rKeys) d2 `shouldReturn` Right Nothing + getQueueLinkData st q lnkId `shouldReturn` Right d2 + storedKeys `shouldReturn` Right rKeys + addQueueLinkData st staleQ lnkId d1 `shouldReturn` Left AUTH + freshQ <- ExceptT $ getQueue ms SRecipient rId + liftIO $ do + addQueueLinkData st freshQ lnkId d1 `shouldReturn` Left AUTH + getQueueLinkData st freshQ lnkId `shouldReturn` Right d2 + void $ ExceptT $ deleteQueue ms q + void $ ExceptT $ deleteQueue ms noLinkQ + -- sizes of queues, senders, links and notifiers maps type QueueMapSizes = (Int, Int, Int, Int) @@ -335,6 +405,23 @@ testStoreLogTimeout = do sl_ <- newTVarIO $ Just sl timeout 100000 (withLog' "test" sl_ $ \_ -> threadDelay 500000) `shouldReturn` Nothing closeStoreLog sl +testCancelStoreLogWrite :: HasTestEnv => IO () +testCancelStoreLogWrite = + bracket (openWriteStoreLog False testStoreLogFile) closeStoreLog $ \sl -> do + sl' <- newTVarIO $ Just sl + testCancelledInside $ \waitCancel -> withLog' "test" sl' $ \_ -> waitCancel + +testCancelBeforeStoreLogWrite :: HasTestEnv => STMMsgStore -> IO () +testCancelBeforeStoreLogWrite ms = do + g <- C.newRandom + (rId, qr) <- testNewQueueRec g QMMessaging + Right q <- addQueue ms rId qr + bracket (openWriteStoreLog False testStoreLogFile) closeStoreLog $ \sl -> + testCancelledInside $ \waitCancel -> do + slAfterCancel <- unsafeInterleaveIO $ waitCancel $> Just sl + sl' <- newTVarIO slAfterCancel + deleteStoreQueue (queueStore ms) {storeLog = sl'} q + B.readFile testStoreLogFile `shouldReturn` strEncode (DeleteQueue rId) <> "\n" mkMsgNtf :: TVar ChaChaDRG -> Int64 -> IO MsgNtf mkMsgNtf g ts = do @@ -457,6 +544,29 @@ testResetMessageCounts ms = do void $ withTransaction (dbStore $ queueStore ms) $ \db -> DB.execute db "UPDATE msg_queues SET msg_queue_size = ?, msg_can_write = ? WHERE recipient_id = ?" (size, canWrt, recipientId q) +testFoldServiceMessagesInPages :: PostgresMsgStore -> IO () +testFoldServiceMessagesInPages ms = do + g <- C.newRandom + serviceId <- atomically $ EntityId <$> C.randomBytes 24 g + void $ withTransaction st $ \db -> + DB.execute db "INSERT INTO services (service_id, service_role, service_cert, service_cert_hash, created_at) VALUES (?, 'M', '', '', 0)" (Only serviceId) + void $ newQueue g Nothing + qs <- replicateM 150 $ newQueue g (Just serviceId) + runRight_ $ forM_ (take 75 qs) $ \q -> writeMsg ms q True =<< mkMessage "message" + expected <- runRight $ forM qs $ \q -> do + msg_ <- tryPeekMsg ms q + pure (recipientId q, (Right (messageId <$> msg_), dbPoolSize st)) + Right folded <- foldRcvServiceMessages ms serviceId collect [] + sortOn fst folded `shouldBe` sortOn fst expected + where + st = dbStore $ queueStore ms + newQueue g rcvServiceId = do + (rId, qr) <- testNewQueueRec g QMMessaging + runRight $ ExceptT $ addQueue ms rId qr {rcvServiceId} + collect acc rId r = do + freeConns <- fromIntegral <$> atomically (lengthTBQueue $ dbPoolConns $ dbPool st) + pure $ (rId, (fmap (messageId . snd) <$> r, freeConns)) : acc + testExpireMessagesInBatches :: PostgresMsgStore -> IO () testExpireMessagesInBatches ms = do g <- C.newRandom @@ -510,6 +620,25 @@ testDBOperationTimeout :: PostgresMsgStore -> IO () testDBOperationTimeout ms = timeout 100000 (runExceptT $ withDB' "test" (queueStore ms) $ \_ -> threadDelay 500000) `shouldReturn` Nothing +testWriteMsgDeadlock :: PostgresMsgStore -> IO () +testWriteMsgDeadlock ms = do + g <- C.newRandom + (rId, qr) <- testNewQueueRec g QMMessaging + void $ withTransaction (dbStore $ queueStore ms) $ \db -> DB.execute_ db $ deadlockOnce "INSERT ON messages" + runRight_ $ do + q <- ExceptT $ addQueue ms rId qr + Just (_, True) <- writeMsg ms q True =<< mkMessage "message 1" + Msg "message 1" <- tryPeekMsg ms q + checkQueueSize ms q (1, True) +testCancelDBTransaction :: PostgresMsgStore -> IO () +testCancelDBTransaction ms = + testCancelledInside $ \waitCancel -> runExceptT $ withDB' "test" (queueStore ms) $ \_ -> waitCancel + +testCancelDBQuery :: PostgresMsgStore -> IO () +testCancelDBQuery ms = + testCancelledWhenBlocked $ \started -> runExceptT $ withDB' "test" (queueStore ms) $ \db -> + started >> (DB.query_ db "SELECT pg_sleep(10)" :: IO [Only ()]) + testReconnectCancel :: PostgresMsgStore -> IO () testReconnectCancel ms = do let st = dbStore $ queueStore ms diff --git a/tests/CoreTests/SOCKSSettings.hs b/tests/CoreTests/SOCKSSettings.hs index a56be966e..d46a87015 100644 --- a/tests/CoreTests/SOCKSSettings.hs +++ b/tests/CoreTests/SOCKSSettings.hs @@ -3,18 +3,35 @@ {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} module CoreTests.SOCKSSettings where -import Network.Socket (SockAddr (..), tupleToHostAddress) +import Control.Concurrent (forkIO) +import Control.Concurrent.Async (race_, withAsync) +import Control.Concurrent.STM +import qualified Control.Exception as E +import Control.Monad +import qualified Data.ByteString as BS +import Data.ByteString.Char8 (ByteString) +import qualified Data.ByteString.Char8 as B +import Data.Time.Clock (getCurrentTime) +import Data.Word (Word8) +import Network.Socket +import Network.Socket.ByteString (recv, sendAll) +import SMPClient (testKeyHash, testPort, withSmpServerConfigOn) +import qualified SMPClient import Simplex.Messaging.Agent.Client (ipAddressProtected) import Simplex.Messaging.Client import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String import Simplex.Messaging.Protocol (ErrorType, pattern SMPServer) +import Simplex.Messaging.Transport (TLS, transport) import Simplex.Messaging.Transport.Client +import Simplex.Messaging.Transport.KeepAlive +import Simplex.Messaging.Transport.Server (startTCPServer) import Test.Hspec hiding (fit, it) import Util @@ -24,6 +41,7 @@ socksSettingsTests = do describe "socksMode setting, independent of hostMode setting" testSocksMode describe "ipAddressProtected, consistent with chosen host and socksMode" testIPAddressProtected describe "socks proxy address encoding" testSocksProxyEncoding + describe "socks proxy connection" testSocksProxyConnection testPublicHost :: TransportHost testPublicHost = "smp.example.com" @@ -92,11 +110,20 @@ testSocksMode = do transportSocks (Just defaultSocksProxyWithAuth) SMAlways testOnionHost `shouldBe` Just defaultSocksProxy transportSocks (Just defaultSocksProxyWithAuth) SMOnion testPublicHost `shouldBe` Nothing transportSocks (Just defaultSocksProxyWithAuth) SMOnion testOnionHost `shouldBe` Just defaultSocksProxy + it "should remove unackedDataTimeout only if SOCKS proxy is used" $ do + transportUnackedTimeout Nothing SMAlways testPublicHost `shouldBe` Just True + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMOnion testPublicHost `shouldBe` Just True + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMAlways testPublicHost `shouldBe` Nothing + transportUnackedTimeout (Just defaultSocksProxyWithAuth) SMOnion testOnionHost `shouldBe` Nothing where transportSocks proxy socksMode = transportSocksCfg defaultNetworkConfig {socksProxy = proxy, socksMode} transportSocksCfg cfg host = let TransportClientConfig {socksProxy} = transportClientConfig cfg NRMInteractive host False Nothing in socksProxy + transportUnackedTimeout proxy socksMode host = + let keepAlive = Just defaultKeepAliveOpts {unackedDataTimeout = Just True} + TransportClientConfig {tcpKeepAlive} = transportClientConfig defaultNetworkConfig {socksProxy = proxy, socksMode, tcpKeepAlive = keepAlive} NRMInteractive host False Nothing + in tcpKeepAlive >>= unackedDataTimeout testIPAddressProtected :: Spec testIPAddressProtected = do @@ -127,7 +154,11 @@ testSocksProxyEncoding = do strDecode "[::1]:9050" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0) strDecode "[::1]:8080" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 8080 0 (0, 0, 0, 1) 0) strDecode "[fd12:3456:789a:1::1]:8080" `shouldBe` authIsolate (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "localhost" `shouldBe` authIsolate (SocksProxyDomain "localhost" 9050) + strDecode "localhost:9050" `shouldBe` authIsolate (SocksProxyDomain "localhost" 9050) + strDecode "tor:9150" `shouldBe` authIsolate (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth SocksIsolateByAuth defaultSocksProxy) `shouldBe` "127.0.0.1:9050" + strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxyDomain "tor" 9150)) `shouldBe` "tor:9150" strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "[::1]:9050" strEncode (SocksProxyWithAuth SocksIsolateByAuth (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "[fd12:3456:789a:1::1]:8080" it "should decode SOCKS proxy without credentials" $ do @@ -138,7 +169,9 @@ testSocksProxyEncoding = do strDecode "@1.1.1.1" `shouldBe` authNull (SocksProxy $ SockAddrInet 9050 $ tupleToHostAddress (1, 1, 1, 1)) strDecode "@127.0.0.1:9050" `shouldBe` authNull defaultSocksProxy strDecode "@[fd12:3456:789a:1::1]:8080" `shouldBe` authNull (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "@tor:9150" `shouldBe` authNull (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth SocksAuthNull defaultSocksProxy) `shouldBe` "@127.0.0.1:9050" + strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxyDomain "tor" 9150)) `shouldBe` "@tor:9150" strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "@[::1]:9050" strEncode (SocksProxyWithAuth SocksAuthNull (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "@[fd12:3456:789a:1::1]:8080" it "should decode SOCKS proxy with credentials" $ do @@ -150,6 +183,75 @@ testSocksProxyEncoding = do strDecode "user:pass@127.0.0.1:9050" `shouldBe` authUser defaultSocksProxy strDecode "user:pass@fd12:3456:789a:1::1" `shouldBe` authUser (SocksProxy $ SockAddrInet6 9050 0 (0xfd123456, 0x789a0001, 0, 1) 0) strDecode "user:pass@[fd12:3456:789a:1::1]:8080" `shouldBe` authUser (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0) + strDecode "user:pass@tor:9150" `shouldBe` authUser (SocksProxyDomain "tor" 9150) strEncode (SocksProxyWithAuth auth defaultSocksProxy) `shouldBe` "user:pass@127.0.0.1:9050" + strEncode (SocksProxyWithAuth auth (SocksProxyDomain "tor" 9150)) `shouldBe` "user:pass@tor:9150" strEncode (SocksProxyWithAuth auth (SocksProxy $ SockAddrInet6 9050 0 (0, 0, 0, 1) 0)) `shouldBe` "user:pass@[::1]:9050" strEncode (SocksProxyWithAuth auth (SocksProxy $ SockAddrInet6 8080 0 (0xfd123456, 0x789a0001, 0, 1) 0)) `shouldBe` "user:pass@[fd12:3456:789a:1::1]:8080" + +testSocksProxyConnection :: Spec +testSocksProxyConnection = do + it "should connect via SOCKS proxy with IPv4 address" $ socksConnectionTest "127.0.0.1" "127.0.0.1:5050" + it "should connect via SOCKS proxy with IPv6 address" $ socksConnectionTest "::1" "[::1]:5050" + it "should connect via SOCKS proxy with domain name" $ socksConnectionTest "127.0.0.1" "localhost:5050" + it "should connect via SOCKS proxy with domain name without credentials" $ socksConnectionTest "127.0.0.1" "@localhost:5050" + +socksConnectionTest :: HasTestEnv => HostName -> ByteString -> IO () +socksConnectionTest proxyHost proxy = + withSmpServerConfigOn (transport @TLS) SMPClient.cfg testPort $ \_ -> + withSocksProxy proxyHost "0" $ \destinations proxyPort -> do + g <- C.newRandom + ts <- getCurrentTime + let (proxyPrefix, proxySuffix) = B.breakSubstring "5050" proxy + proxy' = proxyPrefix <> B.pack proxyPort <> B.drop 4 proxySuffix + networkConfig = defaultNetworkConfig {socksProxy = either error Just $ strDecode proxy', socksMode = SMAlways} + srv = SMPServer ["localhost"] testPort testKeyHash + (c :: SMPClient) <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {networkConfig} [] Nothing ts (\_ -> pure ()) + closeProtocolClient c + readTVarIO destinations `shouldReturn` [B.pack $ "localhost:" <> testPort] + +-- | Minimal SOCKS5 proxy (RFC 1928) for CONNECT command to domain names, +-- with optional username/password authentication (RFC 1929), that records requested destinations. +withSocksProxy :: HostName -> ServiceName -> (TVar [ByteString] -> ServiceName -> IO a) -> IO a +withSocksProxy host port action = do + destinations <- newTVarIO [] + started <- newEmptyTMVarIO + E.bracket (startTCPServer started (Just host) port) close $ \sock -> + withAsync (forever $ accept sock >>= \(conn, _) -> forkIO $ socksConnection destinations conn `E.finally` close conn) $ \_ -> do + proxyPort <- show <$> socketPort sock + action destinations proxyPort + +socksConnection :: TVar [ByteString] -> Socket -> IO () +socksConnection destinations conn = do + [5, nMethods] <- recvBytes 2 + methods <- recvBytes nMethods + if 2 `elem` methods + then do + sendAll conn "\5\2" + [1, uLen] <- recvBytes 2 + [pLen] <- recvBytes uLen >> recvBytes 1 + void $ recvBytes pLen + sendAll conn "\1\0" + else sendAll conn "\5\0" + [5, 1, 0, 3, hLen] <- recvBytes 5 + host <- B.unpack . BS.pack <$> recvBytes hLen + [p1, p2] <- recvBytes 2 + let port = show (fromIntegral p1 * 256 + fromIntegral p2 :: Int) + atomically $ modifyTVar' destinations (<> [B.pack $ host <> ":" <> port]) + addr : _ <- getAddrInfo (Just defaultHints {addrSocketType = Stream}) (Just host) (Just port) + E.bracket (socket (addrFamily addr) Stream defaultProtocol) close $ \dst -> do + connect dst $ addrAddress addr + sendAll conn "\5\0\0\1\0\0\0\0\0\0" + race_ (relay conn dst) (relay dst conn) + where + recvBytes :: Word8 -> IO [Word8] + recvBytes n = BS.unpack <$> recvAll (fromIntegral n) + recvAll n + | n <= 0 = pure "" + | otherwise = do + s <- recv conn n + when (BS.null s) $ E.throwIO $ userError "connection closed" + (s <>) <$> recvAll (n - BS.length s) + relay from to = do + s <- recv from 16384 + unless (BS.null s) $ sendAll to s >> relay from to diff --git a/tests/CoreTests/ServerStatsTests.hs b/tests/CoreTests/ServerStatsTests.hs new file mode 100644 index 000000000..6efaedbee --- /dev/null +++ b/tests/CoreTests/ServerStatsTests.hs @@ -0,0 +1,289 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +module CoreTests.ServerStatsTests where + +import qualified Data.ByteString.Char8 as B +import Data.Hashable (hash) +import Data.IORef +import Data.IntSet (IntSet) +import qualified Data.IntSet as IS +import Data.Maybe (isNothing) +import Data.Time.Calendar (fromGregorian) +import Data.Time.Clock (UTCTime (..)) +import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Server.Stats +import Simplex.Messaging.Server.StatsStore +import System.Directory (doesFileExist) +import Test.Hspec hiding (fit, it) +import Util +#if defined(dbServerPostgres) +import Control.Concurrent (threadDelay, throwTo) +import Control.Concurrent.Async (AsyncCancelled (..), async, asyncThreadId, poll, waitCatch) +import Control.Exception (bracket, fromException) +import Control.Monad (void) +import CoreTests.MsgStoreTests (testPostgresStoreConfig) +import qualified Database.PostgreSQL.Simple as DB +import Data.String (fromString) +import Simplex.Messaging.Agent.Store.Postgres (closeDBStore) +import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore, withTransaction) +import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStore) +import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..)) +import Simplex.Messaging.Server.QueueStore.Postgres (PostgresQueueStore (..)) +import System.Timeout (timeout) +#endif + +serverStatsTests :: Spec +serverStatsTests = do + describe "pending period stats" $ do + it "should not track pending hashes when disabled" testNoPending + it "should track hashes added since the last take" testPendingAdded + it "should reset pending hashes with period sets" testPendingReset + it "should merge restored pending hashes" testMergePending + describe "stats file" $ do + it "should save and load stats" testFileSaveLoad + it "should return no stats without file" testFileMissing + it "should log and continue when file cannot be written" testFileSaveError + it "should fail on invalid file" testFileParseError +#if defined(dbServerPostgres) + describe "stats database" $ do + it "should save and load stats with period sets" testDBSaveLoad + it "should save added hashes and delete reset sets" testDBResetAndAdded + it "should keep pending hashes when save fails" testDBSaveFailure + it "should keep pending hashes when save is cancelled" testDBSaveCancelled + it "should not save when database store is closed" testDBSaveClosed + it "should import stats file when database has no stats" testDBImportFile + it "should ignore stats file when database has stats" testDBIgnoreFile +#endif + +q1, q2, q3, q4, q5 :: EntityId +q1 = EntityId "queue1" +q2 = EntityId "queue2" +q3 = EntityId "queue3" +q4 = EntityId "queue4" +q5 = EntityId "queue5" + +hashes :: [EntityId] -> IntSet +hashes = IS.fromList . map (hash . unEntityId) + +utcDay :: Integer -> Int -> Int -> UTCTime +utcDay y m d = UTCTime (fromGregorian y m d) 3600 + +-- 2026-06-10 is Wednesday, 2026-06-08 is Monday, 2026-06-01 is Monday and the 1st +wednesday, monday, monday1st :: UTCTime +wednesday = utcDay 2026 6 10 +monday = utcDay 2026 6 8 +monday1st = utcDay 2026 6 1 + +noPending :: PendingHashes +noPending = PendingHashes {pendingReset = False, pendingAdded = IS.empty} + +resetPending :: PendingHashes +resetPending = PendingHashes {pendingReset = True, pendingAdded = IS.empty} + +added :: [EntityId] -> PendingHashes +added qs = PendingHashes {pendingReset = False, pendingAdded = hashes qs} + +testNoPending :: IO () +testNoPending = do + ps <- newPeriodStats + isNothing (pendingPeriods ps) `shouldBe` True + updatePeriodStats ps q1 + readIORef (day ps) `shouldReturn` hashes [q1] + ServerStats {activeQueues, activeQueuesNtf} <- newServerStats False wednesday + isNothing (pendingPeriods activeQueues) `shouldBe` True + isNothing (pendingPeriods activeQueuesNtf) `shouldBe` True + +testPendingAdded :: IO () +testPendingAdded = do + ServerStats {activeQueues = ps} <- newServerStats True wednesday + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + mapM_ (updatePeriodStats ps) [q1, q2, q1] + takePendingHashes pendingDay `shouldReturn` added [q1, q2] + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q1 + takePendingHashes pendingDay `shouldReturn` noPending + updatePeriodStats ps q3 + takePendingHashes pendingDay `shouldReturn` added [q3] + takePendingHashes pendingWeek `shouldReturn` added [q1, q2, q3] + takePendingHashes pendingMonth `shouldReturn` added [q1, q2, q3] + readIORef (day ps) `shouldReturn` hashes [q1, q2, q3] + +testPendingReset :: IO () +testPendingReset = do + ps <- newPendingPeriodStats + Just PendingPeriods {pendingDay, pendingWeek, pendingMonth} <- pure $ pendingPeriods ps + updatePeriodStats ps q1 + PeriodStatCounts {dayCount, weekCount, monthCount} <- periodStatCounts ps wednesday + (dayCount, weekCount, monthCount) `shouldBe` ("1", "", "") + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` added [q1] + takePendingHashes pendingMonth `shouldReturn` added [q1] + updatePeriodStats ps q2 + _ <- periodStatCounts ps monday + takePendingHashes pendingDay `shouldReturn` resetPending + takePendingHashes pendingWeek `shouldReturn` resetPending + takePendingHashes pendingMonth `shouldReturn` added [q2] + readIORef (month ps) `shouldReturn` hashes [q1, q2] + updatePeriodStats ps q3 + _ <- periodStatCounts ps monday1st + mapM takePendingHashes [pendingDay, pendingWeek, pendingMonth] `shouldReturn` [resetPending, resetPending, resetPending] + mapM readIORef [day ps, week ps, month ps] `shouldReturn` [IS.empty, IS.empty, IS.empty] + updatePeriodStats ps q4 + takePendingHashes pendingMonth `shouldReturn` added [q4] + +testMergePending :: IO () +testMergePending = do + mergePendingHashes (added [q1]) (added [q2]) `shouldBe` added [q1, q2] + mergePendingHashes resetPending (added [q2]) `shouldBe` PendingHashes {pendingReset = True, pendingAdded = hashes [q2]} + ref <- newIORef $ added [q5] + restorePendingHashes ref PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4]} + readIORef ref `shouldReturn` PendingHashes {pendingReset = True, pendingAdded = hashes [q3, q4, q5]} + +statsFile :: HasTestEnv => FilePath +statsFile = testPath "smp-server-stats.log" + +-- every zero counter line of the file encoding gets a distinct value, so a column order mistake changes the result +distinctCounters :: ServerStatsData -> ServerStatsData +distinctCounters d = either error id $ strDecode $ B.unlines $ zipWith setValue [1 :: Int ..] $ B.lines $ strEncode d + where + setValue i l = case B.breakSubstring "=" l of + (k, "=0") -> k <> "=" <> B.pack (show i) + _ -> l + +newDistinctStats :: Bool -> IO ServerStats +newDistinctStats trackPending = do + ss <- newServerStats trackPending wednesday + setServerStats ss . distinctCounters =<< getServerStatsData ss + pure ss + +testFileSaveLoad :: HasTestEnv => IO () +testFileSaveLoad = do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + updatePeriodStats (activeQueuesNtf ss) q2 + saveStats (StatsFile statsFile) ss + doesFileExist (statsFile <> ".tmp") `shouldReturn` False + expected <- getServerStatsData ss + Just d <- loadStats (StatsFile statsFile) + strEncode d `shouldBe` strEncode expected + doesFileExist statsFile `shouldReturn` True + +testFileMissing :: HasTestEnv => IO () +testFileMissing = (isNothing <$> loadStats (StatsFile statsFile)) `shouldReturn` True + +testFileSaveError :: HasTestEnv => IO () +testFileSaveError = do + let f = testPath "missing/smp-server-stats.log" + saveStats (StatsFile f) =<< newServerStats False wednesday + doesFileExist f `shouldReturn` False + +testFileParseError :: HasTestEnv => IO () +testFileParseError = do + B.writeFile statsFile "invalid" + loadStats (StatsFile statsFile) `shouldThrow` anyIOException + +#if defined(dbServerPostgres) +withStatsDB :: HasTestEnv => (DBStore -> IO a) -> IO a +withStatsDB action = bracket (newMsgStore testPostgresStoreConfig :: IO PostgresMsgStore) closeMsgStore $ action . dbStore . queueStore + +testDBSaveLoad :: HasTestEnv => IO () +testDBSaveLoad = withStatsDB $ \st -> do + ss <- newDistinctStats True + mapM_ (updatePeriodStats $ activeQueues ss) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + expected <- getServerStatsData ss + Just d <- getDBStats st + strEncode d `shouldBe` strEncode expected {_qCount = 0} + _day (_activeQueues d) `shouldBe` hashes [q1, q2] + _month (_activeQueuesNtf d) `shouldBe` hashes [q3] + +testDBResetAndAdded :: HasTestEnv => IO () +testDBResetAndAdded = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + mapM_ (updatePeriodStats msgQueues) [q1, q2] + updatePeriodStats (activeQueuesNtf ss) q3 + saveStats (StatsDB st statsFile) ss + updatePeriodStats msgQueues q4 + _ <- periodStatCounts msgQueues wednesday + updatePeriodStats msgQueues q5 + saveStats (StatsDB st statsFile) ss + Just ServerStatsData {_activeQueues, _activeQueuesNtf} <- getDBStats st + _day _activeQueues `shouldBe` hashes [q5] + _week _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _month _activeQueues `shouldBe` hashes [q1, q2, q4, q5] + _day _activeQueuesNtf `shouldBe` hashes [q3] + +testDBSaveFailure :: HasTestEnv => IO () +testDBSaveFailure = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + updatePeriodStats (activeQueues ss) q2 + renameTable st "server_stats_queues" "server_stats_queues_moved" + saveStats (StatsDB st statsFile) ss + renameTable st "server_stats_queues_moved" "server_stats_queues" + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + saveStats (StatsDB st statsFile) ss + Just d' <- getDBStats st + _day (_activeQueues d') `shouldBe` hashes [q1, q2] + where + renameTable st from to = withTransaction st $ \db -> void $ DB.execute_ db $ fromString $ "ALTER TABLE " <> from <> " RENAME TO " <> to + +testDBSaveCancelled :: HasTestEnv => IO () +testDBSaveCancelled = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + Just (Left e) <- timeout 5000000 $ do + a <- withTransaction st $ \db -> do + void $ DB.execute_ db "LOCK TABLE server_stats_queues IN EXCLUSIVE MODE" + a <- async $ saveStats (StatsDB st statsFile) ss + threadDelay 200000 + isNothing <$> poll a `shouldReturn` True + throwTo (asyncThreadId a) AsyncCancelled + pure a + waitCatch a + fromException e `shouldBe` Just AsyncCancelled + saveStats (StatsDB st statsFile) ss + Just d <- getDBStats st + _day (_activeQueues d) `shouldBe` hashes [q1] + +testDBSaveClosed :: HasTestEnv => IO () +testDBSaveClosed = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + let msgQueues = activeQueues ss + updatePeriodStats msgQueues q1 + closeDBStore st + timeout 5000000 (saveStats (StatsDB st statsFile) ss) `shouldReturn` Just () + Just PendingPeriods {pendingDay} <- pure $ pendingPeriods msgQueues + takePendingHashes pendingDay `shouldReturn` added [q1] + +testDBImportFile :: HasTestEnv => IO () +testDBImportFile = withStatsDB $ \st -> do + ss <- newDistinctStats False + updatePeriodStats (activeQueues ss) q1 + d <- getServerStatsData ss + B.writeFile statsFile $ strEncode d + Just imported <- loadStats (StatsDB st statsFile) + strEncode imported `shouldBe` strEncode d + doesFileExist statsFile `shouldReturn` False + doesFileExist (statsFile <> ".bak") `shouldReturn` True + Just saved <- getDBStats st + strEncode saved `shouldBe` strEncode d {_qCount = 0} + +testDBIgnoreFile :: HasTestEnv => IO () +testDBIgnoreFile = withStatsDB $ \st -> do + ss <- newServerStats True wednesday + updatePeriodStats (activeQueues ss) q1 + saveStats (StatsDB st statsFile) ss + saved <- getServerStatsData ss + B.writeFile statsFile . strEncode =<< getServerStatsData =<< newDistinctStats False + Just loaded <- loadStats (StatsDB st statsFile) + strEncode loaded `shouldBe` strEncode saved {_qCount = 0} + doesFileExist statsFile `shouldReturn` True +#endif diff --git a/tests/CoreTests/StoreLogTests.hs b/tests/CoreTests/StoreLogTests.hs index 45116d4a5..fb615551c 100644 --- a/tests/CoreTests/StoreLogTests.hs +++ b/tests/CoreTests/StoreLogTests.hs @@ -31,7 +31,7 @@ import Simplex.Messaging.Server.Env.STM (readWriteQueueStore) import Simplex.Messaging.Server.MsgStore.STM (STMMsgStore (..)) import Simplex.Messaging.Server.MsgStore.Types import Simplex.Messaging.Server.QueueStore -import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..)) +import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..), setStoreLog) import Simplex.Messaging.Server.QueueStore.Types import Simplex.Messaging.Server.StoreLog import Simplex.Messaging.SystemTime @@ -61,7 +61,8 @@ deriving instance Eq StoreLogRecord deriving instance Eq NtfCreds storeLogTests :: Spec -storeLogTests = +storeLogTests = do + it "should log link data swaps and restore them" testSwapLinkStoreLog forM_ [QMMessaging, QMContact] $ \qm -> do g <- runIO C.newRandom ((rId, qr), ntfCreds, date, sr@ServiceRec {serviceId}) <- runIO $ @@ -75,6 +76,9 @@ storeLogTests = rcvSr = sr {serviceRole = SRMessaging} blockedWithNotice = BlockingInfo {reason = BRContent, notice = Just ClientNotice {ttl = Just 86400}} newKeys <- runIO $ L.fromList <$> sequence [pubKey, pubKey] + newKeys' <- runIO $ L.fromList <$> sequence [pubKey, pubKey, pubKey] + let qd' = (fst qd, EncDataBytes "user data 1") + qd'' = (fst qd, EncDataBytes "user data 2") testSMPStoreLog ("SMP server store log, queueMode = " <> show qm) [ SLTC @@ -148,6 +152,18 @@ storeLogTests = saved = [CreateQueue rId qr, UpdateKeys rId newKeys], compacted = [CreateQueue rId qr {recipientKeys = newKeys}], state = M.fromList [(rId, qr {recipientKeys = newKeys})] + }, + SLTC + { name = "swap link data and recipient keys twice", + saved = [CreateQueue rId' qr', CreateLinkKeys rId' lnkId qd' newKeys, UpdateKeys rId' newKeys, CreateLinkKeys rId' lnkId qd'' newKeys', UpdateKeys rId' newKeys'], + compacted = [CreateQueue rId' qr' {recipientKeys = newKeys', queueData = Just (lnkId, qd'')}], + state = M.fromList [(rId', qr' {recipientKeys = newKeys', queueData = Just (lnkId, qd'')})] + }, + SLTC + { name = "swap link data and recipient keys, then swap link data", + saved = [CreateQueue rId' qr', CreateLinkKeys rId' lnkId qd' newKeys, UpdateKeys rId' newKeys, CreateLink rId' lnkId qd''], + compacted = [CreateQueue rId' qr' {recipientKeys = newKeys, queueData = Just (lnkId, qd'')}], + state = M.fromList [(rId', qr' {recipientKeys = newKeys, queueData = Just (lnkId, qd'')})] } ] @@ -193,6 +209,30 @@ testSMPStoreLog testSuite tests = storeState :: STMMsgStore -> IO (M.Map RecipientId QueueRec) storeState st = M.mapMaybe id <$> (readTVarIO (queues $ queueStore st) >>= mapM (readTVarIO . queueRec)) +testSwapLinkStoreLog :: HasTestEnv => IO () +testSwapLinkStoreLog = do + g <- C.newRandom + lnkId <- atomically $ EntityId <$> C.randomBytes 24 g + (rId, qr) <- testNewQueueRecData g QMContact (Just (lnkId, testLinkData)) + (rKey2, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let (fd, ud) = testLinkData + d1 = (fd, EncDataBytes "user data 1") + d2 = (fd, EncDataBytes "user data 2") + rKeys = rKey2 L.<| recipientKeys qr + ms <- newMsgStore testSMTStoreConfig + setStoreLog (queueStore ms) =<< openWriteStoreLog False testStoreLogFile + Right q <- addQueue ms rId qr + swapQueueLinkData (queueStore ms) q lnkId (linkDataHash ud) (Just rKeys) d1 `shouldReturn` Right Nothing + swapQueueLinkData (queueStore ms) q lnkId (linkDataHash $ snd d1) Nothing d2 `shouldReturn` Right Nothing + closeMsgStore ms + ([], logged) <- partitionEithers . map strDecode . B.lines <$> B.readFile testStoreLogFile + logged `shouldBe` [CreateQueue rId qr, CreateLinkKeys rId lnkId d1 rKeys, UpdateKeys rId rKeys, CreateLink rId lnkId d2] + ms' <- newMsgStore testSMTStoreConfig + sl <- readWriteQueueStore True (mkQueue ms') testStoreLogFile $ queueStore ms' + Right q' <- getQueue ms' SRecipient rId + readTVarIO (queueRec q') `shouldReturn` Just qr {recipientKeys = rKeys, queueData = Just (lnkId, d2)} + closeStoreLog sl + type FileRecState = (FileInfo, RoundedFileTime, Maybe RoundedFileTime, ServerEntityStatus) type XFTPStoreLogTestCase = StoreLogTestCase FileStoreLogRecord (M.Map SenderId FileRecState) diff --git a/tests/CoreTests/TransportTests.hs b/tests/CoreTests/TransportTests.hs new file mode 100644 index 000000000..aa07ec33b --- /dev/null +++ b/tests/CoreTests/TransportTests.hs @@ -0,0 +1,91 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} + +module CoreTests.TransportTests (transportTests) where + +import Control.Concurrent (threadDelay) +import Control.Exception (uninterruptibleMask_) +import Control.Monad +import qualified Data.ByteString.Char8 as B +import Data.Either (isLeft) +import Data.X509.Validation (Fingerprint (..)) +import Network.Socket (ServiceName, Socket, SocketOption (KeepAlive, UserTimeout), getSocketOption) +import SMPClient (serverBracket) +import qualified Simplex.Messaging.Crypto as C +import Simplex.Messaging.Transport +import Simplex.Messaging.Transport.Client (defaultTransportClientConfig, runTLSTransportClient) +import Simplex.Messaging.Transport.KeepAlive (KeepAliveOpts, defaultKeepAliveOpts) +import Simplex.Messaging.Transport.Server +import Test.Hspec hiding (fit, it) +import UnliftIO.Async (async, wait, waitCatch) +import UnliftIO.STM +import UnliftIO.Timeout (timeout) +import Util + +transportTests :: Spec +transportTests = do + describe "TLS connection close" $ + it "should close TLS connection while its peer does not read and data is sent" testCloseBlockedTLS + describe "TCP keep-alive" $ do + it "should enable keep-alive on accepted sockets when configured" $ + testServerKeepAlive (Just defaultKeepAliveOpts) True + it "should not enable keep-alive on accepted sockets by default" $ + testServerKeepAlive Nothing False + describe "TCP user timeout" $ do + it "should set user timeout on accepted sockets when configured" $ + testServerUserTimeout (Just 180000) 180000 + it "should not set user timeout on accepted sockets by default" $ + testServerUserTimeout Nothing 0 + +transportTestPort :: HasTestEnv => ServiceName +transportTestPort = testServerPort 9 + +testCredentials :: ServerCredentials +testCredentials = + ServerCredentials + { caCertificateFile = Just "tests/fixtures/ca.crt", + privateKeyFile = "tests/fixtures/server.key", + certificateFile = "tests/fixtures/server.crt" + } + +withTLSConnection :: HasTestEnv => TransportServerConfig -> (TLS 'TClient -> (Socket, TLS 'TServer) -> IO a) -> IO a +withTLSConnection cfg action = do + credential <- loadServerCredential testCredentials + Fingerprint fp <- loadFingerprint testCredentials + ss <- newSocketState + serverConn <- newEmptyTMVarIO + let creds = TLSServerCredential {credential, sniCredential = Nothing} + server sock (_, tls) = atomically (putTMVar serverConn (sock, tls)) >> threadDelay maxBound + serverBracket + (\started -> runTransportServerState_ ss started transportTestPort defaultSupportedParams creds cfg server) + (pure ()) + $ \_ -> + runTLSTransportClient defaultSupportedParams Nothing defaultTransportClientConfig Nothing "localhost" transportTestPort (Just $ C.KeyHash fp) $ \client -> + atomically (takeTMVar serverConn) >>= action client + +testCloseBlockedTLS :: HasTestEnv => Expectation +testCloseBlockedTLS = withTLSConnection (mkTransportServerConfig True Nothing False) $ \_client (_, server) -> do + sent <- newTVarIO (0 :: Int) + sender <- async . forever $ cPut server block >> atomically (modifyTVar' sent (+ 1)) + timeout 30000000 (waitBlocked sent 0) `shouldReturn` Just () + closing <- async . uninterruptibleMask_ $ closeConnection server + timeout 5000000 (wait closing) `shouldReturn` Just () + timeout 5000000 (isLeft <$> waitCatch sender) `shouldReturn` Just True + where + block = B.replicate 1048576 'x' + waitBlocked sent n = do + threadDelay 500000 + n' <- readTVarIO sent + unless (n' == n) $ waitBlocked sent n' + +testServerUserTimeout :: HasTestEnv => Maybe Int -> Int -> Expectation +testServerUserTimeout tcpUserTimeout expected = + withTLSConnection (mkTransportServerConfig True Nothing False) {tcpUserTimeout} $ \_client (sock, _) -> + getSocketOption sock UserTimeout `shouldReturn` expected + +testServerKeepAlive :: HasTestEnv => Maybe KeepAliveOpts -> Bool -> Expectation +testServerKeepAlive tcpKeepAlive enabled = + withTLSConnection (mkTransportServerConfig True Nothing False) {tcpKeepAlive} $ \_client (sock, _) -> + ((/= 0) <$> getSocketOption sock KeepAlive) `shouldReturn` enabled diff --git a/tests/CoreTests/UtilTests.hs b/tests/CoreTests/UtilTests.hs index c274cbf32..5819f0bf5 100644 --- a/tests/CoreTests/UtilTests.hs +++ b/tests/CoreTests/UtilTests.hs @@ -108,6 +108,13 @@ utilTests = do runExceptT (throwAsync ThreadKilled `catchAllOwnErrors` handleCatch) `shouldThrow` (\e -> e == ThreadKilled) it "should not throw if there are no errors" $ runExceptT (noErrors `catchAllOwnErrors` throwError) `shouldReturn` Right "no errors" + describe "catchOwn_" $ do + it "should catch SomeException" $ + (throwIO (userError "error") `catchOwn_` pure "caught") `shouldReturn` "caught" + it "should catch StackOverflow" $ + (throwIO StackOverflow `catchOwn_` pure "caught") `shouldReturn` "caught" + it "should rethrow ThreadKilled" $ + (throwIO ThreadKilled `catchOwn_` pure "caught") `shouldThrow` (\e -> e == ThreadKilled) where throwTestError :: ExceptT TestError IO String throwTestError = throwError $ TestError "error" diff --git a/tests/CoreTests/XFTPStoreTests.hs b/tests/CoreTests/XFTPStoreTests.hs index 21b91c1c9..92a40599f 100644 --- a/tests/CoreTests/XFTPStoreTests.hs +++ b/tests/CoreTests/XFTPStoreTests.hs @@ -5,11 +5,17 @@ module CoreTests.XFTPStoreTests (xftpStoreTests, xftpMigrationTests) where import Control.Monad +import Control.Monad.Trans.Except (runExceptT) +import qualified Data.ByteString.Char8 as B +import Data.List.NonEmpty (NonEmpty (..)) import Data.Word (Word32) +import Database.PostgreSQL.Simple (Only (..)) import qualified Database.PostgreSQL.Simple as DB +import SMPClient (deadlockOnce) import Simplex.FileTransfer.Protocol (FileInfo (..), SFileParty (..)) import Simplex.FileTransfer.Server.Store -import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore) +import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..)) +import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore (..), importFileStore, exportFileStore, withDB') import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, readWriteFileStore, serverFileName, writeFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (..)) import Simplex.Messaging.Agent.Store.Postgres.Common (DBStore (..), DBStorePool (..), withTransaction) @@ -29,8 +35,9 @@ import XFTPClient (testXFTPPostgresCfg) xftpStoreTests :: Spec xftpStoreTests = do - describe "STMFileStore operations" $ + describe "STMFileStore operations" $ do it "should compute committed used storage and file count" testSTMStorageAndCount + it "should add all recipients or none" $ (newFileStore () :: IO STMFileStore) >>= testAddRecipientsAtomically describe "PostgresFileStore operations" $ do it "should add and get file by sender" testAddGetFileSender it "should add and get file by recipient" testAddGetFileRecipient @@ -39,12 +46,19 @@ xftpStoreTests = do it "should time out getting file while the table is locked" testGetFileTimeout it "should set file path with IS NULL guard" testSetFilePath it "should reject duplicate recipient" testDuplicateRecipient + it "should add all recipients or none" $ withPgStore testAddRecipientsAtomically it "should delete file and cascade recipients" testDeleteFileCascade it "should block file and update status" testBlockFile it "should ack file reception" testAckFile it "should return expired files with limit" testExpiredFiles it "should expire files by stored expiration" testExpiredFilesStoredExpiration + it "should log each file deletion once" testDeleteFilesLog + it "should return at most limit expired files of both kinds" testExpiredFilesTotalLimit it "should compute committed used storage and file count" testStorageAndCount + it "should retry a file creation aborted by a deadlock" testAddFileDeadlock + it "should retry a file deletion aborted by a deadlock" testDeleteFilesDeadlock + it "should end the thread cancelled during database transaction" testCancelDBTransaction + it "should end the thread cancelled during database query" testCancelDBQuery xftpMigrationTests :: Spec xftpMigrationTests = describe "XFTP migration round-trip" $ do @@ -103,7 +117,7 @@ testAddGetFileRecipient = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () result <- getFile st SFRecipient testRecipientId case result of Right (FileRec {senderId}, key) -> do @@ -160,8 +174,27 @@ testDuplicateRecipient = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Left DUPLICATE_ + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Left DUPLICATE_ + +testAddRecipientsAtomically :: FileStoreClass s => s -> Expectation +testAddRecipientsAtomically st = do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + [keyA, keyB, keyC] <- replicateM 3 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) + let rcpA = FileRecipient (EntityId "recipient_a_____") keyA + rcpB = FileRecipient (EntityId "recipient_b_____") keyB + rcpC = FileRecipient (EntityId "recipient_c_____") keyC + recipientKey (FileRecipient rId _) = fmap snd <$> getFile st SFRecipient rId + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + addRecipients st testSenderId (rcpA :| []) `shouldReturn` Right () + addRecipients st testSenderId (rcpB :| [rcpA]) `shouldReturn` Left DUPLICATE_ + recipientKey rcpB `shouldReturn` Left AUTH + addRecipients st testSenderId (rcpB :| [rcpC, rcpB]) `shouldReturn` Left DUPLICATE_ + recipientKey rcpB `shouldReturn` Left AUTH + addRecipients st testSenderId (rcpB :| [rcpC]) `shouldReturn` Right () + mapM recipientKey [rcpA, rcpB, rcpC] `shouldReturn` [Right keyA, Right keyB, Right keyC] + addRecipients st (EntityId "no_such_sender__") (FileRecipient (EntityId "recipient_d_____") keyA :| []) `shouldReturn` Left AUTH testDeleteFileCascade :: HasTestEnv => Expectation testDeleteFileCascade = withPgStore $ \st -> do @@ -170,8 +203,8 @@ testDeleteFileCascade = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () - deleteFile st testSenderId `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () + deleteFile st testSenderId `shouldReturn` Right Nothing -- File and recipient should both be gone getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) getFile st SFRecipient testRecipientId >>= (`shouldBe` Left AUTH) . fmap (const ()) @@ -183,7 +216,7 @@ testBlockFile = withPgStore $ \st -> do let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () let blockInfo = BlockingInfo {reason = BRContent, notice = Nothing} - blockFile st testSenderId blockInfo False `shouldReturn` Right () + blockFile st testSenderId blockInfo `shouldReturn` Right Nothing result <- getFile st SFSender testSenderId case result of Right (FileRec {fileStatus}, _) -> readTVarIO fileStatus `shouldReturn` EntityBlocked blockInfo @@ -196,7 +229,7 @@ testAckFile = withPgStore $ \st -> do (rcpKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g let fileInfo = testFileInfo sndKey addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () - addRecipient st testSenderId (FileRecipient testRecipientId rcpKey) `shouldReturn` Right () + addRecipients st testSenderId (FileRecipient testRecipientId rcpKey :| []) `shouldReturn` Right () ackFile st testRecipientId `shouldReturn` Right () -- Recipient gone, but file still exists getFile st SFRecipient testRecipientId >>= (`shouldBe` Left AUTH) . fmap (const ()) @@ -238,6 +271,33 @@ testExpiredFilesStoredExpiration = withPgStore $ \st -> do expired <- expiredFiles st (RoundedSystemTime 500000) 0 100 map (\(sId, _, _) -> sId) expired `shouldBe` [EntityId "expired_file____"] +testDeleteFilesLog :: HasTestEnv => Expectation +testDeleteFilesLog = do + let storeLogPath = testPath "xftp-delete-files.log" + otherId = EntityId "other_file______" + st <- newFileStore testXFTPPostgresCfg {dbStoreLogPath = Just storeLogPath} :: IO PostgresFileStore + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let fileInfo = testFileInfo sndKey + addFile st testSenderId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () + addFile st otherId fileInfo testCreatedAt Nothing EntityActive `shouldReturn` Right () + void $ deleteFile st testSenderId + void $ deleteFiles st [testSenderId, otherId] + closeFileStore st + map (take 4) . lines <$> readFile storeLogPath `shouldReturn` ["FNEW", "FNEW", "FDEL", "FDEL"] + +testExpiredFilesTotalLimit :: HasTestEnv => Expectation +testExpiredFilesTotalLimit = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let fileInfo = testFileInfo sndKey + oldTime = RoundedSystemTime 100000 + addExpired i expiresAt = addFile st (EntityId $ "expired_file_" <> B.pack (show i) <> "__") fileInfo oldTime expiresAt EntityActive `shouldReturn` Right () + forM_ [1 .. 3 :: Int] $ \i -> addExpired i $ Just (RoundedSystemTime 400000) + forM_ [4 .. 6 :: Int] $ \i -> addExpired i Nothing + length <$> expiredFiles st (RoundedSystemTime 500000) 500000 4 `shouldReturn` 4 + length <$> expiredFiles st (RoundedSystemTime 500000) 500000 10 `shouldReturn` 6 + testStorageAndCount :: HasTestEnv => Expectation testStorageAndCount = withPgStore $ \st -> do testStorageAndCountForStore st @@ -252,20 +312,60 @@ testStorageAndCountForStore :: FileStoreClass s => s -> Expectation testStorageAndCountForStore st = do g <- C.newRandom (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g - getUsedStorage st `shouldReturn` 0 + getUsedStorage st `shouldReturn` (0, 0) getFileCount st `shouldReturn` 0 let fileInfoA = testFileInfo sndKey fileInfoB = fileInfoA {size = 64000} fileA = EntityId "file_a__________" fileB = EntityId "file_b__________" + fileC = EntityId "file_c__________" addFile st fileA fileInfoA testCreatedAt Nothing EntityActive `shouldReturn` Right () addFile st fileB fileInfoB testCreatedAt Nothing EntityActive `shouldReturn` Right () getFileCount st `shouldReturn` 2 - getUsedStorage st `shouldReturn` 0 + getUsedStorage st `shouldReturn` (0, 0) setFilePath st fileA "/tmp/file_a" `shouldReturn` Right () - getUsedStorage st `shouldReturn` 128000 + getUsedStorage st `shouldReturn` (1, 128000) setFilePath st fileB "/tmp/file_b" `shouldReturn` Right () - getUsedStorage st `shouldReturn` 192000 + getUsedStorage st `shouldReturn` (2, 192000) + let blockInfo = BlockingInfo {reason = BRContent, notice = Nothing} + blockFile st fileB blockInfo `shouldReturn` Right (Just "/tmp/file_b") + blockFile st fileB blockInfo `shouldReturn` Right Nothing + getUsedStorage st `shouldReturn` (1, 128000) + getFileCount st `shouldReturn` 2 + addFile st fileC fileInfoA testCreatedAt Nothing EntityActive `shouldReturn` Right () + setFilePath st fileC "/tmp/file_c" `shouldReturn` Right () + deleteFile st fileC `shouldReturn` Right (Just "/tmp/file_c") + deleteFile st fileC `shouldReturn` Left AUTH + deleteFiles st [fileA, fileB, fileC] >>= (`shouldMatchList` [(fileA, Just "/tmp/file_a", 128000), (fileB, Nothing, 64000)]) + deleteFiles st [fileA, fileB] `shouldReturn` [] + getUsedStorage st `shouldReturn` (0, 0) + getFileCount st `shouldReturn` 0 + +testAddFileDeadlock :: HasTestEnv => Expectation +testAddFileDeadlock = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ withTransaction (dbStore st) $ \db -> DB.execute_ db $ deadlockOnce "INSERT ON files" + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + getFile st SFSender testSenderId >>= (`shouldBe` Right sndKey) . fmap snd + +testDeleteFilesDeadlock :: HasTestEnv => Expectation +testDeleteFilesDeadlock = withPgStore $ \st -> do + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + addFile st testSenderId (testFileInfo sndKey) testCreatedAt Nothing EntityActive `shouldReturn` Right () + void $ withTransaction (dbStore st) $ \db -> DB.execute_ db $ deadlockOnce "DELETE ON files" + deleteFiles st [testSenderId] + getFile st SFSender testSenderId >>= (`shouldBe` Left AUTH) . fmap (const ()) + +testCancelDBTransaction :: HasTestEnv => Expectation +testCancelDBTransaction = withPgStore $ \st -> + testCancelledInside $ \waitCancel -> runExceptT $ withDB' "test" st $ \_ -> waitCancel + +testCancelDBQuery :: HasTestEnv => Expectation +testCancelDBQuery = withPgStore $ \st -> + testCancelledWhenBlocked $ \started -> runExceptT $ withDB' "test" st $ \db -> + started >> (DB.query_ db "SELECT pg_sleep(10)" :: IO [Only ()]) -- Migration round-trip test @@ -286,7 +386,7 @@ testMigrationRoundTrip = do rId1 = EntityId "migration_rcp_1_" addFile stmStore sId1 fileInfo1 testCreatedAt (Just testExpiresAt) EntityActive `shouldReturn` Right () void $ setFilePath stmStore sId1 ("/tmp" serverFileName sId1) - addRecipient stmStore sId1 (FileRecipient rId1 rcpKey1) `shouldReturn` Right () + addRecipients stmStore sId1 (FileRecipient rId1 rcpKey1 :| []) `shouldReturn` Right () let testBlockInfo = BlockingInfo {reason = BRSpam, notice = Nothing} addFile stmStore sId2 fileInfo2 testCreatedAt Nothing (EntityBlocked testBlockInfo) `shouldReturn` Right () -- 2. Write to StoreLog diff --git a/tests/FileDescriptionTests.hs b/tests/FileDescriptionTests.hs index 21c62c476..89424091b 100644 --- a/tests/FileDescriptionTests.hs +++ b/tests/FileDescriptionTests.hs @@ -15,6 +15,7 @@ import Data.Either (isRight) import qualified Data.Yaml as Y import Simplex.FileTransfer.Chunks (chunkSize0, chunkSize3, serverChunkSizes) import Simplex.FileTransfer.Client (prepareChunkSizes) +import Simplex.FileTransfer.Client.Main (decodeWebURI, fileWebLink) import Simplex.FileTransfer.Crypto (decryptChunks, encryptFile, sha512HashChunks) import Simplex.FileTransfer.Description import Simplex.FileTransfer.Protocol @@ -24,7 +25,7 @@ import qualified Simplex.Messaging.Crypto.File as CF import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding (smpEncode) import Simplex.Messaging.Encoding.String (StrEncoding (..)) -import Simplex.Messaging.Protocol (EntityId (..)) +import Simplex.Messaging.Protocol (EntityId (..), XFTPServer) import Simplex.Messaging.ServiceScheme (ServiceScheme (..)) import System.Directory (getFileSize, removeFile) import System.IO (IOMode (..), withFile) @@ -47,6 +48,7 @@ fileDescriptionTests = do describe "file description URIs" $ do it "round trip file description URI" testFileDescriptionURI it "round trip file description URI with extra JSON" testFileDescriptionURIExtras + it "encode IPv6 post-upload web link authority and preserve its fragment" testFileWebLinkIPv6 fileDescPath :: FilePath fileDescPath = "tests/fixtures/file_description.yaml" @@ -203,6 +205,7 @@ testFileDescriptionLimits = do split64GB = prepareChunkSizes (gb 64 - mb 1) length largestSplit `shouldBe` 1282 length split64GB `shouldBe` 16386 + validateFileDescription (descriptionOf [] 1) `shouldBe` Left "no chunks" validateFileDescription (descriptionOf largestSplit 16) `shouldSatisfy` isRight validateFileDescription (descriptionOf largestSplit 17) `shouldBe` Left "too many chunk replicas" validateFileDescription (descriptionOf split64GB 4) `shouldSatisfy` isRight @@ -280,6 +283,30 @@ testDecryptChunks = encPath = testPath "encrypted" dstPath = testPath "decrypted" +testFileWebLinkIPv6 :: IO () +testFileWebLinkIPv6 = do + let ipv6Server = either error id (strDecode "xftp://abc=@[2001:db8::1]:5223") :: XFTPServer + ipv6FileDesc = withPrimaryServer ipv6Server fileDesc + case fileWebLink ipv6FileDesc of + Nothing -> expectationFailure "expected an IPv6 web link" + Just (authority, fragment) -> do + let webLink = "https://" <> authority <> "/#" <> fragment + authority `shouldBe` "[2001:db8::1]" + webLink `shouldBe` "https://[2001:db8::1]/#" <> fragment + expected <- either fail pure $ validateFileDescription ipv6FileDesc + decodeWebURI fragment `shouldBe` Right expected + (fst <$> fileWebLink fileDesc) `shouldBe` Just "example1.com" + where + withPrimaryServer :: XFTPServer -> FileDescription 'FRecipient -> FileDescription 'FRecipient + withPrimaryServer server (FileDescription party fdSize fdDigest key nonce fdChunkSize (chunk : chunks) redirect) = + FileDescription party fdSize fdDigest key nonce fdChunkSize (replaceChunk chunk : chunks) redirect + where + replaceChunk :: FileChunk -> FileChunk + replaceChunk (FileChunk chunkNo size digest (FileChunkReplica _ replicaId replicaKey : replicas)) = + FileChunk chunkNo size digest (FileChunkReplica server replicaId replicaKey : replicas) + replaceChunk c = c + withPrimaryServer _ fd = fd + withRemoveTmpFile :: HasTestEnv => IO () -> IO () withRemoveTmpFile = bracket_ diff --git a/tests/NtfServerTests.hs b/tests/NtfServerTests.hs index b221bca4f..ba73d62f1 100644 --- a/tests/NtfServerTests.hs +++ b/tests/NtfServerTests.hs @@ -14,8 +14,8 @@ module NtfServerTests where import Control.Concurrent (killThread, threadDelay) -import Control.Exception (AsyncException (..), fromException) -import Control.Monad (forM, unless, void) +import Control.Exception (AsyncException (..), bracket, fromException) +import Control.Monad (forM, replicateM, replicateM_, unless, void) import qualified Data.Aeson as J import qualified Data.Aeson.Types as JT import Data.Bifunctor (first) @@ -43,6 +43,7 @@ import ServerTests ) import qualified Simplex.Messaging.Agent.Protocol as AP import Simplex.Messaging.Agent.RetryInterval (RetryInterval (..)) +import Simplex.Messaging.Agent.Store.Postgres.Common (withTransaction) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Client.Agent (SMPClientAgentConfig (..)) import qualified Simplex.Messaging.Crypto as C @@ -50,7 +51,7 @@ import Simplex.Messaging.Encoding import Simplex.Messaging.Notifications.Protocol import Simplex.Messaging.Notifications.Server.Env (NtfPushServer (pushClients), NtfServerConfig (..), getPushClient, newNtfPushServer) import Simplex.Messaging.Notifications.Server.Push.APNS -import Simplex.Messaging.Notifications.Server.Store.Postgres (addNtfToken, closeNtfDbStore, mkNtfTknRec, newNtfDbStore, setTokenActive, updateTknCronInterval, updateTokenCronSentAt, withDB') +import Simplex.Messaging.Notifications.Server.Store.Postgres (NtfEntityCounts (..), NtfPostgresStore (dbStore), addNtfToken, closeNtfDbStore, getEntityCounts, mkNtfTknRec, newNtfDbStore, setTokenActive, updateTknCronInterval, updateTokenCronSentAt, withClientDB, withDB') import Simplex.Messaging.Notifications.Transport (THandleNTF) import Simplex.Messaging.Parsers (parse, parseAll) import Simplex.Messaging.Protocol hiding (notification) @@ -76,6 +77,7 @@ ntfServerTests ps@(t, _) = do describe "APNS push delivery" $ do it "resumes sending notifications after the push provider is unreachable" $ testPushWorkerResumesAfterOutage t it "does not connect to the push provider when the key file is not configured" testNoConnectWithoutKeyFile + it "receives notifications from other servers when one server's push queue is full" $ testFullPushQueue ps it "stops connecting to the push provider when the push worker is killed" testPushClientKilled it "stops the server after a periodic notification starts a push worker" $ testPeriodicNtfServerStop t describe "Database pool" $ do @@ -88,6 +90,20 @@ ntfServerTests ps@(t, _) = do describe "Notification service" $ do it "resubscribes queues when service ID changes" $ testResubscribeOnServiceIdChange ps +ntfStoreTests :: Spec +ntfStoreTests = do + it "should retry a transaction aborted by a deadlock" $ + withDeadlockedTokens $ \st -> withDB' "test" st updateTokens `shouldReturn` Right 0 + it "should retry a client transaction aborted by a deadlock" $ + withDeadlockedTokens $ \st -> withClientDB "test" st updateTokens `shouldReturn` Right 0 + where + updateTokens db = PSQL.execute_ db "UPDATE tokens SET cron_interval = 0" + +withDeadlockedTokens :: HasTestEnv => (NtfPostgresStore -> IO ()) -> IO () +withDeadlockedTokens test = bracket (newNtfDbStore ntfTestDBCfg) closeNtfDbStore $ \st -> do + void $ withTransaction (dbStore st) $ \db -> PSQL.execute_ db $ deadlockOnce "UPDATE ON tokens" + test st + ntfSyntaxTests :: ASrvTransport -> Spec ntfSyntaxTests (ATransport t) = do it "unknown command" $ ("", "abcd", "1234", ('H', 'E', 'L', 'L', 'O')) >#> ("", "abcd", "1234", NRErr $ CMD UNKNOWN) @@ -158,15 +174,45 @@ testNoConnectWithoutKeyFile = apnsCfgMissingKey = apnsConfig {authKeyFileEnv = "APNS_KEY_FILE_MISSING"} keyFileError (e :: IOError) = "APNS_KEY_FILE_MISSING" `isInfixOf` show e +testFullPushQueue :: HasTestEnv => (ASrvTransport, AStoreType) -> Expectation +testFullPushQueue (ATransport t, msType) = do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + withAPNSMockServer $ \apns -> + smpTest2 t msType $ \rh sh -> + ntfTest t $ \nh -> bracket (newNtfDbStore ntfTestDBCfg) closeNtfDbStore $ \st -> do + (tknKey, _, tId, regCode) <- registerToken nh apns "abcd" + RespNtf "1" _ NROk <- signSendRecvNtf nh tknKey ("1", tId, TVFY regCode) + (tknKey2, _, tId2, regCode2) <- registerToken nh apns "efgh" + RespNtf "2" _ NROk <- signSendRecvNtf nh tknKey2 ("2", tId2, TVFY regCode2) + let subscribe key tknId srv = do + ((sId, _, _, _), nId, _) <- createNtfQueueNKEY rh sPub nPub + RespNtf "3" NoEntity (NRSubId _) <- signSendRecvNtf nh key ("3", NoEntity, SNEW $ NewNtfSub tknId (SMPQueueNtf srv nId) nKey) + pure sId + sendMsg sId = do + Resp "4" _ OK <- signSendRecv sh sKey ("4", sId, _SEND' "hello") + pure () + checkLastNtfs n = do + NtfEntityCounts {lastNtfCount = cnt} <- getEntityCounts st + unless (cnt == n) $ threadDelay 100000 >> checkLastNtfs n + waitLastNtfs n = timeout 5000000 (checkLastNtfs n) `shouldReturn` Just () + sIds <- replicateM 6 $ subscribe tknKey tId $ SMPServer SMP.testHost SMP.testPort SMP.testKeyHash + sId2 <- subscribe tknKey2 tId2 $ SMPServer SMP.testHost2 SMP.testPort SMP.testKeyHash + mapM_ sendMsg sIds + waitLastNtfs 6 + sendMsg sId2 + waitLastNtfs 7 + testPushClientKilled :: HasTestEnv => Expectation testPushClientKilled = withStallingServerOn' apnsTestPort $ \accepted _ -> do s <- newNtfPushServer 1 apnsConfig - a <- async $ getPushClient s PPApnsTest + a <- async $ getPushClient s PPApnsTest 0 atomically $ takeTMVar accepted killThread $ asyncThreadId a timeout 1000000 (either fromException (const Nothing) <$> waitCatch a) `shouldReturn` Just (Just ThreadKilled) - isNothing <$> TM.lookupIO PPApnsTest (pushClients s) `shouldReturn` True + isNothing <$> TM.lookupIO (PPApnsTest, 0) (pushClients s) `shouldReturn` True where NtfServerConfig {apnsConfig} = ntfServerCfg @@ -442,25 +488,35 @@ testResubscribeOnServiceIdChange ps@(ATransport (t :: TProxy c 'TServer), _) = d testNtfClient $ \(nh :: THandleNTF c 'TClient) -> do (tknKey, _dhSecret, tId, regCode) <- registerToken nh apns "abcd" RespNtf "2" _ NROk <- signSendRecvNtf nh tknKey ("2", tId, TVFY regCode) - let checkActive subId = do + let checkStatus expected subId = do RespNtf "4" _ (NRSub status) <- signSendRecvNtf nh tknKey ("4", subId, SCHK) - unless (status == NSActive) $ threadDelay 100000 >> checkActive subId - waitActive subIds = timeout 5000000 (mapM_ checkActive subIds) `shouldReturn` Just () - (sId, subIds) <- withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do + unless (status == expected) $ threadDelay 100000 >> checkStatus expected subId + waitStatus expected subIds = timeout 5000000 (mapM_ (checkStatus expected) subIds) `shouldReturn` Just () + waitActive = waitStatus NSActive + (sId, subIds, endedSubId) <- withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do ((sId, _, _, _), nId1, _) <- createNtfQueueNKEY h sPub nPub (_, nId2, _) <- createNtfQueueNKEY h sPub nPub - subIds <- forM [nId1, nId2] $ \nId -> do + (_, nId3, _) <- createNtfQueueNKEY h sPub nPub + [subId1, subId2, endedSubId] <- forM [nId1, nId2, nId3] $ \nId -> do RespNtf "3" NoEntity (NRSubId subId) <- signSendRecvNtf nh tknKey ("3", NoEntity, SNEW $ NewNtfSub tId (SMPQueueNtf srv nId) nKey) pure subId - waitActive subIds - pure (sId, subIds) + waitActive [subId1, subId2, endedSubId] + Resp "4" _ (SOK Nothing) <- signSendRecv h nKey ("4", nId3, NSUB) + waitStatus NSEnd [endedSubId] + pure (sId, [subId1, subId2], endedSubId) st <- newNtfDbStore ntfTestDBCfg Right 1 <- withDB' "test" st $ \db -> PSQL.execute_ db "UPDATE smp_servers SET ntf_service_cert = NULL, ntf_service_cert_hash = NULL, ntf_service_priv_key = NULL" + let checkNotificationAfterRestart = withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do + Resp "5" _ OK <- signSendRecv h sKey ("5", sId, _SEND' "hello") + APNSMockRequest {notification = APNSNotification {aps = APNSMutableContent {}}} <- getMockNotification apns $ DeviceToken PPApnsTest "abcd" + waitActive subIds + getServiceId = withDB' "test" st $ \db -> PSQL.query_ db "SELECT ntf_service_id FROM smp_servers" + checkNotificationAfterRestart + Right [PSQL.Only (Just (newServiceId :: ServiceId))] <- getServiceId + checkNotificationAfterRestart + getServiceId `shouldReturn` Right [PSQL.Only (Just newServiceId)] + RespNtf "5" _ (NRSub NSEnd) <- signSendRecvNtf nh tknKey ("5", endedSubId, SCHK) closeNtfDbStore st - withSmpServer ps $ testSMPClient $ \(h :: THandleSMP c 'TClient) -> do - Resp "5" _ OK <- signSendRecv h sKey ("5", sId, _SEND' "hello") - APNSMockRequest {notification = APNSNotification {aps = APNSMutableContent {}}} <- getMockNotification apns $ DeviceToken PPApnsTest "abcd" - waitActive subIds type CreateQueueFunc = forall c. diff --git a/tests/RSLVTests.hs b/tests/RSLVTests.hs index e9b931314..1a2e38a91 100644 --- a/tests/RSLVTests.hs +++ b/tests/RSLVTests.hs @@ -29,7 +29,7 @@ import SMPClient import Simplex.Messaging.Client import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (strDecode) -import SMPNamesTests (availableBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) +import SMPNamesTests (availableBody, errorBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) import Simplex.Messaging.Protocol ( BrokerMsg (..), Cmd (..), @@ -88,6 +88,8 @@ rslvTests = do describe "RSLV direct (non-forwarded)" $ do it "resolver without the v2 route (404) -> NAME RESOLVER, not NOT_FOUND" testRslvBackendNotFound it "resolver replies 502 -> NAME (RESOLVER ..)" testRslvBackendHttpErr + it "a rejected name counts as rejected, not as a resolver error" testRslvRejectedStats + it "a resolver failure counts as a resolver error" testRslvResolverErrStats it "no names config -> NAME NO_RESOLVER" testRslvDisabled it "refuses to send RSLV on a session below namesSMPVersion" testRslvVersion describe "RSLV forwarded (PFWD)" $ do @@ -128,6 +130,27 @@ testRslvBackendHttpErr = (_, _, resp) <- sendRslv h "rs05" (domain "alice.simplex") resp `shouldBe` Right (ERR (NAME (RESOLVER "HTTP 502"))) +testRslvRejectedStats :: HasTestEnv => IO () +testRslvRejectedStats = + rslvStatsTest (status502, errorBody "labelNotRecorded") `shouldReturn` (1, 0) + +testRslvResolverErrStats :: HasTestEnv => IO () +testRslvResolverErrStats = + rslvStatsTest (status502, errorBody "upstreamError") `shouldReturn` (0, 1) + +rslvStatsTest :: HasTestEnv => (Status, LB.ByteString) -> IO (Int, Int) +rslvStatsTest (st, body) = + NRS.withResolverServer (NRS.resolveResp st body) $ \port _ -> + withSmpServerConfigOn (transport @TLS) (metricsCfg port) testPort $ const $ do + testSMPClient @TLS $ \h -> do + (_, _, resp) <- sendRslv h "rs08" (domain "alice.simplex") + resp `shouldBe` Right (ERR (NAME (RESOLVER "HTTP 502"))) + threadDelay 1500000 + ms <- readMetrics + (,) <$> metric ms "simplex_smp_names_rejected" <*> metric ms "simplex_smp_names_resolver_errs" + where + metricsCfg port = updateCfg (withNames port memCfg) $ \c -> c {prometheusInterval = Just 1} + testRslvDisabled :: HasTestEnv => IO () testRslvDisabled = withSmpServerConfigOn (transport @TLS) memCfg testPort $ const $ @@ -336,16 +359,21 @@ data SlotWaitMetrics = SlotWaitMetrics {waits :: Int, waitTimeouts :: Int, waitM readSlotWaitMetrics :: HasTestEnv => IO SlotWaitMetrics readSlotWaitMetrics = do - ms <- map words . lines <$> readFile testPrometheusMetricsFile - -- metric lines are "name value timestamp" - let metric name = case [v | n : v : _ <- ms, n == name] of - [v] -> pure $ read v - _ -> fail $ "no metric " <> name + ms <- readMetrics SlotWaitMetrics - <$> metric "simplex_smp_cmd_slot_wait_ms_count" - <*> metric "simplex_smp_cmd_slot_wait_timeouts" - <*> metric "simplex_smp_cmd_slot_wait_ms_max" - <*> metric "simplex_smp_cmd_slot_wait_ms_sum" + <$> metric ms "simplex_smp_cmd_slot_wait_ms_count" + <*> metric ms "simplex_smp_cmd_slot_wait_timeouts" + <*> metric ms "simplex_smp_cmd_slot_wait_ms_max" + <*> metric ms "simplex_smp_cmd_slot_wait_ms_sum" + +readMetrics :: HasTestEnv => IO [[String]] +readMetrics = map words . lines <$> readFile testPrometheusMetricsFile + +-- metric lines are "name value timestamp" +metric :: [[String]] -> String -> IO Int +metric ms name = case [v | n : v : _ <- ms, n == name] of + [v] -> pure $ read v + _ -> fail $ "no metric " <> name -- | One RSLV per block, so no batch limit applies. sendRslvs :: THandleSMP TLS 'TClient -> String -> Int -> IO () diff --git a/tests/RemoteControl.hs b/tests/RemoteControl.hs index fa36ae6c0..09177372d 100644 --- a/tests/RemoteControl.hs +++ b/tests/RemoteControl.hs @@ -19,10 +19,12 @@ import qualified Data.ByteString.Lazy.Char8 as LB import Data.List (stripPrefix) import Data.List.NonEmpty (NonEmpty (..)) import Data.Time.Clock.System (SystemTime (..), getSystemTime) +import qualified Network.Socket as N import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (StrEncoding (..)) import Simplex.Messaging.Transport (TSbChainKeys (..)) import Simplex.Messaging.Transport.Client (TransportHost) +import Simplex.Messaging.Transport.Server (startTCPServer) import qualified Simplex.RemoteControl.Client as HC (RCHostClient (action)) import qualified Simplex.RemoteControl.Client as RC import Simplex.RemoteControl.Discovery (mkLastLocalHost, preferAddress) @@ -30,6 +32,7 @@ import Simplex.RemoteControl.Invitation ( RCEncInvitation (..), RCInvitation (..), RCSignedInvitation, + RCVerifiedInvitation (..), signInvitation, verifySignedInvitation, ) @@ -43,12 +46,14 @@ remoteControlTests :: Spec remoteControlTests = do describe "preferred bindings should go first" testPreferAddress describe "Invitation parsing" $ do - it "should parse bracketed IPv6 host with port" testInvitationBracketedIPv6Host + it "should encode and parse bracketed IPv6 host with port" testInvitationBracketedIPv6Host + it "should encode, parse and verify signed IPv6 invitation" testSignedInvitationBracketedIPv6Host it "should reject bracketed non-IPv6 host" testInvitationBracketedNonIPv6HostRejected describe "New controller/host pairing" $ do it "should connect to new pairing" testNewPairing it "should connect to existing pairing" testExistingPairing it "should reject host certificate not signed by CA of known host" testHostCertNotSignedByCA + it "returns a TLS startup error when the listening port is occupied" testOccupiedPort describe "Multicast discovery" $ do it "should find paired host and connect" testMulticast it "should accept announcement only within timestamp window" testAnnouncementTimestamp @@ -88,10 +93,9 @@ testPreferAddress = do testInvitationBracketedIPv6Host :: IO () testInvitationBracketedIPv6Host = do invitation <- testIPv6Invitation - let bracketedUri = - B.pack . replaceFirst "@2001:db8::1:" "@[2001:db8::1]:" . B.unpack $ - strEncode invitation + let bracketedUri = strEncode invitation expectedHost = either error id (strDecode "2001:db8::1") :: TransportHost + bracketedUri `shouldSatisfy` B.isInfixOf "@[2001:db8::1]:5223" case strDecode bracketedUri of Left err -> expectationFailure err Right RCInvitation {host, port} -> do @@ -101,9 +105,7 @@ testInvitationBracketedIPv6Host = do testInvitationBracketedNonIPv6HostRejected :: IO () testInvitationBracketedNonIPv6HostRejected = do invitation <- testIPv6Invitation - let bracketedUri = - B.pack . replaceFirst "@2001:db8::1:" "@[simplex.chat]:" . B.unpack $ - strEncode invitation + let bracketedUri = B.pack . replaceFirst "@[2001:db8::1]:" "@[simplex.chat]:" . B.unpack $ strEncode invitation case strDecode bracketedUri :: Either String RCInvitation of Left _ -> pure () Right _ -> expectationFailure "expected parse failure for bracketed non-IPv6 host" @@ -117,6 +119,33 @@ replaceFirst needle replacement = go Just rest -> replacement <> rest Nothing -> c : go cs +testSignedInvitationBracketedIPv6Host :: IO () +testSignedInvitationBracketedIPv6Host = do + drg <- C.newRandom + (skey, sKey) <- atomically $ C.generateKeyPair @'C.Ed25519 drg + (idkey, idKey) <- atomically $ C.generateKeyPair @'C.Ed25519 drg + (dh, _) <- atomically $ C.generateKeyPair @'C.X25519 drg + let invitation = + RCInvitation + (C.KeyHash "test-ca") + (either error id $ strDecode "2001:db8::1") + 5223 + supportedRCPVRange + (J.String "app") + (MkSystemTime 0 0) + skey + idkey + dh + encoded = strEncode $ signInvitation sKey idKey invitation + encoded `shouldSatisfy` B.isInfixOf "@[2001:db8::1]:5223" + case strDecode encoded :: Either String RCSignedInvitation of + Left err -> expectationFailure err + Right signed -> case verifySignedInvitation signed of + Just (RCVerifiedInvitation RCInvitation {host, port}) -> do + host `shouldBe` either error id (strDecode "2001:db8::1") + port `shouldBe` 5223 + Nothing -> expectationFailure "expected valid signed IPv6 invitation" + testIPv6Invitation :: IO RCInvitation testIPv6Invitation = do drg <- C.newRandom @@ -136,6 +165,23 @@ testIPv6Invitation = do dh } +testOccupiedPort :: IO () +testOccupiedPort = do + drg <- C.newRandom + hp <- RC.newRCHostPairing drg + started <- newEmptyTMVarIO + bracket (startTCPServer started Nothing "0") N.close $ \listener -> do + port <- N.socketPort listener + result <- timeout 5000000 $ runExceptT $ RC.connectRCHost drg hp (J.String "app") False Nothing (Just $ fromIntegral port) + case result of + Just (Left e) -> do + e `shouldBe` RCETLSStartFailed + LB.unpack (J.encode e) `shouldContain` "\"tlsStartFailed\"" + Just (Right (_, _, client, _)) -> do + uninterruptibleCancel $ HC.action client + expectationFailure "Started a second listener on an occupied port" + Nothing -> expectationFailure "Remote control did not report the listener startup failure" + testNewPairing :: IO () testNewPairing = do drg <- C.newRandom diff --git a/tests/SMPAgentClient.hs b/tests/SMPAgentClient.hs index feb43387e..0e4b2cacc 100644 --- a/tests/SMPAgentClient.hs +++ b/tests/SMPAgentClient.hs @@ -99,6 +99,7 @@ agentCfg = ntfCfg = defaultNTFClientConfig {qSize = 1, defaultTransport = (ntfTestPort, transport @TLS), networkConfig}, reconnectInterval = fastRetryInterval, persistErrorInterval = 1, + prohibitRequestsInConnLock = True, caCertificateFile = "tests/fixtures/ca.crt", privateKeyFile = "tests/fixtures/server.key", certificateFile = "tests/fixtures/server.crt" diff --git a/tests/SMPClient.hs b/tests/SMPClient.hs index 24f49cea7..9b2be6f97 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) @@ -52,7 +53,7 @@ import UnliftIO.Timeout (timeout) import Util #if defined(dbServerPostgres) -import Database.PostgreSQL.Simple (defaultConnectInfo) +import Database.PostgreSQL.Simple (Query, defaultConnectInfo) import Simplex.Messaging.Server.QueueStore.Postgres.Config (PostgresStoreCfg (..)) #endif @@ -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 @@ -121,6 +125,9 @@ testServerDBConnectInfo = connectUser = "test_server_user", connectDatabase = "test_server_db" } + +deadlockOnce :: Query -> Query +deadlockOnce event = "CREATE SEQUENCE deadlocks; CREATE FUNCTION deadlock() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF nextval('deadlocks') = 1 THEN RAISE EXCEPTION 'test' USING ERRCODE = '40P01'; END IF; RETURN NULL; END $$; CREATE TRIGGER deadlock AFTER " <> event <> " FOR EACH STATEMENT EXECUTE FUNCTION deadlock()" #endif testStoreMsgsFile :: HasTestEnv => FilePath @@ -258,6 +265,7 @@ cfgMS msType = withStoreCfg (testServerStoreConfig msType) $ \serverStoreCfg -> logStatsStartTime = 0, serverStatsLogFile = testPath "smp-server-stats.daily.log", serverStatsBackupFile = Nothing, + statsSaveInterval = defStatsSaveInterval, prometheusInterval = Nothing, prometheusMetricsFile = testPrometheusMetricsFile, pendingENDInterval = 500000, @@ -277,9 +285,11 @@ cfgMS msType = withStoreCfg (testServerStoreConfig msType) $ \serverStoreCfg -> smpAgentCfg = defaultSMPClientAgentConfig {persistErrorInterval = 1, msgQSize = Nothing}, -- seconds allowSMPProxy = False, serverClientConcurrency = 2, + proxyRelayConcurrency = defaultProxyRelayConcurrency, serverResolverConcurrency = defaultNameResolverConcurrency, serverForwardWorkers = defaultForwardWorkers, maxClientCmdWait = defaultMaxClientCmdWait, + maxFwdCorrIds = defaultMaxFwdCorrIds, namesConfig = Nothing, information = Nothing, startOptions = defaultStartOptions @@ -333,7 +343,12 @@ proxyCfgMS msType = let smpAgentCfg' = smpAgentCfg cfg' in cfg' { allowSMPProxy = True, - smpAgentCfg = smpAgentCfg' {smpCfg = (smpCfg smpAgentCfg') {agreeSecret = True, proxyServer = True, serverVRange = supportedProxyClientSMPRelayVRange}} + smpAgentCfg = + smpAgentCfg' + { smpCfg = (smpCfg smpAgentCfg') {agreeSecret = True, proxyServer = True, serverVRange = supportedProxyClientSMPRelayVRange}, + maxConnectingClients = Just defaultProxyConnectConcurrency, + sessionPerConnectedServer = True + } } proxyCfgS2 :: HasTestEnv => AServerConfig @@ -354,6 +369,14 @@ proxyCfgShortTimeout = nt = NetworkTimeout {backgroundTimeout = 4_000000, interactiveTimeout = 4_000000} in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {tcpConnectTimeout = nt}}}} +proxyCfgShortPingInterval :: HasTestEnv => AServerConfig +proxyCfgShortPingInterval = + updateCfg proxyCfg $ \cfg' -> + let aCfg = smpAgentCfg cfg' + cCfg = smpCfg aCfg + in cfg' {smpAgentCfg = aCfg {smpCfg = cCfg {networkConfig = (networkConfig cCfg) {smpPingInterval = 1_000000}}}} + + proxyCfgVPrev :: HasTestEnv => AStoreType -> AServerConfig proxyCfgVPrev msType = updateCfg (proxyCfgMS msType) $ \cfg' -> @@ -494,6 +517,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/SMPNamesTests.hs b/tests/SMPNamesTests.hs index 452c99428..a5e9c78e6 100644 --- a/tests/SMPNamesTests.hs +++ b/tests/SMPNamesTests.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, availableBody, reservedBody, responseBody, resolved) where +module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, availableBody, reservedBody, responseBody, errorBody, resolved) where import qualified Data.Aeson as J import qualified Data.ByteString.Char8 as B @@ -17,17 +17,19 @@ import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Types (status200, status400, status404, status500, status502) import NamesResolverServer (resolveResp, testNamesConfig, withResolverServer, withResolverServerDelayed) import Simplex.Messaging.Encoding (smpDecode, smpEncode) -import Simplex.Messaging.Encoding.String (strDecode) +import Simplex.Messaging.Encoding.String (strDecode, strEncode) import Simplex.Messaging.Protocol (Command (..), ErrorType (..), NameErrorType (..), NamePricing (..), NameQuery (..), NameRecord (..), NameRegistration (..), NameResponse (..), NameReservedReason (..), ProtocolEncoding (..), USDCents (..)) import Simplex.Messaging.Server.Main (validateUrl) import Simplex.Messaging.Server.Names - ( NamesConfig (..), + ( NameFailure (..), + NamesConfig (..), RpcAuth (..), newNamesEnv, pingEndpoint, resolveName, ) import Simplex.Messaging.Server.Names.HttpResolver (ResolverError (..)) +import Simplex.Messaging.Server.Stats (NameResolverStatsData (..)) import Simplex.Messaging.SimplexName (SimplexDomain (..), SimplexTLD (..), labelHash) import Simplex.Messaging.SystemTime (RoundedSystemTime (..)) import Simplex.Messaging.Transport (nameAvailSMPVersion, serverInfoSMPVersion) @@ -62,6 +64,9 @@ availableBody = responseBody "{\"type\":\"available\",\"pricing\":{\"registratio reservedBody :: LB.ByteString reservedBody = responseBody "{\"type\":\"reserved\",\"reservedReason\":\"trademark\"}" +errorBody :: LB.ByteString -> LB.ByteString +errorBody code = "{\"name\":\"alice.simplex\",\"error\":\"" <> code <> "\"}" + -- | The registration, and the block the resolver read it at. responseBody :: LB.ByteString -> LB.ByteString responseBody reg = "{\"lastBlockTs\":" <> testReadAt <> ",\"registration\":" <> reg <> "}" @@ -86,6 +91,7 @@ smpNamesTests = do describe "HTTP resolver" resolverSpec describe "name availability" availabilitySpec describe "Resolver health probe" healthSpec + describe "name resolver stats" nameStatsSpec describe "resolver_endpoint validation" validateUrlSpec nameRecordEncodingSpec :: Spec @@ -263,37 +269,57 @@ resolverSpec = do it "returns RESOLVER on 404 (a resolver without the v2 route)" $ withResolverServer (resolveResp status404 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 404") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 404")) + + it "rejects the query on 400 tldNotConfigured" $ + withResolverServer (resolveResp status400 (errorBody "tldNotConfigured")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 400")) - it "returns RESOLVER on 400 (TLD not configured)" $ - withResolverServer (resolveResp status400 "{}") $ \port _ -> do + it "rejects the query on 400 notFullyQualified" $ + withResolverServer (resolveResp status400 (errorBody "notFullyQualified")) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 400") + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 400")) - it "returns RESOLVER on 502 (upstream failure)" $ + it "rejects the query on 502 labelNotRecorded" $ + withResolverServer (resolveResp status502 (errorBody "labelNotRecorded")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 502")) + + it "rejects the query on 502 noPriceOracle" $ + withResolverServer (resolveResp status502 (errorBody "noPriceOracle")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (QueryRejected (RESOLVER "HTTP 502")) + + it "fails on 502 upstreamError" $ + withResolverServer (resolveResp status502 (errorBody "upstreamError")) $ \port _ -> do + env <- newNamesEnv (testNamesConfig port) + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 502")) + + it "fails on an error status without an error code" $ withResolverServer (resolveResp status502 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "HTTP 502") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "HTTP 502")) it "returns RESOLVER when the body exceeds the response cap" $ withResolverServer (resolveResp status200 (LB.fromStrict (B.replicate 500 'x'))) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) {resolverMaxResponseBytes = 100} - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "response too large") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "response too large")) it "returns RESOLVER on malformed JSON from the resolver" $ withResolverServer (resolveResp status200 "this is not json") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "invalid response") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "invalid response")) it "returns RESOLVER when JSON parses but isn't a NameRegistration shape" $ withResolverServer (resolveResp status200 "{}") $ \port _ -> do env <- newNamesEnv (testNamesConfig port) - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "invalid response") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "invalid response")) it "returns RESOLVER (timeout) when the resolver is slower than resolverTimeoutMs" $ withResolverServerDelayed 1500 (resolveResp status200 (registeredBody testNameRecord)) $ \port _ -> do env <- newNamesEnv (testNamesConfig port) {resolverTimeoutMs = 300} - resolveName env aliceDomain `shouldReturn` Left (RESOLVER "timeout") + resolveName env aliceDomain `shouldReturn` Left (ResolverFailed (RESOLVER "timeout")) it "sends one HTTP request per lookup (no cache)" $ withResolverServer (resolveResp status200 (registeredBody testNameRecord)) $ \port reqs -> do @@ -324,8 +350,8 @@ healthSpec = do withResolverServer healthFails $ \port _ -> do env <- newNamesEnv (testNamesConfig port) pingEndpoint env >>= \case - Left (HttpStatusErr 500) -> pure () - r -> expectationFailure $ "expected Left (HttpStatusErr 500), got " <> show r + Left (HttpStatusErr 500 _) -> pure () + r -> expectationFailure $ "expected Left (HttpStatusErr 500 _), got " <> show r it "pingEndpoint queries /health" $ withResolverServer (resolveResp status200 "{}") $ \port reqs -> do @@ -337,6 +363,15 @@ healthSpec = do ["health"] -> (status500, "{}") _ -> (status404, "{}") +nameStatsSpec :: Spec +nameStatsSpec = do + it "round-trips the rejected count" $ + (_rslvRejected <$> strDecode (strEncode stats {_rslvRejected = 3})) `shouldBe` Right 3 + it "reads stats saved before the rejected count as zero" $ + (_rslvRejected <$> strDecode "reqs=5\nsucc=1\nnotFound=1\nresolverErrs=2\ndisabled=1") `shouldBe` Right 0 + where + stats = NameResolverStatsData {_rslvReqs = 5, _rslvSucc = 1, _rslvNotFound = 1, _rslvResolverErrs = 1, _rslvDisabled = 0, _rslvRejected = 0} + validateUrlSpec :: Spec validateUrlSpec = do it "accepts an https URL with a path prefix" $ diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 02b87a0e0..654c18e62 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) @@ -33,24 +34,27 @@ import Simplex.Messaging.Agent.Env.SQLite (AgentConfig (..), InitialAgentServers import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, REQ) import qualified Simplex.Messaging.Agent.Protocol as A import Simplex.Messaging.Client +import qualified Simplex.Messaging.Client.Agent as CA import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Ratchet (pattern PQSupportOn) import qualified Simplex.Messaging.Crypto.Ratchet as CR +import Simplex.Messaging.Encoding.String (strDecode) import Simplex.Messaging.Protocol (EncRcvMsgBody (..), MsgBody, QueueReqData (..), RcvMessage (..), SubscriptionMode (..), maxMessageLength, noMsgFlags) import qualified Simplex.Messaging.Protocol as SMP import Simplex.Messaging.Server.Env.STM (AStoreType (..), ServerConfig (..)) import Simplex.Messaging.Server.MsgStore.Types (SQSType (..)) +import Simplex.Messaging.Server.Stats (ServerStatsData (..)) import Simplex.Messaging.Transport import Simplex.Messaging.Util (bshow, tshow) import Simplex.Messaging.Version (mkVersionRange) import System.FilePath (splitExtensions) import System.Random (randomRIO) +import Text.Read (readMaybe) import Test.Hspec hiding (fit, it, xit) 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,16 +76,48 @@ smpProxyTests = do testProxyReconnectAfterRelayRestart it "closes connection to relay after sender disconnects mid-connection" $ \_ -> testProxyClosesRelayConnectionAfterDisconnect + it "does not keep oversized forwarded command" $ \_ -> + testForwardOversizedNotKept + it "fails commands of closed client at once" $ \_ -> + testClosedClientCommandsFail + it "releases command kept for late response" $ \_ -> + testLateResponseCommandReleased + it "rejects forwards above the relay concurrency limit" $ \_ -> + testProxyRelayConcurrencyLimit describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel + describe "relay sessions" $ do + it "uses one session for addresses of one relay" $ \_ -> + testRelaySessionPerServer + it "refuses a new relay session when connections are at the limit" $ \_ -> + testRelayConnectLimit + it "removes connection errors after the interval, above the limit at once" $ \_ -> + testPersistedErrorsLimit + it "refuses a connection at the limit without keeping its error" $ \_ -> + testConnectLimitRefusal describe "proxy requests" $ do + describe "bad relay URIs" $ do + it "relay without key hash" testRelayWithoutKeyHash + xit "host not resolved" todo + xit "when SMP port blackholed" todo + xit "no SMP service at host/port" todo + xit "bad SMP fingerprint" todo + xit "batching proxy requests" todo it "relay rejects forwarded command with changed version" $ \_ -> testChangedFwdVersion + it "relay rejects repeated forwarded command below version 23" $ \_ -> + testRepeatedFwdCommand + it "relay closes connection after limit of forwarded commands below version 23" $ \_ -> + testFwdCorrIdsLimit + it "proxy and relay count forwarded commands by version" $ \_ -> + testFwdVersionStats it "proxy rejects forwarded correlation ID that is not 24 bytes" $ \_ -> testFwdCorrIdSize it "relay delays AUTH errors to forwarded commands" $ \_ -> testForwardedAuthErrorDelay + it "proxy closes idle relay connection" $ \_ -> + testProxyClosesIdleRelay describe "deliver message via SMP proxy" $ do let srv1, srv2 :: HasTestEnv => SMPServer srv1 = SMPServer testHost testPort testKeyHash @@ -152,6 +188,7 @@ smpProxyTests = do agentViaProxyRetryOffline it "retries sending when destination relay session disconnects in proxy" $ \_ -> agentViaProxyRetryNoSession + it "sends via proxy to relay below version 23" $ twoServersPrevRelay agentViaProxyPrevRelay describe "stress test 1k" $ do let deliver nAgents nMsgs = agentDeliverMessagesViaProxyConc (replicate nAgents [srv1]) (map bshow [1 :: Int .. nMsgs]) it "2 agents, 250 messages" $ oneServer $ deliver 2 250 @@ -440,6 +477,15 @@ agentViaProxyRetryNoSession = do withServer2 = withSmpServerConfigOn (transport @TLS) proxyCfgS2 testPort2 servers srv = initAgentServersProxy {smp = userServers [srv]} +agentViaProxyPrevRelay :: HasTestEnv => IO () +agentViaProxyPrevRelay = + withAgent 1 agentCfg initAgentServers {smp = userServers [testSMPServer2]} testDB $ \alice -> + withAgent 2 agentCfg initAgentServersProxy {smp = userServers [testSMPServer]} testDB2 $ \bob -> runRight_ $ do + (aliceId, bobId) <- makeConnection alice bob + 2 <- sendMessage bob aliceId noMsgFlags "hello" + get bob ##> ("", aliceId, A.SENT 2 (Just testSMPServer)) + get alice =##> \case ("", c, Msg "hello") -> c == bobId; _ -> False + testNoProxy :: HasTestEnv => AStoreType -> IO () testNoProxy msType = do withSmpServerConfigOn (transport @TLS) (cfgMS msType) testPort2 $ \_ -> do @@ -456,6 +502,13 @@ testProxyAuth msType = do where proxyCfgAuth = updateCfg (proxyCfgMS msType) $ \cfg_ -> cfg_ {newQueueBasicAuth = Just "correct"} +testRelayWithoutKeyHash :: HasTestEnv => AStoreType -> IO () +testRelayWithoutKeyHash msType = do + withSmpServerConfigOn (transport @TLS) (proxyCfgMS msType) testPort $ \_ -> do + testSMPClient_ "127.0.0.1" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (_, _, reply) <- sendRecv th (Nothing, "0", NoEntity, SMP.PRXY (SMPServer testHost testPort2 (C.KeyHash "")) Nothing) + reply `shouldBe` Right (SMP.ERR $ SMP.CMD SMP.SYNTAX) + -- Connect a sender client to the proxy and request a relay session to testSMPServer2 (PRXY). -- On success the reply is PKEY; otherwise it is the proxy error for the relay connection. requestRelaySession :: HasTestEnv => IO (Either SMP.ErrorType SMP.BrokerMsg) @@ -479,9 +532,71 @@ testChangedFwdVersion = et <- encrypt $ SMP.encTransmissionNonce v nonce _ <- runExceptT' $ forward corrId v et runExceptT (forward corrId (prevVersion v) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) - runExceptT (forward (C.unCbNonce $ SMP.encTransmissionNonce v nonce) (prevVersion v) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) - (_, SMP.EncResponse resp) <- runExceptT' . forward corrId (prevVersion v) =<< encrypt nonce - runExceptT (forward (C.unCbNonce $ C.reverseNonce nonce) (prevVersion v) $ SMP.EncTransmission resp) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + runExceptT (forward (C.unCbNonce $ SMP.encTransmissionNonce v nonce) (prevVersion fwdNoncesSMPVersion) et) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + (_, SMP.EncResponse resp) <- runExceptT' . forward corrId (prevVersion fwdNoncesSMPVersion) =<< encrypt nonce + runExceptT (forward (C.unCbNonce $ C.reverseNonce nonce) (prevVersion fwdNoncesSMPVersion) $ SMP.EncTransmission resp) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + +testRepeatedFwdCommand :: HasTestEnv => IO () +testRepeatedFwdCommand = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + forward <- newForwardedPing rc + let v = prevVersion fwdNoncesSMPVersion + Right (Just _, _) <- forward fwdNoncesSMPVersion + Right (Just _, _) <- forward fwdNoncesSMPVersion + Right (Nothing, _) <- forward v + forward v `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + forward (prevVersion v) `shouldReturn` Left (PCEProtocolError SMP.CRYPTO) + +testFwdCorrIdsLimit :: HasTestEnv => IO () +testFwdCorrIdsLimit = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {maxFwdCorrIds = 2}) testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + rc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + let v = prevVersion fwdNoncesSMPVersion + forwardNew = newForwardedPing rc >>= \forward -> forward v + Right _ <- forwardNew + Right _ <- forwardNew + forwardNew `shouldReturn` Left (PCENetworkError SMP.NEFailedError) + +testFwdVersionStats :: HasTestEnv => IO () +testFwdVersionStats = do + withSmpServerConfigOn (transport @TLS) statsCfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive testSMPServer Nothing + forM_ ([fwdNoncesSMPVersion, fwdNoncesSMPVersion, prevVersion fwdNoncesSMPVersion] :: [VersionSMP]) $ \v -> + runExceptT (proxySMPMessage pc NRMInteractive sess {prVersion = v} Nothing (SMP.EntityId "1234") noMsgFlags "hello") `shouldReturn` Left (PCEProtocolError SMP.AUTH) + threadDelay 1500000 + ms <- map B.words . B.lines <$> B.readFile testPrometheusMetricsFile + let metric name = [v | n : v : _ <- ms, n == name] + map + metric + [ "simplex_smp_relay_messages_requests_version{version=\"below_23\"}", + "simplex_smp_relay_messages_requests_version{version=\"from_23\"}", + "simplex_smp_relay_messages_received_version{version=\"below_23\"}", + "simplex_smp_relay_messages_received_version{version=\"from_23\"}" + ] + `shouldBe` [["1"], ["2"], ["1"], ["2"]] + Right ServerStatsData {_pMsgFwdsBelow23, _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23} <- strDecode <$> B.readFile testServerStatsBackupFile + (_pMsgFwdsBelow23, _pMsgFwdsFrom23, _pMsgFwdsRecvBelow23, _pMsgFwdsRecvFrom23) `shouldBe` (1, 2, 1, 2) + where + statsCfg = updateCfg proxyCfg $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, prometheusInterval = Just 1} + +newForwardedPing :: SMPClient -> IO (VersionSMP -> IO (Either SMPClientError (Maybe C.CbNonce, SMP.EncResponse))) +newForwardedPing rc = do + g <- C.newRandom + THAuthClient {peerServerPubKey} <- maybe (fail "getProtocolClient returned no thAuth") pure $ thAuth $ thParams rc + (cmdPubKey, cmdPrivKey) <- atomically $ C.generateKeyPair g + nonce@(C.CbNonce corrId) <- atomically $ C.randomCbNonce g + let t = SMP.tEncodeBatch1 False (Nothing, SMP.encodeTransmission (thParams rc) (SMP.CorrId corrId, SMP.NoEntity, SMP.Cmd SMP.SIdleClient SMP.PING)) + pure $ \v -> do + et <- either (fail . show) (pure . SMP.EncTransmission) $ C.cbEncrypt (C.dh' peerServerPubKey cmdPrivKey) (SMP.encTransmissionNonce v nonce) t SMP.paddedProxiedTLength + runExceptT $ forwardSMPTransmission rc (either error id $ C.corrCbNonce corrId) v cmdPubKey et testFwdCorrIdSize :: HasTestEnv => IO () testFwdCorrIdSize = @@ -495,6 +610,18 @@ testFwdCorrIdSize = (_, _, reply) <- sendRecv th (Nothing, corrId, SMP.EntityId sessId, SMP.PFWD currentClientSMPRelayVersion cmdPubKey (SMP.EncTransmission "")) reply `shouldBe` Right (SMP.ERR $ SMP.CMD SMP.SYNTAX) +testProxyClosesIdleRelay :: HasTestEnv => IO () +testProxyClosesIdleRelay = + withSmpServerConfigOn (transport @TLS) proxyCfgShortPingInterval testPort $ \_ -> + withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 $ \_ -> + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (_, _, Right (SMP.PKEY sessId _ _)) <- sendRecv th (Nothing, "1", NoEntity, SMP.PRXY testSMPServer2 Nothing) + threadDelay 2000000 + g <- C.newRandom + (cmdPubKey, _) <- atomically $ C.generateKeyPair g + (_, _, reply) <- sendRecv th (Nothing, "2", SMP.EntityId sessId, SMP.PFWD currentClientSMPRelayVersion cmdPubKey (SMP.EncTransmission "")) + reply `shouldBe` Right (SMP.ERR $ SMP.PROXY SMP.NO_SESSION) + testForwardedAuthErrorDelay :: HasTestEnv => IO () testForwardedAuthErrorDelay = withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> @@ -623,6 +750,72 @@ testProxyClosesRelayConnectionAfterDisconnect = race_ (atomically $ takeTMVar accepted) requestRelaySession timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testProxyRelayConcurrencyLimit :: HasTestEnv => IO () +testProxyRelayConcurrencyLimit = + withSmpServerConfigOn (transport @TLS) cfg' testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + vr = mkVersionRange minServerSMPRelayVersion currentClientSMPRelayVersion + pc <- either (fail . show) pure =<< getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) + sess <- runExceptT' $ connectSMPProxiedRelay pc NRMInteractive srv (Just "correct") + sId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + rs <- forConcurrently ([1 .. 20] :: [Int]) $ \_ -> runExceptT (proxySMPMessage pc NRMInteractive sess Nothing sId noMsgFlags "hi") + let rejected = length $ filter (== Right (Left (ProxyProtocolError (SMP.PROXY (SMP.BROKER SMP.TIMEOUT))))) rs + rejected `shouldSatisfy` (> 0) + threadDelay 1500000 + readRelayLimitMetric <$> readFile testPrometheusMetricsFile `shouldReturn` Just rejected + where + cfg' = updateCfg proxyCfg $ \cfg_ -> cfg_ {proxyRelayConcurrency = 1, prometheusInterval = Just 1} + readRelayLimitMetric m = case [v | "simplex_smp_relay_messages_concurrency_limit" : v : _ <- map words (lines m)] of + v : _ -> readMaybe v + [] -> Nothing + +testForwardOversizedNotKept :: HasTestEnv => IO () +testForwardOversizedNotKept = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + let proxyClientCfg = defaultSMPClientConfig {serverVRange = supportedProxyClientSMPRelayVRange, agreeSecret = True, proxyServer = True} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) proxyClientCfg [] Nothing ts (\_ -> pure ()) + (k, _) <- atomically $ C.generateKeyPair @'C.X25519 g + let et = SMP.EncTransmission $ B.replicate smpBlockSize 'a' + runExceptT (forwardSMPTransmission c (either error id $ C.corrCbNonce "123456789012345678901234") currentClientSMPRelayVersion k et) + `shouldReturn` Left (PCETransportError TELargeMsg) + pClientSentCommandsCount c `shouldReturn` 0 + +testClosedClientCommandsFail :: HasTestEnv => IO () +testClosedClientCommandsFail = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + closed <- newEmptyTMVarIO + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) + closeProtocolClient c + atomically $ takeTMVar closed + Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) + forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) + pClientSentCommandsCount c `shouldReturn` 0 + atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 + +testLateResponseCommandReleased :: HasTestEnv => IO () +testLateResponseCommandReleased = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + msgQ <- newTBQueueIO 4 + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) + rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g + (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) + `shouldReturn` Left PCEResponseTimeout + pClientSentCommandsCount c `shouldReturn` 1 + threadDelay 1000000 + pClientSentCommandsCount c `shouldReturn` 0 + (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ + pure () + -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which -- rethrows async exceptions. If the connecting thread is cancelled mid-connect, putTMVar is @@ -651,6 +844,66 @@ testAgentClientReconnectAfterCancel = netCfg = (netCfg initAgentServers) {tcpConnectTimeout = NetworkTimeout 4000000 4000000} } +testRelaySessionPerServer :: HasTestEnv => IO () +testRelaySessionPerServer = + withSmpServerConfigOn (transport @TLS) proxyCfg testPort $ \_ -> + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + sessId <- withRelay $ \_ -> relaySessionId th + threadDelay 100000 + sessId' <- withRelay $ \_ -> relaySessionId th + sessId' `shouldNotBe` sessId + where + withRelay = withSmpServerConfigOn (transport @TLS) cfgS2 testPort2 + relaySessionId th = do + sessId : sessIds <- forM relayServers $ \srv -> do + (_, _, Right (SMP.PKEY sessId _ _)) <- sendRecv th (Nothing, "1", NoEntity, SMP.PRXY srv Nothing) + pure sessId + sessIds `shouldBe` [sessId, sessId, sessId] + pure sessId + relayServers = map (\h -> SMPServer h testPort2 testKeyHash) ["127.0.0.1", "127.0.0.2", "::ffff:127.0.0.1", "127.0.0.1,unused.example"] + +testRelayConnectLimit :: HasTestEnv => IO () +testRelayConnectLimit = + withSmpServerConfigOn (transport @TLS) proxyCfgConnectLimit testPort $ \_ -> + withStallingServerOn' testPort2 $ \accepted _ -> + withAsync requestRelaySession $ \_ -> do + atomically $ takeTMVar accepted + testSMPClient_ "localhost" testPort supportedServerSMPRelayVRange Nothing $ \(th :: THandleSMP TLS 'TClient) -> do + (t, (_, _, reply)) <- responseTime $ sendRecv th (Nothing, "1", NoEntity, SMP.PRXY (SMPServer testHost2 testPort2 "1234") Nothing) + reply `shouldBe` Right (SMP.ERR $ SMP.PROXY $ SMP.BROKER SMP.TIMEOUT) + t `shouldSatisfy` (< 1) + where + proxyCfgConnectLimit = updateCfg proxyCfgShortTimeout $ \cfg' -> cfg' {smpAgentCfg = (smpAgentCfg cfg') {CA.maxConnectingClients = Just 1}} + +testPersistedErrorsLimit :: HasTestEnv => IO () +testPersistedErrorsLimit = do + g <- C.newRandom + a@CA.SMPClientAgent {CA.smpClients, CA.persistedErrors} <- CA.newSMPClientAgent SMP.SSender CA.defaultSMPClientAgentConfig {CA.persistErrorInterval = 1, CA.maxPersistedErrors = 2} Nothing g + forM_ ([testSMPServer, testSMPServer2, SMPServer testHost testPort2 testKeyHash] :: [SMPServer]) $ \srv -> + runExceptT (CA.getSMPServerClient'' a srv) >>= \case + Left _ -> pure () + Right _ -> expectationFailure "connected to a server that is not running" + length <$> readTVarIO smpClients `shouldReturn` 2 + readTVarIO persistedErrors `shouldReturn` 2 + threadDelay 1500000 + length <$> readTVarIO smpClients `shouldReturn` 0 + readTVarIO persistedErrors `shouldReturn` 0 + CA.closeSMPClientAgent a + +testConnectLimitRefusal :: HasTestEnv => IO () +testConnectLimitRefusal = do + g <- C.newRandom + a@CA.SMPClientAgent {CA.smpClients, CA.connectingClients} <- CA.newSMPClientAgent SMP.SSender CA.defaultSMPClientAgentConfig {CA.maxConnectingClients = Just 0} Nothing g + runExceptT (CA.getSMPServerClient'' a testSMPServer) >>= \case + Left e -> e `shouldBe` PCEResponseTimeout + Right _ -> expectationFailure "connected above the connection limit" + length <$> readTVarIO smpClients `shouldReturn` 0 + readTVarIO connectingClients `shouldReturn` 0 + CA.closeSMPClientAgent a + +todo :: AStoreType -> IO () +todo _ = fail "TODO" + runExceptT' :: Exception e => ExceptT e IO a -> IO a runExceptT' a = runExceptT a >>= either throwIO pure diff --git a/tests/ServerTests.hs b/tests/ServerTests.hs index daef9034c..ea51aa0b0 100644 --- a/tests/ServerTests.hs +++ b/tests/ServerTests.hs @@ -19,12 +19,14 @@ module ServerTests where import Control.Concurrent (ThreadId, killThread, threadDelay) -import Control.Concurrent.Async (concurrently_) +import Control.Concurrent.Async (concurrently, concurrently_) import Control.Concurrent.STM import Control.Exception (SomeException, finally, throwIO, try) import Control.Monad import Control.Monad.IO.Class +import Control.Monad.Trans.Except (runExceptT) import qualified Crypto.PubKey.ECC.Types as ECC +import Crypto.Random (ChaChaDRG) import Data.Bifunctor (first) import qualified Data.ByteString.Base64 as B64 import Data.ByteString.Char8 (ByteString) @@ -34,7 +36,7 @@ import Data.Hashable (hash) import qualified Data.IntSet as IS import Data.List.NonEmpty (NonEmpty (..)) import Data.List (isPrefixOf) -import Data.Maybe (catMaybes, isJust) +import Data.Maybe (catMaybes, fromMaybe, isJust) import qualified Data.Set as S import Data.String (IsString (..)) import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime) @@ -44,7 +46,7 @@ import qualified Data.X509 as X import qualified Data.X509.Validation as XV import GHC.Stack (withFrozenCallStack) import SMPClient -import Simplex.Messaging.Client (authTransmission) +import Simplex.Messaging.Client (ProtocolClientConfig (..), pattern NRMInteractive, ProtocolClientError (..), addSMPQueueLink, authTransmission, createSMPQueue, defaultSMPClientConfig, getProtocolClient, getSMPQueueLink, swapSMPQueueLink) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String @@ -72,6 +74,8 @@ import Simplex.Messaging.Server.Env.STM (readWriteQueueStore) import Simplex.Messaging.Server.MsgStore.Postgres (PostgresMsgStoreCfg (..), exportDbMessages) import Simplex.Messaging.Server.MsgStore.Types (MsgStoreClass (..), newMsgStore) import Simplex.Messaging.Server.StoreLog (closeStoreLog) +import CoreTests.ServerStatsTests (withStatsDB) +import Simplex.Messaging.Server.StatsStore (getDBStats) #endif serverTests :: SpecWith (ASrvTransport, AStoreType) @@ -110,9 +114,16 @@ serverTests = do testServiceSubAssociatedQueue testServiceDowngradeConnected testServiceSubsReplacesConnection + testServiceRepeatedSUB + testServiceSubsReturnsToConnection + testServiceSubBlockedQueue + testServiceDeletesOtherServiceQueue describe "Store log" testWithStoreLog describe "Restore messages" testRestoreMessages describe "Restore messages (old / v2)" testRestoreExpireMessages + describe "Save server stats" $ do + testSaveStatsPeriodically + testStartupStoreCounts describe "Save prometheus metrics" testPrometheusMetrics describe "Delay of AUTH error" testAuthErrorDelay describe "Message notifications" $ do @@ -122,15 +133,23 @@ serverTests = do testMessageServiceNotifications testServiceNotificationsTwoRestarts testNotificationsInChunks + testServiceNotificationsRepeatedNSUB + testServiceNotificationsReturnToConnection describe "Message expiration" $ do testMsgExpireOnSend testMsgExpireOnInterval testMsgNOTExpireOnInterval describe "Blocking queues" $ testBlockMessageQueue + describe "Inactive clients" testInactiveClientExpiration describe "Short links" $ do testInvQueueLinkData testContactQueueLinkData testDuplicateQueueLinkData + testSwapQueueLink + testSwapQueueLinkKeys + testConcurrentSwapQueueLink + testSwapQueueLinkClient + testSwapQueueLinkStoreLog pattern Resp :: CorrId -> QueueId -> BrokerMsg -> Transmission (Either ErrorType BrokerMsg) pattern Resp corrId queueId command <- (corrId, queueId, Right command) @@ -1353,6 +1372,125 @@ testServiceSubsReplacesConnection = Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg sh1 pure () +testServiceRepeatedSUB :: SpecWith (ASrvTransport, AStoreType) +testServiceRepeatedSUB = + it "should count the queue once when the service repeats SUB in one block" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + Resp "1" NoEntity (Ids rId _ _) <- signSendRecv h rKey ("1", NoEntity, New rPub dhPub) + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1@THandle {params} -> do + let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth params (CorrId "2", rId, SUB) + Right auth <- pure $ authTransmission (thAuth params) True (Just rKey) Nothing tForAuth + let sub = Right (auth, tToSend) + [Right (), Right ()] <- tPut sh1 [sub, sub] + [Resp "2" _ (SOK (Just serviceId)), Resp "2" _ (SOK (Just _))] <- tGetClient sh1 + Resp "" rId' END <- tGet1 h + rId' `shouldBe` rId + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeServiceQueues sh2 aServicePK "3" serviceId [rId] + Resp "" _ (ENDS n idsHash) <- tGet1 sh1 + (n, idsHash) `shouldBe` (1, queueIdsHash [rId]) + +testServiceSubsReturnsToConnection :: SpecWith (ASrvTransport, AStoreType) +testServiceSubsReturnsToConnection = + it "should move the service subscription back to the replaced connection when it subscribes again" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + (rId, sId, dec, serviceId) <- runSMPServiceClient t (tlsCred, serviceKeys) $ \sh -> do + Resp "1" NoEntity (Ids_ rId sId srvDh serviceId) <- serviceSignSendRecv sh rKey servicePK ("1", NoEntity, New rPub dhPub) + pure (rId, sId, decryptMsgV3 $ C.dh' srvDh dhPriv, serviceId) + let subscribeService sh corrId = subscribeServiceQueues sh aServicePK corrId serviceId [rId] + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1 -> do + subscribeService sh1 "2" + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeService sh2 "3" + Resp "" _ (ENDS 1 _) <- tGet1 sh1 + subscribeService sh1 "4" + Resp "" _ (ENDS 1 _) <- tGet1 sh2 + Resp "5" _ OK <- sendRecv h ("", "5", sId, _SEND "hello") + Resp "" _ (Msg mId msg) <- tGet1 sh1 + dec mId msg `shouldBe` Right "hello" + Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg sh2 + pure () + +testServiceSubBlockedQueue :: SpecWith (ASrvTransport, AStoreType) +testServiceSubBlockedQueue = + it "should keep the service subscription to a blocked queue when another connection subscribes it" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + creds <- genCredentials g Nothing (0, 2400) "localhost" + let (_fp, tlsCred) = tlsCredentials [creds] + cpPort = testServerPort 8 + cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {controlPort = Just cpPort, controlPortAdminAuth = Just "admin"} + info = BlockingInfo BRContent Nothing + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + let aServicePK = C.APrivateAuthKey C.SEd25519 servicePK + withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \h -> do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh1 -> do + Resp "1" NoEntity (Ids_ rId sId _ serviceId) <- serviceSignSendRecv sh1 rKey servicePK ("1", NoEntity, New rPub dhPub) + [_, blocked] <- controlPortCommands cpPort ["auth admin", "block " <> B.unpack (strEncode sId) <> " " <> B.unpack (strEncode info)] + blocked `shouldStartWith` "ok, queue blocked" + Resp "2" _ (ERR (BLOCKED _)) <- signSendRecv h rKey ("2", rId, SUB) + runSMPServiceClient t (tlsCred, serviceKeys) $ \sh2 -> do + subscribeServiceQueues sh2 aServicePK "3" serviceId [rId] + Resp "" _ (ENDS n idsHash) <- tGet1 sh1 + (n, idsHash) `shouldBe` (1, queueIdsHash [rId]) + +testServiceDeletesOtherServiceQueue :: SpecWith (ASrvTransport, AStoreType) +testServiceDeletesOtherServiceQueue = + it "should keep the subscription count of a service connection that deletes a queue of another service" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + credsA <- genCredentials g Nothing (0, 2400) "localhost" + credsB <- genCredentials g Nothing (0, 2400) "localhost" + let (_, tlsCredA) = tlsCredentials [credsA] + (_, tlsCredB) = tlsCredentials [credsB] + serviceKeysA@(_, servicePKA) <- atomically $ C.generateKeyPair g + serviceKeysB@(_, servicePKB) <- atomically $ C.generateKeyPair g + withSmpServerConfigOn at (cfgMS msType) testPort $ \_ -> do + (rPubA, rKeyA) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rPubB, rKeyB) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + runSMPServiceClient t (tlsCredA, serviceKeysA) $ \shA -> do + Resp "1" NoEntity (Ids_ rIdA _ _ _) <- serviceSignSendRecv shA rKeyA servicePKA ("1", NoEntity, New rPubA dhPub) + runSMPServiceClient t (tlsCredB, serviceKeysB) $ \shB -> do + Resp "2" NoEntity (Ids_ rIdB _ _ serviceIdB) <- serviceSignSendRecv shB rKeyB servicePKB ("2", NoEntity, New rPubB dhPub) + Resp "3" _ OK <- signSendRecv shB rKeyA ("3", rIdA, DEL) + Resp "" rIdA' DELD <- tGet1 shA + rIdA' `shouldBe` rIdA + runSMPServiceClient t (tlsCredB, serviceKeysB) $ \shB' -> do + subscribeServiceQueues shB' (C.APrivateAuthKey C.SEd25519 servicePKB) "4" serviceIdB [rIdB] + Resp "" _ (ENDS n idsHash) <- tGet1 shB + (n, idsHash) `shouldBe` (1, queueIdsHash [rIdB]) + +subscribeServiceQueues :: (HasCallStack, Transport c) => THandleSMP c 'TClient -> C.APrivateAuthKey -> ByteString -> ServiceId -> [RecipientId] -> IO () +subscribeServiceQueues sh servicePK corrId serviceId rIds = do + let n = fromIntegral $ length rIds + idsHash = queueIdsHash rIds + signSend_ sh servicePK Nothing (corrId, serviceId, SUBS n idsHash) + void $ + receiveInAnyOrder + sh + [ \case + Resp corrId' serviceId' (SOKS n' idsHash') | corrId' == CorrId corrId -> Just () <$ ((serviceId', n', idsHash') `shouldBe` (serviceId, n, idsHash)) + _ -> pure Nothing, + \case + Resp "" NoEntity ALLS -> pure $ Just () + _ -> pure Nothing + ] + readServiceSubsMetric :: String -> Maybe Int readServiceSubsMetric content = case filter ("simplex_smp_subscribtion_service_subs_total " `isPrefixOf`) (lines content) of @@ -1516,8 +1654,7 @@ testRestoreMessages = pure () rId <- readTVarIO recipientId logSize testStoreLogFile `shouldReturn` 2 - logSize testServerStatsBackupFile `shouldReturn` 101 - Right stats1 <- strDecode <$> B.readFile testServerStatsBackupFile + stats1 <- readSavedStats msType checkStats stats1 [rId] 5 1 withSmpServerConfigOn at cfg' testPort . runTest t $ \h -> do Just rKey <- readTVarIO recipientKey @@ -1532,8 +1669,7 @@ testRestoreMessages = logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) -- the last message is not removed because it was not ACK'd -- logSize testStoreMsgsFile `shouldReturn` 3 - logSize testServerStatsBackupFile `shouldReturn` 101 - Right stats2 <- strDecode <$> B.readFile testServerStatsBackupFile + stats2 <- readSavedStats msType checkStats stats2 [rId] 5 3 withSmpServerConfigOn at cfg' testPort . runTest t $ \h -> do @@ -1550,11 +1686,10 @@ testRestoreMessages = pure () logSize testStoreLogFile `shouldReturn` (if compacting then 1 else 2) removeFile testStoreLogFile - logSize testServerStatsBackupFile `shouldReturn` 101 - Right stats3 <- strDecode <$> B.readFile testServerStatsBackupFile + stats3 <- readSavedStats msType checkStats stats3 [rId] 5 5 removeFileIfExists testStoreMsgsFile - removeFile testServerStatsBackupFile + removeFileIfExists testServerStatsBackupFile where runTest :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO ()) -> ThreadId -> Expectation runTest _ test' server = do @@ -1580,6 +1715,76 @@ checkStats s qs sent received = do IS.toList _week `shouldBe` map (hash . unEntityId) qs IS.toList _month `shouldBe` map (hash . unEntityId) qs +readSavedStats :: HasTestEnv => AStoreType -> IO ServerStatsData +readSavedStats = \case + ASType _ SMSMemory -> do + logSize testServerStatsBackupFile `shouldReturn` 106 + either error id . strDecode <$> B.readFile testServerStatsBackupFile +#if defined(dbServerPostgres) + ASType _ SMSPostgres -> withStatsDB $ fmap (fromMaybe $ error "no saved stats") . getDBStats +#else + ASType _ SMSPostgres -> error "compiled without server_postgres flag" +#endif + +testSaveStatsPeriodically :: SpecWith (ASrvTransport, AStoreType) +testSaveStatsPeriodically = + it "should save stats while running and restore them on start" $ \(at@(ATransport t), msType) -> do + removeFileIfExists testServerStatsBackupFile + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {serverStatsBackupFile = Just testServerStatsBackupFile, statsSaveInterval = 1} + (rId, stats1, snapshot) <- withSmpServerConfigOn at cfg' testPort $ \_ -> do + (sId, rId) <- runClient t $ \h -> runClient t $ \rh -> do + (sId, rId, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello") + pure (sId, rId) + threadDelay 2500000 + stats1 <- readSavedStats msType + snapshot <- case msType of + ASType _ SMSMemory -> Just <$> B.readFile testServerStatsBackupFile + _ -> pure Nothing + runClient t $ \h -> do + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () + pure (rId, stats1, snapshot) + checkStats stats1 [rId] 1 0 + -- a crash leaves the last periodic save, not the save on shutdown + mapM_ (B.writeFile testServerStatsBackupFile) snapshot + stats2 <- withSmpServerConfigOn at cfg' testPort $ \_ -> threadDelay 2500000 >> readSavedStats msType + let restoredSent = case msType of + ASType _ SMSMemory -> 1 + _ -> 2 + checkStats stats2 [rId] restoredSent 0 + doesFileExist (testServerStatsBackupFile <> ".bak") `shouldReturn` False + removeFileIfExists testServerStatsBackupFile + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + +testStartupStoreCounts :: SpecWith (ASrvTransport, AStoreType) +testStartupStoreCounts = + it "should count stored queues and messages on start without saved stats" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let cfg' = cfgMS msType + withSmpServerConfigOn at cfg' testPort $ \_ -> runClient t $ \h -> runClient t $ \rh -> do + (sId, _, _, _) <- createAndSecureQueue rh sPub + Resp "1" _ OK <- signSendRecv h sKey ("1", sId, _SEND "hello 1") + Resp "2" _ OK <- signSendRecv h sKey ("2", sId, _SEND "hello 2") + pure () + let cfg2 = updateCfg cfg' $ \cfg_ -> cfg_ {prometheusInterval = Just 1} + removeFileIfExists testPrometheusMetricsFile + metrics <- withSmpServerConfigOn at cfg2 testPort $ \_ -> threadDelay 1500000 >> B.readFile testPrometheusMetricsFile + let expected :: [ByteString] + expected = case msType of + ASType SQSMemory _ -> ["simplex_smp_messages_total 2", "simplex_smp_queues_total1 1"] + -- Postgres queue count is a reltuples estimate + _ -> ["simplex_smp_messages_total 2"] + forM_ expected $ \l -> map (B.unwords . take 2 . B.words) (B.lines metrics) `shouldContain` [l] + where + runClient :: (HasTestEnv, Transport c) => TProxy c 'TServer -> (THandleSMP c 'TClient -> IO a) -> IO a + runClient _ = testSMPClient + testRestoreExpireMessages :: SpecWith (ASrvTransport, AStoreType) testRestoreExpireMessages = it "should store messages on exit and restore on start (old / v2)" $ \(at@(ATransport t), msType) -> do @@ -1628,7 +1833,7 @@ testRestoreExpireMessages = msgs'' <- B.readFile testStoreMsgsFile length (B.lines msgs'') `shouldBe` 2 B.lines msgs'' `shouldBe` drop 2 (B.lines msgs) - Right ServerStatsData {_msgExpired} <- strDecode <$> B.readFile testServerStatsBackupFile + ServerStatsData {_msgExpired} <- readSavedStats msType _msgExpired `shouldBe` 2 where exportStoreMessages :: HasTestEnv => AStoreType -> IO () @@ -2147,6 +2352,76 @@ testNotificationsInChunks = do ts <- 5000000 `timeout` tGetClient h >>= maybe (error "receive timeout") (pure . toList) (ts :) <$> receiveBlocks h (n - length ts) +testServiceNotificationsReturnToConnection :: SpecWith (ASrvTransport, AStoreType) +testServiceNotificationsReturnToConnection = + it "should move the notification service subscription back to the replaced connection when it subscribes again" $ \(ATransport t, msType) -> do + g <- C.newRandom + smpTest2 t msType $ \rh sh -> do + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (sId, rId, rKey, _) <- createAndSecureQueue rh sPub + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvNtfPubDhKey, _) <- atomically $ C.generateKeyPair g + Resp "1" _ (NID nId _) <- signSendRecv rh rKey ("1", rId, NKEY nPub rcvNtfPubDhKey) + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + serviceId <- testNtfServiceClient t serviceKeys $ \nh -> do + Resp "2" _ (SOK (Just serviceId)) <- serviceSignSendRecv nh nKey servicePK ("2", nId, NSUB) + pure serviceId + let idsHash = queueIdsHash [nId] + subscribeService nh corrId = do + Resp _ serviceId' (SOKS n idsHash') <- signSendRecv nh (C.APrivateAuthKey C.SEd25519 servicePK) (corrId, serviceId, NSUBS 1 idsHash) + (serviceId', n, idsHash') `shouldBe` (serviceId, 1, idsHash) + testNtfServiceClient t serviceKeys $ \nh1 -> do + subscribeService nh1 "3" + testNtfServiceClient t serviceKeys $ \nh2 -> do + subscribeService nh2 "4" + Resp "" _ (ENDS 1 _) <- tGet1 nh1 + subscribeService nh1 "5" + Resp "" _ (ENDS 1 _) <- tGet1 nh2 + Resp "6" _ OK <- signSendRecv sh sKey ("6", sId, _SEND' "hello") + Resp "" _ (Msg mId _) <- tGet1 rh + Resp "7" _ OK <- signSendRecv rh rKey ("7", rId, ACK mId) + Resp "" nId' (NMSG _ _) <- tGet1 nh1 + nId' `shouldBe` nId + Nothing <- 100000 `timeout` tGetClient @SMPVersion @ErrorType @BrokerMsg nh2 + pure () + +testServiceNotificationsRepeatedNSUB :: SpecWith (ASrvTransport, AStoreType) +testServiceNotificationsRepeatedNSUB = + it "should end the service subscription to a notifier once when NSUB is repeated in one block" $ \(ATransport t, msType) -> do + g <- C.newRandom + smpTest3 t msType $ \rh sh nh@THandle {params} -> do + let createNtfQueue = do + (sPub, sKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (sId, rId, rKey, _) <- createAndSecureQueue rh sPub + (nPub, nKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvNtfPubDhKey, _) <- atomically $ C.generateKeyPair g + Resp "1" _ (NID nId _) <- signSendRecv rh rKey ("1", rId, NKEY nPub rcvNtfPubDhKey) + pure (sId, sKey, rId, rKey, nId, nKey) + (sId1, sKey1, rId1, rKey1, nId1, nKey1) <- createNtfQueue + (_, _, _, _, nId2, nKey2) <- createNtfQueue + serviceKeys@(_, servicePK) <- atomically $ C.generateKeyPair g + testNtfServiceClient t serviceKeys $ \snh -> do + Resp "2" _ (SOK (Just serviceId)) <- serviceSignSendRecv snh nKey1 servicePK ("2", nId1, NSUB) + Resp "3" _ (SOK (Just _)) <- serviceSignSendRecv snh nKey2 servicePK ("3", nId2, NSUB) + let TransmissionForAuth {tForAuth, tToSend} = encodeTransmissionForAuth params (CorrId "4", nId2, NSUB) + Right auth <- pure $ authTransmission (thAuth params) False (Just nKey2) Nothing tForAuth + let nsub = Right (auth, tToSend) + [Right (), Right (), Right ()] <- tPut nh [nsub, nsub, nsub] + [Resp "4" _ (SOK Nothing), Resp "4" _ (SOK Nothing), Resp "4" _ (SOK Nothing)] <- tGetClient nh + Resp "" nId2' END <- tGet1 snh + nId2' `shouldBe` nId2 + Resp "5" _ OK <- signSendRecv sh sKey1 ("5", sId1, _SEND' "hello") + Resp "" _ (Msg mId _) <- tGet1 rh + Resp "6" _ OK <- signSendRecv rh rKey1 ("6", rId1, ACK mId) + Resp "" nId1' (NMSG _ _) <- tGet1 snh + nId1' `shouldBe` nId1 + testNtfServiceClient t serviceKeys $ \snh' -> do + let idsHash = queueIdsHash [nId1] + Resp "7" _ (SOKS 1 idsHash') <- signSendRecv snh' (C.APrivateAuthKey C.SEd25519 servicePK) ("7", serviceId, NSUBS 1 idsHash) + idsHash' `shouldBe` idsHash + Resp "" _ (ENDS n idsHash'') <- tGet1 snh + (n, idsHash'') `shouldBe` (1, idsHash) + testMsgExpireOnSend :: SpecWith (ASrvTransport, AStoreType) testMsgExpireOnSend = it "should expire messages that are not received before messageTTL on SEND" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do @@ -2186,6 +2461,23 @@ testMsgExpireOnInterval = Nothing -> return () Just _ -> error "nothing should be delivered" +testInactiveClientExpiration :: SpecWith (ASrvTransport, AStoreType) +testInactiveClientExpiration = + it "should disconnect inactive clients without subscriptions" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do + g <- C.newRandom + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _ :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + let cfg' = updateCfg (cfgMS msType) $ \cfg_ -> cfg_ {inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1}} + withSmpServerConfigOn (ATransport t) cfg' testPort $ \_ -> + testSMPClient @c $ \rh -> testSMPClient @c $ \h -> do + Resp "1" NoEntity (Ids _ _ _) <- signSendRecv rh rKey ("1", NoEntity, New rPub dhPub) + threadDelay 2500000 + try (timeout 2000000 $ tGet1 h) >>= \case + Left (_ :: SomeException) -> pure () + Right r -> unexpected (r :: Maybe (Transmission (Either ErrorType BrokerMsg))) + Resp "2" NoEntity PONG <- sendRecv rh (Nothing, "2", NoEntity, PING) + pure () + testMsgNOTExpireOnInterval :: SpecWith (ASrvTransport, AStoreType) testMsgNOTExpireOnInterval = it "should block and unblock message queues" $ \(ATransport (t :: TProxy c 'TServer), msType) -> do @@ -2393,6 +2685,182 @@ testDuplicateQueueLinkData = victimSId2 `shouldBe` victimSId victimLD2 `shouldBe` victimLD +testLargeCommand :: SpecWith (ASrvTransport, AStoreType) +testLargeCommand = + it "refuses a command larger than an encrypted block and keeps the session" $ \(at, msType) -> + withSmpServer (at, msType) $ do + g <- C.newRandom + ts <- getCurrentTime + c <- getProtocolClient g NRMInteractive (1, SMPServer testHost testPort testKeyHash, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> pure ()) >>= either (fail . show) pure + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + fd <- atomically $ C.randomBytes 2048 g + Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing + let largestUserData = 14165 + linkData n = (EncDataBytes fd, EncDataBytes $ B.replicate n 'a') + setLink n = runExceptT $ addSMPQueueLink c NRMInteractive rKey rId lnkId (linkData n) + setLink largestUserData `shouldReturn` Right () + setLink (largestUserData + 1) `shouldReturn` Left (PCETransportError TELargeMsg) + (fmap snd <$> runExceptT (getSMPQueueLink c NRMInteractive lnkId)) `shouldReturn` Right (linkData largestUserData) + +testSwapQueueLink :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLink = + it "swaps short link user data when the stored data hash matches" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r s -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + otherLnkId <- EntityId <$> atomically (C.randomBytes 24 g) + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + Resp "1" _ (LCUR ud) <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld1) Nothing ld1) + (ud, snd ld) #== "returns stored user data when the hash differs" + Resp "2" _ (LNK _ ld') <- sendRecv s ("", "2", lnkId, LGET) + (ld', ld) #== "link data unchanged after the hash differs" + + Resp "3" _ err1 <- signSendRecv r rKey ("3", rId, LSWP otherLnkId (userDataHash ld) Nothing ld1) + (err1, ERR AUTH) #== "rejects another link ID" + Resp "4" _ err2 <- signSendRecv r rKey ("4", rId, LSWP lnkId (userDataHash ld) Nothing (EncDataBytes "other fixed data", snd ld1)) + (err2, ERR AUTH) #== "rejects other fixed data" + + Resp "5" rId' OK <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld) Nothing ld1) + rId' `shouldBe` rId + Resp "6" _ (LNK _ ld1') <- sendRecv s ("", "6", lnkId, LGET) + (ld1', ld1) #== "replaces user data and keeps fixed data" + + (noLinkRId, noLinkKey, Nothing) <- createLinkQueue g r $ \_ -> QRContact Nothing + Resp "7" _ err3 <- signSendRecv r noLinkKey ("7", noLinkRId, LSWP lnkId (userDataHash ld1) Nothing ld1) + (err3, ERR AUTH) #== "rejects queue without link" + + (msgRId, msgKey, Just msgLnkId) <- createLinkQueue g r $ \sId -> QRMessaging $ Just (sId, ld) + Resp "8" _ err4 <- signSendRecv r msgKey ("8", msgRId, LSWP msgLnkId (userDataHash ld) Nothing ld1) + (err4, ERR AUTH) #== "rejects messaging queue" + +testSwapQueueLinkKeys :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkKeys = + it "swaps short link user data with recipient keys" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r s -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + (rPub', rKey') <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + Resp "1" _ OK <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld) (Just [C.toPublic rKey, rPub']) ld1) + Resp "2" _ err1 <- signSendRecv r rKey ("2", rId, LSET lnkId ld2) + (err1, ERR AUTH) #== "rejects LSET on a queue with two keys" + Resp "3" _ err2 <- signSendRecv r rKey' ("3", rId, LSET lnkId ld2) + (err2, ERR AUTH) #== "rejects LSET with the added key" + + Resp "4" _ OK <- signSendRecv r rKey' ("4", rId, LSWP lnkId (userDataHash ld1) (Just [rPub']) ld2) + Resp "5" _ err3 <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld2) Nothing ld1) + (err3, ERR AUTH) #== "rejects the removed key" + Resp "6" _ (LNK _ ld') <- sendRecv s ("", "6", lnkId, LGET) + (ld', ld2) #== "stores data written with the added key" + +testConcurrentSwapQueueLink :: SpecWith (ASrvTransport, AStoreType) +testConcurrentSwapQueueLink = + it "accepts one of concurrent swaps from the same data" $ \(ATransport t, msType) -> + smpTest2 t msType $ \r1 r2 -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + ld3 = (fst ld, EncDataBytes "user data 3") + (rId, rKey, _) <- createLinkQueue g r1 $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + + rs <- + concurrently + (signSendRecv r1 rKey ("1", rId, LSWP lnkId (userDataHash ld) Nothing ld1)) + (signSendRecv r2 rKey ("2", rId, LSWP lnkId (userDataHash ld) Nothing ld2)) + storedLD <- case rs of + (Resp "1" _ OK, Resp "2" _ (LCUR ud)) -> ld1 <$ (ud `shouldBe` snd ld1) + (Resp "1" _ (LCUR ud), Resp "2" _ OK) -> ld2 <$ (ud `shouldBe` snd ld2) + _ -> error $ "expected OK and LCUR, got " <> show rs + + Resp "3" _ OK <- signSendRecv r2 rKey ("3", rId, LSWP lnkId (userDataHash storedLD) Nothing ld3) + Resp "4" _ (LNK _ ld') <- sendRecv r1 ("", "4", lnkId, LGET) + (ld', ld3) #== "stores data swapped from the current data" + +testSwapQueueLinkClient :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkClient = + it "sends swaps only in v24 sessions, with up to 6 recipient keys" $ \(at, msType) -> + withSmpServer (at, msType) $ do + g <- C.newRandom + ts <- getCurrentTime + let srv = SMPServer testHost testPort testKeyHash + connect vr = getProtocolClient g NRMInteractive (1, srv, Nothing) defaultSMPClientConfig {serverVRange = vr} [] Nothing ts (\_ -> pure ()) >>= either (fail . show) pure + c <- connect supportedClientSMPRelayVRange + cPrev <- connect $ prevRange supportedClientSMPRelayVRange + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + fd <- atomically $ C.randomBytes 2048 g + let ld = (EncDataBytes fd, EncDataBytes $ B.replicate 13832 'a') + ld' = (EncDataBytes fd, EncDataBytes $ B.replicate 13832 'b') + otherKeys <- replicateM 5 $ fst <$> atomically (C.generateAuthKeyPair C.SEd25519 g) + (rPub7, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + Right QIK {rcvId = rId} <- runExceptT $ createSMPQueue c NRMInteractive Nothing (rPub, rKey) dhPub Nothing SMSubscribe (QRContact Nothing) Nothing + Right () <- runExceptT $ addSMPQueueLink c NRMInteractive rKey rId lnkId ld + let keys6 = rPub :| otherKeys + keys7 = keys6 <> [rPub7] + swap c' keys = runExceptT $ swapSMPQueueLink c' NRMInteractive rKey rId lnkId (userDataHash ld) keys ld' + storedLD = fmap snd <$> runExceptT (getSMPQueueLink c NRMInteractive lnkId) + + swap cPrev Nothing `shouldReturn` Left (PCETransportError TEVersion) + swap c (Just keys7) `shouldReturn` Left (PCETransportError TELargeMsg) + storedLD `shouldReturn` Right ld + swap c (Just keys6) `shouldReturn` Right Nothing + storedLD `shouldReturn` Right ld' + +testSwapQueueLinkStoreLog :: SpecWith (ASrvTransport, AStoreType) +testSwapQueueLinkStoreLog = + it "restores swapped short link data and recipient keys after restart" $ \(at@(ATransport t), msType) -> do + g <- C.newRandom + lnkId <- EntityId <$> atomically (C.randomBytes 24 g) + (rPub1, rKey1) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rPub2, rKey2) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let ld = (EncDataBytes "fixed data", EncDataBytes "user data") + ld1 = (fst ld, EncDataBytes "user data 1") + ld2 = (fst ld, EncDataBytes "user data 2") + ld3 = (fst ld, EncDataBytes "user data 3") + ld4 = (fst ld, EncDataBytes "user data 4") + (cfg', _) = serverStoreLogCfg msType + (rId, rKey) <- withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \r -> do + (rId, rKey, _) <- createLinkQueue g r $ \sId -> QRContact $ Just (lnkId, (sId, ld)) + Resp "1" _ OK <- signSendRecv r rKey ("1", rId, LSWP lnkId (userDataHash ld) (Just [C.toPublic rKey, rPub1]) ld1) + Resp "2" _ OK <- signSendRecv r rKey1 ("2", rId, LSWP lnkId (userDataHash ld1) (Just [rPub1, rPub2]) ld2) + Resp "3" _ OK <- signSendRecv r rKey2 ("3", rId, LSWP lnkId (userDataHash ld2) Nothing ld3) + pure (rId, rKey) + withSmpServerConfigOn at cfg' testPort $ \_ -> runSMPClient t $ \r -> do + Resp "4" _ (LNK _ ld') <- sendRecv r ("", "4", lnkId, LGET) + (ld', ld3) #== "restores data of the last swap" + Resp "5" _ err1 <- signSendRecv r rKey ("5", rId, LSWP lnkId (userDataHash ld3) Nothing ld4) + (err1, ERR AUTH) #== "restores removed key as removed" + Resp "6" _ (LCUR ud) <- signSendRecv r rKey1 ("6", rId, LSWP lnkId (userDataHash ld2) Nothing ld4) + (ud, snd ld3) #== "restores the first key" + Resp "7" _ OK <- signSendRecv r rKey2 ("7", rId, LSWP lnkId (userDataHash ld3) Nothing ld4) + Resp "8" _ (LNK _ ld4') <- sendRecv r ("", "8", lnkId, LGET) + (ld4', ld4) #== "swaps restored data" + +createLinkQueue :: Transport c => TVar ChaChaDRG -> THandleSMP c 'TClient -> (SenderId -> QueueReqData) -> IO (RecipientId, C.APrivateAuthKey, Maybe LinkId) +createLinkQueue g r queueReqData = do + (rPub, rKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (dhPub, _dhPriv :: C.PrivateKeyX25519) <- atomically $ C.generateKeyPair g + C.CbNonce corrId <- atomically $ C.randomCbNonce g + let sId = EntityId $ B.take 24 $ C.sha3_384 corrId + Resp _ NoEntity (IDS QIK {rcvId, linkId}) <- + signSendRecv r rKey (corrId, NoEntity, NEW (NewQueueReq rPub dhPub Nothing SMSubscribe (Just $ queueReqData sId) Nothing)) + pure (rcvId, rKey, linkId) + +userDataHash :: QueueLinkData -> LinkDataHash +userDataHash = linkDataHash . snd + samplePubKey :: C.APublicVerifyKey samplePubKey = C.APublicVerifyKey C.SEd25519 "MCowBQYDK2VwAyEAfAOflyvbJv1fszgzkQ6buiZJVgSpQWsucXq7U6zjMgY=" diff --git a/tests/Test.hs b/tests/Test.hs index 021ff4dd2..99dd844be 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} +{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeApplications #-} import AgentTests (agentCoreTests, agentTests) @@ -11,14 +12,18 @@ import CoreTests.CryptoFileTests import CoreTests.CryptoTests import CoreTests.EncodingTests import CoreTests.EthCryptoTests +import CoreTests.KeepAliveTests import CoreTests.LockTests import CoreTests.MsgStoreTests import CoreTests.RetryIntervalTests import CoreTests.SOCKSSettings +import CoreTests.ServerStatsTests import CoreTests.StoreLogTests import CoreTests.TSessionSubs +import CoreTests.TransportTests import CoreTests.UtilTests import CoreTests.VersionRangeTests +import Data.Maybe (fromMaybe) import FileDescriptionTests (fileDescriptionTests) import RSLVTests (rslvTests) import RemoteControl (remoteControlTests) @@ -32,11 +37,14 @@ import Simplex.Messaging.Transport (TLS, Transport (..)) import System.Directory (createDirectoryIfMissing, listDirectory, removePathForcibly) import System.Environment (getArgs, setEnv, withArgs) import System.FilePath (()) +import System.Timeout (timeout) import Test.Hspec hiding (fit, it) import Test.Hspec.Core.Runner (defaultConfig, evalSpec, evaluateResult, readConfig, runSpecForest) +import Test.Hspec.Core.Spec +import Test.Hspec.Runner (configPrintSlowItems) import Util import XFTPAgent -import XFTPCLI (xftpCLIFileTests) +import XFTPCLI (xftpCLIConcurrentTests, xftpCLIFileTests) import Simplex.FileTransfer.Server.Env (AFStoreType (..)) import Simplex.FileTransfer.Server.Store (SFSType (..)) import XFTPServerTests (xftpServerTests) @@ -52,7 +60,7 @@ import AgentTests.SchemaDump (schemaDumpTest) #if defined(dbServerPostgres) import CoreTests.XFTPStoreTests (xftpStoreTests, xftpMigrationTests) -import NtfServerTests (ntfServerTests) +import NtfServerTests (ntfServerTests, ntfStoreTests) import NtfClient (ntfTestServerDBConnectInfo, ntfTestServerDBOpts) import SMPClient (testServerDBConnectInfo, testServerDBOpts) import SMPProxyTests (smpProxyPostgresTests) @@ -66,11 +74,18 @@ import PostgresSchemaDump (postgresSchemaDumpTest) import SMPClient (postgressBracket) #endif +#if MIN_VERSION_base(4,18,0) +import Control.Concurrent (forkIO, threadDelay) +import Control.Monad (forM_, void) +import GHC.Conc.Sync (listThreads, threadLabel, threadStatus) +#endif + logCfg :: LogConfig logCfg = LogConfig {lc_file = Nothing, lc_stderr = True} main :: IO () main = do + dumpThreadsAfter 25 setLogLevel testLogLevel withGlobalLogging logCfg $ do setEnv "APNS_KEY_ID" "H82WD9K9AQ" @@ -85,6 +100,7 @@ main = do . aroundAll_ (postgressBracket ntfTestServerDBConnectInfo) . aroundAll_ (postgressBracket testXFTPDBConnectInfo) #endif + . deadline (360 * 1000000) $ do parallel $ do describe "Core tests" $ do @@ -95,11 +111,14 @@ main = do describe "Ethereum crypto tests" ethCryptoTests describe "Encrypted files tests" cryptoFileTests describe "Message store tests" msgStoreTests + describe "Server stats tests" serverStatsTests describe "SOCKS settings tests" socksSettingsTests + describe "TCP keep-alive tests" keepAliveTests describe "Store log tests" storeLogTests describe "XFTP store log tests" fileStoreLogTests fileExpirationTests describe "TSessionSubs tests" tSessionSubsTests + describe "Transport tests" transportTests describe "Util tests" utilTests describe "Names resolver tests" smpNamesTests describe "RSLV functional API tests" rslvTests @@ -120,6 +139,7 @@ main = do ntfServerTests (transport @TLS, ASType SQSMemory SMSMemory) describe "Notifications server (SMP server: postgres-only store)" $ ntfServerTests (transport @TLS, ASType SQSPostgres SMSPostgres) + describe "Notifications store" ntfStoreTests describe "SMP client agent, server postgres-only message store" $ agentTests (transport @TLS, ASType SQSPostgres SMSPostgres) describe "SMP proxy, postgres-only message store" $ do before (pure $ ASType SQSPostgres SMSPostgres) smpProxyTests @@ -168,7 +188,7 @@ main = do describe "SMP proxy capabilities, memory message store" $ before (pure $ ASType SQSMemory SMSMemory) smpProxyCapabilityTests describe "XFTP CLI (memory)" $ - before (pure $ AFSType SFSMemory) xftpCLIFileTests + before (pure $ AFSType SFSMemory) $ xftpCLIFileTests >> xftpCLIConcurrentTests #if defined(dbServerPostgres) describe "XFTP CLI (PostgreSQL)" $ before (pure $ AFSType SFSPostgres) xftpCLIFileTests @@ -205,9 +225,23 @@ main = do describe "Agent SQLite schema dump" schemaDumpTest #endif +dumpThreadsAfter :: Int -> IO () +#if MIN_VERSION_base(4,18,0) +dumpThreadsAfter minutes = void . forkIO $ do + threadDelay $ minutes * 60000000 + ts <- listThreads + putStrLn $ "=== " <> show (length ts) <> " threads after " <> show minutes <> " minutes" + forM_ ts $ \t -> do + s <- threadStatus t + l <- threadLabel t + putStrLn $ show t <> " " <> show s <> " " <> maybe "" id l +#else +dumpThreadsAfter _ = pure () +#endif + hspecInTmpDir :: Spec -> IO () hspecInTmpDir spec = do - (config, forest) <- evalSpec defaultConfig spec + (config, forest) <- evalSpec defaultConfig {configPrintSlowItems = Just 10} spec config' <- getArgs >>= readConfig config withTmpDir (withArgs [] $ runSpecForest forest config') >>= evaluateResult @@ -215,3 +249,4 @@ withTmpDir :: IO a -> IO a withTmpDir = bracket_ (createDirectoryIfMissing False tmpDir >> clearTmpDir) clearTmpDir where clearTmpDir = listDirectory tmpDir >>= mapM_ (removePathForcibly . (tmpDir )) + diff --git a/tests/Util.hs b/tests/Util.hs index 41361af51..39083e1c2 100644 --- a/tests/Util.hs +++ b/tests/Util.hs @@ -8,16 +8,17 @@ module Util where -import Control.Concurrent (threadDelay) +import Control.Concurrent (ThreadId, myThreadId, threadDelay) import Control.Concurrent.Async import Control.Concurrent.STM import Control.Exception as E import Control.Logger.Simple -import Control.Monad (replicateM, when) +import Control.Monad (replicateM, unless, when) import Data.Either (partitionEithers) import Data.List (tails) +import Data.Maybe (fromMaybe) import Data.String (IsString (..)) -import GHC.Conc (getNumCapabilities, getNumProcessors, setNumCapabilities) +import GHC.Conc (BlockReason (..), ThreadStatus (..), getNumCapabilities, getNumProcessors, setNumCapabilities, threadStatus) import GHC.IO.Exception (IOException (..)) import qualified GHC.IO.Exception as IOException import Network.Socket (ServiceName) @@ -29,7 +30,7 @@ import System.Process (callCommand) import System.Timeout (timeout) import Test.Hspec hiding (fit, it, xit) import qualified Test.Hspec as Hspec -import Test.Hspec.Core.Spec (Example (..), Result (..), ResultStatus (..)) +import Test.Hspec.Core.Spec (Example (..), FailureReason (..), Item (..), Result (..), ResultStatus (..), mapSpecItem_) withNumCapabilities :: Int -> IO a -> IO a withNumCapabilities new a = getNumCapabilities >>= \old -> bracket_ (setNumCapabilities new) (setNumCapabilities old) a @@ -44,6 +45,28 @@ inParrallel n action = do map show es `shouldBe` [] length rs `shouldBe` n +testCancelledInside :: (IO () -> IO a) -> IO () +testCancelledInside action = do + canceller <- myThreadId + testCancelledWhenBlocked $ \started -> action $ started >> waitStatus canceller (== ThreadBlocked BlockedOnException) + +testCancelledWhenBlocked :: (IO () -> IO a) -> IO () +testCancelledWhenBlocked action = do + started <- newEmptyTMVarIO + a <- async $ action $ atomically $ putTMVar started () + atomically $ takeTMVar started + waitStatus (asyncThreadId a) (/= ThreadRunning) + cancel a + waitCatch a >>= \case + Left e -> fromException e `shouldBe` Just AsyncCancelled + Right _ -> expectationFailure "cancelled thread continued" + +waitStatus :: ThreadId -> (ThreadStatus -> Bool) -> IO () +waitStatus t done = do + threadDelay 1000 + status <- threadStatus t + unless (done status) $ waitStatus t done + combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations k xs = [y : ys | y : xs' <- tails xs, ys <- combinations (k - 1) xs'] @@ -118,6 +141,14 @@ eventuallyRemove path retries = case retries of data TestWrapper a = TestWrapper String (HasTestEnv => a) +-- | Abort a test after the specified number of microseconds. +deadline :: Int -> SpecWith b -> SpecWith b +deadline limit = mapSpecItem_ $ \item@Item {itemLocation, itemExample} -> + item + { itemExample = \params aw pc -> + fromMaybe (Result "timed out" . Failure itemLocation $ Reason "time limit") <$> timeout limit (itemExample params aw pc) + } + -- TODO [ntfdb] running wiht LogWarn level shows potential issue "Queue count differs" testLogLevel :: LogLevel testLogLevel = LogError diff --git a/tests/XFTPAgent.hs b/tests/XFTPAgent.hs index 8dc8c0bb7..50548a34c 100644 --- a/tests/XFTPAgent.hs +++ b/tests/XFTPAgent.hs @@ -13,6 +13,7 @@ module XFTPAgent where import AgentTests.FunctionalAPITests (get, nGet, pGet, rfGet, runRight, runRight_, sfGet, withAgent, testServerInformation) +import Control.Concurrent.STM (retry) import Control.Logger.Simple import Control.Monad import Control.Monad.Except @@ -22,23 +23,27 @@ import qualified Data.ByteString.Lazy as LB import Data.Either (isLeft) import Data.Int (Int64) import Data.List (find, isSuffixOf) +import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M -import Data.Maybe (fromJust) +import Data.Maybe (fromJust, isJust) import qualified Data.Set as S import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay) import Data.Time.Clock.System (getSystemTime, systemSeconds) -import SMPAgentClient (agentCfg, initAgentServers, testDB, testDB2, testDB3) +import GHC.Conc (BlockReason (BlockedOnSTM), ThreadStatus (ThreadBlocked), threadStatus) +import SMPAgentClient (agentCfg, initAgentServers, noAuthSrvCfg, testDB, testDB2, testDB3, userServers) +import SMPClient (testHost2, withStallingServerOn') import Simplex.FileTransfer.Client (XFTPClientConfig (..)) -import Simplex.FileTransfer.Description (FileChunk (..), FileDescription (..), FileDescriptionURI (..), ValidFileDescription, fileDescriptionURI, kb, mb, qrSizeLimit, pattern ValidFileDescription) -import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..)) +import Simplex.FileTransfer.Description (ChunkReplicaId (..), FileChunk (..), FileChunkReplica (..), FileDescription (..), FileDescriptionURI (..), FileDigest (..), FileSize (..), ValidFileDescription, fileDescriptionURI, kb, mb, qrSizeLimit, validateFileDescription, pattern ValidFileDescription) +import Simplex.FileTransfer.Protocol (FileParty (..), GrantedStorageTime (..), SFileParty (..)) import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..), defaultFileExpiration) import Simplex.FileTransfer.Server.Store (STMFileStore) import Simplex.FileTransfer.Transport (XFTPErrorType (AUTH)) import Simplex.FileTransfer.Types (FileErrorType (NO_FILE), RcvFileId, SndFileId) import Simplex.Messaging.Agent (AgentClient, testProtocolServer, xftpDeleteRcvFile, xftpDeleteSndFileInternal, xftpDeleteSndFileRemote, xftpPrepareReceiveFile, xftpPrepareSendFile, xftpReceiveFile, xftpSendDescription, xftpStartReceiveFile, xftpStartSendFile, xftpStartWorkers) import qualified Simplex.Messaging.Agent as XA -import Simplex.Messaging.Agent.Client (AgentClient (xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, xftpCfg) +import Simplex.Messaging.Agent.Client (AgentClient (subQ, xftpClients, xftpServersStats), AgentOpState (..), AgentOperation (..), ProtocolTestFailure (..), ProtocolTestStep (..), agentClientStore, beginAgentOperation, endAgentOperation) +import qualified Simplex.Messaging.Agent.Client as AC +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, InitialAgentServers, xftpCfg) import qualified Simplex.Messaging.Agent.Env.SQLite as AEnv import Simplex.Messaging.Agent.Protocol hiding (SFDONE) import qualified Simplex.Messaging.Agent.Protocol as A @@ -46,20 +51,22 @@ import Simplex.Messaging.Agent.Stats (AgentXFTPServerStats (downloadAttempts, up import Simplex.Messaging.Agent.Store.Common (withTransaction) import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Agent.Store.Interface (closeDBStore) -import Simplex.Messaging.Client (pattern NRMInteractive) +import Simplex.Messaging.Client (TransportSessionMode (..), pattern NRMInteractive) import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.BBS (bbsKeyGen) import Simplex.Messaging.Crypto.Entitlement (Entitlement (..), MasterKey (..), signEntitlement) import Simplex.Messaging.Crypto.File (CryptoFile (..), CryptoFileArgs) import qualified Simplex.Messaging.Crypto.File as CF import Simplex.Messaging.Encoding.String (StrEncoding (..)) -import Simplex.Messaging.Protocol (BasicAuth, NetworkError (..), ProtoServerWithAuth (..), ProtocolServer (..), XFTPServer, XFTPServerWithAuth) +import Simplex.Messaging.Protocol (AProtocolType (..), BasicAuth, EntityId (..), NetworkError (..), ProtoServerWithAuth (..), ProtocolServer (..), SProtocolType (..), XFTPServer, XFTPServerWithAuth) import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) import Simplex.Messaging.Server.Information (ServerPublicInfo) import Simplex.Messaging.Transport (EntitlementConfig (..)) -import Simplex.Messaging.Util (tshow, unlessM) +import qualified Simplex.Messaging.TMap as TM +import Simplex.Messaging.Util (ifM, tshow, unlessM) import System.Directory (Permissions (writable), createDirectory, doesDirectoryExist, doesFileExist, getFileSize, getPermissions, listDirectory, removeFile, setPermissions) import System.FilePath (()) +import System.Mem.Weak (deRefWeak) import Test.Hspec hiding (fit, it, xit) import UnliftIO import UnliftIO.Concurrent @@ -83,6 +90,7 @@ xftpAgentTests = it "should send and receive with encrypted local files" testXFTPAgentSendReceiveEncrypted it "should send and receive large file with a redirect" testXFTPAgentSendReceiveRedirect it "should send and receive small file without a redirect" testXFTPAgentSendReceiveNoRedirect + it "should remove received chunks before publishing completion" testXFTPAgentCompletionCleanup it "should receive prepared file only after it is started" testXFTPAgentPrepareReceive it "should send prepared file only after it is started" testXFTPAgentPrepareSend it "should prepare files concurrently in distinct work directories" $ \_ -> testXFTPAgentPrepareSendConcurrently @@ -91,6 +99,20 @@ xftpAgentTests = it "should resume receiving file after restart" $ \_ -> testXFTPAgentReceiveRestore it "should cleanup rcv tmp path after permanent error" $ \_ -> testXFTPAgentReceiveCleanup it "should report permanent error even when rcv tmp path cannot be removed" $ \_ -> testXFTPAgentReceiveCleanupError + it "should limit download sessions with servers outside the user's list" $ + testXFTPAgentDownloadSessionsLimit xftpServer2Only + it "should limit download sessions with servers outside the user's list in entity session mode" $ + testXFTPAgentDownloadSessionsLimit $ entitySessionMode xftpServer2Only + it "should release download sessions of stopped workers" testXFTPAgentDownloadSessionsStopped + it "should keep download session with a server outside the user's list for all chunks of a file" $ + testXFTPAgentDownloadSessionChunks xftpServer2Only 1 + it "should open download session per chunk with a server outside the user's list in entity session mode" $ + testXFTPAgentDownloadSessionChunks (entitySessionMode xftpServer2Only) 2 + it "should close download sessions in entity session mode" $ + testXFTPAgentDownloadSessions (entitySessionMode initAgentServers) 0 + it "should keep download session shared with the user's server" $ testXFTPAgentDownloadSessions initAgentServers 1 + it "should keep download session with a disabled server in the user's list" $ + testXFTPAgentDownloadSessions initAgentServers {AEnv.xftp = M.fromList [(1, noAuthSrvCfg testXFTPServer2 {host = testHost2} :| [(noAuthSrvCfg testXFTPServer) {AEnv.enabled = False}])]} 1 it "should resume sending file after restart" $ \_ -> testXFTPAgentSendRestore it "should cleanup snd prefix path after permanent error" $ \_ -> testXFTPAgentSendCleanup it "should delete sent file on server" testXFTPAgentDelete @@ -148,8 +170,13 @@ testXFTPServerTest :: (HasCallStack, HasTestEnv) => Maybe BasicAuth -> XFTPServe testXFTPServerTest newFileBasicAuth srv = withXFTPServerCfg testXFTPServerConfig {newFileBasicAuth, xftpPort = xftpTestPort2, information = Just testServerInformation} $ \_ -> -- initially passed server is not running - withAgent 1 agentCfg initAgentServers testDB $ \a -> - testProtocolServer a NRMInteractive 1 srv + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let workPath = testPath "xftp-work-files" + createDirectory workPath + runRight_ $ xftpStartWorkers a (Just workPath) + r <- testProtocolServer a NRMInteractive 1 srv + listDirectory workPath `shouldReturn` [] + pure r rfProgress :: forall m. (HasCallStack, MonadIO m, MonadFail m) => AgentClient -> Int64 -> m () rfProgress c expected = loop 0 @@ -316,6 +343,63 @@ testXFTPAgentSendReceiveNoRedirect = withXFTPServer $ do inBytes <- B.readFile filePathIn B.readFile out `shouldReturn` inBytes +-- A full event queue is a barrier at RFDONE, after real download/decryption. +-- Holding the not-yet-started local worker lets us install that barrier after +-- draining RFPROG, without sleeps or changing the transfer implementation. +testXFTPAgentCompletionCleanup :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () +testXFTPAgentCompletionCleanup = withXFTPServer $ do + filePathIn <- createRandomFile_ (kb 64) "completion-order" + sentBytes <- B.readFile filePathIn + withAgent 1 agentCfg initAgentServers testDB $ \sndr -> do + runRight_ $ xftpStartWorkers sndr (Just senderFiles) + _ <- runRight $ xftpSendFile sndr 1 (CryptoFile filePathIn Nothing) 1 + sfProgress sndr (kb 128) + (_, _, SFDONE _ (description : _)) <- sfGet sndr + withAgent 2 agentCfg {AEnv.tbqSize = 1} initAgentServers testDB2 $ \rcp -> do + let AEnv.XFTPAgent {AEnv.xftpWorkDir, AEnv.xftpRcvWorkers} = AEnv.xftpAgent $ AC.agentEnv rcp + AEnv.Worker {AEnv.action, AEnv.doWork, AEnv.restarts} <- atomically $ do + writeTVar xftpWorkDir $ Just recipientFiles + workerId <- stateTVar (AC.workerSeq rcp) $ \next -> (next, next + 1) + w <- AEnv.Worker workerId <$> newTMVar () <*> newEmptyTMVar <*> newTVar (AEnv.RestartCount 0 0) + TM.insert Nothing w xftpRcvWorkers + pure w + let releaseWorker = atomically $ void $ tryPutTMVar action Nothing + flip finally releaseWorker $ do + rfId <- runRight $ xftpReceiveFile rcp 1 description Nothing True + rfProgress rcp (kb 128) + [prefixDir] <- listDirectory recipientFiles + let prefixPath = recipientFiles prefixDir + tmpPath = prefixPath "xftp.encrypted" + outputPath = prefixPath "xftp.decrypted" + doesDirectoryExist tmpPath `shouldReturn` True + -- No producer can publish completion until this sentinel is consumed. + atomically $ writeTBQueue (AC.subQ rcp) ("barrier", rfId, AEvt SAERcvFile $ RFPROG 0 (kb 128)) + releaseWorker + weak <- atomically $ readTMVar action >>= maybe retry pure + Just tid <- deRefWeak weak + let awaitPublish = do + blocked <- (== ThreadBlocked BlockedOnSTM) <$> threadStatus tid + decrypted <- + if blocked + then ifM (doesFileExist outputPath) ((== sentBytes) <$> B.readFile outputPath) (pure False) + else pure False + unless (blocked && decrypted) $ yield >> awaitPublish + timeout 10000000 awaitPublish `shouldReturn` Just () + -- This fails on the old order: its worker is blocked in notify while + -- the encrypted chunk directory still exists. + doesDirectoryExist tmpPath `shouldReturn` False + rfGet rcp `shouldReturn` ("barrier", rfId, RFPROG 0 (kb 128)) + rfGet rcp `shouldReturn` ("", rfId, RFDONE outputPath) + -- Model the consumer immediately deleting its completed receive. + xftpDeleteRcvFile rcp rfId + let awaitIdle = do + idle <- atomically $ isEmptyTMVar doWork + blocked <- (== ThreadBlocked BlockedOnSTM) <$> threadStatus tid + unless (idle && blocked) $ yield >> awaitIdle + timeout 10000000 awaitIdle `shouldReturn` Just () + AEnv.restartCount <$> readTVarIO restarts `shouldReturn` 0 + atomically (tryReadTBQueue $ AC.subQ rcp) `shouldReturn` Nothing + testXFTPAgentPrepareReceive :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () testXFTPAgentPrepareReceive = withXFTPServer $ do filePath <- createRandomFile @@ -628,6 +712,84 @@ testXFTPAgentReceiveCleanupError = withGlobalLogging logCfgNoLogs $ do `finally` setPermissions prefixPath perms doesDirectoryExist tmpPath `shouldReturn` True +testXFTPAgentDownloadSessionsLimit :: (HasCallStack, HasTestEnv) => InitialAgentServers -> AFStoreType -> IO () +testXFTPAgentDownloadSessionsLimit rcpServers = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers {AEnv.xftp = userServers $ testXFTPServer {host = testHost2} :| []} + silentRfd <- silentServersDescription 6 + withStallingServerOn' xftpTestPort2 $ \accepted _ -> + withAgent 2 agentCfg {AEnv.xftpMaxDownloadSessions = 1} rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 silentRfd Nothing True + timeout 5000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + threadDelay 500000 + M.size <$> readTVarIO (xftpClients rcp) `shouldReturn` 1 + timeout 5000000 (runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320)) >>= (`shouldSatisfy` isJust) + +testXFTPAgentDownloadSessionsStopped :: (HasCallStack, HasTestEnv) => AFStoreType -> IO () +testXFTPAgentDownloadSessionsStopped = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers + silentRfd <- silentServersDescription 1 + withStallingServerOn' xftpTestPort2 $ \accepted _ -> + withAgent 2 agentCfg {AEnv.xftpMaxDownloadSessions = 1} xftpServer2Only testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 silentRfd Nothing True + timeout 5000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + XA.disconnectAgentClient rcp + XA.resumeAgentClient rcp + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + timeout 10000000 (runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320)) >>= (`shouldSatisfy` isJust) + +silentServersDescription :: HasTestEnv => Int -> IO (ValidFileDescription 'FRecipient) +silentServersDescription n = do + g <- C.newRandom + key <- atomically $ C.randomSbKey g + nonce <- atomically $ C.randomCbNonce g + (_, replicaKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let chunk i = FileChunk {chunkNo = i, chunkSize = FileSize $ kb 64, digest = FileDigest "abc", replicas = [FileChunkReplica {server = testXFTPServer2 {keyHash = C.KeyHash $ B.pack $ show i}, replicaId = ChunkReplicaId $ EntityId "abc", replicaKey}]} + either fail pure . validateFileDescription $ + FileDescription {party = SFRecipient, size = FileSize $ kb 64 * fromIntegral n, digest = FileDigest "abc", key, nonce, chunkSize = FileSize $ kb 64, chunks = map chunk [1 .. n], redirect = Nothing} + +testXFTPAgentDownloadSessions :: (HasCallStack, HasTestEnv) => InitialAgentServers -> Int -> AFStoreType -> IO () +testXFTPAgentDownloadSessions rcpServers sessions = withXFTPServer $ do + (filePath, rfd) <- sendTwoChunkFile initAgentServers + withAgent 2 agentCfg rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ testReceiveCF' rcp rfd Nothing filePath (kb 320) + M.size <$> readTVarIO (xftpClients rcp) `shouldReturn` sessions + +testXFTPAgentDownloadSessionChunks :: (HasCallStack, HasTestEnv) => InitialAgentServers -> Int -> AFStoreType -> IO () +testXFTPAgentDownloadSessionChunks rcpServers connects = withXFTPServer $ do + (_, rfd) <- sendTwoChunkFile initAgentServers + withAgent 2 agentCfg rcpServers testDB2 $ \rcp -> do + runRight_ $ xftpStartWorkers rcp (Just recipientFiles) + _ <- runRight $ xftpReceiveFile rcp 1 rfd Nothing True + timeout 10000000 (xftpConnectsUntilReceived rcp) `shouldReturn` Just connects + timeout 5000000 (atomically $ readTVar (xftpClients rcp) >>= checkSTM . M.null) `shouldReturn` Just () + +sendTwoChunkFile :: (HasCallStack, HasTestEnv) => InitialAgentServers -> IO (FilePath, ValidFileDescription 'FRecipient) +sendTwoChunkFile sndServers = do + filePath <- createRandomFile_ (kb 319 :: Integer) "testfile" + rfd <- withAgent 1 agentCfg sndServers testDB $ \sndr -> runRight $ do + (_, _, rfd, _) <- testSendCF' sndr (CF.plain filePath) (kb 320) + pure rfd + pure (filePath, rfd) + +xftpServer2Only :: HasTestEnv => InitialAgentServers +xftpServer2Only = initAgentServers {AEnv.xftp = userServers $ testXFTPServer2 {host = testHost2} :| []} + +entitySessionMode :: InitialAgentServers -> InitialAgentServers +entitySessionMode servers = servers {AEnv.netCfg = (AEnv.netCfg servers) {AEnv.sessionMode = TSMEntity}} + +xftpConnectsUntilReceived :: AgentClient -> IO Int +xftpConnectsUntilReceived c = count 0 + where + count :: Int -> IO Int + count n = + atomically (readTBQueue $ subQ c) >>= \case + (_, _, AEvt _ (CONNECT (AProtocolType SPXFTP) _)) -> count (n + 1) + (_, _, AEvt _ RFDONE {}) -> pure n + _ -> count n + testXFTPAgentSendRestore :: (HasCallStack, HasTestEnv) => IO () testXFTPAgentSendRestore = withGlobalLogging logCfgNoLogs $ do filePath <- createRandomFile diff --git a/tests/XFTPCLI.hs b/tests/XFTPCLI.hs index 6ec442aab..f5be021ab 100644 --- a/tests/XFTPCLI.hs +++ b/tests/XFTPCLI.hs @@ -1,20 +1,31 @@ -module XFTPCLI (xftpCLIFileTests, xftpCLI) where +{-# LANGUAGE DisambiguateRecordFields #-} +module XFTPCLI (xftpCLIFileTests, xftpCLIConcurrentTests, xftpCLI) where + +import Control.Concurrent (yield) +import Control.Concurrent.Async (forConcurrently_) +import Control.Concurrent.STM (atomically, modifyTVar', newTVarIO, readTVarIO) import Control.Exception (try) +import Control.Monad (forM_, when) +import Control.Monad.Trans.Except (runExceptT) import qualified Data.ByteString as LB +import Data.Int (Int64) import Data.List (isInfixOf, isPrefixOf, isSuffixOf) +import Data.String (fromString) import Simplex.FileTransfer.Client.Main ( prepareChunkSizes, xftpClientCLI, xftpClientDeprecationNotice, ) +import qualified Simplex.FileTransfer.Client.Main as CLI import Simplex.FileTransfer.Description (kb, mb) import Simplex.FileTransfer.Util (safeFileNameStr, uniqueCombine) -import System.Directory (getFileSize, listDirectory) +import Simplex.Messaging.Util (unlessM) +import System.Directory (copyFile, createDirectory, createDirectoryIfMissing, getFileSize, listDirectory) import System.Environment (withArgs) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (takeFileName, ()) -import System.IO.Silently (capture, capture_) +import System.IO.Silently (capture, capture_, silence) import Test.Hspec hiding (fit, it) import Util import Simplex.FileTransfer.Server.Env (AFStoreType) @@ -43,6 +54,14 @@ xftpCLIFileTests = do sanitized n = let n' = safeFileNameStr n in n' /= "" && n' /= "." && n' /= ".." bareName n = let n' = safeFileNameStr n in n' == takeFileName n' +xftpCLIConcurrentTests :: SpecWith AFStoreType +xftpCLIConcurrentTests = + describe "concurrent transfers" $ do + it "should send files with one temporary folder" $ withXFTPServer testXFTPCLISendSharedTemp + it "should save file descriptions in one folder" $ withXFTPServer testXFTPCLISendSharedOutput + it "should receive files with one temporary folder" $ withXFTPServer testXFTPCLIReceiveSharedTemp + it "should save received files in one folder" $ withXFTPServer testXFTPCLIReceiveSharedOutput + xftpCLI :: [String] -> IO [String] xftpCLI params = lines <$> capture_ (withArgs params xftpClientCLI) @@ -161,6 +180,62 @@ testXFTPCLIDelete_ = do xftpCLI ["recv", fdRcv2, recipientFiles, "--tmp=" <> testDir] `shouldThrow` anyException +testXFTPCLISendSharedTemp :: HasTestEnv => IO () +testXFTPCLISendSharedTemp = do + let tmpPath = testPath "xftp-tmp" + sndPath r i = senderFiles show r show i + rcvPath r i = recipientFiles show r show i + createDirectory tmpPath + forM_ [1 .. rounds] $ \r -> do + forM_ [1 .. transfers] $ \i -> do + createDirectoryIfMissing True $ sndPath r i + createDirectoryIfMissing True $ rcvPath r i + createTestFile $ sndPath r i + silence $ atOnce $ \i -> sendFile (\_ _ -> pure ()) (sndPath r i "testfile") (sndPath r i) tmpPath + silence $ forConcurrently_ [1 .. transfers] $ \i -> receiveFile (sndPath r i "testfile.xftp" "rcv1.xftp") (rcvPath r i) (rcvPath r i) + forM_ [1 .. transfers] $ \i -> do + file <- LB.readFile $ sndPath r i "testfile" + LB.readFile (rcvPath r i "testfile") `shouldReturn` file + listDirectory tmpPath `shouldReturn` [] + +testXFTPCLISendSharedOutput :: HasTestEnv => IO () +testXFTPCLISendSharedOutput = do + filePath <- createTestFile senderFiles + let tmpPath i = testPath "xftp-tmp" show i + forM_ [1 .. transfers] $ createDirectoryIfMissing True . tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + let outPath = senderFiles show r + uploaded <- newBarrier transfers + forConcurrently_ [1 .. transfers] $ \i -> + sendFile (\sent total -> when (sent == total) uploaded) filePath outPath (tmpPath i) + length <$> listDirectory outPath `shouldReturn` transfers + +testXFTPCLIReceiveSharedTemp :: HasTestEnv => IO () +testXFTPCLIReceiveSharedTemp = do + (file, fdRcv) <- sendTestFile + let tmpPath = testPath "xftp-tmp" + outPath r i = recipientFiles show r show i + createDirectory tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + forM_ [1 .. transfers] $ \i -> copyFile fdRcv (fdCopy i) >> createDirectoryIfMissing True (outPath r i) + atOnce $ \i -> receiveFile (fdCopy i) (outPath r i) tmpPath + forM_ [1 .. transfers] $ \i -> LB.readFile (outPath r i "testfile") `shouldReturn` file + listDirectory tmpPath `shouldReturn` [] + +testXFTPCLIReceiveSharedOutput :: HasTestEnv => IO () +testXFTPCLIReceiveSharedOutput = do + (file, fdRcv) <- sendTestFile + let tmpPath i = testPath "xftp-tmp" show i + forM_ [1 .. transfers] $ createDirectoryIfMissing True . tmpPath + silence $ forM_ [1 .. rounds] $ \r -> do + let outPath = recipientFiles show r + createDirectory outPath + forM_ [1 .. transfers] $ \i -> copyFile fdRcv (fdCopy i) + atOnce $ \i -> receiveFile (fdCopy i) outPath (tmpPath i) + files <- listDirectory outPath + length files `shouldBe` transfers + forM_ files $ \f -> LB.readFile (outPath f) `shouldReturn` file + testReceivedFileNameCombine :: HasTestEnv => IO () testReceivedFileNameCombine = uniqueCombine recipientFiles "../../escaped.txt" `shouldReturn` (recipientFiles "escaped.txt") @@ -193,3 +268,65 @@ downloadProgress fileName s = "Downloading file..." `isPrefixOf` s && "Decrypting file..." `isInfixOf` s && ("File downloaded: " <> recipientFiles fileName <> "\r") `isSuffixOf` s + +transfers :: Int +transfers = 8 + +rounds :: Int +rounds = 20 + +createTestFile :: FilePath -> IO FilePath +createTestFile dir = do + let filePath = dir "testfile" + xftpCLI ["rand", filePath, "1kb"] `shouldReturn` ["File created: " <> filePath] + pure filePath + +sendTestFile :: HasTestEnv => IO (LB.ByteString, FilePath) +sendTestFile = do + filePath <- createTestFile senderFiles + silence $ sendFile (\_ _ -> pure ()) filePath senderFiles testDir + file <- LB.readFile filePath + pure (file, filePath <> ".xftp" "rcv1.xftp") + +sendFile :: HasTestEnv => (Int64 -> Int64 -> IO ()) -> FilePath -> FilePath -> FilePath -> IO () +sendFile notifyProgress src outPath tmpPath = + runExceptT (CLI.cliSendFileOpts opts False notifyProgress) `shouldReturn` Right () + where + opts = + CLI.SendOptions + { filePath = src, + outputDir = Just outPath, + numRecipients = 1, + xftpServers = [fromString testXFTPServerStr], + retryCount = 3, + tempPath = Just tmpPath, + verbose = False + } + +receiveFile :: FilePath -> FilePath -> FilePath -> IO () +receiveFile fd outPath tmpPath = + runExceptT (CLI.cliReceiveFile opts) `shouldReturn` Right () + where + opts = + CLI.ReceiveOptions + { fileDescription = fd, + filePath = Just outPath, + retryCount = 3, + tempPath = Just tmpPath, + verbose = False, + yes = True + } + +fdCopy :: HasTestEnv => Int -> FilePath +fdCopy i = testPath $ "rcv" <> show i <> ".xftp" + +atOnce :: (Int -> IO ()) -> IO () +atOnce action = do + started <- newBarrier transfers + forConcurrently_ [1 .. transfers] $ \i -> started >> action i + +newBarrier :: Int -> IO (IO ()) +newBarrier n = do + arrived <- newTVarIO 0 + let waitAll = unlessM ((== n) <$> readTVarIO arrived) $ yield >> waitAll + pure $ atomically (modifyTVar' arrived (+ 1)) >> waitAll diff --git a/tests/XFTPClient.hs b/tests/XFTPClient.hs index 233b0af4f..f7a4a65ae 100644 --- a/tests/XFTPClient.hs +++ b/tests/XFTPClient.hs @@ -9,21 +9,27 @@ module XFTPClient where import Control.Concurrent (ThreadId, threadDelay) +import Control.Exception (bracket) +import Control.Monad (forM_) import Data.String (fromString) import Data.Time.Clock (getCurrentTime) import Network.Socket (ServiceName) import SMPClient (serverBracket) import Simplex.FileTransfer.Client import Simplex.FileTransfer.Description +import Simplex.FileTransfer.Protocol (FileInfo) import Simplex.FileTransfer.Server (runXFTPServerBlocking) import Simplex.FileTransfer.Server.Env (XFTPServerConfig (..), XFTPStoreConfig (..), AFStoreType (..), defaultFileExpiration, defaultInactiveClientExpiration) -import Simplex.FileTransfer.Server.Store (FileStoreClass, SFSType (..), STMFileStore) +import Simplex.FileTransfer.Server.Store (FileStoreClass, RoundedFileTime, SFSType (..), STMFileStore) +import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, logAddFile) import Simplex.FileTransfer.Transport (alpnSupportedXFTPhandshakes, supportedFileServerVRange) import Simplex.FileTransfer.Types (SndFileId) import qualified Simplex.Messaging.Agent as A import Simplex.Messaging.Agent.Protocol (UserId) import Simplex.Messaging.Crypto.File (CryptoFile) -import Simplex.Messaging.Protocol (XFTPServer) +import Simplex.Messaging.Protocol (SenderId, XFTPServer) +import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) +import Simplex.Messaging.Server.StoreLog (openWriteStoreLog) import Simplex.Messaging.Transport (defaultSupportedParams) import Simplex.Messaging.Transport.HTTP2 (defaultHTTP2BufferSize, httpALPN) import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) @@ -37,6 +43,8 @@ import Control.Monad (void) import qualified Database.PostgreSQL.Simple as PSQL import Database.PostgreSQL.Simple (ConnectInfo (..), defaultConnectInfo) import Database.PostgreSQL.Simple.Types (Query (..)) +import Simplex.FileTransfer.Server.Store (FileStoreClass (addFile, closeFileStore, newFileStore)) +import Simplex.FileTransfer.Server.Store.Postgres (PostgresFileStore) import Simplex.FileTransfer.Server.Store.Postgres.Config (PostgresFileStoreCfg (..), defaultXFTPDBOpts) import Simplex.Messaging.Agent.Store.Postgres.Options (DBOpts (..)) import Simplex.Messaging.Agent.Store.Shared (MigrationConfirmation (..)) @@ -68,6 +76,24 @@ cfgFS2 (AFSType fs) = case fs of SFSPostgres -> error "no postgres support" #endif +cfgFSTestFiles :: HasTestEnv => AFStoreType -> AXFTPServerConfig +cfgFSTestFiles fsType@(AFSType fs) = case fs of + SFSMemory -> AXFTPSrvCfg testXFTPServerConfig {serverStoreCfg = XSCMemory (Just testXFTPLogFile), storeLogFile = Just testXFTPLogFile} + SFSPostgres -> cfgFS fsType + +addTestFiles :: HasTestEnv => AFStoreType -> [SenderId] -> FileInfo -> RoundedFileTime -> Maybe RoundedFileTime -> IO () +addTestFiles (AFSType fs) sIds file createdAt expiresAt = case fs of + SFSMemory -> + bracket (openWriteStoreLog False testXFTPLogFile) closeStoreLog $ \sl -> + forM_ sIds $ \sId -> logAddFile sl sId file createdAt expiresAt EntityActive +#if defined(dbServerPostgres) + SFSPostgres -> + bracket (newFileStore testXFTPPostgresCfg) closeFileStore $ \(st :: PostgresFileStore) -> + forM_ sIds $ \sId -> addFile st sId file createdAt expiresAt EntityActive >>= either (error . show) pure +#else + SFSPostgres -> error "no postgres support" +#endif + withXFTPServerConfigOn :: HasCallStack => AXFTPServerConfig -> (HasCallStack => ThreadId -> IO a) -> IO a withXFTPServerConfigOn (AXFTPSrvCfg cfg) = withXFTPServerCfg cfg @@ -140,9 +166,9 @@ withStallingXFTPServer action = do requested <- newEmptyTMVarIO closed <- newEmptyTMVarIO creds <- loadServerCredential xftpCredentials - let stall _ _ _ _ _ = atomically (putTMVar requested ()) >> threadDelay maxBound + let stall _ _ _ _ _ _ = atomically (putTMVar requested ()) >> threadDelay maxBound serverBracket - (\started -> runHTTP2Server started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> atomically $ putTMVar closed ()) stall) + (\started -> newSocketState >>= \ss -> runHTTP2Server ss started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> atomically $ putTMVar closed ()) stall) (pure ()) (const $ action requested closed) where diff --git a/tests/XFTPServerTests.hs b/tests/XFTPServerTests.hs index 4b85aec20..b131e9004 100644 --- a/tests/XFTPServerTests.hs +++ b/tests/XFTPServerTests.hs @@ -1,5 +1,6 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} @@ -11,12 +12,13 @@ module XFTPServerTests (xftpServerTests) where import AgentTests.FunctionalAPITests (runRight, runRight_) import Control.Concurrent (threadDelay) -import Control.Exception (SomeException, bracket) +import Control.Exception (IOException, SomeException, bracket, catch) import Control.Monad import Control.Monad.Except import Control.Monad.IO.Unlift import qualified Crypto.PubKey.RSA as RSA import Data.Bifunctor (first) +import qualified Data.ByteArray as BA import qualified Data.ByteString.Base64.URL as B64 import Data.ByteString.Builder (byteString) import Data.ByteString.Char8 (ByteString) @@ -24,39 +26,52 @@ import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import qualified Data.CaseInsensitive as CI import Data.Either (isLeft) -import Data.List (find, isInfixOf) +import Data.List (find, isInfixOf, isPrefixOf) import Data.List.NonEmpty (NonEmpty) -import Data.Time.Clock (getCurrentTime) +import Data.Maybe (listToMaybe) +import qualified Data.Text as T +import qualified Data.Text.IO as T +import Data.Time.Clock (UTCTime (..), getCurrentTime) import qualified Data.X509 as X import Data.X509.Validation (Fingerprint (..), getFingerprint) import Network.HPACK.Token (tokenKey) +import Network.HTTP.Types (ok200) import qualified Network.HTTP2.Client as H2 +import Network.HTTP2.Server (responseNoBody) import qualified Network.TLS as T -import SMPClient (copyWebCredential, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn, withStallingServerOn') +import SMPClient (copyWebCredential, serverBracket, testCredentialCheckInterval, testWebCredentialReload, testWebCredentialReplaced, testWebCredentials, withStallingServerOn, withStallingServerOn') import ServerTests (logSize) import Simplex.FileTransfer.Client hiding (createXFTPChunk) import qualified Simplex.FileTransfer.Client as A -import Simplex.FileTransfer.Description (kb) -import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpEncodeAuthTransmission) -import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..)) -import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), receiveFile, pattern VersionXFTP) +import Simplex.FileTransfer.Description (kb, mb) +import Simplex.FileTransfer.Protocol (FileCmd (..), FileCommand (..), FileInfo (..), FileResponse (..), SFileParty (..), XFTPFileId, xftpBlockSize, xftpDecodeTClient, xftpEncodeAuthTransmission) +import Simplex.FileTransfer.Server.Env (AFStoreType, XFTPServerConfig (..), XFTPStoreConfig (..), defaultInactiveClientExpiration) +import Simplex.FileTransfer.Server.StoreLog (closeStoreLog, logAddFile, logPutFile, serverFileName) +import Simplex.FileTransfer.Transport (XFTPClientHandshake (..), XFTPClientHello (..), XFTPErrorType (..), XFTPRcvChunkSpec (..), XFTPServerHandshake (..), alpnSupportedXFTPhandshakes, receiveEncFile, receiveFile, pattern VersionXFTP) import Simplex.Messaging.Client (NetworkConfig (..), NetworkTimeout (..), ProtocolClientError (..), defaultNetworkConfig) import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding (smpDecode, smpEncode) import Simplex.Messaging.Protocol (BasicAuth, EntityId (..), RecipientId, SenderId, pattern NoEntity) import Simplex.Messaging.Server.Expiration (ExpirationConfig (..)) -import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), TransportPeer (..), closeTLS, defaultSupportedParams, defaultSupportedParamsHTTPS) +import Simplex.Messaging.Server.QueueStore (ServerEntityStatus (..)) +import Simplex.Messaging.Server.StoreLog (openWriteStoreLog) +import Simplex.Messaging.SystemTime (RoundedSystemTime (..), getSystemSeconds) +import Simplex.Messaging.Transport (CertChainPubKey (..), TLS (..), Transport (cGet), TransportPeer (..), closeTLS, defaultSupportedParams, defaultSupportedParamsHTTPS) import Simplex.Messaging.Transport.Client (TransportClientConfig (..), TransportHost (..), defaultTransportClientConfig, runTLSTransportClient) -import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..)) +import Simplex.Messaging.Transport.HTTP2 (HTTP2Body (..), defaultHTTP2BufferSize) +import Simplex.Messaging.Transport.HTTP2.File (fileBlockSize) import qualified Simplex.Messaging.Transport.HTTP2.Client as HC -import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential) +import Simplex.Messaging.Transport.HTTP2.Server (runHTTP2Server) +import Simplex.Messaging.Transport.Server (TransportServerConfig (..), loadFileFingerprint, loadServerCredential, newSocketState) import Simplex.Messaging.Transport.Shared (ChainCertificates (..), chainIdCaCerts) +import Simplex.Messaging.Util (bshow, unlessM, whenM) import Simplex.Messaging.Version (mkVersionRange) -import System.Directory (listDirectory, removeFile) -import System.FilePath (()) +import System.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getSymbolicLinkTarget, listDirectory, removeFile) +import System.FilePath (takeExtension, ()) import Test.Hspec hiding (fit, it) -import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_) +import UnliftIO.Async (async, cancel, pooledReplicateConcurrentlyN, race_, wait, withAsync) +import UnliftIO.Exception (tryAny) import UnliftIO.STM import UnliftIO.Timeout (timeout) import Util @@ -72,14 +87,25 @@ xftpServerTests = do it "should delete file chunk (2 clients)" testFileChunkDelete2 it "should not allow chunks of wrong size" testWrongChunkSize it "should expire chunks after set interval" testFileChunkExpiration + it "should expire chunks that were never uploaded without delays" testExpireNotUploadedFiles it "should disconnect inactive clients" testInactiveClientExpiration + it "should not disconnect clients during downloads longer than inactivity ttl" testLongDownloadExpiration it "should close connection when connecting client is cancelled" $ \_ -> testCancelledClientConnect it "should time out TLS handshake when TLS errors are logged" $ \_ -> testTLSHandshakeTimeout it "should time out closing TLS connection" $ \_ -> testCloseTLSTimeout it "should time out receiving file chunk" $ \_ -> testReceiveFileTimeout it "should not allow uploading chunks after specified storage quota" testFileStorageQuota it "should release storage of interrupted uploads" testInterruptedUploadStorage + it "should complete a new upload of a chunk without waiting for the paused upload it replaces" testConcurrentChunkUpload + it "should cancel a stalled upload and release its storage when its chunk is uploaded again" testCancelStalledChunkUpload + it "should remove a chunk uploaded while its file expires" testUploadDuringExpiration it "should store file records to log and restore them after server restart" testFileLog + it "should reset daily download stats without stats log" testPeriodStatsReset + it "should export socket counts in Prometheus metrics" testSocketMetrics + it "should count stored files after restart without stats backup" $ testFileStatsRestart False + it "should count stored files after restart with stats backup" $ testFileStatsRestart True + it "should count stored files after deletion" testFileStatsDelete + it "should remove files without stored chunks when the server starts" testRemoveUnstoredFiles describe "XFTP basic auth" $ do -- allow FNEW | server auth | clnt auth | success it "prohibited without basic auth" $ testFileBasicAuth True (Just "pwd") Nothing False @@ -88,9 +114,23 @@ xftpServerTests = do it "allowed with correct basic auth" $ testFileBasicAuth True (Just "pwd") (Just "pwd") True it "allowed with auth on server without auth" $ testFileBasicAuth True Nothing (Just "any") True it "should not change content for uploaded and committed files" testFileSkipCommitted + it "should close connection and file when download stalls" testStalledDownload + it "should close connection when the end of a download stalls" testStalledDownloadEnd + it "should close connection when request body stalls" testStalledRequestBody + it "should time out a stalled upload of a committed chunk" $ testStalledUpload True + it "should time out a stalled upload of a new chunk" $ testStalledUpload False + it "should accept a repeated upload of a chunk while its first upload is stalled" testRepeatedUploadDuringStalledUpload + it "should return OK to an upload completed after another upload of the chunk" testUploadAfterCommittedUpload + it "should remove unfinished uploads at start" testRemoveTmpUploads + it "should close connections without requests" testNoRequestTimeout it "should close connection when handshake times out" testHandshakeTimeout it "should close connection when cancelled during handshake" testCancelledHandshake + it "should not send request after it times out" testRequestNotSentAfterTimeout + it "should time out request while request queue is full" testRequestTimeoutInFullQueue it "should decode handshake of servers before v6.5.0 and refuse an invalid signature" testOldServerHandshake + describe "XFTP chunk receiving" $ beforeWith (const (pure ())) $ do + it "should verify digest of received chunk without reading the file back" testReceiveChunkDigest + it "should verify digest of received encrypted chunk without reading the file back" testReceiveEncChunkDigest describe "XFTP SNI and CORS" $ beforeWith (const (pure ())) $ do it "should select web certificate when SNI is used" testSNICertSelection it "should select XFTP certificate when SNI is not used" testNoSNICertSelection @@ -120,7 +160,7 @@ createXFTPChunk :: XFTPClient -> C.APrivateAuthKey -> FileInfo -> NonEmpty C.APu createXFTPChunk c spKey file rcps auth = (\(sId, rIds, _) -> (sId, rIds)) <$> A.createXFTPChunk c spKey file rcps auth Nothing readChunk :: HasTestEnv => XFTPFileId -> IO ByteString -readChunk sId = B.readFile (xftpServerFiles B.unpack (B64.encode $ unEntityId sId)) +readChunk sId = B.readFile (xftpServerFiles serverFileName sId) testFileChunkDelivery :: HasTestEnv => AFStoreType -> Expectation testFileChunkDelivery = xftpTest $ \c -> runRight_ $ runTestFileChunkDelivery c c @@ -234,11 +274,29 @@ testFileChunkExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fs where fileExpiration = ExpirationConfig {ttl = 1, checkInterval = 1} +testExpireNotUploadedFiles :: HasTestEnv => AFStoreType -> Expectation +testExpireNotUploadedFiles _ = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + now <- getSystemSeconds + let sIds = map (\i -> EntityId $ "never_uploaded" <> B.pack (show i)) [10 .. 59 :: Int] + fileInfo = FileInfo {sndKey, size = chSize, digest = "digest"} + createdAt = RoundedSystemTime $ roundedSeconds now + expiresAt = RoundedSystemTime $ roundedSeconds now + 2 + sl <- openWriteStoreLog False testXFTPLogFile + forM_ sIds $ \sId -> logAddFile sl sId fileInfo createdAt (Just expiresAt) EntityActive + closeStoreLog sl + withXFTPServerCfg testXFTPServerConfig {serverStoreCfg = XSCMemory (Just testXFTPLogFile), storeLogFile = Just testXFTPLogFile, fileExpiration} $ \_ -> do + threadDelay 6000000 + testXFTPClient $ \c -> forM_ sIds $ \sId -> + runExceptT (addXFTPRecipients c spKey sId [rcvKey]) `shouldReturn` Left (PCEProtocolError AUTH) + where + fileExpiration = ExpirationConfig {ttl = 86400, checkInterval = 1} + testInactiveClientExpiration :: HasTestEnv => AFStoreType -> Expectation testInactiveClientExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {inactiveClientExpiration}) $ \_ -> runRight_ $ do - disconnected <- newEmptyTMVarIO - ts <- liftIO getCurrentTime - c <- ExceptT $ getXFTPClient (1, testXFTPServer, Nothing) testXFTPClientConfig [] ts (\_ -> pure Nothing) (\_ -> atomically $ putTMVar disconnected ()) + (c, disconnected) <- liftIO connectXFTPClient pingXFTP c liftIO $ do threadDelay 100000 @@ -250,6 +308,30 @@ testInactiveClientExpiration fsType = withXFTPServerConfigOn (updateXFTPCfg (cfg where inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} +testLongDownloadExpiration :: HasTestEnv => AFStoreType -> Expectation +testLongDownloadExpiration fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {inactiveClientExpiration}) $ \_ -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyPart}} <- sendFGET c rpKey rId + getPart <- maybe (error "no response body") pure bodyPart + slowBytes <- readBody getPart (mb 2) 25000 + restBytes <- timeout 15000000 (readBody getPart maxBound 0) >>= maybe (error "body not read within 15 seconds") pure + slowBytes + restBytes `shouldBe` mb 4 + C.authTagSize + runRight_ $ pingXFTP c + expectDisconnected disconnected + where + inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} + +readBody :: (Int -> IO ByteString) -> Int -> Int -> IO Int +readBody getPart limit delay = go 0 + where + go n + | n >= limit = pure n + | otherwise = do + threadDelay delay + len <- B.length <$> getPart fileBlockSize + if len == 0 then pure n else go (n + len) + testCancelledClientConnect :: HasTestEnv => Expectation testCancelledClientConnect = withStallingServerOn' xftpTestPort $ \accepted closed -> replicateM_ 1000 $ do @@ -340,6 +422,110 @@ testInterruptedUploadStorage fsType = withXFTPServerConfigOn (updateXFTPCfg (cfg listDirectory xftpServerFiles `shouldReturn` [] testXFTPClient $ \c -> runRight_ $ forM_ (take 10 sIds) $ \sId -> uploadXFTPChunk c spKey sId chunkSpec +testConcurrentChunkUpload :: HasTestEnv => AFStoreType -> Expectation +testConcurrentChunkUpload = xftpTest2 $ \c@XFTPClient {http2Client, thParams} c' -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey file [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + resume <- newEmptyTMVarIO + let (part1, part2) = B.splitAt (chSize `div` 2) bytes + req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send $ byteString t + send $ byteString part1 + flush + atomically $ takeTMVar resume + send $ byteString part2 + flush + waitServerFile = unlessM (any (serverFileName sId `isPrefixOf`) <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitServerFile + upload1 <- async $ HC.sendRequest http2Client req Nothing + timeout 5000000 waitServerFile `shouldReturn` Just () + timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) + atomically $ putTMVar resume () + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} <- either (error . show) pure =<< wait upload1 + case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr TIMEOUT)) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + listDirectory xftpServerFiles `shouldReturn` [serverFileName sId] + runRight_ $ downloadXFTPChunk g c' rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest + B.readFile (testPath "received_chunk1") `shouldReturn` bytes + +testCancelStalledChunkUpload :: HasTestEnv => AFStoreType -> Expectation +testCancelStalledChunkUpload fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileSizeQuota = Just chSize}) $ + \_ -> testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> testXFTPClient $ \c' -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, _) <- runRight $ createXFTPChunk c spKey file [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send $ byteString t + send $ byteString $ B.replicate 1024 'x' + flush + threadDelay maxBound + waitServerFile = unlessM (any (serverFileName sId `isPrefixOf`) <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitServerFile + upload1 <- async $ HC.sendRequest http2Client req Nothing + timeout 5000000 waitServerFile `shouldReturn` Just () + timeout 5000000 (runExceptT $ uploadXFTPChunk c' spKey sId chunkSpec) `shouldReturn` Just (Right ()) + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} <- either (error . show) pure =<< wait upload1 + case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr TIMEOUT)) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + +testUploadDuringExpiration :: HasTestEnv => AFStoreType -> Expectation +testUploadDuringExpiration fsType = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + RoundedSystemTime now <- getSystemSeconds + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + fileId i = EntityId $ "expiring_file_" <> bshow (i :: Int) + sId = fileId 0 + uploadedIds = map fileId [1 .. 20] + uploadedFiles = map ((xftpServerFiles ) . serverFileName) uploadedIds + waitExpiration = whenM (and <$> mapM doesFileExist uploadedFiles) $ threadDelay 10000 >> waitExpiration + waitRemoved = unlessM (null <$> listDirectory xftpServerFiles) $ threadDelay 10000 >> waitRemoved + addTestFiles fsType (sId : uploadedIds) file (RoundedSystemTime now) (Just $ RoundedSystemTime $ now + 5) + withXFTPServerConfigOn (updateXFTPCfg (cfgFSTestFiles fsType) $ \c -> c {fileExpiration}) $ \_ -> do + testXFTPClient $ \c -> do + runRight_ $ forM_ uploadedIds $ \fId -> uploadXFTPChunk c spKey fId chunkSpec + runRight_ $ uploadXFTPChunk c spKey sId chunkSpec + timeout 20000000 waitExpiration `shouldReturn` Just () + timeout 10000000 waitRemoved `shouldReturn` Just () + where + fileExpiration = ExpirationConfig {ttl = 3600, checkInterval = 1} + +testRemoveUnstoredFiles :: HasTestEnv => AFStoreType -> Expectation +testRemoveUnstoredFiles fsType = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, rId, partialId) <- withXFTPServerConfigOn (cfgFSTestFiles fsType) $ \_ -> testXFTPClient $ \c -> runRight $ do + (sId, [rId]) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId chunkSpec + (partialId, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + pure (sId, rId, partialId) + forM_ ([partialId, EntityId "orphan_file_0000"] :: [SenderId]) $ \fId -> B.writeFile (xftpServerFiles serverFileName fId) "partial" + withXFTPServerConfigOn (cfgFSTestFiles fsType) $ \_ -> do + listDirectory xftpServerFiles `shouldReturn` [serverFileName sId] + testXFTPClient $ \c -> runRight_ $ downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest + B.readFile (testPath "received_chunk1") `shouldReturn` bytes + testFileLog :: HasTestEnv => AFStoreType -> Expectation testFileLog _ = do g <- C.newRandom @@ -412,6 +598,112 @@ testFileLog _ = do downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk1") chSize digest liftIO $ B.readFile (testPath "received_chunk1") `shouldReturn` bytes +testPeriodStatsReset :: HasTestEnv => AFStoreType -> Expectation +testPeriodStatsReset fsType = do + ts <- getCurrentTime + let resetTime = floor (utctDayTime ts) + 10 + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {logStatsInterval = Nothing, logStatsStartTime = resetTime, prometheusInterval = Just 1}) $ \_ -> do + testXFTPClient $ \c -> runRight_ $ runTestFileChunkDelivery c c + threadDelay 1500000 + dailyDownloads `shouldReturn` Just "1" + threadDelay 10000000 + dailyDownloads `shouldReturn` Just "0" + where + dailyDownloads = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure $ listToMaybe [n | l <- metrics, ["simplex_xftp_files_count_daily", n, _] <- [T.words l]] + +testSocketMetrics :: HasTestEnv => AFStoreType -> Expectation +testSocketMetrics fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {prometheusInterval = Just 1}) $ \_ -> do + testXFTPClient $ \c -> do + runRight_ $ pingXFTP c + threadDelay 1500000 + socketMetrics `shouldReturn` [("accepted", "1"), ("closed", "0"), ("active", "1"), ("leaked", "0")] + closeXFTPClient c + threadDelay 2500000 + socketMetrics `shouldReturn` [("accepted", "1"), ("closed", "1"), ("active", "0"), ("leaked", "0")] + where + socketMetrics = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure + [ (name, n) + | l <- metrics, + [metric, n, _] <- [T.words l], + Just name <- [T.stripPrefix "simplex_xftp_sockets_" =<< T.stripSuffix portLabel metric] + ] + portLabel = "{port=\"" <> T.pack xftpTestPort <> "\"}" + +testFileStatsRestart :: HasTestEnv => Bool -> AFStoreType -> Expectation +testFileStatsRestart statsBackup _ = do + when statsBackup $ do + withXFTPServerCfg cfg $ \_ -> pure () + doesFileExist testXFTPStatsBackupFile `shouldReturn` True + g <- C.newRandom + (sndKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + createDirectoryIfMissing True xftpServerFiles + sl <- openWriteStoreLog False testXFTPLogFile + let fileInfo = FileInfo {sndKey, size = chSize, digest = "digest"} + addTestFile sId expiresAt = logAddFile sl sId fileInfo (RoundedSystemTime 0) (Just $ RoundedSystemTime expiresAt) EntityActive + putTestFile sId = do + let path = xftpServerFiles serverFileName sId + void $ createTestChunk path + logPutFile sl sId path + expiredId = EntityId "expired_file____" + storedId = EntityId "stored_file_____" + addTestFile expiredId 3600 + putTestFile expiredId + addTestFile storedId 4102444800 + putTestFile storedId + addTestFile (EntityId "new_file________") 4102444800 + closeStoreLog sl + withXFTPServerCfg cfg $ \_ -> threadDelay 2500000 + fileMetrics `shouldReturn` [("expired", "1"), ("deleted", "0"), ("count_total", "1"), ("size", "131072")] + where + cfg = + testXFTPServerConfig + { serverStoreCfg = XSCMemory (Just testXFTPLogFile), + storeLogFile = Just testXFTPLogFile, + serverStatsBackupFile = if statsBackup then Just testXFTPStatsBackupFile else Nothing, + prometheusInterval = Just 1 + } + +testFileStatsDelete :: HasTestEnv => AFStoreType -> Expectation +testFileStatsDelete fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {prometheusInterval = Just 1}) $ \_ -> + testXFTPClient $ \c -> runRight_ $ do + g <- liftIO C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ liftIO $ createTestChunk testChunkPath + digest <- liftIO $ LC.sha256Hash <$> LB.readFile testChunkPath + let file = FileInfo {sndKey, size = chSize, digest} + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId1, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId1 chunkSpec + (sId2, _) <- createXFTPChunk c spKey file [rcvKey] Nothing + uploadXFTPChunk c spKey sId2 chunkSpec + liftIO $ do + threadDelay 1500000 + fileMetrics `shouldReturn` [("expired", "0"), ("deleted", "0"), ("count_total", "2"), ("size", "262144")] + removeFile $ xftpServerFiles serverFileName sId2 + deleteXFTPChunk c spKey sId1 + deleteXFTPChunk c spKey sId2 + liftIO $ do + threadDelay 1500000 + fileMetrics `shouldReturn` [("expired", "0"), ("deleted", "2"), ("count_total", "0"), ("size", "0")] + +fileMetrics :: HasTestEnv => IO [(T.Text, T.Text)] +fileMetrics = do + metrics <- T.lines <$> T.readFile xftpTestPrometheusMetricsFile + pure + [ (name, n) + | l <- metrics, + [metric, n, _] <- [T.words l], + Just name <- [T.stripPrefix "simplex_xftp_files_" metric], + name `elem` (["expired", "deleted", "count_total", "size"] :: [T.Text]) + ] + testFileBasicAuth :: HasTestEnv => Bool -> Maybe BasicAuth -> Maybe BasicAuth -> Bool -> AFStoreType -> IO () testFileBasicAuth allowNewFiles newFileBasicAuth clntAuth success fsType = withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {allowNewFiles, newFileBasicAuth}) $ @@ -453,6 +745,178 @@ testFileSkipCommitted fsType = downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest liftIO $ B.readFile (testPath "received_chunk") `shouldReturn` bytes -- new chunk content got ignored +testStalledDownload :: HasTestEnv => AFStoreType -> Expectation +testStalledDownload fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration = Nothing}) $ \_ -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + void $ sendFGET c rpKey rId + expectDisconnected disconnected + filesClosed (20 :: Int) `shouldReturn` True + where + filesClosed n = do + closed <- all (maybe True (== 0)) <$> (mapM (openDescriptors . (xftpServerFiles )) =<< listDirectory xftpServerFiles) + if closed || n <= 0 then pure closed else threadDelay 100000 >> filesClosed (n - 1) + +testStalledDownloadEnd :: HasTestEnv => AFStoreType -> Expectation +testStalledDownloadEnd fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration}) $ \_ -> + forM_ [mb 1 + kb k | k <- [0, 64 .. 320]] $ \unread -> do + (c, disconnected, rId, rpKey) <- uploadLargeChunk + HC.HTTP2Response {HC.respBody = HTTP2Body {bodyPart}} <- sendFGET c rpKey rId + getPart <- maybe (error "no response body") pure bodyPart + void $ readBody getPart (mb 4 + C.authTagSize - unread) 0 + expectDisconnected disconnected + where + inactiveClientExpiration = Just ExpirationConfig {ttl = 1, checkInterval = 1} + +testStalledRequestBody :: HasTestEnv => AFStoreType -> Expectation +testStalledRequestBody fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000, inactiveClientExpiration = Nothing}) $ \_ -> do + (XFTPClient {http2Client}, disconnected) <- connectXFTPClient + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send "x" >> flush >> threadDelay maxBound + withAsync (HC.sendRequest http2Client req Nothing) $ \_ -> expectDisconnected disconnected + +testStalledUpload :: HasTestEnv => Bool -> AFStoreType -> Expectation +testStalledUpload committed fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000}) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, _) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + void $ createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + sId <- runRight $ do + (sId, _) <- createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + when committed $ uploadXFTPChunk c spKey sId chunkSpec + pure sId + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send (byteString t) >> flush >> threadDelay maxBound + timeout 5000000 (HC.sendRequest http2Client req Nothing) >>= \case + Just (Right HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}}) -> case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right (FRErr e)) -> e `shouldBe` TIMEOUT + r -> expectationFailure $ "unexpected response: " <> show r + Just (Left e) -> expectationFailure $ "request error: " <> show e + Nothing -> expectationFailure "no response within 5 seconds" + +testRepeatedUploadDuringStalledUpload :: HasTestEnv => AFStoreType -> Expectation +testRepeatedUploadDuringStalledUpload fsType = + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c -> c {fileTimeout = 2000000}) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> send (byteString t) >> flush >> threadDelay maxBound + download c' = do + runRight_ $ downloadXFTPChunk g c' rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest + B.readFile (testPath "received_chunk") `shouldReturn` bytes + withAsync (HC.sendRequest http2Client req Nothing) $ \_ -> do + threadDelay 500000 + testXFTPClient $ \c' -> do + runRight_ $ uploadXFTPChunk c' spKey sId chunkSpec + download c' + threadDelay 2500000 + download c' + filter ((".tmp" ==) . takeExtension) <$> listDirectory xftpServerFiles `shouldReturn` [] + +testUploadAfterCommittedUpload :: HasTestEnv => AFStoreType -> Expectation +testUploadAfterCommittedUpload fsType = + withXFTPServerConfigOn (cfgFS fsType) $ \_ -> + testXFTPClient $ \c@XFTPClient {http2Client, thParams} -> do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + bytes <- createTestChunk testChunkPath + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + let chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = chSize} + (sId, [rId]) <- runRight $ createXFTPChunk c spKey FileInfo {sndKey, size = chSize, digest} [rcvKey] Nothing + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams spKey ("", sId, FileCmd SFSender FPUT) + bodyAllowed <- newEmptyTMVarIO + let req = H2.requestStreaming "POST" "/" [] $ \send flush -> do + send (byteString t) >> flush + atomically $ takeTMVar bodyAllowed + send (byteString bytes) >> flush + withAsync (HC.sendRequest http2Client req Nothing) $ \firstUpload -> do + threadDelay 500000 + testXFTPClient $ \c' -> runRight_ $ uploadXFTPChunk c' spKey sId chunkSpec + atomically $ putTMVar bodyAllowed () + wait firstUpload >>= \case + Right HC.HTTP2Response {HC.respBody = HTTP2Body {bodyHead}} -> case xftpDecodeTClient thParams bodyHead of + Right (_, _, Right FROk) -> pure () + r -> expectationFailure $ "unexpected response: " <> show r + Left e -> expectationFailure $ "request error: " <> show e + runRight_ $ downloadXFTPChunk g c rpKey rId $ XFTPRcvChunkSpec (testPath "received_chunk") chSize digest + B.readFile (testPath "received_chunk") `shouldReturn` bytes + +testRemoveTmpUploads :: HasTestEnv => AFStoreType -> Expectation +testRemoveTmpUploads _ = do + createDirectoryIfMissing True xftpServerFiles + writeFile (xftpServerFiles "chunk") "chunk" + writeFile (xftpServerFiles "chunk.upload.tmp") "partial upload" + withXFTPServerThreadOn $ \_ -> listDirectory xftpServerFiles `shouldReturn` ["chunk"] + +testNoRequestTimeout :: HasTestEnv => AFStoreType -> Expectation +testNoRequestTimeout fsType = + forM_ ([Nothing, Just defaultInactiveClientExpiration] :: [Maybe ExpirationConfig]) $ \inactiveClientExpiration -> + withXFTPServerConfigOn (updateXFTPCfg (cfgFS fsType) $ \c@XFTPServerConfig {transportConfig = tc} -> c {inactiveClientExpiration, transportConfig = tc {firstRequestTimeout = 1000000}}) $ \_ -> do + Fingerprint fp <- loadFileFingerprint "tests/fixtures/ca.crt" + let cfg = defaultTransportClientConfig {clientALPN = Just alpnSupportedXFTPhandshakes} :: TransportClientConfig + runTLSTransportClient defaultSupportedParams Nothing cfg Nothing "localhost" xftpTestPort (Just $ C.KeyHash fp) $ \(tls :: TLS 'TClient) -> + timeout 5000000 (tryAny $ cGet tls 1) >>= (`shouldSatisfy` maybe False (either (const True) B.null)) + (c, disconnected) <- connectXFTPClient + threadDelay 2000000 + atomically (tryReadTMVar disconnected) `shouldReturn` Nothing + runRight_ $ pingXFTP c + +connectXFTPClient :: HasTestEnv => IO (XFTPClient, TMVar ()) +connectXFTPClient = do + disconnected <- newEmptyTMVarIO + ts <- getCurrentTime + c <- either (error . show) pure =<< getXFTPClient (1, testXFTPServer, Nothing) testXFTPClientConfig [] ts (\_ -> pure Nothing) (\_ -> atomically $ putTMVar disconnected ()) + pure (c, disconnected) + +uploadLargeChunk :: HasTestEnv => IO (XFTPClient, TMVar (), RecipientId, C.APrivateAuthKey) +uploadLargeChunk = do + g <- C.newRandom + (sndKey, spKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + (rcvKey, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g + let size = mb 4 + chunkSpec = XFTPChunkSpec {filePath = testChunkPath, chunkOffset = 0, chunkSize = size} + B.writeFile testChunkPath =<< atomically (C.randomBytes (fromIntegral size) g) + digest <- LC.sha256Hash <$> LB.readFile testChunkPath + (c, disconnected) <- connectXFTPClient + rId <- runRight $ do + (sId, [rId]) <- createXFTPChunk c spKey FileInfo {sndKey, size, digest} [rcvKey] Nothing + uploadXFTPChunk c spKey sId chunkSpec + pure rId + pure (c, disconnected, rId, rpKey) + +expectDisconnected :: TMVar () -> Expectation +expectDisconnected disconnected = timeout 5000000 (atomically $ takeTMVar disconnected) `shouldReturn` Just () + +sendFGET :: XFTPClient -> C.APrivateAuthKey -> RecipientId -> IO HC.HTTP2Response +sendFGET XFTPClient {http2Client, thParams} rpKey rId = do + (rDhKey, _) <- atomically . C.generateKeyPair =<< C.newRandom + t <- either (error . show) pure $ xftpEncodeAuthTransmission thParams rpKey ("", rId, FileCmd SFRecipient $ FGET rDhKey) + either (error . show) pure =<< HC.sendRequest http2Client (H2.requestBuilder "POST" "/" [] $ byteString t) Nothing + +openDescriptors :: FilePath -> IO (Maybe Int) +openDescriptors path = + doesDirectoryExist fdDir >>= \case + False -> pure Nothing + True -> do + target <- canonicalizePath path + fds <- listDirectory fdDir + Just . length . filter (== target) <$> mapM linkTarget fds + where + fdDir = "/proc/self/fd" + linkTarget fd = getSymbolicLinkTarget (fdDir fd) `catch` \(_ :: IOException) -> pure "" + testHandshakeTimeout :: HasTestEnv => AFStoreType -> Expectation testHandshakeTimeout _ = withStallingXFTPServer $ \_ closed -> do @@ -471,6 +935,46 @@ testCancelledHandshake _ = cancel a timeout 1000000 (atomically $ takeTMVar closed) `shouldReturn` Just () +testRequestNotSentAfterTimeout :: HasTestEnv => AFStoreType -> Expectation +testRequestNotSentAfterTimeout _ = + withHeldHTTP2Requests $ \send received release -> + withAsync (send $ Just 5000000) $ \held -> do + atomically $ readTVar received >>= checkSTM . (1 ==) + Left HC.HCResponseTimeout <- send Nothing + atomically $ putTMVar release () + Right _ <- wait held + threadDelay 500000 + readTVarIO received `shouldReturn` 1 + +testRequestTimeoutInFullQueue :: HasTestEnv => AFStoreType -> Expectation +testRequestTimeoutInFullQueue _ = + withHeldHTTP2Requests $ \send received _ -> + withAsync (send $ Just 5000000) $ \_ -> do + atomically $ readTVar received >>= checkSTM . (1 ==) + Left HC.HCResponseTimeout <- send Nothing + Just (Left HC.HCResponseTimeout) <- timeout 5000000 $ send Nothing + pure () + +withHeldHTTP2Requests :: HasTestEnv => ((Maybe Int -> IO (Either HC.HTTP2ClientError HC.HTTP2Response)) -> TVar Int -> TMVar () -> IO a) -> IO a +withHeldHTTP2Requests action = do + received <- newTVarIO 0 + release <- newEmptyTMVarIO + creds <- loadServerCredential xftpCredentials + Fingerprint fp <- loadFileFingerprint "tests/fixtures/ca.crt" + let hold _ _ _ _ _ respond = do + atomically $ modifyTVar' received (+ 1) + atomically $ readTMVar release + respond $ responseNoBody ok200 [] + cfg = HC.defaultHTTP2ClientConfig {HC.qSize = 1, HC.connTimeout = 1000000, HC.suportedTLSParams = defaultSupportedParams} + connect = either (error . show) pure =<< HC.getVerifiedHTTP2Client Nothing (THDomainName "localhost") xftpTestPort (Just $ C.KeyHash fp) Nothing cfg (pure ()) + serverBracket + (\started -> newSocketState >>= \ss -> runHTTP2Server ss started xftpTestPort defaultHTTP2BufferSize defaultSupportedParams creds Nothing transportConfig Nothing (\_ -> pure ()) hold) + (pure ()) + $ \_ -> bracket connect HC.closeHTTP2Client $ \c -> + action (HC.sendRequest c $ H2.requestNoBody "POST" "/" []) received release + where + XFTPServerConfig {xftpCredentials, transportConfig} = testXFTPServerConfig + testOldServerHandshake :: HasTestEnv => AFStoreType -> Expectation testOldServerHandshake _ = do (chain, pk) <- loadServerCredential xftpCredentials @@ -486,6 +990,33 @@ testOldServerHandshake _ = do where XFTPServerConfig {xftpCredentials} = testXFTPServerConfig +testReceiveChunkDigest :: Expectation +testReceiveChunkDigest = do + bytes <- atomically . C.randomBytes chSize =<< C.newRandom + let digest = LC.sha256Hash $ LB.fromStrict bytes + receive d = bodyReader bytes >>= \getBody -> runExceptT $ receiveFile getBody $ XFTPRcvChunkSpec "/dev/null" chSize d + receive digest `shouldReturn` Right () + receive (digest <> "_wrong") `shouldReturn` Left DIGEST + +testReceiveEncChunkDigest :: Expectation +testReceiveEncChunkDigest = do + g <- C.newRandom + bytes <- atomically $ C.randomBytes chSize g + key <- atomically $ C.randomSbKey g + nonce <- atomically $ C.randomCbNonce g + sbState <- either (error . show) pure $ LC.sbInit key nonce + let (encrypted, sbState') = LC.sbEncryptChunk sbState bytes + body = encrypted <> BA.convert (LC.sbAuth sbState') + digest = LC.sha256Hash $ LB.fromStrict bytes + receive d = bodyReader body >>= \getBody -> runExceptT $ receiveEncFile getBody sbState $ XFTPRcvChunkSpec "/dev/null" chSize d + receive digest `shouldReturn` Right () + receive (digest <> "_wrong") `shouldReturn` Left DIGEST + +bodyReader :: ByteString -> IO (Int -> IO ByteString) +bodyReader bytes = do + rest <- newTVarIO bytes + pure $ \n -> atomically $ stateTVar rest $ B.splitAt n + -- SNI and CORS tests lookupResponseHeader :: B.ByteString -> H2.Response -> Maybe B.ByteString diff --git a/tests/XFTPWebTests.hs b/tests/XFTPWebTests.hs index 4d1275f26..60942418a 100644 --- a/tests/XFTPWebTests.hs +++ b/tests/XFTPWebTests.hs @@ -38,6 +38,8 @@ import qualified Simplex.Messaging.Crypto as C import qualified Simplex.Messaging.Crypto.Lazy as LC import Simplex.Messaging.Encoding import Simplex.Messaging.Encoding.String (strDecode, strEncode) +import Simplex.Messaging.Protocol (XFTPServer, pattern XFTPServer) +import Simplex.Messaging.Transport.Client (TransportHost) import Simplex.Messaging.Transport.Server (loadFileFingerprint) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, removeDirectoryRecursive) import System.Environment (getEnvironment) @@ -2903,6 +2905,27 @@ tsAddressTests = describe "protocol/address" $ do <> jsOut "new TextEncoder().encode(s.host + ':' + s.port)" result `shouldBe` "host1.com:5000" + it "preserves Haskell-produced IPv6 list ports with IPv6 first and last" $ do + let base = either error id (strDecode "xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@example.com") :: XFTPServer + XFTPServer _ _ keyHash = base + ipv6Host = either error id (strDecode "2001:db8::1") :: TransportHost + vectors = + [ (ipv6Host NE.:| ["example.com"], "[2001:db8::1]", "5223"), + ("example.com" NE.:| [ipv6Host], "example.com", "5223"), + (ipv6Host NE.:| [], "[2001:db8::1]", "443") + ] + forM_ vectors $ \(hosts, expectedHost, expectedPort) -> do + let addressPort = if expectedPort == "443" then "" else expectedPort + address = strEncode $ XFTPServer hosts addressPort keyHash + result <- + callNode $ + impAddr + <> "const address = new TextDecoder().decode(" + <> jsUint8 address + <> ");const s = Addr.parseXFTPServer(address);" + <> jsOut "new TextEncoder().encode(s.host + '|' + s.port + '|' + Addr.formatXFTPServer(s))" + result `shouldBe` expectedHost <> "|" <> BC.pack expectedPort <> "|xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@" <> expectedHost <> ":" <> BC.pack expectedPort + -- ── integration ─────────────────────────────────────────────────── tsIntegrationTests :: Spec diff --git a/xftp-web/src/protocol/address.ts b/xftp-web/src/protocol/address.ts index c2897a63e..a2526fbbf 100644 --- a/xftp-web/src/protocol/address.ts +++ b/xftp-web/src/protocol/address.ts @@ -33,9 +33,13 @@ export function parseXFTPServer(address: string): XFTPServer { const keyHash = base64urlDecode(m[1]) if (keyHash.length !== 32) throw new Error("parseXFTPServer: keyHash must be 32 bytes") const hostPart = m[2] + const listPort = hostPart.includes(',') && /\[[0-9a-f:]*:[0-9a-f:]*\]/i.test(hostPart) + ? hostPart.match(/:(\d+)$/)?.[1] + : undefined // Take the first host (before any comma), then split port from that const firstHost = hostPart.split(',')[0] - return {keyHash, ...parseHostPort(firstHost)} + const hostPort = parseHostPort(firstHost) + return {keyHash, ...hostPort, port: listPort ?? hostPort.port} } function parseHostPort(firstHost: string): Pick { diff --git a/xftp-web/test/address.node.test.ts b/xftp-web/test/address.node.test.ts index b9738b334..e0fae482f 100644 --- a/xftp-web/test/address.node.test.ts +++ b/xftp-web/test/address.node.test.ts @@ -19,3 +19,19 @@ test('parseXFTPServer uses the default port for bracketed IPv6 hosts', () => { expect(server.port).toBe('443') expect(serverOrigin(server)).toBe('https://[2001:db8::1]') }) + +test('parseXFTPServer preserves a list-level port with IPv6 first', () => { + const server = parseXFTPServer(`xftp://${keyHash}@[2001:db8::1],example.com:5223`) + + expect(server.host).toBe('[2001:db8::1]') + expect(server.port).toBe('5223') + expect(formatXFTPServer(server)).toBe(`xftp://${keyHash}@[2001:db8::1]:5223`) +}) + +test('parseXFTPServer preserves a list-level port with IPv6 last', () => { + const server = parseXFTPServer(`xftp://${keyHash}@example.com,[2001:db8::1]:5223`) + + expect(server.host).toBe('example.com') + expect(server.port).toBe('5223') + expect(formatXFTPServer(server)).toBe(`xftp://${keyHash}@example.com:5223`) +})