diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b198c094..411d439ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,10 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) so the worker stops serving the removed event (ADR-0862). * A sliding sync `pos` is bound to the user and device it was issued to; any other is `M_UNKNOWN_POS`, so one user can no longer continue another's connection (ADR-0866). +* An account's presence changes at most once every 5 s (a later sync's change is dropped, `PUT /presence` is 429), so a + flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0875, ADR-0876). +* A full presence tracker's refused changes and evicted accounts are logged at warning level as + `presence.tracker.full`, at most once a minute with how many of each, so an operator sees it saturate (ADR-0876). ## Bug fixes @@ -181,6 +185,14 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The Fedora 44 and 45 RPMs build again: GCC 16 refused `std::ranges::find` with a bare string literal under C++26, and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. +* Two clients of one account, one syncing online and one `unavailable`, no longer flip its presence on every sync: an + online device holds the account online for 5 minutes (ADR-0875). +* A classic `/sync` whose only news is the caller's own presence keeps waiting instead of answering nothing (ADR-0873). +* A classic `/sync` with `full_state=true` is answered at once, whatever its `timeout`, as the spec says; it waited + like any other long poll (ADR-0873). +* A sliding sync refused with `M_UNKNOWN_POS` no longer changes the caller's presence: `set_presence` is applied + only once the `pos` is accepted (ADR-0876). +* `docs/observability-audit.md` named the wrong logger for `presence.sync.set`; it is `client_server`. * The example configurations list every module a structured logger call names (twelve were missing, `token` is gone), and a tooling test fails when that list and the modules the sources name differ (ADR-0872). * The TURN log calls mark GCC's cleanup of their braced field lists excluded from coverage, a compiler path no test diff --git a/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md new file mode 100644 index 000000000..107599086 --- /dev/null +++ b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md @@ -0,0 +1,51 @@ +# A classic /sync whose only news is the caller's own presence keeps waiting + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the presence loop of ADR-0875. A classic `/sync` long-poll returned at once whenever the sync stream +moved past its `since`, even when the only new row was the caller's own presence, which `/sync` never sends to its own +user. Each presence change of an account answered every waiting sync of that account with nothing, and each client +synced again at once. + +## Context and Problem Statement + +The long-poll check of `GET /sync` is "has the sync stream or the timeline moved past `since`?". Sliding sync already +waits past bumps its response would not send (ADR-0863, ADR-0869). Classic `/sync` did not, so a change of the caller's +own presence, including the one the same request's `set_presence` just made, woke it into an empty answer. + +## Decision Drivers + +* ADR-0863's rule: never wake a poll with a test the response does not share, or it is answered with nothing, again. +* The check runs under `runtime.mutex` on every rerun, so it must cost a constant. + +## Considered Options + +1. When a `/sync` with a `since` token would answer and its only news is exactly one sync stream position, the + caller's own presence row (`only_own_presence_since`), answer `needs_wait` with the wait cursor advanced to the + stream's newest position. The response, when it comes, is built from the request's own `since`, as before. +2. Judge every position after `since` (a walk of each sync surface). +3. Send the caller their own presence, so the answer is not empty. + +## Decision Outcome + +Chosen option: 1, because it is a constant-time check and covers the case that loops: one device's change waking the +account's other devices, and a request's own `set_presence` waking itself. + +* With any other position after `since`, or several, the sync answers as before; the check never delays news. +* A sync with no `since` (an initial sync) is not affected. +* A sync with `full_state=true` never waits, this check or any other: the spec says that with it "the `timeout` + parameter will be ignored and the query will return immediately". The long-poll gate waited for it before this + decision. +* The rerun of a woken poll judges again from the same `since`: a new position that is not the caller's presence ends + the wait. + +### Positive Consequences + +* A client's own presence change no longer costs it, or its other devices, an empty round trip. + +### Negative Consequences + +* Two of the caller's own presence changes in a row (at least 5 s apart, ADR-0876) answer the second with nothing, as + before this decision. +* Option 3 changes what clients are sent; the spec's presence events are for other users. diff --git a/docs/adr/0875-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0875-a-device-syncing-online-holds-its-account-online.md new file mode 100644 index 000000000..55d028f3d --- /dev/null +++ b/docs/adr/0875-a-device-syncing-online-holds-its-account-online.md @@ -0,0 +1,72 @@ +# A device syncing online holds its account online against another device syncing unavailable + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the owner's server logged `presence.outbound.refused` for every remote server, many times a second. +Two devices of one account were syncing at once, one with `set_presence` omitted (online) and one with +`set_presence=unavailable`. Each sync set the account's presence its own way, each change woke the other device's +long-poll, and the two flipped it every 50 to 250 ms. Each flip queued an `m.presence` EDU for each of about 470 +servers, which filled the outbound dispatch queue and so refused every other federation send. + +## Context and Problem Statement + +A presence row is one per account, but `set_presence` is sent per sync, and so per device. The spec says "Any activity +that bumps the last active time on any of the user's clients will cause the server to automatically set their presence +to `online`", so a client in the background asking for `unavailable` should not take the account down while another +client is in use. How should the asks of several devices become one presence? + +## Decision Drivers + +* The account must not flip with each device's sync. +* A device that stops syncing must not hold the account online for ever. +* Memory stays bounded whatever the number of accounts and devices. + +## Considered Options + +1. Note each device's last ask in memory (`AccountPresenceTracker`). A device that asked for `online` holds the account + online for `device_fresh_ms` (5 minutes, the idle timeout of ADR-0492). A sync asking for `unavailable` changes + nothing while another device holds the account online, and never raises the account to online. +2. Keep one ask per account, the latest, as before. +3. Store the devices' asks in the database. + +## Decision Outcome + +Chosen option: 1, because it matches the spec's "any of the user's clients" and ends the loop at its cause. + +* `set_presence=offline` forgets the device's ask: it no longer holds the account online. +* The freshness time is the idle timeout, so a closed client holds the account online exactly as long as the idle + sweep would leave it online after that client's last sync; a `static_assert` in `PresenceService.cpp` keeps the + two equal. +* At most `max_devices_per_account` (64) devices per account. At the cap a new device takes the place of the least + recently seen device that asked for `unavailable`; only a device asking for `online` takes the place of an online + one (the least recently seen), and a device asking for `unavailable` with no such place is not recorded, since it + holds nothing: replacing by age alone let a 65th device asking for `unavailable` end the only online hold, which is + the flip this decision prevents. At most `max_accounts` + (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. An account with an open window + (ADR-0876) is filed under its end, any other under the time its latest online device goes stale (a device that last + asked for `unavailable` holds no place), so a prune visits only expired accounts, never the table: a flood of + overflow requests under `runtime.mutex` costs no scan. With the table still full, the account with no open window + whose devices go stale soonest is evicted to make room: it loses its devices' holds until it syncs again, never a + window. Only when every account has an open window does a sync of an account the table does not hold have its device + ignored and its change refused (ADR-0876), at most until the soonest window ends. +* The asks are in memory only: after a restart each device's next sync puts its ask back. +* The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. The idle sweep measures activity on + the wall clock (`observed_at_ms`), so after a wall-clock step the hold and the sweep disagree by the step until the + device syncs again: after a backward step a background device's `unavailable` can win while the sweep still counts the + user active, and after a forward step the sweep can set the account unavailable while a hold stands. Accepted: either + is one change, limited by ADR-0876, never a loop. Judging the hold on the wall clock instead would let one clock step + lift or extend every hold at once, and the `static_assert` keeps only the two durations equal. +* An account the table does not hold takes no place for a device asking for `unavailable`: the ask alone never evicts + another account's hold. If that sync changes the stored state, the change still opens a window (ADR-0876) and may + evict a closed account to make room, as any kept change does. + +### Positive Consequences + +* Two clients of one account no longer set its presence back and forth. + +### Negative Consequences + +* After every online client closes, a background client asking for `unavailable` sets the account unavailable only + once the freshness time has passed, up to 5 minutes later (the idle sweep sets it unavailable at the same moment). +* Option 2 is the simpler model, and looks better in isolation; it is the one that made the loop. diff --git a/docs/adr/0876-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0876-the-first-presence-change-in-a-five-second-window-is-kept.md new file mode 100644 index 000000000..185269b30 --- /dev/null +++ b/docs/adr/0876-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -0,0 +1,67 @@ +# The first presence change in a five-second window is kept, and every other one in it is dropped + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the presence loop of ADR-0875. Even with the devices combined, anything that changes an account's +presence many times a second (a buggy client, two clients fighting through `PUT /presence`) queues an EDU for every +server in the account's rooms each time. + +## Context and Problem Statement + +Every change of a local user's presence is stored, wakes the syncs of everyone who shares a room with them and queues +one `m.presence` EDU per remote server in those rooms, each in its own transaction. How often may one account cause +that? + +## Decision Drivers + +* One account must not be able to fill the federation dispatch queue. +* The owner's rule: the first change in a window goes through and the rest are dropped. Keeping the last change for + later ("coalescing") is the same rate limit with a different change kept, and the last change is as likely to be the + wrong one as the first. +* `PUT /presence/{userId}/status` has only 200 and 429 in the spec. + +## Considered Options + +1. A window of `change_window_ms` (5 s) per account, started by a change kept. A change asked for inside it is dropped + (a sync: nothing stored, woken or sent) or refused (`PUT`: 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` and + `Retry-After`). Judged and noted under `runtime.mutex`, with the write. +2. Coalesce: hold the last change asked for in the window and send it when the window ends. +3. Limit only the outbound EDUs, and store every change. + +## Decision Outcome + +Chosen option: 1. + +* The window is per account, not per device, since the row and its EDUs are per account. +* A change is a change of the stored state by a sync, or any `PUT`. A sync that leaves the state as it is refreshes the + last-active time in memory as before and is not limited. +* Not limited: the idle sweep (the server's own change, at most once per idle period; a user who returns at once is + marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar + (it stores the row for local syncs and appservices and sends no `m.presence` EDU), and inbound presence from other + servers (their own server's to limit). +* An account with an open window is never removed from `AccountPresenceTracker`, or removing it would lift its limit. + A full table makes room by evicting an account with no open window (ADR-0875), so accounts that keep syncing never + shut others out. Only when every account in it has an open window is a change of an account it does not hold refused + (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. The + refusal's `retry_after_ms` is the rest of the soonest window (at most `change_window_ms`), and its log line's `cause` + is `tracker_full`, not `window`. Such a refusal, and every eviction a full table makes (ADR-0875), counts towards + `presence.tracker.full`, a warning logged at most once a minute (`full_warning_interval_ms`) with the number of + each since the last one and no user IDs. A user who did nothing wrong is refused only here, and an evicted account + loses its devices' holds, so an operator must see both without debug logging; one warning per refusal or eviction + would let the flood that fills the table flood the log too. The report is asked for after each use of the table + (`take_saturation_report`, O(1)), so what a quiet minute leaves is reported by the next sync or `PUT`. +* A dropped change is never kept later: a parked `/sync` or sliding sync is run again after a wake-up or its timeout + (`rerun_waiting_sync`, `ClientServerDispatchOptions::sync_rerun`), and that rerun does not apply its `set_presence` + again, so a change dropped in the window is not stored once the window has ended. +* Tests move the clock with `HomeserverRuntime::test_presence_clock_advance_ms`. + +### Positive Consequences + +* One account causes at most one presence broadcast every 5 seconds. + +### Negative Consequences + +* A change asked for in the window is lost, not deferred: a client that set `unavailable` a second after a sync set it + `online` is refused, and its sync's next change is what counts. +* A client that does not retry a 429 on `PUT /presence` keeps whatever was set first. diff --git a/docs/adr/index.md b/docs/adr/index.md index 5743f5ca4..836b538ec 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -746,4 +746,7 @@ * [0870 - A ranges algorithm takes a typed value, never a bare string literal](0870-a-ranges-algorithm-takes-a-typed-value-never-a-bare-string-literal.md) * [0871 - TURN credential requests log under their own `turn` module, and never log a credential](0871-turn-credential-requests-log-under-their-own-turn-module.md) * [0872 - The example configs list every log module, and a tooling test reads the modules from the sources](0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md) +* [0873 - A classic /sync whose only news is the caller's own presence keeps waiting](0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md) * [0874 - A braced log-field list may mark GCC's cleanup branches excluded from coverage](0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md) +* [0875 - A device syncing online holds its account online against another device syncing unavailable](0875-a-device-syncing-online-holds-its-account-online.md) +* [0876 - The first presence change in a five-second window is kept, and every other one in it is dropped](0876-the-first-presence-change-in-a-five-second-window-is-kept.md) diff --git a/docs/database-persistence.md b/docs/database-persistence.md index 7bae77c9c..9da8ce62d 100644 --- a/docs/database-persistence.md +++ b/docs/database-persistence.md @@ -646,7 +646,9 @@ value. Test fixtures that do not exercise persistence select it through (256) rows with a thread root as `thread_id` in one room; a new one is committed with the delete of that user's own oldest (ADR-0737). The device-list change, stored filter and presence tables are read through standing indexes by observer, user and user (`for_each_observer_device_list_change`, `for_each_user_filter`, - `find_presence_state`; ADR-0659). `store_receipts` commits an inbound `m.receipt` + `find_presence_state`; ADR-0659). A presence row is changed in place only through `find_mutable_presence_state`, which + answers from the same position lookup, and the change keeps the row's `user_id`, the key of `presence_user_index`. + `store_receipts` commits an inbound `m.receipt` EDU's accepted rows in one transaction and, past `max_inbound_receipt_entries`, deletes the oldest remote rows in it, taken from the ordered `receipt_remote_by_stream` index (ADR-0652). - The v1 schema's media tables carry the upload names and pending uploads. diff --git a/docs/matrix-v1.19-client-server-api.md b/docs/matrix-v1.19-client-server-api.md index 7b82dee2e..657bb1360 100644 --- a/docs/matrix-v1.19-client-server-api.md +++ b/docs/matrix-v1.19-client-server-api.md @@ -181,7 +181,7 @@ comparison (ADR-0631); any other `from` is `400 M_INVALID_PARAM`. | `GET` | `/_matrix/client/v3/presence/{userId}/status` | `getPresence` | access token | - | 200, 403, 404 | | `PUT` | `/_matrix/client/v3/presence/{userId}/status` | `setPresence` | access token | required application/json | 200, 429 | -`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". +`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. A device that synced `online` in the last 5 minutes holds the account online against another syncing `unavailable` (ADR-0875). An account's presence changes at most once in 5 s: a later `/sync` change in the window is dropped and a `PUT` is 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` (ADR-0876). The same 429 (error `too many accounts are changing presence`) and dropped `/sync` change also come, for an account that has not changed at all, when every account in the server's presence tracker has a window open; `retry_after_ms` is then the soonest window's end, and the server logs `presence.tracker.full`. A `/sync` long-poll whose only news is the caller's own presence keeps waiting (ADR-0873). `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". ## Push notifications diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 1be107c64..7ea8b7ae8 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -130,8 +130,19 @@ is full. covered by `server.sso.redirect_url_allowlist` — see `docs/threat-model.md` ("Open redirect and login-token exfiltration via SSO redirectUrl"). - `presence.set` (debug, logger `client_server`) records a `PUT /presence/{userId}/status` - (fields `actor`, `presence`; never the status message). `presence.sync.set` (debug, logger - `presence`) records a `/sync` that changed the caller's state (fields `actor`, `presence`). + (fields `actor`, `presence`; never the status message). `presence.set.limited` (debug, logger + `client_server`) records one refused with 429 because the account's presence changed less than + 5 s before (`cause` `window`) or the presence tracker had no room for the account (`cause` + `tracker_full`) (fields `actor`, `presence`, `cause`, `retry_after_ms`; ADR-0876). `presence.sync.set` (debug, + logger `client_server`) records a `/sync` that changed the caller's state (fields `actor`, + `presence`). `presence.change.limited` (debug, logger `presence`) records a `/sync` change dropped + for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`), and a `/sync` asking for + `unavailable` while another device of the account holds it online and the account is not already `unavailable` + (`cause` `device_online`, no `retry_after_ms`; ADR-0875). + `presence.tracker.full` (warning, logger `presence`) fires when the presence tracker refused a change because it + had no room (`cause` `tracker_full` above) or evicted an account to make room, at most once a minute, with the + number of each since the last warning (fields `refused`, `evicted`, `accounts`, `limit`; never a user ID; ADR-0875, + ADR-0876). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/docs/threat-model.md b/docs/threat-model.md index 81580300f..c34274b6d 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -2791,6 +2791,18 @@ nothing, all from trusting the worker's view or the hook's transport. reporting it. - **Presence off.** `presence.enabled=false` stores and sends nothing, so an operator who does not want to publish presence to the federation need not. +- **One account flooding the federation queue with presence.** Each change of a local user's + presence queues an `m.presence` EDU for every server in their rooms. Two clients of one account + fighting over `set_presence` changed it many times a second and filled the dispatch queue, so + every other federation send was refused. A device that synced online holds the account online + for 5 minutes (ADR-0875), a classic `/sync` no longer wakes for its own presence (ADR-0873), and + an account's presence changes at most once every 5 s, the first change kept (ADR-0876). The + tracker behind both is bounded and fails closed when full. **Residual risk:** one change every + 5 s per account still costs an EDU per remote server; many accounts at once are bounded only by + the dispatch queue's own shares. A profile change stores the user's presence row again (so local + syncs and appservices see the new name or avatar) but sends no `m.presence` EDU and is not + limited: its federation cost is its `m.room.member` events, bounded by the profile propagation + (ADR-0353). ### Remote space hierarchy answers (0.12.60) diff --git a/docs/user-manual.md b/docs/user-manual.md index 724be355f..c2e83f6ec 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1216,8 +1216,17 @@ the users who share a room with them in `/sync` (`presence.events`) and by `GET /presence/{userId}/status`, and sent to other servers that share a room with them as an `m.presence` EDU. `PUT /presence/{userId}/status` sets it, and so does `/sync`: omitting `set_presence` marks the user online, `unavailable` marks them idle, `offline` leaves it as it -is. Presence reaches only users who share a joined room with the user; anyone else asking for it -gets `403 M_FORBIDDEN`, as for a user who does not exist. +is. A device that synced online in the last 5 minutes keeps the user online while another of their devices syncs +`unavailable`; a sync from that device with `set_presence=offline` ends its hold at once. A user's presence changes at +most once every 5 seconds: a later change by `/sync` in that time is ignored, and `PUT /presence` answers `429` with +`retry_after_ms`. While as many accounts as the server tracks (65,536) have all changed in the last 5 seconds, a change +by any other account is refused the same way (`too many accounts are changing presence`) until the soonest of those +5 seconds ends. With that many accounts tracked and some of them not changed lately, a new one takes the place of the +account whose devices went quiet soonest instead, which loses its online hold until it next syncs. Both are logged by +the warning `presence.tracker.full`, at most once a minute. The server's own idle +change (an online user inactive for 5 minutes becomes `unavailable`) is not limited and does not start those 5 seconds. +Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as +for a user who does not exist. | Key | Default | When to change | |---|---|---| diff --git a/include/merovingian/database/PersistentStore.hpp b/include/merovingian/database/PersistentStore.hpp index 9d2c9c124..3277ed6fc 100644 --- a/include/merovingian/database/PersistentStore.hpp +++ b/include/merovingian/database/PersistentStore.hpp @@ -1586,6 +1586,8 @@ auto for_each_user_filter(PersistentStore const& store, std::string_view user_id // The presence row of `user_id`, or nullptr, through the user index (ADR-0659). [[nodiscard]] auto find_presence_state(PersistentStore const& store, std::string_view user_id) -> PersistentPresence const*; +// The same row for a change in place, or nullptr. A change must keep `user_id`: the index is keyed on it. +[[nodiscard]] auto find_mutable_presence_state(PersistentStore& store, std::string_view user_id) -> PersistentPresence*; [[nodiscard]] auto upsert_presence(PersistentStore& store, PersistentPresence state) -> bool; // Store a sync filter uploaded by a client. On conflict the JSON is replaced. [[nodiscard]] auto store_filter(PersistentStore& store, PersistentFilter filter) -> bool; diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp new file mode 100644 index 000000000..b1ada3a0f --- /dev/null +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -0,0 +1,189 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace merovingian::homeserver +{ + +// What each local account's devices last asked of its presence through a sync's `set_presence`, and when the account's +// presence last changed. In memory only; every operation takes the time in milliseconds of a clock that never goes back +// (`presence_limit_clock_ms`). +// +// Devices (ADR-0875): a device that syncs `online` holds its account online for `device_fresh_ms`, so another device +// syncing `unavailable` in that time does not set the account unavailable. Two clients of one account, one in the +// foreground and one in the background, otherwise set the presence back and forth on every sync. +// +// Changes (ADR-0876): the first change of an account's presence starts a window of `change_window_ms`; every other +// change asked for in the window is dropped (a sync) or refused with 429 (`PUT /presence`). The first one asked for is +// the one kept, never the last. +// +// Bounded: at most `max_accounts` accounts (the account cap, which a test may set lower) of `max_devices_per_account` +// devices each. A new device past the device cap replaces the account's least recently seen one. An account with an +// open window is filed under the window's end; any other under the time its last online device goes stale, and an +// account moves from the first to the second when its window ends. A prune removes only the accounts whose time has +// passed, never visiting the table. When the table is full after a prune, the account with no open window whose devices +// go stale soonest makes room: it loses only its devices' holds, never a window, so the limit holds. Only when every +// account has an open window is there no room: a newcomer's devices are ignored and its change refused until the +// soonest window ends (at most `change_window_ms`), so a flood of accounts cannot lift the limit for itself. Every +// operation does O(log n) work per account it moves or removes. Not thread-safe: `runtime.mutex` serialises every use +// (`HomeserverRuntime::presence_tracker`). +class AccountPresenceTracker final +{ +public: + static constexpr auto change_window_ms = std::int64_t{5'000}; + // The idle timeout (`presence_idle_timeout_ms`): a device holds the account online for as long as the idle sweep + // would leave it online after that device's last sync. `PresenceService.cpp` asserts the two are equal. + static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; + // Far more devices than one person syncs from at once; each is a device ID and two integers. At the cap a new + // device takes the place of one that asked for unavailable first, and only one asking for online takes an online + // device's place (`make_device_place`). + static constexpr auto max_devices_per_account = std::size_t{64U}; + // Accounts with a device that asked for online within the last five minutes, or a window open: the account cap a + // tracker has unless it is made with another. + static constexpr auto max_accounts = std::size_t{65'536U}; + // At most one report of what a full table cost in this time, so a flood of refusals or evictions costs one warning + // a minute, which counts what it stands for. + static constexpr auto full_warning_interval_ms = std::int64_t{60'000}; + + // What a full table did since the last report. + struct SaturationReport final + { + // Changes refused because the table had no room (`note_full_refusal`). + std::uint64_t refused{0U}; + // Accounts evicted to make room, which lost their devices' holds. + std::uint64_t evicted{0U}; + + [[nodiscard]] auto operator==(SaturationReport const&) const -> bool = default; + }; + + AccountPresenceTracker() = default; + // A tracker holding at most `account_cap` accounts (at least one), so a test can fill the table without + // `max_accounts` of them. The server's tracker is made with the default. + explicit AccountPresenceTracker(std::size_t account_cap) noexcept; + + // Notes that `device` of `user` synced asking for `online` (true) or `unavailable` (false) at `now_ms`. True when a + // device the table holds for the account, this one included, asked for online within `device_fresh_ms`. Records + // nothing and answers false for an account the table does not hold when the ask is `unavailable` (it needs no + // place) or when the table has no room for it (fails closed; room is made only by a prune or an eviction, and + // `is_full_for` tells the caller a change is refused). + [[nodiscard]] auto note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) + -> bool; + + // A sync with `set_presence=offline` at `now_ms`: the device no longer holds the account online. + auto forget_device(std::string_view user, std::string_view device, std::int64_t now_ms) -> void; + + // How long `user` must wait before a change of presence is kept, or nullopt when one may be kept now: the rest of + // the account's window, or, when `is_full_for`, the rest of the table's soonest window. Never over the window. + [[nodiscard]] auto change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const + -> std::optional; + + // True when a change of `user` is refused because the table has no room for the account (every account in it has an + // open window), not because of the account's own window. + [[nodiscard]] auto is_full_for(std::string_view user, std::int64_t now_ms) const -> bool; + + // Starts the window of `user` at `now_ms`: a change was just kept. Does nothing for an account the table has no + // room for, which `change_blocked_for_ms` refused a change of first. + auto note_change(std::string_view user, std::int64_t now_ms) -> void; + + // Removes every account whose online devices are all stale and whose window ended by `now_ms`. + auto prune(std::int64_t now_ms) -> void; + + // Accounts held, ones a prune would remove included. + [[nodiscard]] auto account_count() const noexcept -> std::size_t; + + // Accounts a prune re-filed when their window ended or removed, or a full table evicted, since the table was made, + // for tests that prove the cost. + [[nodiscard]] auto accounts_examined() const noexcept -> std::uint64_t; + + // The most accounts the table holds. + [[nodiscard]] auto account_cap() const noexcept -> std::size_t; + + // Counts a change refused because the table is full (`is_full_for`). + auto note_full_refusal() noexcept -> void; + + // Changes refused because the table was full, since the table was made. + [[nodiscard]] auto full_refusals() const noexcept -> std::uint64_t; + + // Accounts a full table evicted to make room, since the table was made. + [[nodiscard]] auto evictions() const noexcept -> std::uint64_t; + + // What the table refused and evicted since the last report, when it did either and no report was taken in the + // `full_warning_interval_ms` before `now_ms`; the report is then taken as of `now_ms`. Otherwise nullopt. O(1), so + // a caller may ask after every use of the table. + [[nodiscard]] auto take_saturation_report(std::int64_t now_ms) -> std::optional; + +private: + struct Device final + { + std::string id{}; + std::int64_t seen_at_ms{0}; + bool online{false}; + }; + struct Account final + { + std::vector devices{}; + std::optional changed_at_ms{}; + // Its key: the end of its open window (in `m_open_windows`), or else the time its last online device goes stale + // or its window ended, whichever is later (in `m_closed`). + std::int64_t filed_at_ms{0}; + bool window_open{false}; + }; + // Looks a user ID up as a string_view without making a string. + struct UserHash final + { + using is_transparent = void; + [[nodiscard]] auto operator()(std::string_view user) const noexcept -> std::size_t + { + return std::hash{}(user); + } + }; + using Accounts = std::unordered_map>; + using FiledKey = std::pair; + + // The account of `user`, made when there is room (after a prune, and an eviction when the table is still full); + // `m_accounts.end()` when there is none. + [[nodiscard]] auto account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator; + + // Files `entry` again, after its devices or window changed or its window ended. + auto refile(Accounts::iterator entry, std::int64_t now_ms) -> void; + + // Moves every account whose window ended by `now_ms` from `m_open_windows` to `m_closed`. + auto close_ended_windows(std::int64_t now_ms) -> void; + + // Makes a place in a full `devices` for a new device asking for `online` (true) or `unavailable`: the least + // recently seen device that asked for unavailable gives up its place, or, for an online newcomer when every device + // asked for online, the least recently seen of them. False when there is none to give: an unavailable newcomer + // holds nothing, so it never ends another device's online hold (ADR-0875). + [[nodiscard]] static auto make_device_place(std::vector& devices, bool online) -> bool; + + // True when the table can hold another account at `now_ms`: it is not full, or an account in it has no open window. + [[nodiscard]] auto has_room(std::int64_t now_ms) const noexcept -> bool; + + Accounts m_accounts{}; + // (window end, user) of every account whose window was open when it was filed, soonest first. + std::set m_open_windows{}; + // (stale-or-ended time, user) of every other account, soonest first: the ones a prune removes, and the one a full + // table evicts. + std::set m_closed{}; + std::uint64_t m_accounts_examined{0U}; + std::size_t m_account_cap{max_accounts}; + std::uint64_t m_full_refusals{0U}; + std::uint64_t m_evictions{0U}; + // The two counts when the last report was taken, and when that was. + std::uint64_t m_reported_refusals{0U}; + std::uint64_t m_reported_evictions{0U}; + std::optional m_reported_at_ms{}; +}; + +} // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/ClientServerDispatchOptions.hpp b/include/merovingian/homeserver/ClientServerDispatchOptions.hpp index 93d76acca..71bbdbdd1 100644 --- a/include/merovingian/homeserver/ClientServerDispatchOptions.hpp +++ b/include/merovingian/homeserver/ClientServerDispatchOptions.hpp @@ -17,6 +17,10 @@ struct ClientServerDispatchOptions final // The transport already counted this request against the rate limiter (the // media fetch pool running a deferred request again); do not count it twice. bool rate_limit_admitted{false}; + // A parked /sync or sliding sync run again after a wake-up or its timeout (`rerun_waiting_sync`). Its + // `set_presence` was applied on its first run and is not applied again, so a change the window dropped stays + // dropped (ADR-0876). + bool sync_rerun{false}; }; } // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/ClientServerRuntime.hpp b/include/merovingian/homeserver/ClientServerRuntime.hpp index 01629c8db..a51c9aafe 100644 --- a/include/merovingian/homeserver/ClientServerRuntime.hpp +++ b/include/merovingian/homeserver/ClientServerRuntime.hpp @@ -18,6 +18,7 @@ #include "merovingian/homeserver/LocalHttpResponse.hpp" #include "merovingian/homeserver/LoginTokenStore.hpp" #include "merovingian/homeserver/OperationResult.hpp" +#include "merovingian/homeserver/PresenceWrite.hpp" #include "merovingian/homeserver/RegistrationValidationSession.hpp" #include "merovingian/homeserver/SafetyReportIndex.hpp" #include "merovingian/homeserver/UiaSession.hpp" @@ -139,7 +140,12 @@ auto install_test_per_user_rate_limit_engine(ClientServerRuntime& runtime) -> vo std::vector changes) -> bool; [[nodiscard]] auto record_device_list_change(ClientServerRuntime& runtime, database::PersistentDeviceListChange change) -> bool; -[[nodiscard]] auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> bool; +// Stores a presence the user set (`PUT /presence`), wakes syncs and tells the servers that share a room with them. +// `limited` when the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago, or, with +// `PresenceWrite::tracker_full`, when the tracker has no room for the account (ADR-0876): nothing is stored. +// Takes runtime.mutex. +[[nodiscard]] auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) + -> PresenceWrite; // One pass of the "presence-idle" job (CS API "Presence", "Idle timeout"; ADR-0492): every local user whose // presence is `online` and whose last active time is over `presence_idle_timeout_ms` is set to `unavailable`, // told to the servers that share a room with them, and long-polling syncs are woken. Takes runtime.mutex for diff --git a/include/merovingian/homeserver/HomeserverRuntime.hpp b/include/merovingian/homeserver/HomeserverRuntime.hpp index a212bf414..63a45ddd3 100644 --- a/include/merovingian/homeserver/HomeserverRuntime.hpp +++ b/include/merovingian/homeserver/HomeserverRuntime.hpp @@ -17,6 +17,7 @@ #include "merovingian/federation/FederationRuntimeState.hpp" #include "merovingian/federation/RemoteDeviceListCache.hpp" #include "merovingian/federation/ServerDiscoveryNetwork.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/AccountSessionStore.hpp" #include "merovingian/homeserver/ActiveServerSigningKeySecret.hpp" #include "merovingian/homeserver/AppserviceDeliveryBackoff.hpp" @@ -261,6 +262,12 @@ struct HomeserverRuntime final // Test-only: added to the wall clock by `oauth_device_clock_ms`, so a test moves the device grant's time (expiry, // polling interval, the wrong-code window) without sleeping. Always 0 in production. std::uint64_t test_device_grant_clock_advance_ms{0U}; + // What each local account's devices last asked of its presence, and when its presence last changed (ADR-0875, + // ADR-0876). In memory only, bounded. Guarded by `mutex`. Takes its time from `presence_limit_clock_ms`. + AccountPresenceTracker presence_tracker{}; + // Test-only: added to the steady clock by `presence_limit_clock_ms`, so a test moves past a presence change window + // or a device's freshness without sleeping. Always 0 in production. + std::int64_t test_presence_clock_advance_ms{0}; // The signed-in sessions of the account pages at `/_merovingian/account` (plan P6, ADR-0796) and the cross-signing // reset approvals they grant (ADR-0797). In memory only, bounded. Here, not on `ClientServerRuntime`, because a // password change, a password reset and a deactivation (`AuthService.cpp`) end them. Guarded by `mutex`. diff --git a/include/merovingian/homeserver/PresenceService.hpp b/include/merovingian/homeserver/PresenceService.hpp index f81573a5b..738fcec2c 100644 --- a/include/merovingian/homeserver/PresenceService.hpp +++ b/include/merovingian/homeserver/PresenceService.hpp @@ -61,6 +61,16 @@ inline constexpr auto presence_idle_catch_up_interval = std::chrono::seconds{1}; // Wall-clock milliseconds since the Unix epoch. [[nodiscard]] auto presence_now_ms() -> std::int64_t; +// The clock of `HomeserverRuntime::presence_tracker` (ADR-0875, ADR-0876): steady-clock milliseconds, which never go +// back, plus `test_presence_clock_advance_ms`. Not a point in calendar time. +[[nodiscard]] auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t; + +// Logs `presence.tracker.full` at warning level when the presence tracker refused a change or evicted an account since +// the last report, at most once every `AccountPresenceTracker::full_warning_interval_ms` (ADR-0876). Called after +// every use of the tracker that may refuse or evict; O(1) when there is nothing to report. The caller holds +// `runtime.mutex`. +auto report_presence_tracker_saturation(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void; + // "The last active time must be up to date whenever the server gives a presence event to the // client": the stored value plus the time since it was true. Never negative. [[nodiscard]] auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept @@ -115,12 +125,18 @@ auto note_local_message_activity(HomeserverRuntime& runtime, std::string_view us [[nodiscard]] auto parse_sync_presence_mode(std::optional value) noexcept -> std::optional; -// Applies a /sync's `set_presence` to a local user. Only a change of state is stored (and so only -// a change is sent to other users); an `online` user who syncs again just has their last-active -// time refreshed in memory. The caller holds runtime.mutex. Returns the new row when the state -// changed, so the caller can send it to other servers and wake long-polling syncs. -[[nodiscard]] auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, SyncPresenceMode mode) - -> std::optional; +// Applies the `set_presence` of a /sync from `device` to a local user. Only a change of state is stored (and so only +// a change is sent to other users); an `online` user who syncs again just has their last-active time refreshed in +// memory. The device's ask is noted in `runtime.presence_tracker`: +// * `offline` stores nothing and the device no longer holds the account online; +// * `unavailable` changes nothing while another device of the account asked for `online` within +// `AccountPresenceTracker::device_fresh_ms` (ADR-0875); +// * a change within `AccountPresenceTracker::change_window_ms` of the account's last one is dropped, and so is a +// change of an account the tracker has no room for (`is_full_for`, ADR-0876). +// The caller holds runtime.mutex. Returns the new row when the state changed, so the caller can send it to other +// servers and wake long-polling syncs. +[[nodiscard]] auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional; // The `presence.events` of a /sync response for `user`: other users who share a joined room, // whose presence changed since `since_sync_stream_id` or who started sharing a room in diff --git a/include/merovingian/homeserver/PresenceWrite.hpp b/include/merovingian/homeserver/PresenceWrite.hpp new file mode 100644 index 000000000..5fc19af44 --- /dev/null +++ b/include/merovingian/homeserver/PresenceWrite.hpp @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "merovingian/homeserver/PresenceWriteStatus.hpp" + +#include + +namespace merovingian::homeserver +{ + +struct PresenceWrite final +{ + PresenceWriteStatus status{PresenceWriteStatus::failed}; + // When `status` is limited: how long until a change can be kept, at least 1 ms. + std::uint32_t retry_after_ms{0U}; + // When `status` is limited: true when `AccountPresenceTracker` had no room for the account (ADR-0876), false when + // the account's own window is open. + bool tracker_full{false}; +}; + +} // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/PresenceWriteStatus.hpp b/include/merovingian/homeserver/PresenceWriteStatus.hpp new file mode 100644 index 000000000..c791b4ad0 --- /dev/null +++ b/include/merovingian/homeserver/PresenceWriteStatus.hpp @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include + +namespace merovingian::homeserver +{ + +// What became of a presence a user set (`set_presence`). +enum class PresenceWriteStatus : std::uint8_t +{ + // Stored and sent, or accepted and dropped because presence is off. + stored, + // Not stored: refused by `AccountPresenceTracker` (ADR-0876). The account's presence changed less than + // `AccountPresenceTracker::change_window_ms` ago, or, when `PresenceWrite::tracker_full` is set, the table had no + // room for the account, whose presence need not have changed at all. + limited, + // The store refused the row. + failed, +}; + +} // namespace merovingian::homeserver diff --git a/src/database/AGENTS.md b/src/database/AGENTS.md index d4b6abb0c..171f089a8 100644 --- a/src/database/AGENTS.md +++ b/src/database/AGENTS.md @@ -393,7 +393,7 @@ as `core::CopyableMutex` has. No production code copies a store; only tests do. `device_list_observer_index` (device-list changes by observer), `filter_user_index` (stored filters by user) and `presence_user_index` (presence rows by user) follow the row-index rule above: trusted only while built for the vector's current row count, rebuilt by their writer when found out of step and by `rebuild_key_indexes` after hydration. Read through -`for_each_observer_device_list_change`, `for_each_user_filter`, `find_filter` and `find_presence_state`, never by looping the -vector in a request. `record_device_list_changes` replaces a pair's row by erasing it (the last row moves into the gap, so the +`for_each_observer_device_list_change`, `for_each_user_filter`, `find_filter` and `find_presence_state` (`find_mutable_presence_state` +for a change in place: never turn the const accessor's pointer back into a position), never by looping the vector in a request. `record_device_list_changes` replaces a pair's row by erasing it (the last row moves into the gap, so the vector has no order) and appending the new one. Tests prove cost with `device_list_rows_examined`, `filter_rows_examined` and `presence_rows_examined`. diff --git a/src/database/PersistentStore.cpp b/src/database/PersistentStore.cpp index 6f4f0a70c..34a500f37 100644 --- a/src/database/PersistentStore.cpp +++ b/src/database/PersistentStore.cpp @@ -8744,6 +8744,40 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str return record_device_list_changes(store, std::move(batch)); } +namespace +{ + + // The position in `store.presence_states` of `user_id`'s row, or nullopt, through the user index (ADR-0659). The + // const and the mutable lookup both answer from it, so neither turns the other's pointer back into a position. + [[nodiscard]] auto presence_position(PersistentStore const& store, + std::string_view user_id) -> std::optional + { + if (store.presence_user_index.in_step(store.presence_states.size())) + { + store.presence_rows_examined.add(1U); + auto const position = store.presence_user_index.find(std::string{user_id}); + if (!position.has_value()) + { + return std::nullopt; + } + if (*position < store.presence_states.size() && store.presence_states[*position].user_id == user_id) + { + return position; + } + } + store.presence_rows_examined.add(store.presence_states.size()); + auto const found = std::ranges::find_if(store.presence_states, [user_id](PersistentPresence const& row) { + return row.user_id == user_id; + }); + if (found == store.presence_states.end()) + { + return std::nullopt; + } + return static_cast(std::ranges::distance(store.presence_states.begin(), found)); + } + +} // namespace + [[nodiscard]] auto upsert_presence(PersistentStore& store, PersistentPresence state) -> bool { if (state.user_id.empty() || state.presence.empty()) @@ -8765,9 +8799,9 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str return false; } sync_presence_index(store); - if (auto const* current = find_presence_state(store, state.user_id); current != nullptr) + if (auto* const current = find_mutable_presence_state(store, state.user_id); current != nullptr) { - store.presence_states[static_cast(current - store.presence_states.data())] = std::move(state); + *current = std::move(state); return true; } store.presence_states.push_back(std::move(state)); @@ -8778,28 +8812,14 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str [[nodiscard]] auto find_presence_state(PersistentStore const& store, std::string_view user_id) -> PersistentPresence const* { - if (store.presence_user_index.in_step(store.presence_states.size())) - { - store.presence_rows_examined.add(1U); - auto const position = store.presence_user_index.find(std::string{user_id}); - if (!position.has_value()) - { - return nullptr; - } - if (*position < store.presence_states.size() && store.presence_states[*position].user_id == user_id) - { - return &store.presence_states[*position]; - } - } - store.presence_rows_examined.add(store.presence_states.size()); - for (auto const& row : store.presence_states) - { - if (row.user_id == user_id) - { - return &row; - } - } - return nullptr; + auto const position = presence_position(store, user_id); + return position.has_value() ? &store.presence_states[*position] : nullptr; +} + +[[nodiscard]] auto find_mutable_presence_state(PersistentStore& store, std::string_view user_id) -> PersistentPresence* +{ + auto const position = presence_position(store, user_id); + return position.has_value() ? &store.presence_states[*position] : nullptr; } [[nodiscard]] auto store_room_alias(PersistentStore& store, PersistentRoomAlias alias) -> bool diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index e3b920f5e..63973af9f 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,6 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0875) and the 5 s window after a presence change (ADR-0876); 64 devices per account, 65,536 accounts (`max_accounts`; a unit test makes a tracker with a smaller cap to fill it, and only the integration scenario that proves the full table's 429 fills the server's tracker, once per case, with windows dated ahead), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts every account a prune re-files or removes, and every eviction); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | @@ -75,7 +76,7 @@ This is the largest and most complex module — read this file carefully before | `PushRoomFacts.cpp` | `push_room_facts`, `room_member_display_name`, `push_evaluation_context`: the evaluation context push delivery and unread counting share | | `PushBadgeCount.cpp` | `count_push_badge`: the Push Gateway `counts.unread` from one walk of the events, newest first in stream order, that stops once every room is settled, at most 10000 rows (ADR-0207) | | `PushRuleUnreadClassifier.cpp` | `PushRuleUnreadClassifier`: counts unread events by the user's push rules, from the start of their current join (R15, ADR-0205) | -| `PresenceService.cpp` | Presence (CS API "Presence", SS API `m.presence`): `read_presence` (GET), `apply_sync_presence` (the `/sync` `set_presence` parameter), `build_sync_presence_events` (`presence.events`), `accept_inbound_presence` (the EDU sink's presence case) and `record_presence`, the one place a presence row is stored. `expire_idle_presence` (the idle sweep, ADR-0492). `presence.enabled=false` turns every entry point into a no-op. Sending the EDU stays in `ClientServerRuntime.cpp` (`broadcast_presence_edu`), beside the other outbound EDUs | +| `PresenceService.cpp` | Presence (CS API "Presence", SS API `m.presence`): `read_presence` (GET), `apply_sync_presence` (the `/sync` `set_presence` parameter), `build_sync_presence_events` (`presence.events`), `accept_inbound_presence` (the EDU sink's presence case) and `record_presence`, the one place a presence row is stored. `expire_idle_presence` (the idle sweep, ADR-0492). `presence_limit_clock_ms`, the clock of `AccountPresenceTracker`. `presence.enabled=false` turns every entry point into a no-op. Sending the EDU stays in `ClientServerRuntime.cpp` (`broadcast_presence_edu`), beside the other outbound EDUs | | `PushRetry.cpp` | `attempt_push_delivery` (every push attempt: circuit breaker, rejected pushkeys, scheduling retries) and `PushRetryJob`, the one thread that sends retries (R14, ADR-0206); a run is bounded by a time budget, takes retries one recipient at a time in turn and sends with a shorter timeout (ADR-0410), and a slow answer counts against the gateway's circuit (ADR-0409) | | `PasswordReset.cpp` | Password reset by email (ADR-0481): `make_password_reset_token` (8 characters, 40 bits), `normalize_password_reset_token`, `send_password_reset_email` (a background task parked in `orphan_futures_`, at most 8 in flight, no lock held while it sends). The endpoints are in `ClientServerRuntime.cpp` before the auth gate; `reset_local_user_password` is in `AuthService.cpp` | | `ClientServerRuntime.cpp` (MatrixRTC) | `GET /_matrix/client/v1/rtc/transports` and `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports` advertise `server.rtc.livekit.service_url` as `{"type":"livekit","livekit_service_url":...}` (`livekit_transport_json`): `transports` and `[]` when none on the stable path, `rtc_transports` and `{}` on the unstable one; both flags `org.matrix.msc4143` and `org.matrix.msc4143.stable` are always in `/versions`, and the well-known document gains `org.matrix.msc4143.rtc_foci` only with a URL (ADR-0822). With the built-in token service instead (`server.rtc.livekit.url`, ADR-0829) they list `{"type":"livekit","url":...}` (`livekit_sfu_transport_json`), the stable path `m.livekit` after it, and `org.matrix.msc4195` and `.stable` are true; `rtc_foci` stays for the external service only. `voip/turnServer` returns `server.turn.server` or, when that is empty, each `server.turn.uris` entry in order (ADR-0821) | @@ -1379,6 +1380,20 @@ without that check ignores `presence.enabled=false`. Rules: - A `/sync` changes presence only on a change of state (`apply_sync_presence`), and only a change is sent to other servers (`broadcast_presence_edu`); a sync loop must never cost a row, a stream position or an EDU per poll. +- Each device's `set_presence` is noted in `HomeserverRuntime::presence_tracker` (`AccountPresenceTracker`, ADR-0875): + a device that asked for `online` in the last 5 minutes holds the account online, so a sync asking for `unavailable` + then changes nothing and never raises the account; `offline` forgets the device. The idle sweep prunes the table. +- A change of an account's presence starts a 5 s window in which no other change is kept (ADR-0876): a sync's is + dropped, a `PUT /presence` is 429 (`set_presence` returns `PresenceWrite`). Judge and note it under `runtime.mutex` + with the write, and keep the first change, never the last. The idle sweep and the profile propagation are not + limited. A new path that changes a local user's presence state is limited the same way. A parked poll's rerun + (`ClientServerDispatchOptions::sync_rerun`) never applies `set_presence` again, or a dropped change would be kept + once the window ends. Tests move the clock with `test_presence_clock_advance_ms`, never with a sleep. A change + refused because the tracker is full (`is_full_for`) calls `note_full_refusal`, and every path that uses the tracker + ends with `report_presence_tracker_saturation`, which logs the rate-limited `presence.tracker.full` warning of + refusals and evictions (`apply_sync_presence` does it once, after `judge_sync_presence`); a new path does too. +- A classic `/sync` whose only news is the caller's own presence row waits on (`only_own_presence_since`, ADR-0873): + never wake a poll for what its response does not send. - `accept_inbound_presence` binds `user_id` to the sending origin, bounds the entries it looks at, and keeps only users who share a joined room with a local user (one pass over the memberships per EDU). A new field accepted from the EDU needs a bound. diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp new file mode 100644 index 000000000..8a16ecb75 --- /dev/null +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -0,0 +1,292 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "merovingian/homeserver/AccountPresenceTracker.hpp" + +#include +#include + +namespace merovingian::homeserver +{ +namespace +{ + + // True when a device last seen at `seen_at_ms` still speaks for its account at `now_ms`. A time ahead of `now_ms` + // (which the clock does not produce) counts as just seen. + [[nodiscard]] auto device_is_fresh(std::int64_t seen_at_ms, std::int64_t now_ms) noexcept -> bool + { + return now_ms <= seen_at_ms || now_ms - seen_at_ms < AccountPresenceTracker::device_fresh_ms; + } + + // True when a window started at `changed_at_ms` has ended at `now_ms`. + [[nodiscard]] auto window_has_ended(std::optional changed_at_ms, std::int64_t now_ms) noexcept -> bool + { + return !changed_at_ms.has_value() || + (now_ms > *changed_at_ms && now_ms - *changed_at_ms >= AccountPresenceTracker::change_window_ms); + } + + // `at_ms + by_ms`, held at the largest value instead of overflowing. + [[nodiscard]] auto saturating_after(std::int64_t at_ms, std::int64_t by_ms) noexcept -> std::int64_t + { + return at_ms > std::numeric_limits::max() - by_ms ? std::numeric_limits::max() + : at_ms + by_ms; + } + +} // namespace + +AccountPresenceTracker::AccountPresenceTracker(std::size_t account_cap) noexcept + : m_account_cap{std::max(account_cap, std::size_t{1U})} +{ +} + +auto AccountPresenceTracker::refile(Accounts::iterator entry, std::int64_t now_ms) -> void +{ + auto& account = entry->second; + auto const lowest = std::numeric_limits::min(); + auto const window_end_ms = + account.changed_at_ms.has_value() ? saturating_after(*account.changed_at_ms, change_window_ms) : lowest; + auto const window_open = window_end_ms > now_ms; + // A closed account matters until its latest online device is stale and its window has ended. A device whose last + // ask was unavailable speaks for nothing (`note_sync` answers from online devices only), so it never keeps an + // account. + auto filed_at_ms = window_end_ms; + if (!window_open) + { + for (auto const& held : account.devices) + { + if (held.online) + { + filed_at_ms = std::max(filed_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + } + } + } + (account.window_open ? m_open_windows : m_closed).erase(FiledKey{account.filed_at_ms, entry->first}); + account.window_open = window_open; + account.filed_at_ms = filed_at_ms; + (window_open ? m_open_windows : m_closed).emplace(filed_at_ms, entry->first); +} + +auto AccountPresenceTracker::close_ended_windows(std::int64_t now_ms) -> void +{ + while (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms) + { + // Refiling erases this front entry, so the loop always moves on. Each visit counts, so a prune that closed + // windows not yet ended would show in `accounts_examined`. + ++m_accounts_examined; + auto const ended = m_accounts.find(m_open_windows.begin()->second); + if (ended == m_accounts.end()) + { + m_open_windows.erase(m_open_windows.begin()); + continue; + } + refile(ended, now_ms); + } +} + +auto AccountPresenceTracker::has_room(std::int64_t now_ms) const noexcept -> bool +{ + return m_accounts.size() < m_account_cap || !m_closed.empty() || + (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms); +} + +auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator +{ + if (auto const found = m_accounts.find(user); found != m_accounts.end()) + { + return found; + } + if (m_accounts.size() >= m_account_cap) + { + prune(now_ms); + } + if (m_accounts.size() >= m_account_cap) + { + if (m_closed.empty()) + { + // Every account has an open window: evicting one would lift its limit. + return m_accounts.end(); + } + // The account whose devices go stale soonest loses their holds; it has no window to lose. + auto const evicted = m_closed.begin(); + ++m_accounts_examined; + ++m_evictions; + m_accounts.erase(evicted->second); + m_closed.erase(evicted); + } + auto const made = m_accounts.try_emplace(std::string{user}).first; + made->second.filed_at_ms = std::numeric_limits::min(); + m_closed.emplace(made->second.filed_at_ms, made->first); + return made; +} + +auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) + -> bool +{ + // A device asking for unavailable holds nothing, so an account the table does not hold takes no place for it and + // never evicts another account's hold to make one. + auto const tracked = m_accounts.find(user); + if (tracked == m_accounts.end() && !online) + { + return false; + } + auto const entry = tracked != m_accounts.end() ? tracked : account_for(user, now_ms); + if (entry == m_accounts.end()) + { + // No room (fails closed): nothing is recorded, so no device the table holds asks for anything. + return false; + } + auto& devices = entry->second.devices; + // A stale device speaks for nothing; dropping it here keeps an account that keeps syncing from holding them. + std::erase_if(devices, [now_ms](Device const& held) { + return !device_is_fresh(held.seen_at_ms, now_ms); + }); + auto const same_device = [device](Device const& held) { + return held.id == device; + }; + if (auto const held = std::ranges::find_if(devices, same_device); held != devices.end()) + { + held->seen_at_ms = now_ms; + held->online = online; + } + else if (devices.size() < max_devices_per_account || make_device_place(devices, online)) + { + devices.push_back(Device{std::string{device}, now_ms, online}); + } + refile(entry, now_ms); + return std::ranges::any_of(devices, [](Device const& held) { + return held.online; + }); +} + +auto AccountPresenceTracker::make_device_place(std::vector& devices, bool online) -> bool +{ + auto victim = devices.end(); + for (auto held = devices.begin(); held != devices.end(); ++held) + { + if (!held->online && (victim == devices.end() || held->seen_at_ms < victim->seen_at_ms)) + { + victim = held; + } + } + if (victim == devices.end() && online) + { + // Every device asked for online: the newcomer holds the account online as well as the one it replaces. + victim = std::ranges::min_element(devices, std::ranges::less{}, &Device::seen_at_ms); + } + if (victim == devices.end()) + { + return false; + } + devices.erase(victim); + return true; +} + +auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device, std::int64_t now_ms) -> void +{ + auto const found = m_accounts.find(user); + if (found == m_accounts.end()) + { + return; + } + std::erase_if(found->second.devices, [device](Device const& held) { + return held.id == device; + }); + refile(found, now_ms); +} + +auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const + -> std::optional +{ + auto const found = m_accounts.find(user); + if (found == m_accounts.end()) + { + // No window to wait for, unless there is no room to start one: then the change is refused (fails closed) until + // the soonest window ends, which is later than now since every window is open. + if (is_full_for(user, now_ms)) + { + return m_open_windows.begin()->first - now_ms; + } + return std::nullopt; + } + auto const changed_at_ms = found->second.changed_at_ms; + if (!changed_at_ms.has_value() || window_has_ended(changed_at_ms, now_ms)) + { + return std::nullopt; + } + auto const started_ms = changed_at_ms.value(); + // A start ahead of `now_ms` (which the clock does not produce) is waited for in full, never longer. + auto const elapsed = now_ms > started_ms ? now_ms - started_ms : std::int64_t{0}; + return change_window_ms - elapsed; +} + +auto AccountPresenceTracker::is_full_for(std::string_view user, std::int64_t now_ms) const -> bool +{ + return !has_room(now_ms) && !m_accounts.contains(user); +} + +auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now_ms) -> void +{ + if (auto const entry = account_for(user, now_ms); entry != m_accounts.end()) + { + entry->second.changed_at_ms = now_ms; + refile(entry, now_ms); + } +} + +auto AccountPresenceTracker::prune(std::int64_t now_ms) -> void +{ + close_ended_windows(now_ms); + while (!m_closed.empty() && m_closed.begin()->first <= now_ms) + { + auto const soonest = m_closed.begin(); + ++m_accounts_examined; + m_accounts.erase(soonest->second); + m_closed.erase(soonest); + } +} + +auto AccountPresenceTracker::account_count() const noexcept -> std::size_t +{ + return m_accounts.size(); +} + +auto AccountPresenceTracker::accounts_examined() const noexcept -> std::uint64_t +{ + return m_accounts_examined; +} + +auto AccountPresenceTracker::account_cap() const noexcept -> std::size_t +{ + return m_account_cap; +} + +auto AccountPresenceTracker::note_full_refusal() noexcept -> void +{ + ++m_full_refusals; +} + +auto AccountPresenceTracker::full_refusals() const noexcept -> std::uint64_t +{ + return m_full_refusals; +} + +auto AccountPresenceTracker::evictions() const noexcept -> std::uint64_t +{ + return m_evictions; +} + +auto AccountPresenceTracker::take_saturation_report(std::int64_t now_ms) -> std::optional +{ + auto const report = SaturationReport{m_full_refusals - m_reported_refusals, m_evictions - m_reported_evictions}; + if ((report.refused == 0U && report.evicted == 0U) || + (m_reported_at_ms.has_value() && now_ms - m_reported_at_ms.value() < full_warning_interval_ms)) + { + return std::nullopt; + } + m_reported_refusals = m_full_refusals; + m_reported_evictions = m_evictions; + m_reported_at_ms = now_ms; + return report; +} + +} // namespace merovingian::homeserver diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index f38cbd32e..1d0bc02f6 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -80,6 +80,7 @@ #include "merovingian/federation/PublicRoomsRefusal.hpp" #include "merovingian/federation/Security.hpp" #include "merovingian/homeserver/AccountPage.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/AppserviceDelivery.hpp" #include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/homeserver/AuthService.hpp" @@ -122,6 +123,8 @@ #include "merovingian/homeserver/PasswordReset.hpp" #include "merovingian/homeserver/PresenceReadStatus.hpp" #include "merovingian/homeserver/PresenceService.hpp" +#include "merovingian/homeserver/PresenceWrite.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include "merovingian/homeserver/PublicRooms.hpp" #include "merovingian/homeserver/PushRuleUnreadClassifier.hpp" #include "merovingian/homeserver/RecentlyUnreachableServers.hpp" @@ -7080,6 +7083,20 @@ namespace joined_room.push_back(json_member(std::string{events::unstable_sticky_field}, section)); } + // True when the one sync stream position after `since` is `user`'s own presence row (ADR-0873). A /sync never sends + // the caller their own presence (`build_sync_presence_events`), so its response would hold nothing new. Only one + // position is judged: with any other after `since` the sync answers, as before. + [[nodiscard]] auto only_own_presence_since(database::PersistentStore const& store, std::string_view user, + std::uint64_t since) -> bool + { + if (store.next_sync_stream_id <= since || store.next_sync_stream_id - since != 1U) + { + return false; + } + auto const* const own = database::find_presence_state(store, user); + return own != nullptr && own->stream_id == store.next_sync_stream_id; + } + [[nodiscard]] auto sync_json(ClientServerRuntime& rt, std::string_view user, std::string_view device_id, core::SyncRequest const& request, bool can_wait = true) -> DispatchResult { @@ -7128,17 +7145,25 @@ namespace // Spec §9.4: omitting `timeout` means respond immediately — no default. // HTTP-4: cap the client-supplied timeout so a single sync cannot pin a // worker indefinitely; the client receives the capped wait. - if (can_wait && request.timeout.has_value() && *request.timeout > 0U) + // Spec (GET /sync, `full_state`): with it true "the `timeout` parameter will be ignored and the query will + // return immediately", so such a sync never waits. + if (can_wait && !request.full_state.value_or(false) && request.timeout.has_value() && *request.timeout > 0U) { auto const capped_timeout_ms = std::min(*request.timeout, sync::k_max_sync_timeout_ms); auto const has_timeline_advance = visible_stream_position(rt.homeserver.database) > since_ordering; auto const has_sync_advance = store.next_sync_stream_id > since_sync_stream_id; - if (!has_timeline_advance && !has_sync_advance) - { + // ADR-0873: the caller's own presence row is never in their response, so a sync whose only news it is + // waits on, past it, rather than answering nothing and being sent again at once. + auto const only_own_presence = + since_token.has_value() && only_own_presence_since(store, user, since_sync_stream_id); + if (!has_timeline_advance && (!has_sync_advance || only_own_presence)) + { + // Only the caller's own presence row moves the cursor; otherwise it stays at `since`, never behind it. + auto const wait_sync_stream_id = only_own_presence ? store.next_sync_stream_id : since_sync_stream_id; return DispatchResult{ DispatchResult::Status::needs_wait, {}, - {since_ordering, since_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, + {since_ordering, wait_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, std::string{user}, std::string{device_id}} }; } @@ -8682,6 +8707,17 @@ namespace return false; } + // A token from this stream epoch and not ahead of the live watermarks (ADR-0592): the only kind a sliding sync + // serves. The dispatcher asks it too, before it applies `set_presence`, so a request this refuses changes nothing. + [[nodiscard]] auto sliding_sync_token_is_current(HomeserverRuntime const& runtime, + sync::StreamToken const& token) -> bool + { + auto const& store = runtime.database.persistent_store; + auto const event_watermark = visible_stream_position(runtime.database); + return token.epoch == store.stream_token_epoch && token.event_ordering <= event_watermark && + token.membership_ordering <= event_watermark && token.sync_stream_id <= store.next_sync_stream_id; + } + [[nodiscard]] auto sliding_sync_json(ClientServerRuntime& rt, std::string_view user, std::string_view device_id, sync::SlidingSyncRequest const& ssreq, std::optional const& request_pos, @@ -8724,8 +8760,7 @@ namespace { auto const event_watermark = visible_stream_position(rt.homeserver.database); auto const sync_watermark = store.next_sync_stream_id; - if (pos->epoch != store.stream_token_epoch || pos->event_ordering > event_watermark || - pos->membership_ordering > event_watermark || pos->sync_stream_id > sync_watermark) + if (!sliding_sync_token_is_current(rt.homeserver, *pos)) { // Drop the connection state: the client restarts with no pos // and must receive a full initial snapshot. @@ -22360,7 +22395,14 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, *presence_mode); changed.has_value()) + // ADR-0876: applied on the request's first run only. A rerun of a parked poll is the same request, and a + // change the window dropped stays dropped, never kept once the window has ended. Every refusal of a /sync is + // above this line: `sync_json` serves any `since` (one it cannot use as no `since`, ADR-0315) and filter it is + // given, so a refused request never changes presence. Keep any new refusal above it. + if (auto const changed = dispatch_options.sync_rerun + ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id, *presence_mode); + changed.has_value()) { log_diagnostic("presence.sync.set", { {"actor", *user, false}, @@ -22422,15 +22464,6 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, *sliding_presence_mode); changed.has_value()) - { - log_diagnostic("presence.sync.set", { - {"actor", *user, false}, - {"presence", changed->presence, false} - }); - broadcast_presence_edu(rt.homeserver, *changed); - std::ignore = ensure_sync_notifier(rt); - } // Prefer query-string pos/timeout; fall back to the newer body-level fields. MSC4186: "Servers MUST reject a // `pos` that was not issued to the requesting user and device, responding with `M_UNKNOWN_POS`": a pos with no // valid binding to this user and device, or one that does not read as a position, is refused whole, never @@ -22457,6 +22490,23 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_UNKNOWN_POS", "unknown sliding sync position"); } } + // ADR-0876: on the request's first run only, as for /sync, and only for a `pos` that is bound and current (the + // check `sliding_sync_json` refuses with M_UNKNOWN_POS), so a refused request changes no presence and opens no + // window. + auto const pos_is_current = !pos.has_value() || sliding_sync_token_is_current(rt.homeserver, pos->token); + if (auto const changed = + dispatch_options.sync_rerun || !pos_is_current + ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id_4186, *sliding_presence_mode); + changed.has_value()) + { + log_diagnostic("presence.sync.set", { + {"actor", *user, false}, + {"presence", changed->presence, false} + }); + broadcast_presence_edu(rt.homeserver, *changed); + std::ignore = ensure_sync_notifier(rt); + } // MSC4186 `timeout`: "Ignored when no `pos` is set": a request without one is answered at once (ADR-0865). auto const timeout = pos.has_value() @@ -24387,7 +24437,23 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp state.status_msg = status_msg != nullptr ? *status_msg : std::string{}; state.last_active_ago = 0; state.currently_active = (presence_state == "online"); - if (!set_presence(rt, state)) + auto const written = set_presence(rt, state); + if (written.status == PresenceWriteStatus::limited) + { + // ADR-0876: the spec's 429 for this endpoint. The change is refused, not kept for later. + log_diagnostic("presence.set.limited", + { + {"actor", *user, false}, + {"presence", presence_state, false}, + {"cause", written.tracker_full ? "tracker_full" : "window", false}, + {"retry_after_ms", std::to_string(written.retry_after_ms), false} + }); + return dispatch_err(req, rt, 429U, "M_LIMIT_EXCEEDED", + written.tracker_full ? "too many accounts are changing presence" + : "presence changed too recently", + written.retry_after_ms); + } + if (written.status == PresenceWriteStatus::failed) { return dispatch_err(req, rt, 500U, "M_UNKNOWN", "presence persistence failed"); } @@ -25382,22 +25448,40 @@ auto record_device_list_change(ClientServerRuntime& runtime, database::Persisten return stored; } -auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> bool +auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> PresenceWrite { auto guard = RuntimeLock{runtime.homeserver.mutex}; if (!presence_enabled(runtime.homeserver)) { // Nothing is tracked, so there is nothing to fail: the caller's update is accepted and dropped. - return true; + return PresenceWrite{PresenceWriteStatus::stored, 0U}; } - auto const stored = record_presence(runtime.homeserver, state); - if (stored) + auto& tracker = runtime.homeserver.presence_tracker; + auto const clock_ms = presence_limit_clock_ms(runtime.homeserver); + // ADR-0876: judged and noted under the same lock as the write, so two requests at once cannot both be first. + if (auto const blocked = tracker.change_blocked_for_ms(state.user_id, clock_ms); blocked.has_value()) { - std::ignore = ensure_sync_notifier(runtime); - // The servers that share a room with the user are told; the row is as stored just now. - broadcast_presence_edu(runtime.homeserver, state); + // The account's own window, or a full table's soonest one: never longer than the window. + auto const retry_after_ms = std::clamp(*blocked, 1, AccountPresenceTracker::change_window_ms); + auto const tracker_full = tracker.is_full_for(state.user_id, clock_ms); + if (tracker_full) + { + tracker.note_full_refusal(); + } + report_presence_tracker_saturation(runtime.homeserver, clock_ms); + return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), tracker_full}; } - return stored; + if (!record_presence(runtime.homeserver, state)) + { + return PresenceWrite{PresenceWriteStatus::failed, 0U}; + } + tracker.note_change(state.user_id, clock_ms); + // The change may have evicted an account to make room (ADR-0875). + report_presence_tracker_saturation(runtime.homeserver, clock_ms); + std::ignore = ensure_sync_notifier(runtime); + // The servers that share a room with the user are told; the row is as stored just now. + broadcast_presence_edu(runtime.homeserver, state); + return PresenceWrite{PresenceWriteStatus::stored, 0U}; } auto run_presence_idle_sweep(ClientServerRuntime& runtime) -> std::chrono::milliseconds diff --git a/src/homeserver/HttpServer.cpp b/src/homeserver/HttpServer.cpp index 7cf28747d..93693d751 100644 --- a/src/homeserver/HttpServer.cpp +++ b/src/homeserver/HttpServer.cpp @@ -1256,7 +1256,8 @@ namespace -> DispatchResult { return handle_client_server_request( - runtime, request, ClientServerDispatchOptions{.can_wait = can_wait, .rate_limit_admitted = true}); + runtime, request, + ClientServerDispatchOptions{.can_wait = can_wait, .rate_limit_admitted = true, .sync_rerun = true}); } // The long-poll of the transports with no sync pool: one wait for the whole timeout, no peer peek. True when diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 96049d67f..c0059fc21 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -7,18 +7,23 @@ #include "merovingian/canonicaljson/ParseError.hpp" #include "merovingian/canonicaljson/Parser.hpp" #include "merovingian/canonicaljson/Serializer.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" +#include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/homeserver/PresenceRead.hpp" #include "merovingian/homeserver/PresenceReadStatus.hpp" #include "merovingian/homeserver/SyncPresenceMode.hpp" -#include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/observability/LogEventSeverity.hpp" #include "merovingian/observability/SingleLog.hpp" #include "merovingian/sync/SyncFilter.hpp" #include #include +#include #include #include +#include +#include +#include #include #include #include @@ -27,6 +32,14 @@ namespace merovingian::homeserver { + +// ADR-0875: a device's online ask goes stale exactly when the idle sweep would set its account unavailable. With the +// two apart, a background device's `unavailable` would win while the sweep still counts the user active, or a closed +// client would hold the account online past the sweep. This keeps the durations equal; the hold runs on the steady +// clock and the sweep on the wall clock, so a wall-clock step still moves them apart by the step (accepted in the ADR). +static_assert(AccountPresenceTracker::device_fresh_ms == presence_idle_timeout_ms, + "a device's online ask must last exactly as long as the idle timeout"); + namespace { @@ -129,6 +142,31 @@ auto presence_now_ms() -> std::int64_t .count(); } +auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t +{ + auto const steady_ms = + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); + return static_cast(steady_ms) + runtime.test_presence_clock_advance_ms; +} + +auto report_presence_tracker_saturation(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void +{ + auto& tracker = runtime.presence_tracker; + if (auto const report = tracker.take_saturation_report(clock_ms); report.has_value()) + { + // Aggregate only: the operator learns the tracker saturated, never which accounts were refused or evicted. + log_presence("presence.tracker.full", + { + {"refused", std::to_string(report->refused), false}, + {"evicted", std::to_string(report->evicted), false}, + {"accounts", std::to_string(tracker.account_count()), false}, + {"limit", std::to_string(tracker.account_cap()), false} + }, + observability::LogEventSeverity::warning); + } +} + auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept -> std::int64_t { auto ago = std::max(row.last_active_ago, std::int64_t{0}); @@ -196,6 +234,10 @@ auto expire_idle_presence(HomeserverRuntime& runtime, std::int64_t now_ms, std:: { return changed; } + // The pass also drops the devices and change windows that no longer speak for an account (ADR-0875). Its own + // changes are neither limited nor noted: the server sets an account idle at most once per idle period, and a user + // who comes back at once is marked online at once. + runtime.presence_tracker.prune(presence_limit_clock_ms(runtime)); // Chosen first, written after: recording a row must not run while the rows are being walked. At most `max_changes` // are chosen; the rest are found by the next pass. auto idle = std::vector{}; @@ -297,44 +339,102 @@ auto parse_sync_presence_mode(std::optional value) noexcept -> return std::nullopt; } -auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, SyncPresenceMode mode) - -> std::optional +namespace { - if (mode == SyncPresenceMode::offline || !presence_enabled(runtime)) - { - return std::nullopt; - } - auto& store = runtime.database.persistent_store; - auto const now_ms = presence_now_ms(); - auto const desired = - mode == SyncPresenceMode::online ? std::string_view{"online"} : std::string_view{"unavailable"}; - auto const existing = std::ranges::find_if(store.presence_states, [user](database::PersistentPresence const& row) { - return row.user_id == user; - }); - if (existing != store.presence_states.end() && existing->presence == desired) + + // `apply_sync_presence` without the saturation report, so the report is made once, after every way out. + [[nodiscard]] auto judge_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional { - if (mode == SyncPresenceMode::online) + if (!presence_enabled(runtime)) { - // Still online: nothing to tell anyone, but the user did just do something. - existing->last_active_ago = 0; - existing->observed_at_ms = now_ms; - existing->currently_active = true; + return std::nullopt; } - return std::nullopt; - } - auto row = existing != store.presence_states.end() ? *existing : database::PersistentPresence{}; - row.user_id = std::string{user}; - row.presence = std::string{desired}; - row.last_active_ago = mode == SyncPresenceMode::online || existing == store.presence_states.end() - ? std::int64_t{0} - : presence_last_active_ago(*existing, now_ms); - row.currently_active = mode == SyncPresenceMode::online; - if (!record_presence(runtime, row)) - { - return std::nullopt; + auto& tracker = runtime.presence_tracker; + auto const clock_ms = presence_limit_clock_ms(runtime); + if (mode == SyncPresenceMode::offline) + { + // "offline": the client is not to be marked online, so it no longer holds the account online either. + tracker.forget_device(user, device, clock_ms); + return std::nullopt; + } + auto const asks_online = mode == SyncPresenceMode::online; + auto const any_device_online = tracker.note_sync(user, device, asks_online, clock_ms); + if (!asks_online && any_device_online) + { + // ADR-0875: another device of the account asked for online in the freshness time; online beats unavailable. + // Logged only when the ask would have changed the stored state: an account already unavailable loses + // nothing. + if (auto const* const row = database::find_presence_state(runtime.database.persistent_store, user); + row == nullptr || row->presence != "unavailable") + { + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", "unavailable", false}, + {"cause", "device_online", false} + }); + } + return std::nullopt; + } + auto& store = runtime.database.persistent_store; + auto const now_ms = presence_now_ms(); + auto const desired = asks_online ? std::string_view{"online"} : std::string_view{"unavailable"}; + auto* const existing = database::find_mutable_presence_state(store, user); + if (existing != nullptr && existing->presence == desired) + { + if (asks_online) + { + // Still online: nothing to tell anyone, but the user did just do something. + existing->last_active_ago = 0; + existing->observed_at_ms = now_ms; + existing->currently_active = true; + } + return std::nullopt; + } + if (auto const blocked = tracker.change_blocked_for_ms(user, clock_ms); blocked.has_value()) + { + // ADR-0876: the first change in the window was kept, or the tracker has no room for the account; this one + // is dropped, not kept for later. + auto const tracker_full = tracker.is_full_for(user, clock_ms); + if (tracker_full) + { + tracker.note_full_refusal(); + } + auto const cause = std::string{tracker_full ? "tracker_full" : "window"}; + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", std::string{desired}, false}, + {"cause", cause, false}, + {"retry_after_ms", std::to_string(*blocked), false} + }); + return std::nullopt; + } + auto row = existing != nullptr ? *existing : database::PersistentPresence{}; + row.user_id = std::string{user}; + row.presence = std::string{desired}; + row.last_active_ago = + asks_online || existing == nullptr ? std::int64_t{0} : presence_last_active_ago(*existing, now_ms); + row.currently_active = asks_online; + if (!record_presence(runtime, row)) + { + return std::nullopt; + } + tracker.note_change(user, clock_ms); + row.observed_at_ms = now_ms; + return row; } - row.observed_at_ms = now_ms; - return row; + +} // namespace + +auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional +{ + auto changed = judge_sync_presence(runtime, user, device, mode); + // ADR-0876: an eviction (by the sync's online ask or its change) or a refusal made above is reported here. + report_presence_tracker_saturation(runtime, presence_limit_clock_ms(runtime)); + return changed; } auto build_sync_presence_events(database::PersistentStore const& store, sync::EventTypeFilter const& filter, diff --git a/src/homeserver/meson.build b/src/homeserver/meson.build index 0c8d9b076..b38d76e5b 100644 --- a/src/homeserver/meson.build +++ b/src/homeserver/meson.build @@ -14,6 +14,7 @@ homeserver_sources = files( 'PendingAuthorisationStore.cpp', 'DeviceAuthorisationStore.cpp', 'UserCodeAttemptThrottle.cpp', + 'AccountPresenceTracker.cpp', 'RequestHeaders.cpp', 'SafetyReportIndex.cpp', 'RetentionSweep.cpp', diff --git a/tests/conformance/test_client_server_conformance.cpp b/tests/conformance/test_client_server_conformance.cpp index 4cb1a81fe..30695a595 100644 --- a/tests/conformance/test_client_server_conformance.cpp +++ b/tests/conformance/test_client_server_conformance.cpp @@ -49,6 +49,7 @@ #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include #include @@ -3104,7 +3105,8 @@ SCENARIO("GET /sync returns the full top-level v1.19 sync envelope", "[conforman REQUIRE(merovingian::homeserver::record_device_list_change(started.runtime, {0U, user_id, "@carol:example.org", "left"})); REQUIRE(merovingian::homeserver::set_presence(started.runtime, - {0U, "@dave:example.org", "online", "Coding!", 1000U, true})); + {0U, "@dave:example.org", "online", "Coding!", 1000U, true}) + .status == merovingian::homeserver::PresenceWriteStatus::stored); REQUIRE( merovingian::database::store_one_time_key(started.runtime.homeserver.database.persistent_store, {user_id, "DEVICE1", "signed_curve25519:AAA", R"({"key":"x"})"})); diff --git a/tests/integration/test_database_nul_remaining_query_flow.cpp b/tests/integration/test_database_nul_remaining_query_flow.cpp index 11cfcc6b0..ec7a4dc4c 100644 --- a/tests/integration/test_database_nul_remaining_query_flow.cpp +++ b/tests/integration/test_database_nul_remaining_query_flow.cpp @@ -5,9 +5,9 @@ #include "../support/TempDirectory.hpp" #include "merovingian/canonicaljson/CanonicalJsonError.hpp" #include "merovingian/canonicaljson/ParseError.hpp" -#include "merovingian/canonicaljson/Value.hpp" #include "merovingian/canonicaljson/Parser.hpp" #include "merovingian/canonicaljson/Serializer.hpp" +#include "merovingian/canonicaljson/Value.hpp" #include "merovingian/config/ClientRateLimitsConfig.hpp" #include "merovingian/config/Config.hpp" #include "merovingian/config/DatabaseBackend.hpp" @@ -20,13 +20,14 @@ #include "merovingian/database/ExaminedRows.hpp" #include "merovingian/database/PersistentStore.hpp" #include "merovingian/database/PersistentStoreOpenResult.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" +#include "merovingian/homeserver/AuthService.hpp" #include "merovingian/homeserver/ClientServerClock.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/CreateRoomOptions.hpp" #include "merovingian/homeserver/LocalHttpRequest.hpp" #include "merovingian/homeserver/LocalHttpResponse.hpp" -#include "merovingian/homeserver/AuthService.hpp" #include "merovingian/homeserver/RoomService.hpp" #include @@ -287,6 +288,8 @@ SCENARIO("Profile, presence and room identities ignore unrelated raw query text" {"avatar_url", avatar_url} })); } + // Each case changes the presence, so the change window of the last one is let end (ADR-0876). + runtime.homeserver.test_presence_clock_advance_ms += hs::AccountPresenceTracker::change_window_ms; std::ignore = send_request("PUT", presence_path + with_marker("/status"), "{\"presence\":\"" + presence + "\",\"status_msg\":\"" + status_msg + "\"}"); diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index 030c44c49..c0866b7a4 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -30,8 +30,10 @@ #include "merovingian/federation/EduDispositionStatus.hpp" #include "merovingian/federation/EduType.hpp" #include "merovingian/federation/InboundEduEnvelope.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" +#include "merovingian/homeserver/DispatchResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" #include "merovingian/homeserver/PresenceService.hpp" @@ -203,6 +205,18 @@ auto install_unstarted_dispatch_worker(ClientServerRuntime& runtime) -> void std::string{presence} + R"(","last_active_ago":5000)" + std::string{extra} + "}]}"; } +// The clock of the presence change window and of the devices' freshness moves on without a sleep (ADR-0875, ADR-0876). +auto advance_presence_clock(ClientServerRuntime& runtime, std::int64_t by_ms) -> void +{ + runtime.homeserver.test_presence_clock_advance_ms += by_ms; +} + +// Lets the window opened by the last presence change end, so the next change is kept. +auto let_presence_window_end(ClientServerRuntime& runtime) -> void +{ + advance_presence_clock(runtime, merovingian::homeserver::AccountPresenceTracker::change_window_ms); +} + [[nodiscard]] auto sync_presence_senders(ClientServerRuntime& runtime, std::string const& token) -> std::vector { @@ -544,7 +558,8 @@ namespace constexpr auto minute_ms = std::int64_t{60 * 1000}; // Presence rows hold when they were last observed; moving that back is the passage of time without a -// sleep. The row is changed in place, as `record_presence` would restamp it. +// sleep. The row is changed in place, as `record_presence` would restamp it. The clock of the change window and of +// the devices' freshness (ADR-0875, ADR-0876) moves on by as much. auto age_presence(ClientServerRuntime& runtime, std::string_view user_id, std::int64_t by_ms) -> void { for (auto& row : runtime.homeserver.database.persistent_store.presence_states) @@ -554,6 +569,7 @@ auto age_presence(ClientServerRuntime& runtime, std::string_view user_id, std::i row.observed_at_ms -= by_ms; } } + advance_presence_clock(runtime, by_ms); } [[nodiscard]] auto read_alice_presence(ClientServerRuntime& runtime, std::string const& token) -> std::string @@ -637,6 +653,7 @@ SCENARIO("A user idle past the presence threshold is set unavailable", "[integra WHEN("alice set herself offline, a long time ago, and the idle sweep runs") { + let_presence_window_end(runtime); REQUIRE(put_alice_presence(runtime, token, R"({"presence":"offline"})").status == 200U); age_presence(runtime, local_alice, 60 * minute_ms); std::ignore = merovingian::homeserver::run_presence_idle_sweep(runtime); @@ -710,6 +727,7 @@ SCENARIO("A user who keeps sending messages is not set unavailable", "[integrati WHEN("she is unavailable by her own choice and sends a message") { + let_presence_window_end(runtime); REQUIRE(put_alice_presence(runtime, token, R"({"presence":"unavailable"})").status == 200U); REQUIRE(send(1).status == 200U); @@ -924,3 +942,587 @@ SCENARIO("Sliding sync honours set_presence", "[integration][presence][sliding-s } } } + +namespace +{ + +// A second device of alice's, for the scenarios where two clients of one account sync at once. +[[nodiscard]] auto log_alice_in_on(ClientServerRuntime& runtime, std::string_view device_id) -> std::string +{ + auto const login = call(runtime, "POST", "/_matrix/client/v3/login", {}, + R"({"type":"m.login.password","identifier":{"type":"m.id.user","user":"alice"},)" + R"("password":"CorrectHorse7!","device_id":")" + + std::string{device_id} + R"("})"); + REQUIRE(login.status == 200U); + auto const body = parse_object(login.body); + auto const* token = string_member(body, "access_token"); + REQUIRE(token != nullptr); + return *token; +} + +// A /sync that answers at once, asking for `mode` (online, unavailable or offline). +auto sync_once(ClientServerRuntime& runtime, std::string const& token, std::string_view mode) -> void +{ + REQUIRE(call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=" + std::string{mode}, token).status == + 200U); +} + +[[nodiscard]] auto alice_presence_state(ClientServerRuntime const& runtime) -> std::string +{ + auto const row = stored_presence(runtime, local_alice); + return row.has_value() ? row->presence : std::string{"none"}; +} + +} // namespace + +// Spec: Matrix Client-Server API v1.19, Presence, "Idle timeout": "Any activity that bumps the last active time on any +// of the user's clients will cause the server to automatically set their presence to `online`." +// +// ADR-0875: a device that syncs online holds the account online for AccountPresenceTracker::device_fresh_ms, so another +// device syncing unavailable does not set it unavailable in between. Without this, a client in the foreground and one +// in the background set the presence back and forth on every sync, each change waking the other's sync and queueing an +// EDU for every server in the user's rooms. +SCENARIO("Two devices of one account syncing online and unavailable do not set its presence back and forth", + "[integration][presence][sync][devices]") +{ + GIVEN("alice shares a room with bob on another server and her desktop has synced online") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const desktop = register_alice(runtime); + auto const phone = log_alice_in_on(runtime, "PHONE"); + share_room_with_remote_bob(runtime); + sync_once(runtime, desktop, "online"); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("her phone syncs unavailable and her desktop online, in turn, with every change window ended") + { + for (auto round = 0; round < 10; ++round) + { + let_presence_window_end(runtime); + sync_once(runtime, phone, "unavailable"); + let_presence_window_end(runtime); + sync_once(runtime, desktop, "online"); + } + + THEN("she stays online and bob's server was told once") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("her desktop stops syncing for longer than a device holds the account and her phone syncs unavailable") + { + advance_presence_clock(runtime, merovingian::homeserver::AccountPresenceTracker::device_fresh_ms); + sync_once(runtime, phone, "unavailable"); + + THEN("she is unavailable and bob's server is told") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("her desktop syncs with set_presence=offline and then her phone syncs unavailable") + { + sync_once(runtime, desktop, "offline"); + let_presence_window_end(runtime); + sync_once(runtime, phone, "unavailable"); + + THEN("the desktop no longer holds her online, so she is unavailable") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + } + } + } +} + +// ADR-0876: the first change of an account's presence opens a window of AccountPresenceTracker::change_window_ms in +// which no other change is kept: a sync's is dropped, a PUT is answered 429 M_LIMIT_EXCEEDED, which the spec gives this +// endpoint. The first change asked for is the one kept, never the last. +// +// Spec: Matrix Client-Server API v1.19, PUT /_matrix/client/v3/presence/{userId}/status, responses 200 and 429. +SCENARIO("Only the first presence change in a window is kept", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server and has just synced online") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + sync_once(runtime, token, "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + auto const& store = runtime.homeserver.database.persistent_store; + auto const watermark = store.next_sync_stream_id; + + WHEN("she syncs unavailable at once") + { + sync_once(runtime, token, "unavailable"); + + THEN("the change is dropped: nothing is stored, woken or sent") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("she syncs unavailable once the window has ended") + { + let_presence_window_end(runtime); + sync_once(runtime, token, "unavailable"); + + THEN("the change is kept and bob's server is told") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("she sets her presence at once") + { + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable","status_msg":"away"})"); + + THEN("it is refused with 429 M_LIMIT_EXCEEDED and when to retry, and nothing is stored or sent") + { + REQUIRE(put.status == 429U); + auto const body = parse_object(put.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_LIMIT_EXCEEDED"); + auto const* retry_after_ms = int_member(body, "retry_after_ms"); + REQUIRE(retry_after_ms != nullptr); + REQUIRE(*retry_after_ms > 0); + REQUIRE(*retry_after_ms <= merovingian::homeserver::AccountPresenceTracker::change_window_ms); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("she sets her presence once the window has ended") + { + let_presence_window_end(runtime); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("it is stored and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + } +} + +// ADR-0876: a sync that leaves the stored presence as it is changes nothing, so it opens no window. Without this, a +// client polling /sync (an omitted set_presence asks for online) could never change its presence: every poll would +// open a window, and PUT /presence would answer 429. +SCENARIO("A sync that leaves the presence as it is opens no change window", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server and her change to online has had its window end") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + sync_once(runtime, token, "online"); + let_presence_window_end(runtime); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she syncs online again, which changes nothing, and at once sets her presence unavailable") + { + sync_once(runtime, token, "online"); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("the change is kept and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("she is set unavailable, the window ends, she syncs unavailable, and at once sets her presence online") + { + // Offline forgets the device's online ask, so the unavailable sync below is judged on the stored state + // alone. + sync_once(runtime, token, "offline"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"unavailable"})").status == 200U); + let_presence_window_end(runtime); + sync_once(runtime, token, "unavailable"); + auto const put = put_alice_presence(runtime, token, R"({"presence":"online"})"); + + THEN("the unavailable sync changed nothing, so the change is kept and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 3U); + } + } + } +} + +// A /sync refused with a 400 changes no presence, as a refused sliding sync does not (ADR-0876): the refusal would +// otherwise store a change, send it to every server in the user's rooms and open the window against the user's next +// real change. Every refusal of a /sync comes before its `set_presence` is applied. +SCENARIO("A /sync refused for its filter changes no presence", "[integration][presence][sync]") +{ + GIVEN("alice shares a room with bob on another server and has never set her presence") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + + WHEN("she syncs online with an inline filter that is not JSON and with a filter ID she never stored") + { + auto const not_json = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&filter=%7Bnot", token); + auto const unknown = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&filter=unknown", token); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("both are refused, nothing was stored or sent, and no window stops her next change") + { + REQUIRE(not_json.status == 400U); + REQUIRE(unknown.status == 400U); + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + +// ADR-0876: a change dropped in a window is dropped, never kept for later. A long-polling sync whose change was +// dropped is run again after a wake-up or its timeout (`rerun_waiting_sync`); that rerun is the same request and does +// not apply its `set_presence` again, even once the window has ended. +SCENARIO("A parked sync run again does not apply its set_presence a second time", "[integration][presence][long_poll]") +{ + GIVEN("alice shares a room with bob on another server, set herself online, and holds a next_batch") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + auto const initial = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=offline", token); + REQUIRE(initial.status == 200U); + auto const initial_body = parse_object(initial.body); + auto const* since = string_member(initial_body, "next_batch"); + REQUIRE(since != nullptr); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she long-polls asking for unavailable inside the window, and the poll is run again once it has ended") + { + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&set_presence=unavailable&since=" + *since, token, {}}; + auto const first = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(first.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + let_presence_window_end(runtime); + auto const rerun = merovingian::homeserver::handle_client_server_request( + runtime, long_poll, + merovingian::homeserver::ClientServerDispatchOptions{ + .can_wait = false, .rate_limit_admitted = true, .sync_rerun = true}); + + THEN("the dropped change stays dropped: she is still online and bob's server is told nothing more") + { + REQUIRE(rerun.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + +namespace +{ + +constexpr auto sliding_sync_target = std::string_view{"/_matrix/client/unstable/org.matrix.msc4186/sync"}; + +// The `pos` of a sliding sync that answers at once and leaves alice's presence alone. +[[nodiscard]] auto sliding_sync_pos(ClientServerRuntime& runtime, std::string const& token) -> std::string +{ + auto const synced = call(runtime, "POST", std::string{sliding_sync_target}, token, R"({"set_presence":"offline"})"); + REQUIRE(synced.status == 200U); + auto const body = parse_object(synced.body); + auto const* pos = string_member(body, "pos"); + REQUIRE(pos != nullptr); + return *pos; +} + +} // namespace + +SCENARIO("A parked sliding sync run again does not apply its set_presence a second time", + "[integration][presence][sliding-sync][long_poll]") +{ + GIVEN("alice shares a room with bob on another server, set herself online, and holds a sliding sync pos") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + auto const pos = sliding_sync_pos(runtime, token); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she long-polls asking for unavailable inside the window, and the poll is run again once it has ended") + { + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "POST", std::string{sliding_sync_target} + "?timeout=30000&pos=" + pos, token, + R"({"set_presence":"unavailable"})"}; + auto const first = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(first.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + let_presence_window_end(runtime); + auto const rerun = merovingian::homeserver::handle_client_server_request( + runtime, long_poll, + merovingian::homeserver::ClientServerDispatchOptions{ + .can_wait = false, .rate_limit_admitted = true, .sync_rerun = true}); + + THEN("the dropped change stays dropped: she is still online and bob's server is told nothing more") + { + REQUIRE(rerun.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + +// MSC4186: "Servers MUST reject a `pos` that was not issued to the requesting user and device", and a pos from another +// stream epoch is unknown too (ADR-0592). A refused request does nothing else, so its set_presence opens no ADR-0876 +// window that would make a later PUT /presence 429. +SCENARIO("A sliding sync refused for an unknown pos changes no presence", "[integration][presence][sliding-sync]") +{ + GIVEN("a registered user with no presence row") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const token = register_alice(runtime); + + WHEN("she sliding-syncs with a pos this server never issued, asking for unavailable") + { + auto const refused = call(runtime, "POST", std::string{sliding_sync_target} + "?pos=not-issued", token, + R"({"set_presence":"unavailable"})"); + + THEN("it is 400 M_UNKNOWN_POS, nothing is stored, and her presence may be set at once") + { + REQUIRE(refused.status == 400U); + auto const body = parse_object(refused.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_UNKNOWN_POS"); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + } + } + + WHEN("she sliding-syncs with a pos this server issued before a restore moved the stream epoch on") + { + auto const pos = sliding_sync_pos(runtime, token); + runtime.homeserver.database.persistent_store.stream_token_epoch += 1U; + auto const refused = call(runtime, "POST", std::string{sliding_sync_target} + "?pos=" + pos, token, + R"({"set_presence":"unavailable"})"); + + THEN("it is 400 M_UNKNOWN_POS, nothing is stored, and her presence may be set at once") + { + REQUIRE(refused.status == 400U); + auto const body = parse_object(refused.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_UNKNOWN_POS"); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + } + } + } +} + +// ADR-0875: a device is one device whichever sync API it uses, so the hold one transport takes is released by the +// other's set_presence=offline. +SCENARIO("A device's hold taken through sliding sync is released by its classic sync", + "[integration][presence][sliding-sync][devices]") +{ + GIVEN("alice's desktop sliding-synced online and she has a phone too") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const desktop = register_alice(runtime); + auto const phone = log_alice_in_on(runtime, "PHONE"); + REQUIRE(call(runtime, "POST", std::string{sliding_sync_target}, desktop, "{}").status == 200U); + REQUIRE(alice_presence_state(runtime) == "online"); + let_presence_window_end(runtime); + + WHEN("the phone syncs asking for unavailable while the desktop holds the account") + { + sync_once(runtime, phone, "unavailable"); + + THEN("she stays online") + { + REQUIRE(alice_presence_state(runtime) == "online"); + } + } + + WHEN("the desktop's classic sync says offline, and then the phone asks for unavailable") + { + sync_once(runtime, desktop, "offline"); + sync_once(runtime, phone, "unavailable"); + + THEN("the desktop no longer holds the account, so she becomes unavailable") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + } + } + } +} + +// ADR-0876: at its cap, with every account in its window, the presence tracker refuses a change of an account it does +// not hold (fails closed), so a flood of accounts cannot lift the limit for itself. The refusal says so and waits for +// the soonest window to end. +SCENARIO("A presence change is refused while the presence tracker is full", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server, and the tracker is full of accounts that just changed") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + using merovingian::homeserver::AccountPresenceTracker; + auto& tracker = runtime.homeserver.presence_tracker; + auto const now_ms = merovingian::homeserver::presence_limit_clock_ms(runtime.homeserver); + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + { + // Started a window ahead, so no window can end while the scenario runs on the live clock. + tracker.note_change("@user" + std::to_string(index) + ":other.example", + now_ms + AccountPresenceTracker::change_window_ms); + } + auto const& store = runtime.homeserver.database.persistent_store; + auto const watermark = store.next_sync_stream_id; + + WHEN("she sets her presence") + { + auto const put = put_alice_presence(runtime, token, R"({"presence":"online"})"); + + THEN("it is 429 naming the full tracker, told to wait for the soonest window, and nothing is kept") + { + REQUIRE(put.status == 429U); + auto const body = parse_object(put.body); + auto const* error = string_member(body, "error"); + REQUIRE(error != nullptr); + REQUIRE(*error == "too many accounts are changing presence"); + auto const* retry_after_ms = int_member(body, "retry_after_ms"); + REQUIRE(retry_after_ms != nullptr); + REQUIRE(*retry_after_ms > 0); + REQUIRE(*retry_after_ms <= AccountPresenceTracker::change_window_ms); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).empty()); + REQUIRE(tracker.full_refusals() == 1U); + } + } + + WHEN("she syncs, which asks for online") + { + sync_once(runtime, token, "online"); + + THEN("the change is dropped: nothing is stored or sent, and the tracker does not grow") + { + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(queued_presence_edus(runtime).empty()); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.full_refusals() == 1U); + } + } + } +} + +// ADR-0873: a /sync never sends the caller their own presence, so a long-poll whose only news is the caller's own +// presence row would be answered with nothing, and its client would sync again at once. It keeps waiting instead, as +// sliding sync does for what its response does not send (ADR-0869). +SCENARIO("A long-polling /sync whose only news is the caller's own presence keeps waiting", + "[integration][presence][sync][long_poll]") +{ + GIVEN("alice has synced with set_presence=offline and holds its next_batch") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const token = register_alice(runtime); + auto const initial = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=offline", token); + REQUIRE(initial.status == 200U); + auto const initial_body = parse_object(initial.body); + auto const* since = string_member(initial_body, "next_batch"); + REQUIRE(since != nullptr); + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&since=" + *since, token, {}}; + auto const& store = runtime.homeserver.database.persistent_store; + + WHEN("she long-polls from it without set_presence, which marks her online") + { + auto const result = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + + THEN("she is online and the sync waits past her own presence row") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + REQUIRE(result.wait.since_sync_stream_id == store.next_sync_stream_id); + } + } + + WHEN("she long-polls from it with full_state=true and nothing new to send") + { + std::ignore = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + auto const full_state = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&full_state=true&since=" + *since, token, {}}; + auto const result = merovingian::homeserver::handle_client_server_request(runtime, full_state); + + THEN("the timeout is ignored and it is answered at once, as the spec requires") + { + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(result.response.status == 200U); + } + } + + WHEN("something else is stored for her after her own presence, and the sync runs again") + { + std::ignore = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(call(runtime, "PUT", "/_matrix/client/v3/user/%40alice%3Aexample.org/account_data/org.example.a", + token, R"({"a":1})") + .status == 200U); + auto const result = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + + THEN("it is answered") + { + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(result.response.status == 200U); + } + } + } +} diff --git a/tests/integration/test_security_audit_presence_flow.cpp b/tests/integration/test_security_audit_presence_flow.cpp index f346cbda2..3a72aaa9f 100644 --- a/tests/integration/test_security_audit_presence_flow.cpp +++ b/tests/integration/test_security_audit_presence_flow.cpp @@ -15,6 +15,7 @@ #include "merovingian/database/ExaminedRows.hpp" #include "merovingian/database/PersistentPresence.hpp" #include "merovingian/database/PersistentStore.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/ClientServerClock.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" @@ -248,6 +249,9 @@ SCENARIO("Sync presence is visible only between users with current shared room m { REQUIRE(set_presence(runtime, localpart, token, R"({"presence":"online"})").status == 200U); } + // Each user's next change is kept, not refused inside the window this one opened (ADR-0876). + runtime.homeserver.test_presence_clock_advance_ms += + merovingian::homeserver::AccountPresenceTracker::change_window_ms; WHEN("Alice performs an initial sync and then an incremental sync after everyone updates presence") { diff --git a/tests/integration/test_sync_handler_flow.cpp b/tests/integration/test_sync_handler_flow.cpp index 43b351a77..2e3276919 100644 --- a/tests/integration/test_sync_handler_flow.cpp +++ b/tests/integration/test_sync_handler_flow.cpp @@ -53,6 +53,7 @@ #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/DispatchResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include "merovingian/homeserver/RoomService.hpp" #include "merovingian/homeserver/WorkerPool.hpp" #include "merovingian/sync/StreamToken.hpp" @@ -256,8 +257,8 @@ SCENARIO("Sync surfaces account_data, to_device, device_lists, presence, and key REQUIRE(merovingian::homeserver::push_to_device_message( rt, {0U, "@bob:example.org", alice_id, device_id, "m.room_key", R"({"session":"abc"})"})); REQUIRE(merovingian::homeserver::record_device_list_change(rt, {0U, alice_id, "@bob:example.org", "changed"})); - REQUIRE( - merovingian::homeserver::set_presence(rt, {0U, "@charlie:example.org", "online", "Coding!", 1000, true})); + REQUIRE(merovingian::homeserver::set_presence(rt, {0U, "@charlie:example.org", "online", "Coding!", 1000, true}) + .status == merovingian::homeserver::PresenceWriteStatus::stored); REQUIRE(merovingian::database::store_one_time_key( store, {alice_id, device_id, "signed_curve25519:AAA", R"({"key":"x"})"})); REQUIRE(merovingian::database::store_one_time_key( diff --git a/tests/meson.build b/tests/meson.build index 85facb0af..0f1970d2d 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -323,6 +323,7 @@ shell = find_program('sh') 'unit/test_resolved_state_memo.cpp', 'unit/test_room_power.cpp', 'unit/test_stored_room_version.cpp', + 'unit/test_account_presence_tracker.cpp', 'unit/test_appservice_client.cpp', 'unit/test_appservice_ephemeral.cpp', 'unit/test_periodic_job.cpp', diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp new file mode 100644 index 000000000..4bce66543 --- /dev/null +++ b/tests/unit/test_account_presence_tracker.cpp @@ -0,0 +1,483 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later + +// ADR-0875 and ADR-0876: what an account's devices last asked of its presence, and the window after a change in which +// no other change is kept. Every operation takes the time, so no scenario sleeps. + +#include "merovingian/homeserver/AccountPresenceTracker.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + +using merovingian::homeserver::AccountPresenceTracker; + +constexpr auto start_ms = std::int64_t{1'000'000}; +constexpr auto alice = std::string_view{"@alice:example.org"}; +constexpr auto bob = std::string_view{"@bob:example.org"}; +constexpr auto phone = std::string_view{"PHONE"}; +constexpr auto desktop = std::string_view{"DESKTOP"}; +// The account cap of the trackers the bound scenarios fill: small, so a full table costs a handful of accounts. The cap +// is the same code at any size. +constexpr auto small_cap = std::size_t{8U}; + +// Fills a tracker of `small_cap` with accounts each held online by a desktop and none with a window open. @user0 synced +// at start_ms and the rest a millisecond later, so @user0's hold goes stale first and is the one a full table evicts. +auto fill_held_online(AccountPresenceTracker& tracker) -> void +{ + std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); + for (auto index = std::size_t{1U}; index < small_cap; ++index) + { + std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); + } +} + +} // namespace + +SCENARIO("A device syncing online holds its account online against a device syncing unavailable", + "[unit][presence][account_presence_tracker]") +{ + GIVEN("alice's desktop synced asking for online") + { + auto tracker = AccountPresenceTracker{}; + REQUIRE(tracker.note_sync(alice, desktop, true, start_ms)); + + WHEN("her phone syncs asking for unavailable a moment later") + { + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 100); + + THEN("a device of the account still asks for online") + { + REQUIRE(any_online); + } + } + + WHEN("her phone syncs asking for unavailable once the desktop has not synced for the freshness time") + { + auto const any_online = + tracker.note_sync(alice, phone, false, start_ms + AccountPresenceTracker::device_fresh_ms); + + THEN("no device asks for online any more") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("the desktop itself syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, desktop, false, start_ms + 100); + + THEN("its earlier ask is replaced, so no device asks for online") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("the desktop syncs with set_presence=offline and the phone asks for unavailable") + { + tracker.forget_device(alice, desktop, start_ms + 100); + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 100); + + THEN("the desktop no longer holds the account online") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("another account's device asks for unavailable") + { + auto const any_online = tracker.note_sync(bob, phone, false, start_ms + 100); + + THEN("alice's desktop does not speak for bob") + { + REQUIRE_FALSE(any_online); + } + } + } +} + +SCENARIO("The first presence change in a window is kept and the rest wait for it to end", + "[unit][presence][account_presence_tracker]") +{ + GIVEN("an account whose presence has not changed") + { + auto tracker = AccountPresenceTracker{}; + + THEN("a change may be kept at once") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(alice, start_ms).has_value()); + } + + WHEN("a change is kept") + { + tracker.note_change(alice, start_ms); + + THEN("another change two seconds later waits for the rest of the window") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 2'000); + REQUIRE(blocked == std::optional{AccountPresenceTracker::change_window_ms - 2'000}); + } + THEN("a change once the window has ended may be kept") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(alice, start_ms + AccountPresenceTracker::change_window_ms) + .has_value()); + } + THEN("another account's change is not held back") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(bob, start_ms + 1).has_value()); + } + } + } +} + +SCENARIO("A prune removes what no longer speaks for an account", "[unit][presence][account_presence_tracker]") +{ + GIVEN("alice changed her presence and synced from one device") + { + auto tracker = AccountPresenceTracker{}; + tracker.note_change(alice, start_ms); + std::ignore = tracker.note_sync(alice, desktop, true, start_ms); + REQUIRE(tracker.account_count() == 1U); + + WHEN("a prune runs inside the window and the freshness time") + { + tracker.prune(start_ms + 1'000); + + THEN("the account is kept") + { + REQUIRE(tracker.account_count() == 1U); + REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 1'000).has_value()); + } + } + + WHEN("a prune runs once the device is stale and the window has ended") + { + tracker.prune(start_ms + AccountPresenceTracker::device_fresh_ms); + + THEN("the account is removed") + { + REQUIRE(tracker.account_count() == 0U); + } + } + } + + GIVEN("bob, whose presence has not changed, synced from a device asking for unavailable") + { + auto tracker = AccountPresenceTracker{}; + std::ignore = tracker.note_sync(bob, phone, false, start_ms); + + WHEN("a prune runs at once") + { + tracker.prune(start_ms); + + THEN("the account is removed: a device asking for unavailable speaks for nothing and holds no place") + { + REQUIRE(tracker.account_count() == 0U); + } + } + } +} + +// ADR-0875: an account holds at most max_devices_per_account devices; at the cap a device that holds nothing gives up +// its place first, and only a device asking for online takes an online device's place. +SCENARIO("An account holds a bounded number of devices, and the cap never ends an online hold for nothing", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("an account with as many devices as the cap, the oldest of them the only one asking for online") + { + auto tracker = AccountPresenceTracker{}; + std::ignore = tracker.note_sync(alice, "OLDEST", true, start_ms); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + std::ignore = tracker.note_sync(alice, "D" + std::to_string(index), false, + start_ms + static_cast(index)); + } + + WHEN("one more device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); + + THEN("it takes the place of the least recently seen device that asked for unavailable, and the online hold " + "stays") + { + REQUIRE(any_online); + REQUIRE(tracker.note_sync(alice, "NEWEST", false, start_ms + 1'001)); + } + } + } + + GIVEN("an account with as many devices as the cap, every one of them asking for online") + { + auto tracker = AccountPresenceTracker{}; + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + std::ignore = tracker.note_sync(alice, "D" + std::to_string(index), true, + start_ms + static_cast(index)); + } + + WHEN("one more device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); + // Forgetting every device but D0 leaves the account held online only if D0, the least recently seen, kept + // its place; it is never synced again, so the probe cannot put it back. + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + tracker.forget_device(alice, "D" + std::to_string(index), start_ms + 1'001); + } + + THEN("it is not recorded, since it holds nothing, and every online hold stays, D0's included") + { + REQUIRE(any_online); + REQUIRE(tracker.note_sync(alice, "PROBE", false, start_ms + 1'002)); + } + } + + WHEN("one more device syncs asking for online") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", true, start_ms + 1'000); + // Forgetting every device but D0 leaves the account held online only if D0 kept its place. + tracker.forget_device(alice, "NEWEST", start_ms + 1'001); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + tracker.forget_device(alice, "D" + std::to_string(index), start_ms + 1'001); + } + + THEN("it takes the place of the least recently seen online device, D0") + { + REQUIRE(any_online); + REQUIRE_FALSE(tracker.note_sync(alice, "PROBE", false, start_ms + 1'002)); + } + } + } +} + +// ADR-0875, ADR-0876: the table holds at most its account cap. A full table evicts the account whose devices go stale +// soonest, and refuses (fails closed) only while every account has an open window. +SCENARIO("The tracker holds a bounded number of accounts", "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a table holding as many accounts as the cap, each inside its window") + { + auto tracker = AccountPresenceTracker{small_cap}; + for (auto index = std::size_t{0U}; index < small_cap; ++index) + { + tracker.note_change("@user" + std::to_string(index) + ":example.org", start_ms); + } + REQUIRE(tracker.account_count() == small_cap); + + WHEN("an account with no entry asks to change its presence") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 1); + tracker.note_change(alice, start_ms + 1); + + THEN("it is refused and the table does not grow: a flood of accounts cannot lift the limit") + { + REQUIRE(blocked.has_value()); + REQUIRE(tracker.account_count() == small_cap); + } + } + + WHEN("it syncs asking for online") + { + auto const any_online = tracker.note_sync(alice, desktop, true, start_ms + 1); + + THEN("nothing is recorded, so no device the table holds asks for online, and the table does not grow") + { + REQUIRE_FALSE(any_online); + REQUIRE(tracker.account_count() == small_cap); + } + } + + WHEN("the windows have ended and an account with no entry syncs") + { + std::ignore = tracker.note_sync(alice, desktop, true, start_ms + AccountPresenceTracker::change_window_ms); + + THEN("the ended accounts are pruned to make room and it is held") + { + REQUIRE(tracker.account_count() == 1U); + } + } + } + + GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") + { + auto tracker = AccountPresenceTracker{small_cap}; + fill_held_online(tracker); + + WHEN("an account with no entry asks to change its presence, however recently the others synced") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 2); + tracker.note_change(alice, start_ms + 2); + + THEN("it is allowed, and the account whose device goes stale soonest gives up its place") + { + REQUIRE_FALSE(blocked.has_value()); + REQUIRE(tracker.account_count() == small_cap); + REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.evictions() == 1U); + REQUIRE(tracker.take_saturation_report(start_ms + 2) == + std::optional{ + AccountPresenceTracker::SaturationReport{0U, 1U} + }); + REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 3).has_value()); + REQUIRE_FALSE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); + } + } + } +} + +SCENARIO("A prune of a full table looks only at the accounts that have expired", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a full table in which one account's window ended as the others' began") + { + auto tracker = AccountPresenceTracker{small_cap}; + tracker.note_change("@early:example.org", start_ms); + auto const later_ms = start_ms + AccountPresenceTracker::change_window_ms; + for (auto index = std::size_t{1U}; index < small_cap; ++index) + { + tracker.note_change("@user" + std::to_string(index) + ":example.org", later_ms); + } + REQUIRE(tracker.account_count() == small_cap); + + WHEN("an account with no entry asks to change its presence") + { + auto const blocked = tracker.change_blocked_for_ms(alice, later_ms + 1); + tracker.note_change(alice, later_ms + 1); + + THEN("it is allowed and takes the expired account's place: a prune re-filed that one account as its window " + "ended, then removed it, and looked at no other") + { + REQUIRE_FALSE(blocked.has_value()); + REQUIRE(tracker.account_count() == small_cap); + REQUIRE(tracker.accounts_examined() == 2U); + REQUIRE(tracker.change_blocked_for_ms(alice, later_ms + 2).has_value()); + } + } + + WHEN("the table is full again and a flood of accounts with no entry syncs") + { + tracker.note_change(alice, later_ms + 1); + for (auto index = 0; index < 1'000; ++index) + { + std::ignore = + tracker.note_sync("@flood" + std::to_string(index) + ":example.org", desktop, true, later_ms + 2); + } + + THEN("no request looks at the table, since no account has expired") + { + REQUIRE(tracker.accounts_examined() == 2U); + REQUIRE(tracker.account_count() == small_cap); + } + } + } +} + +SCENARIO("A device asking for unavailable takes no place in the tracker", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("an account the tracker does not hold") + { + auto tracker = AccountPresenceTracker{}; + + WHEN("its device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(bob, phone, false, start_ms); + + THEN("no device asks for online and the account is not held") + { + REQUIRE_FALSE(any_online); + REQUIRE(tracker.account_count() == 0U); + } + } + } + + GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") + { + auto tracker = AccountPresenceTracker{small_cap}; + fill_held_online(tracker); + + WHEN("an account with no entry syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 2); + + THEN("nothing is evicted: the account whose device goes stale soonest keeps its hold") + { + REQUIRE_FALSE(any_online); + REQUIRE(tracker.accounts_examined() == 0U); + REQUIRE(tracker.account_count() == small_cap); + REQUIRE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); + } + } + } +} + +SCENARIO("A tracker holds max_accounts accounts unless it is made with another cap", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a tracker made as the server makes it, and two made with a cap") + { + auto const server = AccountPresenceTracker{}; + auto const small = AccountPresenceTracker{small_cap}; + auto const zero = AccountPresenceTracker{0U}; + + THEN("the server's holds max_accounts, the small one its cap, and a cap of zero holds one account") + { + REQUIRE(server.account_cap() == AccountPresenceTracker::max_accounts); + REQUIRE(small.account_cap() == small_cap); + REQUIRE(zero.account_cap() == 1U); + } + } +} + +// ADR-0876: a full table's refusals and evictions are counted, and a report of them is due at most once every +// full_warning_interval_ms, carrying what it stands for, so a flood costs one warning a minute. Nothing to report is +// never a report. +SCENARIO("A full tracker's refusals and evictions are reported at most once an interval", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a tracker that has refused and evicted nothing") + { + auto tracker = AccountPresenceTracker{small_cap}; + REQUIRE(tracker.full_refusals() == 0U); + REQUIRE(tracker.evictions() == 0U); + REQUIRE_FALSE(tracker.take_saturation_report(start_ms).has_value()); + + WHEN("it refuses one change, then two more within the interval, and is asked after each") + { + using Report = AccountPresenceTracker::SaturationReport; + tracker.note_full_refusal(); + auto const first = tracker.take_saturation_report(start_ms); + tracker.note_full_refusal(); + auto const second = tracker.take_saturation_report(start_ms + 1); + tracker.note_full_refusal(); + auto const third = + tracker.take_saturation_report(start_ms + AccountPresenceTracker::full_warning_interval_ms - 1); + auto const after_interval = + tracker.take_saturation_report(start_ms + AccountPresenceTracker::full_warning_interval_ms); + auto const nothing_new = + tracker.take_saturation_report(start_ms + 2 * AccountPresenceTracker::full_warning_interval_ms); + + THEN("the first is reported, the next two wait for the interval, and nothing new is never reported") + { + REQUIRE(first == std::optional{ + Report{1U, 0U} + }); + REQUIRE_FALSE(second.has_value()); + REQUIRE_FALSE(third.has_value()); + REQUIRE(after_interval == std::optional{ + Report{2U, 0U} + }); + REQUIRE_FALSE(nothing_new.has_value()); + REQUIRE(tracker.full_refusals() == 3U); + } + } + } +}